title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
SQL Tryit Editor v1.6
|
CREATE VIEW [Products Above Average Price] AS
SELECT ProductName, Price
FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
Edit the SQL Statement, and click "Run SQL" to see the result.
This SQL-Statement is not supported in the WebSQL Database.
The example still works, because it uses a modified version of SQL.
Your browser does not support WebSQL.
Your are now using a light-version of the Try-SQL Editor, with a read-only Database.
If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time.
Our Try-SQL Editor uses WebSQL to demonstrate SQL.
A Database-object is created in your browser, for testing purposes.
You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the "Restore Database" button.
WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object.
WebSQL is supported in Chrome, Safari, Opera, and Edge(79).
If you use another browser you will still be able to use our Try SQL Editor, but a different version, using a server-based ASP application, with a read-only Access Database, where users are not allowed to make any changes to the data.
|
[
{
"code": null,
"e": 46,
"s": 0,
"text": "CREATE VIEW [Products Above Average Price] AS"
},
{
"code": null,
"e": 72,
"s": 46,
"text": "SELECT ProductName, Price"
},
{
"code": null,
"e": 86,
"s": 72,
"text": "FROM Products"
},
{
"code": null,
"e": 136,
"s": 86,
"text": "WHERE Price > (SELECT AVG(Price) FROM Products); "
},
{
"code": null,
"e": 138,
"s": 136,
"text": ""
},
{
"code": null,
"e": 201,
"s": 138,
"text": "Edit the SQL Statement, and click \"Run SQL\" to see the result."
},
{
"code": null,
"e": 261,
"s": 201,
"text": "This SQL-Statement is not supported in the WebSQL Database."
},
{
"code": null,
"e": 329,
"s": 261,
"text": "The example still works, because it uses a modified version of SQL."
},
{
"code": null,
"e": 367,
"s": 329,
"text": "Your browser does not support WebSQL."
},
{
"code": null,
"e": 452,
"s": 367,
"text": "Your are now using a light-version of the Try-SQL Editor, with a read-only Database."
},
{
"code": null,
"e": 626,
"s": 452,
"text": "If you switch to a browser with WebSQL support, you can try any SQL statement, and play with the Database as much as you like. The Database can also be restored at any time."
},
{
"code": null,
"e": 677,
"s": 626,
"text": "Our Try-SQL Editor uses WebSQL to demonstrate SQL."
},
{
"code": null,
"e": 745,
"s": 677,
"text": "A Database-object is created in your browser, for testing purposes."
},
{
"code": null,
"e": 916,
"s": 745,
"text": "You can try any SQL statement, and play with the Database as much as you like. The Database can be restored at any time, simply by clicking the \"Restore Database\" button."
},
{
"code": null,
"e": 1016,
"s": 916,
"text": "WebSQL stores a Database locally, on the user's computer. Each user gets their own Database object."
},
{
"code": null,
"e": 1076,
"s": 1016,
"text": "WebSQL is supported in Chrome, Safari, Opera, and Edge(79)."
}
] |
MySQL query to get a substring from a string except the last three characters?
|
For this, you can use SUBSTR along with length().
Let us first create a table −
mysql> create table DemoTable
(
Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
FirstName varchar(20)
);
Query OK, 0 rows affected (1.31 sec)
Following is the query to insert some records in the table using insert command −
mysql> insert into DemoTable(FirstName) values('John');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Carol');
Query OK, 1 row affected (0.22 sec)
mysql> insert into DemoTable(FirstName) values('Robert');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable(FirstName) values('Chris');
Query OK, 1 row affected (0.16 sec)
mysql> insert into DemoTable(FirstName) values('David');
Query OK, 1 row affected (0.17 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 | FirstName |
+----+-----------+
| 1 | John |
| 2 | Carol |
| 3 | Robert |
| 4 | Chris |
| 5 | David |
+----+-----------+
5 rows in set (0.00 sec)
Following is the query to get a substring removing the last 3 characters −
mysql> select substr(FirstName,1,length(FirstName)-3) from DemoTable;
This will produce the following output −
+-----------------------------------------+
| substr(FirstName,1,length(FirstName)-3) |
+-----------------------------------------+
| J |
| Ca |
| Rob |
| Ch |
| Da |
+-----------------------------------------+
5 rows in set (0.00 sec)
To get same output, you can use following alternate query −
mysql> select left(FirstName,length(FirstName)-3) from DemoTable;
This will produce the following output −
+-------------------------------------+
| left(FirstName,length(FirstName)-3) |
+-------------------------------------+
| J |
| Ca |
| Rob |
| Ch |
| Da |
+-------------------------------------+
5 rows in set (0.00 sec)
To get last three characters, you can use the following query −
mysql> select substr(FirstName,-3) from DemoTable;
This will produce the following output −
+----------------------+
| substr(FirstName,-3) |
+----------------------+
| ohn |
| rol |
| ert |
| ris |
| vid |
+----------------------+
5 rows in set (0.00 sec)
|
[
{
"code": null,
"e": 1112,
"s": 1062,
"text": "For this, you can use SUBSTR along with length()."
},
{
"code": null,
"e": 1142,
"s": 1112,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1292,
"s": 1142,
"text": "mysql> create table DemoTable\n (\n Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n FirstName varchar(20)\n );\nQuery OK, 0 rows affected (1.31 sec)"
},
{
"code": null,
"e": 1374,
"s": 1292,
"text": "Following is the query to insert some records in the table using insert command −"
},
{
"code": null,
"e": 1839,
"s": 1374,
"text": "mysql> insert into DemoTable(FirstName) values('John');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(FirstName) values('Carol');\nQuery OK, 1 row affected (0.22 sec)\nmysql> insert into DemoTable(FirstName) values('Robert');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable(FirstName) values('Chris');\nQuery OK, 1 row affected (0.16 sec)\nmysql> insert into DemoTable(FirstName) values('David');\nQuery OK, 1 row affected (0.17 sec)"
},
{
"code": null,
"e": 1919,
"s": 1839,
"text": "Following is the query to display records from the table using select command −"
},
{
"code": null,
"e": 1950,
"s": 1919,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1991,
"s": 1950,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2187,
"s": 1991,
"text": "+----+-----------+\n| Id | FirstName |\n+----+-----------+\n| 1 | John |\n| 2 | Carol |\n| 3 | Robert |\n| 4 | Chris |\n| 5 | David |\n+----+-----------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2262,
"s": 2187,
"text": "Following is the query to get a substring removing the last 3 characters −"
},
{
"code": null,
"e": 2332,
"s": 2262,
"text": "mysql> select substr(FirstName,1,length(FirstName)-3) from DemoTable;"
},
{
"code": null,
"e": 2373,
"s": 2332,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2794,
"s": 2373,
"text": "+-----------------------------------------+\n| substr(FirstName,1,length(FirstName)-3) |\n+-----------------------------------------+\n| J |\n| Ca |\n| Rob |\n| Ch |\n| Da |\n+-----------------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2854,
"s": 2794,
"text": "To get same output, you can use following alternate query −"
},
{
"code": null,
"e": 2920,
"s": 2854,
"text": "mysql> select left(FirstName,length(FirstName)-3) from DemoTable;"
},
{
"code": null,
"e": 2961,
"s": 2920,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3346,
"s": 2961,
"text": "+-------------------------------------+\n| left(FirstName,length(FirstName)-3) |\n+-------------------------------------+\n| J |\n| Ca |\n| Rob |\n| Ch |\n| Da |\n+-------------------------------------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 3410,
"s": 3346,
"text": "To get last three characters, you can use the following query −"
},
{
"code": null,
"e": 3461,
"s": 3410,
"text": "mysql> select substr(FirstName,-3) from DemoTable;"
},
{
"code": null,
"e": 3502,
"s": 3461,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3752,
"s": 3502,
"text": "+----------------------+\n| substr(FirstName,-3) |\n+----------------------+\n| ohn |\n| rol |\n| ert |\n| ris |\n| vid |\n+----------------------+\n5 rows in set (0.00 sec)"
}
] |
Program to find the maximum element in a Matrix in C++
|
In this problem, we are given a matrix of size nXm. Our task is to create a
program to find the maximum element in a Matrix in C++.
Problem Description − Here, we need to simply find the largest element of matrix.
Let’s take an example to understand the problem,
mat[3][3] = {{4, 1, 6},
{5, 2, 9},
{7, 3, 0}}
9
The solution to the problem is by simply traversing the matrix. This is done by using two nested loops, and checking whether each element of the matrix is greater than maxVal. And return the maxVal at the end.
Program to illustrate the working of our solution,
Live Demo
#include <iostream>
using namespace std;
#define n 3
#define m 3
int CalcMaxVal(int mat[n][m]) {
int maxVal = mat[0][0];
for (int i = 0; i < n; i++)
for (int j = 0; j < m; j++)
if (mat[i][j] > maxVal)
maxVal = mat[i][j];
return maxVal;
}
int main(){
int mat[n][m] = {{4, 1, 6},{5, 2, 9},{7, 3, 0}};
cout<<"The maximum element in a Matrix is "<<CalcMaxVal(mat);
return 0;
}
The maximum element in a Matrix is 9
|
[
{
"code": null,
"e": 1194,
"s": 1062,
"text": "In this problem, we are given a matrix of size nXm. Our task is to create a\nprogram to find the maximum element in a Matrix in C++."
},
{
"code": null,
"e": 1276,
"s": 1194,
"text": "Problem Description − Here, we need to simply find the largest element of matrix."
},
{
"code": null,
"e": 1325,
"s": 1276,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1371,
"s": 1325,
"text": "mat[3][3] = {{4, 1, 6},\n{5, 2, 9},\n{7, 3, 0}}"
},
{
"code": null,
"e": 1373,
"s": 1371,
"text": "9"
},
{
"code": null,
"e": 1583,
"s": 1373,
"text": "The solution to the problem is by simply traversing the matrix. This is done by using two nested loops, and checking whether each element of the matrix is greater than maxVal. And return the maxVal at the end."
},
{
"code": null,
"e": 1634,
"s": 1583,
"text": "Program to illustrate the working of our solution,"
},
{
"code": null,
"e": 1645,
"s": 1634,
"text": " Live Demo"
},
{
"code": null,
"e": 2063,
"s": 1645,
"text": "#include <iostream>\nusing namespace std;\n#define n 3\n#define m 3\nint CalcMaxVal(int mat[n][m]) {\n int maxVal = mat[0][0];\n for (int i = 0; i < n; i++)\n for (int j = 0; j < m; j++)\n if (mat[i][j] > maxVal)\n maxVal = mat[i][j];\n return maxVal;\n}\nint main(){\n int mat[n][m] = {{4, 1, 6},{5, 2, 9},{7, 3, 0}};\n cout<<\"The maximum element in a Matrix is \"<<CalcMaxVal(mat);\n return 0;\n}"
},
{
"code": null,
"e": 2100,
"s": 2063,
"text": "The maximum element in a Matrix is 9"
}
] |
Class Instances in Python. String Representations of Class... | by Sadrach Pierre, Ph.D. | Towards Data Science
|
Customizing how class instances are represented is a good way to simplify debugging and instance output. In this post, we will discuss how defining ‘__repr__’ and ‘__str__’ methods allows us to change the string representation of an instance.
Let’s get started!
To begin, let’s define a class that describes a YouTube channel. The class will contain attributes (data) specific to Youtube channels such as channel name, subscribers, and verification status :
class YouTube: def __init__(self, channel_name, subscribers, verification): self.channel_name = channel_name self.subscribers = subscribers self.verification = verification
Let’s create an instance of our YouTube class. As a reminder, an instance is a concrete occurrence of a class object. For our instance, let’s set attributes corresponding to one of my favorite YouTube channels, sentdex:
sentdex = YouTube('Sentdex', 847000, True)
Now that we’ve created our instance, let’s print out the instance:
print(sentdex)
We see that we have an object of type ‘YouTube’ at the specified memory address. While this corresponds to what we’d expect, it isn’t the most readable representation of our instance. If we’d like to change how this object is represented, we can define ‘__repr__’ and ‘__str__’ methods. First, let’s define the ‘__repr__’ method:
class YouTube: def __init__(self, channel_name, subscribers, verification): self.channel_name = channel_name self.subscribers = subscribers self.verification = verification def __repr__(self): return 'YouTube({0.channel_name!r}, {0.subscribers!r}, {0.verification!r})'.format(self)
Let’s redefine our object, ‘sentdex’, and print the result:
sentdex = YouTube('Sentdex', 847000, True)print(sentdex)
We see that the ‘__repr__’ method returns the code representation of our instance. It simply corresponds to the code we typed to create the instance.
Now, let’s define the ‘__str__’ method:
class YouTube: def __init__(self, channel_name, subscribers, verification): self.channel_name = channel_name self.subscribers = subscribers self.verification = verification def __repr__(self): return 'YouTube({0.channel_name!r}, {0.subscribers!r}, {0.verification!r})'.format(self) def __str__(self): return '({0.channel_name!s}, {0.subscribers!s}, {0.verification!s})'.format(self)
Let’s define our instance again and print the result:
sentdex = YouTube('Sentdex', 847000, True)print(sentdex)
We see that we now have a string representation of our instance. If we’d like to print out the code representation, with our current class implementation, we can use the built-in ‘repr()’ method:
sentdex = YouTube('Sentdex', 847000, True)print(repr(sentdex))
I’d also like to point out the difference in text formatting between ‘__repr__()’ and ‘__str__()’. The special ‘!r’ formatting code indicates the output of ‘__repr__()’ should be used instead of the default ‘__str__()’. For example, if we include ‘!r’ in our string:
sentdex = YouTube('Sentdex', 847000, True)print('sentdex is {0!r}'.format(sentdex))
We get the code representation. If we leave out the ‘!r’ code, the string representation is used as default:
sentdex = YouTube('Sentdex', 847000, True)print('sentdex is {0}'.format(sentdex))
Defining the ‘__repr__()’ and ‘__str__()’ methods is often good practice as it can make class instances much easier to interpret and debug downstream. For example, logging custom string representations of instances can provide programmers with much more useful information about the instance contents. I’ll stop here but I encourage you to play around with the code yourself. If you’re interested in learning more programming patterns related to class definitions in python, I encourage you to check out The Python Cookbook.
To summarize, in this post we discussed string representations of class instances. We showed how to define ‘__repr__()’ and ‘__str__()’ methods, which allowed us to display code representations and string representations of instances. This practice can make class instance contents transparent and can significantly simplify debugging when done well. I hope you found this post useful/interesting. The code in this post is available on GitHub. Thank you for reading!
|
[
{
"code": null,
"e": 415,
"s": 172,
"text": "Customizing how class instances are represented is a good way to simplify debugging and instance output. In this post, we will discuss how defining ‘__repr__’ and ‘__str__’ methods allows us to change the string representation of an instance."
},
{
"code": null,
"e": 434,
"s": 415,
"text": "Let’s get started!"
},
{
"code": null,
"e": 630,
"s": 434,
"text": "To begin, let’s define a class that describes a YouTube channel. The class will contain attributes (data) specific to Youtube channels such as channel name, subscribers, and verification status :"
},
{
"code": null,
"e": 827,
"s": 630,
"text": "class YouTube: def __init__(self, channel_name, subscribers, verification): self.channel_name = channel_name self.subscribers = subscribers self.verification = verification"
},
{
"code": null,
"e": 1047,
"s": 827,
"text": "Let’s create an instance of our YouTube class. As a reminder, an instance is a concrete occurrence of a class object. For our instance, let’s set attributes corresponding to one of my favorite YouTube channels, sentdex:"
},
{
"code": null,
"e": 1090,
"s": 1047,
"text": "sentdex = YouTube('Sentdex', 847000, True)"
},
{
"code": null,
"e": 1157,
"s": 1090,
"text": "Now that we’ve created our instance, let’s print out the instance:"
},
{
"code": null,
"e": 1172,
"s": 1157,
"text": "print(sentdex)"
},
{
"code": null,
"e": 1502,
"s": 1172,
"text": "We see that we have an object of type ‘YouTube’ at the specified memory address. While this corresponds to what we’d expect, it isn’t the most readable representation of our instance. If we’d like to change how this object is represented, we can define ‘__repr__’ and ‘__str__’ methods. First, let’s define the ‘__repr__’ method:"
},
{
"code": null,
"e": 1826,
"s": 1502,
"text": "class YouTube: def __init__(self, channel_name, subscribers, verification): self.channel_name = channel_name self.subscribers = subscribers self.verification = verification def __repr__(self): return 'YouTube({0.channel_name!r}, {0.subscribers!r}, {0.verification!r})'.format(self)"
},
{
"code": null,
"e": 1886,
"s": 1826,
"text": "Let’s redefine our object, ‘sentdex’, and print the result:"
},
{
"code": null,
"e": 1943,
"s": 1886,
"text": "sentdex = YouTube('Sentdex', 847000, True)print(sentdex)"
},
{
"code": null,
"e": 2093,
"s": 1943,
"text": "We see that the ‘__repr__’ method returns the code representation of our instance. It simply corresponds to the code we typed to create the instance."
},
{
"code": null,
"e": 2133,
"s": 2093,
"text": "Now, let’s define the ‘__str__’ method:"
},
{
"code": null,
"e": 2568,
"s": 2133,
"text": "class YouTube: def __init__(self, channel_name, subscribers, verification): self.channel_name = channel_name self.subscribers = subscribers self.verification = verification def __repr__(self): return 'YouTube({0.channel_name!r}, {0.subscribers!r}, {0.verification!r})'.format(self) def __str__(self): return '({0.channel_name!s}, {0.subscribers!s}, {0.verification!s})'.format(self)"
},
{
"code": null,
"e": 2622,
"s": 2568,
"text": "Let’s define our instance again and print the result:"
},
{
"code": null,
"e": 2679,
"s": 2622,
"text": "sentdex = YouTube('Sentdex', 847000, True)print(sentdex)"
},
{
"code": null,
"e": 2875,
"s": 2679,
"text": "We see that we now have a string representation of our instance. If we’d like to print out the code representation, with our current class implementation, we can use the built-in ‘repr()’ method:"
},
{
"code": null,
"e": 2938,
"s": 2875,
"text": "sentdex = YouTube('Sentdex', 847000, True)print(repr(sentdex))"
},
{
"code": null,
"e": 3205,
"s": 2938,
"text": "I’d also like to point out the difference in text formatting between ‘__repr__()’ and ‘__str__()’. The special ‘!r’ formatting code indicates the output of ‘__repr__()’ should be used instead of the default ‘__str__()’. For example, if we include ‘!r’ in our string:"
},
{
"code": null,
"e": 3289,
"s": 3205,
"text": "sentdex = YouTube('Sentdex', 847000, True)print('sentdex is {0!r}'.format(sentdex))"
},
{
"code": null,
"e": 3398,
"s": 3289,
"text": "We get the code representation. If we leave out the ‘!r’ code, the string representation is used as default:"
},
{
"code": null,
"e": 3480,
"s": 3398,
"text": "sentdex = YouTube('Sentdex', 847000, True)print('sentdex is {0}'.format(sentdex))"
},
{
"code": null,
"e": 4005,
"s": 3480,
"text": "Defining the ‘__repr__()’ and ‘__str__()’ methods is often good practice as it can make class instances much easier to interpret and debug downstream. For example, logging custom string representations of instances can provide programmers with much more useful information about the instance contents. I’ll stop here but I encourage you to play around with the code yourself. If you’re interested in learning more programming patterns related to class definitions in python, I encourage you to check out The Python Cookbook."
}
] |
The Top 1̶0̶ 15 Places to Find Datasets 📊 | Towards Data Science
|
Without further ado, here are the best places to find data, with some helpful information about each. Folks keep pointing me to new sources, so the list is expanding! If you have a favorite, please send it my way! 😀
Awesome Data is a GitHub repository with a seriously impressive list of datasets separated by category. It is updated regularly.
Jeremy Singer-Vine’s Data Is Plural weekly newsletter has great fresh data sources. I’m always impressed by the quality. The archive is available here.
In addition to competitions, Kaggle has a huge range of datasets. Kaggle Datasets provide great summary information and previews for most datasets. You can download the data or use their platform to analyze it in a Jupyter notebook. You can also contribute your own datasets and make them public or private.
Like Kaggle, Data.world provides a wide range of user-contributed datasets. It also offers a platform for companies to store and organize their data.
I think it’s safe to say that Google knows a thing or two about search. It recently added a separate search functionality for datasets through its Google Dataset Search Tool. It’s worth a shot if you’re looking for data on a particular topic or from a particular source.
Hugging Face has nearly 2,000 datasets, including many NLP datasets. I love their model cards that contain descriptions, intended uses and limitations, operating instructions, biases, training data and training procedure information, and evaluation results on many common metrics. Added Nov. 16, 2021.
The subreddit r/datasets has lots of great datasets posted regularly by users. Added January 25, 2021.
OpenDaL is a data aggregator that allows you to search using a variety of metadata. For example, you can search based on time or location.
The Pandas DataReader will help you pull data from online sources into Python pandas DataFrames. Most of the data sources are financial. Here’s the list of available data sources as of late 2020:
Tiingo
IEX
Alpha Vantage
Enigma
Quandl
St.Louis FED (FRED)
Kenneth French’s data library
World Bank
OECD
Eurostat
Thrift Savings Plan
Nasdaq Trader symbol definitions
Stooq
MOEX
Naver Finance
Here’s how you use it after installing it into a Python environment with pip install pandas-datareader.
import pandas_datareader as pdrpdr.get_data_fred('GS10')
If you are looking for computer vision datasets, VisualData is a nice new source. It has some handy filtering options. Thanks to Jie Feng for reminding me of it! Added Nov. 2, 2020.
If you are looking to use the US government’s datasets, Data.gov has over 217,000 ofthem! Thanks to Michael Wallace for recommending it. Added Nov. 4, 2020.
The official portal for European data has over a million datasets. data.europa.eu is hosted by the European Union. Added Oct. 28, 2021.
Christoph Rieke has a GitHub repo that is just what it sounds like. Jacob Koehler led me to it; added on May 26, 2021.
Papers With Code has over 4,000 datasets as of mid 2021. The datasets are ranked by the number of papers they appear in. “The mission of Papers with Code is to create a free and open resource with Machine Learning papers, code and evaluation tables.” — and apparently datasets! 🎉
I recently updated my list of Python API wrappers to help users see how popular each package is popular and whether its being actively maintained. My repo now uses shields.io to automatically display GitHub stars and the date of the most recent commit. This list was originally forked from the GitHub repo of Real Python via johnwmillr. My repo contains what I believe is the largest updated list of Python API wrappers — many of which can help you find the data you might need for a project.
Getting data from a documented API using Python might sound intimidating if you haven’t done it before, but it’s really not bad. Check out my guide to getting data from APIs here. 🚀
When all else fails, collecting your own data can be an excellent way to create a dataset for your needs. 😉
Awesome Data
Kaggle Datasets
Data.world
Google Dataset Search Tool
Hugging Face
r/datasets
OpenDaL
Pandas Data Reader
Data Is Plural
VisualData
Data.gov
data.europa.eu
Awesome Satellite Imagery Datasets
Papers With Code
API Wrappers
APIs
Make your own!
Do you have a favorite place to find data? Awesome! Share it on Twitter or leave it in the comments! 🎉
I hope you find this tool helpful when you’re searching for data sources. If you do, please share it on your favorite social media. 🚀
I write about Python, data science, and other tech topics. If you’re into that kind of stuff read more here and subscribe to my Data Awesome newsletter for awesome monthly curated data resources.
Happy data hunting! 😀
|
[
{
"code": null,
"e": 388,
"s": 172,
"text": "Without further ado, here are the best places to find data, with some helpful information about each. Folks keep pointing me to new sources, so the list is expanding! If you have a favorite, please send it my way! 😀"
},
{
"code": null,
"e": 517,
"s": 388,
"text": "Awesome Data is a GitHub repository with a seriously impressive list of datasets separated by category. It is updated regularly."
},
{
"code": null,
"e": 669,
"s": 517,
"text": "Jeremy Singer-Vine’s Data Is Plural weekly newsletter has great fresh data sources. I’m always impressed by the quality. The archive is available here."
},
{
"code": null,
"e": 977,
"s": 669,
"text": "In addition to competitions, Kaggle has a huge range of datasets. Kaggle Datasets provide great summary information and previews for most datasets. You can download the data or use their platform to analyze it in a Jupyter notebook. You can also contribute your own datasets and make them public or private."
},
{
"code": null,
"e": 1127,
"s": 977,
"text": "Like Kaggle, Data.world provides a wide range of user-contributed datasets. It also offers a platform for companies to store and organize their data."
},
{
"code": null,
"e": 1398,
"s": 1127,
"text": "I think it’s safe to say that Google knows a thing or two about search. It recently added a separate search functionality for datasets through its Google Dataset Search Tool. It’s worth a shot if you’re looking for data on a particular topic or from a particular source."
},
{
"code": null,
"e": 1700,
"s": 1398,
"text": "Hugging Face has nearly 2,000 datasets, including many NLP datasets. I love their model cards that contain descriptions, intended uses and limitations, operating instructions, biases, training data and training procedure information, and evaluation results on many common metrics. Added Nov. 16, 2021."
},
{
"code": null,
"e": 1803,
"s": 1700,
"text": "The subreddit r/datasets has lots of great datasets posted regularly by users. Added January 25, 2021."
},
{
"code": null,
"e": 1942,
"s": 1803,
"text": "OpenDaL is a data aggregator that allows you to search using a variety of metadata. For example, you can search based on time or location."
},
{
"code": null,
"e": 2138,
"s": 1942,
"text": "The Pandas DataReader will help you pull data from online sources into Python pandas DataFrames. Most of the data sources are financial. Here’s the list of available data sources as of late 2020:"
},
{
"code": null,
"e": 2145,
"s": 2138,
"text": "Tiingo"
},
{
"code": null,
"e": 2149,
"s": 2145,
"text": "IEX"
},
{
"code": null,
"e": 2163,
"s": 2149,
"text": "Alpha Vantage"
},
{
"code": null,
"e": 2170,
"s": 2163,
"text": "Enigma"
},
{
"code": null,
"e": 2177,
"s": 2170,
"text": "Quandl"
},
{
"code": null,
"e": 2197,
"s": 2177,
"text": "St.Louis FED (FRED)"
},
{
"code": null,
"e": 2227,
"s": 2197,
"text": "Kenneth French’s data library"
},
{
"code": null,
"e": 2238,
"s": 2227,
"text": "World Bank"
},
{
"code": null,
"e": 2243,
"s": 2238,
"text": "OECD"
},
{
"code": null,
"e": 2252,
"s": 2243,
"text": "Eurostat"
},
{
"code": null,
"e": 2272,
"s": 2252,
"text": "Thrift Savings Plan"
},
{
"code": null,
"e": 2305,
"s": 2272,
"text": "Nasdaq Trader symbol definitions"
},
{
"code": null,
"e": 2311,
"s": 2305,
"text": "Stooq"
},
{
"code": null,
"e": 2316,
"s": 2311,
"text": "MOEX"
},
{
"code": null,
"e": 2330,
"s": 2316,
"text": "Naver Finance"
},
{
"code": null,
"e": 2434,
"s": 2330,
"text": "Here’s how you use it after installing it into a Python environment with pip install pandas-datareader."
},
{
"code": null,
"e": 2491,
"s": 2434,
"text": "import pandas_datareader as pdrpdr.get_data_fred('GS10')"
},
{
"code": null,
"e": 2673,
"s": 2491,
"text": "If you are looking for computer vision datasets, VisualData is a nice new source. It has some handy filtering options. Thanks to Jie Feng for reminding me of it! Added Nov. 2, 2020."
},
{
"code": null,
"e": 2830,
"s": 2673,
"text": "If you are looking to use the US government’s datasets, Data.gov has over 217,000 ofthem! Thanks to Michael Wallace for recommending it. Added Nov. 4, 2020."
},
{
"code": null,
"e": 2966,
"s": 2830,
"text": "The official portal for European data has over a million datasets. data.europa.eu is hosted by the European Union. Added Oct. 28, 2021."
},
{
"code": null,
"e": 3085,
"s": 2966,
"text": "Christoph Rieke has a GitHub repo that is just what it sounds like. Jacob Koehler led me to it; added on May 26, 2021."
},
{
"code": null,
"e": 3365,
"s": 3085,
"text": "Papers With Code has over 4,000 datasets as of mid 2021. The datasets are ranked by the number of papers they appear in. “The mission of Papers with Code is to create a free and open resource with Machine Learning papers, code and evaluation tables.” — and apparently datasets! 🎉"
},
{
"code": null,
"e": 3858,
"s": 3365,
"text": "I recently updated my list of Python API wrappers to help users see how popular each package is popular and whether its being actively maintained. My repo now uses shields.io to automatically display GitHub stars and the date of the most recent commit. This list was originally forked from the GitHub repo of Real Python via johnwmillr. My repo contains what I believe is the largest updated list of Python API wrappers — many of which can help you find the data you might need for a project."
},
{
"code": null,
"e": 4040,
"s": 3858,
"text": "Getting data from a documented API using Python might sound intimidating if you haven’t done it before, but it’s really not bad. Check out my guide to getting data from APIs here. 🚀"
},
{
"code": null,
"e": 4148,
"s": 4040,
"text": "When all else fails, collecting your own data can be an excellent way to create a dataset for your needs. 😉"
},
{
"code": null,
"e": 4161,
"s": 4148,
"text": "Awesome Data"
},
{
"code": null,
"e": 4177,
"s": 4161,
"text": "Kaggle Datasets"
},
{
"code": null,
"e": 4188,
"s": 4177,
"text": "Data.world"
},
{
"code": null,
"e": 4215,
"s": 4188,
"text": "Google Dataset Search Tool"
},
{
"code": null,
"e": 4228,
"s": 4215,
"text": "Hugging Face"
},
{
"code": null,
"e": 4239,
"s": 4228,
"text": "r/datasets"
},
{
"code": null,
"e": 4247,
"s": 4239,
"text": "OpenDaL"
},
{
"code": null,
"e": 4266,
"s": 4247,
"text": "Pandas Data Reader"
},
{
"code": null,
"e": 4281,
"s": 4266,
"text": "Data Is Plural"
},
{
"code": null,
"e": 4292,
"s": 4281,
"text": "VisualData"
},
{
"code": null,
"e": 4301,
"s": 4292,
"text": "Data.gov"
},
{
"code": null,
"e": 4316,
"s": 4301,
"text": "data.europa.eu"
},
{
"code": null,
"e": 4351,
"s": 4316,
"text": "Awesome Satellite Imagery Datasets"
},
{
"code": null,
"e": 4368,
"s": 4351,
"text": "Papers With Code"
},
{
"code": null,
"e": 4381,
"s": 4368,
"text": "API Wrappers"
},
{
"code": null,
"e": 4386,
"s": 4381,
"text": "APIs"
},
{
"code": null,
"e": 4401,
"s": 4386,
"text": "Make your own!"
},
{
"code": null,
"e": 4504,
"s": 4401,
"text": "Do you have a favorite place to find data? Awesome! Share it on Twitter or leave it in the comments! 🎉"
},
{
"code": null,
"e": 4638,
"s": 4504,
"text": "I hope you find this tool helpful when you’re searching for data sources. If you do, please share it on your favorite social media. 🚀"
},
{
"code": null,
"e": 4834,
"s": 4638,
"text": "I write about Python, data science, and other tech topics. If you’re into that kind of stuff read more here and subscribe to my Data Awesome newsletter for awesome monthly curated data resources."
}
] |
Microsoft Interview Experience | 4+ Years Experienced - GeeksforGeeks
|
11 May, 2021
Round 1:-
Started with an introduction about projects and Education.
Then he asks me a question about my project which I had done previously(questions related to the synchronization of the transaction, if multiple transactions on multiple servers happen same time how do you handle it)
Then he asks me a question which is (you have given the array of non-negative Integer, the problem to solve is you have to reverse the array but all zeros which exist in the array should be move to the right side)For ExampleArray = {0, 4, 2, 3, 0, 9, 10, 0, 34,
8, 0, 23, 56, 12}
Resulted array = {12, 56, 23, 8, 34, 10, 9,
3, 2, 4, 0, 0, 0, 0} You have to solve this problem in O(n) time complexity and you should use constant space O(1) he ask me to write the code for the same to pass all edge case and write the all edge case possible for this problem.
For Example
Array = {0, 4, 2, 3, 0, 9, 10, 0, 34,
8, 0, 23, 56, 12}
Resulted array = {12, 56, 23, 8, 34, 10, 9,
3, 2, 4, 0, 0, 0, 0}
You have to solve this problem in O(n) time complexity and you should use constant space O(1) he ask me to write the code for the same to pass all edge case and write the all edge case possible for this problem.
Round 2:-
He introduce himself and about the project he working on then he started asking about my experience and what i have done
Asking questions on Java as Java is my primary Language and working of HashMap, how does it works.
Then he ask me to design the data structure such we can perform operationinsertFirst(value):- value inserted head of the list Time Complexity O(1)insertLast(value):- value inserted last of the list Time Complexity O(1)deleteValue(val):- delete the value from the list if the list contains multiple values then it should delete only first occurrence expected time complexity O(1).isExist(value):- return the true if value exist in the data structure otherwise false, expected time complexity O(1)
insertFirst(value):- value inserted head of the list Time Complexity O(1)
insertLast(value):- value inserted last of the list Time Complexity O(1)
deleteValue(val):- delete the value from the list if the list contains multiple values then it should delete only first occurrence expected time complexity O(1).
isExist(value):- return the true if value exist in the data structure otherwise false, expected time complexity O(1)
Write the code for the above problem using the best data structure and cover all test case, almost 1 hrs. Complete to solve this problem
Round 3:-
I introduce my self and we both are from the same college (NITK)
Then he move to the programing question which is you have given two singly linked list and you have to add these two linked list the constraints you can’t modify the input linked list list1 => 9->5->4 list2 => 8->0->7 resulted list => 1->7->6->1 **you can’t modify the input linked list**
then he ask me to develop the programing language which has a maximum throughput, we have discussion on this problem to what data structure we can use.
Round 4:-
This is hiring manager round but not looks like hiring manager round
He started with the problem and the problem was you have given the matrix of n*n which contains the small character only and you have given the dictionary as well which contain the English valid word, you have to find the how many word can be formed using this matrix, the word must contain in dictionary, you can move in matrix to left, right, top, bottom and diagonal
t o p
a g i
b r g
the possible Words are:- 1. top 2. tab 3. bat 4. pig 5. bag 6. gip
discussion about what data structure you have to use for Dictionary and i have solve this problem by using of DFS. and for dictionary i have used the Trie data structure.
After 2 days of all round complete, I got a call from HR and I got Selected in Microsoft, Dreams Come True.
Be focus on codding and all edge case passes.
Marketing
Microsoft
Experienced
Interview Experiences
Microsoft
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Amazon Interview Experience for SDE1 (8 Months Experienced) 2022
Paypal Interview Experience for SSE
Amazon Interview Experience for System Development Engineer (Exp - 6 months)
Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)
Walmart Interview Experience for SDE-III
Amazon Interview Questions
Microsoft Interview Experience for Internship (Via Engage)
Commonly Asked Java Programming Interview Questions | Set 2
Amazon Interview Experience for SDE-1 (On-Campus)
Amazon Interview Experience for SDE-1
|
[
{
"code": null,
"e": 25241,
"s": 25213,
"text": "\n11 May, 2021"
},
{
"code": null,
"e": 25251,
"s": 25241,
"text": "Round 1:-"
},
{
"code": null,
"e": 25310,
"s": 25251,
"text": "Started with an introduction about projects and Education."
},
{
"code": null,
"e": 25527,
"s": 25310,
"text": "Then he asks me a question about my project which I had done previously(questions related to the synchronization of the transaction, if multiple transactions on multiple servers happen same time how do you handle it)"
},
{
"code": null,
"e": 26087,
"s": 25527,
"text": "Then he asks me a question which is (you have given the array of non-negative Integer, the problem to solve is you have to reverse the array but all zeros which exist in the array should be move to the right side)For ExampleArray = {0, 4, 2, 3, 0, 9, 10, 0, 34,\n 8, 0, 23, 56, 12} \nResulted array = {12, 56, 23, 8, 34, 10, 9, \n3, 2, 4, 0, 0, 0, 0} You have to solve this problem in O(n) time complexity and you should use constant space O(1) he ask me to write the code for the same to pass all edge case and write the all edge case possible for this problem."
},
{
"code": null,
"e": 26099,
"s": 26087,
"text": "For Example"
},
{
"code": null,
"e": 26224,
"s": 26099,
"text": "Array = {0, 4, 2, 3, 0, 9, 10, 0, 34,\n 8, 0, 23, 56, 12} \nResulted array = {12, 56, 23, 8, 34, 10, 9, \n3, 2, 4, 0, 0, 0, 0} "
},
{
"code": null,
"e": 26436,
"s": 26224,
"text": "You have to solve this problem in O(n) time complexity and you should use constant space O(1) he ask me to write the code for the same to pass all edge case and write the all edge case possible for this problem."
},
{
"code": null,
"e": 26446,
"s": 26436,
"text": "Round 2:-"
},
{
"code": null,
"e": 26567,
"s": 26446,
"text": "He introduce himself and about the project he working on then he started asking about my experience and what i have done"
},
{
"code": null,
"e": 26666,
"s": 26567,
"text": "Asking questions on Java as Java is my primary Language and working of HashMap, how does it works."
},
{
"code": null,
"e": 27162,
"s": 26666,
"text": "Then he ask me to design the data structure such we can perform operationinsertFirst(value):- value inserted head of the list Time Complexity O(1)insertLast(value):- value inserted last of the list Time Complexity O(1)deleteValue(val):- delete the value from the list if the list contains multiple values then it should delete only first occurrence expected time complexity O(1).isExist(value):- return the true if value exist in the data structure otherwise false, expected time complexity O(1)"
},
{
"code": null,
"e": 27236,
"s": 27162,
"text": "insertFirst(value):- value inserted head of the list Time Complexity O(1)"
},
{
"code": null,
"e": 27309,
"s": 27236,
"text": "insertLast(value):- value inserted last of the list Time Complexity O(1)"
},
{
"code": null,
"e": 27471,
"s": 27309,
"text": "deleteValue(val):- delete the value from the list if the list contains multiple values then it should delete only first occurrence expected time complexity O(1)."
},
{
"code": null,
"e": 27588,
"s": 27471,
"text": "isExist(value):- return the true if value exist in the data structure otherwise false, expected time complexity O(1)"
},
{
"code": null,
"e": 27725,
"s": 27588,
"text": "Write the code for the above problem using the best data structure and cover all test case, almost 1 hrs. Complete to solve this problem"
},
{
"code": null,
"e": 27735,
"s": 27725,
"text": "Round 3:-"
},
{
"code": null,
"e": 27800,
"s": 27735,
"text": "I introduce my self and we both are from the same college (NITK)"
},
{
"code": null,
"e": 28090,
"s": 27800,
"text": "Then he move to the programing question which is you have given two singly linked list and you have to add these two linked list the constraints you can’t modify the input linked list list1 => 9->5->4 list2 => 8->0->7 resulted list => 1->7->6->1 **you can’t modify the input linked list**"
},
{
"code": null,
"e": 28242,
"s": 28090,
"text": "then he ask me to develop the programing language which has a maximum throughput, we have discussion on this problem to what data structure we can use."
},
{
"code": null,
"e": 28252,
"s": 28242,
"text": "Round 4:-"
},
{
"code": null,
"e": 28322,
"s": 28252,
"text": "This is hiring manager round but not looks like hiring manager round "
},
{
"code": null,
"e": 28692,
"s": 28322,
"text": "He started with the problem and the problem was you have given the matrix of n*n which contains the small character only and you have given the dictionary as well which contain the English valid word, you have to find the how many word can be formed using this matrix, the word must contain in dictionary, you can move in matrix to left, right, top, bottom and diagonal"
},
{
"code": null,
"e": 28698,
"s": 28692,
"text": "t o p"
},
{
"code": null,
"e": 28704,
"s": 28698,
"text": "a g i"
},
{
"code": null,
"e": 28710,
"s": 28704,
"text": "b r g"
},
{
"code": null,
"e": 28777,
"s": 28710,
"text": "the possible Words are:- 1. top 2. tab 3. bat 4. pig 5. bag 6. gip"
},
{
"code": null,
"e": 28948,
"s": 28777,
"text": "discussion about what data structure you have to use for Dictionary and i have solve this problem by using of DFS. and for dictionary i have used the Trie data structure."
},
{
"code": null,
"e": 29056,
"s": 28948,
"text": "After 2 days of all round complete, I got a call from HR and I got Selected in Microsoft, Dreams Come True."
},
{
"code": null,
"e": 29102,
"s": 29056,
"text": "Be focus on codding and all edge case passes."
},
{
"code": null,
"e": 29112,
"s": 29102,
"text": "Marketing"
},
{
"code": null,
"e": 29122,
"s": 29112,
"text": "Microsoft"
},
{
"code": null,
"e": 29134,
"s": 29122,
"text": "Experienced"
},
{
"code": null,
"e": 29156,
"s": 29134,
"text": "Interview Experiences"
},
{
"code": null,
"e": 29166,
"s": 29156,
"text": "Microsoft"
},
{
"code": null,
"e": 29264,
"s": 29166,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29273,
"s": 29264,
"text": "Comments"
},
{
"code": null,
"e": 29286,
"s": 29273,
"text": "Old Comments"
},
{
"code": null,
"e": 29351,
"s": 29286,
"text": "Amazon Interview Experience for SDE1 (8 Months Experienced) 2022"
},
{
"code": null,
"e": 29387,
"s": 29351,
"text": "Paypal Interview Experience for SSE"
},
{
"code": null,
"e": 29464,
"s": 29387,
"text": "Amazon Interview Experience for System Development Engineer (Exp - 6 months)"
},
{
"code": null,
"e": 29544,
"s": 29464,
"text": "Infosys Interview Experience for Java Backend Developer (3-5 Years Experienced)"
},
{
"code": null,
"e": 29585,
"s": 29544,
"text": "Walmart Interview Experience for SDE-III"
},
{
"code": null,
"e": 29612,
"s": 29585,
"text": "Amazon Interview Questions"
},
{
"code": null,
"e": 29671,
"s": 29612,
"text": "Microsoft Interview Experience for Internship (Via Engage)"
},
{
"code": null,
"e": 29731,
"s": 29671,
"text": "Commonly Asked Java Programming Interview Questions | Set 2"
},
{
"code": null,
"e": 29781,
"s": 29731,
"text": "Amazon Interview Experience for SDE-1 (On-Campus)"
}
] |
What are predefined attributes in C#?
|
The following are the predefined attributes in C# −
AttributeUsage
Conditional
Obsolete
The pre-defined attribute AttributeUsage describes how a custom attribute class can be used. Here is the syntax −
[AttributeUsage (
validon,
AllowMultiple = allowmultiple,
Inherited = inherited
)]
This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace.
The following is the syntax −
[Conditional(
conditionalSymbol
)]
This predefined attribute marks a program entity that should not be used. It enables you to inform the compiler to discard a particular target element. Here is the syntax −
[Obsolete (
message
)]
[Obsolete (
message,
iserror
)]
|
[
{
"code": null,
"e": 1114,
"s": 1062,
"text": "The following are the predefined attributes in C# −"
},
{
"code": null,
"e": 1129,
"s": 1114,
"text": "AttributeUsage"
},
{
"code": null,
"e": 1141,
"s": 1129,
"text": "Conditional"
},
{
"code": null,
"e": 1150,
"s": 1141,
"text": "Obsolete"
},
{
"code": null,
"e": 1264,
"s": 1150,
"text": "The pre-defined attribute AttributeUsage describes how a custom attribute class can be used. Here is the syntax −"
},
{
"code": null,
"e": 1356,
"s": 1264,
"text": "[AttributeUsage (\n validon,\n AllowMultiple = allowmultiple,\n Inherited = inherited\n)]"
},
{
"code": null,
"e": 1582,
"s": 1356,
"text": "This predefined attribute marks a conditional method whose execution depends on a specified preprocessing identifier. It causes conditional compilation of method calls, depending on the specified value such as Debug or Trace."
},
{
"code": null,
"e": 1612,
"s": 1582,
"text": "The following is the syntax −"
},
{
"code": null,
"e": 1650,
"s": 1612,
"text": "[Conditional(\n conditionalSymbol\n)]"
},
{
"code": null,
"e": 1823,
"s": 1650,
"text": "This predefined attribute marks a program entity that should not be used. It enables you to inform the compiler to discard a particular target element. Here is the syntax −"
},
{
"code": null,
"e": 1888,
"s": 1823,
"text": "[Obsolete (\n message\n)]\n\n[Obsolete (\n message,\n iserror\n)]"
}
] |
How to make a Country field in Django?
|
If you need to add a location field in your form or database, you can do that using charfield but it is still not that good idea. In Django, we have a third-party package called 'django-countries' that provides the country field. In this article, let's see how to use django-countries to add a Country field in Django.
First, create a Django project and an app.
Add the app in INSTALLED_APPS and set up urls.
Install the django-countries module −
pip install django-countries
In settings.py, add this −
INSTALLED_APPS += [ 'django_countries']
In app's urls.py −
from django.urls import path
from . import views
urlpatterns = [
path('', views.home, name="home"),
]
First setup your urls.
In views.py −
from django.shortcuts import render
from django import forms
from .models import Data
class SalaryForm(forms.ModelForm):
class Meta:
model=Data
fields="__all__"
def home(request):
if request.method=='POST':
form=SalaryForm(request.POST)
if form.is_valid():
form.save()
else:
form=SalaryForm()
return render(request,'home.html',{'form':form})
Here we simply created a form and rendered it in GET request handler of our view. In POST handler, we save the form data.
Create a templates folder in app directory and a home.html in it. In home.html −
<!DOCTYPE html>
<html>
<head>
<title>
TUT
</title>
<style>
</style>
</head>
<body>
<h2>FORM</h2>
<form action="/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">
</form>
</body>
</html>
This is the front-end html of our form.
In models.py −
from django.db import models
from django_countries.fields import CountryField
# Create your models here.
class Data(models.Model):
Name=models.CharField(max_length=100)
salary = models.CharField(max_length=20)
country_of_work = CountryField(blank=True)
Here we created a model in which we simply added a country field which will store the country data.
Now, make migrations and migrate. You are all done. Now, you can proceed to check the output.
|
[
{
"code": null,
"e": 1381,
"s": 1062,
"text": "If you need to add a location field in your form or database, you can do that using charfield but it is still not that good idea. In Django, we have a third-party package called 'django-countries' that provides the country field. In this article, let's see how to use django-countries to add a Country field in Django."
},
{
"code": null,
"e": 1424,
"s": 1381,
"text": "First, create a Django project and an app."
},
{
"code": null,
"e": 1471,
"s": 1424,
"text": "Add the app in INSTALLED_APPS and set up urls."
},
{
"code": null,
"e": 1509,
"s": 1471,
"text": "Install the django-countries module −"
},
{
"code": null,
"e": 1538,
"s": 1509,
"text": "pip install django-countries"
},
{
"code": null,
"e": 1565,
"s": 1538,
"text": "In settings.py, add this −"
},
{
"code": null,
"e": 1605,
"s": 1565,
"text": "INSTALLED_APPS += [ 'django_countries']"
},
{
"code": null,
"e": 1624,
"s": 1605,
"text": "In app's urls.py −"
},
{
"code": null,
"e": 1730,
"s": 1624,
"text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.home, name=\"home\"),\n]"
},
{
"code": null,
"e": 1753,
"s": 1730,
"text": "First setup your urls."
},
{
"code": null,
"e": 1767,
"s": 1753,
"text": "In views.py −"
},
{
"code": null,
"e": 2161,
"s": 1767,
"text": "from django.shortcuts import render\nfrom django import forms\nfrom .models import Data\nclass SalaryForm(forms.ModelForm):\n class Meta:\n model=Data\n fields=\"__all__\"\ndef home(request):\n if request.method=='POST':\n form=SalaryForm(request.POST)\n if form.is_valid():\n form.save()\n\n else:\n form=SalaryForm()\n return render(request,'home.html',{'form':form})"
},
{
"code": null,
"e": 2283,
"s": 2161,
"text": "Here we simply created a form and rendered it in GET request handler of our view. In POST handler, we save the form data."
},
{
"code": null,
"e": 2364,
"s": 2283,
"text": "Create a templates folder in app directory and a home.html in it. In home.html −"
},
{
"code": null,
"e": 2673,
"s": 2364,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>\n TUT\n </title>\n <style>\n\n </style>\n </head>\n <body>\n <h2>FORM</h2>\n <form action=\"/\" method=\"post\">\n {% csrf_token %}\n {{ form }}\n <input type=\"submit\" value=\"Submit\">\n </form>\n </body>\n</html>"
},
{
"code": null,
"e": 2713,
"s": 2673,
"text": "This is the front-end html of our form."
},
{
"code": null,
"e": 2728,
"s": 2713,
"text": "In models.py −"
},
{
"code": null,
"e": 2991,
"s": 2728,
"text": "from django.db import models\nfrom django_countries.fields import CountryField\n\n# Create your models here.\nclass Data(models.Model):\n Name=models.CharField(max_length=100)\n salary = models.CharField(max_length=20)\n country_of_work = CountryField(blank=True)"
},
{
"code": null,
"e": 3091,
"s": 2991,
"text": "Here we created a model in which we simply added a country field which will store the country data."
},
{
"code": null,
"e": 3185,
"s": 3091,
"text": "Now, make migrations and migrate. You are all done. Now, you can proceed to check the output."
}
] |
HTML checked Attribute
|
The checked attribute in HTML is used to set that an <input> element is pre-selected when the page loads.
This works for input type radio and checkbox.
Let us work on the checked attribute for checkbox i.e. input type checkbox. Following is the syntax −
<input type=”checkbox” checked>
Above, we have set it checked since we wanted the checkbox to be selected when the web page loads. Let us now see an example to implement the checked attribute of the <input> element −
Live Demo
<!DOCTYPE html>
<html>
<body>
<h2>Register</h2>
<form action="" method="get">
Id: <input type="text" name="id" placeholder="Enter UserId here..." size = "25"><br>
Password: <input type="password" name="pwd" placeholder="Enter password here..."><br>
DOB: <input type="date" name="dob" placeholder="Enter date of birth here..."><br>
Telephone: <input type="tel" name="tel" placeholder="Enter mobile number here..."><br>
Email: <input type="email" name="email" placeholder="Enter email here..." size = "35"><br><br>
<input type="checkbox" name="vehicle" value="Bike" checked>Newsletter Subscription: <br>
<button type="submit" value="Submit">Submit</button>
</form>
</body>
</html>
In the above example, we have a form with input elements and a button −
<form action="" method="get">
Id: <input type="text" name="id" placeholder="Enter UserId here..." size = "25"><br>
Password: <input type="password" name="pwd" placeholder="Enter password here..."><br>
DOB: <input type="date" name="dob" placeholder="Enter date of birth here..."><br>
Telephone: <input type="tel" name="tel" placeholder="Enter mobile number here..."><br>
Email: <input type="email" name="email" placeholder="Enter email here..." size = "35"><br><br>
<input type="checkbox" name="vehicle" value="Bike" checked>Newsletter Subscription: <br>
<button type="submit" value="Submit">Submit</button>
</form>
We have set a checkbox using the input type checkbox. To set it checked when the web page loads, the checked attribute is used −
<input type="checkbox" name="vehicle" value="Bike" checked>Newsletter Subscription:
|
[
{
"code": null,
"e": 1168,
"s": 1062,
"text": "The checked attribute in HTML is used to set that an <input> element is pre-selected when the page loads."
},
{
"code": null,
"e": 1214,
"s": 1168,
"text": "This works for input type radio and checkbox."
},
{
"code": null,
"e": 1316,
"s": 1214,
"text": "Let us work on the checked attribute for checkbox i.e. input type checkbox. Following is the syntax −"
},
{
"code": null,
"e": 1348,
"s": 1316,
"text": "<input type=”checkbox” checked>"
},
{
"code": null,
"e": 1533,
"s": 1348,
"text": "Above, we have set it checked since we wanted the checkbox to be selected when the web page loads. Let us now see an example to implement the checked attribute of the <input> element −"
},
{
"code": null,
"e": 1544,
"s": 1533,
"text": " Live Demo"
},
{
"code": null,
"e": 2244,
"s": 1544,
"text": "<!DOCTYPE html>\n<html>\n<body>\n<h2>Register</h2>\n<form action=\"\" method=\"get\">\n Id: <input type=\"text\" name=\"id\" placeholder=\"Enter UserId here...\" size = \"25\"><br>\n Password: <input type=\"password\" name=\"pwd\" placeholder=\"Enter password here...\"><br>\n DOB: <input type=\"date\" name=\"dob\" placeholder=\"Enter date of birth here...\"><br>\n Telephone: <input type=\"tel\" name=\"tel\" placeholder=\"Enter mobile number here...\"><br>\n Email: <input type=\"email\" name=\"email\" placeholder=\"Enter email here...\" size = \"35\"><br><br>\n <input type=\"checkbox\" name=\"vehicle\" value=\"Bike\" checked>Newsletter Subscription: <br>\n <button type=\"submit\" value=\"Submit\">Submit</button>\n</form>\n</body>\n</html>"
},
{
"code": null,
"e": 2316,
"s": 2244,
"text": "In the above example, we have a form with input elements and a button −"
},
{
"code": null,
"e": 2952,
"s": 2316,
"text": "<form action=\"\" method=\"get\">\n Id: <input type=\"text\" name=\"id\" placeholder=\"Enter UserId here...\" size = \"25\"><br>\n Password: <input type=\"password\" name=\"pwd\" placeholder=\"Enter password here...\"><br>\n DOB: <input type=\"date\" name=\"dob\" placeholder=\"Enter date of birth here...\"><br>\n Telephone: <input type=\"tel\" name=\"tel\" placeholder=\"Enter mobile number here...\"><br>\n Email: <input type=\"email\" name=\"email\" placeholder=\"Enter email here...\" size = \"35\"><br><br>\n <input type=\"checkbox\" name=\"vehicle\" value=\"Bike\" checked>Newsletter Subscription: <br>\n <button type=\"submit\" value=\"Submit\">Submit</button>\n</form>"
},
{
"code": null,
"e": 3081,
"s": 2952,
"text": "We have set a checkbox using the input type checkbox. To set it checked when the web page loads, the checked attribute is used −"
},
{
"code": null,
"e": 3165,
"s": 3081,
"text": "<input type=\"checkbox\" name=\"vehicle\" value=\"Bike\" checked>Newsletter Subscription:"
}
] |
Tryit Editor v3.7
|
Tryit: The text-align-last property
|
[] |
map::begin() and end() in C++ STL
|
In this article we will be discussing the working, syntax and examples of map::begin() and map::end() functions 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::begin() function is an inbuilt function in C++ STL, which is defined in header file. begin() is used to access the element which is at the very beginning of the associated map container.
This function returns an iterator which points to the first element of the container. When the container has no values in it the iterator cannot be dereferenced
map_name.begin();
The function accepts no parameter.
This function returns an iterator which is pointing to the first value of the map container.
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.begin();
a:10
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;
cout<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
cout << "\t" << i->first << "\t" << i->second << '\n';
}
return 0;
}
Elements of TP_1 after swap:
KEY ELEMENT
1 10
2 20
3 30
4 40
map::end() function is an inbuilt function in C++ STL, which is defined in <map> header file. end() is used to access the element which is at after the last element in the container, or the past the last element.
This function returns an iterator which points to the element which is next to the last element of the container. When the container has no values in it the iterator cannot be dereferenced
Usually begin() and end() are used to iterate through the map container by giving them range.
map_name.end();
The function accepts no parameter.
This function returns an iterator which is pointing to the past the last value of the map container.
std::map<int> mymap;
mymap.insert({‘a’, 10});
mymap.insert({‘b’, 20});
mymap.insert({‘c’, 30});
mymap.end();
error
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;
cout<<"Elements of TP_1 after swap:\n"<< "\tKEY\tELEMENT\n";
for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {
cout << "\t" << i->first << "\t" << i->second << '\n';
}
return 0;
}
Elements of TP_1 after swap:
KEY ELEMENT
1 10
2 20
3 30
4 40
|
[
{
"code": null,
"e": 1186,
"s": 1062,
"text": "In this article we will be discussing the working, syntax and examples of map::begin() and map::end() functions in C++ STL."
},
{
"code": null,
"e": 1496,
"s": 1186,
"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": 1689,
"s": 1496,
"text": "map::begin() function is an inbuilt function in C++ STL, which is defined in header file. begin() is used to access the element which is at the very beginning of the associated map container."
},
{
"code": null,
"e": 1850,
"s": 1689,
"text": "This function returns an iterator which points to the first element of the container. When the container has no values in it the iterator cannot be dereferenced"
},
{
"code": null,
"e": 1868,
"s": 1850,
"text": "map_name.begin();"
},
{
"code": null,
"e": 1903,
"s": 1868,
"text": "The function accepts no parameter."
},
{
"code": null,
"e": 1996,
"s": 1903,
"text": "This function returns an iterator which is pointing to the first value of the map container."
},
{
"code": null,
"e": 2107,
"s": 1996,
"text": "std::map<int> mymap;\nmymap.insert({‘a’, 10});\nmymap.insert({‘b’, 20});\nmymap.insert({‘c’, 30});\nmymap.begin();"
},
{
"code": null,
"e": 2112,
"s": 2107,
"text": "a:10"
},
{
"code": null,
"e": 2123,
"s": 2112,
"text": " Live Demo"
},
{
"code": null,
"e": 2472,
"s": 2123,
"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 cout<<\"Elements of TP_1 after swap:\\n\"<< \"\\tKEY\\tELEMENT\\n\";\n for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {\n cout << \"\\t\" << i->first << \"\\t\" << i->second << '\\n';\n }\n return 0;\n}"
},
{
"code": null,
"e": 2560,
"s": 2472,
"text": "Elements of TP_1 after swap:\nKEY ELEMENT\n1 10\n2 20\n3 30\n4 40"
},
{
"code": null,
"e": 2773,
"s": 2560,
"text": "map::end() function is an inbuilt function in C++ STL, which is defined in <map> header file. end() is used to access the element which is at after the last element in the container, or the past the last element."
},
{
"code": null,
"e": 2962,
"s": 2773,
"text": "This function returns an iterator which points to the element which is next to the last element of the container. When the container has no values in it the iterator cannot be dereferenced"
},
{
"code": null,
"e": 3056,
"s": 2962,
"text": "Usually begin() and end() are used to iterate through the map container by giving them range."
},
{
"code": null,
"e": 3072,
"s": 3056,
"text": "map_name.end();"
},
{
"code": null,
"e": 3107,
"s": 3072,
"text": "The function accepts no parameter."
},
{
"code": null,
"e": 3208,
"s": 3107,
"text": "This function returns an iterator which is pointing to the past the last value of the map container."
},
{
"code": null,
"e": 3317,
"s": 3208,
"text": "std::map<int> mymap;\nmymap.insert({‘a’, 10});\nmymap.insert({‘b’, 20});\nmymap.insert({‘c’, 30});\nmymap.end();"
},
{
"code": null,
"e": 3323,
"s": 3317,
"text": "error"
},
{
"code": null,
"e": 3334,
"s": 3323,
"text": " Live Demo"
},
{
"code": null,
"e": 3683,
"s": 3334,
"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 cout<<\"Elements of TP_1 after swap:\\n\"<< \"\\tKEY\\tELEMENT\\n\";\n for (auto i = TP_1.begin(); i!= TP_1.end(); i++) {\n cout << \"\\t\" << i->first << \"\\t\" << i->second << '\\n';\n }\n return 0;\n}"
},
{
"code": null,
"e": 3771,
"s": 3683,
"text": "Elements of TP_1 after swap:\nKEY ELEMENT\n1 10\n2 20\n3 30\n4 40"
}
] |
How to call a virtual function inside constructors in C++?
|
Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. This is because the virtual function you call is called from the Base class and not the derived class.
In C++ every class builds its version of the virtual method table prior to entering its own construction. So a call to the virtual method in the constructor will call the Base class' virtual method. Or if it has no implementation at that level, it'll produce a pure virtual method call. Once the Base is fully constructed, the compiler starts building Derived class, and overrides the method pointers to point Derived class' implementation. So for example, If you have the code −
#include<iostream>
using namespace std;
class Base {
public:
Base() { f(); }
virtual void f() { std::cout << "Base" << std::endl; }
};
class Derived : public Base {
public:
Derived() : Base() {}
virtual void f() { std::cout << "Derived" << std::endl; }
};
int main() {
Derived d;
return 0;
}
This will give the output −
Base
|
[
{
"code": null,
"e": 1278,
"s": 1062,
"text": "Calling virtual functions from a constructor or destructor is dangerous and should be avoided whenever possible. This is because the virtual function you call is called from the Base class and not the derived class."
},
{
"code": null,
"e": 1758,
"s": 1278,
"text": "In C++ every class builds its version of the virtual method table prior to entering its own construction. So a call to the virtual method in the constructor will call the Base class' virtual method. Or if it has no implementation at that level, it'll produce a pure virtual method call. Once the Base is fully constructed, the compiler starts building Derived class, and overrides the method pointers to point Derived class' implementation. So for example, If you have the code −"
},
{
"code": null,
"e": 2074,
"s": 1758,
"text": "#include<iostream>\nusing namespace std;\n\nclass Base {\npublic:\n Base() { f(); }\n virtual void f() { std::cout << \"Base\" << std::endl; }\n};\nclass Derived : public Base {\npublic:\n Derived() : Base() {}\n virtual void f() { std::cout << \"Derived\" << std::endl; }\n};\n\nint main() {\n Derived d; \n return 0;\n}"
},
{
"code": null,
"e": 2102,
"s": 2074,
"text": "This will give the output −"
},
{
"code": null,
"e": 2107,
"s": 2102,
"text": "Base"
}
] |
Render Interactive plots with Matplotlib | by Parul Pandey | Towards Data Science
|
Good charts effectively convey information. Great charts enable, inform, and improve decision making.” — Dante Vitagliano
Interactive charts are loved by all as they can tell a story more effectively. The same is true in data science and allied fields. Exploratory data analysis is an essential step in the data preprocessing pipeline, and there are a lot of libraries available in the ecosystem to achieve that. The graphic below beautifully encapsulates this idea.
Even with so many choices, Matplotlib , fondly known as the Grandfather of python visualization packages remains a favorite for many. The lack of interactiveness, however, remains a bottleneck. So, workarounds have been devised to include interactivity via some third-party libraries. But did you know that it is also possible to create interactive plots with matplotlib directly, provided you are using an interactive backend? This article will look at two such backends and how they render interactivity within the notebooks, using only matplotlib.
Matplotlib caters to different users and hence supports various backends. As per the documentation:
the “frontend” is the user facing code, i.e., the plotting code, whereas the “backend” does all the hard work behind-the-scenes to make the figure.
This means the pre-requisite for interactivity is having an interactive backend. The default backend in the Jupyter notebooks is the inline backend which is enabled by %matplotlib inline.It is great at rendering static images but offers no interactive features like pan, zoom, or auto-updating the figures from other cells.
On the contrary, there are backends which when enabled, render interactive images. This article will go over the two common ones and so that you can use them in your data visualization tasks.
The backend_nbagg renders interactive figures in a notebook. It makes use of the infrastructure developed for the webagg backend.
Enabling the backend
To enable the backend in the Jupyter notebook, type the following
%matplotlib notebook
Usage
Here is an elementary example to showcase the usage of the nbagg backend.
# The code is to be run in a Jupyter Notebookimport matplotlib.pyplot as plt%matplotlib notebookplt.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45], linewidth = 3, c = 'g')
It is also possible to auto-update the figure from other cells. For instance, the line chart can be updated via the code executed in the subsequent cells in the figure below.
This functionality can be switched off easily with a blue button 🔵 provided on the right-hand side corner. When clicked, the interaction will stop, and a new plot will be generated in the next cell. It's that simple.
The interactivity is not only limited to 2D plots but can also be observed in 3D plots. The code has been taken from matplotlib's official documentation.
# The code is to be run in a Jupyter Notebook or Jupyter Labimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import axes3d%matplotlib notebookfig = plt.figure()ax = fig.add_subplot(111, projection='3d')# Grab some test data.X, Y, Z = axes3d.get_test_data(0.05)# Plot a surface plot.ax.plot_surface(X, Y, Z, rstride=10, cstride=10, )plt.show()
This option works well and gets our work done, but it is not compatible with Jupyter Lab. As a result, it isn't of much use for the Jupyter Lab users. Also, the save option doesn’t seem to work for me. There is a better alternative to achieve the same results, albeit with a different backend.
The ipyml backend renders interactive figures in the 'classic' notebook as well as the Jupyter lab. The ipyml backend uses the ipywidget framework and needs to be installed separately. Widgets are used to build interactive GUIs right in the notebook environment. With the help of controls like a slider, textbox, etc., users can seamlessly interact with their visualizations.
Ipympl's can be easily installed with pip or conda. Refer to the documentation for more details.
pip install ipymplor conda install -c conda-forge ipympl
For Jupyter Lab users, node js and jupyterLab extension manager are also required. For a better experience, it is recommended to use JupyterLab >= 3.
conda install -c conda-forge nodejsjupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter-matplotlib
Enabling the backend
To be able to use the ipyml backend, one needs to type the following :
%matplotlib widget
Now that we have fulfilled all the requirements, it's time for the demo.
We'll use the same example as we used in the last section. This will also help us to compare the two functionalities.
# The code is to be run in a Jupyter Notebook or Jupyter Labimport matplotlib.pyplot as plt%matplotlib widgetplt.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45])
The ipyml backend also works for the 3D visualizations.
The controls, in this case, lie on the right side of the figure but other than that, it is pretty similar to the plot obtained in the last section. That is true, but there are some subtle differences, in case you have noticed:
Plots can be saved as static images.
The plot widget can be resized by the UI.
This is a great feature that I haven't seen in most of the other visualization libraries.
The ipyml backend enables interactivity in matplotlib and all the libraries built on top of matplotlib like Pandas, Geopandas, Seaborn, etc.
Here is a summary of what we covered in this article. We learnt about a few of the matplotlib's backends and learnt about the ones that enable interactivity. Both nbagg and ipyml seem to work great, but ipyml has additional features that are preferable. I'm sure you'll like to experiment with these backends and see the interactive features for yourself. If you liked this article, I believe you'll also like few other pieces that I wrote involving matplotlib directly or indirectly.
In case you want to use the matplotlib library to create some engaging animations.
towardsdatascience.com
A tutorial on creating Plotly and Bokeh plots directly with Pandas plotting syntax
towardsdatascience.com
Some of the advanced plots in matplotlib, which can take our analysis a notch higher.
|
[
{
"code": null,
"e": 294,
"s": 172,
"text": "Good charts effectively convey information. Great charts enable, inform, and improve decision making.” — Dante Vitagliano"
},
{
"code": null,
"e": 639,
"s": 294,
"text": "Interactive charts are loved by all as they can tell a story more effectively. The same is true in data science and allied fields. Exploratory data analysis is an essential step in the data preprocessing pipeline, and there are a lot of libraries available in the ecosystem to achieve that. The graphic below beautifully encapsulates this idea."
},
{
"code": null,
"e": 1190,
"s": 639,
"text": "Even with so many choices, Matplotlib , fondly known as the Grandfather of python visualization packages remains a favorite for many. The lack of interactiveness, however, remains a bottleneck. So, workarounds have been devised to include interactivity via some third-party libraries. But did you know that it is also possible to create interactive plots with matplotlib directly, provided you are using an interactive backend? This article will look at two such backends and how they render interactivity within the notebooks, using only matplotlib."
},
{
"code": null,
"e": 1290,
"s": 1190,
"text": "Matplotlib caters to different users and hence supports various backends. As per the documentation:"
},
{
"code": null,
"e": 1438,
"s": 1290,
"text": "the “frontend” is the user facing code, i.e., the plotting code, whereas the “backend” does all the hard work behind-the-scenes to make the figure."
},
{
"code": null,
"e": 1762,
"s": 1438,
"text": "This means the pre-requisite for interactivity is having an interactive backend. The default backend in the Jupyter notebooks is the inline backend which is enabled by %matplotlib inline.It is great at rendering static images but offers no interactive features like pan, zoom, or auto-updating the figures from other cells."
},
{
"code": null,
"e": 1954,
"s": 1762,
"text": "On the contrary, there are backends which when enabled, render interactive images. This article will go over the two common ones and so that you can use them in your data visualization tasks."
},
{
"code": null,
"e": 2084,
"s": 1954,
"text": "The backend_nbagg renders interactive figures in a notebook. It makes use of the infrastructure developed for the webagg backend."
},
{
"code": null,
"e": 2105,
"s": 2084,
"text": "Enabling the backend"
},
{
"code": null,
"e": 2171,
"s": 2105,
"text": "To enable the backend in the Jupyter notebook, type the following"
},
{
"code": null,
"e": 2192,
"s": 2171,
"text": "%matplotlib notebook"
},
{
"code": null,
"e": 2198,
"s": 2192,
"text": "Usage"
},
{
"code": null,
"e": 2272,
"s": 2198,
"text": "Here is an elementary example to showcase the usage of the nbagg backend."
},
{
"code": null,
"e": 2446,
"s": 2272,
"text": "# The code is to be run in a Jupyter Notebookimport matplotlib.pyplot as plt%matplotlib notebookplt.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45], linewidth = 3, c = 'g')"
},
{
"code": null,
"e": 2621,
"s": 2446,
"text": "It is also possible to auto-update the figure from other cells. For instance, the line chart can be updated via the code executed in the subsequent cells in the figure below."
},
{
"code": null,
"e": 2838,
"s": 2621,
"text": "This functionality can be switched off easily with a blue button 🔵 provided on the right-hand side corner. When clicked, the interaction will stop, and a new plot will be generated in the next cell. It's that simple."
},
{
"code": null,
"e": 2992,
"s": 2838,
"text": "The interactivity is not only limited to 2D plots but can also be observed in 3D plots. The code has been taken from matplotlib's official documentation."
},
{
"code": null,
"e": 3343,
"s": 2992,
"text": "# The code is to be run in a Jupyter Notebook or Jupyter Labimport matplotlib.pyplot as pltfrom mpl_toolkits.mplot3d import axes3d%matplotlib notebookfig = plt.figure()ax = fig.add_subplot(111, projection='3d')# Grab some test data.X, Y, Z = axes3d.get_test_data(0.05)# Plot a surface plot.ax.plot_surface(X, Y, Z, rstride=10, cstride=10, )plt.show()"
},
{
"code": null,
"e": 3637,
"s": 3343,
"text": "This option works well and gets our work done, but it is not compatible with Jupyter Lab. As a result, it isn't of much use for the Jupyter Lab users. Also, the save option doesn’t seem to work for me. There is a better alternative to achieve the same results, albeit with a different backend."
},
{
"code": null,
"e": 4013,
"s": 3637,
"text": "The ipyml backend renders interactive figures in the 'classic' notebook as well as the Jupyter lab. The ipyml backend uses the ipywidget framework and needs to be installed separately. Widgets are used to build interactive GUIs right in the notebook environment. With the help of controls like a slider, textbox, etc., users can seamlessly interact with their visualizations."
},
{
"code": null,
"e": 4110,
"s": 4013,
"text": "Ipympl's can be easily installed with pip or conda. Refer to the documentation for more details."
},
{
"code": null,
"e": 4167,
"s": 4110,
"text": "pip install ipymplor conda install -c conda-forge ipympl"
},
{
"code": null,
"e": 4317,
"s": 4167,
"text": "For Jupyter Lab users, node js and jupyterLab extension manager are also required. For a better experience, it is recommended to use JupyterLab >= 3."
},
{
"code": null,
"e": 4436,
"s": 4317,
"text": "conda install -c conda-forge nodejsjupyter labextension install @jupyter-widgets/jupyterlab-manager jupyter-matplotlib"
},
{
"code": null,
"e": 4457,
"s": 4436,
"text": "Enabling the backend"
},
{
"code": null,
"e": 4528,
"s": 4457,
"text": "To be able to use the ipyml backend, one needs to type the following :"
},
{
"code": null,
"e": 4547,
"s": 4528,
"text": "%matplotlib widget"
},
{
"code": null,
"e": 4620,
"s": 4547,
"text": "Now that we have fulfilled all the requirements, it's time for the demo."
},
{
"code": null,
"e": 4738,
"s": 4620,
"text": "We'll use the same example as we used in the last section. This will also help us to compare the two functionalities."
},
{
"code": null,
"e": 4901,
"s": 4738,
"text": "# The code is to be run in a Jupyter Notebook or Jupyter Labimport matplotlib.pyplot as plt%matplotlib widgetplt.plot([1,2,3,4,5,6,7], [10, 50, 100, 23,15,28,45])"
},
{
"code": null,
"e": 4957,
"s": 4901,
"text": "The ipyml backend also works for the 3D visualizations."
},
{
"code": null,
"e": 5184,
"s": 4957,
"text": "The controls, in this case, lie on the right side of the figure but other than that, it is pretty similar to the plot obtained in the last section. That is true, but there are some subtle differences, in case you have noticed:"
},
{
"code": null,
"e": 5221,
"s": 5184,
"text": "Plots can be saved as static images."
},
{
"code": null,
"e": 5263,
"s": 5221,
"text": "The plot widget can be resized by the UI."
},
{
"code": null,
"e": 5353,
"s": 5263,
"text": "This is a great feature that I haven't seen in most of the other visualization libraries."
},
{
"code": null,
"e": 5494,
"s": 5353,
"text": "The ipyml backend enables interactivity in matplotlib and all the libraries built on top of matplotlib like Pandas, Geopandas, Seaborn, etc."
},
{
"code": null,
"e": 5979,
"s": 5494,
"text": "Here is a summary of what we covered in this article. We learnt about a few of the matplotlib's backends and learnt about the ones that enable interactivity. Both nbagg and ipyml seem to work great, but ipyml has additional features that are preferable. I'm sure you'll like to experiment with these backends and see the interactive features for yourself. If you liked this article, I believe you'll also like few other pieces that I wrote involving matplotlib directly or indirectly."
},
{
"code": null,
"e": 6062,
"s": 5979,
"text": "In case you want to use the matplotlib library to create some engaging animations."
},
{
"code": null,
"e": 6085,
"s": 6062,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6168,
"s": 6085,
"text": "A tutorial on creating Plotly and Bokeh plots directly with Pandas plotting syntax"
},
{
"code": null,
"e": 6191,
"s": 6168,
"text": "towardsdatascience.com"
}
] |
Convert Binary fraction to Decimal - GeeksforGeeks
|
14 May, 2021
Given an string of binary number n. Convert binary fractional n into it’s decimal equivalent.
Examples:
Input: n = 110.101
Output: 6.625
Input: n = 101.1101
Output: 5.8125
Following are the steps of converting binary fractional to decimal.
A) Convert the integral part of binary to decimal equivalent
Multiply each digit separately from left side of radix point till the first digit by 20, 21, 22,... respectively.Add all the result coming from step 1.Equivalent integral decimal number would be the result obtained in step 2.
Multiply each digit separately from left side of radix point till the first digit by 20, 21, 22,... respectively.
Add all the result coming from step 1.
Equivalent integral decimal number would be the result obtained in step 2.
B) Convert the fractional part of binary to decimal equivalent
Divide each digit from right side of radix point till the end by 21, 22, 23, ... respectively.Add all the result coming from step 1.Equivalent fractional decimal number would be the result obtained in step 2.
Divide each digit from right side of radix point till the end by 21, 22, 23, ... respectively.
Add all the result coming from step 1.
Equivalent fractional decimal number would be the result obtained in step 2.
C) Add both integral and fractional part of decimal number.Illustration
Let's take an example for n = 110.101
Step 1: Conversion of 110 to decimal
=> 1102 = (1*22) + (1*21) + (0*20)
=> 1102 = 4 + 2 + 0
=> 1102 = 6
So equivalent decimal of binary integral is 6.
Step 2: Conversion of .101 to decimal
=> 0.1012 = (1*1/2) + (0*1/22) + (1*1/23)
=> 0.1012 = 1*0.5 + 0*0.25 + 1*0.125
=> 0.1012 = 0.625
So equivalent decimal of binary fractional is 0.625
Step 3: Add result of step 1 and 2.
=> 6 + 0.625 = 6.625
C++
Java
Python3
C#
Javascript
// C++ program to demonstrate above steps of// binary fractional to decimal conversion#include<bits/stdc++.h>using namespace std; // Function to convert binary fractional to// decimaldouble binaryToDecimal(string binary, int len){ // Fetch the radix point size_t point = binary.find('.'); // Update point if not found if (point == string::npos) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for (int i = point-1; i>=0; --i) { // Subtract '0' to convert character // into integer intDecimal += (binary[i] - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for (int i = point+1; i < len; ++i) { fracDecimal += (binary[i] - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal;} // Driver codeint main(){ string n = "110.101"; cout << binaryToDecimal(n, n.length()) << "\n"; n = "101.1101"; cout << binaryToDecimal(n, n.length()); return 0;}
// Java program to demonstrate above steps of// binary fractional to decimal conversionimport java.io.*; class GFG{ // Function to convert binary fractional to// decimalstatic double binaryToDecimal(String binary, int len){ // Fetch the radix point int point = binary.indexOf('.'); // Update point if not found if (point == -1) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for(int i = point - 1; i >= 0; i--) { intDecimal += (binary.charAt(i) - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for(int i = point + 1; i < len; i++) { fracDecimal += (binary.charAt(i) - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal;} // Driver Codepublic static void main(String[] args){ String n = "110.101"; System.out.println( binaryToDecimal(n, n.length())); n = "101.1101"; System.out.println( binaryToDecimal(n, n.length()));}} // This code is contributed by dheeraj_2801
# Python3 program to demonstrate above steps# of binary fractional to decimal conversion # Function to convert binary fractional # to decimaldef binaryToDecimal(binary, length) : # Fetch the radix point point = binary.find('.') # Update point if not found if (point == -1) : point = length intDecimal = 0 fracDecimal = 0 twos = 1 # Convert integral part of binary # to decimal equivalent for i in range(point-1, -1, -1) : # Subtract '0' to convert # character into integer intDecimal += ((ord(binary[i]) - ord('0')) * twos) twos *= 2 # Convert fractional part of binary # to decimal equivalent twos = 2 for i in range(point + 1, length): fracDecimal += ((ord(binary[i]) - ord('0')) / twos); twos *= 2.0 # Add both integral and fractional part ans = intDecimal + fracDecimal return ans # Driver code :if __name__ == "__main__" : n = "110.101" print(binaryToDecimal(n, len(n))) n = "101.1101" print(binaryToDecimal(n, len(n))) # This code is contributed# by aishwarya.27
// C# program to demonstrate above steps of// binary fractional to decimal conversionusing System; class GFG{ // Function to convert binary fractional to// decimalstatic double binaryToDecimal(string binary, int len){ // Fetch the radix point int point = binary.IndexOf('.'); // Update point if not found if (point == -1) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for(int i = point - 1; i >= 0; i--) { intDecimal += (binary[i] - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for(int i = point + 1; i < len; i++) { fracDecimal += (binary[i] - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal;} // Driver Codepublic static void Main(string[] args){ string n = "110.101"; Console.Write( binaryToDecimal(n, n.Length) + "\n"); n = "101.1101"; Console.Write( binaryToDecimal(n, n.Length));}} // This code is contributed by rutvik_56
<script> // JavaScript program to demonstrate above steps of // binary fractional to decimal conversion // Function to convert binary fractional to // decimal function binaryToDecimal(binary, len) { // Fetch the radix point var point = binary.indexOf("."); // Update point if not found if (point === -1) point = len; var intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for (var i = point - 1; i >= 0; i--) { intDecimal += (binary[i] - "0") * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for (var i = point + 1; i < len; i++) { fracDecimal += (binary[i] - "0") / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal; } // Driver Code var n = "110.101"; document.write(binaryToDecimal(n, n.length) + "<br>"); n = "101.1101"; document.write(binaryToDecimal(n, n.length)); </script>
Output:
6.625
5.8125
Time complexity: O(len(n)) Auxiliary space: O(len(n))
Where len is the total digits contain in binary number of n.
See this: Convert decimal fraction to binary number.This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
aishwarya.27
mohndar131131
dheeraj_2801
rutvik_56
khushboogoyal499
rdtank
binary-representation
Fraction
number-digits
TCS
Mathematical
Strings
TCS
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Prime Numbers
Program to find sum of elements in a given array
Reverse a string in Java
Write a program to reverse an array or string
Longest Common Subsequence | DP-4
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
|
[
{
"code": null,
"e": 24806,
"s": 24778,
"text": "\n14 May, 2021"
},
{
"code": null,
"e": 24900,
"s": 24806,
"text": "Given an string of binary number n. Convert binary fractional n into it’s decimal equivalent."
},
{
"code": null,
"e": 24910,
"s": 24900,
"text": "Examples:"
},
{
"code": null,
"e": 24979,
"s": 24910,
"text": "Input: n = 110.101\nOutput: 6.625\n\nInput: n = 101.1101\nOutput: 5.8125"
},
{
"code": null,
"e": 25047,
"s": 24979,
"text": "Following are the steps of converting binary fractional to decimal."
},
{
"code": null,
"e": 25108,
"s": 25047,
"text": "A) Convert the integral part of binary to decimal equivalent"
},
{
"code": null,
"e": 25334,
"s": 25108,
"text": "Multiply each digit separately from left side of radix point till the first digit by 20, 21, 22,... respectively.Add all the result coming from step 1.Equivalent integral decimal number would be the result obtained in step 2."
},
{
"code": null,
"e": 25448,
"s": 25334,
"text": "Multiply each digit separately from left side of radix point till the first digit by 20, 21, 22,... respectively."
},
{
"code": null,
"e": 25487,
"s": 25448,
"text": "Add all the result coming from step 1."
},
{
"code": null,
"e": 25562,
"s": 25487,
"text": "Equivalent integral decimal number would be the result obtained in step 2."
},
{
"code": null,
"e": 25625,
"s": 25562,
"text": "B) Convert the fractional part of binary to decimal equivalent"
},
{
"code": null,
"e": 25834,
"s": 25625,
"text": "Divide each digit from right side of radix point till the end by 21, 22, 23, ... respectively.Add all the result coming from step 1.Equivalent fractional decimal number would be the result obtained in step 2."
},
{
"code": null,
"e": 25929,
"s": 25834,
"text": "Divide each digit from right side of radix point till the end by 21, 22, 23, ... respectively."
},
{
"code": null,
"e": 25968,
"s": 25929,
"text": "Add all the result coming from step 1."
},
{
"code": null,
"e": 26045,
"s": 25968,
"text": "Equivalent fractional decimal number would be the result obtained in step 2."
},
{
"code": null,
"e": 26117,
"s": 26045,
"text": "C) Add both integral and fractional part of decimal number.Illustration"
},
{
"code": null,
"e": 26553,
"s": 26117,
"text": "Let's take an example for n = 110.101\n\nStep 1: Conversion of 110 to decimal\n=> 1102 = (1*22) + (1*21) + (0*20)\n=> 1102 = 4 + 2 + 0\n=> 1102 = 6\nSo equivalent decimal of binary integral is 6.\n\nStep 2: Conversion of .101 to decimal\n=> 0.1012 = (1*1/2) + (0*1/22) + (1*1/23)\n=> 0.1012 = 1*0.5 + 0*0.25 + 1*0.125\n=> 0.1012 = 0.625\nSo equivalent decimal of binary fractional is 0.625\n\nStep 3: Add result of step 1 and 2.\n=> 6 + 0.625 = 6.625"
},
{
"code": null,
"e": 26557,
"s": 26553,
"text": "C++"
},
{
"code": null,
"e": 26562,
"s": 26557,
"text": "Java"
},
{
"code": null,
"e": 26570,
"s": 26562,
"text": "Python3"
},
{
"code": null,
"e": 26573,
"s": 26570,
"text": "C#"
},
{
"code": null,
"e": 26584,
"s": 26573,
"text": "Javascript"
},
{
"code": "// C++ program to demonstrate above steps of// binary fractional to decimal conversion#include<bits/stdc++.h>using namespace std; // Function to convert binary fractional to// decimaldouble binaryToDecimal(string binary, int len){ // Fetch the radix point size_t point = binary.find('.'); // Update point if not found if (point == string::npos) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for (int i = point-1; i>=0; --i) { // Subtract '0' to convert character // into integer intDecimal += (binary[i] - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for (int i = point+1; i < len; ++i) { fracDecimal += (binary[i] - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal;} // Driver codeint main(){ string n = \"110.101\"; cout << binaryToDecimal(n, n.length()) << \"\\n\"; n = \"101.1101\"; cout << binaryToDecimal(n, n.length()); return 0;}",
"e": 27722,
"s": 26584,
"text": null
},
{
"code": "// Java program to demonstrate above steps of// binary fractional to decimal conversionimport java.io.*; class GFG{ // Function to convert binary fractional to// decimalstatic double binaryToDecimal(String binary, int len){ // Fetch the radix point int point = binary.indexOf('.'); // Update point if not found if (point == -1) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for(int i = point - 1; i >= 0; i--) { intDecimal += (binary.charAt(i) - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for(int i = point + 1; i < len; i++) { fracDecimal += (binary.charAt(i) - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal;} // Driver Codepublic static void main(String[] args){ String n = \"110.101\"; System.out.println( binaryToDecimal(n, n.length())); n = \"101.1101\"; System.out.println( binaryToDecimal(n, n.length()));}} // This code is contributed by dheeraj_2801",
"e": 28943,
"s": 27722,
"text": null
},
{
"code": "# Python3 program to demonstrate above steps# of binary fractional to decimal conversion # Function to convert binary fractional # to decimaldef binaryToDecimal(binary, length) : # Fetch the radix point point = binary.find('.') # Update point if not found if (point == -1) : point = length intDecimal = 0 fracDecimal = 0 twos = 1 # Convert integral part of binary # to decimal equivalent for i in range(point-1, -1, -1) : # Subtract '0' to convert # character into integer intDecimal += ((ord(binary[i]) - ord('0')) * twos) twos *= 2 # Convert fractional part of binary # to decimal equivalent twos = 2 for i in range(point + 1, length): fracDecimal += ((ord(binary[i]) - ord('0')) / twos); twos *= 2.0 # Add both integral and fractional part ans = intDecimal + fracDecimal return ans # Driver code :if __name__ == \"__main__\" : n = \"110.101\" print(binaryToDecimal(n, len(n))) n = \"101.1101\" print(binaryToDecimal(n, len(n))) # This code is contributed# by aishwarya.27",
"e": 30114,
"s": 28943,
"text": null
},
{
"code": "// C# program to demonstrate above steps of// binary fractional to decimal conversionusing System; class GFG{ // Function to convert binary fractional to// decimalstatic double binaryToDecimal(string binary, int len){ // Fetch the radix point int point = binary.IndexOf('.'); // Update point if not found if (point == -1) point = len; double intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for(int i = point - 1; i >= 0; i--) { intDecimal += (binary[i] - '0') * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for(int i = point + 1; i < len; i++) { fracDecimal += (binary[i] - '0') / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal;} // Driver Codepublic static void Main(string[] args){ string n = \"110.101\"; Console.Write( binaryToDecimal(n, n.Length) + \"\\n\"); n = \"101.1101\"; Console.Write( binaryToDecimal(n, n.Length));}} // This code is contributed by rutvik_56",
"e": 31320,
"s": 30114,
"text": null
},
{
"code": "<script> // JavaScript program to demonstrate above steps of // binary fractional to decimal conversion // Function to convert binary fractional to // decimal function binaryToDecimal(binary, len) { // Fetch the radix point var point = binary.indexOf(\".\"); // Update point if not found if (point === -1) point = len; var intDecimal = 0, fracDecimal = 0, twos = 1; // Convert integral part of binary to decimal // equivalent for (var i = point - 1; i >= 0; i--) { intDecimal += (binary[i] - \"0\") * twos; twos *= 2; } // Convert fractional part of binary to // decimal equivalent twos = 2; for (var i = point + 1; i < len; i++) { fracDecimal += (binary[i] - \"0\") / twos; twos *= 2.0; } // Add both integral and fractional part return intDecimal + fracDecimal; } // Driver Code var n = \"110.101\"; document.write(binaryToDecimal(n, n.length) + \"<br>\"); n = \"101.1101\"; document.write(binaryToDecimal(n, n.length)); </script>",
"e": 32472,
"s": 31320,
"text": null
},
{
"code": null,
"e": 32481,
"s": 32472,
"text": "Output: "
},
{
"code": null,
"e": 32494,
"s": 32481,
"text": "6.625\n5.8125"
},
{
"code": null,
"e": 32549,
"s": 32494,
"text": "Time complexity: O(len(n)) Auxiliary space: O(len(n)) "
},
{
"code": null,
"e": 32610,
"s": 32549,
"text": "Where len is the total digits contain in binary number of n."
},
{
"code": null,
"e": 32960,
"s": 32610,
"text": "See this: Convert decimal fraction to binary number.This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 32973,
"s": 32960,
"text": "aishwarya.27"
},
{
"code": null,
"e": 32987,
"s": 32973,
"text": "mohndar131131"
},
{
"code": null,
"e": 33000,
"s": 32987,
"text": "dheeraj_2801"
},
{
"code": null,
"e": 33010,
"s": 33000,
"text": "rutvik_56"
},
{
"code": null,
"e": 33027,
"s": 33010,
"text": "khushboogoyal499"
},
{
"code": null,
"e": 33034,
"s": 33027,
"text": "rdtank"
},
{
"code": null,
"e": 33056,
"s": 33034,
"text": "binary-representation"
},
{
"code": null,
"e": 33065,
"s": 33056,
"text": "Fraction"
},
{
"code": null,
"e": 33079,
"s": 33065,
"text": "number-digits"
},
{
"code": null,
"e": 33083,
"s": 33079,
"text": "TCS"
},
{
"code": null,
"e": 33096,
"s": 33083,
"text": "Mathematical"
},
{
"code": null,
"e": 33104,
"s": 33096,
"text": "Strings"
},
{
"code": null,
"e": 33108,
"s": 33104,
"text": "TCS"
},
{
"code": null,
"e": 33116,
"s": 33108,
"text": "Strings"
},
{
"code": null,
"e": 33129,
"s": 33116,
"text": "Mathematical"
},
{
"code": null,
"e": 33227,
"s": 33129,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 33251,
"s": 33227,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 33293,
"s": 33251,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 33336,
"s": 33293,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 33350,
"s": 33336,
"text": "Prime Numbers"
},
{
"code": null,
"e": 33399,
"s": 33350,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 33424,
"s": 33399,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 33470,
"s": 33424,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 33504,
"s": 33470,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 33579,
"s": 33504,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
Check if a given pattern exists in a given string or not - GeeksforGeeks
|
11 Jun, 2021
Given two strings text and pattern of length M and N respectively, the task is to check if the pattern matches the text or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Note: pattern can include the characters ‘*’ and ‘•’
‘*’ matches zero or more occurrences of character right before the current character
‘•’ matches any signal character.
Examples:
Input: pattern = “ge*ksforgeeks”, text = “geeksforgeeks” Output: Yes Explanation: Replacing * with ‘e’, modifies pattern equal to “geeksforgeeks”. Therefore, the required output is Yes.
Input: pattern = “ab*d”, text = “abcds”Output: No Explanation: The given pattern cannot be matched with the text.
Naive Approach: The simplest approach to solve this problem is to iterate over the characters of the both the strings using recursion. If current character is ‘.’, replace current character to any character and recur for the remaining pattern and text string. Otherwise, if the current character is ‘*’, recur for the remaining text and check if it matches the rest of the pattern or not. If found to be true, then print “Yes”. Otherwise, print “No”.
Time Complexity: O((M + N) * 2(M + N / 2)) Auxiliary Space: O((M + N) * 2(M + N / 2))
Efficient Approach: The above approach can be optimized using Dynamic Programming. Following are the recurrence relation:
Initialize a 2D array, dp[M + 1][N + 1], where dp[i][j] check if the substring { text[0], ..., text[i] } is matches with the substring { pattern[0], ... pattern[j] } or not.
Iterate over the characters of the both the strings and fill the dp[][] array based on the following recurrence relation: If text[i] and pattern[j] are the same then fill dp[i + 1][j + 1] = dp[i][j].If pattern[j] is ‘.’ then fill dp[i + 1][j + 1] = dp[i][j].If pattern[j] is ‘*’ then check the following conditions: If text[i] is not equal to pattern[j – 1] and pattern[j – 1] is not equal to ‘.’, then fill dp[i + 1][j + 1] = dp[i + 1][j – 1].Otherwise, fill dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j – 1]).
If text[i] and pattern[j] are the same then fill dp[i + 1][j + 1] = dp[i][j].
If pattern[j] is ‘.’ then fill dp[i + 1][j + 1] = dp[i][j].
If pattern[j] is ‘*’ then check the following conditions: If text[i] is not equal to pattern[j – 1] and pattern[j – 1] is not equal to ‘.’, then fill dp[i + 1][j + 1] = dp[i + 1][j – 1].Otherwise, fill dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j – 1]).
If text[i] is not equal to pattern[j – 1] and pattern[j – 1] is not equal to ‘.’, then fill dp[i + 1][j + 1] = dp[i + 1][j – 1].
Otherwise, fill dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j – 1]).
Finally, print the value of dp[M][N].
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the pattern// consisting of '*', '.' and lowercase// characters matches the text or notint isMatch(string text, string pattern){ // Base Case if (text == "" or pattern == "") return false; // Stores length of text int N = text.size(); // Stores length of pattern int M = pattern.size(); // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not vector<vector<bool>> dp(N + 1, vector<bool>(M + 1, false)); // Base Case dp[0][0] = true; // Iterate over the characters // of the string pattern for (int i = 0; i < M; i++) { if (pattern[i] == '*' && dp[0][i - 1]) { // Update dp[0][i + 1] dp[0][i + 1] = true; } } // Iterate over the characters // of both the strings for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern[j] == '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character in // both the strings are equal if (pattern[j] == text[i]) { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character // in the pattern is '*' if (pattern[j] == '*') { if (pattern[j - 1] != text[i] && pattern[j - 1] != '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] or dp[i][j + 1] or dp[i + 1][j - 1]); } } } } // Return dp[M][N] return dp[N][M];} // Driver Codeint main(){ string text = "geeksforgeeks"; string pattern = "ge*ksforgeeks"; if (isMatch(text, pattern)) cout<<"Yes"; else cout<<"No";} // This code is contributed by mohiy kumar 29.
// Java program for the above approach import java.io.*; class GFG { // Function to check if the pattern // consisting of '*', '.' and lowercase // characters matches the text or not static boolean isMatch(String text, String pattern) { // Base Case if (text == null || pattern == null) { return false; } // Stores length of text int N = text.length(); // Stores length of pattern int M = pattern.length(); // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not boolean[][] dp = new boolean[N + 1][M + 1]; // Base Case dp[0][0] = true; // Iterate over the characters // of the string pattern for (int i = 0; i < M; i++) { if (pattern.charAt(i) == '*' && dp[0][i - 1]) { // Update dp[0][i + 1] dp[0][i + 1] = true; } } // Iterate over the characters // of both the strings for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern.charAt(j) == '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character in // both the strings are equal if (pattern.charAt(j) == text.charAt(i)) { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character // in the pattern is '*' if (pattern.charAt(j) == '*') { if (pattern.charAt(j - 1) != text.charAt(i) && pattern.charAt(j - 1) != '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } // Return dp[M][N] return dp[N][M]; } // Driver Code public static void main(String[] args) { String text = "geeksforgeeks"; String pattern = "ge*ksforgeeks"; if (isMatch(text, pattern)) { System.out.println("Yes"); } else { System.out.println("No"); } }}
# Python3 program for the above approachimport numpy as np # Function to check if the pattern# consisting of '*', '.' and lowercase# characters matches the text or notdef isMatch(text, pattern): # Base Case if (text == "" or pattern == ""): return False # Stores length of text N = len(text) # Stores length of pattern M = len(pattern) # dp[i][j]: Check if { text[0], .. text[i] } # matches {pattern[0], ... pattern[j]} or not dp = np.zeros((N + 1, M + 1)) # Base Case dp[0][0] = True # Iterate over the characters # of the string pattern for i in range(M): if (pattern[i] == '*' and dp[0][i - 1]): # Update dp[0][i + 1] dp[0][i + 1] = True # Iterate over the characters # of both the strings for i in range(N): for j in range(M): # If current character # in the pattern is '.' if (pattern[j] == '.'): # Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j] # If current character in # both the strings are equal if (pattern[j] == text[i]): # Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j] # If current character # in the pattern is '*' if (pattern[j] == '*'): if (pattern[j - 1] != text[i] and pattern[j - 1] != '.'): # Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1] else: # Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] or dp[i][j + 1] or dp[i + 1][j - 1]) # Return dp[M][N] return dp[N][M] # Driver Codeif __name__ == "__main__" : text = "geeksforgeeks" pattern = "ge*ksforgeeks" if (isMatch(text, pattern)): print("Yes") else: print("No") # This code is contributed by AnkThon
// C# program for the above approachusing System; class GFG{ // Function to check if the pattern// consisting of '*', '.' and lowercase// characters matches the text or notstatic bool isMatch(string text, string pattern){ // Base Case if (text == null || pattern == null) { return false; } // Stores length of text int N = text.Length; // Stores length of pattern int M = pattern.Length; // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not bool[,] dp = new bool[N + 1, M + 1]; // Base Case dp[0, 0] = true; // Iterate over the characters // of the string pattern for(int i = 0; i < M; i++) { if (pattern[i] == '*' && dp[0, i - 1]) { // Update dp[0][i + 1] dp[0, i + 1] = true; } } // Iterate over the characters // of both the strings for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern[j] == '.') { // Update dp[i + 1][j + 1] dp[i + 1, j + 1] = dp[i, j]; } // If current character in // both the strings are equal if (pattern[j] == text[i]) { // Update dp[i + 1][j + 1] dp[i + 1, j + 1] = dp[i, j]; } // If current character // in the pattern is '*' if (pattern[j] == '*') { if (pattern[j - 1] != text[i] && pattern[j - 1] != '.') { // Update dp[i + 1][j + 1] dp[i + 1, j + 1] = dp[i + 1, j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1, j + 1] = (dp[i + 1, j] || dp[i, j + 1] || dp[i + 1, j - 1]); } } } } // Return dp[M][N] return dp[N, M];} // Driver Codepublic static void Main(){ string text = "geeksforgeeks"; string pattern = "ge*ksforgeeks"; if (isMatch(text, pattern)) { Console.WriteLine("Yes"); } else { Console.WriteLine("No"); }}} // This code is contributed by ukasp
<script> // JavaScript program for the above approach // Function to check if the pattern // consisting of '*', '.' and lowercase // characters matches the text or not function isMatch(text, pattern) { // Base Case if (text == null || pattern == null) { return false; } // Stores length of text let N = text.length; // Stores length of pattern let M = pattern.length; // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not let dp = new Array(N + 1); for (let i = 0; i <= N; i++) { dp[i] = new Array(M + 1); for (let j = 0; j <= M; j++) { dp[i][j] = false; } } // Base Case dp[0][0] = true; // Iterate over the characters // of the string pattern for (let i = 0; i < M; i++) { if (pattern[i] == '*' && dp[0][i - 1]) { // Update dp[0][i + 1] dp[0][i + 1] = true; } } // Iterate over the characters // of both the strings for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern[j] == '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character in // both the strings are equal if (pattern[j] == text[i]) { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character // in the pattern is '*' if (pattern[j] == '*') { if (pattern[j - 1] != text[i] && pattern[j - 1] != '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } // Return dp[M][N] return dp[N][M]; } let text = "geeksforgeeks"; let pattern = "ge*ksforgeeks"; if (isMatch(text, pattern)) { document.write("Yes"); } else { document.write("No"); } </script>
Yes
Time Complexity: O(M * N)Auxiliary Space: O(M * N)
mohit kumar 29
ukasp
ankthon
divyeshrabadiya07
regular-expression
Technical Scripter 2020
Dynamic Programming
Pattern Searching
Recursion
Strings
Technical Scripter
Strings
Dynamic Programming
Recursion
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Optimal Substructure Property in Dynamic Programming | DP-2
Min Cost Path | DP-6
Count All Palindrome Sub-Strings in a String | Set 1
Maximum sum such that no two elements are adjacent
Optimal Strategy for a Game | DP-31
KMP Algorithm for Pattern Searching
Rabin-Karp Algorithm for Pattern Searching
Naive algorithm for Pattern Searching
Check if a string is substring of another
Boyer Moore Algorithm for Pattern Searching
|
[
{
"code": null,
"e": 24696,
"s": 24668,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 24886,
"s": 24696,
"text": "Given two strings text and pattern of length M and N respectively, the task is to check if the pattern matches the text or not. If found to be true, then print “Yes”. Otherwise, print “No”."
},
{
"code": null,
"e": 24939,
"s": 24886,
"text": "Note: pattern can include the characters ‘*’ and ‘•’"
},
{
"code": null,
"e": 25024,
"s": 24939,
"text": "‘*’ matches zero or more occurrences of character right before the current character"
},
{
"code": null,
"e": 25058,
"s": 25024,
"text": "‘•’ matches any signal character."
},
{
"code": null,
"e": 25068,
"s": 25058,
"text": "Examples:"
},
{
"code": null,
"e": 25254,
"s": 25068,
"text": "Input: pattern = “ge*ksforgeeks”, text = “geeksforgeeks” Output: Yes Explanation: Replacing * with ‘e’, modifies pattern equal to “geeksforgeeks”. Therefore, the required output is Yes."
},
{
"code": null,
"e": 25368,
"s": 25254,
"text": "Input: pattern = “ab*d”, text = “abcds”Output: No Explanation: The given pattern cannot be matched with the text."
},
{
"code": null,
"e": 25820,
"s": 25368,
"text": "Naive Approach: The simplest approach to solve this problem is to iterate over the characters of the both the strings using recursion. If current character is ‘.’, replace current character to any character and recur for the remaining pattern and text string. Otherwise, if the current character is ‘*’, recur for the remaining text and check if it matches the rest of the pattern or not. If found to be true, then print “Yes”. Otherwise, print “No”. "
},
{
"code": null,
"e": 25908,
"s": 25820,
"text": "Time Complexity: O((M + N) * 2(M + N / 2)) Auxiliary Space: O((M + N) * 2(M + N / 2))"
},
{
"code": null,
"e": 26031,
"s": 25908,
"text": "Efficient Approach: The above approach can be optimized using Dynamic Programming. Following are the recurrence relation: "
},
{
"code": null,
"e": 26205,
"s": 26031,
"text": "Initialize a 2D array, dp[M + 1][N + 1], where dp[i][j] check if the substring { text[0], ..., text[i] } is matches with the substring { pattern[0], ... pattern[j] } or not."
},
{
"code": null,
"e": 26736,
"s": 26205,
"text": "Iterate over the characters of the both the strings and fill the dp[][] array based on the following recurrence relation: If text[i] and pattern[j] are the same then fill dp[i + 1][j + 1] = dp[i][j].If pattern[j] is ‘.’ then fill dp[i + 1][j + 1] = dp[i][j].If pattern[j] is ‘*’ then check the following conditions: If text[i] is not equal to pattern[j – 1] and pattern[j – 1] is not equal to ‘.’, then fill dp[i + 1][j + 1] = dp[i + 1][j – 1].Otherwise, fill dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j – 1])."
},
{
"code": null,
"e": 26814,
"s": 26736,
"text": "If text[i] and pattern[j] are the same then fill dp[i + 1][j + 1] = dp[i][j]."
},
{
"code": null,
"e": 26874,
"s": 26814,
"text": "If pattern[j] is ‘.’ then fill dp[i + 1][j + 1] = dp[i][j]."
},
{
"code": null,
"e": 27147,
"s": 26874,
"text": "If pattern[j] is ‘*’ then check the following conditions: If text[i] is not equal to pattern[j – 1] and pattern[j – 1] is not equal to ‘.’, then fill dp[i + 1][j + 1] = dp[i + 1][j – 1].Otherwise, fill dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j – 1])."
},
{
"code": null,
"e": 27276,
"s": 27147,
"text": "If text[i] is not equal to pattern[j – 1] and pattern[j – 1] is not equal to ‘.’, then fill dp[i + 1][j + 1] = dp[i + 1][j – 1]."
},
{
"code": null,
"e": 27363,
"s": 27276,
"text": "Otherwise, fill dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j – 1])."
},
{
"code": null,
"e": 27401,
"s": 27363,
"text": "Finally, print the value of dp[M][N]."
},
{
"code": null,
"e": 27452,
"s": 27401,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27456,
"s": 27452,
"text": "C++"
},
{
"code": null,
"e": 27461,
"s": 27456,
"text": "Java"
},
{
"code": null,
"e": 27469,
"s": 27461,
"text": "Python3"
},
{
"code": null,
"e": 27472,
"s": 27469,
"text": "C#"
},
{
"code": null,
"e": 27483,
"s": 27472,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if the pattern// consisting of '*', '.' and lowercase// characters matches the text or notint isMatch(string text, string pattern){ // Base Case if (text == \"\" or pattern == \"\") return false; // Stores length of text int N = text.size(); // Stores length of pattern int M = pattern.size(); // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not vector<vector<bool>> dp(N + 1, vector<bool>(M + 1, false)); // Base Case dp[0][0] = true; // Iterate over the characters // of the string pattern for (int i = 0; i < M; i++) { if (pattern[i] == '*' && dp[0][i - 1]) { // Update dp[0][i + 1] dp[0][i + 1] = true; } } // Iterate over the characters // of both the strings for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern[j] == '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character in // both the strings are equal if (pattern[j] == text[i]) { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character // in the pattern is '*' if (pattern[j] == '*') { if (pattern[j - 1] != text[i] && pattern[j - 1] != '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] or dp[i][j + 1] or dp[i + 1][j - 1]); } } } } // Return dp[M][N] return dp[N][M];} // Driver Codeint main(){ string text = \"geeksforgeeks\"; string pattern = \"ge*ksforgeeks\"; if (isMatch(text, pattern)) cout<<\"Yes\"; else cout<<\"No\";} // This code is contributed by mohiy kumar 29.",
"e": 29479,
"s": 27483,
"text": null
},
{
"code": "// Java program for the above approach import java.io.*; class GFG { // Function to check if the pattern // consisting of '*', '.' and lowercase // characters matches the text or not static boolean isMatch(String text, String pattern) { // Base Case if (text == null || pattern == null) { return false; } // Stores length of text int N = text.length(); // Stores length of pattern int M = pattern.length(); // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not boolean[][] dp = new boolean[N + 1][M + 1]; // Base Case dp[0][0] = true; // Iterate over the characters // of the string pattern for (int i = 0; i < M; i++) { if (pattern.charAt(i) == '*' && dp[0][i - 1]) { // Update dp[0][i + 1] dp[0][i + 1] = true; } } // Iterate over the characters // of both the strings for (int i = 0; i < N; i++) { for (int j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern.charAt(j) == '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character in // both the strings are equal if (pattern.charAt(j) == text.charAt(i)) { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character // in the pattern is '*' if (pattern.charAt(j) == '*') { if (pattern.charAt(j - 1) != text.charAt(i) && pattern.charAt(j - 1) != '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } // Return dp[M][N] return dp[N][M]; } // Driver Code public static void main(String[] args) { String text = \"geeksforgeeks\"; String pattern = \"ge*ksforgeeks\"; if (isMatch(text, pattern)) { System.out.println(\"Yes\"); } else { System.out.println(\"No\"); } }}",
"e": 32186,
"s": 29479,
"text": null
},
{
"code": "# Python3 program for the above approachimport numpy as np # Function to check if the pattern# consisting of '*', '.' and lowercase# characters matches the text or notdef isMatch(text, pattern): # Base Case if (text == \"\" or pattern == \"\"): return False # Stores length of text N = len(text) # Stores length of pattern M = len(pattern) # dp[i][j]: Check if { text[0], .. text[i] } # matches {pattern[0], ... pattern[j]} or not dp = np.zeros((N + 1, M + 1)) # Base Case dp[0][0] = True # Iterate over the characters # of the string pattern for i in range(M): if (pattern[i] == '*' and dp[0][i - 1]): # Update dp[0][i + 1] dp[0][i + 1] = True # Iterate over the characters # of both the strings for i in range(N): for j in range(M): # If current character # in the pattern is '.' if (pattern[j] == '.'): # Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j] # If current character in # both the strings are equal if (pattern[j] == text[i]): # Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j] # If current character # in the pattern is '*' if (pattern[j] == '*'): if (pattern[j - 1] != text[i] and pattern[j - 1] != '.'): # Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1] else: # Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] or dp[i][j + 1] or dp[i + 1][j - 1]) # Return dp[M][N] return dp[N][M] # Driver Codeif __name__ == \"__main__\" : text = \"geeksforgeeks\" pattern = \"ge*ksforgeeks\" if (isMatch(text, pattern)): print(\"Yes\") else: print(\"No\") # This code is contributed by AnkThon",
"e": 33963,
"s": 32186,
"text": null
},
{
"code": "// C# program for the above approachusing System; class GFG{ // Function to check if the pattern// consisting of '*', '.' and lowercase// characters matches the text or notstatic bool isMatch(string text, string pattern){ // Base Case if (text == null || pattern == null) { return false; } // Stores length of text int N = text.Length; // Stores length of pattern int M = pattern.Length; // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not bool[,] dp = new bool[N + 1, M + 1]; // Base Case dp[0, 0] = true; // Iterate over the characters // of the string pattern for(int i = 0; i < M; i++) { if (pattern[i] == '*' && dp[0, i - 1]) { // Update dp[0][i + 1] dp[0, i + 1] = true; } } // Iterate over the characters // of both the strings for(int i = 0; i < N; i++) { for(int j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern[j] == '.') { // Update dp[i + 1][j + 1] dp[i + 1, j + 1] = dp[i, j]; } // If current character in // both the strings are equal if (pattern[j] == text[i]) { // Update dp[i + 1][j + 1] dp[i + 1, j + 1] = dp[i, j]; } // If current character // in the pattern is '*' if (pattern[j] == '*') { if (pattern[j - 1] != text[i] && pattern[j - 1] != '.') { // Update dp[i + 1][j + 1] dp[i + 1, j + 1] = dp[i + 1, j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1, j + 1] = (dp[i + 1, j] || dp[i, j + 1] || dp[i + 1, j - 1]); } } } } // Return dp[M][N] return dp[N, M];} // Driver Codepublic static void Main(){ string text = \"geeksforgeeks\"; string pattern = \"ge*ksforgeeks\"; if (isMatch(text, pattern)) { Console.WriteLine(\"Yes\"); } else { Console.WriteLine(\"No\"); }}} // This code is contributed by ukasp",
"e": 36444,
"s": 33963,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to check if the pattern // consisting of '*', '.' and lowercase // characters matches the text or not function isMatch(text, pattern) { // Base Case if (text == null || pattern == null) { return false; } // Stores length of text let N = text.length; // Stores length of pattern let M = pattern.length; // dp[i][j]: Check if { text[0], .. text[i] } // matches {pattern[0], ... pattern[j]} or not let dp = new Array(N + 1); for (let i = 0; i <= N; i++) { dp[i] = new Array(M + 1); for (let j = 0; j <= M; j++) { dp[i][j] = false; } } // Base Case dp[0][0] = true; // Iterate over the characters // of the string pattern for (let i = 0; i < M; i++) { if (pattern[i] == '*' && dp[0][i - 1]) { // Update dp[0][i + 1] dp[0][i + 1] = true; } } // Iterate over the characters // of both the strings for (let i = 0; i < N; i++) { for (let j = 0; j < M; j++) { // If current character // in the pattern is '.' if (pattern[j] == '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character in // both the strings are equal if (pattern[j] == text[i]) { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i][j]; } // If current character // in the pattern is '*' if (pattern[j] == '*') { if (pattern[j - 1] != text[i] && pattern[j - 1] != '.') { // Update dp[i + 1][j + 1] dp[i + 1][j + 1] = dp[i + 1][j - 1]; } else { // Update dp[i+1][j+1] dp[i + 1][j + 1] = (dp[i + 1][j] || dp[i][j + 1] || dp[i + 1][j - 1]); } } } } // Return dp[M][N] return dp[N][M]; } let text = \"geeksforgeeks\"; let pattern = \"ge*ksforgeeks\"; if (isMatch(text, pattern)) { document.write(\"Yes\"); } else { document.write(\"No\"); } </script>",
"e": 39110,
"s": 36444,
"text": null
},
{
"code": null,
"e": 39114,
"s": 39110,
"text": "Yes"
},
{
"code": null,
"e": 39167,
"s": 39116,
"text": "Time Complexity: O(M * N)Auxiliary Space: O(M * N)"
},
{
"code": null,
"e": 39182,
"s": 39167,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 39188,
"s": 39182,
"text": "ukasp"
},
{
"code": null,
"e": 39196,
"s": 39188,
"text": "ankthon"
},
{
"code": null,
"e": 39214,
"s": 39196,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 39233,
"s": 39214,
"text": "regular-expression"
},
{
"code": null,
"e": 39257,
"s": 39233,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 39277,
"s": 39257,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39295,
"s": 39277,
"text": "Pattern Searching"
},
{
"code": null,
"e": 39305,
"s": 39295,
"text": "Recursion"
},
{
"code": null,
"e": 39313,
"s": 39305,
"text": "Strings"
},
{
"code": null,
"e": 39332,
"s": 39313,
"text": "Technical Scripter"
},
{
"code": null,
"e": 39340,
"s": 39332,
"text": "Strings"
},
{
"code": null,
"e": 39360,
"s": 39340,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 39370,
"s": 39360,
"text": "Recursion"
},
{
"code": null,
"e": 39388,
"s": 39370,
"text": "Pattern Searching"
},
{
"code": null,
"e": 39486,
"s": 39388,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 39546,
"s": 39486,
"text": "Optimal Substructure Property in Dynamic Programming | DP-2"
},
{
"code": null,
"e": 39567,
"s": 39546,
"text": "Min Cost Path | DP-6"
},
{
"code": null,
"e": 39620,
"s": 39567,
"text": "Count All Palindrome Sub-Strings in a String | Set 1"
},
{
"code": null,
"e": 39671,
"s": 39620,
"text": "Maximum sum such that no two elements are adjacent"
},
{
"code": null,
"e": 39707,
"s": 39671,
"text": "Optimal Strategy for a Game | DP-31"
},
{
"code": null,
"e": 39743,
"s": 39707,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 39786,
"s": 39743,
"text": "Rabin-Karp Algorithm for Pattern Searching"
},
{
"code": null,
"e": 39824,
"s": 39786,
"text": "Naive algorithm for Pattern Searching"
},
{
"code": null,
"e": 39866,
"s": 39824,
"text": "Check if a string is substring of another"
}
] |
Flutter - Positioned Widget - GeeksforGeeks
|
10 Aug, 2021
Positioned is a widget that comes built-in with flutter SDK. Postioned does exactly what it sounds like, which is it arbitrarily positioned widgets on top of each other. It is usually used to position child widgets in Stack widget or similar. It only works for Stateless and Stateful widgets.
It is responsible for controlling where a child of Stack is positioned.
const Positioned(
{Key key,
double left,
double top,
double right,
double bottom,
double width,
double height,
@required Widget child}
)
It is responsible for controlling where a child of Stack is positioned. But has additional properties for specifying the Text direction.
Positioned.directional(
{Key key,
@required TextDirection textDirection,
double start,
double top,
double end,
double bottom,
double width,
double height,
@required Widget child}
)
It creates a Positioned object with a default value set to 0.0 for left, top, right, and bottom unless a value for them is passed.
const Positioned.fill(
{Key key,
double left: 0.0,
double top: 0.0,
double right: 0.0,
double bottom: 0.0,
@required Widget child}
)
It is used to create a Positioned object with the values from the given Rect.
Positioned.fromRect(
{Key key,
Rect rect,
@required Widget child}
)
It is used to create a Positioned object with the values from the given RelativeRect.
Positioned.fromRelativeRect(
{Key key,
RelativeRect rect,
@required Widget child}
)
Properties of Positioned Widget:
bottom: This property controls the distance that the child widgets are inset from the bottom of the Stack. It takes in a double value as the object.
debugTypicalAncestorWidgetClass: This widget takes in a Type class as the object. In the case of an error, this gives information about what widget typically wraps this ParentdataWidget.
height: This property takes in a double value as the object to decide the height of its child widget.
left: This property controls the distance that the child widgets are inset from the left of the Stack. It takes in a double value as the object.
top: The top property also takes in a double value to decide the distance between the top edge of the child widget and the Stack.
width: This property takes in a double value to decide the width of the child widget.
Example:
Dart
import 'package:flutter/material.dart'; // Material design libraryvoid main() { runApp( // widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Padding( padding: EdgeInsets.only(top: 300), child: Stack( alignment: AlignmentDirectional.center, children: <Widget>[ /** Positioned WIdget **/ Positioned( top: 0.0, child: Icon(Icons.message, size: 128.0, color: Colors.greenAccent[400]), //Icon ), //Positioned /** Positioned WIdget **/ Positioned( top: 0, right: 285, child: CircleAvatar( radius: 16, backgroundColor: Colors.red, foregroundColor: Colors.white, child: Text('24'), ), //CircularAvatar ), //Positioned ], //<Widget>[] ), //Stack ), //Padding ), //Scaffold ), //MaterialApp );}
Output:
Explanation: The parent widget in this flutter app is Padding which is employing its only property padding to print an empty space of 300 px on the top of its child widget which is Stack. The alignment is set to center in the Stack widget. Stack, as it does, is taking a list of widgets as children, here it’s taking in two Positioned widgets. The first one is containing a green-colored material design message icon, which is 128 px long in width and height. The second Positioned widget is having a red-colored CircleAvatar as its child. The text n the CircleAvatar is 24 with white color. And the result of all this is message icons showing 24 notifications.
anikakapoor
android
Flutter
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter - Checkbox Widget
Flutter - BoxShadow Widget
ListView Class in Flutter
Flutter - DropDownButton Widget
Flutter - Custom Bottom Navigation Bar
Flutter Tutorial
Flutter - Checkbox Widget
Flutter - BoxShadow Widget
|
[
{
"code": null,
"e": 23906,
"s": 23878,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 24199,
"s": 23906,
"text": "Positioned is a widget that comes built-in with flutter SDK. Postioned does exactly what it sounds like, which is it arbitrarily positioned widgets on top of each other. It is usually used to position child widgets in Stack widget or similar. It only works for Stateless and Stateful widgets."
},
{
"code": null,
"e": 24271,
"s": 24199,
"text": "It is responsible for controlling where a child of Stack is positioned."
},
{
"code": null,
"e": 24408,
"s": 24271,
"text": "const Positioned(\n{Key key,\ndouble left,\ndouble top,\ndouble right,\ndouble bottom,\ndouble width,\ndouble height,\n@required Widget child}\n)"
},
{
"code": null,
"e": 24545,
"s": 24408,
"text": "It is responsible for controlling where a child of Stack is positioned. But has additional properties for specifying the Text direction."
},
{
"code": null,
"e": 24726,
"s": 24545,
"text": "Positioned.directional(\n{Key key,\n@required TextDirection textDirection,\ndouble start,\ndouble top,\ndouble end,\ndouble bottom,\ndouble width,\ndouble height,\n@required Widget child}\n)"
},
{
"code": null,
"e": 24857,
"s": 24726,
"text": "It creates a Positioned object with a default value set to 0.0 for left, top, right, and bottom unless a value for them is passed."
},
{
"code": null,
"e": 24990,
"s": 24857,
"text": "const Positioned.fill(\n{Key key,\ndouble left: 0.0,\ndouble top: 0.0,\ndouble right: 0.0,\ndouble bottom: 0.0,\n@required Widget child}\n)"
},
{
"code": null,
"e": 25068,
"s": 24990,
"text": "It is used to create a Positioned object with the values from the given Rect."
},
{
"code": null,
"e": 25136,
"s": 25068,
"text": "Positioned.fromRect(\n{Key key,\nRect rect,\n@required Widget child}\n)"
},
{
"code": null,
"e": 25222,
"s": 25136,
"text": "It is used to create a Positioned object with the values from the given RelativeRect."
},
{
"code": null,
"e": 25306,
"s": 25222,
"text": "Positioned.fromRelativeRect(\n{Key key,\nRelativeRect rect,\n@required Widget child}\n)"
},
{
"code": null,
"e": 25340,
"s": 25306,
"text": "Properties of Positioned Widget: "
},
{
"code": null,
"e": 25489,
"s": 25340,
"text": "bottom: This property controls the distance that the child widgets are inset from the bottom of the Stack. It takes in a double value as the object."
},
{
"code": null,
"e": 25676,
"s": 25489,
"text": "debugTypicalAncestorWidgetClass: This widget takes in a Type class as the object. In the case of an error, this gives information about what widget typically wraps this ParentdataWidget."
},
{
"code": null,
"e": 25778,
"s": 25676,
"text": "height: This property takes in a double value as the object to decide the height of its child widget."
},
{
"code": null,
"e": 25923,
"s": 25778,
"text": "left: This property controls the distance that the child widgets are inset from the left of the Stack. It takes in a double value as the object."
},
{
"code": null,
"e": 26053,
"s": 25923,
"text": "top: The top property also takes in a double value to decide the distance between the top edge of the child widget and the Stack."
},
{
"code": null,
"e": 26139,
"s": 26053,
"text": "width: This property takes in a double value to decide the width of the child widget."
},
{
"code": null,
"e": 26149,
"s": 26139,
"text": "Example: "
},
{
"code": null,
"e": 26154,
"s": 26149,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; // Material design libraryvoid main() { runApp( // widget tree starts here MaterialApp( home: Scaffold( appBar: AppBar( title: Text('GeeksforGeeks'), backgroundColor: Colors.greenAccent[400], centerTitle: true, ), //AppBar body: Padding( padding: EdgeInsets.only(top: 300), child: Stack( alignment: AlignmentDirectional.center, children: <Widget>[ /** Positioned WIdget **/ Positioned( top: 0.0, child: Icon(Icons.message, size: 128.0, color: Colors.greenAccent[400]), //Icon ), //Positioned /** Positioned WIdget **/ Positioned( top: 0, right: 285, child: CircleAvatar( radius: 16, backgroundColor: Colors.red, foregroundColor: Colors.white, child: Text('24'), ), //CircularAvatar ), //Positioned ], //<Widget>[] ), //Stack ), //Padding ), //Scaffold ), //MaterialApp );}",
"e": 27393,
"s": 26154,
"text": null
},
{
"code": null,
"e": 27402,
"s": 27393,
"text": "Output: "
},
{
"code": null,
"e": 28064,
"s": 27402,
"text": "Explanation: The parent widget in this flutter app is Padding which is employing its only property padding to print an empty space of 300 px on the top of its child widget which is Stack. The alignment is set to center in the Stack widget. Stack, as it does, is taking a list of widgets as children, here it’s taking in two Positioned widgets. The first one is containing a green-colored material design message icon, which is 128 px long in width and height. The second Positioned widget is having a red-colored CircleAvatar as its child. The text n the CircleAvatar is 24 with white color. And the result of all this is message icons showing 24 notifications."
},
{
"code": null,
"e": 28076,
"s": 28064,
"text": "anikakapoor"
},
{
"code": null,
"e": 28084,
"s": 28076,
"text": "android"
},
{
"code": null,
"e": 28092,
"s": 28084,
"text": "Flutter"
},
{
"code": null,
"e": 28108,
"s": 28092,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 28113,
"s": 28108,
"text": "Dart"
},
{
"code": null,
"e": 28121,
"s": 28113,
"text": "Flutter"
},
{
"code": null,
"e": 28219,
"s": 28121,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28251,
"s": 28219,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 28290,
"s": 28251,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28316,
"s": 28290,
"text": "Flutter - Checkbox Widget"
},
{
"code": null,
"e": 28343,
"s": 28316,
"text": "Flutter - BoxShadow Widget"
},
{
"code": null,
"e": 28369,
"s": 28343,
"text": "ListView Class in Flutter"
},
{
"code": null,
"e": 28401,
"s": 28369,
"text": "Flutter - DropDownButton Widget"
},
{
"code": null,
"e": 28440,
"s": 28401,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 28457,
"s": 28440,
"text": "Flutter Tutorial"
},
{
"code": null,
"e": 28483,
"s": 28457,
"text": "Flutter - Checkbox Widget"
}
] |
Spatial Autocorrelation: Neighbors Affecting Neighbors | by Mahbubul Alam | Towards Data Science
|
The purpose of this article is to introduce an important concept in geospatial analysis — “Spatial Autocorrelation” with a focus on the following things: (i) key concepts of autocorrelation; (ii) industry applications and (iii) an implementation in R
“Everything is related to everything else. But near things are more related than distant things”. Waldo Tobler’s (1969) First Law of Geography
To understand Tobler’s Law above, let’s do a thought experiment.
Let’s randomly pick a house from a listing website such as Zillow and let’s say the listing price of the house is $400K. Next, say, the house next to it is also listed for sale. Now, if you are to predict the price of the second house and given two options, $450K and $1.2M, which one would you pick?
If you picked $450K then you already sub-consciously know what a spatial autocorrelation is. It is indeed a correlation between two neighbors in some common features (e.g. house price). “Auto” means self, “correlation” means association. So in a more formal way of saying — autocorrelation is a measure of similarity between nearby observations that describes the degree to which observations of a variable (e.g. population density) are similar to each other at a given spatial scale. Or simply speaking, “the Moran’s I statistic is the correlation coefficient for the relationship between a variable (like income) and its surrounding values” (source).
Note that there is a similar concept called temporal autocorrelation, where observations (e.g. height, weight etc.) in one time point is correlated to observation in the previous time point. Such temporal autocorrelation is a useful concept in time series forecasting.
We can always have a hunch about spatial autocorrelation of some features just by looking on the map. However, there is a formal way to measure it quantitatively, and Moran’s I is one such statistic used for this purpose. It takes values between -1 and +1 (like normal correlation coefficient, r, would) while providing an associated p-value as a test for significance (discussed below). A positive Moran’s I indicates that similar observations are closer to each other, whereas negative values imply dissimilar values are clustered. Values around 0 would indicate that there is no autocorrelation, and instead, observed values are randomly distributed.
Once Moran’s I is measured for a particular dataset, how can you know if it is significant or not under the null hypothesis that observations are randomly distributed?
One way to measure the significance is to perform a Monte Carlo test. It is done in three steps: (i) first, observations (e.g. house prices) are randomly distributed in different spatial units (e.g. county polygons, raster cells etc), (ii) then, a Moran’s I is calculated for this random dataset, (iii) and finally, the simulated Moran’s I is compared to the observed Moran’s I. This 3-step process is repeated many many times. After running all the simulations the probability p is calculated as follows:
(# of simulated Moran’s I greater than observed Moran’s I +1)/(# of simulations ran + 1)
For example, say,
number of simulations = 200
number of simulated Moran's I that are higher than observed value = 2
then according to the equation above the probability of null hypothesis being true:
p = (1+1)/(200+1) = 0.009
where p<0.01, therefore, the null hypothesis that the observations (e.g. population, house prices) are randomly distributed in space can be rejected. In other words, the observed autocorrelation of house prices is pretty significant.
Autocorrelation is a key concept in spatial analysis that has wide ranging industry applications. Some of them are as follows:
A measure of spatial inequality/diversity: whether income, population, race etc. are clustered or uniformly distributed in certain areas — can be computed using Moran’s I.
It’s been used to identify contamination hotspots of rare earth elements in urban soils of London
Has been used to demonstrate different distance-decay functions of variables of interest (e.g. how far away house prices drop as a function of distance from urban center?).
Autocorrelation is frequently used in many other machine learning algorithms (e.g. spatial regression, classification, cluster analysis) as well as in spatial data visualization as part of EDA (e.g. heatmap, hotspot analysis)
Step 1: Install dependencies
library(sf)library(spdep)library(tigris)library(acs)library(tidyverse)library(tmap)
Step 2: Get the data
The data I am using for this demo is a median household income dataset at the county/census tract level, retrieved from American Community Survey. To access the data users have to put a request for API key. In my case, it was processed fairly quickly once requested.
api="MY API KEY"api.key.install(key=api)acs.tables.install()set.seed(1234) # because we are randomizing part of the process# Access the shapefiles <- get_acs(geography = "tract", variables = "B19013_001", state = c("VA"), geometry = TRUE)# remove NA values is anys <- na.omit(s)# select column to work withs <- subset(s, select=c("estimate"))
Step 3: Exploratory data analysis
# check data skewnesshist(s$estimate, main=NULL)# check for outliersboxplot(s$estimate, horizontal = TRUE)# plot variabletm_shape(s) + tm_fill(col="estimate", style="quantile", n=5, palette="Greens") +tm_legend(outside=TRUE)
Step 4: Modeling
# define neighbornb <- poly2nb(s, queen=TRUE) # here nb list all ID numbers of neighbors;# assign weights to neighborslw <- nb2listw(nb, style="W", zero.policy=TRUE) # equal weights# compute neighbor averageinc.lag <- lag.listw(lw, s$estimate)# plot polygons vs lagsplot(inc.lag ~ s$estimate, pch=16, asp=1)M1 <- lm(inc.lag ~ s$estimate)abline(M1, col="blue")# access Moran's coeffcoef(M1)[2]# calculating Moran coeff with one lineI <- moran(s$estimate, lw, length(nb), Szero(lw))[1]
Step 5: Test of hypothesis
# hypothesis test with moran.test functionmoran.test(s$estimate,lw, alternative="greater")# using Monte-Carlo simulationMC<- moran.mc(s$estimate, lw, nsim=999, alternative="greater")# View results (including p-value)MC# plot Null distributionplot(MC)
Understanding spatial autocorrelation is an important concept in spatial data analytics — not only for understanding spatial pattern and variation of data, but also for use in business decisions. It is also a key statistic providing inputs to advanced spatially explicit statistical and machine learning algorithms. In terms of implementation, once you have the data it’s fairly easy to implement. I implemented in R environment but there are some Python libraries (e.g. geopandas) too, however, in my experience R has been more user friendly because of easy access to county/census tract scale datasets using existing packages.
|
[
{
"code": null,
"e": 422,
"s": 171,
"text": "The purpose of this article is to introduce an important concept in geospatial analysis — “Spatial Autocorrelation” with a focus on the following things: (i) key concepts of autocorrelation; (ii) industry applications and (iii) an implementation in R"
},
{
"code": null,
"e": 565,
"s": 422,
"text": "“Everything is related to everything else. But near things are more related than distant things”. Waldo Tobler’s (1969) First Law of Geography"
},
{
"code": null,
"e": 630,
"s": 565,
"text": "To understand Tobler’s Law above, let’s do a thought experiment."
},
{
"code": null,
"e": 931,
"s": 630,
"text": "Let’s randomly pick a house from a listing website such as Zillow and let’s say the listing price of the house is $400K. Next, say, the house next to it is also listed for sale. Now, if you are to predict the price of the second house and given two options, $450K and $1.2M, which one would you pick?"
},
{
"code": null,
"e": 1584,
"s": 931,
"text": "If you picked $450K then you already sub-consciously know what a spatial autocorrelation is. It is indeed a correlation between two neighbors in some common features (e.g. house price). “Auto” means self, “correlation” means association. So in a more formal way of saying — autocorrelation is a measure of similarity between nearby observations that describes the degree to which observations of a variable (e.g. population density) are similar to each other at a given spatial scale. Or simply speaking, “the Moran’s I statistic is the correlation coefficient for the relationship between a variable (like income) and its surrounding values” (source)."
},
{
"code": null,
"e": 1853,
"s": 1584,
"text": "Note that there is a similar concept called temporal autocorrelation, where observations (e.g. height, weight etc.) in one time point is correlated to observation in the previous time point. Such temporal autocorrelation is a useful concept in time series forecasting."
},
{
"code": null,
"e": 2507,
"s": 1853,
"text": "We can always have a hunch about spatial autocorrelation of some features just by looking on the map. However, there is a formal way to measure it quantitatively, and Moran’s I is one such statistic used for this purpose. It takes values between -1 and +1 (like normal correlation coefficient, r, would) while providing an associated p-value as a test for significance (discussed below). A positive Moran’s I indicates that similar observations are closer to each other, whereas negative values imply dissimilar values are clustered. Values around 0 would indicate that there is no autocorrelation, and instead, observed values are randomly distributed."
},
{
"code": null,
"e": 2675,
"s": 2507,
"text": "Once Moran’s I is measured for a particular dataset, how can you know if it is significant or not under the null hypothesis that observations are randomly distributed?"
},
{
"code": null,
"e": 3181,
"s": 2675,
"text": "One way to measure the significance is to perform a Monte Carlo test. It is done in three steps: (i) first, observations (e.g. house prices) are randomly distributed in different spatial units (e.g. county polygons, raster cells etc), (ii) then, a Moran’s I is calculated for this random dataset, (iii) and finally, the simulated Moran’s I is compared to the observed Moran’s I. This 3-step process is repeated many many times. After running all the simulations the probability p is calculated as follows:"
},
{
"code": null,
"e": 3270,
"s": 3181,
"text": "(# of simulated Moran’s I greater than observed Moran’s I +1)/(# of simulations ran + 1)"
},
{
"code": null,
"e": 3288,
"s": 3270,
"text": "For example, say,"
},
{
"code": null,
"e": 3316,
"s": 3288,
"text": "number of simulations = 200"
},
{
"code": null,
"e": 3386,
"s": 3316,
"text": "number of simulated Moran's I that are higher than observed value = 2"
},
{
"code": null,
"e": 3470,
"s": 3386,
"text": "then according to the equation above the probability of null hypothesis being true:"
},
{
"code": null,
"e": 3496,
"s": 3470,
"text": "p = (1+1)/(200+1) = 0.009"
},
{
"code": null,
"e": 3730,
"s": 3496,
"text": "where p<0.01, therefore, the null hypothesis that the observations (e.g. population, house prices) are randomly distributed in space can be rejected. In other words, the observed autocorrelation of house prices is pretty significant."
},
{
"code": null,
"e": 3857,
"s": 3730,
"text": "Autocorrelation is a key concept in spatial analysis that has wide ranging industry applications. Some of them are as follows:"
},
{
"code": null,
"e": 4029,
"s": 3857,
"text": "A measure of spatial inequality/diversity: whether income, population, race etc. are clustered or uniformly distributed in certain areas — can be computed using Moran’s I."
},
{
"code": null,
"e": 4127,
"s": 4029,
"text": "It’s been used to identify contamination hotspots of rare earth elements in urban soils of London"
},
{
"code": null,
"e": 4300,
"s": 4127,
"text": "Has been used to demonstrate different distance-decay functions of variables of interest (e.g. how far away house prices drop as a function of distance from urban center?)."
},
{
"code": null,
"e": 4526,
"s": 4300,
"text": "Autocorrelation is frequently used in many other machine learning algorithms (e.g. spatial regression, classification, cluster analysis) as well as in spatial data visualization as part of EDA (e.g. heatmap, hotspot analysis)"
},
{
"code": null,
"e": 4555,
"s": 4526,
"text": "Step 1: Install dependencies"
},
{
"code": null,
"e": 4639,
"s": 4555,
"text": "library(sf)library(spdep)library(tigris)library(acs)library(tidyverse)library(tmap)"
},
{
"code": null,
"e": 4660,
"s": 4639,
"text": "Step 2: Get the data"
},
{
"code": null,
"e": 4927,
"s": 4660,
"text": "The data I am using for this demo is a median household income dataset at the county/census tract level, retrieved from American Community Survey. To access the data users have to put a request for API key. In my case, it was processed fairly quickly once requested."
},
{
"code": null,
"e": 5286,
"s": 4927,
"text": "api=\"MY API KEY\"api.key.install(key=api)acs.tables.install()set.seed(1234) # because we are randomizing part of the process# Access the shapefiles <- get_acs(geography = \"tract\", variables = \"B19013_001\", state = c(\"VA\"), geometry = TRUE)# remove NA values is anys <- na.omit(s)# select column to work withs <- subset(s, select=c(\"estimate\"))"
},
{
"code": null,
"e": 5320,
"s": 5286,
"text": "Step 3: Exploratory data analysis"
},
{
"code": null,
"e": 5545,
"s": 5320,
"text": "# check data skewnesshist(s$estimate, main=NULL)# check for outliersboxplot(s$estimate, horizontal = TRUE)# plot variabletm_shape(s) + tm_fill(col=\"estimate\", style=\"quantile\", n=5, palette=\"Greens\") +tm_legend(outside=TRUE)"
},
{
"code": null,
"e": 5562,
"s": 5545,
"text": "Step 4: Modeling"
},
{
"code": null,
"e": 6046,
"s": 5562,
"text": "# define neighbornb <- poly2nb(s, queen=TRUE) # here nb list all ID numbers of neighbors;# assign weights to neighborslw <- nb2listw(nb, style=\"W\", zero.policy=TRUE) # equal weights# compute neighbor averageinc.lag <- lag.listw(lw, s$estimate)# plot polygons vs lagsplot(inc.lag ~ s$estimate, pch=16, asp=1)M1 <- lm(inc.lag ~ s$estimate)abline(M1, col=\"blue\")# access Moran's coeffcoef(M1)[2]# calculating Moran coeff with one lineI <- moran(s$estimate, lw, length(nb), Szero(lw))[1]"
},
{
"code": null,
"e": 6073,
"s": 6046,
"text": "Step 5: Test of hypothesis"
},
{
"code": null,
"e": 6324,
"s": 6073,
"text": "# hypothesis test with moran.test functionmoran.test(s$estimate,lw, alternative=\"greater\")# using Monte-Carlo simulationMC<- moran.mc(s$estimate, lw, nsim=999, alternative=\"greater\")# View results (including p-value)MC# plot Null distributionplot(MC)"
}
] |
A Complete Logistic Regression Algorithm From Scratch in Python: Step by Step | by Rashida Nasrin Sucky | Towards Data Science
|
Logistic regression is a popular method since the last century. It establishes the relationship between a categorical variable and one or more independent variables. This relationship is used in machine learning to predict the outcome of a categorical variable. It is widely used in many different fields such as the medical field, trading and business, technology, and many more.
This article explains the process of developing a binary classification algorithm and implements it on Kaggle’s Heart disease dataset.
In this article, we will use a dataset from Kaggle that contains the health data of a population. It has a column at the end that contains if a person has heart disease or not. Our goal is to see if we can predict if a person has heart disease or not using the other columns in the table.
Here I will load the dataset. I will use pandas for that:
import pandas as pdimport numpy as npdf = pd.read_csv('Heart.csv')df.head()
The dataset looks like this:
Look at the last column of the dataset. It is ‘AHD’. This denotes heart disease. We will use the rest of the columns to predict heart disease. So in the future, if we have all the data, we will be able to predict if a person has heart disease without a medical checkup.
Our output will be 0 or 1. If a person has heart disease our algorithm will return 1 and if a person does not have heart disease the algorithm should return 0.
Remember the linear regression formula. That very basic formula of a straight line:
Y= A+BX
Where A is the intercept and B is the slope. If we avoid the ‘intercept’ A in this equation, the formula becomes:
Y = BX
Traditionally, in machine learning, it is pressed as,
Here, ‘h’ is the hypothesis or the predicted value and X is the predictor or input variable. Theta is initialized randomly in the beginning and updated it later.
For the logistic regression, we need to transform this simple hypothesis using a sigmoid function that returns a value from 0 to 1. A sigmoid function can be called a logistic function as well. Logistic regression uses the sigmoid function to predict the output. Here is the sigmoid activation function:
z is the input features multiplied by a randomly initialized term theta.
Here, X is the input feature and theta is the randomly initialized values that will be updated in this algorithm.
The reason we need to use a logistic function is, the curve of a logistic function looks like this:
As you can see from the picture above, it returns a value between 0 to 1. So, it is very helpful for classification. As we will work on a binary classification today,
we will return a zero if the logistic function returns a value that is less than 0.5 and we will return 1 if the logistic function returns a value greater than or equal to 0.5
Cost Function
The cost function gives you the measure of how far the predicted output(calculated hypothesis ‘h’) is from the original output(‘AHD’ column from the dataset).
Before diving into the cost function of logistic regression, I want to remind you of the cost function of a linear regression which was much more straightforward. The cost of linear regression is:
Where,
y is the original label (‘AHD’ column of the dataset)
The average cost function is:
Where,
m is the number of training data
The equation above takes the difference between the predicted label ‘h’ and the original label ‘y’ first. The formula includes squared to avoid any negative values and uses 1/2 to optimize that squared.
This simple and straightforward equation works for linear regression because linear regression uses a simple linear equation: (Y= A+BX).
But logistic regression uses a sigmoid function which is not linear.
We can not use that simple cost function here because it will not converge to global minima. To address this issue, we will use a log to regularize the cost function so that it converges to a global minimum.
Here is the cost function we will use to guarantee a global minimum:
if y = 1,
Cost(h, y) = -log(h)
if y = 0,
Cost(h, y) = -log(1 — h)
Simplified and combined cost function:
Here is the cost function expression:
Why this equation? Look, we can have only two cases y = 0 or 1. And in the cost function equation above, we have two terms:
y*logh and(1-y)*log(1-h).
y*logh and
(1-y)*log(1-h).
If y = 0, the first term becomes zero, and the second term becomes log(1-h). In the equation, we already put a negative sign in the beginning.
If y = 1, the second term becomes zero and only ylogh term remains, with the negative sign in the beginning.
I hope it makes sense now!
Gradient Descent
We need to update our randomly initialized theta values. Gradient descent equation does just that. If we take a partial differential of the cost function with respect to theta:
Using this expression above the gradient descent formula becomes:
Here, alpha is the learning rate.
Using this equation theta values will be updated in each iteration. It will be more clear to you when you will implement thin in python.
This is the time to use all the equations above to develop the algorithm
Step 1: Develop the hypothesis.
The hypothesis is simply the implementation of the sigmoid function.
def hypothesis(X, theta): z = np.dot(theta, X.T) return 1/(1+np.exp(-(z))) - 0.0000001
I deducted 0.0000001 from the output here because of this expression in the cost function:
If the outcome of the hypothesis expression comes out to be 1, then this expression will turn out to be the log of zero. To mitigate that, I used this very small number at the end.
Step 2: Determine the cost function.
def cost(X, y, theta): y1 = hypothesis(X, theta) return -(1/len(X)) * np.sum(y*np.log(y1) + (1-y)*np.log(1-y1))
This is just a straightforward implementation of the cost function equation above.
Step 3: Update the theta values.
Theta values need to keep updating until the cost function reaches its minimum. We should get our final theta values and the cost of each iteration as output.
def gradient_descent(X, y, theta, alpha, epochs): m =len(X) J = [cost(X, y, theta)] for i in range(0, epochs): h = hypothesis(X, theta) for i in range(0, len(X.columns)): theta[i] -= (alpha/m) * np.sum((h-y)*X.iloc[:, i]) J.append(cost(X, y, theta)) return J, theta
Step 4: Calculate the final prediction and accuracy
Use the theta values that come out of the ‘gradient_descent’ function and calculate the final prediction using the sigmoid function. Then, calculate the accuracy.
def predict(X, y, theta, alpha, epochs): J, th = gradient_descent(X, y, theta, alpha, epochs) h = hypothesis(X, theta) for i in range(len(h)): h[i]=1 if h[i]>=0.5 else 0 y = list(y) acc = np.sum([y[i] == h[i] for i in range(len(y))])/len(y) return J, acc
The final output is the list of costs in each epoch and the accuracy. Let’s implement this model to solve a real problem.
I already showed the dataset in the beginning. But for your convenience I am including it again here:
Notice, there are a few categorical features in the dataset. We need to convert them to numerical data.
df["ChestPainx"]= df.ChestPain.replace({"typical": 1, "asymptomatic": 2, "nonanginal": 3, "nontypical": 4})df["Thalx"] = df.Thal.replace({"fixed": 1, "normal":2, "reversable":3})df["AHD"] = df.AHD.replace({"Yes": 1, "No":0})
Add one extra column for the bias. This should be a column of ones because any real number remains unchanged if multiplied by one.
df = pd.concat([pd.Series(1, index = df.index, name = '00'), df], axis=1)
Define the input features and output variables. The output column is the categorical column that we want to predict. The input features will be all the columns except the categorical columns that we modified earlier.
X = df.drop(columns=["Unnamed: 0", "ChestPain", "Thal"])y= df["AHD"]
Finally, initialize the theta values in a list and predict the result and calculate the accuracy. Here I am initializing the theta values like 0.5. It can be initialized as for any other value. As each feature should have a corresponding theta value, one theta value should be initialized for each feature in the X, including the bias column.
theta = [0.5]*len(X.columns)J, acc = predict(X, y, theta, 0.0001, 25000)
The final accuracy is 84.85%. I used 0.0001 as the learning rate and 25000 iterations.
I ran this algorithm a few times to determine that.
Please check my GitHub link for this project provided below.
‘predict’ function also returns the list of costs in each iteration. Cost should keep going down in each iteration in a good algorithm. Plot the cost for each iteration to visualize the trend.
%matplotlib inlineimport matplotlib.pyplot as pltplt.figure(figsize = (12, 8))plt.scatter(range(0, len(J)), J)plt.show()
Cost decreased very rapidly in the beginning and then the rate of decrease slowed down. This is the behavior of a perfect cost function!
I hope, this was helpful. If you are a beginner, it will be a bit hard to grasp all the concepts in the beginning. But I suggest please run all the code by yourself in a notebook and observe the output carefully. That will be immensely helpful. This type of logistic regression is helpful for a lot of real-world problems. I hope, you will be using this to develop some cool projects!
If please let me know in the comment section if you have a problem running any piece of code.
Here you will find the complete code:
|
[
{
"code": null,
"e": 553,
"s": 172,
"text": "Logistic regression is a popular method since the last century. It establishes the relationship between a categorical variable and one or more independent variables. This relationship is used in machine learning to predict the outcome of a categorical variable. It is widely used in many different fields such as the medical field, trading and business, technology, and many more."
},
{
"code": null,
"e": 688,
"s": 553,
"text": "This article explains the process of developing a binary classification algorithm and implements it on Kaggle’s Heart disease dataset."
},
{
"code": null,
"e": 977,
"s": 688,
"text": "In this article, we will use a dataset from Kaggle that contains the health data of a population. It has a column at the end that contains if a person has heart disease or not. Our goal is to see if we can predict if a person has heart disease or not using the other columns in the table."
},
{
"code": null,
"e": 1035,
"s": 977,
"text": "Here I will load the dataset. I will use pandas for that:"
},
{
"code": null,
"e": 1111,
"s": 1035,
"text": "import pandas as pdimport numpy as npdf = pd.read_csv('Heart.csv')df.head()"
},
{
"code": null,
"e": 1140,
"s": 1111,
"text": "The dataset looks like this:"
},
{
"code": null,
"e": 1410,
"s": 1140,
"text": "Look at the last column of the dataset. It is ‘AHD’. This denotes heart disease. We will use the rest of the columns to predict heart disease. So in the future, if we have all the data, we will be able to predict if a person has heart disease without a medical checkup."
},
{
"code": null,
"e": 1570,
"s": 1410,
"text": "Our output will be 0 or 1. If a person has heart disease our algorithm will return 1 and if a person does not have heart disease the algorithm should return 0."
},
{
"code": null,
"e": 1654,
"s": 1570,
"text": "Remember the linear regression formula. That very basic formula of a straight line:"
},
{
"code": null,
"e": 1662,
"s": 1654,
"text": "Y= A+BX"
},
{
"code": null,
"e": 1776,
"s": 1662,
"text": "Where A is the intercept and B is the slope. If we avoid the ‘intercept’ A in this equation, the formula becomes:"
},
{
"code": null,
"e": 1783,
"s": 1776,
"text": "Y = BX"
},
{
"code": null,
"e": 1837,
"s": 1783,
"text": "Traditionally, in machine learning, it is pressed as,"
},
{
"code": null,
"e": 1999,
"s": 1837,
"text": "Here, ‘h’ is the hypothesis or the predicted value and X is the predictor or input variable. Theta is initialized randomly in the beginning and updated it later."
},
{
"code": null,
"e": 2303,
"s": 1999,
"text": "For the logistic regression, we need to transform this simple hypothesis using a sigmoid function that returns a value from 0 to 1. A sigmoid function can be called a logistic function as well. Logistic regression uses the sigmoid function to predict the output. Here is the sigmoid activation function:"
},
{
"code": null,
"e": 2376,
"s": 2303,
"text": "z is the input features multiplied by a randomly initialized term theta."
},
{
"code": null,
"e": 2490,
"s": 2376,
"text": "Here, X is the input feature and theta is the randomly initialized values that will be updated in this algorithm."
},
{
"code": null,
"e": 2590,
"s": 2490,
"text": "The reason we need to use a logistic function is, the curve of a logistic function looks like this:"
},
{
"code": null,
"e": 2757,
"s": 2590,
"text": "As you can see from the picture above, it returns a value between 0 to 1. So, it is very helpful for classification. As we will work on a binary classification today,"
},
{
"code": null,
"e": 2933,
"s": 2757,
"text": "we will return a zero if the logistic function returns a value that is less than 0.5 and we will return 1 if the logistic function returns a value greater than or equal to 0.5"
},
{
"code": null,
"e": 2947,
"s": 2933,
"text": "Cost Function"
},
{
"code": null,
"e": 3106,
"s": 2947,
"text": "The cost function gives you the measure of how far the predicted output(calculated hypothesis ‘h’) is from the original output(‘AHD’ column from the dataset)."
},
{
"code": null,
"e": 3303,
"s": 3106,
"text": "Before diving into the cost function of logistic regression, I want to remind you of the cost function of a linear regression which was much more straightforward. The cost of linear regression is:"
},
{
"code": null,
"e": 3310,
"s": 3303,
"text": "Where,"
},
{
"code": null,
"e": 3364,
"s": 3310,
"text": "y is the original label (‘AHD’ column of the dataset)"
},
{
"code": null,
"e": 3394,
"s": 3364,
"text": "The average cost function is:"
},
{
"code": null,
"e": 3401,
"s": 3394,
"text": "Where,"
},
{
"code": null,
"e": 3434,
"s": 3401,
"text": "m is the number of training data"
},
{
"code": null,
"e": 3637,
"s": 3434,
"text": "The equation above takes the difference between the predicted label ‘h’ and the original label ‘y’ first. The formula includes squared to avoid any negative values and uses 1/2 to optimize that squared."
},
{
"code": null,
"e": 3774,
"s": 3637,
"text": "This simple and straightforward equation works for linear regression because linear regression uses a simple linear equation: (Y= A+BX)."
},
{
"code": null,
"e": 3843,
"s": 3774,
"text": "But logistic regression uses a sigmoid function which is not linear."
},
{
"code": null,
"e": 4051,
"s": 3843,
"text": "We can not use that simple cost function here because it will not converge to global minima. To address this issue, we will use a log to regularize the cost function so that it converges to a global minimum."
},
{
"code": null,
"e": 4120,
"s": 4051,
"text": "Here is the cost function we will use to guarantee a global minimum:"
},
{
"code": null,
"e": 4130,
"s": 4120,
"text": "if y = 1,"
},
{
"code": null,
"e": 4151,
"s": 4130,
"text": "Cost(h, y) = -log(h)"
},
{
"code": null,
"e": 4161,
"s": 4151,
"text": "if y = 0,"
},
{
"code": null,
"e": 4186,
"s": 4161,
"text": "Cost(h, y) = -log(1 — h)"
},
{
"code": null,
"e": 4225,
"s": 4186,
"text": "Simplified and combined cost function:"
},
{
"code": null,
"e": 4263,
"s": 4225,
"text": "Here is the cost function expression:"
},
{
"code": null,
"e": 4387,
"s": 4263,
"text": "Why this equation? Look, we can have only two cases y = 0 or 1. And in the cost function equation above, we have two terms:"
},
{
"code": null,
"e": 4413,
"s": 4387,
"text": "y*logh and(1-y)*log(1-h)."
},
{
"code": null,
"e": 4424,
"s": 4413,
"text": "y*logh and"
},
{
"code": null,
"e": 4440,
"s": 4424,
"text": "(1-y)*log(1-h)."
},
{
"code": null,
"e": 4583,
"s": 4440,
"text": "If y = 0, the first term becomes zero, and the second term becomes log(1-h). In the equation, we already put a negative sign in the beginning."
},
{
"code": null,
"e": 4692,
"s": 4583,
"text": "If y = 1, the second term becomes zero and only ylogh term remains, with the negative sign in the beginning."
},
{
"code": null,
"e": 4719,
"s": 4692,
"text": "I hope it makes sense now!"
},
{
"code": null,
"e": 4736,
"s": 4719,
"text": "Gradient Descent"
},
{
"code": null,
"e": 4913,
"s": 4736,
"text": "We need to update our randomly initialized theta values. Gradient descent equation does just that. If we take a partial differential of the cost function with respect to theta:"
},
{
"code": null,
"e": 4979,
"s": 4913,
"text": "Using this expression above the gradient descent formula becomes:"
},
{
"code": null,
"e": 5013,
"s": 4979,
"text": "Here, alpha is the learning rate."
},
{
"code": null,
"e": 5150,
"s": 5013,
"text": "Using this equation theta values will be updated in each iteration. It will be more clear to you when you will implement thin in python."
},
{
"code": null,
"e": 5223,
"s": 5150,
"text": "This is the time to use all the equations above to develop the algorithm"
},
{
"code": null,
"e": 5255,
"s": 5223,
"text": "Step 1: Develop the hypothesis."
},
{
"code": null,
"e": 5324,
"s": 5255,
"text": "The hypothesis is simply the implementation of the sigmoid function."
},
{
"code": null,
"e": 5417,
"s": 5324,
"text": "def hypothesis(X, theta): z = np.dot(theta, X.T) return 1/(1+np.exp(-(z))) - 0.0000001"
},
{
"code": null,
"e": 5508,
"s": 5417,
"text": "I deducted 0.0000001 from the output here because of this expression in the cost function:"
},
{
"code": null,
"e": 5689,
"s": 5508,
"text": "If the outcome of the hypothesis expression comes out to be 1, then this expression will turn out to be the log of zero. To mitigate that, I used this very small number at the end."
},
{
"code": null,
"e": 5726,
"s": 5689,
"text": "Step 2: Determine the cost function."
},
{
"code": null,
"e": 5844,
"s": 5726,
"text": "def cost(X, y, theta): y1 = hypothesis(X, theta) return -(1/len(X)) * np.sum(y*np.log(y1) + (1-y)*np.log(1-y1))"
},
{
"code": null,
"e": 5927,
"s": 5844,
"text": "This is just a straightforward implementation of the cost function equation above."
},
{
"code": null,
"e": 5960,
"s": 5927,
"text": "Step 3: Update the theta values."
},
{
"code": null,
"e": 6119,
"s": 5960,
"text": "Theta values need to keep updating until the cost function reaches its minimum. We should get our final theta values and the cost of each iteration as output."
},
{
"code": null,
"e": 6430,
"s": 6119,
"text": "def gradient_descent(X, y, theta, alpha, epochs): m =len(X) J = [cost(X, y, theta)] for i in range(0, epochs): h = hypothesis(X, theta) for i in range(0, len(X.columns)): theta[i] -= (alpha/m) * np.sum((h-y)*X.iloc[:, i]) J.append(cost(X, y, theta)) return J, theta"
},
{
"code": null,
"e": 6482,
"s": 6430,
"text": "Step 4: Calculate the final prediction and accuracy"
},
{
"code": null,
"e": 6645,
"s": 6482,
"text": "Use the theta values that come out of the ‘gradient_descent’ function and calculate the final prediction using the sigmoid function. Then, calculate the accuracy."
},
{
"code": null,
"e": 6926,
"s": 6645,
"text": "def predict(X, y, theta, alpha, epochs): J, th = gradient_descent(X, y, theta, alpha, epochs) h = hypothesis(X, theta) for i in range(len(h)): h[i]=1 if h[i]>=0.5 else 0 y = list(y) acc = np.sum([y[i] == h[i] for i in range(len(y))])/len(y) return J, acc"
},
{
"code": null,
"e": 7048,
"s": 6926,
"text": "The final output is the list of costs in each epoch and the accuracy. Let’s implement this model to solve a real problem."
},
{
"code": null,
"e": 7150,
"s": 7048,
"text": "I already showed the dataset in the beginning. But for your convenience I am including it again here:"
},
{
"code": null,
"e": 7254,
"s": 7150,
"text": "Notice, there are a few categorical features in the dataset. We need to convert them to numerical data."
},
{
"code": null,
"e": 7479,
"s": 7254,
"text": "df[\"ChestPainx\"]= df.ChestPain.replace({\"typical\": 1, \"asymptomatic\": 2, \"nonanginal\": 3, \"nontypical\": 4})df[\"Thalx\"] = df.Thal.replace({\"fixed\": 1, \"normal\":2, \"reversable\":3})df[\"AHD\"] = df.AHD.replace({\"Yes\": 1, \"No\":0})"
},
{
"code": null,
"e": 7610,
"s": 7479,
"text": "Add one extra column for the bias. This should be a column of ones because any real number remains unchanged if multiplied by one."
},
{
"code": null,
"e": 7684,
"s": 7610,
"text": "df = pd.concat([pd.Series(1, index = df.index, name = '00'), df], axis=1)"
},
{
"code": null,
"e": 7901,
"s": 7684,
"text": "Define the input features and output variables. The output column is the categorical column that we want to predict. The input features will be all the columns except the categorical columns that we modified earlier."
},
{
"code": null,
"e": 7970,
"s": 7901,
"text": "X = df.drop(columns=[\"Unnamed: 0\", \"ChestPain\", \"Thal\"])y= df[\"AHD\"]"
},
{
"code": null,
"e": 8313,
"s": 7970,
"text": "Finally, initialize the theta values in a list and predict the result and calculate the accuracy. Here I am initializing the theta values like 0.5. It can be initialized as for any other value. As each feature should have a corresponding theta value, one theta value should be initialized for each feature in the X, including the bias column."
},
{
"code": null,
"e": 8386,
"s": 8313,
"text": "theta = [0.5]*len(X.columns)J, acc = predict(X, y, theta, 0.0001, 25000)"
},
{
"code": null,
"e": 8473,
"s": 8386,
"text": "The final accuracy is 84.85%. I used 0.0001 as the learning rate and 25000 iterations."
},
{
"code": null,
"e": 8525,
"s": 8473,
"text": "I ran this algorithm a few times to determine that."
},
{
"code": null,
"e": 8586,
"s": 8525,
"text": "Please check my GitHub link for this project provided below."
},
{
"code": null,
"e": 8779,
"s": 8586,
"text": "‘predict’ function also returns the list of costs in each iteration. Cost should keep going down in each iteration in a good algorithm. Plot the cost for each iteration to visualize the trend."
},
{
"code": null,
"e": 8900,
"s": 8779,
"text": "%matplotlib inlineimport matplotlib.pyplot as pltplt.figure(figsize = (12, 8))plt.scatter(range(0, len(J)), J)plt.show()"
},
{
"code": null,
"e": 9037,
"s": 8900,
"text": "Cost decreased very rapidly in the beginning and then the rate of decrease slowed down. This is the behavior of a perfect cost function!"
},
{
"code": null,
"e": 9422,
"s": 9037,
"text": "I hope, this was helpful. If you are a beginner, it will be a bit hard to grasp all the concepts in the beginning. But I suggest please run all the code by yourself in a notebook and observe the output carefully. That will be immensely helpful. This type of logistic regression is helpful for a lot of real-world problems. I hope, you will be using this to develop some cool projects!"
},
{
"code": null,
"e": 9516,
"s": 9422,
"text": "If please let me know in the comment section if you have a problem running any piece of code."
}
] |
Yen's k-Shortest Path Algorithm in Data Structure
|
Instead of giving a single shortest path, Yen’s k-shortest path algorithm gives k shortest paths so that we can get the second shortest path and the third shortest path and so on.
Let us consider a scenario that we have to travel from place A to place B and there are multiple routes available between place A and place B, but we have to find the shortest path and neglect all the paths that are less considered in terms of its time complexity in order to reach the destination.
Let us understand with an example-
Consider the given example as the bridge which is having a peak of B. If someone wants to cross the bridge from A to C, then nobody will go to the peak to cross the bridge. So it would be a bit longer path from A to C.
There are multiple ways to get the shortest path. But we have to find the shortest path up to (k-1).
query= “””
MATCH(start: place{id:source}),*end: Place {Id:destination})
Call algo.kshortestPaths.stream(start,end,10, “distance”)
Yield nodeIDs, path costs, index
Return index.
[node in algo.getNodeByID(nodeId[1.....-1]) | node.id] aS,
Reduce (acc=0.0, cost in costs | acc+cost ) as total cost
“””
params= {“source”: Alex,Destination: “US”}
With driver.selection() as session:
Row session.run(query, params)
df = pd.DataFrame[dict(record) for record in rows])
pd.set_option(‘max_colwidth’, 100)
display(df)
|
[
{
"code": null,
"e": 1242,
"s": 1062,
"text": "Instead of giving a single shortest path, Yen’s k-shortest path algorithm gives k shortest paths so that we can get the second shortest path and the third shortest path and so on."
},
{
"code": null,
"e": 1541,
"s": 1242,
"text": "Let us consider a scenario that we have to travel from place A to place B and there are multiple routes available between place A and place B, but we have to find the shortest path and neglect all the paths that are less considered in terms of its time complexity in order to reach the destination."
},
{
"code": null,
"e": 1576,
"s": 1541,
"text": "Let us understand with an example-"
},
{
"code": null,
"e": 1795,
"s": 1576,
"text": "Consider the given example as the bridge which is having a peak of B. If someone wants to cross the bridge from A to C, then nobody will go to the peak to cross the bridge. So it would be a bit longer path from A to C."
},
{
"code": null,
"e": 1896,
"s": 1795,
"text": "There are multiple ways to get the shortest path. But we have to find the shortest path up to (k-1)."
},
{
"code": null,
"e": 2413,
"s": 1896,
"text": "query= “””\nMATCH(start: place{id:source}),*end: Place {Id:destination})\nCall algo.kshortestPaths.stream(start,end,10, “distance”)\nYield nodeIDs, path costs, index\nReturn index.\n [node in algo.getNodeByID(nodeId[1.....-1]) | node.id] aS,\n Reduce (acc=0.0, cost in costs | acc+cost ) as total cost\n“””\nparams= {“source”: Alex,Destination: “US”}\nWith driver.selection() as session:\n Row session.run(query, params)\n df = pd.DataFrame[dict(record) for record in rows])\npd.set_option(‘max_colwidth’, 100)\ndisplay(df)"
}
] |
LeafletJS - Vector Layers
|
In the previous chapter, we learned how to use markers in Leaflet. Along with markers, we can also add various shapes such as circles, polygons, rectangles, polylines, etc. In this chapter, we will discuss how to use the shapes provided by Google Maps.
To draw polyline overlay on a map using Leaflet JavaScript library, follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create a latlangs variable to hold the points to draw polyline, as shown below.
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.000538, 81.804034],
[17.686816, 83.218482]
];
Step 5 − Create a polyline using the L.polyline(). To draw the polyline, pass the locations as variable and an option to specify the color of the lines.
// Creating a poly line
var polyline = L.polyline(latlngs, {color: 'red'});
Step 6 − Add the polyline to the map using the addTo() method of the Polyline class.
// Adding to poly line to map
polyline.addTo(map);
Following is the code which draws a polyline, covering the cities Hyderabad, Vijayawada, Rajamahendrawaram and, Vishakhapatnam (India).
DOCTYPE html>
<html>
<head>
<title>Leaflet Poly lines</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [16.506174, 80.648015],
zoom: 7
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.000538, 81.804034],
[17.686816, 83.218482]
];
// Creating a poly line
var polyline = L.polyline(latlngs, {color: 'red'});
// Adding to poly line to map
polyline.addTo(map);
</script>
</body>
</html>
It generates the following output
To draw a polygon overlay on a map using Leaflet JavaScript library, follow the steps given below −
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create a latlangs variable to hold the points to draw the polygon.
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.686816, 83.218482]
];
Step 5 − Create a polygon using the L.polygon(). Pass the locations/points as variable to draw the polygon, and an option to specify the color of the polygon.
// Creating a polygon
var polygon = L.polygon(latlngs, {color: 'red'});
Step 6 − Add the polygon to the map using the addTo() method of the Polygon class.
// Adding to polygon to map
polygon.addTo(map);
Following is the code to draw a polygon covering the cities Hyderabad, Vijayawada, and Vishakhapatnam (India).
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Polygons</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [16.506174, 80.648015],
zoom: 7
}
// Creating a map object
var map = new L.map('map', mapOptions);
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
// Adding layer to the map
map.addLayer(layer);
// Creating latlng object
var latlngs = [
[17.385044, 78.486671],
[16.506174, 80.648015],
[17.686816, 83.218482]
];
// Creating a polygon
var polygon = L.polygon(latlngs, {color: 'red'});
// Adding to polygon to map
polygon.addTo(map);
</script>
</body>
</html>
It generates the following output −
To draw a Rectangle overlay on a map using Leaflet JavaScript library, follow the steps given below
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create a latlangs variable to hold the points to draw a rectangle on the map.
// Creating latlng object
var latlngs = [
[17.342761, 78.552432],
[16.396553, 80.727725]
];
Step 5 − Create a rectangle using the L.rectangle() function. Pass the locations/points as a variable to draw a rectangle and rectangleOptions to specify the color and weight of the rectangle.
// Creating rectOptions
var rectOptions = {color: 'Red', weight: 1}
// Creating a rectangle
var rectangle = L.rectangle(latlngs, rectOptions);
Step 6 − Add the rectangle to the map using the addTo() method of the Polygon class.
// Adding to rectangle to map
rectangle.addTo(map);
Following is the code to draw a rectangle on the map using Leaflet JavaScript library.
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Rectangle</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width:900px; height:580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [16.506174, 80.648015],
zoom: 7
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
// Creating latlng object
var latlngs = [
[17.342761, 78.552432],
[16.396553, 80.727725]
];
var rectOptions = {color: 'Red', weight: 1} // Creating rectOptions
// Creating a rectangle
var rectangle = L.rectangle(latlngs, rectOptions);
rectangle.addTo(map); // Adding to rectangle to map
</script>
</body>
</html>
It generates the following output −
To draw a circle overlay on a map using Leaflet JavaScript library follow the steps given below.
Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional).
Step 2 − Create a Layer object by passing the URL of the desired tile.
Step 3 − Add the layer object to the map using the addLayer() method of the Map class.
Step 4 − Create a latlangs variable to hold the center of the circle as shown below.
// Center of the circle
var circleCenter = [17.385044, 78.486671];
Step 5 − Create a variable circleOptions to specify values to the options color, fillColor and, fillOpacity as shown below.
// Circle options
var circleOptions = {
color: 'red',
fillColor: '#f03',
fillOpacity: 0
}
Step 6 − Create a circle using L.circle(). Pass the center of the circle, radius, and the circle options to this function.
// Creating a circle
var circle = L.circle(circleCenter, 50000, circleOptions);
Step 7 − Add the above-created circle to the map using the addTo() method of the Polyline class.
// Adding circle to the map
circle.addTo(map);
Following is the code to draw a circle with the coordinates of the city Hyderabad as its radius.
<!DOCTYPE html>
<html>
<head>
<title>Leaflet Circle</title>
<link rel = "stylesheet" href = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css"/>
<script src = "http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js"></script>
</head>
<body>
<div id = "map" style = "width: 900px; height: 580px"></div>
<script>
// Creating map options
var mapOptions = {
center: [17.385044, 78.486671],
zoom: 7
}
var map = new L.map('map', mapOptions); // Creating a map object
// Creating a Layer object
var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');
map.addLayer(layer); // Adding layer to the map
var circleCenter = [17.385044, 78.486671]; // Center of the circle
// Circle options
var circleOptions = {
color: 'red',
fillColor: '#f03',
fillOpacity: 0
}
// Creating a circle
var circle = L.circle(circleCenter, 50000, circleOptions);
circle.addTo(map); // Adding circle to the map
</script>
</body>
</html>>
It generates the following output −
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2051,
"s": 1798,
"text": "In the previous chapter, we learned how to use markers in Leaflet. Along with markers, we can also add various shapes such as circles, polygons, rectangles, polylines, etc. In this chapter, we will discuss how to use the shapes provided by Google Maps."
},
{
"code": null,
"e": 2150,
"s": 2051,
"text": "To draw polyline overlay on a map using Leaflet JavaScript library, follow the steps given below −"
},
{
"code": null,
"e": 2253,
"s": 2150,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 2324,
"s": 2253,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 2411,
"s": 2324,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 2500,
"s": 2411,
"text": "Step 4 − Create a latlangs variable to hold the points to draw polyline, as shown below."
},
{
"code": null,
"e": 2653,
"s": 2500,
"text": "// Creating latlng object\nvar latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.000538, 81.804034],\n [17.686816, 83.218482]\n];\n"
},
{
"code": null,
"e": 2806,
"s": 2653,
"text": "Step 5 − Create a polyline using the L.polyline(). To draw the polyline, pass the locations as variable and an option to specify the color of the lines."
},
{
"code": null,
"e": 2883,
"s": 2806,
"text": "// Creating a poly line\nvar polyline = L.polyline(latlngs, {color: 'red'});\n"
},
{
"code": null,
"e": 2968,
"s": 2883,
"text": "Step 6 − Add the polyline to the map using the addTo() method of the Polyline class."
},
{
"code": null,
"e": 3020,
"s": 2968,
"text": "// Adding to poly line to map\npolyline.addTo(map);\n"
},
{
"code": null,
"e": 3156,
"s": 3020,
"text": "Following is the code which draws a polyline, covering the cities Hyderabad, Vijayawada, Rajamahendrawaram and, Vishakhapatnam (India)."
},
{
"code": null,
"e": 4376,
"s": 3156,
"text": "DOCTYPE html>\n<html>\n <head>\n <title>Leaflet Poly lines</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width:900px; height:580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [16.506174, 80.648015],\n zoom: 7\n }\n // Creating a map object\n var map = new L.map('map', mapOptions);\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n \n // Adding layer to the map\n map.addLayer(layer);\n \n // Creating latlng object\n var latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.000538, 81.804034],\n [17.686816, 83.218482]\n ];\n // Creating a poly line\n var polyline = L.polyline(latlngs, {color: 'red'});\n \n // Adding to poly line to map\n polyline.addTo(map);\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 4410,
"s": 4376,
"text": "It generates the following output"
},
{
"code": null,
"e": 4510,
"s": 4410,
"text": "To draw a polygon overlay on a map using Leaflet JavaScript library, follow the steps given below −"
},
{
"code": null,
"e": 4613,
"s": 4510,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 4684,
"s": 4613,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 4771,
"s": 4684,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 4847,
"s": 4771,
"text": "Step 4 − Create a latlangs variable to hold the points to draw the polygon."
},
{
"code": null,
"e": 4973,
"s": 4847,
"text": "// Creating latlng object\nvar latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.686816, 83.218482]\n];\n"
},
{
"code": null,
"e": 5132,
"s": 4973,
"text": "Step 5 − Create a polygon using the L.polygon(). Pass the locations/points as variable to draw the polygon, and an option to specify the color of the polygon."
},
{
"code": null,
"e": 5205,
"s": 5132,
"text": "// Creating a polygon\nvar polygon = L.polygon(latlngs, {color: 'red'});\n"
},
{
"code": null,
"e": 5288,
"s": 5205,
"text": "Step 6 − Add the polygon to the map using the addTo() method of the Polygon class."
},
{
"code": null,
"e": 5337,
"s": 5288,
"text": "// Adding to polygon to map\npolygon.addTo(map);\n"
},
{
"code": null,
"e": 5448,
"s": 5337,
"text": "Following is the code to draw a polygon covering the cities Hyderabad, Vijayawada, and Vishakhapatnam (India)."
},
{
"code": null,
"e": 6621,
"s": 5448,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Leaflet Polygons</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n\n <body>\n <div id = \"map\" style = \"width:900px; height:580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [16.506174, 80.648015],\n zoom: 7\n }\n // Creating a map object\n var map = new L.map('map', mapOptions);\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n \n // Adding layer to the map\n map.addLayer(layer);\n \n // Creating latlng object\n var latlngs = [\n [17.385044, 78.486671],\n [16.506174, 80.648015],\n [17.686816, 83.218482]\n ];\n // Creating a polygon\n var polygon = L.polygon(latlngs, {color: 'red'});\n \n // Adding to polygon to map\n polygon.addTo(map);\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 6657,
"s": 6621,
"text": "It generates the following output −"
},
{
"code": null,
"e": 6757,
"s": 6657,
"text": "To draw a Rectangle overlay on a map using Leaflet JavaScript library, follow the steps given below"
},
{
"code": null,
"e": 6860,
"s": 6757,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 6931,
"s": 6860,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 7018,
"s": 6931,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 7105,
"s": 7018,
"text": "Step 4 − Create a latlangs variable to hold the points to draw a rectangle on the map."
},
{
"code": null,
"e": 7204,
"s": 7105,
"text": "// Creating latlng object\nvar latlngs = [\n [17.342761, 78.552432],\n [16.396553, 80.727725]\n];\n"
},
{
"code": null,
"e": 7397,
"s": 7204,
"text": "Step 5 − Create a rectangle using the L.rectangle() function. Pass the locations/points as a variable to draw a rectangle and rectangleOptions to specify the color and weight of the rectangle."
},
{
"code": null,
"e": 7542,
"s": 7397,
"text": "// Creating rectOptions\nvar rectOptions = {color: 'Red', weight: 1}\n\n// Creating a rectangle\nvar rectangle = L.rectangle(latlngs, rectOptions);\n"
},
{
"code": null,
"e": 7627,
"s": 7542,
"text": "Step 6 − Add the rectangle to the map using the addTo() method of the Polygon class."
},
{
"code": null,
"e": 7680,
"s": 7627,
"text": "// Adding to rectangle to map\nrectangle.addTo(map);\n"
},
{
"code": null,
"e": 7767,
"s": 7680,
"text": "Following is the code to draw a rectangle on the map using Leaflet JavaScript library."
},
{
"code": null,
"e": 8959,
"s": 7767,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Leaflet Rectangle</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width:900px; height:580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [16.506174, 80.648015],\n zoom: 7\n }\n var map = new L.map('map', mapOptions); // Creating a map object\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n \n // Creating latlng object\n var latlngs = [\n [17.342761, 78.552432],\n [16.396553, 80.727725]\n ];\n var rectOptions = {color: 'Red', weight: 1} // Creating rectOptions\n \n // Creating a rectangle\n var rectangle = L.rectangle(latlngs, rectOptions);\n rectangle.addTo(map); // Adding to rectangle to map\n </script>\n </body>\n \n</html>"
},
{
"code": null,
"e": 8995,
"s": 8959,
"text": "It generates the following output −"
},
{
"code": null,
"e": 9092,
"s": 8995,
"text": "To draw a circle overlay on a map using Leaflet JavaScript library follow the steps given below."
},
{
"code": null,
"e": 9195,
"s": 9092,
"text": "Step 1 − Create a Map object by passing a <div> element (String or object) and map options (optional)."
},
{
"code": null,
"e": 9266,
"s": 9195,
"text": "Step 2 − Create a Layer object by passing the URL of the desired tile."
},
{
"code": null,
"e": 9353,
"s": 9266,
"text": "Step 3 − Add the layer object to the map using the addLayer() method of the Map class."
},
{
"code": null,
"e": 9438,
"s": 9353,
"text": "Step 4 − Create a latlangs variable to hold the center of the circle as shown below."
},
{
"code": null,
"e": 9506,
"s": 9438,
"text": "// Center of the circle\nvar circleCenter = [17.385044, 78.486671];\n"
},
{
"code": null,
"e": 9630,
"s": 9506,
"text": "Step 5 − Create a variable circleOptions to specify values to the options color, fillColor and, fillOpacity as shown below."
},
{
"code": null,
"e": 9730,
"s": 9630,
"text": "// Circle options\nvar circleOptions = {\n color: 'red',\n fillColor: '#f03',\n fillOpacity: 0\n}\n"
},
{
"code": null,
"e": 9853,
"s": 9730,
"text": "Step 6 − Create a circle using L.circle(). Pass the center of the circle, radius, and the circle options to this function."
},
{
"code": null,
"e": 9934,
"s": 9853,
"text": "// Creating a circle\nvar circle = L.circle(circleCenter, 50000, circleOptions);\n"
},
{
"code": null,
"e": 10031,
"s": 9934,
"text": "Step 7 − Add the above-created circle to the map using the addTo() method of the Polyline class."
},
{
"code": null,
"e": 10079,
"s": 10031,
"text": "// Adding circle to the map\ncircle.addTo(map);\n"
},
{
"code": null,
"e": 10176,
"s": 10079,
"text": "Following is the code to draw a circle with the coordinates of the city Hyderabad as its radius."
},
{
"code": null,
"e": 11379,
"s": 10176,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Leaflet Circle</title>\n <link rel = \"stylesheet\" href = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.css\"/>\n <script src = \"http://cdn.leafletjs.com/leaflet-0.7.3/leaflet.js\"></script>\n </head>\n \n <body>\n <div id = \"map\" style = \"width: 900px; height: 580px\"></div>\n <script>\n // Creating map options\n var mapOptions = {\n center: [17.385044, 78.486671],\n zoom: 7\n }\n var map = new L.map('map', mapOptions); // Creating a map object\n \n // Creating a Layer object\n var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png');\n map.addLayer(layer); // Adding layer to the map\n var circleCenter = [17.385044, 78.486671]; // Center of the circle\n \n // Circle options\n var circleOptions = {\n color: 'red',\n fillColor: '#f03',\n fillOpacity: 0\n }\n // Creating a circle\n var circle = L.circle(circleCenter, 50000, circleOptions);\n circle.addTo(map); // Adding circle to the map\n </script>\n </body>\n \n</html>>"
},
{
"code": null,
"e": 11415,
"s": 11379,
"text": "It generates the following output −"
},
{
"code": null,
"e": 11422,
"s": 11415,
"text": " Print"
},
{
"code": null,
"e": 11433,
"s": 11422,
"text": " Add Notes"
}
] |
Java Program to subtract year from current date
|
Firstly, you need to import the following package for Calendar class in Java
import java.util.Calendar;
Create a Calendar object and display the current date and time
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date and Time = " + calendar.getTime());
Now, let us decrement the year using the calendar.add() method and Calendar.YEAR constant. Set a negative value since we are decrementing here
calendar.add(Calendar.YEAR, -20);
The following is an example
Live Demo
import java.util.Calendar;
public class Demo {
public static void main(String[] args) {
Calendar calendar = Calendar.getInstance();
System.out.println("Current Date = " + calendar.getTime());
// Subtract 20 Years
calendar.add(Calendar.YEAR, -20);
System.out.println("Updated Date = " + calendar.getTime());
}
}
Current Date = Thu Nov 22 18:20:30 UTC 2018
Updated Date = Sun Nov 22 18:20:30 UTC 1998
|
[
{
"code": null,
"e": 1139,
"s": 1062,
"text": "Firstly, you need to import the following package for Calendar class in Java"
},
{
"code": null,
"e": 1166,
"s": 1139,
"text": "import java.util.Calendar;"
},
{
"code": null,
"e": 1229,
"s": 1166,
"text": "Create a Calendar object and display the current date and time"
},
{
"code": null,
"e": 1342,
"s": 1229,
"text": "Calendar calendar = Calendar.getInstance();\nSystem.out.println(\"Current Date and Time = \" + calendar.getTime());"
},
{
"code": null,
"e": 1485,
"s": 1342,
"text": "Now, let us decrement the year using the calendar.add() method and Calendar.YEAR constant. Set a negative value since we are decrementing here"
},
{
"code": null,
"e": 1519,
"s": 1485,
"text": "calendar.add(Calendar.YEAR, -20);"
},
{
"code": null,
"e": 1547,
"s": 1519,
"text": "The following is an example"
},
{
"code": null,
"e": 1558,
"s": 1547,
"text": " Live Demo"
},
{
"code": null,
"e": 1905,
"s": 1558,
"text": "import java.util.Calendar;\npublic class Demo {\n public static void main(String[] args) {\n Calendar calendar = Calendar.getInstance();\n System.out.println(\"Current Date = \" + calendar.getTime());\n // Subtract 20 Years\n calendar.add(Calendar.YEAR, -20);\n System.out.println(\"Updated Date = \" + calendar.getTime());\n }\n}"
},
{
"code": null,
"e": 1993,
"s": 1905,
"text": "Current Date = Thu Nov 22 18:20:30 UTC 2018\nUpdated Date = Sun Nov 22 18:20:30 UTC 1998"
}
] |
Python | Intersection of two String
|
27 Nov, 2018
One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings.
There are various ways in Python, through which we can perform the Intersection of two strings.
Method #1 : Naive MethodCreate an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. This can be achieved by loops and if/else statements.
# Python3 code to demonstrate # string intersection# using naive method # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # using naive method to# get string intersectionres = ""for i in test_str1: if i in test_str2 and not i in res: res += i # printing intersectionprint ("String intersection is : " + res)
Output :
String intersection is : eksfor
Method #2 : Using set() + intersection()
Firstly, both the strings are converted into sets using set() and then intersection is performed using intersection(). Returns the sorted set.
# Python3 code to demonstrate # string intersection# using set() + intersection() # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # using set() + intersection() to# get string intersectionres = set(test_str1).intersection(test_str2) # printing intersectionprint ("String intersection is : " + str(res))
Output :
String intersection is : {'e', 'f', 's', 'o', 'k', 'r'}
Method #3 : Using join()
join() performs the task similar to list comprehension in case of lists. This encapsulates whole intersection logic and joins together each element filtered through the intersection logic into one string, hence computing the intersection. It converts the strings into set and then computed & operation on them.
# Python3 code to demonstrate # string intersection# using join() # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # using join() to# get string intersectionres = ''.join(sorted(set(test_str1) & set(test_str2), key = test_str1.index)) # printing intersectionprint ("String intersection is : " + str(res))
Output :
String intersection is : eksfor
Python string-programs
python-string
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Nov, 2018"
},
{
"code": null,
"e": 169,
"s": 28,
"text": "One of the string operations can be computing the intersection of two strings i.e, output the common values that appear in both the strings."
},
{
"code": null,
"e": 265,
"s": 169,
"text": "There are various ways in Python, through which we can perform the Intersection of two strings."
},
{
"code": null,
"e": 493,
"s": 265,
"text": "Method #1 : Naive MethodCreate an empty string and check for new occurrence of character common to both string and appending it. Hence computing the new intersection string. This can be achieved by loops and if/else statements."
},
{
"code": "# Python3 code to demonstrate # string intersection# using naive method # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # using naive method to# get string intersectionres = \"\"for i in test_str1: if i in test_str2 and not i in res: res += i # printing intersectionprint (\"String intersection is : \" + res)",
"e": 847,
"s": 493,
"text": null
},
{
"code": null,
"e": 856,
"s": 847,
"text": "Output :"
},
{
"code": null,
"e": 889,
"s": 856,
"text": "String intersection is : eksfor\n"
},
{
"code": null,
"e": 931,
"s": 889,
"text": " Method #2 : Using set() + intersection()"
},
{
"code": null,
"e": 1074,
"s": 931,
"text": "Firstly, both the strings are converted into sets using set() and then intersection is performed using intersection(). Returns the sorted set."
},
{
"code": "# Python3 code to demonstrate # string intersection# using set() + intersection() # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # using set() + intersection() to# get string intersectionres = set(test_str1).intersection(test_str2) # printing intersectionprint (\"String intersection is : \" + str(res))",
"e": 1414,
"s": 1074,
"text": null
},
{
"code": null,
"e": 1423,
"s": 1414,
"text": "Output :"
},
{
"code": null,
"e": 1480,
"s": 1423,
"text": "String intersection is : {'e', 'f', 's', 'o', 'k', 'r'}\n"
},
{
"code": null,
"e": 1507,
"s": 1482,
"text": "Method #3 : Using join()"
},
{
"code": null,
"e": 1818,
"s": 1507,
"text": "join() performs the task similar to list comprehension in case of lists. This encapsulates whole intersection logic and joins together each element filtered through the intersection logic into one string, hence computing the intersection. It converts the strings into set and then computed & operation on them."
},
{
"code": "# Python3 code to demonstrate # string intersection# using join() # initializing stringstest_str1 = 'GeeksforGeeks'test_str2 = 'Codefreaks' # using join() to# get string intersectionres = ''.join(sorted(set(test_str1) & set(test_str2), key = test_str1.index)) # printing intersectionprint (\"String intersection is : \" + str(res))",
"e": 2167,
"s": 1818,
"text": null
},
{
"code": null,
"e": 2176,
"s": 2167,
"text": "Output :"
},
{
"code": null,
"e": 2209,
"s": 2176,
"text": "String intersection is : eksfor\n"
},
{
"code": null,
"e": 2232,
"s": 2209,
"text": "Python string-programs"
},
{
"code": null,
"e": 2246,
"s": 2232,
"text": "python-string"
},
{
"code": null,
"e": 2253,
"s": 2246,
"text": "Python"
},
{
"code": null,
"e": 2351,
"s": 2253,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2369,
"s": 2351,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2411,
"s": 2369,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2433,
"s": 2411,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2468,
"s": 2433,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2494,
"s": 2468,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2526,
"s": 2494,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2555,
"s": 2526,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2582,
"s": 2555,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2612,
"s": 2582,
"text": "Iterate over a list in Python"
}
] |
Java Competitive Programming Setup in VS Code with Fast I/O and Snippets
|
10 May, 2022
Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and fro where python being slowest among dynamic is hardly seen in the competitive world. So users who are comfortable with programming in Java only and wanted to pursue competitive programming with it, here’s how to set up your environment on the local computer. As an editor, we will be using one of the most popular code editors as of today that is VS Code.
Procedure:
Follow the standard steps sequentially to set up. There are 4 steps to be followed as follows:
Install VS Code and set up JDK (if not installed). Let us carry on.Set up a snippet for the Fast I/O.Setting up your input and output files.Partitioning your screen.
Install VS Code and set up JDK (if not installed). Let us carry on.
Set up a snippet for the Fast I/O.
Setting up your input and output files.
Partitioning your screen.
Now we will be digging down to each step alongside visual aids right from the starting to get absolutely clear understanding geek as they last longer.
Explanation:
Step 1: Install VS Code and set up JDK
Install VS Code from the official VS Code website
Thereafter, do install/update the latest version of the JDK. (Java Development Kit)
Step 2: Set up a snippet for the Fast I/O.
Snippets are very useful to quickly insert a large amount of pre-written code that you use frequently. Since the input and output code will be used for every competitive programming problem, a snippet will be extremely helpful to our cause.
To set up a snippet, observe the following steps:
2.1 Open up VS Code and go to File -> Preferences -> User Snippets.
2.2 Select java.json from the succeeding drop-down box as shown below.
2.3 You will find VS Code already provides a rough guide on how to create a custom snippet. The text should look something like as follows:
{
Place your snippets for java here. Each snippet is defined
under a snippet name and has a prefix, body and
description.
The prefix is what is used to trigger the snippet and
the body will be expanded and inserted. Possible variables are:
$1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.
Placeholders with the
same ids are connected.
Illustration:
"Print to console": {
"prefix": "log",
"body": [
"console.log('$1');",
"$2"
],
"description": "Log output to console"
}
}
2.4 Below the given comments and inside the curly braces, paste the following code:
"Template for CP" : {
"prefix": "template",
"body":[
"import java.util.*;",
"import java.io.*;",
"public class Main {",
"$LINE_COMMENT For fast input output",
"static class FastReader {",
"BufferedReader br;",
"StringTokenizer st;",
"public FastReader()",
"{ try {br = new BufferedReader(",
"new FileReader(\"input.txt\"));",
"PrintStream out = new PrintStream(new FileOutputStream(\"output.txt\"));",
"System.setOut(out);}",
"catch(Exception e) { br = new BufferedReader(new InputStreamReader(System.in));}",
"}",
"String next()",
"{",
"while (st == null || !st.hasMoreElements()) {",
"try {st = new StringTokenizer(br.readLine());}",
"catch (IOException e) {",
"e.printStackTrace();}",
"}",
"return st.nextToken();",
"}",
"int nextInt() { return Integer.parseInt(next()); }",
"long nextLong() { return Long.parseLong(next()); }",
"double nextDouble() {return Double.parseDouble(next()); }",
"String nextLine()",
"{",
"String str = \"\";",
"try {",
"str = br.readLine();",
"}",
"catch (IOException e) {",
"e.printStackTrace();",
"}",
"return str;",
"}",
"}",
"$LINE_COMMENT end of fast i/o code",
"public static void main(String[] args) {",
"FastReader reader = new FastReader();",
"$0",
"}",
"}"
],
"description": "template for cp in java"
},
"For loop":{
"prefix" : "forl",
"body" : [
"for(int i = 0; i < $0; i++)"
]
}
Note: Explanation of the above snippet is provided and is necessary to understand in order to understand its usage and further modification
Template for CP is the name of the snippet. It is used to identify the snippet while it appears during code-completion (marked in red).
template is the prefix that is used to trigger the code completion (marked in green).
body is where the code of the snippet lies. Some important points to note here is:The Fast I/O code is a slight modification of the FastReader code from the article Fast I/O in Java in Competitive Programming.The modification lies in the try/catch block in the constructor of the FastReader class. It is used to connect to the input and output file on our local computer. We will look at the process to set up input and output files later in this article.$0 in the main function is used as a placeholder for the cursor. After the snippet pastes itself on your Java file, the cursor will be automatically placed at the $0 mark.Comments can be added in the snippet with the keyword $LINE_COMMENT placed before the comment.Special characters, (like quotation marks) must be escaped using backslash (\);It is important to note that, every line in the body of the snippet must be individually placed in quotes and a comma must be placed after every line, as illustrated below.
The Fast I/O code is a slight modification of the FastReader code from the article Fast I/O in Java in Competitive Programming.
The modification lies in the try/catch block in the constructor of the FastReader class. It is used to connect to the input and output file on our local computer. We will look at the process to set up input and output files later in this article.
$0 in the main function is used as a placeholder for the cursor. After the snippet pastes itself on your Java file, the cursor will be automatically placed at the $0 mark.
Comments can be added in the snippet with the keyword $LINE_COMMENT placed before the comment.
Special characters, (like quotation marks) must be escaped using backslash (\);
It is important to note that, every line in the body of the snippet must be individually placed in quotes and a comma must be placed after every line, as illustrated below.
description is used to leave a short note about the snippet for future reference.
Tip: When the snippet is implemented in your program, it appears in an unformatted and un-indented form. To quickly format it, press Shift + Alt + F.
Step 3: Setting up your input and output files.
During competitions, it is easier to paste a large input and read the corresponding output from files rather than manually entering input in your terminal window. Therefore, we will set up an input and output file. The steps to take so are as follows:
Create a separate folder and create two text files in it: “input.txt” and “output.txt“. It is imperative that your Java code file be in that same folder. This should be enough to do the trick. In case you want to put the input, output, and Java files in different directories, put the path of the files in your code in the places shown below.
We need to look closely at the following code snippet to get to know how the try/catch block works here which is provided below in the example.
Example
// This code snippet is a part of the FastReader class
// as illustrated above
public FastReader() {
// The try block runs when both input and output files
// are present in the specified directory.
try {
// We modify the input stream to take input
//from the input.txt file
br = new BufferedReader(new FileReader("input.txt"));
// We modify the output stream to print the output
// in the output.txt file
PrintStream out = new
PrintStream(new FileOutputStream("output.txt"));
System.setOut(out);
}
// In case the input or the output file is not found,
// a FileNotFoundException is thrown and we enter the
// catch block.
// Catch block to handle th exception
catch (Exception e) {
// Since an input file is not present, we take input
// from the usual system input stream.
br = new BufferedReader(
new InputStreamReader(System.in));
}
}
Explanation of the above snippet is as follows:
Here basically we are looking for an input and output file first, which should be present on our local device, and input and output there. However, if an input and output text file is not found, as is the case of when the code is submitted to an online judge, the program will read input from the standard input stream and output in the standard output stream.
Step 3 ( Alternative ): Setting up your input and output files.
During competitions, it is easier to paste a large input and read the corresponding output from files rather than manually entering input in your terminal window. Therefore, we will set up an input and output file. The steps to take so are as follows:
Search & Install an Extension Named Code Builder.
Run the Code using Build with IO Command or use CTRL+ALT+K
It will ask you for the Input & Output Files at Runtime if Not Set otherwise it will use Previous Selected Files.
Make Sure that Input & Output files are in the Same Drive as Source file.
Then You will not have to Modify the Input Stream and Output Stream.
Snippet Modifications will be done as below
Example
// This code snippet is a part of the FastReader class
// as illustrated above
public FastReader() {
// The try block runs when both input and output files
// are present in the specified directory.
try {
//The Extension will PIPE the Input and Output Stream to Files at Runtime
br = new BufferedReader(System.in);
}
// In case there is an error input or the output file is not found,
// Exception is thrown and we enter the
// catch block.
// Catch block to handle the exception
catch (Exception e) {
// Printing the Stack Trace of Exception
e.printStackTrace();
}
}
Step 4: Partitioning your screen
Now, that all the necessary files have been created, let us set up our coding environment:
Open up VS Code and open the folder which contains your input, output, and Java program file. To achieve this, go to File-> Open Folder and select your folder.
Open all three files simultaneously so that they are in separate tabs.
Go to View-> Editor Layout-> Two Rows Right.
Drag the input.txt to the top-right pane and the output.txt to the bottom-right pane or vice-versa, according to your convenience. Keep your Java file in the left-pane to give it maximum screen coverage. Adjust the sizes of the panes by dragging the borders of each pane division.
The final product should look something like this:
Tip: You can switch quickly between panes using Ctrl + PgUp and Ctrl + PgDown key combinations.
gulshankumarar231
user_aryg
gabaa406
Java 8
Java-Competitive-Programming
Competitive Programming
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 53,
"s": 25,
"text": "\n10 May, 2022"
},
{
"code": null,
"e": 698,
"s": 53,
"text": "Though C++ is the dominating language in the competitive programming universe, there is a fair share of users who still continue to use Java as it has been there seen in the development arena and at the same time can be used competitive programming being fast as it can be toggled to and fro where python being slowest among dynamic is hardly seen in the competitive world. So users who are comfortable with programming in Java only and wanted to pursue competitive programming with it, here’s how to set up your environment on the local computer. As an editor, we will be using one of the most popular code editors as of today that is VS Code."
},
{
"code": null,
"e": 709,
"s": 698,
"text": "Procedure:"
},
{
"code": null,
"e": 804,
"s": 709,
"text": "Follow the standard steps sequentially to set up. There are 4 steps to be followed as follows:"
},
{
"code": null,
"e": 970,
"s": 804,
"text": "Install VS Code and set up JDK (if not installed). Let us carry on.Set up a snippet for the Fast I/O.Setting up your input and output files.Partitioning your screen."
},
{
"code": null,
"e": 1038,
"s": 970,
"text": "Install VS Code and set up JDK (if not installed). Let us carry on."
},
{
"code": null,
"e": 1073,
"s": 1038,
"text": "Set up a snippet for the Fast I/O."
},
{
"code": null,
"e": 1113,
"s": 1073,
"text": "Setting up your input and output files."
},
{
"code": null,
"e": 1139,
"s": 1113,
"text": "Partitioning your screen."
},
{
"code": null,
"e": 1290,
"s": 1139,
"text": "Now we will be digging down to each step alongside visual aids right from the starting to get absolutely clear understanding geek as they last longer."
},
{
"code": null,
"e": 1303,
"s": 1290,
"text": "Explanation:"
},
{
"code": null,
"e": 1343,
"s": 1303,
"text": "Step 1: Install VS Code and set up JDK "
},
{
"code": null,
"e": 1393,
"s": 1343,
"text": "Install VS Code from the official VS Code website"
},
{
"code": null,
"e": 1477,
"s": 1393,
"text": "Thereafter, do install/update the latest version of the JDK. (Java Development Kit)"
},
{
"code": null,
"e": 1520,
"s": 1477,
"text": "Step 2: Set up a snippet for the Fast I/O."
},
{
"code": null,
"e": 1761,
"s": 1520,
"text": "Snippets are very useful to quickly insert a large amount of pre-written code that you use frequently. Since the input and output code will be used for every competitive programming problem, a snippet will be extremely helpful to our cause."
},
{
"code": null,
"e": 1811,
"s": 1761,
"text": "To set up a snippet, observe the following steps:"
},
{
"code": null,
"e": 1879,
"s": 1811,
"text": "2.1 Open up VS Code and go to File -> Preferences -> User Snippets."
},
{
"code": null,
"e": 1950,
"s": 1879,
"text": "2.2 Select java.json from the succeeding drop-down box as shown below."
},
{
"code": null,
"e": 2090,
"s": 1950,
"text": "2.3 You will find VS Code already provides a rough guide on how to create a custom snippet. The text should look something like as follows:"
},
{
"code": null,
"e": 2626,
"s": 2090,
"text": "{\n\nPlace your snippets for java here. Each snippet is defined \nunder a snippet name and has a prefix, body and \ndescription. \n\nThe prefix is what is used to trigger the snippet and\nthe body will be expanded and inserted. Possible variables are:\n\n$1, $2 for tab stops, $0 for the final cursor position, and ${1:label}, ${2:another} for placeholders.\nPlaceholders with the \nsame ids are connected.\n\nIllustration:\n\n\n\"Print to console\": {\n\"prefix\": \"log\",\n\"body\": [\n\"console.log('$1');\",\n\"$2\"\n],\n\"description\": \"Log output to console\"\n\n}\n}"
},
{
"code": null,
"e": 2710,
"s": 2626,
"text": "2.4 Below the given comments and inside the curly braces, paste the following code:"
},
{
"code": null,
"e": 5158,
"s": 2710,
"text": "\"Template for CP\" : {\n \"prefix\": \"template\",\n \"body\":[\n \"import java.util.*;\",\n \"import java.io.*;\",\n \n \"public class Main {\",\n \"$LINE_COMMENT For fast input output\",\n \"static class FastReader {\",\n \"BufferedReader br;\",\n \"StringTokenizer st;\",\n \n \"public FastReader()\",\n \"{ try {br = new BufferedReader(\",\n \"new FileReader(\\\"input.txt\\\"));\",\n \"PrintStream out = new PrintStream(new FileOutputStream(\\\"output.txt\\\"));\",\n \"System.setOut(out);}\",\n \"catch(Exception e) { br = new BufferedReader(new InputStreamReader(System.in));}\",\n \"}\",\n \n \"String next()\",\n \"{\",\n \"while (st == null || !st.hasMoreElements()) {\",\n \"try {st = new StringTokenizer(br.readLine());}\",\n \"catch (IOException e) {\",\n \"e.printStackTrace();}\",\n \"}\",\n \"return st.nextToken();\",\n \"}\",\n \n \"int nextInt() { return Integer.parseInt(next()); }\", \n \"long nextLong() { return Long.parseLong(next()); }\", \n \"double nextDouble() {return Double.parseDouble(next()); }\",\n \n \"String nextLine()\",\n \"{\",\n \"String str = \\\"\\\";\",\n \"try {\",\n \"str = br.readLine();\",\n \"}\",\n \"catch (IOException e) {\",\n \"e.printStackTrace();\",\n \"}\",\n \"return str;\",\n \"}\",\n \"}\",\n \"$LINE_COMMENT end of fast i/o code\",\n \n \n \"public static void main(String[] args) {\",\n \"FastReader reader = new FastReader();\",\n \"$0\",\n \"}\",\n \"}\"\n ],\n \"description\": \"template for cp in java\"\n },\n\n \"For loop\":{\n \"prefix\" : \"forl\",\n \"body\" : [\n \"for(int i = 0; i < $0; i++)\"\n ]\n } "
},
{
"code": null,
"e": 5298,
"s": 5158,
"text": "Note: Explanation of the above snippet is provided and is necessary to understand in order to understand its usage and further modification"
},
{
"code": null,
"e": 5434,
"s": 5298,
"text": "Template for CP is the name of the snippet. It is used to identify the snippet while it appears during code-completion (marked in red)."
},
{
"code": null,
"e": 5520,
"s": 5434,
"text": "template is the prefix that is used to trigger the code completion (marked in green)."
},
{
"code": null,
"e": 6492,
"s": 5520,
"text": "body is where the code of the snippet lies. Some important points to note here is:The Fast I/O code is a slight modification of the FastReader code from the article Fast I/O in Java in Competitive Programming.The modification lies in the try/catch block in the constructor of the FastReader class. It is used to connect to the input and output file on our local computer. We will look at the process to set up input and output files later in this article.$0 in the main function is used as a placeholder for the cursor. After the snippet pastes itself on your Java file, the cursor will be automatically placed at the $0 mark.Comments can be added in the snippet with the keyword $LINE_COMMENT placed before the comment.Special characters, (like quotation marks) must be escaped using backslash (\\);It is important to note that, every line in the body of the snippet must be individually placed in quotes and a comma must be placed after every line, as illustrated below."
},
{
"code": null,
"e": 6620,
"s": 6492,
"text": "The Fast I/O code is a slight modification of the FastReader code from the article Fast I/O in Java in Competitive Programming."
},
{
"code": null,
"e": 6867,
"s": 6620,
"text": "The modification lies in the try/catch block in the constructor of the FastReader class. It is used to connect to the input and output file on our local computer. We will look at the process to set up input and output files later in this article."
},
{
"code": null,
"e": 7039,
"s": 6867,
"text": "$0 in the main function is used as a placeholder for the cursor. After the snippet pastes itself on your Java file, the cursor will be automatically placed at the $0 mark."
},
{
"code": null,
"e": 7134,
"s": 7039,
"text": "Comments can be added in the snippet with the keyword $LINE_COMMENT placed before the comment."
},
{
"code": null,
"e": 7214,
"s": 7134,
"text": "Special characters, (like quotation marks) must be escaped using backslash (\\);"
},
{
"code": null,
"e": 7387,
"s": 7214,
"text": "It is important to note that, every line in the body of the snippet must be individually placed in quotes and a comma must be placed after every line, as illustrated below."
},
{
"code": null,
"e": 7469,
"s": 7387,
"text": "description is used to leave a short note about the snippet for future reference."
},
{
"code": null,
"e": 7619,
"s": 7469,
"text": "Tip: When the snippet is implemented in your program, it appears in an unformatted and un-indented form. To quickly format it, press Shift + Alt + F."
},
{
"code": null,
"e": 7667,
"s": 7619,
"text": "Step 3: Setting up your input and output files."
},
{
"code": null,
"e": 7920,
"s": 7667,
"text": "During competitions, it is easier to paste a large input and read the corresponding output from files rather than manually entering input in your terminal window. Therefore, we will set up an input and output file. The steps to take so are as follows: "
},
{
"code": null,
"e": 8263,
"s": 7920,
"text": "Create a separate folder and create two text files in it: “input.txt” and “output.txt“. It is imperative that your Java code file be in that same folder. This should be enough to do the trick. In case you want to put the input, output, and Java files in different directories, put the path of the files in your code in the places shown below."
},
{
"code": null,
"e": 8407,
"s": 8263,
"text": "We need to look closely at the following code snippet to get to know how the try/catch block works here which is provided below in the example."
},
{
"code": null,
"e": 8415,
"s": 8407,
"text": "Example"
},
{
"code": null,
"e": 9333,
"s": 8415,
"text": "// This code snippet is a part of the FastReader class\n// as illustrated above\n\npublic FastReader() {\n\n // The try block runs when both input and output files\n // are present in the specified directory.\n try {\n\n // We modify the input stream to take input\n //from the input.txt file\n br = new BufferedReader(new FileReader(\"input.txt\"));\n\n // We modify the output stream to print the output\n // in the output.txt file\n PrintStream out = new\n PrintStream(new FileOutputStream(\"output.txt\"));\n\n System.setOut(out);\n }\n\n // In case the input or the output file is not found,\n // a FileNotFoundException is thrown and we enter the\n // catch block.\n\n // Catch block to handle th exception\n catch (Exception e) {\n\n // Since an input file is not present, we take input\n // from the usual system input stream.\n br = new BufferedReader(\n new InputStreamReader(System.in));\n }\n}"
},
{
"code": null,
"e": 9381,
"s": 9333,
"text": "Explanation of the above snippet is as follows:"
},
{
"code": null,
"e": 9742,
"s": 9381,
"text": "Here basically we are looking for an input and output file first, which should be present on our local device, and input and output there. However, if an input and output text file is not found, as is the case of when the code is submitted to an online judge, the program will read input from the standard input stream and output in the standard output stream."
},
{
"code": null,
"e": 9806,
"s": 9742,
"text": "Step 3 ( Alternative ): Setting up your input and output files."
},
{
"code": null,
"e": 10059,
"s": 9806,
"text": "During competitions, it is easier to paste a large input and read the corresponding output from files rather than manually entering input in your terminal window. Therefore, we will set up an input and output file. The steps to take so are as follows: "
},
{
"code": null,
"e": 10109,
"s": 10059,
"text": "Search & Install an Extension Named Code Builder."
},
{
"code": null,
"e": 10168,
"s": 10109,
"text": "Run the Code using Build with IO Command or use CTRL+ALT+K"
},
{
"code": null,
"e": 10282,
"s": 10168,
"text": "It will ask you for the Input & Output Files at Runtime if Not Set otherwise it will use Previous Selected Files."
},
{
"code": null,
"e": 10356,
"s": 10282,
"text": "Make Sure that Input & Output files are in the Same Drive as Source file."
},
{
"code": null,
"e": 10425,
"s": 10356,
"text": "Then You will not have to Modify the Input Stream and Output Stream."
},
{
"code": null,
"e": 10469,
"s": 10425,
"text": "Snippet Modifications will be done as below"
},
{
"code": null,
"e": 10477,
"s": 10469,
"text": "Example"
},
{
"code": null,
"e": 11087,
"s": 10477,
"text": "// This code snippet is a part of the FastReader class\n// as illustrated above\n\npublic FastReader() {\n\n // The try block runs when both input and output files\n // are present in the specified directory.\n try {\n\n //The Extension will PIPE the Input and Output Stream to Files at Runtime\n br = new BufferedReader(System.in);\n }\n\n // In case there is an error input or the output file is not found,\n // Exception is thrown and we enter the\n // catch block.\n\n // Catch block to handle the exception\n catch (Exception e) {\n\n // Printing the Stack Trace of Exception\n e.printStackTrace();\n }\n}"
},
{
"code": null,
"e": 11120,
"s": 11087,
"text": "Step 4: Partitioning your screen"
},
{
"code": null,
"e": 11211,
"s": 11120,
"text": "Now, that all the necessary files have been created, let us set up our coding environment:"
},
{
"code": null,
"e": 11371,
"s": 11211,
"text": "Open up VS Code and open the folder which contains your input, output, and Java program file. To achieve this, go to File-> Open Folder and select your folder."
},
{
"code": null,
"e": 11442,
"s": 11371,
"text": "Open all three files simultaneously so that they are in separate tabs."
},
{
"code": null,
"e": 11487,
"s": 11442,
"text": "Go to View-> Editor Layout-> Two Rows Right."
},
{
"code": null,
"e": 11768,
"s": 11487,
"text": "Drag the input.txt to the top-right pane and the output.txt to the bottom-right pane or vice-versa, according to your convenience. Keep your Java file in the left-pane to give it maximum screen coverage. Adjust the sizes of the panes by dragging the borders of each pane division."
},
{
"code": null,
"e": 11819,
"s": 11768,
"text": "The final product should look something like this:"
},
{
"code": null,
"e": 11915,
"s": 11819,
"text": "Tip: You can switch quickly between panes using Ctrl + PgUp and Ctrl + PgDown key combinations."
},
{
"code": null,
"e": 11933,
"s": 11915,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 11943,
"s": 11933,
"text": "user_aryg"
},
{
"code": null,
"e": 11952,
"s": 11943,
"text": "gabaa406"
},
{
"code": null,
"e": 11959,
"s": 11952,
"text": "Java 8"
},
{
"code": null,
"e": 11988,
"s": 11959,
"text": "Java-Competitive-Programming"
},
{
"code": null,
"e": 12012,
"s": 11988,
"text": "Competitive Programming"
},
{
"code": null,
"e": 12017,
"s": 12012,
"text": "Java"
},
{
"code": null,
"e": 12022,
"s": 12017,
"text": "Java"
}
] |
Java program to expand a String if range is given?
|
29 Sep, 2021
Suppose we have given a string in which some ranges as specified and we have to place the numbers which is between the given range in the specified place as provided and depicted in the illustration below as follows for a better understanding.
Illustration:
Input : string x = "1-5, 8, 11-14, 18, 20, 26-29"
Output : string y = "1, 2, 3, 4, 5, 8, 11, 12,
13, 14, 18, 20, 26, 27, 28, 29"
Approach:
In order to solve the above problem, we can follow the below approach:
First, we have to split the String into String[] array. We have to split the String where we found – symbol.
Now we have a String[] array with the elements. Now we just go to the first index last element i.e. 1 and the preceding index first element of the String[] array say it be 5.
After that with the help of for loop, we can add the numbers which are between 1 and 5 and store them in the String variable.
The above process continues till the length of the string array.
Note:
With the help of Collections and various utility methods we can solve the problem easily but Collections concept is not a good option performance-wise. If we go through Collections, performance is reduced and time complexity is also increased.There in the below program we explicitly define our own split method and logic.
Implementation:
Here we will now be proposing and discussing all three scenarios with help of clean java program as follows:
Example 1
Java
// Java program to Expand a String if Range is Given // Main classpublic class Solution { // Main driver method public static void expand(String word) { // Creating an object of StringBuffer class to // make a modifiable string object StringBuilder sb = new StringBuilder(); // Get all intervals String[] strArr = word.split(", "); // Traverse through every interval for (int i = 0; i < strArr.length; i++) { // Get lower and upper String[] a = strArr[i].split("-"); // Setting high and low counters if (a.length == 2) { int low = Integer.parseInt(a[0]); int high = Integer.parseInt(a[a.length - 1]); // Condition check holds true // Till low counter is lesser or equal to // high counter while (low <= high) { // Append all numbers sb.append(low + " "); low++; } } // If we reaches here then // High counter exceeds lower counter else { sb.append(strArr[i] + " "); } } // Print the modifiable string System.out.println(sb.toString()); } // Method 2 // Main driver method public static void main(String args[]) { // Custom input string as input String s = "1-5, 8, 11-14, 18, 20, 26-29"; expand(s); }}
1 2 3 4 5 8 11 12 13 14 18 20 26 27 28 29
Example 2
Java
// Java Program to Illustrate Expansion of String // Main classpublic class StringExpand { // Method 1 // To split the string static String[] split(String st) { // Count how many words in our string // Irrespective of spaces int wc = countWords(st); String w[] = new String[wc]; char[] c = st.toCharArray(); int k = 0; for (int i = 0; i < c.length; i++) { // Initially declaring and initializing // string as empty String s = ""; // Whenever we found an non-space character while (i < c.length && c[i] != ' ') { // Concat with the String s // Increment the value of i s = s + c[i]; i++; } // If the String is not empty if (s.length() != 0) { // Add the String to the String[] // array w[k] = s; k++; } } // Returning the string array return w; } // Method 2 // To count the number of words in a string static int countWords(String str) { int count = 0; for (int i = 0; i < str.length(); i++) { // The below condition to check // whether the first character is // space or not if (i == 0 && str.charAt(i) != ' ' || str.charAt(i) != ' ' && str.charAt(i - 1) == ' ') { count++; } } // Returning the count return count; } // Method 3 // To expand the string public static void expand(String s) { String p = s; String[] arr = p.split("\\-"); String k = ""; // Traversing over array using for loop for (int i = 0; i < arr.length; i++) { // Case 1 if (i != arr.length - 1) { String[] arr1 = arr[i].split(", "); String[] arr2 = arr[i + 1].split(", "); int a = Integer.parseInt( arr1[arr1.length - 1]); int b = Integer.parseInt(arr2[0]); for (int j = a + 1; j < b; j++) { arr[i] = arr[i] + ", " + j; } } // Case 2 if (k != "") k = k + ", " + arr[i]; // Case 3 else k = k + arr[i]; } // Print the expanded string System.out.println(k); } // Method 4 // Main driver method public static void main(String[] args) { // Custom string input String s = "1-5, 8, 11-14, 18, 20, 26-29"; // Calling the method 3 to // expand the string expand(s); }}
1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29
Example 3
Java
// Java program to Expand a String if Range is Given // Main class// GenerateStringOnRangeclass GFG { // Method 1 // To generate string on range public static String generateStringOn(String input) { String[] words = input.split(" "); // Initially setting up range String[] ranges = null; int number = 0; // Creating a StringBuffer object so that // we can modify the string StringBuffer buffer = new StringBuffer(); // Looking out for words by // iterating using for each loop for (String word : words) { // To be replaced by // using replace() method word = word.replace(",", ""); // If word is containing "-" character if (word.contains("-")) { ranges = word.split("-"); number = Integer.parseInt(ranges[0]); // Till number is within range while (number <= Integer.parseInt(ranges[1])) { // Append , in between them buffer.append(number + ", "); number++; } } // If we reaches here then // word does contains "-" else { buffer.append(word + ", "); } } // Return the StringBuffer object return buffer.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string String input = "1-5, 8, 11-14, 18, 20, 26-29"; // Calling the method 1 as created above System.out.println(generateStringOn(input)); }}
1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29,
rahulkumarverma0507
rohitraghav1296
simranarora5sos
Java-String-Programs
Java-Strings
Java
Strings
Java-Strings
Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
Stream In Java
Write a program to reverse an array or string
Write a program to print all permutations of a given string
C++ Data Types
Check for Balanced Brackets in an expression (well-formedness) using Stack
Longest Common Subsequence | DP-4
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 296,
"s": 52,
"text": "Suppose we have given a string in which some ranges as specified and we have to place the numbers which is between the given range in the specified place as provided and depicted in the illustration below as follows for a better understanding."
},
{
"code": null,
"e": 311,
"s": 296,
"text": "Illustration: "
},
{
"code": null,
"e": 463,
"s": 311,
"text": "Input : string x = \"1-5, 8, 11-14, 18, 20, 26-29\" \nOutput : string y = \"1, 2, 3, 4, 5, 8, 11, 12, \n 13, 14, 18, 20, 26, 27, 28, 29\""
},
{
"code": null,
"e": 474,
"s": 463,
"text": "Approach: "
},
{
"code": null,
"e": 546,
"s": 474,
"text": "In order to solve the above problem, we can follow the below approach: "
},
{
"code": null,
"e": 655,
"s": 546,
"text": "First, we have to split the String into String[] array. We have to split the String where we found – symbol."
},
{
"code": null,
"e": 830,
"s": 655,
"text": "Now we have a String[] array with the elements. Now we just go to the first index last element i.e. 1 and the preceding index first element of the String[] array say it be 5."
},
{
"code": null,
"e": 956,
"s": 830,
"text": "After that with the help of for loop, we can add the numbers which are between 1 and 5 and store them in the String variable."
},
{
"code": null,
"e": 1021,
"s": 956,
"text": "The above process continues till the length of the string array."
},
{
"code": null,
"e": 1028,
"s": 1021,
"text": "Note: "
},
{
"code": null,
"e": 1351,
"s": 1028,
"text": "With the help of Collections and various utility methods we can solve the problem easily but Collections concept is not a good option performance-wise. If we go through Collections, performance is reduced and time complexity is also increased.There in the below program we explicitly define our own split method and logic."
},
{
"code": null,
"e": 1367,
"s": 1351,
"text": "Implementation:"
},
{
"code": null,
"e": 1476,
"s": 1367,
"text": "Here we will now be proposing and discussing all three scenarios with help of clean java program as follows:"
},
{
"code": null,
"e": 1486,
"s": 1476,
"text": "Example 1"
},
{
"code": null,
"e": 1491,
"s": 1486,
"text": "Java"
},
{
"code": "// Java program to Expand a String if Range is Given // Main classpublic class Solution { // Main driver method public static void expand(String word) { // Creating an object of StringBuffer class to // make a modifiable string object StringBuilder sb = new StringBuilder(); // Get all intervals String[] strArr = word.split(\", \"); // Traverse through every interval for (int i = 0; i < strArr.length; i++) { // Get lower and upper String[] a = strArr[i].split(\"-\"); // Setting high and low counters if (a.length == 2) { int low = Integer.parseInt(a[0]); int high = Integer.parseInt(a[a.length - 1]); // Condition check holds true // Till low counter is lesser or equal to // high counter while (low <= high) { // Append all numbers sb.append(low + \" \"); low++; } } // If we reaches here then // High counter exceeds lower counter else { sb.append(strArr[i] + \" \"); } } // Print the modifiable string System.out.println(sb.toString()); } // Method 2 // Main driver method public static void main(String args[]) { // Custom input string as input String s = \"1-5, 8, 11-14, 18, 20, 26-29\"; expand(s); }}",
"e": 3019,
"s": 1491,
"text": null
},
{
"code": null,
"e": 3061,
"s": 3019,
"text": "1 2 3 4 5 8 11 12 13 14 18 20 26 27 28 29"
},
{
"code": null,
"e": 3073,
"s": 3063,
"text": "Example 2"
},
{
"code": null,
"e": 3078,
"s": 3073,
"text": "Java"
},
{
"code": "// Java Program to Illustrate Expansion of String // Main classpublic class StringExpand { // Method 1 // To split the string static String[] split(String st) { // Count how many words in our string // Irrespective of spaces int wc = countWords(st); String w[] = new String[wc]; char[] c = st.toCharArray(); int k = 0; for (int i = 0; i < c.length; i++) { // Initially declaring and initializing // string as empty String s = \"\"; // Whenever we found an non-space character while (i < c.length && c[i] != ' ') { // Concat with the String s // Increment the value of i s = s + c[i]; i++; } // If the String is not empty if (s.length() != 0) { // Add the String to the String[] // array w[k] = s; k++; } } // Returning the string array return w; } // Method 2 // To count the number of words in a string static int countWords(String str) { int count = 0; for (int i = 0; i < str.length(); i++) { // The below condition to check // whether the first character is // space or not if (i == 0 && str.charAt(i) != ' ' || str.charAt(i) != ' ' && str.charAt(i - 1) == ' ') { count++; } } // Returning the count return count; } // Method 3 // To expand the string public static void expand(String s) { String p = s; String[] arr = p.split(\"\\\\-\"); String k = \"\"; // Traversing over array using for loop for (int i = 0; i < arr.length; i++) { // Case 1 if (i != arr.length - 1) { String[] arr1 = arr[i].split(\", \"); String[] arr2 = arr[i + 1].split(\", \"); int a = Integer.parseInt( arr1[arr1.length - 1]); int b = Integer.parseInt(arr2[0]); for (int j = a + 1; j < b; j++) { arr[i] = arr[i] + \", \" + j; } } // Case 2 if (k != \"\") k = k + \", \" + arr[i]; // Case 3 else k = k + arr[i]; } // Print the expanded string System.out.println(k); } // Method 4 // Main driver method public static void main(String[] args) { // Custom string input String s = \"1-5, 8, 11-14, 18, 20, 26-29\"; // Calling the method 3 to // expand the string expand(s); }}",
"e": 5848,
"s": 3078,
"text": null
},
{
"code": null,
"e": 5905,
"s": 5848,
"text": "1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29"
},
{
"code": null,
"e": 5917,
"s": 5907,
"text": "Example 3"
},
{
"code": null,
"e": 5922,
"s": 5917,
"text": "Java"
},
{
"code": "// Java program to Expand a String if Range is Given // Main class// GenerateStringOnRangeclass GFG { // Method 1 // To generate string on range public static String generateStringOn(String input) { String[] words = input.split(\" \"); // Initially setting up range String[] ranges = null; int number = 0; // Creating a StringBuffer object so that // we can modify the string StringBuffer buffer = new StringBuffer(); // Looking out for words by // iterating using for each loop for (String word : words) { // To be replaced by // using replace() method word = word.replace(\",\", \"\"); // If word is containing \"-\" character if (word.contains(\"-\")) { ranges = word.split(\"-\"); number = Integer.parseInt(ranges[0]); // Till number is within range while (number <= Integer.parseInt(ranges[1])) { // Append , in between them buffer.append(number + \", \"); number++; } } // If we reaches here then // word does contains \"-\" else { buffer.append(word + \", \"); } } // Return the StringBuffer object return buffer.toString(); } // Method 2 // Main driver method public static void main(String[] args) { // Custom input string String input = \"1-5, 8, 11-14, 18, 20, 26-29\"; // Calling the method 1 as created above System.out.println(generateStringOn(input)); }}",
"e": 7644,
"s": 5922,
"text": null
},
{
"code": null,
"e": 7703,
"s": 7644,
"text": "1, 2, 3, 4, 5, 8, 11, 12, 13, 14, 18, 20, 26, 27, 28, 29, "
},
{
"code": null,
"e": 7723,
"s": 7703,
"text": "rahulkumarverma0507"
},
{
"code": null,
"e": 7739,
"s": 7723,
"text": "rohitraghav1296"
},
{
"code": null,
"e": 7755,
"s": 7739,
"text": "simranarora5sos"
},
{
"code": null,
"e": 7776,
"s": 7755,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 7789,
"s": 7776,
"text": "Java-Strings"
},
{
"code": null,
"e": 7794,
"s": 7789,
"text": "Java"
},
{
"code": null,
"e": 7802,
"s": 7794,
"text": "Strings"
},
{
"code": null,
"e": 7815,
"s": 7802,
"text": "Java-Strings"
},
{
"code": null,
"e": 7823,
"s": 7815,
"text": "Strings"
},
{
"code": null,
"e": 7828,
"s": 7823,
"text": "Java"
},
{
"code": null,
"e": 7926,
"s": 7828,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7977,
"s": 7926,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 8008,
"s": 7977,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 8027,
"s": 8008,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 8057,
"s": 8027,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 8072,
"s": 8057,
"text": "Stream In Java"
},
{
"code": null,
"e": 8118,
"s": 8072,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 8178,
"s": 8118,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 8193,
"s": 8178,
"text": "C++ Data Types"
},
{
"code": null,
"e": 8268,
"s": 8193,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
}
] |
isspace() in C/C++ and its application to count whitespace characters
|
15 Jun, 2022
isspace() function In C++, isspace is a predefined function used for string and character handling.cstring is the header file required for string functions and cctype is the headerfile required for character functions. This function is used to check if the argument contains any whitespace characters. There are many types of whitespace characters in c++ such as-
‘ ‘ – Space
‘\t’ – Horizontal tab
‘\n’ – Newline
‘\v’ – Vertical tab
‘\f’ – Feed
‘\r’ – Carriage return
Syntax :
int isspace(int x)
x : x is character to be checked
Application Given a string, we need to count the number of whitespace characters in the string using isspace() function. Examples:
Input : string = 'Geeks for geeks'
Output : 2
Input :string = 'My name is Ayush'
Output : 3
C++
C
// C++ program to illustrate// isspace() function #include <iostream>using namespace std; int main(){ // taking input char ch = ' '; // checking is it space? if (isspace(ch)) cout << "\nEntered character is space"; else cout << "\nEntered character is not space"; return 0;} // This code is contributed by sarajadhav12052009
// C program to illustrate// isspace() function#include <ctype.h>#include <stdio.h>int main(){ // taking input char ch = ' '; // checking is it space? if (isspace(ch)) printf("\nEntered character is space"); else printf("\nEntered character is not space");}
Output :
Entered character is space
Application: isspace() function is used to find number of spaces in a given sentence. Examples:
Input : This is a good website
Output : Number of spaces in the sentence is : 4
Input : heyy this is geeksforgeeks
Output : Number of spaces in the sentence is : 3
Input : hello how can I help you
Output : Number of spaces in the sentence is : 5
Algorithm 1. Traverse the given string character by character upto its length, check if character is a whitespace character. 2. If it is a whitespace character, increment the counter by 1, else traverse to the next character. 3. Print the value of the counter.
C++
C
// C++ program to illustrate// isspace() function #include <iostream>using namespace std; // Function for counting spacesint cnt_space(int i, int count, char ch){ // input sentence char buf[50] = "Geeks for Geeks"; ch = buf[0]; // counting spaces while (ch != '\0') { ch = buf[i]; if (isspace(ch)) count++; i++; } // returning number of spaces return (count);}int main(){ char ch; int i = 0, count = 0; // Calling function count = cnt_space(i, count, ch); // printing number of spaces cout << "\nNumber of spaces in the sentence is : " << count; return 0;} // This code is contributed by sarajadhav12052009
// C program to illustrate// isspace() function#include <ctype.h>#include <stdio.h> // Function for counting spacesint cnt_space(int i, int count, char ch){ // input sentence char buf[50] = "Geeks for Geeks"; ch = buf[0]; // counting spaces while (ch != '\0') { ch = buf[i]; if (isspace(ch)) count++; i++; } // returning number of spaces return (count);}int main(){ char ch; int i = 0, count = 0; // Calling function count = cnt_space(i, count, ch); // printing number of spaces printf("\nNumber of spaces in the sentence is : %d", count); return 0;}
Output:
Number of spaces in the sentence is : 2
CPP
// CPP program to count white spaces in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate whitespacesvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (isspace(c)) count++; } cout << count;} // Driver Codeint main(){ string str = "Geeks for geeks"; space(str); return 0;}
Output:
2
This article is contributed by Ayush Saxena and Kanchan Ray. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ManasChhabra2
sarajadhav12052009
C-String
CPP-Library
cpp-string
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Multidimensional Arrays in C / C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
Vector in C++ STL
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
Priority Queue in C++ Standard Template Library (STL)
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jun, 2022"
},
{
"code": null,
"e": 416,
"s": 52,
"text": "isspace() function In C++, isspace is a predefined function used for string and character handling.cstring is the header file required for string functions and cctype is the headerfile required for character functions. This function is used to check if the argument contains any whitespace characters. There are many types of whitespace characters in c++ such as-"
},
{
"code": null,
"e": 428,
"s": 416,
"text": "‘ ‘ – Space"
},
{
"code": null,
"e": 450,
"s": 428,
"text": "‘\\t’ – Horizontal tab"
},
{
"code": null,
"e": 465,
"s": 450,
"text": "‘\\n’ – Newline"
},
{
"code": null,
"e": 485,
"s": 465,
"text": "‘\\v’ – Vertical tab"
},
{
"code": null,
"e": 497,
"s": 485,
"text": "‘\\f’ – Feed"
},
{
"code": null,
"e": 520,
"s": 497,
"text": "‘\\r’ – Carriage return"
},
{
"code": null,
"e": 581,
"s": 520,
"text": "Syntax :\nint isspace(int x)\nx : x is character to be checked"
},
{
"code": null,
"e": 712,
"s": 581,
"text": "Application Given a string, we need to count the number of whitespace characters in the string using isspace() function. Examples:"
},
{
"code": null,
"e": 805,
"s": 712,
"text": "Input : string = 'Geeks for geeks'\nOutput : 2\n\nInput :string = 'My name is Ayush'\nOutput : 3"
},
{
"code": null,
"e": 809,
"s": 805,
"text": "C++"
},
{
"code": null,
"e": 811,
"s": 809,
"text": "C"
},
{
"code": "// C++ program to illustrate// isspace() function #include <iostream>using namespace std; int main(){ // taking input char ch = ' '; // checking is it space? if (isspace(ch)) cout << \"\\nEntered character is space\"; else cout << \"\\nEntered character is not space\"; return 0;} // This code is contributed by sarajadhav12052009",
"e": 1172,
"s": 811,
"text": null
},
{
"code": "// C program to illustrate// isspace() function#include <ctype.h>#include <stdio.h>int main(){ // taking input char ch = ' '; // checking is it space? if (isspace(ch)) printf(\"\\nEntered character is space\"); else printf(\"\\nEntered character is not space\");}",
"e": 1460,
"s": 1172,
"text": null
},
{
"code": null,
"e": 1469,
"s": 1460,
"text": "Output :"
},
{
"code": null,
"e": 1496,
"s": 1469,
"text": "Entered character is space"
},
{
"code": null,
"e": 1592,
"s": 1496,
"text": "Application: isspace() function is used to find number of spaces in a given sentence. Examples:"
},
{
"code": null,
"e": 1840,
"s": 1592,
"text": "Input : This is a good website\nOutput : Number of spaces in the sentence is : 4\n\nInput : heyy this is geeksforgeeks\nOutput : Number of spaces in the sentence is : 3\n\nInput : hello how can I help you\nOutput : Number of spaces in the sentence is : 5"
},
{
"code": null,
"e": 2102,
"s": 1840,
"text": "Algorithm 1. Traverse the given string character by character upto its length, check if character is a whitespace character. 2. If it is a whitespace character, increment the counter by 1, else traverse to the next character. 3. Print the value of the counter. "
},
{
"code": null,
"e": 2106,
"s": 2102,
"text": "C++"
},
{
"code": null,
"e": 2108,
"s": 2106,
"text": "C"
},
{
"code": "// C++ program to illustrate// isspace() function #include <iostream>using namespace std; // Function for counting spacesint cnt_space(int i, int count, char ch){ // input sentence char buf[50] = \"Geeks for Geeks\"; ch = buf[0]; // counting spaces while (ch != '\\0') { ch = buf[i]; if (isspace(ch)) count++; i++; } // returning number of spaces return (count);}int main(){ char ch; int i = 0, count = 0; // Calling function count = cnt_space(i, count, ch); // printing number of spaces cout << \"\\nNumber of spaces in the sentence is : \" << count; return 0;} // This code is contributed by sarajadhav12052009",
"e": 2800,
"s": 2108,
"text": null
},
{
"code": "// C program to illustrate// isspace() function#include <ctype.h>#include <stdio.h> // Function for counting spacesint cnt_space(int i, int count, char ch){ // input sentence char buf[50] = \"Geeks for Geeks\"; ch = buf[0]; // counting spaces while (ch != '\\0') { ch = buf[i]; if (isspace(ch)) count++; i++; } // returning number of spaces return (count);}int main(){ char ch; int i = 0, count = 0; // Calling function count = cnt_space(i, count, ch); // printing number of spaces printf(\"\\nNumber of spaces in the sentence is : %d\", count); return 0;}",
"e": 3436,
"s": 2800,
"text": null
},
{
"code": null,
"e": 3444,
"s": 3436,
"text": "Output:"
},
{
"code": null,
"e": 3484,
"s": 3444,
"text": "Number of spaces in the sentence is : 2"
},
{
"code": null,
"e": 3488,
"s": 3484,
"text": "CPP"
},
{
"code": "// CPP program to count white spaces in a string#include <iostream>#include <cstring>#include <cctype>using namespace std; // function to calculate whitespacesvoid space(string& str){ int count = 0; int length = str.length(); for (int i = 0; i < length; i++) { int c = str[i]; if (isspace(c)) count++; } cout << count;} // Driver Codeint main(){ string str = \"Geeks for geeks\"; space(str); return 0;}",
"e": 3938,
"s": 3488,
"text": null
},
{
"code": null,
"e": 3946,
"s": 3938,
"text": "Output:"
},
{
"code": null,
"e": 3948,
"s": 3946,
"text": "2"
},
{
"code": null,
"e": 4385,
"s": 3948,
"text": "This article is contributed by Ayush Saxena and Kanchan Ray. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4399,
"s": 4385,
"text": "ManasChhabra2"
},
{
"code": null,
"e": 4418,
"s": 4399,
"text": "sarajadhav12052009"
},
{
"code": null,
"e": 4427,
"s": 4418,
"text": "C-String"
},
{
"code": null,
"e": 4439,
"s": 4427,
"text": "CPP-Library"
},
{
"code": null,
"e": 4450,
"s": 4439,
"text": "cpp-string"
},
{
"code": null,
"e": 4461,
"s": 4450,
"text": "C Language"
},
{
"code": null,
"e": 4465,
"s": 4461,
"text": "C++"
},
{
"code": null,
"e": 4469,
"s": 4465,
"text": "CPP"
},
{
"code": null,
"e": 4567,
"s": 4469,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4584,
"s": 4567,
"text": "Substring in C++"
},
{
"code": null,
"e": 4619,
"s": 4584,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 4641,
"s": 4619,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 4687,
"s": 4641,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 4732,
"s": 4687,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4750,
"s": 4732,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 4793,
"s": 4750,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4839,
"s": 4793,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4882,
"s": 4839,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
How to Make Java Regular Expression Case Insensitive in Java?
|
09 Mar, 2021
In this article, we will learn how to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract data from character sequences. Java Regular Expressions are case-sensitive by default. But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are two ways to make Regular Expression case-insensitive:
Using CASE_INSENSITIVE flagUsing modifier
Using CASE_INSENSITIVE flag
Using modifier
1. Using CASE_INSENSITIVE flag: The compile method of the Pattern class takes the CASE_INSENSITIVE flag along with the pattern to make the Expression case-insensitive. Below is the implementation:
Java
// Java program demonstrate How to make Java// Regular Expression case insensitive in Javaimport java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { public static void main(String[] args) { // String String str = "From GFG class. Welcome to gfg."; // Create pattern to match along // with the flag CASE_INSENSITIVE Pattern patrn = Pattern.compile( "gfg", Pattern.CASE_INSENSITIVE); // All metched patrn from str case // insensitive or case sensitive Matcher match = patrn.matcher(str); while (match.find()) { // Print matched Patterns System.out.println(match.group()); } }}
GFG
gfg
2. Using modifier: The ” ?i “ modifier used to make a Java Regular Expression case-insensitive. So to make the Java Regular Expression case-insensitive we pass the pattern along with the ” ?i ” modifier that makes it case-insensitive. Below is the implementation:
Java
// Java program demonstrate How to make Java// Regular Expression case insensitive in Javaimport java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { public static void main(String[] args) { // String String str = "From GFG class. Welcome to gfg."; // Create pattern to match along // with the ?i modifier Pattern patrn = Pattern.compile("(?i)gfg"); // All metched patrn from str case // insensitive or case sensitive Matcher match = patrn.matcher(str); while (match.find()) { // Print matched Patterns System.out.println(match.group()); } }}
GFG
gfg
java-regular-expression
Picked
How To
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Set Git Username and Password in GitBash?
How to Install Jupyter Notebook on MacOS?
How to Install and Use NVM on Windows?
How to Install Python Packages for AWS Lambda Layers?
How to Add External JAR File to an IntelliJ IDEA Project?
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
Reverse a string in Java
Object Oriented Programming (OOPs) Concept in Java
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2021"
},
{
"code": null,
"e": 431,
"s": 28,
"text": "In this article, we will learn how to make Java Regular Expression case-insensitive in Java. Java Regular Expression is used to find, match, and extract data from character sequences. Java Regular Expressions are case-sensitive by default. But with the help of Regular Expression, we can make the Java Regular Expression case-insensitive. There are two ways to make Regular Expression case-insensitive:"
},
{
"code": null,
"e": 473,
"s": 431,
"text": "Using CASE_INSENSITIVE flagUsing modifier"
},
{
"code": null,
"e": 501,
"s": 473,
"text": "Using CASE_INSENSITIVE flag"
},
{
"code": null,
"e": 516,
"s": 501,
"text": "Using modifier"
},
{
"code": null,
"e": 713,
"s": 516,
"text": "1. Using CASE_INSENSITIVE flag: The compile method of the Pattern class takes the CASE_INSENSITIVE flag along with the pattern to make the Expression case-insensitive. Below is the implementation:"
},
{
"code": null,
"e": 718,
"s": 713,
"text": "Java"
},
{
"code": "// Java program demonstrate How to make Java// Regular Expression case insensitive in Javaimport java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { public static void main(String[] args) { // String String str = \"From GFG class. Welcome to gfg.\"; // Create pattern to match along // with the flag CASE_INSENSITIVE Pattern patrn = Pattern.compile( \"gfg\", Pattern.CASE_INSENSITIVE); // All metched patrn from str case // insensitive or case sensitive Matcher match = patrn.matcher(str); while (match.find()) { // Print matched Patterns System.out.println(match.group()); } }}",
"e": 1430,
"s": 718,
"text": null
},
{
"code": null,
"e": 1438,
"s": 1430,
"text": "GFG\ngfg"
},
{
"code": null,
"e": 1702,
"s": 1438,
"text": "2. Using modifier: The ” ?i “ modifier used to make a Java Regular Expression case-insensitive. So to make the Java Regular Expression case-insensitive we pass the pattern along with the ” ?i ” modifier that makes it case-insensitive. Below is the implementation:"
},
{
"code": null,
"e": 1707,
"s": 1702,
"text": "Java"
},
{
"code": "// Java program demonstrate How to make Java// Regular Expression case insensitive in Javaimport java.util.regex.Matcher;import java.util.regex.Pattern; class GFG { public static void main(String[] args) { // String String str = \"From GFG class. Welcome to gfg.\"; // Create pattern to match along // with the ?i modifier Pattern patrn = Pattern.compile(\"(?i)gfg\"); // All metched patrn from str case // insensitive or case sensitive Matcher match = patrn.matcher(str); while (match.find()) { // Print matched Patterns System.out.println(match.group()); } }}",
"e": 2375,
"s": 1707,
"text": null
},
{
"code": null,
"e": 2383,
"s": 2375,
"text": "GFG\ngfg"
},
{
"code": null,
"e": 2407,
"s": 2383,
"text": "java-regular-expression"
},
{
"code": null,
"e": 2414,
"s": 2407,
"text": "Picked"
},
{
"code": null,
"e": 2421,
"s": 2414,
"text": "How To"
},
{
"code": null,
"e": 2426,
"s": 2421,
"text": "Java"
},
{
"code": null,
"e": 2431,
"s": 2426,
"text": "Java"
},
{
"code": null,
"e": 2529,
"s": 2431,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2578,
"s": 2529,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2620,
"s": 2578,
"text": "How to Install Jupyter Notebook on MacOS?"
},
{
"code": null,
"e": 2659,
"s": 2620,
"text": "How to Install and Use NVM on Windows?"
},
{
"code": null,
"e": 2713,
"s": 2659,
"text": "How to Install Python Packages for AWS Lambda Layers?"
},
{
"code": null,
"e": 2771,
"s": 2713,
"text": "How to Add External JAR File to an IntelliJ IDEA Project?"
},
{
"code": null,
"e": 2786,
"s": 2771,
"text": "Arrays in Java"
},
{
"code": null,
"e": 2830,
"s": 2786,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 2866,
"s": 2830,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 2891,
"s": 2866,
"text": "Reverse a string in Java"
}
] |
Combinational Sum
|
23 Jun, 2022
Given an array of positive integers arr[] and a sum x, find all unique combinations in arr[] where the sum is equal to x. The same repeated number may be chosen from arr[] unlimited number of times. Elements in a combination (a1, a2, ..., ak) must be printed in non-descending order. (ie, a1 <= a2 <= ... <= ak). The combinations themselves must be sorted in ascending order, i.e., the combination with smallest first element should be printed first. If there is no combination possible the print “Empty” (without quotes).
Examples:
Input : arr[] = 2, 4, 6, 8
x = 8
Output : [2, 2, 2, 2]
[2, 2, 4]
[2, 6]
[4, 4]
[8]
Since the problem is to get all the possible results, not the best or the number of result, thus we don’t need to consider DP(dynamic programming), recursion is needed to handle it.
We should use the following algorithm.
1. Sort the array(non-decreasing).
2. First remove all the duplicates from array.
3. Then use recursion and backtracking to solve
the problem.
(A) If at any time sub-problem sum == 0 then
add that array to the result (vector of
vectors).
(B) Else if sum is negative then ignore that
sub-problem.
(C) Else insert the present index in that
array to the current vector and call
the function with sum = sum-ar[index] and
index = index, then pop that element from
current index (backtrack) and call the
function with sum = sum and index = index+1
Below is the C++ implementation of the above steps.
C++
Java
Python3
C#
Javascript
// C++ program to find all combinations that// sum to a given value#include <bits/stdc++.h>using namespace std; // Print all members of ar[] that have givenvoid findNumbers(vector<int>& ar, int sum, vector<vector<int> >& res, vector<int>& r, int i){ // if we get exact answer if (sum == 0) { res.push_back(r); return; } // Recur for all remaining elements that // have value smaller than sum. while (i < ar.size() && sum - ar[i] >= 0) { // Till every element in the array starting // from i which can contribute to the sum r.push_back(ar[i]); // add them to list // recursive call for next numbers findNumbers(ar, sum - ar[i], res, r, i); i++; // Remove number from list (backtracking) r.pop_back(); }} // Returns all combinations// of ar[] that have given// sum.vector<vector<int> > combinationSum(vector<int>& ar, int sum){ // sort input array sort(ar.begin(), ar.end()); // remove duplicates ar.erase(unique(ar.begin(), ar.end()), ar.end()); vector<int> r; vector<vector<int> > res; findNumbers(ar, sum, res, r, 0); return res;} // Driver codeint main(){ vector<int> ar; ar.push_back(2); ar.push_back(4); ar.push_back(6); ar.push_back(8); int n = ar.size(); int sum = 8; // set value of sum vector<vector<int> > res = combinationSum(ar, sum); // If result is empty, then if (res.size() == 0) { cout << "Empty"; return 0; } // Print all combinations stored in res. for (int i = 0; i < res.size(); i++) { if (res[i].size() > 0) { cout << " ( "; for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << " "; cout << ")"; } } return 0;}
// Java program to find all combinations that// sum to a given valueimport java.io.*;import java.util.*; class GFG { static ArrayList<ArrayList<Integer> > combinationSum(ArrayList<Integer> arr, int sum) { ArrayList<ArrayList<Integer> > ans = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); // first do hashing since hashset does not always // sort // removing the duplicates using HashSet and // Sorting the arrayList Set<Integer> set = new HashSet<>(arr); arr.clear(); arr.addAll(set); Collections.sort(arr); findNumbers(ans, arr, sum, 0, temp); return ans; } static void findNumbers(ArrayList<ArrayList<Integer> > ans, ArrayList<Integer> arr, int sum, int index, ArrayList<Integer> temp) { if (sum == 0) { // Adding deep copy of list to ans ans.add(new ArrayList<>(temp)); return; } for (int i = index; i < arr.size(); i++) { // checking that sum does not become negative if ((sum - arr.get(i)) >= 0) { // adding element which can contribute to // sum temp.add(arr.get(i)); findNumbers(ans, arr, sum - arr.get(i), i, temp); // removing element from list (backtracking) temp.remove(arr.get(i)); } } } // Driver Code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(); arr.add(2); arr.add(4); arr.add(6); arr.add(8); int sum = 8; ArrayList<ArrayList<Integer> > ans = combinationSum(arr, sum); // If result is empty, then if (ans.size() == 0) { System.out.println("Empty"); return; } // print all combinations stored in ans for (int i = 0; i < ans.size(); i++) { System.out.print("("); for (int j = 0; j < ans.get(i).size(); j++) { System.out.print(ans.get(i).get(j) + " "); } System.out.print(") "); } }}
# Python3 program to find all combinations that# sum to a given value def combinationSum(arr, sum): ans = [] temp = [] # first do hashing nothing but set{} # since set does not always sort # removing the duplicates using Set and # Sorting the List arr = sorted(list(set(arr))) findNumbers(ans, arr, temp, sum, 0) return ans def findNumbers(ans, arr, temp, sum, index): if(sum == 0): # Adding deep copy of list to ans ans.append(list(temp)) return # Iterate from index to len(arr) - 1 for i in range(index, len(arr)): # checking that sum does not become negative if(sum - arr[i]) >= 0: # adding element which can contribute to # sum temp.append(arr[i]) findNumbers(ans, arr, temp, sum-arr[i], i) # removing element from list (backtracking) temp.remove(arr[i]) # Driver Codearr = [2, 4, 6, 8]sum = 8ans = combinationSum(arr, sum) # If result is empty, thenif len(ans) <= 0: print("empty") # print all combinations stored in ansfor i in range(len(ans)): print("(", end=' ') for j in range(len(ans[i])): print(str(ans[i][j])+" ", end=' ') print(")", end=' ') # This Code Is Contributed by Rakesh(vijayarigela09)
// C# program for the above approachusing System;using System.Collections.Generic;using System.Collections; class GFG { static List<List<int> > combinationSum(List<int> arr, int sum) { List<List<int> > ans = new List<List<int> >(); List<int> temp = new List<int>(); // first do hashing since hashset does not always // sort // removing the duplicates using HashSet and // Sorting the List HashSet<int> set = new HashSet<int>(arr); arr.Clear(); arr.AddRange(set); arr.Sort(); findNumbers(ans, arr, sum, 0, temp); return ans; } static void findNumbers(List<List<int> > ans, List<int> arr, int sum, int index, List<int> temp) { if (sum == 0) { // Adding deep copy of list to ans ans.Add(new List<int>(temp)); return; } for (int i = index; i < arr.Count; i++) { // checking that sum does not become negative if ((sum - arr[i]) >= 0) { // Adding element which can contribute to // sum temp.Add(arr[i]); findNumbers(ans, arr, sum - arr[i], i, temp); // removing element from list (backtracking) temp.Remove(arr[i]); } } } // Driver Code public static void Main() { List<int> arr = new List<int>(); arr.Add(2); arr.Add(4); arr.Add(6); arr.Add(8); int sum = 8; List<List<int> > ans = combinationSum(arr, sum); // If result is empty, then if (ans.Count == 0) { Console.WriteLine("Empty"); return; } // print all combinations stored in ans for (int i = 0; i < ans.Count; i++) { Console.Write("("); for (int j = 0; j < ans[i].Count; j++) { Console.Write(ans[i][j] + " "); } Console.Write(") "); } }} // This code is contributed by ShubhamSingh10
<script>// Javascript program to find all combinations that// sum to a given value function combinationSum(arr, sum) { let ans = new Array(); let temp = new Array(); // first do hashing since hashset does not always // sort // removing the duplicates using HashSet and // Sorting the arrayList let set = new Set([...arr]); arr = [...set]; arr.sort() findNumbers(ans, arr, sum, 0, temp); return ans;} function findNumbers(ans, arr, sum, index, temp) { if (sum == 0) { // pushing deep copy of list to ans ans.push([...temp]); return; } for (let i = index; i < arr.length; i++) { // checking that sum does not become negative if ((sum - arr[i]) >= 0) { // pushing element which can contribute to // sum temp.push(arr[i]); findNumbers(ans, arr, sum - arr[i], i, temp); // removing element from list (backtracking) temp.splice(temp.indexOf(arr[i]), 1); } }} // Driver Code let arr = [] arr.push(2);arr.push(4);arr.push(6);arr.push(8); let sum = 8; let ans = combinationSum(arr, sum); // If result is empty, thenif (ans.length == 0) { document.write("Empty");} // print all combinations stored in ansfor (let i = 0; i < ans.length; i++) { document.write("("); for (let j = 0; j < ans[i].length; j++) { document.write(" ", ans[i][j] + " "); } document.write(") ");} // This code is contributed by saurabh_jaiswal.</script>
( 2 2 2 2 ) ( 2 2 4 ) ( 2 6 ) ( 4 4 ) ( 8 )
Time Complexity: O(n2), where n is the size of array.
Auxiliary Space: O(n2)
This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
ss801101
msharma04
ashishrajput1952
rakesh419
NikitaRana07
SHUBHAMSINGH10
girikgarg8
_saurabh_jaiswal
raghav_maheshwari
shivamanandrj9
Adobe
Amazon
Microsoft
Backtracking
Combinatorial
Recursion
Amazon
Microsoft
Adobe
Recursion
Combinatorial
Backtracking
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)
Generate all the binary strings of N bits
Print all paths from a given source to a destination
Print all permutations of a string in Java
Find if there is a path of more than k length from a source
Permutation and Combination in Python
Factorial of a large number
Count of subsets with sum equal to X
itertools.combinations() module in Python to print all possible combinations
Program to calculate value of nCr
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Jun, 2022"
},
{
"code": null,
"e": 577,
"s": 54,
"text": "Given an array of positive integers arr[] and a sum x, find all unique combinations in arr[] where the sum is equal to x. The same repeated number may be chosen from arr[] unlimited number of times. Elements in a combination (a1, a2, ..., ak) must be printed in non-descending order. (ie, a1 <= a2 <= ... <= ak). The combinations themselves must be sorted in ascending order, i.e., the combination with smallest first element should be printed first. If there is no combination possible the print “Empty” (without quotes)."
},
{
"code": null,
"e": 588,
"s": 577,
"text": "Examples: "
},
{
"code": null,
"e": 720,
"s": 588,
"text": "Input : arr[] = 2, 4, 6, 8 \n x = 8\nOutput : [2, 2, 2, 2]\n [2, 2, 4]\n [2, 6]\n [4, 4]\n [8]"
},
{
"code": null,
"e": 902,
"s": 720,
"text": "Since the problem is to get all the possible results, not the best or the number of result, thus we don’t need to consider DP(dynamic programming), recursion is needed to handle it."
},
{
"code": null,
"e": 942,
"s": 902,
"text": "We should use the following algorithm. "
},
{
"code": null,
"e": 1560,
"s": 942,
"text": "1. Sort the array(non-decreasing).\n2. First remove all the duplicates from array.\n3. Then use recursion and backtracking to solve \n the problem.\n (A) If at any time sub-problem sum == 0 then \n add that array to the result (vector of \n vectors).\n (B) Else if sum is negative then ignore that \n sub-problem.\n (C) Else insert the present index in that \n array to the current vector and call \n the function with sum = sum-ar[index] and\n index = index, then pop that element from \n current index (backtrack) and call the \n function with sum = sum and index = index+1"
},
{
"code": null,
"e": 1612,
"s": 1560,
"text": "Below is the C++ implementation of the above steps."
},
{
"code": null,
"e": 1616,
"s": 1612,
"text": "C++"
},
{
"code": null,
"e": 1621,
"s": 1616,
"text": "Java"
},
{
"code": null,
"e": 1629,
"s": 1621,
"text": "Python3"
},
{
"code": null,
"e": 1632,
"s": 1629,
"text": "C#"
},
{
"code": null,
"e": 1643,
"s": 1632,
"text": "Javascript"
},
{
"code": "// C++ program to find all combinations that// sum to a given value#include <bits/stdc++.h>using namespace std; // Print all members of ar[] that have givenvoid findNumbers(vector<int>& ar, int sum, vector<vector<int> >& res, vector<int>& r, int i){ // if we get exact answer if (sum == 0) { res.push_back(r); return; } // Recur for all remaining elements that // have value smaller than sum. while (i < ar.size() && sum - ar[i] >= 0) { // Till every element in the array starting // from i which can contribute to the sum r.push_back(ar[i]); // add them to list // recursive call for next numbers findNumbers(ar, sum - ar[i], res, r, i); i++; // Remove number from list (backtracking) r.pop_back(); }} // Returns all combinations// of ar[] that have given// sum.vector<vector<int> > combinationSum(vector<int>& ar, int sum){ // sort input array sort(ar.begin(), ar.end()); // remove duplicates ar.erase(unique(ar.begin(), ar.end()), ar.end()); vector<int> r; vector<vector<int> > res; findNumbers(ar, sum, res, r, 0); return res;} // Driver codeint main(){ vector<int> ar; ar.push_back(2); ar.push_back(4); ar.push_back(6); ar.push_back(8); int n = ar.size(); int sum = 8; // set value of sum vector<vector<int> > res = combinationSum(ar, sum); // If result is empty, then if (res.size() == 0) { cout << \"Empty\"; return 0; } // Print all combinations stored in res. for (int i = 0; i < res.size(); i++) { if (res[i].size() > 0) { cout << \" ( \"; for (int j = 0; j < res[i].size(); j++) cout << res[i][j] << \" \"; cout << \")\"; } } return 0;}",
"e": 3494,
"s": 1643,
"text": null
},
{
"code": "// Java program to find all combinations that// sum to a given valueimport java.io.*;import java.util.*; class GFG { static ArrayList<ArrayList<Integer> > combinationSum(ArrayList<Integer> arr, int sum) { ArrayList<ArrayList<Integer> > ans = new ArrayList<>(); ArrayList<Integer> temp = new ArrayList<>(); // first do hashing since hashset does not always // sort // removing the duplicates using HashSet and // Sorting the arrayList Set<Integer> set = new HashSet<>(arr); arr.clear(); arr.addAll(set); Collections.sort(arr); findNumbers(ans, arr, sum, 0, temp); return ans; } static void findNumbers(ArrayList<ArrayList<Integer> > ans, ArrayList<Integer> arr, int sum, int index, ArrayList<Integer> temp) { if (sum == 0) { // Adding deep copy of list to ans ans.add(new ArrayList<>(temp)); return; } for (int i = index; i < arr.size(); i++) { // checking that sum does not become negative if ((sum - arr.get(i)) >= 0) { // adding element which can contribute to // sum temp.add(arr.get(i)); findNumbers(ans, arr, sum - arr.get(i), i, temp); // removing element from list (backtracking) temp.remove(arr.get(i)); } } } // Driver Code public static void main(String[] args) { ArrayList<Integer> arr = new ArrayList<>(); arr.add(2); arr.add(4); arr.add(6); arr.add(8); int sum = 8; ArrayList<ArrayList<Integer> > ans = combinationSum(arr, sum); // If result is empty, then if (ans.size() == 0) { System.out.println(\"Empty\"); return; } // print all combinations stored in ans for (int i = 0; i < ans.size(); i++) { System.out.print(\"(\"); for (int j = 0; j < ans.get(i).size(); j++) { System.out.print(ans.get(i).get(j) + \" \"); } System.out.print(\") \"); } }}",
"e": 5728,
"s": 3494,
"text": null
},
{
"code": "# Python3 program to find all combinations that# sum to a given value def combinationSum(arr, sum): ans = [] temp = [] # first do hashing nothing but set{} # since set does not always sort # removing the duplicates using Set and # Sorting the List arr = sorted(list(set(arr))) findNumbers(ans, arr, temp, sum, 0) return ans def findNumbers(ans, arr, temp, sum, index): if(sum == 0): # Adding deep copy of list to ans ans.append(list(temp)) return # Iterate from index to len(arr) - 1 for i in range(index, len(arr)): # checking that sum does not become negative if(sum - arr[i]) >= 0: # adding element which can contribute to # sum temp.append(arr[i]) findNumbers(ans, arr, temp, sum-arr[i], i) # removing element from list (backtracking) temp.remove(arr[i]) # Driver Codearr = [2, 4, 6, 8]sum = 8ans = combinationSum(arr, sum) # If result is empty, thenif len(ans) <= 0: print(\"empty\") # print all combinations stored in ansfor i in range(len(ans)): print(\"(\", end=' ') for j in range(len(ans[i])): print(str(ans[i][j])+\" \", end=' ') print(\")\", end=' ') # This Code Is Contributed by Rakesh(vijayarigela09)",
"e": 7024,
"s": 5728,
"text": null
},
{
"code": "// C# program for the above approachusing System;using System.Collections.Generic;using System.Collections; class GFG { static List<List<int> > combinationSum(List<int> arr, int sum) { List<List<int> > ans = new List<List<int> >(); List<int> temp = new List<int>(); // first do hashing since hashset does not always // sort // removing the duplicates using HashSet and // Sorting the List HashSet<int> set = new HashSet<int>(arr); arr.Clear(); arr.AddRange(set); arr.Sort(); findNumbers(ans, arr, sum, 0, temp); return ans; } static void findNumbers(List<List<int> > ans, List<int> arr, int sum, int index, List<int> temp) { if (sum == 0) { // Adding deep copy of list to ans ans.Add(new List<int>(temp)); return; } for (int i = index; i < arr.Count; i++) { // checking that sum does not become negative if ((sum - arr[i]) >= 0) { // Adding element which can contribute to // sum temp.Add(arr[i]); findNumbers(ans, arr, sum - arr[i], i, temp); // removing element from list (backtracking) temp.Remove(arr[i]); } } } // Driver Code public static void Main() { List<int> arr = new List<int>(); arr.Add(2); arr.Add(4); arr.Add(6); arr.Add(8); int sum = 8; List<List<int> > ans = combinationSum(arr, sum); // If result is empty, then if (ans.Count == 0) { Console.WriteLine(\"Empty\"); return; } // print all combinations stored in ans for (int i = 0; i < ans.Count; i++) { Console.Write(\"(\"); for (int j = 0; j < ans[i].Count; j++) { Console.Write(ans[i][j] + \" \"); } Console.Write(\") \"); } }} // This code is contributed by ShubhamSingh10",
"e": 9147,
"s": 7024,
"text": null
},
{
"code": "<script>// Javascript program to find all combinations that// sum to a given value function combinationSum(arr, sum) { let ans = new Array(); let temp = new Array(); // first do hashing since hashset does not always // sort // removing the duplicates using HashSet and // Sorting the arrayList let set = new Set([...arr]); arr = [...set]; arr.sort() findNumbers(ans, arr, sum, 0, temp); return ans;} function findNumbers(ans, arr, sum, index, temp) { if (sum == 0) { // pushing deep copy of list to ans ans.push([...temp]); return; } for (let i = index; i < arr.length; i++) { // checking that sum does not become negative if ((sum - arr[i]) >= 0) { // pushing element which can contribute to // sum temp.push(arr[i]); findNumbers(ans, arr, sum - arr[i], i, temp); // removing element from list (backtracking) temp.splice(temp.indexOf(arr[i]), 1); } }} // Driver Code let arr = [] arr.push(2);arr.push(4);arr.push(6);arr.push(8); let sum = 8; let ans = combinationSum(arr, sum); // If result is empty, thenif (ans.length == 0) { document.write(\"Empty\");} // print all combinations stored in ansfor (let i = 0; i < ans.length; i++) { document.write(\"(\"); for (let j = 0; j < ans[i].length; j++) { document.write(\" \", ans[i][j] + \" \"); } document.write(\") \");} // This code is contributed by saurabh_jaiswal.</script>",
"e": 10654,
"s": 9147,
"text": null
},
{
"code": null,
"e": 10699,
"s": 10654,
"text": " ( 2 2 2 2 ) ( 2 2 4 ) ( 2 6 ) ( 4 4 ) ( 8 )"
},
{
"code": null,
"e": 10753,
"s": 10699,
"text": "Time Complexity: O(n2), where n is the size of array."
},
{
"code": null,
"e": 10776,
"s": 10753,
"text": "Auxiliary Space: O(n2)"
},
{
"code": null,
"e": 11209,
"s": 10776,
"text": "This article is contributed by Aditya Nihal Kumar Singh. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 11218,
"s": 11209,
"text": "ss801101"
},
{
"code": null,
"e": 11228,
"s": 11218,
"text": "msharma04"
},
{
"code": null,
"e": 11245,
"s": 11228,
"text": "ashishrajput1952"
},
{
"code": null,
"e": 11255,
"s": 11245,
"text": "rakesh419"
},
{
"code": null,
"e": 11268,
"s": 11255,
"text": "NikitaRana07"
},
{
"code": null,
"e": 11283,
"s": 11268,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 11294,
"s": 11283,
"text": "girikgarg8"
},
{
"code": null,
"e": 11311,
"s": 11294,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 11329,
"s": 11311,
"text": "raghav_maheshwari"
},
{
"code": null,
"e": 11344,
"s": 11329,
"text": "shivamanandrj9"
},
{
"code": null,
"e": 11350,
"s": 11344,
"text": "Adobe"
},
{
"code": null,
"e": 11357,
"s": 11350,
"text": "Amazon"
},
{
"code": null,
"e": 11367,
"s": 11357,
"text": "Microsoft"
},
{
"code": null,
"e": 11380,
"s": 11367,
"text": "Backtracking"
},
{
"code": null,
"e": 11394,
"s": 11380,
"text": "Combinatorial"
},
{
"code": null,
"e": 11404,
"s": 11394,
"text": "Recursion"
},
{
"code": null,
"e": 11411,
"s": 11404,
"text": "Amazon"
},
{
"code": null,
"e": 11421,
"s": 11411,
"text": "Microsoft"
},
{
"code": null,
"e": 11427,
"s": 11421,
"text": "Adobe"
},
{
"code": null,
"e": 11437,
"s": 11427,
"text": "Recursion"
},
{
"code": null,
"e": 11451,
"s": 11437,
"text": "Combinatorial"
},
{
"code": null,
"e": 11464,
"s": 11451,
"text": "Backtracking"
},
{
"code": null,
"e": 11562,
"s": 11464,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 11647,
"s": 11562,
"text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)"
},
{
"code": null,
"e": 11689,
"s": 11647,
"text": "Generate all the binary strings of N bits"
},
{
"code": null,
"e": 11742,
"s": 11689,
"text": "Print all paths from a given source to a destination"
},
{
"code": null,
"e": 11785,
"s": 11742,
"text": "Print all permutations of a string in Java"
},
{
"code": null,
"e": 11845,
"s": 11785,
"text": "Find if there is a path of more than k length from a source"
},
{
"code": null,
"e": 11883,
"s": 11845,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 11911,
"s": 11883,
"text": "Factorial of a large number"
},
{
"code": null,
"e": 11948,
"s": 11911,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 12025,
"s": 11948,
"text": "itertools.combinations() module in Python to print all possible combinations"
}
] |
Types of Schedules in DBMS
|
04 Feb, 2020
Schedule, as the name suggests, is a process of lining the transactions and executing them one by one. When there are multiple transactions that are running in a concurrent manner and the order of operation is needed to be set so that the operations do not overlap each other, Scheduling is brought into play and the transactions are timed accordingly. The basics of Transactions and Schedules is discussed in Concurrency Control (Introduction), and Transaction Isolation Levels in DBMS articles. Here we will discuss various types of schedules.
Serial Schedules:Schedules in which the transactions are executed non-interleaved, i.e., a serial schedule is one in which no transaction starts until a running transaction has ended are called serial schedules.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(B)W(B)R(A)R(B)where R(A) denotes that a read operation is performed on some data item ‘A’This is a serial schedule since the transactions perform serially in the order T1 —> T2Non-Serial Schedule:This is a type of Scheduling where the operations of multiple transactions are interleaved. This might lead to a rise in the concurrency problem. The transactions are executed in a non-serial manner, keeping the end result correct and same as the serial schedule. Unlike the serial schedule where one transaction must wait for another to complete all its operation, in the non-serial schedule, the other transaction proceeds without waiting for the previous transaction to complete. This sort of schedule does not provide any benefit of the concurrent transaction. It can be of two types namely, Serializable and Non-Serializable Schedule.The Non-Serial Schedule can be divided further into Serializable and Non-Serializable.Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
Serial Schedules:Schedules in which the transactions are executed non-interleaved, i.e., a serial schedule is one in which no transaction starts until a running transaction has ended are called serial schedules.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(B)W(B)R(A)R(B)where R(A) denotes that a read operation is performed on some data item ‘A’This is a serial schedule since the transactions perform serially in the order T1 —> T2
Example: Consider the following schedule involving two transactions T1 and T2.
where R(A) denotes that a read operation is performed on some data item ‘A’This is a serial schedule since the transactions perform serially in the order T1 —> T2
Non-Serial Schedule:This is a type of Scheduling where the operations of multiple transactions are interleaved. This might lead to a rise in the concurrency problem. The transactions are executed in a non-serial manner, keeping the end result correct and same as the serial schedule. Unlike the serial schedule where one transaction must wait for another to complete all its operation, in the non-serial schedule, the other transaction proceeds without waiting for the previous transaction to complete. This sort of schedule does not provide any benefit of the concurrent transaction. It can be of two types namely, Serializable and Non-Serializable Schedule.The Non-Serial Schedule can be divided further into Serializable and Non-Serializable.Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
The Non-Serial Schedule can be divided further into Serializable and Non-Serializable.
Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.
Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.
Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operation
They belong to different transactions
They operate on the same data item
At Least one of them is a write operation
View Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.
Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.
Example – Consider the following schedule involving two transactions T1 and T2.
This is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.
There can be three types of recoverable schedule:
Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.
Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:
Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:
Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.
In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.
Example: Consider the following schedule involving two transactions T1 and T2.
This schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.
Example: Consider the following schedule involving two transactions T1 and T2.
It is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.
Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.
Example: Consider the following schedule involving two transactions T1 and T2.
This is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.
Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
T2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable.
Note – It can be seen that:
Cascadeless schedules are stricter than recoverable schedules or are a subset of recoverable schedules.Strict schedules are stricter than cascadeless schedules or are a subset of cascadeless schedules.Serial schedules satisfy constraints of all recoverable, cascadeless and strict schedules and hence is a subset of strict schedules.
Cascadeless schedules are stricter than recoverable schedules or are a subset of recoverable schedules.
Strict schedules are stricter than cascadeless schedules or are a subset of cascadeless schedules.
Serial schedules satisfy constraints of all recoverable, cascadeless and strict schedules and hence is a subset of strict schedules.
The relation between various types of schedules can be depicted as:
Example: Consider the following schedule:
S:R1(A), W2(A), Commit2, W1(A), W3(A), Commit3, Commit1
Which of the following is true?(A) The schedule is view serializable schedule and strict recoverable schedule(B) The schedule is non-serializable schedule and strict recoverable schedule(C) The schedule is non-serializable schedule and is not strict recoverable schedule.(D) The Schedule is serializable schedule and is not strict recoverable schedule
Solution: The schedule can be re-written as:-
First of all, it is a view serializable schedule as it has view equal serial schedule T1 —> T2 —> T3 which satisfies the initial and updated reads and final write on variable A which is required for view serializability. Now we can see there is write – write pair done by transactions T1 followed by T3 which is violating the above-mentioned condition of strict schedules as T3 is supposed to do write operation only after T1 commits which is violated in the given schedule. Hence the given schedule is serializable but not strict recoverable.So, option (D) is correct.
singhpriansh
DBMS
GATE CS
DBMS
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
SQL | Join (Inner, Left, Right and Full Joins)
SQL | WITH clause
SQL query to find second highest salary?
CTE in SQL
Difference between Clustered and Non-clustered index
Layers of OSI Model
TCP/IP Model
Types of Operating Systems
Page Replacement Algorithms in Operating Systems
Inter Process Communication (IPC)
|
[
{
"code": null,
"e": 54,
"s": 26,
"text": "\n04 Feb, 2020"
},
{
"code": null,
"e": 600,
"s": 54,
"text": "Schedule, as the name suggests, is a process of lining the transactions and executing them one by one. When there are multiple transactions that are running in a concurrent manner and the order of operation is needed to be set so that the operations do not overlap each other, Scheduling is brought into play and the transactions are timed accordingly. The basics of Transactions and Schedules is discussed in Concurrency Control (Introduction), and Transaction Isolation Levels in DBMS articles. Here we will discuss various types of schedules."
},
{
"code": null,
"e": 6126,
"s": 600,
"text": "Serial Schedules:Schedules in which the transactions are executed non-interleaved, i.e., a serial schedule is one in which no transaction starts until a running transaction has ended are called serial schedules.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(B)W(B)R(A)R(B)where R(A) denotes that a read operation is performed on some data item ‘A’This is a serial schedule since the transactions perform serially in the order T1 —> T2Non-Serial Schedule:This is a type of Scheduling where the operations of multiple transactions are interleaved. This might lead to a rise in the concurrency problem. The transactions are executed in a non-serial manner, keeping the end result correct and same as the serial schedule. Unlike the serial schedule where one transaction must wait for another to complete all its operation, in the non-serial schedule, the other transaction proceeds without waiting for the previous transaction to complete. This sort of schedule does not provide any benefit of the concurrent transaction. It can be of two types namely, Serializable and Non-Serializable Schedule.The Non-Serial Schedule can be divided further into Serializable and Non-Serializable.Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 6606,
"s": 6126,
"text": "Serial Schedules:Schedules in which the transactions are executed non-interleaved, i.e., a serial schedule is one in which no transaction starts until a running transaction has ended are called serial schedules.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(B)W(B)R(A)R(B)where R(A) denotes that a read operation is performed on some data item ‘A’This is a serial schedule since the transactions perform serially in the order T1 —> T2"
},
{
"code": null,
"e": 6685,
"s": 6606,
"text": "Example: Consider the following schedule involving two transactions T1 and T2."
},
{
"code": null,
"e": 6848,
"s": 6685,
"text": "where R(A) denotes that a read operation is performed on some data item ‘A’This is a serial schedule since the transactions perform serially in the order T1 —> T2"
},
{
"code": null,
"e": 11895,
"s": 6848,
"text": "Non-Serial Schedule:This is a type of Scheduling where the operations of multiple transactions are interleaved. This might lead to a rise in the concurrency problem. The transactions are executed in a non-serial manner, keeping the end result correct and same as the serial schedule. Unlike the serial schedule where one transaction must wait for another to complete all its operation, in the non-serial schedule, the other transaction proceeds without waiting for the previous transaction to complete. This sort of schedule does not provide any benefit of the concurrent transaction. It can be of two types namely, Serializable and Non-Serializable Schedule.The Non-Serial Schedule can be divided further into Serializable and Non-Serializable.Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 11982,
"s": 11895,
"text": "The Non-Serial Schedule can be divided further into Serializable and Non-Serializable."
},
{
"code": null,
"e": 16284,
"s": 11982,
"text": "Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable.Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 17598,
"s": 16284,
"text": "Serializable:This is used to maintain the consistency of the database. It is mainly used in the Non-Serial scheduling to verify whether the scheduling will lead to any inconsistency or not. On the other hand, a serial schedule does not need the serializability because it follows a transaction only when the previous transaction is complete. The non-serial schedule is said to be in a serializable schedule only when it is equivalent to the serial schedules, for an n number of transactions. Since concurrency is allowed in this case thus, multiple transactions can execute concurrently. A serializable schedule helps in improving both resource utilization and CPU throughput. These are of two types:Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable."
},
{
"code": null,
"e": 18212,
"s": 17598,
"text": "Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operationView Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable."
},
{
"code": null,
"e": 18546,
"s": 18212,
"text": "Conflict Serializable:A schedule is called conflict serializable if it can be transformed into a serial schedule by swapping non-conflicting operations. Two operations are said to be conflicting if all conditions satisfy:They belong to different transactionsThey operate on the same data itemAt Least one of them is a write operation"
},
{
"code": null,
"e": 18584,
"s": 18546,
"text": "They belong to different transactions"
},
{
"code": null,
"e": 18619,
"s": 18584,
"text": "They operate on the same data item"
},
{
"code": null,
"e": 18661,
"s": 18619,
"text": "At Least one of them is a write operation"
},
{
"code": null,
"e": 18942,
"s": 18661,
"text": "View Serializable:A Schedule is called view serializable if it is view equal to a serial schedule (no overlapping transactions). A conflict schedule is a view serializable but if the serializability contains blind writes, then the view serializable does not conflict serializable."
},
{
"code": null,
"e": 21931,
"s": 18942,
"text": "Non-Serializable:The non-serializable schedule is divided into two types, Recoverable and Non-recoverable Schedule.Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 24805,
"s": 21931,
"text": "Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1.Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 27376,
"s": 24805,
"text": "Recoverable Schedule:Schedules in which transactions commit only after all transactions whose changes they read commit are called recoverable schedules. In other words, if some transaction Tj is reading value updated or written by some other transaction Ti, then the commit of Tj must occur after the commit of Ti.Example – Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitcommitThis is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct.There can be three types of recoverable schedule:Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1."
},
{
"code": null,
"e": 27456,
"s": 27376,
"text": "Example – Consider the following schedule involving two transactions T1 and T2."
},
{
"code": null,
"e": 27556,
"s": 27456,
"text": "This is a recoverable schedule since T1 commits before T2, that makes the value read by T2 correct."
},
{
"code": null,
"e": 27606,
"s": 27556,
"text": "There can be three types of recoverable schedule:"
},
{
"code": null,
"e": 29604,
"s": 27606,
"text": "Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1.Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1."
},
{
"code": null,
"e": 29883,
"s": 29604,
"text": "Cascading Schedule:Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:"
},
{
"code": null,
"e": 30143,
"s": 29883,
"text": "Also called Avoids cascading aborts/rollbacks (ACA). When there is a failure in one transaction and this leads to the rolling back or aborting other dependent transactions, then such scheduling is referred to as Cascading rollback or cascading abort. Example:"
},
{
"code": null,
"e": 31300,
"s": 30143,
"text": "Cascadeless Schedule:Schedules in which transactions read values only after all transactions whose changes they are going to read commit are called cascadeless schedules. Avoids that a single transaction abort leads to a series of transaction rollbacks. A strategy to prevent cascading aborts is to disallow a transaction from reading uncommitted changes from another transaction in the same schedule.In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)commitR(A)commitThis schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)R(A)W(A)abortabortIt is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1."
},
{
"code": null,
"e": 31467,
"s": 31300,
"text": "In other words, if some transaction Tj wants to read value updated or written by some other transaction Ti, then the commit of Tj must read it after the commit of Ti."
},
{
"code": null,
"e": 31546,
"s": 31467,
"text": "Example: Consider the following schedule involving two transactions T1 and T2."
},
{
"code": null,
"e": 31672,
"s": 31546,
"text": "This schedule is cascadeless. Since the updated value of A is read by T2 only after the updating transaction i.e. T1 commits."
},
{
"code": null,
"e": 31751,
"s": 31672,
"text": "Example: Consider the following schedule involving two transactions T1 and T2."
},
{
"code": null,
"e": 31998,
"s": 31751,
"text": "It is a recoverable schedule but it does not avoid cascading aborts. It can be seen that if T1 aborts, T2 will have to be aborted too in order to maintain the correctness of the schedule as T2 has already read the uncommitted value written by T1."
},
{
"code": null,
"e": 32562,
"s": 31998,
"text": "Strict Schedule:A schedule is strict if for any two transactions Ti, Tj, if a write operation of Ti precedes a conflicting operation of Tj (either read or write), then the commit or abort event of Ti also precedes that conflicting operation of Tj.In other words, Tj can read or write updated or written value of Ti only after Ti commits/aborts.Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)R(A)W(A)commitW(A)R(A)commitThis is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1."
},
{
"code": null,
"e": 32641,
"s": 32562,
"text": "Example: Consider the following schedule involving two transactions T1 and T2."
},
{
"code": null,
"e": 32747,
"s": 32641,
"text": "This is a strict schedule since T2 reads and writes A which is written by T1 only after the commit of T1."
},
{
"code": null,
"e": 33051,
"s": 32747,
"text": "Non-Recoverable Schedule:Example: Consider the following schedule involving two transactions T1 and T2.T1T2R(A)W(A)W(A)R(A)commitabortT2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 33221,
"s": 33051,
"text": "T2 read the value of A written by T1, and committed. T1 later aborted, therefore the value read by T2 is wrong, but since T2 committed, this schedule is non-recoverable."
},
{
"code": null,
"e": 33249,
"s": 33221,
"text": "Note – It can be seen that:"
},
{
"code": null,
"e": 33583,
"s": 33249,
"text": "Cascadeless schedules are stricter than recoverable schedules or are a subset of recoverable schedules.Strict schedules are stricter than cascadeless schedules or are a subset of cascadeless schedules.Serial schedules satisfy constraints of all recoverable, cascadeless and strict schedules and hence is a subset of strict schedules."
},
{
"code": null,
"e": 33687,
"s": 33583,
"text": "Cascadeless schedules are stricter than recoverable schedules or are a subset of recoverable schedules."
},
{
"code": null,
"e": 33786,
"s": 33687,
"text": "Strict schedules are stricter than cascadeless schedules or are a subset of cascadeless schedules."
},
{
"code": null,
"e": 33919,
"s": 33786,
"text": "Serial schedules satisfy constraints of all recoverable, cascadeless and strict schedules and hence is a subset of strict schedules."
},
{
"code": null,
"e": 33987,
"s": 33919,
"text": "The relation between various types of schedules can be depicted as:"
},
{
"code": null,
"e": 34029,
"s": 33987,
"text": "Example: Consider the following schedule:"
},
{
"code": null,
"e": 34086,
"s": 34029,
"text": "S:R1(A), W2(A), Commit2, W1(A), W3(A), Commit3, Commit1 "
},
{
"code": null,
"e": 34438,
"s": 34086,
"text": "Which of the following is true?(A) The schedule is view serializable schedule and strict recoverable schedule(B) The schedule is non-serializable schedule and strict recoverable schedule(C) The schedule is non-serializable schedule and is not strict recoverable schedule.(D) The Schedule is serializable schedule and is not strict recoverable schedule"
},
{
"code": null,
"e": 34484,
"s": 34438,
"text": "Solution: The schedule can be re-written as:-"
},
{
"code": null,
"e": 35054,
"s": 34484,
"text": "First of all, it is a view serializable schedule as it has view equal serial schedule T1 —> T2 —> T3 which satisfies the initial and updated reads and final write on variable A which is required for view serializability. Now we can see there is write – write pair done by transactions T1 followed by T3 which is violating the above-mentioned condition of strict schedules as T3 is supposed to do write operation only after T1 commits which is violated in the given schedule. Hence the given schedule is serializable but not strict recoverable.So, option (D) is correct."
},
{
"code": null,
"e": 35067,
"s": 35054,
"text": "singhpriansh"
},
{
"code": null,
"e": 35072,
"s": 35067,
"text": "DBMS"
},
{
"code": null,
"e": 35080,
"s": 35072,
"text": "GATE CS"
},
{
"code": null,
"e": 35085,
"s": 35080,
"text": "DBMS"
},
{
"code": null,
"e": 35183,
"s": 35085,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35230,
"s": 35183,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 35248,
"s": 35230,
"text": "SQL | WITH clause"
},
{
"code": null,
"e": 35289,
"s": 35248,
"text": "SQL query to find second highest salary?"
},
{
"code": null,
"e": 35300,
"s": 35289,
"text": "CTE in SQL"
},
{
"code": null,
"e": 35353,
"s": 35300,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 35373,
"s": 35353,
"text": "Layers of OSI Model"
},
{
"code": null,
"e": 35386,
"s": 35373,
"text": "TCP/IP Model"
},
{
"code": null,
"e": 35413,
"s": 35386,
"text": "Types of Operating Systems"
},
{
"code": null,
"e": 35462,
"s": 35413,
"text": "Page Replacement Algorithms in Operating Systems"
}
] |
ReactJS Evergreen Toaster Component
|
11 Jun, 2021
React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. Toaster Component allows the user to show an ephemeral message as an overlay. We can use the following approach in ReactJS to use the Evergreen Toaster Component.
Toast Props:
zIndex: It is used to denote the z-index of the toast.
duration: It is used to denote the duration of the toast.
onRemove: It is a callback function that is triggered when the toast is all the way closed.
intent: It is used to denote the type of alert.
title: It is used to denote the title of the alert.
children: It is used to define the description of the alert.
hasCloseButton: It is used to show a close icon button inside the toast when this is set to true.
isShown: It is used to close the Toast and call onRemove when finished then this is set to false.
ToastManager Props:
bindNotify: It is a function that is triggered with the this.notify function.
bindRemove: It is a function that is triggered with the this.remove function.
bindGetToasts: It is a function that is triggered with the this.getToasts function.
bindCloseAll: It is a function that is triggered with the this.closeAll function.
Creating React Application And Installing Module:
Step 1: Create a React application using the following command:npx create-react-app foldername
Step 1: Create a React application using the following command:
npx create-react-app foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername
Step 2: After creating your project folder i.e. foldername, move to it using the following command:
cd foldername
Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui
Step 3: After creating the ReactJS application, Install the required module using the following command:
npm install evergreen-ui
Project Structure: It will look like the following.
Project Structure
Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code.
App.js
import React from 'react'import { Button, toaster } from 'evergreen-ui' export default function App() { // Function using toaster notify const customNotify = () => { toaster.notify('Greetings from GeeksforGeeks') } return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen Toaster Component</h4> <Button onClick={customNotify}> Trigger Toaster </Button> </div> );}
Step to Run Application: Run the application using the following command from the root directory of the project:
npm start
Output: Now open your browser and go to http://localhost:3000/, you will see the following output:
Reference: https://evergreen.segment.com/components/toaster
ReactJS-Evergreen
JavaScript
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
JavaScript | Promises
How to fetch data from an API in ReactJS ?
How to redirect to another page in ReactJS ?
Axios in React: A Guide for Beginners
ReactJS Functional Components
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jun, 2021"
},
{
"code": null,
"e": 368,
"s": 28,
"text": "React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. Toaster Component allows the user to show an ephemeral message as an overlay. We can use the following approach in ReactJS to use the Evergreen Toaster Component."
},
{
"code": null,
"e": 381,
"s": 368,
"text": "Toast Props:"
},
{
"code": null,
"e": 436,
"s": 381,
"text": "zIndex: It is used to denote the z-index of the toast."
},
{
"code": null,
"e": 494,
"s": 436,
"text": "duration: It is used to denote the duration of the toast."
},
{
"code": null,
"e": 586,
"s": 494,
"text": "onRemove: It is a callback function that is triggered when the toast is all the way closed."
},
{
"code": null,
"e": 634,
"s": 586,
"text": "intent: It is used to denote the type of alert."
},
{
"code": null,
"e": 686,
"s": 634,
"text": "title: It is used to denote the title of the alert."
},
{
"code": null,
"e": 747,
"s": 686,
"text": "children: It is used to define the description of the alert."
},
{
"code": null,
"e": 845,
"s": 747,
"text": "hasCloseButton: It is used to show a close icon button inside the toast when this is set to true."
},
{
"code": null,
"e": 943,
"s": 845,
"text": "isShown: It is used to close the Toast and call onRemove when finished then this is set to false."
},
{
"code": null,
"e": 963,
"s": 943,
"text": "ToastManager Props:"
},
{
"code": null,
"e": 1041,
"s": 963,
"text": "bindNotify: It is a function that is triggered with the this.notify function."
},
{
"code": null,
"e": 1119,
"s": 1041,
"text": "bindRemove: It is a function that is triggered with the this.remove function."
},
{
"code": null,
"e": 1203,
"s": 1119,
"text": "bindGetToasts: It is a function that is triggered with the this.getToasts function."
},
{
"code": null,
"e": 1285,
"s": 1203,
"text": "bindCloseAll: It is a function that is triggered with the this.closeAll function."
},
{
"code": null,
"e": 1337,
"s": 1287,
"text": "Creating React Application And Installing Module:"
},
{
"code": null,
"e": 1432,
"s": 1337,
"text": "Step 1: Create a React application using the following command:npx create-react-app foldername"
},
{
"code": null,
"e": 1496,
"s": 1432,
"text": "Step 1: Create a React application using the following command:"
},
{
"code": null,
"e": 1528,
"s": 1496,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1641,
"s": 1528,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername"
},
{
"code": null,
"e": 1741,
"s": 1641,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:"
},
{
"code": null,
"e": 1755,
"s": 1741,
"text": "cd foldername"
},
{
"code": null,
"e": 1884,
"s": 1755,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui"
},
{
"code": null,
"e": 1989,
"s": 1884,
"text": "Step 3: After creating the ReactJS application, Install the required module using the following command:"
},
{
"code": null,
"e": 2014,
"s": 1989,
"text": "npm install evergreen-ui"
},
{
"code": null,
"e": 2066,
"s": 2014,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2084,
"s": 2066,
"text": "Project Structure"
},
{
"code": null,
"e": 2214,
"s": 2084,
"text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code."
},
{
"code": null,
"e": 2221,
"s": 2214,
"text": "App.js"
},
{
"code": "import React from 'react'import { Button, toaster } from 'evergreen-ui' export default function App() { // Function using toaster notify const customNotify = () => { toaster.notify('Greetings from GeeksforGeeks') } return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen Toaster Component</h4> <Button onClick={customNotify}> Trigger Toaster </Button> </div> );}",
"e": 2674,
"s": 2221,
"text": null
},
{
"code": null,
"e": 2787,
"s": 2674,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project:"
},
{
"code": null,
"e": 2797,
"s": 2787,
"text": "npm start"
},
{
"code": null,
"e": 2896,
"s": 2797,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 2956,
"s": 2896,
"text": "Reference: https://evergreen.segment.com/components/toaster"
},
{
"code": null,
"e": 2974,
"s": 2956,
"text": "ReactJS-Evergreen"
},
{
"code": null,
"e": 2985,
"s": 2974,
"text": "JavaScript"
},
{
"code": null,
"e": 2993,
"s": 2985,
"text": "ReactJS"
},
{
"code": null,
"e": 3010,
"s": 2993,
"text": "Web Technologies"
},
{
"code": null,
"e": 3108,
"s": 3010,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3169,
"s": 3108,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 3209,
"s": 3169,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 3251,
"s": 3209,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 3292,
"s": 3251,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 3314,
"s": 3292,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 3357,
"s": 3314,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 3402,
"s": 3357,
"text": "How to redirect to another page in ReactJS ?"
},
{
"code": null,
"e": 3440,
"s": 3402,
"text": "Axios in React: A Guide for Beginners"
}
] |
Python | Sort JSON by value
|
12 Feb, 2019
Let’s see the different ways to sort the JSON data using Python.
What is JSON ?JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types.
The task is to sort the JSON first by code, then by grade and then by enrollment_no .
Code #1: Sorting in Desc order
# Python code to demonstrate sorting in JSON.import json data='''{ "Student":[ { "enrollment_no":"9915103000", "name":"JIIT", "subject":[ { "code":"DBMS", "grade":"C" } ] }, { "enrollment_no":"8815103057", "name":"JSS", "subject":[ { "code":"COA", "grade":"A" }, { "code":"CN", "grade":"A+" } ] } ]}''' # Parsing Json objectjson_parse = json.loads(data) # iterating for it in json_parse['Student']: for y in it['subject']: print(y['code'],y['grade'],it['enrollment_no'],it['name'])
Output :
DBMS C 9915103000 JIIT
COA A 8815103057 JSS
CN A+ 8815103057 JSS
Code #2 : By using External library such as Pandas (Sorting in Ascending order).
from pandas.io.json import json_normalize df = json_normalize(json_parse['Student'], 'subject', ['enrollment_no', 'name']) df.sort_values(['code', 'grade', 'enrollment_no']).reset_index(drop=True)
Output:
code grade enrollment_no name
0 CN A+ 8815103057 JSS
1 COA A 8815103057 JSS
2 DBMS C 9915103000 JIIT
JSON
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
Python | Convert string dictionary to dictionary
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n12 Feb, 2019"
},
{
"code": null,
"e": 93,
"s": 28,
"text": "Let’s see the different ways to sort the JSON data using Python."
},
{
"code": null,
"e": 541,
"s": 93,
"text": "What is JSON ?JSON (JavaScript Object Notation) is a lightweight, text-based, language-independent data exchange format that is easy for humans and machines to read and write. JSON can represent two structured types: objects and arrays. An object is an unordered collection of zero or more name/value pairs. An array is an ordered sequence of zero or more values. The values can be strings, numbers, booleans, null, and these two structured types."
},
{
"code": null,
"e": 627,
"s": 541,
"text": "The task is to sort the JSON first by code, then by grade and then by enrollment_no ."
},
{
"code": null,
"e": 658,
"s": 627,
"text": "Code #1: Sorting in Desc order"
},
{
"code": "# Python code to demonstrate sorting in JSON.import json data='''{ \"Student\":[ { \"enrollment_no\":\"9915103000\", \"name\":\"JIIT\", \"subject\":[ { \"code\":\"DBMS\", \"grade\":\"C\" } ] }, { \"enrollment_no\":\"8815103057\", \"name\":\"JSS\", \"subject\":[ { \"code\":\"COA\", \"grade\":\"A\" }, { \"code\":\"CN\", \"grade\":\"A+\" } ] } ]}''' # Parsing Json objectjson_parse = json.loads(data) # iterating for it in json_parse['Student']: for y in it['subject']: print(y['code'],y['grade'],it['enrollment_no'],it['name'])",
"e": 1410,
"s": 658,
"text": null
},
{
"code": null,
"e": 1419,
"s": 1410,
"text": "Output :"
},
{
"code": null,
"e": 1484,
"s": 1419,
"text": "DBMS C 9915103000 JIIT\nCOA A 8815103057 JSS\nCN A+ 8815103057 JSS"
},
{
"code": null,
"e": 1566,
"s": 1484,
"text": " Code #2 : By using External library such as Pandas (Sorting in Ascending order)."
},
{
"code": "from pandas.io.json import json_normalize df = json_normalize(json_parse['Student'], 'subject', ['enrollment_no', 'name']) df.sort_values(['code', 'grade', 'enrollment_no']).reset_index(drop=True)",
"e": 1815,
"s": 1566,
"text": null
},
{
"code": null,
"e": 1823,
"s": 1815,
"text": "Output:"
},
{
"code": null,
"e": 1970,
"s": 1823,
"text": " code grade enrollment_no name\n0 CN A+ 8815103057 JSS\n1 COA A 8815103057 JSS\n2 DBMS C 9915103000 JIIT"
},
{
"code": null,
"e": 1975,
"s": 1970,
"text": "JSON"
},
{
"code": null,
"e": 1982,
"s": 1975,
"text": "Python"
},
{
"code": null,
"e": 1998,
"s": 1982,
"text": "Python Programs"
},
{
"code": null,
"e": 2096,
"s": 1998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2114,
"s": 2096,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2156,
"s": 2114,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2178,
"s": 2156,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2213,
"s": 2178,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2239,
"s": 2213,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2282,
"s": 2239,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 2304,
"s": 2282,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 2343,
"s": 2304,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2381,
"s": 2343,
"text": "Python | Convert a list to dictionary"
}
] |
Java Program to Print the Smallest Element in an Array
|
27 Nov, 2020
Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type.
Example:
arr1[] = {2 , -1 , 9 , 10}
output : -1
arr2[] = {0, -10, -13, 5}
output : -13
We need to find and print the smallest value element of an array in this program.
By maintaining a min element and updating it while traversing over the whole array if we encounter a number smaller than min.By sorting an array and printing the 0th index element of the array after sorting.
By maintaining a min element and updating it while traversing over the whole array if we encounter a number smaller than min.
By sorting an array and printing the 0th index element of the array after sorting.
Approach 1: Maintaining a min element and updating it while traversing over the whole array if we encounter a number smaller than min.
Java
// Java program to print the smallest element of the array public class FindSmallestElementInArray { public static void main(String[] args) { // Either we can initialize array elements or can // get input from user. Always it is best to get // input from user and form the array int[] initializedArray = new int[] { 25, 110, 74, 75, 5 }; System.out.println("Given array "); for (int i = 0; i < initializedArray.length; i++) { System.out.println(initializedArray[i]); } // Initialize minValue with first element of array. int minValue = initializedArray[0]; // Loop through the array for (int i = 0; i < initializedArray.length; i++) { // Compare elements of array with minValue and // if condition true, make minValue to that // element if (initializedArray[i] < minValue) minValue = initializedArray[i]; } System.out.println( "Smallest element present in given array: " + minValue); }}
Given array
25
110
74
75
5
Smallest element present in given array: 5
Time Complexity: O(n)
Space Complexity: O(1)
Approach 2: By sorting an array and printing the 0th index element of the array after sorting.
Java
// Java program to print the smallest element of the array import java.util.*; public class FindSmallestElementInArray { public static void main(String[] args) { // we can initialize array elements int[] initializedArray = new int[] { 25, 110, 74, 75, 5 }; System.out.println("Given array "); for (int i = 0; i < initializedArray.length; i++) { System.out.println(initializedArray[i]); } // sort the array Arrays.sort(initializedArray); int minValue = initializedArray[0]; System.out.println( "Smallest element present in given array: " + minValue); }}
Given array
25
110
74
75
5
Smallest element present in given array: 5
Time complexity: O(NlogN) Since the time taken for sorting is NlogN, where there are N elements of the array
Space complexity: O(1)
.
Java-Array-Programs
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Nov, 2020"
},
{
"code": null,
"e": 197,
"s": 28,
"text": "Java provides a data structure, the array, which stores the collection of data of the same type. It is a fixed-size sequential collection of elements of the same type. "
},
{
"code": null,
"e": 206,
"s": 197,
"text": "Example:"
},
{
"code": null,
"e": 285,
"s": 206,
"text": "arr1[] = {2 , -1 , 9 , 10}\noutput : -1\n\narr2[] = {0, -10, -13, 5}\noutput : -13"
},
{
"code": null,
"e": 367,
"s": 285,
"text": "We need to find and print the smallest value element of an array in this program."
},
{
"code": null,
"e": 575,
"s": 367,
"text": "By maintaining a min element and updating it while traversing over the whole array if we encounter a number smaller than min.By sorting an array and printing the 0th index element of the array after sorting."
},
{
"code": null,
"e": 701,
"s": 575,
"text": "By maintaining a min element and updating it while traversing over the whole array if we encounter a number smaller than min."
},
{
"code": null,
"e": 784,
"s": 701,
"text": "By sorting an array and printing the 0th index element of the array after sorting."
},
{
"code": null,
"e": 919,
"s": 784,
"text": "Approach 1: Maintaining a min element and updating it while traversing over the whole array if we encounter a number smaller than min."
},
{
"code": null,
"e": 924,
"s": 919,
"text": "Java"
},
{
"code": "// Java program to print the smallest element of the array public class FindSmallestElementInArray { public static void main(String[] args) { // Either we can initialize array elements or can // get input from user. Always it is best to get // input from user and form the array int[] initializedArray = new int[] { 25, 110, 74, 75, 5 }; System.out.println(\"Given array \"); for (int i = 0; i < initializedArray.length; i++) { System.out.println(initializedArray[i]); } // Initialize minValue with first element of array. int minValue = initializedArray[0]; // Loop through the array for (int i = 0; i < initializedArray.length; i++) { // Compare elements of array with minValue and // if condition true, make minValue to that // element if (initializedArray[i] < minValue) minValue = initializedArray[i]; } System.out.println( \"Smallest element present in given array: \" + minValue); }}",
"e": 2035,
"s": 924,
"text": null
},
{
"code": null,
"e": 2106,
"s": 2035,
"text": "Given array \n25\n110\n74\n75\n5\nSmallest element present in given array: 5"
},
{
"code": null,
"e": 2129,
"s": 2106,
"text": "Time Complexity: O(n) "
},
{
"code": null,
"e": 2152,
"s": 2129,
"text": "Space Complexity: O(1)"
},
{
"code": null,
"e": 2247,
"s": 2152,
"text": "Approach 2: By sorting an array and printing the 0th index element of the array after sorting."
},
{
"code": null,
"e": 2252,
"s": 2247,
"text": "Java"
},
{
"code": "// Java program to print the smallest element of the array import java.util.*; public class FindSmallestElementInArray { public static void main(String[] args) { // we can initialize array elements int[] initializedArray = new int[] { 25, 110, 74, 75, 5 }; System.out.println(\"Given array \"); for (int i = 0; i < initializedArray.length; i++) { System.out.println(initializedArray[i]); } // sort the array Arrays.sort(initializedArray); int minValue = initializedArray[0]; System.out.println( \"Smallest element present in given array: \" + minValue); }}",
"e": 2958,
"s": 2252,
"text": null
},
{
"code": null,
"e": 3029,
"s": 2958,
"text": "Given array \n25\n110\n74\n75\n5\nSmallest element present in given array: 5"
},
{
"code": null,
"e": 3138,
"s": 3029,
"text": "Time complexity: O(NlogN) Since the time taken for sorting is NlogN, where there are N elements of the array"
},
{
"code": null,
"e": 3161,
"s": 3138,
"text": "Space complexity: O(1)"
},
{
"code": null,
"e": 3163,
"s": 3161,
"text": "."
},
{
"code": null,
"e": 3183,
"s": 3163,
"text": "Java-Array-Programs"
},
{
"code": null,
"e": 3190,
"s": 3183,
"text": "Picked"
},
{
"code": null,
"e": 3214,
"s": 3190,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3219,
"s": 3214,
"text": "Java"
},
{
"code": null,
"e": 3233,
"s": 3219,
"text": "Java Programs"
},
{
"code": null,
"e": 3252,
"s": 3233,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3257,
"s": 3252,
"text": "Java"
}
] |
C# | Getting the unique identifier for the current managed thread
|
01 Feb, 2019
A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ManagedThreadId to check the unique identifier for the current managed thread. Or in other words, the value of ManagedThreadId property of a thread defines uniquely that thread within its process. The value of the ManagedThreadId property does not vary according to time.
Syntax:
public int ManagedThreadId { get; }
Return Value: This property returns a value that indicates a unique identifier for this managed thread. The return type of this property is System.Int32.
Example 1:
// C# program to illustrate the // use of ManagedThreadId propertyusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread T; // Get the reference of main Thread // Using CurrentThread property T = Thread.CurrentThread; // Display the unique id of the main // thread Using ManagedThreadId property Console.WriteLine("The unique id of the main "+ "thread is: {0} ", T.ManagedThreadId); }}
Output:
The unique id of the main thread is: 1
Example 2:
// C# program to illustrate the // use of ManagedThreadId propertyusing System;using System.Threading; public class GFG { // Main method public static void Main() { // Creating and initializing threads Thread thr1 = new Thread(new ThreadStart(job)); Thread thr2 = new Thread(new ThreadStart(job)); Thread thr3 = new Thread(new ThreadStart(job)); Console.WriteLine("ManagedThreadId of thread 1 "+ "is: {0}", thr1.ManagedThreadId); Console.WriteLine("ManagedThreadId of thread 2 "+ "is: {0}", thr2.ManagedThreadId); Console.WriteLine("ManagedThreadId of thread 3 "+ "is: {0}", thr3.ManagedThreadId); // Running state thr1.Start(); thr2.Start(); thr3.Start(); } // Static method public static void job() { Thread.Sleep(2000); }}
Output:
ManagedThreadId of thread 1 is: 3
ManagedThreadId of thread 2 is: 4
ManagedThreadId of thread 3 is: 5
Reference:
https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.managedthreadid?view=netframework-4.7.2
CSharp Multithreading
CSharp Thread Class
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C# Dictionary with examples
C# | Multiple inheritance using interfaces
C# | Delegates
Introduction to .NET Framework
Differences Between .NET Core and .NET Framework
C# | Data Types
C# | Method Overriding
C# | String.IndexOf( ) Method | Set - 1
C# | Constructors
C# | Class and Object
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Feb, 2019"
},
{
"code": null,
"e": 426,
"s": 28,
"text": "A Thread class is responsible for creating and managing a thread in multi-thread programming. It provides a property known as ManagedThreadId to check the unique identifier for the current managed thread. Or in other words, the value of ManagedThreadId property of a thread defines uniquely that thread within its process. The value of the ManagedThreadId property does not vary according to time."
},
{
"code": null,
"e": 434,
"s": 426,
"text": "Syntax:"
},
{
"code": null,
"e": 470,
"s": 434,
"text": "public int ManagedThreadId { get; }"
},
{
"code": null,
"e": 624,
"s": 470,
"text": "Return Value: This property returns a value that indicates a unique identifier for this managed thread. The return type of this property is System.Int32."
},
{
"code": null,
"e": 635,
"s": 624,
"text": "Example 1:"
},
{
"code": "// C# program to illustrate the // use of ManagedThreadId propertyusing System;using System.Threading; public class GFG { // Main Method static public void Main() { Thread T; // Get the reference of main Thread // Using CurrentThread property T = Thread.CurrentThread; // Display the unique id of the main // thread Using ManagedThreadId property Console.WriteLine(\"The unique id of the main \"+ \"thread is: {0} \", T.ManagedThreadId); }}",
"e": 1157,
"s": 635,
"text": null
},
{
"code": null,
"e": 1165,
"s": 1157,
"text": "Output:"
},
{
"code": null,
"e": 1206,
"s": 1165,
"text": "The unique id of the main thread is: 1 \n"
},
{
"code": null,
"e": 1217,
"s": 1206,
"text": "Example 2:"
},
{
"code": "// C# program to illustrate the // use of ManagedThreadId propertyusing System;using System.Threading; public class GFG { // Main method public static void Main() { // Creating and initializing threads Thread thr1 = new Thread(new ThreadStart(job)); Thread thr2 = new Thread(new ThreadStart(job)); Thread thr3 = new Thread(new ThreadStart(job)); Console.WriteLine(\"ManagedThreadId of thread 1 \"+ \"is: {0}\", thr1.ManagedThreadId); Console.WriteLine(\"ManagedThreadId of thread 2 \"+ \"is: {0}\", thr2.ManagedThreadId); Console.WriteLine(\"ManagedThreadId of thread 3 \"+ \"is: {0}\", thr3.ManagedThreadId); // Running state thr1.Start(); thr2.Start(); thr3.Start(); } // Static method public static void job() { Thread.Sleep(2000); }}",
"e": 2133,
"s": 1217,
"text": null
},
{
"code": null,
"e": 2141,
"s": 2133,
"text": "Output:"
},
{
"code": null,
"e": 2244,
"s": 2141,
"text": "ManagedThreadId of thread 1 is: 3\nManagedThreadId of thread 2 is: 4\nManagedThreadId of thread 3 is: 5\n"
},
{
"code": null,
"e": 2255,
"s": 2244,
"text": "Reference:"
},
{
"code": null,
"e": 2363,
"s": 2255,
"text": "https://docs.microsoft.com/en-us/dotnet/api/system.threading.thread.managedthreadid?view=netframework-4.7.2"
},
{
"code": null,
"e": 2385,
"s": 2363,
"text": "CSharp Multithreading"
},
{
"code": null,
"e": 2405,
"s": 2385,
"text": "CSharp Thread Class"
},
{
"code": null,
"e": 2408,
"s": 2405,
"text": "C#"
},
{
"code": null,
"e": 2506,
"s": 2408,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2534,
"s": 2506,
"text": "C# Dictionary with examples"
},
{
"code": null,
"e": 2577,
"s": 2534,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2592,
"s": 2577,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2623,
"s": 2592,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2672,
"s": 2623,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2688,
"s": 2672,
"text": "C# | Data Types"
},
{
"code": null,
"e": 2711,
"s": 2688,
"text": "C# | Method Overriding"
},
{
"code": null,
"e": 2751,
"s": 2711,
"text": "C# | String.IndexOf( ) Method | Set - 1"
},
{
"code": null,
"e": 2769,
"s": 2751,
"text": "C# | Constructors"
}
] |
HTML | <select> size Attribute
|
09 May, 2019
The HTML size Attribute is used to specifies the number of visible options in a drop-down list.
Note: If the value of the size attribute is greater than 1 but lower that the number of options in a DropDown List. so the Browser will automatically add the scrollbar for specifying that there are more options to view.
Syntax:
<select size = "value"> option values...</select>
Attribute Values: It contains a numeric value which specify the number of visible options in the drop-down list. It has a Default value which is 4.
Example:
<!DOCTYPE html><html> <head> <title>HTML select size Attribute</title></head> <body> <h1 style="color: green;"> GeeksforGeeks </h1> <h2> HTML select size Attribute </h2> <p>Sorting Algorithms</p> <select size="3"> <option value="merge">merge sort</option> <option value="bubble">bubble sort</option> <option value="selection">selection sort</option> <option value="quick">quick sort</option> <option value="insertion">insertion sort</option> </select></body> </html>
Output:
Supported Browsers: The browser supported by HTML Select size Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Design a Tribute Page using HTML & CSS
HTTP headers | Content-Type
How to Insert Form Data into Database using PHP ?
Installation of Node.js on Linux
Difference between var, let and const keywords in JavaScript
How to fetch data from an API in ReactJS ?
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
|
[
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 May, 2019"
},
{
"code": null,
"e": 124,
"s": 28,
"text": "The HTML size Attribute is used to specifies the number of visible options in a drop-down list."
},
{
"code": null,
"e": 344,
"s": 124,
"text": "Note: If the value of the size attribute is greater than 1 but lower that the number of options in a DropDown List. so the Browser will automatically add the scrollbar for specifying that there are more options to view."
},
{
"code": null,
"e": 352,
"s": 344,
"text": "Syntax:"
},
{
"code": null,
"e": 403,
"s": 352,
"text": "<select size = \"value\"> option values...</select> "
},
{
"code": null,
"e": 551,
"s": 403,
"text": "Attribute Values: It contains a numeric value which specify the number of visible options in the drop-down list. It has a Default value which is 4."
},
{
"code": null,
"e": 560,
"s": 551,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>HTML select size Attribute</title></head> <body> <h1 style=\"color: green;\"> GeeksforGeeks </h1> <h2> HTML select size Attribute </h2> <p>Sorting Algorithms</p> <select size=\"3\"> <option value=\"merge\">merge sort</option> <option value=\"bubble\">bubble sort</option> <option value=\"selection\">selection sort</option> <option value=\"quick\">quick sort</option> <option value=\"insertion\">insertion sort</option> </select></body> </html>",
"e": 1125,
"s": 560,
"text": null
},
{
"code": null,
"e": 1133,
"s": 1125,
"text": "Output:"
},
{
"code": null,
"e": 1223,
"s": 1133,
"text": "Supported Browsers: The browser supported by HTML Select size Attribute are listed below:"
},
{
"code": null,
"e": 1237,
"s": 1223,
"text": "Google Chrome"
},
{
"code": null,
"e": 1255,
"s": 1237,
"text": "Internet Explorer"
},
{
"code": null,
"e": 1263,
"s": 1255,
"text": "Firefox"
},
{
"code": null,
"e": 1269,
"s": 1263,
"text": "Opera"
},
{
"code": null,
"e": 1276,
"s": 1269,
"text": "Safari"
},
{
"code": null,
"e": 1292,
"s": 1276,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 1297,
"s": 1292,
"text": "HTML"
},
{
"code": null,
"e": 1314,
"s": 1297,
"text": "Web Technologies"
},
{
"code": null,
"e": 1319,
"s": 1314,
"text": "HTML"
},
{
"code": null,
"e": 1417,
"s": 1319,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1441,
"s": 1417,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 1478,
"s": 1441,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 1517,
"s": 1478,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 1545,
"s": 1517,
"text": "HTTP headers | Content-Type"
},
{
"code": null,
"e": 1595,
"s": 1545,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 1628,
"s": 1595,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 1689,
"s": 1628,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1732,
"s": 1689,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 1804,
"s": 1732,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Node.js process.env Property
|
11 Apr, 2022
The process.env property is an inbuilt application programming interface of the process module which is used to get the user environment. Syntax:
process.env
Return Value: This property returns an object containing the user environment. Below examples illustrate the use of process.env property in Node.js: Example 1:
javascript
// Node.js program to demonstrate the// process.env Property // Include process moduleconst process = require('process'); // Printing process.env property valueconsole.log(process.env);
Output:
{ ALLUSERSPROFILE: 'C:\\ProgramData',
APPDATA: 'C:\\Users\\gekcho\\AppData\\Roaming',
cmake: 'D:\\programfiles\\Cmake\\bin\\cmake.exe',
CommonProgramFiles: 'C:\\Program Files\\Common Files',
'CommonProgramFiles(x86)': 'C:\\Program Files (x86)\\Common Files',
CommonProgramW6432: 'C:\\Program Files\\Common Files',
COMPUTERNAME: 'gekchos_lappy',
ComSpec: 'C:\\Windows\\system32\\cmd.exe',
DriverData: 'C:\\Windows\\System32\\Drivers\\DriverData',
GTK_BASEPATH: 'C:\\Program Files (x86)\\GtkSharp\\2.12\\',
HADOOP_HOME:
'C:\\Users\\gekcho\\Downloads\\Compressed\\hadoop-3.1.0\\hadoop-3.1.0\\bin',
HOMEDRIVE: 'C:',
HOMEPATH: '\\Users\\gekcho',
JAVA_HOME: 'C:\\Java\\jdk1.8.0_201',
LOCALAPPDATA: 'C:\\Users\\gekcho\\AppData\\Local',
LOGONSERVER: '\\\\gekchos_lappy',
MAGICK_HOME: 'C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick',
NUMBER_OF_PROCESSORS: '4',
OneDrive: 'C:\\Users\\gekcho\\OneDrive',
OneDriveConsumer: 'C:\\Users\\gekcho\\OneDrive',
OS: 'Windows_NT',
Path:
'C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick;
C:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;
C:\\Windows\\system32;C:\\Windows;C:\\Windows\\System32\\Wbem;
C:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;
C:\\Windows\\System32\\OpenSSH\\;D:\\programfiles\\Git\\cmd;
D:\\programfiles\\Cmake\\bin;C:\\Program Files\\nodejs\\;
C:\\Users\\gekcho\\Downloads\\Compressed\\hadoop-3.1.0\\hadoop-3.1.0\\bin;
C:\\Java\\jdk1.8.0_201\\bin;
C:\\Users\\gekcho\\Downloads\\Compressed\\spark-2.4.4-bin-hadoop2.7\\bin;
C:\\Program Files (x86)\\GtkSharp\\2.12\\bin;
C:\\Users\\gekcho\\AppData\\Local\\Microsoft\\WindowsApps;
C:\\Users\\gekcho\\AppData\\Roaming\\npm',
PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',
PROCESSOR_ARCHITECTURE: 'AMD64',
PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 142 Stepping 9, GenuineIntel',
PROCESSOR_LEVEL: '6',
PROCESSOR_REVISION: '8e09',
ProgramData: 'C:\\ProgramData',
ProgramFiles: 'C:\\Program Files',
'ProgramFiles(x86)': 'C:\\Program Files (x86)',
ProgramW6432: 'C:\\Program Files',
PROMPT: '$P$G',
PSModulePath:
'C:\\Program Files\\WindowsPowerShell\\Modules;
C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules',
PUBLIC: 'C:\\Users\\Public',
python3:
'C:\\Users\\gekcho\\AppData\\Local\\Programs\\Python\\Python37-32\\python.exe',
SESSIONNAME: 'Console',
SPARK_HOME:
'C:\\Users\\gekcho\\Downloads\\Compressed\\spark-2.4.4-bin-hadoop2.7',
SystemDrive: 'C:',
SystemRoot: 'C:\\Windows',
TEMP: 'C:\\Users\\gekcho\\AppData\\Local\\Temp',
TMP: 'C:\\Users\\gekcho\\AppData\\Local\\Temp',
USERDOMAIN: 'gekchos_lappy',
USERDOMAIN_ROAMINGPROFILE: 'gekchos_lappy',
USERNAME: 'gekcho',
USERPROFILE: 'C:\\Users\\gekcho',
windir: 'C:\\Windows' }
Example2:
javascript
// Node.js program to demonstrate the// process.env Property // Include process moduleconst process = require('process'); // Printing process.env property valuevar no_env = 0; // Calling process.envvar env = process.env; // Iterating through all returned datafor (var key in env) { // Print value console.log(key + ":\t\t\t" + env[key]); no_env++;} // Printing countconsole.log("total no of values available = " + no_env); // Accessing one by oneconsole.log("operating system: " + env['OS']);console.log("alluserprofile: " + env['ALLUSERSPROFILE']);console.log("public directory: " + env['PUBLIC']);
Output:
ALLUSERSPROFILE: C:\ProgramData
APPDATA: C:\Users\gekcho\AppData\Roaming
cmake: D:\programfiles\Cmake\bin\cmake.exe
CommonProgramFiles: C:\Program Files\Common Files
CommonProgramFiles(x86):C:\Program Files (x86)\Common Files
CommonProgramW6432: C:\Program Files\Common Files
COMPUTERNAME: gekchos_lappy
ComSpec: C:\Windows\system32\cmd.exe
DriverData: C:\Windows\System32\Drivers\DriverData
GTK_BASEPATH: C:\Program Files (x86)\GtkSharp\2.12\
HADOOP_HOME: C:\Users\gekcho\Downloads\Compressed\hadoop-3.1.0\hadoop-3.1.0\bin
HOMEDRIVE: C:
HOMEPATH: \Users\gekcho
JAVA_HOME: C:\Java\jdk1.8.0_201
LOCALAPPDATA: C:\Users\gekcho\AppData\Local
LOGONSERVER: \\gekchos_lappy
MAGICK_HOME: C:\wamp64\bin\php\php7.3.1\ext\ImageMagick
NUMBER_OF_PROCESSORS: 4
OneDrive: C:\Users\gekcho\OneDrive
OneDriveConsumer: C:\Users\gekcho\OneDrive
OS: Windows_NT
Path: C:\wamp64\bin\php\php7.3.1\ext\ImageMagick;
C:\Program Files (x86)\Common Files\Oracle\Java\javapath;
C:\Windows\system32;C:\Windows;
C:\Windows\System32\Wbem;
C:\Windows\System32\WindowsPowerShell\v1.0\;
C:\Windows\System32\OpenSSH\;D:\programfiles\Git\cmd;
D:\programfiles\Cmake\bin;C:\Program Files\nodejs\;
C:\Users\gekcho\Downloads\Compressed\hadoop-3.1.0\hadoop-3.1.0\bin;
C:\Java\jdk1.8.0_201\bin;
C:\Users\gekcho\Downloads\Compressed\spark-2.4.4-bin-hadoop2.7\bin;
C:\Program Files (x86)\GtkSharp\2.12\bin;
C:\Users\gekcho\AppData\Local\Microsoft\WindowsApps;
C:\Users\gekcho\AppData\Roaming\npm
PATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC
PROCESSOR_ARCHITECTURE:AMD64
PROCESSOR_IDENTIFIER: Intel64 Family 6 Model 142 Stepping 9, GenuineIntel
PROCESSOR_LEVEL: 6
PROCESSOR_REVISION: 8e09
ProgramData: C:\ProgramData
ProgramFiles: C:\Program Files
ProgramFiles(x86): C:\Program Files (x86)
ProgramW6432: C:\Program Files
PROMPT: $P$G
PSModulePath: C:\Program Files\WindowsPowerShell\Modules;
C:\Windows\system32\WindowsPowerShell\v1.0\Modules
PUBLIC: C:\Users\Public
python3: C:\Users\gekcho\AppData\Local\Programs\Python\Python37-32\python.exe
SESSIONNAME: Console
SPARK_HOME: C:\Users\gekcho\Downloads\Compressed\spark-2.4.4-bin-hadoop2.7
SystemDrive: C:
SystemRoot: C:\Windows
TEMP: C:\Users\gekcho\AppData\Local\Temp
TMP: C:\Users\gekcho\AppData\Local\Temp
USERDOMAIN: gekchos_lappy
USERDOMAIN_ROAMINGPROFILE:gekchos_lappy
USERNAME: gekcho
USERPROFILE: C:\Users\gekcho
windir: C:\Windows
total no of values available = 46
operating system: Windows_NT
alluserprofile: C:\ProgramData
public directory: C:\Users\Public
Example 3:
javascript
// Node.js program to demonstrate the// process.env Property // Include process moduleconst process = require('process'); // Printing process.env property valuevar env = process.env; console.log("operating system: " + env.OS);console.log("alluserprofile: " + env.ALLUSERSPROFILE);console.log("public directory: " + env.PUBLIC); // Setting new dataenv.gekcho = "gekcho custom data";console.log("stored in env.gekcho: " + env.gekcho); // Delete datadelete env.gekchoconsole.log("stored in env.gekcho: " + env.gekcho);
Output:
operating system: Windows_NT
alluserprofile: C:\ProgramData
public directory: C:\Users\Public
stored in env.gekcho: gekcho custom data
stored in env.gekcho: undefined
Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/process.html#process_process_env
arorakashish0911
Node.js-process-module
Node.js
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": "\n11 Apr, 2022"
},
{
"code": null,
"e": 198,
"s": 52,
"text": "The process.env property is an inbuilt application programming interface of the process module which is used to get the user environment. Syntax:"
},
{
"code": null,
"e": 210,
"s": 198,
"text": "process.env"
},
{
"code": null,
"e": 371,
"s": 210,
"text": "Return Value: This property returns an object containing the user environment. Below examples illustrate the use of process.env property in Node.js: Example 1: "
},
{
"code": null,
"e": 382,
"s": 371,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// process.env Property // Include process moduleconst process = require('process'); // Printing process.env property valueconsole.log(process.env);",
"e": 569,
"s": 382,
"text": null
},
{
"code": null,
"e": 577,
"s": 569,
"text": "Output:"
},
{
"code": null,
"e": 3402,
"s": 577,
"text": "{ ALLUSERSPROFILE: 'C:\\\\ProgramData',\n APPDATA: 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Roaming',\n cmake: 'D:\\\\programfiles\\\\Cmake\\\\bin\\\\cmake.exe',\n CommonProgramFiles: 'C:\\\\Program Files\\\\Common Files',\n 'CommonProgramFiles(x86)': 'C:\\\\Program Files (x86)\\\\Common Files',\n CommonProgramW6432: 'C:\\\\Program Files\\\\Common Files',\n COMPUTERNAME: 'gekchos_lappy',\n ComSpec: 'C:\\\\Windows\\\\system32\\\\cmd.exe',\n DriverData: 'C:\\\\Windows\\\\System32\\\\Drivers\\\\DriverData',\n GTK_BASEPATH: 'C:\\\\Program Files (x86)\\\\GtkSharp\\\\2.12\\\\',\n HADOOP_HOME:\n 'C:\\\\Users\\\\gekcho\\\\Downloads\\\\Compressed\\\\hadoop-3.1.0\\\\hadoop-3.1.0\\\\bin',\n HOMEDRIVE: 'C:',\n HOMEPATH: '\\\\Users\\\\gekcho',\n JAVA_HOME: 'C:\\\\Java\\\\jdk1.8.0_201',\n LOCALAPPDATA: 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Local',\n LOGONSERVER: '\\\\\\\\gekchos_lappy',\n MAGICK_HOME: 'C:\\\\wamp64\\\\bin\\\\php\\\\php7.3.1\\\\ext\\\\ImageMagick',\n NUMBER_OF_PROCESSORS: '4',\n OneDrive: 'C:\\\\Users\\\\gekcho\\\\OneDrive',\n OneDriveConsumer: 'C:\\\\Users\\\\gekcho\\\\OneDrive',\n OS: 'Windows_NT',\n Path:\n 'C:\\\\wamp64\\\\bin\\\\php\\\\php7.3.1\\\\ext\\\\ImageMagick;\n C:\\\\Program Files (x86)\\\\Common Files\\\\Oracle\\\\Java\\\\javapath;\n C:\\\\Windows\\\\system32;C:\\\\Windows;C:\\\\Windows\\\\System32\\\\Wbem;\n C:\\\\Windows\\\\System32\\\\WindowsPowerShell\\\\v1.0\\\\;\n C:\\\\Windows\\\\System32\\\\OpenSSH\\\\;D:\\\\programfiles\\\\Git\\\\cmd;\n D:\\\\programfiles\\\\Cmake\\\\bin;C:\\\\Program Files\\\\nodejs\\\\;\n C:\\\\Users\\\\gekcho\\\\Downloads\\\\Compressed\\\\hadoop-3.1.0\\\\hadoop-3.1.0\\\\bin;\n C:\\\\Java\\\\jdk1.8.0_201\\\\bin;\n C:\\\\Users\\\\gekcho\\\\Downloads\\\\Compressed\\\\spark-2.4.4-bin-hadoop2.7\\\\bin;\n C:\\\\Program Files (x86)\\\\GtkSharp\\\\2.12\\\\bin;\n C:\\\\Users\\\\gekcho\\\\AppData\\\\Local\\\\Microsoft\\\\WindowsApps;\n C:\\\\Users\\\\gekcho\\\\AppData\\\\Roaming\\\\npm',\n PATHEXT: '.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC',\n PROCESSOR_ARCHITECTURE: 'AMD64',\n PROCESSOR_IDENTIFIER: 'Intel64 Family 6 Model 142 Stepping 9, GenuineIntel',\n PROCESSOR_LEVEL: '6',\n PROCESSOR_REVISION: '8e09',\n ProgramData: 'C:\\\\ProgramData',\n ProgramFiles: 'C:\\\\Program Files',\n 'ProgramFiles(x86)': 'C:\\\\Program Files (x86)',\n ProgramW6432: 'C:\\\\Program Files',\n PROMPT: '$P$G',\n PSModulePath:\n 'C:\\\\Program Files\\\\WindowsPowerShell\\\\Modules;\n C:\\\\Windows\\\\system32\\\\WindowsPowerShell\\\\v1.0\\\\Modules',\n PUBLIC: 'C:\\\\Users\\\\Public',\n python3:\n 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Local\\\\Programs\\\\Python\\\\Python37-32\\\\python.exe',\n SESSIONNAME: 'Console',\n SPARK_HOME:\n 'C:\\\\Users\\\\gekcho\\\\Downloads\\\\Compressed\\\\spark-2.4.4-bin-hadoop2.7',\n SystemDrive: 'C:',\n SystemRoot: 'C:\\\\Windows',\n TEMP: 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Local\\\\Temp',\n TMP: 'C:\\\\Users\\\\gekcho\\\\AppData\\\\Local\\\\Temp',\n USERDOMAIN: 'gekchos_lappy',\n USERDOMAIN_ROAMINGPROFILE: 'gekchos_lappy',\n USERNAME: 'gekcho',\n USERPROFILE: 'C:\\\\Users\\\\gekcho',\n windir: 'C:\\\\Windows' }"
},
{
"code": null,
"e": 3413,
"s": 3402,
"text": "Example2: "
},
{
"code": null,
"e": 3424,
"s": 3413,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// process.env Property // Include process moduleconst process = require('process'); // Printing process.env property valuevar no_env = 0; // Calling process.envvar env = process.env; // Iterating through all returned datafor (var key in env) { // Print value console.log(key + \":\\t\\t\\t\" + env[key]); no_env++;} // Printing countconsole.log(\"total no of values available = \" + no_env); // Accessing one by oneconsole.log(\"operating system: \" + env['OS']);console.log(\"alluserprofile: \" + env['ALLUSERSPROFILE']);console.log(\"public directory: \" + env['PUBLIC']);",
"e": 4050,
"s": 3424,
"text": null
},
{
"code": null,
"e": 4058,
"s": 4050,
"text": "Output:"
},
{
"code": null,
"e": 7044,
"s": 4058,
"text": "ALLUSERSPROFILE: C:\\ProgramData\nAPPDATA: C:\\Users\\gekcho\\AppData\\Roaming\ncmake: D:\\programfiles\\Cmake\\bin\\cmake.exe\nCommonProgramFiles: C:\\Program Files\\Common Files\nCommonProgramFiles(x86):C:\\Program Files (x86)\\Common Files\nCommonProgramW6432: C:\\Program Files\\Common Files\nCOMPUTERNAME: gekchos_lappy\nComSpec: C:\\Windows\\system32\\cmd.exe\nDriverData: C:\\Windows\\System32\\Drivers\\DriverData\nGTK_BASEPATH: C:\\Program Files (x86)\\GtkSharp\\2.12\\\nHADOOP_HOME: C:\\Users\\gekcho\\Downloads\\Compressed\\hadoop-3.1.0\\hadoop-3.1.0\\bin\nHOMEDRIVE: C:\nHOMEPATH: \\Users\\gekcho\nJAVA_HOME: C:\\Java\\jdk1.8.0_201\nLOCALAPPDATA: C:\\Users\\gekcho\\AppData\\Local\nLOGONSERVER: \\\\gekchos_lappy\nMAGICK_HOME: C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick\nNUMBER_OF_PROCESSORS: 4\nOneDrive: C:\\Users\\gekcho\\OneDrive\nOneDriveConsumer: C:\\Users\\gekcho\\OneDrive\nOS: Windows_NT\nPath: C:\\wamp64\\bin\\php\\php7.3.1\\ext\\ImageMagick;\nC:\\Program Files (x86)\\Common Files\\Oracle\\Java\\javapath;\nC:\\Windows\\system32;C:\\Windows;\nC:\\Windows\\System32\\Wbem;\nC:\\Windows\\System32\\WindowsPowerShell\\v1.0\\;\nC:\\Windows\\System32\\OpenSSH\\;D:\\programfiles\\Git\\cmd;\nD:\\programfiles\\Cmake\\bin;C:\\Program Files\\nodejs\\;\nC:\\Users\\gekcho\\Downloads\\Compressed\\hadoop-3.1.0\\hadoop-3.1.0\\bin;\nC:\\Java\\jdk1.8.0_201\\bin;\nC:\\Users\\gekcho\\Downloads\\Compressed\\spark-2.4.4-bin-hadoop2.7\\bin;\nC:\\Program Files (x86)\\GtkSharp\\2.12\\bin;\nC:\\Users\\gekcho\\AppData\\Local\\Microsoft\\WindowsApps;\nC:\\Users\\gekcho\\AppData\\Roaming\\npm\nPATHEXT: .COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC\nPROCESSOR_ARCHITECTURE:AMD64\nPROCESSOR_IDENTIFIER: Intel64 Family 6 Model 142 Stepping 9, GenuineIntel\nPROCESSOR_LEVEL: 6\nPROCESSOR_REVISION: 8e09\nProgramData: C:\\ProgramData\nProgramFiles: C:\\Program Files\nProgramFiles(x86): C:\\Program Files (x86)\nProgramW6432: C:\\Program Files\nPROMPT: $P$G\nPSModulePath: C:\\Program Files\\WindowsPowerShell\\Modules;\n C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\Modules\nPUBLIC: C:\\Users\\Public\npython3: C:\\Users\\gekcho\\AppData\\Local\\Programs\\Python\\Python37-32\\python.exe\nSESSIONNAME: Console\nSPARK_HOME: C:\\Users\\gekcho\\Downloads\\Compressed\\spark-2.4.4-bin-hadoop2.7\nSystemDrive: C:\nSystemRoot: C:\\Windows\nTEMP: C:\\Users\\gekcho\\AppData\\Local\\Temp\nTMP: C:\\Users\\gekcho\\AppData\\Local\\Temp\nUSERDOMAIN: gekchos_lappy\nUSERDOMAIN_ROAMINGPROFILE:gekchos_lappy\nUSERNAME: gekcho\nUSERPROFILE: C:\\Users\\gekcho\nwindir: C:\\Windows\ntotal no of values available = 46\noperating system: Windows_NT\nalluserprofile: C:\\ProgramData\npublic directory: C:\\Users\\Public"
},
{
"code": null,
"e": 7056,
"s": 7044,
"text": "Example 3: "
},
{
"code": null,
"e": 7067,
"s": 7056,
"text": "javascript"
},
{
"code": "// Node.js program to demonstrate the// process.env Property // Include process moduleconst process = require('process'); // Printing process.env property valuevar env = process.env; console.log(\"operating system: \" + env.OS);console.log(\"alluserprofile: \" + env.ALLUSERSPROFILE);console.log(\"public directory: \" + env.PUBLIC); // Setting new dataenv.gekcho = \"gekcho custom data\";console.log(\"stored in env.gekcho: \" + env.gekcho); // Delete datadelete env.gekchoconsole.log(\"stored in env.gekcho: \" + env.gekcho);",
"e": 7586,
"s": 7067,
"text": null
},
{
"code": null,
"e": 7594,
"s": 7586,
"text": "Output:"
},
{
"code": null,
"e": 7761,
"s": 7594,
"text": "operating system: Windows_NT\nalluserprofile: C:\\ProgramData\npublic directory: C:\\Users\\Public\nstored in env.gekcho: gekcho custom data\nstored in env.gekcho: undefined"
},
{
"code": null,
"e": 7912,
"s": 7761,
"text": "Note: The above program will compile and run by using the node filename.js command. Reference: https://nodejs.org/api/process.html#process_process_env"
},
{
"code": null,
"e": 7929,
"s": 7912,
"text": "arorakashish0911"
},
{
"code": null,
"e": 7952,
"s": 7929,
"text": "Node.js-process-module"
},
{
"code": null,
"e": 7960,
"s": 7952,
"text": "Node.js"
},
{
"code": null,
"e": 7977,
"s": 7960,
"text": "Web Technologies"
}
] |
Python | Padding a string upto fixed length
|
20 Mar, 2019
Given a string, the task is to pad string up to given specific length with whitespaces. Let’s discuss few methods to solve the given task.
Method #1: Using ljust()
# Python code to demonstrate# pad spaces in string# upto fixed length # initialising stringini_string = "123abcjw"padding_size = 15 # printing string and its lengthprint ("initial string : ", ini_string, len(ini_string)) # code to pad spaces in stringres = ini_string.ljust(padding_size) # printing string and its lengthprint ("final string : ", res, len(res))
initial string : 123abcjw 8
final string : 123abcjw 15
Method #2: Using format
# Python code to demonstrate# pad spaces in string# upto fixed length # initialising stringini_string = "123abcjw" # printing string and its lengthprint ("initial string : ", ini_string, len(ini_string)) # code to pad spaces in stringres = "{:<15}".format(ini_string) # printing string and its lengthprint ("final string : ", res, len(res))
initial string : 123abcjw 8
final string : 123abcjw 15
Method #3: Using operators( * and +)
# Python code to demonstrate# pad spaces in string# upto fixed length # initialising stringini_string = "123abcjw"padding_size = 15 # printing string and its lengthprint ("initial string : ", ini_string, len(ini_string)) # code to pad spaces in stringres = ini_string + " "*(padding_size - len(ini_string)) # printing string and its lengthprint ("final string : ", res, len(res))
initial string : 123abcjw 8
final string : 123abcjw 15
Python string-programs
Python
Python Programs
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
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": 52,
"s": 24,
"text": "\n20 Mar, 2019"
},
{
"code": null,
"e": 191,
"s": 52,
"text": "Given a string, the task is to pad string up to given specific length with whitespaces. Let’s discuss few methods to solve the given task."
},
{
"code": null,
"e": 216,
"s": 191,
"text": "Method #1: Using ljust()"
},
{
"code": "# Python code to demonstrate# pad spaces in string# upto fixed length # initialising stringini_string = \"123abcjw\"padding_size = 15 # printing string and its lengthprint (\"initial string : \", ini_string, len(ini_string)) # code to pad spaces in stringres = ini_string.ljust(padding_size) # printing string and its lengthprint (\"final string : \", res, len(res))",
"e": 581,
"s": 216,
"text": null
},
{
"code": null,
"e": 646,
"s": 581,
"text": "initial string : 123abcjw 8\nfinal string : 123abcjw 15\n"
},
{
"code": null,
"e": 671,
"s": 646,
"text": " Method #2: Using format"
},
{
"code": "# Python code to demonstrate# pad spaces in string# upto fixed length # initialising stringini_string = \"123abcjw\" # printing string and its lengthprint (\"initial string : \", ini_string, len(ini_string)) # code to pad spaces in stringres = \"{:<15}\".format(ini_string) # printing string and its lengthprint (\"final string : \", res, len(res))",
"e": 1016,
"s": 671,
"text": null
},
{
"code": null,
"e": 1081,
"s": 1016,
"text": "initial string : 123abcjw 8\nfinal string : 123abcjw 15\n"
},
{
"code": null,
"e": 1119,
"s": 1081,
"text": " Method #3: Using operators( * and +)"
},
{
"code": "# Python code to demonstrate# pad spaces in string# upto fixed length # initialising stringini_string = \"123abcjw\"padding_size = 15 # printing string and its lengthprint (\"initial string : \", ini_string, len(ini_string)) # code to pad spaces in stringres = ini_string + \" \"*(padding_size - len(ini_string)) # printing string and its lengthprint (\"final string : \", res, len(res))",
"e": 1503,
"s": 1119,
"text": null
},
{
"code": null,
"e": 1568,
"s": 1503,
"text": "initial string : 123abcjw 8\nfinal string : 123abcjw 15\n"
},
{
"code": null,
"e": 1591,
"s": 1568,
"text": "Python string-programs"
},
{
"code": null,
"e": 1598,
"s": 1591,
"text": "Python"
},
{
"code": null,
"e": 1614,
"s": 1598,
"text": "Python Programs"
},
{
"code": null,
"e": 1712,
"s": 1614,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1754,
"s": 1712,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1776,
"s": 1754,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 1802,
"s": 1776,
"text": "Python String | replace()"
},
{
"code": null,
"e": 1834,
"s": 1802,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 1863,
"s": 1834,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 1906,
"s": 1863,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 1928,
"s": 1906,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 1967,
"s": 1928,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 2005,
"s": 1967,
"text": "Python | Convert a list to dictionary"
}
] |
Check if given number is Emirp Number or not
|
08 Jun, 2022
An Emirp Number (prime spelled backwards) is a prime number that results in a different prime when its decimal digits are reversed. This definition excludes the related palindromic primes. Examples :
Input : n = 13
Output : 13 is Emirp!
Explanation :
13 and 31 are both prime numbers.
Thus, 13 is an Emirp number.
Input : n = 27
Output : 27 is not Emirp.
Objective : Input a number and find whether the number is an emirp number or not.
Approach : Input a number and firstly check if its a prime number or not. If the number is a prime number, then we find the reverse of the original number and check the reversed number for being prime or not. If the reversed number is also prime, then the original number is an Emirp Number otherwise it is not.Below is the implementation of above approach :.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to check if given// number is Emirp or not.#include <iostream>using namespace std; // Returns true if n is prime.// Else false.bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Function will check whether number// is Emirp or notbool isEmirp(int n){ // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n int rev = 0; while (n != 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev);} // Driver codeint main(){ int n = 13; // Input number if (isEmirp(n) == true) cout << "Yes"; else cout << "No";} // This code is contributed by Anant Agarwal.
// Java program to check if given number is// Emirp or not.import java.io.*;class Emirp { // Returns true if n is prime. Else // false. public static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function will check whether number // is Emirp or not public static boolean isEmirp(int n) { // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n int rev = 0; while (n != 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev); } // Driver Function public static void main(String args[]) throws IOException { int n = 13; // Input number if (isEmirp(n) == true) System.out.println("Yes"); else System.out.println("No"); }}
# Python3 code to check if# given number is Emirp or not. # Returns true if n is prime.# Else false.def isPrime( n ): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False return True # Function will check whether# number is Emirp or notdef isEmirp( n): # Check if n is prime n = int(n) if isPrime(n) == False: return False # Find reverse of n rev = 0 while n != 0: d = n % 10 rev = rev * 10 + d n = int(n / 10) # If both Original and Reverse # are Prime, then it is an # Emirp number return isPrime(rev) # Driver Functionn = 13 # Input numberif isEmirp(n): print("Yes")else: print("No") # This code is contributed by "Sharad_Bhardwaj".
// C# program to check if given// number is Emirp or not.using System; class Emirp { // Returns true if n is prime // Else false. public static bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function will check whether number // is Emirp or not public static bool isEmirp(int n) { // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n int rev = 0; while (n != 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev); } // Driver Function public static void Main() { int n = 13; // Input number if (isEmirp(n) == true) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by vt_m.
<?php// PHP program to check if given// number is Emirp or not. // Returns true if n// is prime else false function isPrime($n){ // Corner case if ($n <= 1) return -1; // Check from 2 to n-1 for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return -1; return 1;} // Function will check// whether number is// Emirp or notfunction isEmirp($n){ // Check if n is prime if (isPrime($n) == -1) return -1; // Find reverse of n $rev = 0; while ($n != 0) { $d = $n % 10; $rev = $rev * 10 + $d; $n /= 10; } // If both Original and // Reverse are Prime, // then it is an Emirp number return isPrime($rev);} // Driver code$n = 13; if (isEmirp($n) ==-1) echo "Yes"; else echo "No"; // This code is contributed by ajit?>
<script> // javascript program to check if given number is// Emirp or not. // Returns true if n is prime. Else // false. function isPrime(n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function will check whether number // is Emirp or not function isEmirp(n) { // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n var rev = 0; while (n != 0) { var d = n % 10; rev = rev * 10 + d; n = parseInt(n/10); } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev); } // Driver Function var n = 13; // Input number if (isEmirp(n) == true) document.write("Yes"); else document.write("No"); // This code contributed by Princi Singh</script>
Output :
Yes
Time complexity: O(n)
Auxiliary Space:O(1)
jit_t
princi singh
hasani
Prime Number
Mathematical
Mathematical
Prime Number
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Merge two sorted arrays
Operators in C / C++
Prime Numbers
Find minimum number of coins that make a given value
Minimum number of jumps to reach end
The Knight's tour problem | Backtracking-1
Algorithm to solve Rubik's Cube
Program for Decimal to Binary Conversion
Modulo 10^9+7 (1000000007)
Modulo Operator (%) in C/C++ with Examples
|
[
{
"code": null,
"e": 52,
"s": 24,
"text": "\n08 Jun, 2022"
},
{
"code": null,
"e": 254,
"s": 52,
"text": "An Emirp Number (prime spelled backwards) is a prime number that results in a different prime when its decimal digits are reversed. This definition excludes the related palindromic primes. Examples : "
},
{
"code": null,
"e": 411,
"s": 254,
"text": "Input : n = 13\nOutput : 13 is Emirp!\nExplanation :\n13 and 31 are both prime numbers. \nThus, 13 is an Emirp number.\n\nInput : n = 27\nOutput : 27 is not Emirp."
},
{
"code": null,
"e": 495,
"s": 411,
"text": "Objective : Input a number and find whether the number is an emirp number or not. "
},
{
"code": null,
"e": 857,
"s": 495,
"text": "Approach : Input a number and firstly check if its a prime number or not. If the number is a prime number, then we find the reverse of the original number and check the reversed number for being prime or not. If the reversed number is also prime, then the original number is an Emirp Number otherwise it is not.Below is the implementation of above approach :. "
},
{
"code": null,
"e": 861,
"s": 857,
"text": "C++"
},
{
"code": null,
"e": 866,
"s": 861,
"text": "Java"
},
{
"code": null,
"e": 874,
"s": 866,
"text": "Python3"
},
{
"code": null,
"e": 877,
"s": 874,
"text": "C#"
},
{
"code": null,
"e": 881,
"s": 877,
"text": "PHP"
},
{
"code": null,
"e": 892,
"s": 881,
"text": "Javascript"
},
{
"code": "// C++ program to check if given// number is Emirp or not.#include <iostream>using namespace std; // Returns true if n is prime.// Else false.bool isPrime(int n){ // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true;} // Function will check whether number// is Emirp or notbool isEmirp(int n){ // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n int rev = 0; while (n != 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev);} // Driver codeint main(){ int n = 13; // Input number if (isEmirp(n) == true) cout << \"Yes\"; else cout << \"No\";} // This code is contributed by Anant Agarwal.",
"e": 1803,
"s": 892,
"text": null
},
{
"code": "// Java program to check if given number is// Emirp or not.import java.io.*;class Emirp { // Returns true if n is prime. Else // false. public static boolean isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function will check whether number // is Emirp or not public static boolean isEmirp(int n) { // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n int rev = 0; while (n != 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev); } // Driver Function public static void main(String args[]) throws IOException { int n = 13; // Input number if (isEmirp(n) == true) System.out.println(\"Yes\"); else System.out.println(\"No\"); }}",
"e": 2929,
"s": 1803,
"text": null
},
{
"code": "# Python3 code to check if# given number is Emirp or not. # Returns true if n is prime.# Else false.def isPrime( n ): # Corner case if n <= 1: return False # Check from 2 to n-1 for i in range(2, n): if n % i == 0: return False return True # Function will check whether# number is Emirp or notdef isEmirp( n): # Check if n is prime n = int(n) if isPrime(n) == False: return False # Find reverse of n rev = 0 while n != 0: d = n % 10 rev = rev * 10 + d n = int(n / 10) # If both Original and Reverse # are Prime, then it is an # Emirp number return isPrime(rev) # Driver Functionn = 13 # Input numberif isEmirp(n): print(\"Yes\")else: print(\"No\") # This code is contributed by \"Sharad_Bhardwaj\".",
"e": 3781,
"s": 2929,
"text": null
},
{
"code": "// C# program to check if given// number is Emirp or not.using System; class Emirp { // Returns true if n is prime // Else false. public static bool isPrime(int n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (int i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function will check whether number // is Emirp or not public static bool isEmirp(int n) { // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n int rev = 0; while (n != 0) { int d = n % 10; rev = rev * 10 + d; n /= 10; } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev); } // Driver Function public static void Main() { int n = 13; // Input number if (isEmirp(n) == true) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by vt_m.",
"e": 4898,
"s": 3781,
"text": null
},
{
"code": "<?php// PHP program to check if given// number is Emirp or not. // Returns true if n// is prime else false function isPrime($n){ // Corner case if ($n <= 1) return -1; // Check from 2 to n-1 for ($i = 2; $i < $n; $i++) if ($n % $i == 0) return -1; return 1;} // Function will check// whether number is// Emirp or notfunction isEmirp($n){ // Check if n is prime if (isPrime($n) == -1) return -1; // Find reverse of n $rev = 0; while ($n != 0) { $d = $n % 10; $rev = $rev * 10 + $d; $n /= 10; } // If both Original and // Reverse are Prime, // then it is an Emirp number return isPrime($rev);} // Driver code$n = 13; if (isEmirp($n) ==-1) echo \"Yes\"; else echo \"No\"; // This code is contributed by ajit?>",
"e": 5723,
"s": 4898,
"text": null
},
{
"code": "<script> // javascript program to check if given number is// Emirp or not. // Returns true if n is prime. Else // false. function isPrime(n) { // Corner case if (n <= 1) return false; // Check from 2 to n-1 for (i = 2; i < n; i++) if (n % i == 0) return false; return true; } // Function will check whether number // is Emirp or not function isEmirp(n) { // Check if n is prime if (isPrime(n) == false) return false; // Find reverse of n var rev = 0; while (n != 0) { var d = n % 10; rev = rev * 10 + d; n = parseInt(n/10); } // If both Original and Reverse are Prime, // then it is an Emirp number return isPrime(rev); } // Driver Function var n = 13; // Input number if (isEmirp(n) == true) document.write(\"Yes\"); else document.write(\"No\"); // This code contributed by Princi Singh</script>",
"e": 6779,
"s": 5723,
"text": null
},
{
"code": null,
"e": 6790,
"s": 6779,
"text": "Output : "
},
{
"code": null,
"e": 6794,
"s": 6790,
"text": "Yes"
},
{
"code": null,
"e": 6816,
"s": 6794,
"text": "Time complexity: O(n)"
},
{
"code": null,
"e": 6838,
"s": 6816,
"text": "Auxiliary Space:O(1) "
},
{
"code": null,
"e": 6844,
"s": 6838,
"text": "jit_t"
},
{
"code": null,
"e": 6857,
"s": 6844,
"text": "princi singh"
},
{
"code": null,
"e": 6864,
"s": 6857,
"text": "hasani"
},
{
"code": null,
"e": 6877,
"s": 6864,
"text": "Prime Number"
},
{
"code": null,
"e": 6890,
"s": 6877,
"text": "Mathematical"
},
{
"code": null,
"e": 6903,
"s": 6890,
"text": "Mathematical"
},
{
"code": null,
"e": 6916,
"s": 6903,
"text": "Prime Number"
},
{
"code": null,
"e": 7014,
"s": 6916,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7038,
"s": 7014,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 7059,
"s": 7038,
"text": "Operators in C / C++"
},
{
"code": null,
"e": 7073,
"s": 7059,
"text": "Prime Numbers"
},
{
"code": null,
"e": 7126,
"s": 7073,
"text": "Find minimum number of coins that make a given value"
},
{
"code": null,
"e": 7163,
"s": 7126,
"text": "Minimum number of jumps to reach end"
},
{
"code": null,
"e": 7206,
"s": 7163,
"text": "The Knight's tour problem | Backtracking-1"
},
{
"code": null,
"e": 7238,
"s": 7206,
"text": "Algorithm to solve Rubik's Cube"
},
{
"code": null,
"e": 7279,
"s": 7238,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 7306,
"s": 7279,
"text": "Modulo 10^9+7 (1000000007)"
}
] |
How to Color Scatterplot by a variable in Matplotlib? - GeeksforGeeks
|
24 Jan, 2021
In this article, we are going to see how to color scatterplot by variable in Matplotlib. Here we will use matplotlib.pyplot.scatter() methods matplotlib library is used to draw a scatter plot. Scatter plots are widely used to represent relations among variables and how change in one affects the other.
Syntax: matplotlib.pyplot.scatter(x_axis_data, y_axis_data,s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)
Example 1: Color Scatterplot by variable values.
In this example, We are going to see how to color scatterplot with their variable value. Here we will plot a simple scatterplot with x and y data, Then will use c attributes for coloring the point(Scatterplot variable points).
Python3
import matplotlib.pyplot as plt x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y =[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86] plt.scatter(x, y, c = 'red') # To show the plot plt.show()
Output:
Example 2: Color Scatterplot point with dependent values.
In this example, We will plot a variable depending on another variable. Sometimes we need precisely based visualization so in this case, It can help us to visualize the data that depend on another variable. Here we will use three different values for each point and use colormap with specific data.
Python3
import matplotlib.pyplot as plt x =[5, 7, 8, 7, 3, 4, 5, 6, 7] y =[99, 86, 87, 88, 4, 43, 34, 22, 12] z = [1,2,3,4, 5, 6, 7, 8, 9] plt.scatter(x, y, c = z , cmap = "magma")
Output:
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Box Plot in Python using Matplotlib
Bar Plot in Matplotlib
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Python - Call function from another file
loops in python
Multithreading in Python | Set 2 (Synchronization)
Python Dictionary keys() method
Python Lambda Functions
|
[
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n24 Jan, 2021"
},
{
"code": null,
"e": 24205,
"s": 23901,
"text": "In this article, we are going to see how to color scatterplot by variable in Matplotlib. Here we will use matplotlib.pyplot.scatter() methods matplotlib library is used to draw a scatter plot. Scatter plots are widely used to represent relations among variables and how change in one affects the other. "
},
{
"code": null,
"e": 24372,
"s": 24205,
"text": "Syntax: matplotlib.pyplot.scatter(x_axis_data, y_axis_data,s=None, c=None, marker=None, cmap=None, vmin=None, vmax=None, alpha=None, linewidths=None, edgecolors=None)"
},
{
"code": null,
"e": 24421,
"s": 24372,
"text": "Example 1: Color Scatterplot by variable values."
},
{
"code": null,
"e": 24649,
"s": 24421,
"text": "In this example, We are going to see how to color scatterplot with their variable value. Here we will plot a simple scatterplot with x and y data, Then will use c attributes for coloring the point(Scatterplot variable points). "
},
{
"code": null,
"e": 24657,
"s": 24649,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x =[5, 7, 8, 7, 2, 17, 2, 9, 4, 11, 12, 9, 6] y =[99, 86, 87, 88, 100, 86, 103, 87, 94, 78, 77, 85, 86] plt.scatter(x, y, c = 'red') # To show the plot plt.show() ",
"e": 24869,
"s": 24657,
"text": null
},
{
"code": null,
"e": 24877,
"s": 24869,
"text": "Output:"
},
{
"code": null,
"e": 24935,
"s": 24877,
"text": "Example 2: Color Scatterplot point with dependent values."
},
{
"code": null,
"e": 25234,
"s": 24935,
"text": "In this example, We will plot a variable depending on another variable. Sometimes we need precisely based visualization so in this case, It can help us to visualize the data that depend on another variable. Here we will use three different values for each point and use colormap with specific data."
},
{
"code": null,
"e": 25242,
"s": 25234,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x =[5, 7, 8, 7, 3, 4, 5, 6, 7] y =[99, 86, 87, 88, 4, 43, 34, 22, 12] z = [1,2,3,4, 5, 6, 7, 8, 9] plt.scatter(x, y, c = z , cmap = \"magma\")",
"e": 25420,
"s": 25242,
"text": null
},
{
"code": null,
"e": 25428,
"s": 25420,
"text": "Output:"
},
{
"code": null,
"e": 25448,
"s": 25430,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 25455,
"s": 25448,
"text": "Python"
},
{
"code": null,
"e": 25553,
"s": 25455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25562,
"s": 25553,
"text": "Comments"
},
{
"code": null,
"e": 25575,
"s": 25562,
"text": "Old Comments"
},
{
"code": null,
"e": 25611,
"s": 25575,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 25634,
"s": 25611,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 25673,
"s": 25634,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 25706,
"s": 25673,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 25755,
"s": 25706,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 25796,
"s": 25755,
"text": "Python - Call function from another file"
},
{
"code": null,
"e": 25812,
"s": 25796,
"text": "loops in python"
},
{
"code": null,
"e": 25863,
"s": 25812,
"text": "Multithreading in Python | Set 2 (Synchronization)"
},
{
"code": null,
"e": 25895,
"s": 25863,
"text": "Python Dictionary keys() method"
}
] |
Make multiple directories based on a List using Python - GeeksforGeeks
|
16 May, 2021
In this article, we are going to learn how to make directories based on a list using Python. Python has the module named os which forms the core part of the python ecosystem. The os module helps us to work with operating system folders and other related functionalities. Although we can make folders/directories directly on the system here we will see how to make many folders from a list given in python which is less time-consuming.
To do our task, we will use some modules and their methods provided in Python which are as follows:
os: The os module in python provide us some methods for interacting with the operating system(here for creating the folders).
os.mkdir(path): Used to create a single folder(here path) at a time in a directory.
os.path.join(root_path, path): This method concatenates several paths to a single directory. Here the parameters root path will be concatenated with the path want to create.
partial(function,argument1,argument2,...): This method permits one to fix certain number of arguments and generate a new function.
os.makedirs(path): This method helps us to create multiple directories at once. Here the parameter path indicates the directory with sub folders we want to create.
Example 1: Create folders in the same directory where Python is installed
In this example, we have taken a list of elements. Then we iterate through each element in the list. Since we have not mentioned any root directory, the os module makes a folder of each element of the list in the directory where our python ide is installed.
Python3
import os list = ['folder10','folder11','folder12', 'folder13', 'folder15'] for items in list: os.mkdir(items)
Output:
Example 2: Create files in a different directory
Declare the root directory where we want to create the list of folders in a variable. Initialize a list of items. Then iterate through each element in the list. The os module makes a folder of each element of the list in the directory where our python ide is installed. Use os.path.join() to join the items of the list as a folder to the root directory. Then use os.mkdir() to create a single directory in each iteration through the list.
Python3
import os root_path = 'Documents/tmp/year/month/week/day/hour' list = ['car', 'truck', 'bike', 'cycle', 'train'] for items in list: path = os.path.join(root_path, items) os.mkdir(path)
Output:
Example 3: Create a list of directories with subfolders inside a given root directory
First, import the partial function from the functions module and initialize the root directory and list of directories. Use the partial function and pre-fill it with the root directory to create the path for creating a list of folders inside. Then again with the help of partial function and os.makedirs() method prefills the make_directory function. Iterate through the list of items given. In each iteration call the make_directory method with each list item as a parameter to create a directory.
Python3
import osfrom functools import partial root_directory = 'Documents/abc' list = ('one/sub_file_1', 'two/sub_file_2', 'three/sub_file_3') concat_root_path = partial(os.path.join, root_directory)make_directory = partial(os.makedirs, exist_ok=True) for path_items in map(concat_root_path, list): make_directory(path_items)
Output:
Snapshot of created subfolder given below.
Picked
Python directory-program
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python OOPs Concepts
How to Install PIP on Windows ?
Bar Plot in Matplotlib
Defaultdict in Python
Python Classes and Objects
Deque in Python
Check if element exists in list in Python
How to drop one or multiple columns in Pandas Dataframe
Python - Ways to remove duplicates from list
Class method vs Static method in Python
|
[
{
"code": null,
"e": 23927,
"s": 23899,
"text": "\n16 May, 2021"
},
{
"code": null,
"e": 24362,
"s": 23927,
"text": "In this article, we are going to learn how to make directories based on a list using Python. Python has the module named os which forms the core part of the python ecosystem. The os module helps us to work with operating system folders and other related functionalities. Although we can make folders/directories directly on the system here we will see how to make many folders from a list given in python which is less time-consuming."
},
{
"code": null,
"e": 24462,
"s": 24362,
"text": "To do our task, we will use some modules and their methods provided in Python which are as follows:"
},
{
"code": null,
"e": 24588,
"s": 24462,
"text": "os: The os module in python provide us some methods for interacting with the operating system(here for creating the folders)."
},
{
"code": null,
"e": 24673,
"s": 24588,
"text": "os.mkdir(path): Used to create a single folder(here path) at a time in a directory. "
},
{
"code": null,
"e": 24847,
"s": 24673,
"text": "os.path.join(root_path, path): This method concatenates several paths to a single directory. Here the parameters root path will be concatenated with the path want to create."
},
{
"code": null,
"e": 24978,
"s": 24847,
"text": "partial(function,argument1,argument2,...): This method permits one to fix certain number of arguments and generate a new function."
},
{
"code": null,
"e": 25142,
"s": 24978,
"text": "os.makedirs(path): This method helps us to create multiple directories at once. Here the parameter path indicates the directory with sub folders we want to create."
},
{
"code": null,
"e": 25216,
"s": 25142,
"text": "Example 1: Create folders in the same directory where Python is installed"
},
{
"code": null,
"e": 25474,
"s": 25216,
"text": "In this example, we have taken a list of elements. Then we iterate through each element in the list. Since we have not mentioned any root directory, the os module makes a folder of each element of the list in the directory where our python ide is installed."
},
{
"code": null,
"e": 25482,
"s": 25474,
"text": "Python3"
},
{
"code": "import os list = ['folder10','folder11','folder12', 'folder13', 'folder15'] for items in list: os.mkdir(items)",
"e": 25605,
"s": 25482,
"text": null
},
{
"code": null,
"e": 25613,
"s": 25605,
"text": "Output:"
},
{
"code": null,
"e": 25662,
"s": 25613,
"text": "Example 2: Create files in a different directory"
},
{
"code": null,
"e": 26101,
"s": 25662,
"text": "Declare the root directory where we want to create the list of folders in a variable. Initialize a list of items. Then iterate through each element in the list. The os module makes a folder of each element of the list in the directory where our python ide is installed. Use os.path.join() to join the items of the list as a folder to the root directory. Then use os.mkdir() to create a single directory in each iteration through the list."
},
{
"code": null,
"e": 26109,
"s": 26101,
"text": "Python3"
},
{
"code": "import os root_path = 'Documents/tmp/year/month/week/day/hour' list = ['car', 'truck', 'bike', 'cycle', 'train'] for items in list: path = os.path.join(root_path, items) os.mkdir(path)",
"e": 26303,
"s": 26109,
"text": null
},
{
"code": null,
"e": 26311,
"s": 26303,
"text": "Output:"
},
{
"code": null,
"e": 26397,
"s": 26311,
"text": "Example 3: Create a list of directories with subfolders inside a given root directory"
},
{
"code": null,
"e": 26896,
"s": 26397,
"text": "First, import the partial function from the functions module and initialize the root directory and list of directories. Use the partial function and pre-fill it with the root directory to create the path for creating a list of folders inside. Then again with the help of partial function and os.makedirs() method prefills the make_directory function. Iterate through the list of items given. In each iteration call the make_directory method with each list item as a parameter to create a directory."
},
{
"code": null,
"e": 26904,
"s": 26896,
"text": "Python3"
},
{
"code": "import osfrom functools import partial root_directory = 'Documents/abc' list = ('one/sub_file_1', 'two/sub_file_2', 'three/sub_file_3') concat_root_path = partial(os.path.join, root_directory)make_directory = partial(os.makedirs, exist_ok=True) for path_items in map(concat_root_path, list): make_directory(path_items)",
"e": 27230,
"s": 26904,
"text": null
},
{
"code": null,
"e": 27238,
"s": 27230,
"text": "Output:"
},
{
"code": null,
"e": 27281,
"s": 27238,
"text": "Snapshot of created subfolder given below."
},
{
"code": null,
"e": 27288,
"s": 27281,
"text": "Picked"
},
{
"code": null,
"e": 27313,
"s": 27288,
"text": "Python directory-program"
},
{
"code": null,
"e": 27320,
"s": 27313,
"text": "Python"
},
{
"code": null,
"e": 27418,
"s": 27320,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27427,
"s": 27418,
"text": "Comments"
},
{
"code": null,
"e": 27440,
"s": 27427,
"text": "Old Comments"
},
{
"code": null,
"e": 27461,
"s": 27440,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 27493,
"s": 27461,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27516,
"s": 27493,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27538,
"s": 27516,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27565,
"s": 27538,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27581,
"s": 27565,
"text": "Deque in Python"
},
{
"code": null,
"e": 27623,
"s": 27581,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27679,
"s": 27623,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27724,
"s": 27679,
"text": "Python - Ways to remove duplicates from list"
}
] |
Reshape pandas dataframe | Towards Data Science
|
There are many different ways to reshape a pandas dataframe from long to wide form. But the pivot_table() method is the most flexible and probably the only one you need to use once you learn it well, just like how you only need to learn one method melt to reshape from wide to long (see my other post below).
towardsdatascience.com
This tutorial will walk you through reshaping dataframes using pd.pivot_table or the pivot_table method associated with pandas dataframes. In other languages like R, pivot is also known as spread or dcast.
I highly recommend you try the code in Python while you read this article. Try running this tutorial on my shared DeepNote notebook (you can only run but not edit this notebook).
Also, you might be interested a similar tutorial that describes the reverse (reshape from wide to long) with pd.melt and my numpy reshape tutorial.
towardsdatascience.com
It’s easiest to understand what a long dataframe is or looks like if we look at one and compare it with a wide dataframe.
And below is the corresponding dataframe (with the same information) but in the wide form:
Before we begin our pd.pivot_table tutorial, let’s recreate the wide dataframe above in Python with pd.DataFrame. Remember, you can also follow along with my shared notebook.
df_long = pd.DataFrame({ "student": ["Andy", "Bernie", "Cindy", "Deb", "Andy", "Bernie", "Cindy", "Deb", "Andy", "Bernie", "Cindy", "Deb"], "school": ["Z", "Y", "Z", "Y", "Z", "Y", "Z", "Y", "Z", "Y", "Z", "Y"], "class": ["english", "english", "english", "english", "math", "math", "math", "math", "physics", "physics", "physics", "physics"], "grade": [10, 100, 1000, 10000, 20, 200, 2000, 20000, 30, 300, 3000, 30000]})
We often want to keep the identifier columns as they are (index=["student", "school"]), but pivot or “split” a column’s values (values="grade") based on another column (columns="class"). Compare the original and pivoted dataframes below and you’ll understand what that means.
df_long.pivot_table(index=["student", "school"], columns='class', values='grade')
Each unique value in the class column will be a new column (english, math, physics) in the pivoted/wide dataframe. We can also provide a list to the columns parameter.
To get rid of the multi-index, use reset_index().
You can also aggregate each resulting row and column by specifying margins=True (default False).
df_long.pivot_table(index=["student", "school"], columns='class', values='grade', margins=True, # add margins aggfunc='sum') # sum margins (rows/columns)
Here we aggregate by computing the sum via aggfunc='sum' (default 'mean').
There are many other aggregation functions you can use (e.g.,'median' 'sum' 'max'). You can also specify multiple functions as a list (e.g.,aggfunc=['mean', 'sum']).
If we don’t specify any columns via columns, all remaining non-identifier numeric columns (only grade in this dataframe) will be pivoted (long to wide).
df_long.pivot_table(index=["student", "school"])
In the original long data, each student has four grades (english, math, physics), yet in the pivot_tableexample above, each student only has one grade after pivoting.
Why and how does it work? If you remember from the example above, the default is aggfunc='mean'. Thus, what the function did was it grouped the data by student and school (via index=["student", "school"]), and computed the mean value for each group.
If you use the groupby method associated with the pandas dataframe, you will get the same result as above.
df_long.groupby(['student', 'school']).mean().reset_index() student school grade0 Andy Z 201 Bernie Y 2002 Cindy Z 20003 Deb Y 20000
If you change the default aggregation function (e.g., aggfunc='max'), you’ll get different results. The examples below show you how to specify different aggregation functions and also show you how groupby can be used to perform the same pivot.
Note that you’ll also see the class that is associated with each ‘max’ and ‘first’ value.
df_long.pivot_table(index=["student", "school"], aggfunc=['max', 'first'])# groupby equivalent# df_long.groupby(["student", "school"]).agg(['max', 'first']) max first class grade class gradestudent school Andy Z physics 30 english 10Bernie Y physics 300 english 100Cindy Z physics 3000 english 1000Deb Y physics 30000 english 10000
The final example shows you what happens when you pivot multiple columns (columns=['school', 'class']) and you can also deal with missing values after pivoting by replacing the NaN values with another value (-5 in the example below).
df_long.pivot_table(index="student", columns=['school', 'class'], values='grade', fill_value=-5) # replace NaN with -5
The NaN values are expected because each student belongs to only one school (Y or Z). For example, Andy is in school Z and therefore doesn’t have grades in the Y columns.
I hope now you have a better understanding of how pd.pivot_table reshapes dataframes. I look forward to your thoughts and comments.
If you find this post useful, follow me and visit my site for more data science tutorials and also my other articles:
towardsdatascience.com
towardsdatascience.com
medium.com
towardsdatascience.com
medium.com
For more posts, subscribe to my mailing list.
|
[
{
"code": null,
"e": 481,
"s": 172,
"text": "There are many different ways to reshape a pandas dataframe from long to wide form. But the pivot_table() method is the most flexible and probably the only one you need to use once you learn it well, just like how you only need to learn one method melt to reshape from wide to long (see my other post below)."
},
{
"code": null,
"e": 504,
"s": 481,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 710,
"s": 504,
"text": "This tutorial will walk you through reshaping dataframes using pd.pivot_table or the pivot_table method associated with pandas dataframes. In other languages like R, pivot is also known as spread or dcast."
},
{
"code": null,
"e": 889,
"s": 710,
"text": "I highly recommend you try the code in Python while you read this article. Try running this tutorial on my shared DeepNote notebook (you can only run but not edit this notebook)."
},
{
"code": null,
"e": 1037,
"s": 889,
"text": "Also, you might be interested a similar tutorial that describes the reverse (reshape from wide to long) with pd.melt and my numpy reshape tutorial."
},
{
"code": null,
"e": 1060,
"s": 1037,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1182,
"s": 1060,
"text": "It’s easiest to understand what a long dataframe is or looks like if we look at one and compare it with a wide dataframe."
},
{
"code": null,
"e": 1273,
"s": 1182,
"text": "And below is the corresponding dataframe (with the same information) but in the wide form:"
},
{
"code": null,
"e": 1448,
"s": 1273,
"text": "Before we begin our pd.pivot_table tutorial, let’s recreate the wide dataframe above in Python with pd.DataFrame. Remember, you can also follow along with my shared notebook."
},
{
"code": null,
"e": 2037,
"s": 1448,
"text": "df_long = pd.DataFrame({ \"student\": [\"Andy\", \"Bernie\", \"Cindy\", \"Deb\", \"Andy\", \"Bernie\", \"Cindy\", \"Deb\", \"Andy\", \"Bernie\", \"Cindy\", \"Deb\"], \"school\": [\"Z\", \"Y\", \"Z\", \"Y\", \"Z\", \"Y\", \"Z\", \"Y\", \"Z\", \"Y\", \"Z\", \"Y\"], \"class\": [\"english\", \"english\", \"english\", \"english\", \"math\", \"math\", \"math\", \"math\", \"physics\", \"physics\", \"physics\", \"physics\"], \"grade\": [10, 100, 1000, 10000, 20, 200, 2000, 20000, 30, 300, 3000, 30000]})"
},
{
"code": null,
"e": 2313,
"s": 2037,
"text": "We often want to keep the identifier columns as they are (index=[\"student\", \"school\"]), but pivot or “split” a column’s values (values=\"grade\") based on another column (columns=\"class\"). Compare the original and pivoted dataframes below and you’ll understand what that means."
},
{
"code": null,
"e": 2435,
"s": 2313,
"text": "df_long.pivot_table(index=[\"student\", \"school\"], columns='class', values='grade')"
},
{
"code": null,
"e": 2603,
"s": 2435,
"text": "Each unique value in the class column will be a new column (english, math, physics) in the pivoted/wide dataframe. We can also provide a list to the columns parameter."
},
{
"code": null,
"e": 2653,
"s": 2603,
"text": "To get rid of the multi-index, use reset_index()."
},
{
"code": null,
"e": 2750,
"s": 2653,
"text": "You can also aggregate each resulting row and column by specifying margins=True (default False)."
},
{
"code": null,
"e": 2984,
"s": 2750,
"text": "df_long.pivot_table(index=[\"student\", \"school\"], columns='class', values='grade', margins=True, # add margins aggfunc='sum') # sum margins (rows/columns)"
},
{
"code": null,
"e": 3059,
"s": 2984,
"text": "Here we aggregate by computing the sum via aggfunc='sum' (default 'mean')."
},
{
"code": null,
"e": 3225,
"s": 3059,
"text": "There are many other aggregation functions you can use (e.g.,'median' 'sum' 'max'). You can also specify multiple functions as a list (e.g.,aggfunc=['mean', 'sum'])."
},
{
"code": null,
"e": 3378,
"s": 3225,
"text": "If we don’t specify any columns via columns, all remaining non-identifier numeric columns (only grade in this dataframe) will be pivoted (long to wide)."
},
{
"code": null,
"e": 3427,
"s": 3378,
"text": "df_long.pivot_table(index=[\"student\", \"school\"])"
},
{
"code": null,
"e": 3594,
"s": 3427,
"text": "In the original long data, each student has four grades (english, math, physics), yet in the pivot_tableexample above, each student only has one grade after pivoting."
},
{
"code": null,
"e": 3844,
"s": 3594,
"text": "Why and how does it work? If you remember from the example above, the default is aggfunc='mean'. Thus, what the function did was it grouped the data by student and school (via index=[\"student\", \"school\"]), and computed the mean value for each group."
},
{
"code": null,
"e": 3951,
"s": 3844,
"text": "If you use the groupby method associated with the pandas dataframe, you will get the same result as above."
},
{
"code": null,
"e": 4126,
"s": 3951,
"text": "df_long.groupby(['student', 'school']).mean().reset_index() student school grade0 Andy Z 201 Bernie Y 2002 Cindy Z 20003 Deb Y 20000"
},
{
"code": null,
"e": 4370,
"s": 4126,
"text": "If you change the default aggregation function (e.g., aggfunc='max'), you’ll get different results. The examples below show you how to specify different aggregation functions and also show you how groupby can be used to perform the same pivot."
},
{
"code": null,
"e": 4460,
"s": 4370,
"text": "Note that you’ll also see the class that is associated with each ‘max’ and ‘first’ value."
},
{
"code": null,
"e": 4959,
"s": 4460,
"text": "df_long.pivot_table(index=[\"student\", \"school\"], aggfunc=['max', 'first'])# groupby equivalent# df_long.groupby([\"student\", \"school\"]).agg(['max', 'first']) max first class grade class gradestudent school Andy Z physics 30 english 10Bernie Y physics 300 english 100Cindy Z physics 3000 english 1000Deb Y physics 30000 english 10000"
},
{
"code": null,
"e": 5193,
"s": 4959,
"text": "The final example shows you what happens when you pivot multiple columns (columns=['school', 'class']) and you can also deal with missing values after pivoting by replacing the NaN values with another value (-5 in the example below)."
},
{
"code": null,
"e": 5373,
"s": 5193,
"text": "df_long.pivot_table(index=\"student\", columns=['school', 'class'], values='grade', fill_value=-5) # replace NaN with -5"
},
{
"code": null,
"e": 5544,
"s": 5373,
"text": "The NaN values are expected because each student belongs to only one school (Y or Z). For example, Andy is in school Z and therefore doesn’t have grades in the Y columns."
},
{
"code": null,
"e": 5676,
"s": 5544,
"text": "I hope now you have a better understanding of how pd.pivot_table reshapes dataframes. I look forward to your thoughts and comments."
},
{
"code": null,
"e": 5794,
"s": 5676,
"text": "If you find this post useful, follow me and visit my site for more data science tutorials and also my other articles:"
},
{
"code": null,
"e": 5817,
"s": 5794,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5840,
"s": 5817,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5851,
"s": 5840,
"text": "medium.com"
},
{
"code": null,
"e": 5874,
"s": 5851,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5885,
"s": 5874,
"text": "medium.com"
}
] |
Evaluation Metrics for Clustering Models | by Soner Yıldırım | Towards Data Science
|
Clustering is a fundamental task in machine learning. Clustering algorithms group data points in clusters in a way that similar data points are grouped together.
The ultimate goal of a clustering algorithm is to achieve high intra-cluster similarity and low inter-cluster similarity. In other words, we want data points in the same cluster to be as close to each other as possible. The distance between different clusters needs to be as high as possible.
There are different metrics used to evaluate the performance of a clustering model or clustering quality. In this article, we will cover the following metrics:
Purity
Normalized mutual information (NMI)
Rand index
Purity is quite simple to calculate. We assign a label to each cluster based on the most frequent class in it. Then the purity becomes the number of correctly matched class and cluster labels divided by the number of total data points.
Consider a case where our clustering model groups the data points into 3 clusters as seen below:
Each cluster is assigned with the most frequent class label. We sum the number of correct class labels in each cluster and divide it by the total number of data points.
In general, purity increases as the number of clusters increases. For instance, if we have a model that groups each observation in a separate cluster, the purity becomes one.
For this very reason, purity cannot be used as a trade off between the number of clusters and clustering quality.
NMI is related to the information theory. We need to understand what entropy is so I will briefly explain it first.
Entropy is a measure that quantifies uncertainty.
Pi is the probability of the label i (P(i)). Let’s calculate the entropy of the class labels in the previous examples.
We can calculate the probability of a class label by dividing the number of data points belong to that class to the total number of data points. For instance, probability of class A is 6 / 18.
The entropy in our case is calculated as below. If you run the calculation, you will see that the result is 1.089.
The labels are approximately equally distributed among classes so we have relatively high entropy.
Entropy decreases as the uncertainty decreases. Consider a case where we have two classes (9 data points in class A and 1 data point in class B). In that case, we are more certain than the previous case if we are to predict the class of a randomly selected data point. The entropy is this case is calculated as below which results in 0.325.
We now have a basic understanding of entropy. Normalized mutual information (NMI) gives us the reduction in entropy of class labels when we are given the cluster labels.
In a sense, NMI tells us how much the uncertainty about class labels decreases when we know the cluster labels.
It is similar to the information gain in decision trees. In the process of building a decision tree, each split adds information gain to the model. In fact, the split that results in the highest information gain is selected.
Recall the case with three clusters. Since there are approximately equal number of data points in each class, we are uncertain about the class of a randomly picked data point.
However, if we know a data point belongs to cluster A, it is highly likely that the point belongs to class A. Thus, our uncertainty has decreased. NMI measures this reduction in uncertainty. Thus, it is measure of clustering quality.
One advantage of NMI is that we can use it to compare different clustering models that have different number of clusters because NMI is normalized.
The normalized_mutual_info_score function of scikit-learn can be used to calculate NMI.
Rand index is a measure of similarity between two clusterings. We can use it to compare actual class labels and predicted cluster labels to evaluate the performance of a clustering algorithm.
The first step is to create a set of unordered pairs of data points. For instance, if we have 6 data points, the set contains 15 unordered pairs which are also called binomial coefficients. The number of binomial coefficients can easily be calculated using the scipy package for Python.
import scipy.speciascipy.special.binom(6,2)15
Consider we have the following data points.
The unordered pairs of data points are {a,b}, {a,c}, {a,d}, {a,e}, {a,f}, {b,c}, {b,d}, {b,e}, {b,f}, {c,d}, {c,e}, {c,f}, {d,e}, {d,f}, {e,f}.
To calculate the rand index, we are interested in two values:
The number of times a pair of elements are in the same cluster for both actual and predicted clustering.
The number of times a pair of elements are not in the same cluster for both actual and predicted clustering.
The elements in pair {a, b} are in the same cluster for both actual and predicted. The other pair that fits this description is {e, f} (Total of 2 pairs).
The elements in pair {a, d} are in different clusters for both actual and predicted clustering. The other pairs that fit this description are {a,e}, {a,f}, {b,d}, {b,e}, {b,f}, {c,e}, {c,f} (Total of 8 pairs)
We can now introduce the formula for rand index:
a is the number of times a pair of elements are in the same cluster for both actual and predicted clustering which we calculate as 2.
b is the number of times a pair of elements are not in the same cluster for both actual and predicted clustering which we calculate as 8.
The expression in the denominator is the total number of binomial coefficients which is 15.
Thus, rand index in this case is 10 / 15 = 0.67
The rand_score function of scikit-learn can be used to calculate rand index.
We have covered 3 commonly used evaluation metrics for clustering models. Evaluating a model is just as important as creating it. Without a robust and thorough evaluation, we might get unexpected results after the model is deployed.
A comprehensive understanding of the evaluation metrics is essential to efficiently and appropriately use them.
Thank you for reading. Please let me know if you have any feedback.
|
[
{
"code": null,
"e": 334,
"s": 172,
"text": "Clustering is a fundamental task in machine learning. Clustering algorithms group data points in clusters in a way that similar data points are grouped together."
},
{
"code": null,
"e": 627,
"s": 334,
"text": "The ultimate goal of a clustering algorithm is to achieve high intra-cluster similarity and low inter-cluster similarity. In other words, we want data points in the same cluster to be as close to each other as possible. The distance between different clusters needs to be as high as possible."
},
{
"code": null,
"e": 787,
"s": 627,
"text": "There are different metrics used to evaluate the performance of a clustering model or clustering quality. In this article, we will cover the following metrics:"
},
{
"code": null,
"e": 794,
"s": 787,
"text": "Purity"
},
{
"code": null,
"e": 830,
"s": 794,
"text": "Normalized mutual information (NMI)"
},
{
"code": null,
"e": 841,
"s": 830,
"text": "Rand index"
},
{
"code": null,
"e": 1077,
"s": 841,
"text": "Purity is quite simple to calculate. We assign a label to each cluster based on the most frequent class in it. Then the purity becomes the number of correctly matched class and cluster labels divided by the number of total data points."
},
{
"code": null,
"e": 1174,
"s": 1077,
"text": "Consider a case where our clustering model groups the data points into 3 clusters as seen below:"
},
{
"code": null,
"e": 1343,
"s": 1174,
"text": "Each cluster is assigned with the most frequent class label. We sum the number of correct class labels in each cluster and divide it by the total number of data points."
},
{
"code": null,
"e": 1518,
"s": 1343,
"text": "In general, purity increases as the number of clusters increases. For instance, if we have a model that groups each observation in a separate cluster, the purity becomes one."
},
{
"code": null,
"e": 1632,
"s": 1518,
"text": "For this very reason, purity cannot be used as a trade off between the number of clusters and clustering quality."
},
{
"code": null,
"e": 1748,
"s": 1632,
"text": "NMI is related to the information theory. We need to understand what entropy is so I will briefly explain it first."
},
{
"code": null,
"e": 1798,
"s": 1748,
"text": "Entropy is a measure that quantifies uncertainty."
},
{
"code": null,
"e": 1917,
"s": 1798,
"text": "Pi is the probability of the label i (P(i)). Let’s calculate the entropy of the class labels in the previous examples."
},
{
"code": null,
"e": 2110,
"s": 1917,
"text": "We can calculate the probability of a class label by dividing the number of data points belong to that class to the total number of data points. For instance, probability of class A is 6 / 18."
},
{
"code": null,
"e": 2225,
"s": 2110,
"text": "The entropy in our case is calculated as below. If you run the calculation, you will see that the result is 1.089."
},
{
"code": null,
"e": 2324,
"s": 2225,
"text": "The labels are approximately equally distributed among classes so we have relatively high entropy."
},
{
"code": null,
"e": 2665,
"s": 2324,
"text": "Entropy decreases as the uncertainty decreases. Consider a case where we have two classes (9 data points in class A and 1 data point in class B). In that case, we are more certain than the previous case if we are to predict the class of a randomly selected data point. The entropy is this case is calculated as below which results in 0.325."
},
{
"code": null,
"e": 2835,
"s": 2665,
"text": "We now have a basic understanding of entropy. Normalized mutual information (NMI) gives us the reduction in entropy of class labels when we are given the cluster labels."
},
{
"code": null,
"e": 2947,
"s": 2835,
"text": "In a sense, NMI tells us how much the uncertainty about class labels decreases when we know the cluster labels."
},
{
"code": null,
"e": 3172,
"s": 2947,
"text": "It is similar to the information gain in decision trees. In the process of building a decision tree, each split adds information gain to the model. In fact, the split that results in the highest information gain is selected."
},
{
"code": null,
"e": 3348,
"s": 3172,
"text": "Recall the case with three clusters. Since there are approximately equal number of data points in each class, we are uncertain about the class of a randomly picked data point."
},
{
"code": null,
"e": 3582,
"s": 3348,
"text": "However, if we know a data point belongs to cluster A, it is highly likely that the point belongs to class A. Thus, our uncertainty has decreased. NMI measures this reduction in uncertainty. Thus, it is measure of clustering quality."
},
{
"code": null,
"e": 3730,
"s": 3582,
"text": "One advantage of NMI is that we can use it to compare different clustering models that have different number of clusters because NMI is normalized."
},
{
"code": null,
"e": 3818,
"s": 3730,
"text": "The normalized_mutual_info_score function of scikit-learn can be used to calculate NMI."
},
{
"code": null,
"e": 4010,
"s": 3818,
"text": "Rand index is a measure of similarity between two clusterings. We can use it to compare actual class labels and predicted cluster labels to evaluate the performance of a clustering algorithm."
},
{
"code": null,
"e": 4297,
"s": 4010,
"text": "The first step is to create a set of unordered pairs of data points. For instance, if we have 6 data points, the set contains 15 unordered pairs which are also called binomial coefficients. The number of binomial coefficients can easily be calculated using the scipy package for Python."
},
{
"code": null,
"e": 4343,
"s": 4297,
"text": "import scipy.speciascipy.special.binom(6,2)15"
},
{
"code": null,
"e": 4387,
"s": 4343,
"text": "Consider we have the following data points."
},
{
"code": null,
"e": 4531,
"s": 4387,
"text": "The unordered pairs of data points are {a,b}, {a,c}, {a,d}, {a,e}, {a,f}, {b,c}, {b,d}, {b,e}, {b,f}, {c,d}, {c,e}, {c,f}, {d,e}, {d,f}, {e,f}."
},
{
"code": null,
"e": 4593,
"s": 4531,
"text": "To calculate the rand index, we are interested in two values:"
},
{
"code": null,
"e": 4698,
"s": 4593,
"text": "The number of times a pair of elements are in the same cluster for both actual and predicted clustering."
},
{
"code": null,
"e": 4807,
"s": 4698,
"text": "The number of times a pair of elements are not in the same cluster for both actual and predicted clustering."
},
{
"code": null,
"e": 4962,
"s": 4807,
"text": "The elements in pair {a, b} are in the same cluster for both actual and predicted. The other pair that fits this description is {e, f} (Total of 2 pairs)."
},
{
"code": null,
"e": 5171,
"s": 4962,
"text": "The elements in pair {a, d} are in different clusters for both actual and predicted clustering. The other pairs that fit this description are {a,e}, {a,f}, {b,d}, {b,e}, {b,f}, {c,e}, {c,f} (Total of 8 pairs)"
},
{
"code": null,
"e": 5220,
"s": 5171,
"text": "We can now introduce the formula for rand index:"
},
{
"code": null,
"e": 5354,
"s": 5220,
"text": "a is the number of times a pair of elements are in the same cluster for both actual and predicted clustering which we calculate as 2."
},
{
"code": null,
"e": 5492,
"s": 5354,
"text": "b is the number of times a pair of elements are not in the same cluster for both actual and predicted clustering which we calculate as 8."
},
{
"code": null,
"e": 5584,
"s": 5492,
"text": "The expression in the denominator is the total number of binomial coefficients which is 15."
},
{
"code": null,
"e": 5632,
"s": 5584,
"text": "Thus, rand index in this case is 10 / 15 = 0.67"
},
{
"code": null,
"e": 5709,
"s": 5632,
"text": "The rand_score function of scikit-learn can be used to calculate rand index."
},
{
"code": null,
"e": 5942,
"s": 5709,
"text": "We have covered 3 commonly used evaluation metrics for clustering models. Evaluating a model is just as important as creating it. Without a robust and thorough evaluation, we might get unexpected results after the model is deployed."
},
{
"code": null,
"e": 6054,
"s": 5942,
"text": "A comprehensive understanding of the evaluation metrics is essential to efficiently and appropriately use them."
}
] |
Mongoose Virtuals - GeeksforGeeks
|
24 May, 2021
Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document’s collection.
With the get method of virtual property, we can set the value of the virtual property from existing document field values, and it returns the virtual property value. Mongoose calls the get method every time we access the virtual property.
Installing Module:
Step 1: You can visit the link Install mongoose to get information about installing the mongoose module. You can install this package by using this command:
npm install mongoose
Step 2: After installing the mongoose module, you can import it into your file using the following code:
const mongoose = require('mongoose');
Database: Initially, we have an empty collection of users in the database GFG.
Initially, collection users is empty
Filename: app.js
Javascript
// Requiring moduleconst mongoose = require('mongoose');const express = require('express');const app = express(); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); // Constructing mongoose schemaconst userSchema = new mongoose.Schema({ name: { first: String, last: String }}); // Setting virtual property using get methoduserSchema.virtual('name.full') .get(function () { return this.name.first + ' ' + this.name.last; }) // Creating mongoose modelconst User = mongoose.model('user', userSchema); const newUser = new User({ name: { first: "David", last: "Beckham" }}) newUser.save() .then(u => { console.log("USERNAME: ", u.name.full) }) .catch(error => { console.log(error); })
Run app.js file using the following command:
node app.js
Output:
Output after executing app.js
Database: After the execution of the program, our database will look like this.
Collection users after executing app.js
Explanation: Here schema contains fields name.first and name.last and has one virtual property name.full. Whenever name.full is accessed, the get method is called, and we get the fullname as a concatenation of first and last name. Hence, whenever we have to get the full name, we don’t have to access the firstname and lastname separately and concatenating them, instead, we can get them easily through the virtual property.
With the set method of virtual property, we can set the value of existing document fields from the value of the virtual property.
Filename: index.js
Javascript
// Requiring moduleconst mongoose = require('mongoose');const express = require('express');const app = express(); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); // Constructing mongoose schemaconst userSchema = new mongoose.Schema({ name: { first: String, last: String }}); // Setting the firstname and lastname using set methoduserSchema.virtual('name.full') .get(function () { return this.name.first + ' ' + this.name.last; }) .set(function (value) { var fname = value.split(' '); this.name.first = fname[0]; this.name.last = fname[1]; }) // Creating mongoose modelconst User = mongoose.model('user', userSchema); const newUser = new User({ name: { full: "Dave Bautista" }}) newUser.save() .then(u => { console.log("FIRSTNAME: ", u.name.first, "\nLASTNAME:", u.name.last) }) .catch(error => { console.log(error); })
Run index.js file using the following command:
node index.js
Output:
Output after executing index.js
Database: After the execution of the program, our database will look like this.
Collection users after executing index.js
Explanation: Here when the user saves the document using virtual property name.full, the set function automatically sets the fields name.first and name.last field values using name.full. Hence, with the help of virtual property, we didn’t need to provide each field separately for creating a document.
MongoDB
Mongoose
Node.js-Methods
MongoDB
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
MongoDB - FindOne() Method
MongoDB Cursor
Create user and add role in MongoDB
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Express.js express.Router() Function
Node.js fs.readFile() Method
|
[
{
"code": null,
"e": 24454,
"s": 24426,
"text": "\n24 May, 2021"
},
{
"code": null,
"e": 24622,
"s": 24454,
"text": "Virtuals are document properties that do not persist or get stored in the MongoDB database, they only exist logically and are not written to the document’s collection."
},
{
"code": null,
"e": 24861,
"s": 24622,
"text": "With the get method of virtual property, we can set the value of the virtual property from existing document field values, and it returns the virtual property value. Mongoose calls the get method every time we access the virtual property."
},
{
"code": null,
"e": 24880,
"s": 24861,
"text": "Installing Module:"
},
{
"code": null,
"e": 25037,
"s": 24880,
"text": "Step 1: You can visit the link Install mongoose to get information about installing the mongoose module. You can install this package by using this command:"
},
{
"code": null,
"e": 25058,
"s": 25037,
"text": "npm install mongoose"
},
{
"code": null,
"e": 25163,
"s": 25058,
"text": "Step 2: After installing the mongoose module, you can import it into your file using the following code:"
},
{
"code": null,
"e": 25201,
"s": 25163,
"text": "const mongoose = require('mongoose');"
},
{
"code": null,
"e": 25280,
"s": 25201,
"text": "Database: Initially, we have an empty collection of users in the database GFG."
},
{
"code": null,
"e": 25317,
"s": 25280,
"text": "Initially, collection users is empty"
},
{
"code": null,
"e": 25334,
"s": 25317,
"text": "Filename: app.js"
},
{
"code": null,
"e": 25345,
"s": 25334,
"text": "Javascript"
},
{
"code": "// Requiring moduleconst mongoose = require('mongoose');const express = require('express');const app = express(); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); // Constructing mongoose schemaconst userSchema = new mongoose.Schema({ name: { first: String, last: String }}); // Setting virtual property using get methoduserSchema.virtual('name.full') .get(function () { return this.name.first + ' ' + this.name.last; }) // Creating mongoose modelconst User = mongoose.model('user', userSchema); const newUser = new User({ name: { first: \"David\", last: \"Beckham\" }}) newUser.save() .then(u => { console.log(\"USERNAME: \", u.name.full) }) .catch(error => { console.log(error); })",
"e": 26240,
"s": 25345,
"text": null
},
{
"code": null,
"e": 26285,
"s": 26240,
"text": "Run app.js file using the following command:"
},
{
"code": null,
"e": 26297,
"s": 26285,
"text": "node app.js"
},
{
"code": null,
"e": 26305,
"s": 26297,
"text": "Output:"
},
{
"code": null,
"e": 26335,
"s": 26305,
"text": "Output after executing app.js"
},
{
"code": null,
"e": 26415,
"s": 26335,
"text": "Database: After the execution of the program, our database will look like this."
},
{
"code": null,
"e": 26455,
"s": 26415,
"text": "Collection users after executing app.js"
},
{
"code": null,
"e": 26880,
"s": 26455,
"text": "Explanation: Here schema contains fields name.first and name.last and has one virtual property name.full. Whenever name.full is accessed, the get method is called, and we get the fullname as a concatenation of first and last name. Hence, whenever we have to get the full name, we don’t have to access the firstname and lastname separately and concatenating them, instead, we can get them easily through the virtual property."
},
{
"code": null,
"e": 27011,
"s": 26880,
"text": "With the set method of virtual property, we can set the value of existing document fields from the value of the virtual property. "
},
{
"code": null,
"e": 27030,
"s": 27011,
"text": "Filename: index.js"
},
{
"code": null,
"e": 27041,
"s": 27030,
"text": "Javascript"
},
{
"code": "// Requiring moduleconst mongoose = require('mongoose');const express = require('express');const app = express(); // Connecting to databasemongoose.connect('mongodb://localhost:27017/GFG', { useNewUrlParser: true, useUnifiedTopology: true, useFindAndModify: false }); // Constructing mongoose schemaconst userSchema = new mongoose.Schema({ name: { first: String, last: String }}); // Setting the firstname and lastname using set methoduserSchema.virtual('name.full') .get(function () { return this.name.first + ' ' + this.name.last; }) .set(function (value) { var fname = value.split(' '); this.name.first = fname[0]; this.name.last = fname[1]; }) // Creating mongoose modelconst User = mongoose.model('user', userSchema); const newUser = new User({ name: { full: \"Dave Bautista\" }}) newUser.save() .then(u => { console.log(\"FIRSTNAME: \", u.name.first, \"\\nLASTNAME:\", u.name.last) }) .catch(error => { console.log(error); })",
"e": 28117,
"s": 27041,
"text": null
},
{
"code": null,
"e": 28164,
"s": 28117,
"text": "Run index.js file using the following command:"
},
{
"code": null,
"e": 28178,
"s": 28164,
"text": "node index.js"
},
{
"code": null,
"e": 28186,
"s": 28178,
"text": "Output:"
},
{
"code": null,
"e": 28218,
"s": 28186,
"text": "Output after executing index.js"
},
{
"code": null,
"e": 28298,
"s": 28218,
"text": "Database: After the execution of the program, our database will look like this."
},
{
"code": null,
"e": 28340,
"s": 28298,
"text": "Collection users after executing index.js"
},
{
"code": null,
"e": 28642,
"s": 28340,
"text": "Explanation: Here when the user saves the document using virtual property name.full, the set function automatically sets the fields name.first and name.last field values using name.full. Hence, with the help of virtual property, we didn’t need to provide each field separately for creating a document."
},
{
"code": null,
"e": 28650,
"s": 28642,
"text": "MongoDB"
},
{
"code": null,
"e": 28659,
"s": 28650,
"text": "Mongoose"
},
{
"code": null,
"e": 28675,
"s": 28659,
"text": "Node.js-Methods"
},
{
"code": null,
"e": 28683,
"s": 28675,
"text": "MongoDB"
},
{
"code": null,
"e": 28691,
"s": 28683,
"text": "Node.js"
},
{
"code": null,
"e": 28708,
"s": 28691,
"text": "Web Technologies"
},
{
"code": null,
"e": 28806,
"s": 28708,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28815,
"s": 28806,
"text": "Comments"
},
{
"code": null,
"e": 28828,
"s": 28815,
"text": "Old Comments"
},
{
"code": null,
"e": 28866,
"s": 28828,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 28891,
"s": 28866,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 28918,
"s": 28891,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 28933,
"s": 28918,
"text": "MongoDB Cursor"
},
{
"code": null,
"e": 28969,
"s": 28933,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 29002,
"s": 28969,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 29050,
"s": 29002,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29083,
"s": 29050,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 29120,
"s": 29083,
"text": "Express.js express.Router() Function"
}
] |
How to install install mariadb 10 2 centos 7
|
In this article we shall learn about – how to install MariaDB 10.2 on Centos 7 / RHEL. This can be used as a guide for beginners or as a reference. Please note that, this can also be used as an alternative replacement of MySQL.
MariaDB is an open-source and an alternative relational database management software.
MariaDB is robust, fast and Scalable with rich storage engines.
MariaDB has new features such as GIS and JSON.
The Package included: MariadB, Mariadb-server,MariaDB-libs.
The Daemon Name used is: mariadb.
Port No: 3306.
Configuration path: /etc/my.cnf.
In general, the mariaDB package comes with an installation media in the local repository which we can install, but if we needed to install the latest package we can do it by adding the repository to the yum local repository list. We use this below command and code to add the repository to the yum.
Adding the Repo for Centos 7 64 bit
[mariadb]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/centos7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
[mariadb10]
name = MariaDB
baseurl = http://yum.mariadb.org/10.2/rhel7-amd64
gpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB
gpgcheck=1
We can install the MariaDB using the Yum Repo, as we just added the repository to the local yum below is the command to install the mariaDB using the Yum
# yum groupinstall mariadb*
Loaded plugins: fastestmirror, refresh-packagekit, security
Loading mirror speeds from cached hostfile
* base: ftp.iitm.ac.in
* extras: ftp.iitm.ac.in
* updates: ftp.iitm.ac.in
....
....
.....
....
....
...
....
Downloading packages:
--------------------------------------------------------------------------------------------------------------------------------------------
Total 68 MB/s | 22 MB 00:00:00
Running transaction check
Running transaction test
Transaction test succeeded
Running transaction
Warning: RPMDB altered outside of yum.
Installing : perl-Data-Dumper-2.145-3.el7.x86_64 1/13
Installing : unixODBC-2.3.1-10.el7.x86_64 2/13
Installing : perl-Net-Daemon-0.48-5.el7.noarch 3/13
Installing : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64 4/13
Installing : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64 5/13
Installing : perl-IO-Compress-2.061-2.el7.noarch 6/13
Installing : perl-PlRPC-0.2020-14.el7.noarch 7/13
Installing : perl-DBI-1.627-4.el7.x86_64 8/13
Installing : perl-DBD-MySQL-4.023-5.el7.x86_64 9/13
Installing : 1:mariadb-5.5.41-2.el7_0.x86_64 10/13
Installing : 1:mariadb-server-5.5.41-2.el7_0.x86_64 11/13
Installing : mysql-connector-odbc-5.2.5-6.el7.x86_64 12/13
Installing : MySQL-python-1.2.3-11.el7.x86_64 13/13
Verifying : 1:mariadb-5.5.41-2.el7_0.x86_64 1/13
Verifying : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64 2/13
Verifying : mysql-connector-odbc-5.2.5-6.el7.x86_64 3/13
Verifying : perl-Data-Dumper-2.145-3.el7.x86_64 4/13
Verifying : MySQL-python-1.2.3-11.el7.x86_64 5/13
Verifying : 1:mariadb-server-5.5.41-2.el7_0.x86_64 6/13
Verifying : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64 7/13
Verifying : perl-PlRPC-0.2020-14.el7.noarch 8/13
Verifying : perl-Net-Daemon-0.48-5.el7.noarch 9/13
Verifying : perl-DBI-1.627-4.el7.x86_64 10/13
Verifying : unixODBC-2.3.1-10.el7.x86_64 11/13
Verifying : perl-DBD-MySQL-4.023-5.el7.x86_64 12/13
Verifying : perl-IO-Compress-2.061-2.el7.noarch 13/13
Installed:
MySQL-python.x86_64 0:1.2.3-11.el7 mariadb.x86_64 1:5.5.41-2.el7_0 mariadb-server.x86_64 1:5.5.41-2.el7_0
mysql-connector-odbc.x86_64 0:5.2.5-6.el7
Dependency Installed:
perl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7 perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7 perl-DBD-MySQL.x86_64 0:4.023-5.el7
perl-DBI.x86_64 0:1.627-4.el7 perl-Data-Dumper.x86_64 0:2.145-3.el7 perl-IO-Compress.noarch 0:2.061-2.el7
perl-Net-Daemon.noarch 0:0.48-5.el7 perl-PlRPC.noarch 0:0.2020-14.el7 unixODBC.x86_64 0:2.3.1-10.el7
Complete!
Below is the command to start the mariaDB services
# systemctl start mariadb.services
And we needed to add the services to start services at the boot time, we can use the below command to start the mariaDB services at the boot time.
# systemctl enable mariadb.services
# firewall-cmd –permanent –add-services=mysql
# firewall-cmd –permanent –add-port=3306/tcp
# firewall-cmd –reload
By default, the root password for the mariadb is not set and without root password, we cannot log into the database server. Below is the command to set the root password for mariaDB and remove the anonymous users and secure the mariaDB by restricting the remote login for root and remove the test database.
# mysql_secure_installation
/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found
NOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB
SERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!
In order to log into MariaDB to secure it, we'll need the current
password for the root user. If you've just installed MariaDB, and
you haven't set the root password yet, the password will be blank,
so you should just press enter here.
Enter current password for root (enter for none):
OK, successfully used password, moving on...
Setting the root password ensures that nobody can log into the MariaDB
root user without the proper authorization.
Set root password? [Y/n] y
New password:
Re-enter new password:
Password updated successfully!
Reloading the privilege tables..
... Success!
By default, a MariaDB installation has an anonymous user, allowing anyone
to log into MariaDB without having to have a user account created for
them. This is intended only for testing, and to make the installation
go a bit smoother. You should remove them before moving into a
production environment.
Remove anonymous users? [Y/n] y
... Success!
Normally, root should only be allowed to connect from 'localhost'. This
ensures that someone cannot guess at the root password from the network.
Disallow root login remotely? [Y/n] y
... Success!
By default, MariaDB comes with a database named 'test' that anyone can
access. This is also intended only for testing, and should be removed
before moving into a production environment. Install MariaDB 10.2 RHEL 7
Remove test database and access to it? [Y/n] y
- Dropping test database...
... Success!
- Removing privileges on test database...
... Success!
Reloading the privilege tables will ensure that all changes made so far
will take effect immediately. Install MariaDB 10.2 RHEL 7
Reload privilege tables now? [Y/n] y
... Success!
Cleaning up...
All done! If you've completed all of the above steps, your MariaDB
installation should now be secure.
Thanks for using MariaDB!
As we have completed the installation and assigned a password for the root user and secure the connection, we needed to test the mariadb by logging into the database. Below is the command to test the mariaDB –
# mysql -uroot -p
Enter password:
Welcome to the MariaDB monitor. Commands end with; or \g.
Your MariaDB connection id is 10
Server version: 5.5.41-MariaDB MariaDB Server Install MariaDB 10.2 RHEL 7
Copyright (c) 2000, 2014, Oracle, MariaDB Corporation Ab and others.
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
MariaDB [(none)]>
By using the above steps, we can install the MariadDB 10.2 on CentOS 7 / RHEL 7 and secure the mariadb by removing the anonymous user and test database which is a good alternative replacement of MySQL server. In our future articles, you will learn more about MariaDB.
|
[
{
"code": null,
"e": 1290,
"s": 1062,
"text": "In this article we shall learn about – how to install MariaDB 10.2 on Centos 7 / RHEL. This can be used as a guide for beginners or as a reference. Please note that, this can also be used as an alternative replacement of MySQL."
},
{
"code": null,
"e": 1376,
"s": 1290,
"text": "MariaDB is an open-source and an alternative relational database management software."
},
{
"code": null,
"e": 1440,
"s": 1376,
"text": "MariaDB is robust, fast and Scalable with rich storage engines."
},
{
"code": null,
"e": 1487,
"s": 1440,
"text": "MariaDB has new features such as GIS and JSON."
},
{
"code": null,
"e": 1547,
"s": 1487,
"text": "The Package included: MariadB, Mariadb-server,MariaDB-libs."
},
{
"code": null,
"e": 1581,
"s": 1547,
"text": "The Daemon Name used is: mariadb."
},
{
"code": null,
"e": 1596,
"s": 1581,
"text": "Port No: 3306."
},
{
"code": null,
"e": 1629,
"s": 1596,
"text": "Configuration path: /etc/my.cnf."
},
{
"code": null,
"e": 1928,
"s": 1629,
"text": "In general, the mariaDB package comes with an installation media in the local repository which we can install, but if we needed to install the latest package we can do it by adding the repository to the yum local repository list. We use this below command and code to add the repository to the yum."
},
{
"code": null,
"e": 1964,
"s": 1928,
"text": "Adding the Repo for Centos 7 64 bit"
},
{
"code": null,
"e": 2103,
"s": 1964,
"text": "[mariadb]\nname = MariaDB\nbaseurl = http://yum.mariadb.org/10.2/centos7-amd64\ngpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB\ngpgcheck=1"
},
{
"code": null,
"e": 2242,
"s": 2103,
"text": "[mariadb10]\nname = MariaDB\nbaseurl = http://yum.mariadb.org/10.2/rhel7-amd64\ngpgkey=https://yum.mariadb.org/RPM-GPG-KEY-MariaDB\ngpgcheck=1"
},
{
"code": null,
"e": 2396,
"s": 2242,
"text": "We can install the MariaDB using the Yum Repo, as we just added the repository to the local yum below is the command to install the mariaDB using the Yum"
},
{
"code": null,
"e": 4873,
"s": 2396,
"text": "# yum groupinstall mariadb*\nLoaded plugins: fastestmirror, refresh-packagekit, security\nLoading mirror speeds from cached hostfile\n* base: ftp.iitm.ac.in\n* extras: ftp.iitm.ac.in\n* updates: ftp.iitm.ac.in\n....\n....\n.....\n....\n....\n...\n....\nDownloading packages:\n--------------------------------------------------------------------------------------------------------------------------------------------\nTotal 68 MB/s | 22 MB 00:00:00\nRunning transaction check\nRunning transaction test\nTransaction test succeeded\nRunning transaction\nWarning: RPMDB altered outside of yum.\nInstalling : perl-Data-Dumper-2.145-3.el7.x86_64 1/13\nInstalling : unixODBC-2.3.1-10.el7.x86_64 2/13\nInstalling : perl-Net-Daemon-0.48-5.el7.noarch 3/13\nInstalling : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64 4/13\nInstalling : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64 5/13\nInstalling : perl-IO-Compress-2.061-2.el7.noarch 6/13\nInstalling : perl-PlRPC-0.2020-14.el7.noarch 7/13\nInstalling : perl-DBI-1.627-4.el7.x86_64 8/13\nInstalling : perl-DBD-MySQL-4.023-5.el7.x86_64 9/13\nInstalling : 1:mariadb-5.5.41-2.el7_0.x86_64 10/13\nInstalling : 1:mariadb-server-5.5.41-2.el7_0.x86_64 11/13\nInstalling : mysql-connector-odbc-5.2.5-6.el7.x86_64 12/13\nInstalling : MySQL-python-1.2.3-11.el7.x86_64 13/13\nVerifying : 1:mariadb-5.5.41-2.el7_0.x86_64 1/13\nVerifying : perl-Compress-Raw-Bzip2-2.061-3.el7.x86_64 2/13\nVerifying : mysql-connector-odbc-5.2.5-6.el7.x86_64 3/13\nVerifying : perl-Data-Dumper-2.145-3.el7.x86_64 4/13\nVerifying : MySQL-python-1.2.3-11.el7.x86_64 5/13\nVerifying : 1:mariadb-server-5.5.41-2.el7_0.x86_64 6/13\nVerifying : 1:perl-Compress-Raw-Zlib-2.061-4.el7.x86_64 7/13\nVerifying : perl-PlRPC-0.2020-14.el7.noarch 8/13\nVerifying : perl-Net-Daemon-0.48-5.el7.noarch 9/13\nVerifying : perl-DBI-1.627-4.el7.x86_64 10/13\nVerifying : unixODBC-2.3.1-10.el7.x86_64 11/13\nVerifying : perl-DBD-MySQL-4.023-5.el7.x86_64 12/13\nVerifying : perl-IO-Compress-2.061-2.el7.noarch 13/13\nInstalled:\nMySQL-python.x86_64 0:1.2.3-11.el7 mariadb.x86_64 1:5.5.41-2.el7_0 mariadb-server.x86_64 1:5.5.41-2.el7_0\nmysql-connector-odbc.x86_64 0:5.2.5-6.el7\nDependency Installed:\nperl-Compress-Raw-Bzip2.x86_64 0:2.061-3.el7 perl-Compress-Raw-Zlib.x86_64 1:2.061-4.el7 perl-DBD-MySQL.x86_64 0:4.023-5.el7\nperl-DBI.x86_64 0:1.627-4.el7 perl-Data-Dumper.x86_64 0:2.145-3.el7 perl-IO-Compress.noarch 0:2.061-2.el7\nperl-Net-Daemon.noarch 0:0.48-5.el7 perl-PlRPC.noarch 0:0.2020-14.el7 unixODBC.x86_64 0:2.3.1-10.el7\nComplete!"
},
{
"code": null,
"e": 4924,
"s": 4873,
"text": "Below is the command to start the mariaDB services"
},
{
"code": null,
"e": 4959,
"s": 4924,
"text": "# systemctl start mariadb.services"
},
{
"code": null,
"e": 5106,
"s": 4959,
"text": "And we needed to add the services to start services at the boot time, we can use the below command to start the mariaDB services at the boot time."
},
{
"code": null,
"e": 5142,
"s": 5106,
"text": "# systemctl enable mariadb.services"
},
{
"code": null,
"e": 5256,
"s": 5142,
"text": "# firewall-cmd –permanent –add-services=mysql\n# firewall-cmd –permanent –add-port=3306/tcp\n# firewall-cmd –reload"
},
{
"code": null,
"e": 5563,
"s": 5256,
"text": "By default, the root password for the mariadb is not set and without root password, we cannot log into the database server. Below is the command to set the root password for mariaDB and remove the anonymous users and secure the mariaDB by restricting the remote login for root and remove the test database."
},
{
"code": null,
"e": 7613,
"s": 5563,
"text": "# mysql_secure_installation\n/usr/bin/mysql_secure_installation: line 379: find_mysql_client: command not found\nNOTE: RUNNING ALL PARTS OF THIS SCRIPT IS RECOMMENDED FOR ALL MariaDB\nSERVERS IN PRODUCTION USE! PLEASE READ EACH STEP CAREFULLY!\nIn order to log into MariaDB to secure it, we'll need the current\npassword for the root user. If you've just installed MariaDB, and\nyou haven't set the root password yet, the password will be blank,\nso you should just press enter here.\nEnter current password for root (enter for none):\nOK, successfully used password, moving on...\nSetting the root password ensures that nobody can log into the MariaDB\nroot user without the proper authorization.\nSet root password? [Y/n] y\nNew password:\nRe-enter new password:\nPassword updated successfully!\nReloading the privilege tables..\n... Success!\nBy default, a MariaDB installation has an anonymous user, allowing anyone\nto log into MariaDB without having to have a user account created for\nthem. This is intended only for testing, and to make the installation\ngo a bit smoother. You should remove them before moving into a\nproduction environment.\nRemove anonymous users? [Y/n] y\n... Success!\nNormally, root should only be allowed to connect from 'localhost'. This\nensures that someone cannot guess at the root password from the network.\nDisallow root login remotely? [Y/n] y\n... Success!\nBy default, MariaDB comes with a database named 'test' that anyone can\naccess. This is also intended only for testing, and should be removed\nbefore moving into a production environment. Install MariaDB 10.2 RHEL 7\nRemove test database and access to it? [Y/n] y\n- Dropping test database...\n... Success!\n- Removing privileges on test database...\n... Success!\nReloading the privilege tables will ensure that all changes made so far\nwill take effect immediately. Install MariaDB 10.2 RHEL 7\nReload privilege tables now? [Y/n] y\n... Success!\nCleaning up...\nAll done! If you've completed all of the above steps, your MariaDB\ninstallation should now be secure.\nThanks for using MariaDB!"
},
{
"code": null,
"e": 7823,
"s": 7613,
"text": "As we have completed the installation and assigned a password for the root user and secure the connection, we needed to test the mariadb by logging into the database. Below is the command to test the mariaDB –"
},
{
"code": null,
"e": 8188,
"s": 7823,
"text": "# mysql -uroot -p\nEnter password:\nWelcome to the MariaDB monitor. Commands end with; or \\g.\nYour MariaDB connection id is 10\nServer version: 5.5.41-MariaDB MariaDB Server Install MariaDB 10.2 RHEL 7\nCopyright (c) 2000, 2014, Oracle, MariaDB Corporation Ab and others.\nType 'help;' or '\\h' for help. Type '\\c' to clear the current input statement.\nMariaDB [(none)]>"
},
{
"code": null,
"e": 8456,
"s": 8188,
"text": "By using the above steps, we can install the MariadDB 10.2 on CentOS 7 / RHEL 7 and secure the mariadb by removing the anonymous user and test database which is a good alternative replacement of MySQL server. In our future articles, you will learn more about MariaDB."
}
] |
PHP Form Handling
|
The PHP superglobals $_GET and $_POST are used to collect form-data.
The example below displays a simple HTML form with two input fields and a submit button:
When the user fills out the form above and clicks the submit button, the form data is sent
for processing to a PHP file named "welcome.php". The form data is sent with
the HTTP POST method.
To display the submitted data you could simply echo all the variables. The "welcome.php" looks like this:
The output could be something like this:
The same result could also be achieved using the HTTP GET method:
and "welcome_get.php" looks like this:
The code above is quite simple. However, the most important thing is missing. You need
to validate form data to protect your script from malicious code.
Think SECURITY when processing PHP forms!
This page does not contain any form validation, it just shows how you can
send and retrieve form data.
However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important
to protect your form from hackers and spammers!
Both GET and POST create an array (e.g. array( key1 => value1,
key2 => value2, key3 => value3, ...)). This array holds key/value pairs, where
keys are the names of the form controls and values are the input data from the user.
Both GET and POST are treated as $_GET and $_POST. These are superglobals,
which means that they are always accessible, regardless of scope - and you can access them from any function,
class or file without having to do anything special.
$_GET is an array of variables passed to the current script via the URL parameters.
$_POST is an array of variables passed to the current script via the HTTP POST method.
Information sent from a form with the GET method is visible to everyone (all
variable names and values are displayed in the URL). GET also has limits on the amount of
information to send. The limitation is about 2000 characters. However,
because the variables are displayed in the URL, it is possible to bookmark the
page. This can be useful in some cases.
GET may be used for sending non-sensitive data.
Note: GET should NEVER be used for sending passwords or other sensitive information!
Information sent from a form with the POST method is invisible to others
(all names/values are embedded within the body of the HTTP request) and
has no limits on the amount of information to send.
Moreover POST supports advanced functionality such as support for multi-part
binary input while uploading files to server.
However, because the variables are not displayed in the URL, it is not possible to bookmark the page.
Developers prefer POST for sending form data.
Next, lets see how we can process PHP forms the secure way!
If the form in the white section below gets submitted, how can you, in welcome.php, output the value from the "first name" field?
<form action="welcome.php" method="get">
First name: <input type="text" name="fname">
</form>
<html>
<body>
Welcome <?php echo ; ?>
</body>
</html>
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools.
|
[
{
"code": null,
"e": 69,
"s": 0,
"text": "The PHP superglobals $_GET and $_POST are used to collect form-data."
},
{
"code": null,
"e": 158,
"s": 69,
"text": "The example below displays a simple HTML form with two input fields and a submit button:"
},
{
"code": null,
"e": 350,
"s": 158,
"text": "When the user fills out the form above and clicks the submit button, the form data is sent \nfor processing to a PHP file named \"welcome.php\". The form data is sent with \nthe HTTP POST method."
},
{
"code": null,
"e": 456,
"s": 350,
"text": "To display the submitted data you could simply echo all the variables. The \"welcome.php\" looks like this:"
},
{
"code": null,
"e": 497,
"s": 456,
"text": "The output could be something like this:"
},
{
"code": null,
"e": 563,
"s": 497,
"text": "The same result could also be achieved using the HTTP GET method:"
},
{
"code": null,
"e": 602,
"s": 563,
"text": "and \"welcome_get.php\" looks like this:"
},
{
"code": null,
"e": 756,
"s": 602,
"text": "The code above is quite simple. However, the most important thing is missing. You need \nto validate form data to protect your script from malicious code."
},
{
"code": null,
"e": 798,
"s": 756,
"text": "Think SECURITY when processing PHP forms!"
},
{
"code": null,
"e": 902,
"s": 798,
"text": "This page does not contain any form validation, it just shows how you can \nsend and retrieve form data."
},
{
"code": null,
"e": 1077,
"s": 902,
"text": "However, the next pages will show how to process PHP forms with security in mind! Proper validation of form data is important \nto protect your form from hackers and spammers!"
},
{
"code": null,
"e": 1306,
"s": 1077,
"text": "Both GET and POST create an array (e.g. array( key1 => value1, \nkey2 => value2, key3 => value3, ...)). This array holds key/value pairs, where \nkeys are the names of the form controls and values are the input data from the user."
},
{
"code": null,
"e": 1545,
"s": 1306,
"text": "Both GET and POST are treated as $_GET and $_POST. These are superglobals, \nwhich means that they are always accessible, regardless of scope - and you can access them from any function,\nclass or file without having to do anything special."
},
{
"code": null,
"e": 1629,
"s": 1545,
"text": "$_GET is an array of variables passed to the current script via the URL parameters."
},
{
"code": null,
"e": 1716,
"s": 1629,
"text": "$_POST is an array of variables passed to the current script via the HTTP POST method."
},
{
"code": null,
"e": 2077,
"s": 1716,
"text": "Information sent from a form with the GET method is visible to everyone (all \nvariable names and values are displayed in the URL). GET also has limits on the amount of \ninformation to send. The limitation is about 2000 characters. However, \nbecause the variables are displayed in the URL, it is possible to bookmark the \npage. This can be useful in some cases."
},
{
"code": null,
"e": 2125,
"s": 2077,
"text": "GET may be used for sending non-sensitive data."
},
{
"code": null,
"e": 2210,
"s": 2125,
"text": "Note: GET should NEVER be used for sending passwords or other sensitive information!"
},
{
"code": null,
"e": 2409,
"s": 2210,
"text": "Information sent from a form with the POST method is invisible to others \n(all names/values are embedded within the body of the HTTP request) and \nhas no limits on the amount of information to send."
},
{
"code": null,
"e": 2533,
"s": 2409,
"text": "Moreover POST supports advanced functionality such as support for multi-part \nbinary input while uploading files to server."
},
{
"code": null,
"e": 2635,
"s": 2533,
"text": "However, because the variables are not displayed in the URL, it is not possible to bookmark the page."
},
{
"code": null,
"e": 2681,
"s": 2635,
"text": "Developers prefer POST for sending form data."
},
{
"code": null,
"e": 2741,
"s": 2681,
"text": "Next, lets see how we can process PHP forms the secure way!"
},
{
"code": null,
"e": 2871,
"s": 2741,
"text": "If the form in the white section below gets submitted, how can you, in welcome.php, output the value from the \"first name\" field?"
},
{
"code": null,
"e": 3021,
"s": 2871,
"text": "<form action=\"welcome.php\" method=\"get\">\nFirst name: <input type=\"text\" name=\"fname\">\n</form>\n\n<html>\n<body>\nWelcome <?php echo ; ?>\n</body>\n</html>\n"
},
{
"code": null,
"e": 3054,
"s": 3021,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 3096,
"s": 3054,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 3203,
"s": 3096,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 3222,
"s": 3203,
"text": "[email protected]"
}
] |
Colouring the edges by weight in networkx (Matplotlib)
|
To color the edges by weight in networkx, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Initialize a graph with edges, name, or graph attributes.
Add nodes to the current graph.
Add edges to the current graph's nodes.
Iterate the given graph's edges and set some weight to them.
Draw current graphs with weights for edge color.
To display the figure, use show() method.
import random as rd
import matplotlib.pylab as plt
import networkx as nx
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
G = nx.DiGraph()
G.add_nodes_from([1, 2, 3, 4])
G.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])
for u, v, d in G.edges(data=True):
d['weight'] = rd.random()
edges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())
nx.draw(G, node_color='b', edge_color=weights, width=2, with_labels=True)
plt.show()
|
[
{
"code": null,
"e": 1138,
"s": 1062,
"text": "To color the edges by weight in networkx, we can take the following steps −"
},
{
"code": null,
"e": 1214,
"s": 1138,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1272,
"s": 1214,
"text": "Initialize a graph with edges, name, or graph attributes."
},
{
"code": null,
"e": 1304,
"s": 1272,
"text": "Add nodes to the current graph."
},
{
"code": null,
"e": 1344,
"s": 1304,
"text": "Add edges to the current graph's nodes."
},
{
"code": null,
"e": 1405,
"s": 1344,
"text": "Iterate the given graph's edges and set some weight to them."
},
{
"code": null,
"e": 1454,
"s": 1405,
"text": "Draw current graphs with weights for edge color."
},
{
"code": null,
"e": 1496,
"s": 1454,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1982,
"s": 1496,
"text": "import random as rd\nimport matplotlib.pylab as plt\nimport networkx as nx\n\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nG = nx.DiGraph()\nG.add_nodes_from([1, 2, 3, 4])\nG.add_edges_from([(1, 2), (2, 3), (3, 4), (4, 1), (1, 3)])\nfor u, v, d in G.edges(data=True):\n d['weight'] = rd.random()\nedges, weights = zip(*nx.get_edge_attributes(G, 'weight').items())\nnx.draw(G, node_color='b', edge_color=weights, width=2, with_labels=True)\n\nplt.show()"
}
] |
Python 3 - dictionary setdefault() Method
|
The method setdefault() is similar to get(), but will set dict[key] = default if key is not already in dict.
Following is the syntax for setdefault() method −
dict.setdefault(key, default = None)
key − This is the key to be searched.
key − This is the key to be searched.
default − This is the Value to be returned in case key is not found.
default − This is the Value to be returned in case key is not found.
This method returns the key value available in the dictionary and if given key is not available then it will return provided default value.
The following example shows the usage of setdefault() method.
#!/usr/bin/python3
dict = {'Name': 'Zara', 'Age': 7}
print ("Value : %s" % dict.setdefault('Age', None))
print ("Value : %s" % dict.setdefault('Sex', None))
print (dict)
When we run above program, it produces the following result −
Value : 7
Value : None
{'Name': 'Zara', 'Sex': None, 'Age': 7}
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": 2449,
"s": 2340,
"text": "The method setdefault() is similar to get(), but will set dict[key] = default if key is not already in dict."
},
{
"code": null,
"e": 2499,
"s": 2449,
"text": "Following is the syntax for setdefault() method −"
},
{
"code": null,
"e": 2537,
"s": 2499,
"text": "dict.setdefault(key, default = None)\n"
},
{
"code": null,
"e": 2576,
"s": 2537,
"text": "key − This is the key to be searched. "
},
{
"code": null,
"e": 2615,
"s": 2576,
"text": "key − This is the key to be searched. "
},
{
"code": null,
"e": 2684,
"s": 2615,
"text": "default − This is the Value to be returned in case key is not found."
},
{
"code": null,
"e": 2753,
"s": 2684,
"text": "default − This is the Value to be returned in case key is not found."
},
{
"code": null,
"e": 2893,
"s": 2753,
"text": "This method returns the key value available in the dictionary and if given key is not available then it will return provided default value."
},
{
"code": null,
"e": 2955,
"s": 2893,
"text": "The following example shows the usage of setdefault() method."
},
{
"code": null,
"e": 3128,
"s": 2955,
"text": "#!/usr/bin/python3\n\ndict = {'Name': 'Zara', 'Age': 7}\nprint (\"Value : %s\" % dict.setdefault('Age', None))\nprint (\"Value : %s\" % dict.setdefault('Sex', None))\nprint (dict)"
},
{
"code": null,
"e": 3190,
"s": 3128,
"text": "When we run above program, it produces the following result −"
},
{
"code": null,
"e": 3254,
"s": 3190,
"text": "Value : 7\nValue : None\n{'Name': 'Zara', 'Sex': None, 'Age': 7}\n"
},
{
"code": null,
"e": 3291,
"s": 3254,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 3307,
"s": 3291,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3340,
"s": 3307,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 3359,
"s": 3340,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 3394,
"s": 3359,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 3416,
"s": 3394,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 3450,
"s": 3416,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 3478,
"s": 3450,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3513,
"s": 3478,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 3527,
"s": 3513,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3560,
"s": 3527,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3577,
"s": 3560,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3584,
"s": 3577,
"text": " Print"
},
{
"code": null,
"e": 3595,
"s": 3584,
"text": " Add Notes"
}
] |
Macros and Preprocessors in C
|
The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP.
All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −
Some examples of Preprocessors −
Analyze the following examples to understand various directives.
#define MAX_ARRAY_LENGTH 20
This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability.
#include <stdio.h>
#include "myheader.h"
These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file.
#undef FILE_SIZE
#define FILE_SIZE 42
It tells the CPP to undefine existing FILE_SIZE and define it as 42.
#ifndef MESSAGE
#define MESSAGE "You wish!"
#endif
It tells the CPP to define MESSAGE only if MESSAGE isn't already defined.
#ifdef DEBUG
/* Your debugging statements here */
#endif
It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation.
ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified.
#include <stdio.h>
int main() {
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("ANSI :%d\n", __STDC__ );
}
File :test.c
Date :Jun 2 2012
Time :03:36:24
Line :8
ANSI :1
|
[
{
"code": null,
"e": 1363,
"s": 1062,
"text": "The C Preprocessor is not a part of the compiler, but is a separate step in the compilation process. In simple terms, a C Preprocessor is just a text substitution tool and it instructs the compiler to do required pre-processing before the actual compilation. We'll refer to the C Preprocessor as CPP."
},
{
"code": null,
"e": 1617,
"s": 1363,
"text": "All preprocessor commands begin with a hash symbol (#). It must be the first nonblank character, and for readability, a preprocessor directive should begin in the first column. The following section lists down all the important preprocessor directives −"
},
{
"code": null,
"e": 1650,
"s": 1617,
"text": "Some examples of Preprocessors −"
},
{
"code": null,
"e": 1715,
"s": 1650,
"text": "Analyze the following examples to understand various directives."
},
{
"code": null,
"e": 1743,
"s": 1715,
"text": "#define MAX_ARRAY_LENGTH 20"
},
{
"code": null,
"e": 1873,
"s": 1743,
"text": "This directive tells the CPP to replace instances of MAX_ARRAY_LENGTH with 20. Use #define for constants to increase readability."
},
{
"code": null,
"e": 1914,
"s": 1873,
"text": "#include <stdio.h>\n#include \"myheader.h\""
},
{
"code": null,
"e": 2141,
"s": 1914,
"text": "These directives tell the CPP to get stdio.h from System Libraries and add the text to the current source file. The next line tells CPP to get myheader.h from the local directory and add the content to the current source file."
},
{
"code": null,
"e": 2179,
"s": 2141,
"text": "#undef FILE_SIZE\n#define FILE_SIZE 42"
},
{
"code": null,
"e": 2248,
"s": 2179,
"text": "It tells the CPP to undefine existing FILE_SIZE and define it as 42."
},
{
"code": null,
"e": 2299,
"s": 2248,
"text": "#ifndef MESSAGE\n#define MESSAGE \"You wish!\"\n#endif"
},
{
"code": null,
"e": 2373,
"s": 2299,
"text": "It tells the CPP to define MESSAGE only if MESSAGE isn't already defined."
},
{
"code": null,
"e": 2430,
"s": 2373,
"text": "#ifdef DEBUG\n/* Your debugging statements here */\n#endif"
},
{
"code": null,
"e": 2687,
"s": 2430,
"text": "It tells the CPP to process the statements enclosed if DEBUG is defined. This is useful if you pass the -DDEBUG flag to the gcc compiler at the time of compilation. This will define DEBUG, so you can turn debugging on and off on the fly during compilation."
},
{
"code": null,
"e": 2832,
"s": 2687,
"text": "ANSI C defines a number of macros. Although each one is available for use in programming, the predefined macros should not be directly modified."
},
{
"code": null,
"e": 3046,
"s": 2832,
"text": "#include <stdio.h>\nint main() {\n printf(\"File :%s\\n\", __FILE__ );\n printf(\"Date :%s\\n\", __DATE__ );\n printf(\"Time :%s\\n\", __TIME__ );\n printf(\"Line :%d\\n\", __LINE__ );\n printf(\"ANSI :%d\\n\", __STDC__ );\n}"
},
{
"code": null,
"e": 3107,
"s": 3046,
"text": "File :test.c\nDate :Jun 2 2012\nTime :03:36:24\nLine :8\nANSI :1"
}
] |
How to use the Subprocess Module in Python?
|
When you code and execute a program on Windows, MAC or Linux, your Operating System creates a process(single).It uses system resources like CPU, RAM, Disk space and also data structures in the operating system’s kernel. A process is isolated from other processes—it can’t see what other processes are doing or interfere with them.
Note: This code has to be run on Linux like sytems. When executed on windows might throw exceptions.
The main twin goals of OS are to spread the work of the process fairly and be responsive to the user. These are acheived by keeping a track of all the running processes, giving each a little time to run and then switching to another. You can see the state of your processes with graphical interfaces such as the Task Manager on Windows-based computers, the Mac’s Activity Monitor (macOS),or the top command in Linux.
Being a programmer, we can access the process data from our own program. But How? Simply by using standard library OS module. I will show you few examples.
# This script works only on linux/unix
import os
print(f" *** Process ID - {os.getpid()}")
print(f" *** My User ID - {os.getuid()} and My Group ID - {os.getgid()} ")
print(f" *** Current Working Directory is - {os.getcwd()}")
Running and spinning up a new system process can be quite useful to developers and system administrators who want to automate specific operating system tasks.
Python has a subprocess module, which can spin a new processes, send and receive information from the processes, and also handle error and return codes.
The official Python documentation recommends the subprocess module for accessing system commands.
The subprocess call() function waits for the called command to finish reading the output. We will see couple of examples below to extract the systems disk space information.
Below code will execute df -h command and captures the information. The output is then captured to a pandas dataframe for any further processing.
# python code to create a subprocess for extracting disk space on linux using df -h
from io import StringIO
import pandas as pd
import subprocess
import ast
diskspace = "df"
diskspace_arg = "-h"
sp = subprocess.Popen([diskspace,diskspace_arg], stdout=subprocess.PIPE)
b = StringIO(sp.communicate()[0].decode('utf-8'))
df = pd.read_csv(b, sep=",")
print(df)
<_io.StringIO object at 0x7ff67ef52798>
Filesystem Size Used Avail Use% Mounted on
0 devtmpfs 7.8G 0 7.8G 0% /dev
1 tmpfs 7.8G 0 7.8G 0% /dev/shm
2 tmpfs 7.8G 33M 7.8G 1% /run
3 tmpfs 7.8G 0 7.8G 0% /sys/fs/...
4 /dev/xvda2 20G 16G 4.3G 79% /
5 /dev/xvdb 246G 16G 218G 7% /tdm
6 tmpfs 1.6G 0 1.6G 0% /run/use...
To get a more detailed output with subprocess see below code.
from io import StringIO
import pandas as pd
import subprocess
def uname_func():
uname = "uname"
uname_arg = "-a"
user_info = subprocess.call([uname, uname_arg])
return user_info
def disk_func():
diskspace = "pydf"
diskspace_arg = "-a"
discinfo_df = diskspace
stdout = subprocess.check_output([diskspace, diskspace_arg])
return stdout
def main():
userinfo = uname_func()
discinfo = disk_func()
print("Displaying values now... ")
# print(stdout.decode('utf-8'))
print(discinfo.decode('utf-8'))
print(type(discinfo.decode('utf-8')))
content = discinfo.decode('utf-8').split("\n")
print(content)
main()
Linux ip-00-000-00-000.xxxx.xxxx.xx.xx 0.00.0-000.el7.x86_64 #1 SMP Tue Aug 18 14:50:17 EDT 2020 x86_64 x86_64 x86_64 GNU/Linux
Displaying values now...
Filesystem Size Used Avail Use% Mounted on
/dev/xvda2 20G 16G 4318M 78.9 [#####.] /
devtmpfs 7918M 0 7918M 0.0 [......] /dev
hugetlbfs 0 0 0 - [......] /dev/hugepages
mqueue 0 0 0 - [......] /dev/mqueue
devpts 0 0 0 - [......] /dev/pts
tmpfs 7942M 0 7942M 0.0 [......] /dev/shm
proc 0 0 0 - [......] /proc
binfmt_misc 0 0 0 - [......] /proc/sys/fs/binfmt_misc
tmpfs 7942M 32M 7909M 0.4 [......] /run
tmpfs 1588M 0 1588M 0.0 [......] /run/user/1000
sysfs 0 0 0 - [......] /sys
tmpfs 7942M 0 7942M 0.0 [......] /sys/fs/cgroup
cgroup 0 0 0 - [......] /sys/fs/cgroup/blkio
cgroup 0 0 0 - [......] /sys/fs/cgroup/cpu,cpuacct
cgroup 0 0 0 - [......] /sys/fs/cgroup/cpuset
cgroup 0 0 0 - [......] /sys/fs/cgroup/devices
cgroup 0 0 0 - [......] /sys/fs/cgroup/freezer
cgroup 0 0 0 - [......] /sys/fs/cgroup/hugetlb
cgroup 0 0 0 - [......] /sys/fs/cgroup/memory
cgroup 0 0 0 - [......] /sys/fs/cgroup/net_cls,net_prio
cgroup 0 0 0 - [......] /sys/fs/cgroup/perf_event
cgroup 0 0 0 - [......] /sys/fs/cgroup/pids
cgroup 0 0 0 - [......] /sys/fs/cgroup/systemd
pstore 0 0 0 - [......] /sys/fs/pstore
configfs 0 0 0 - [......] /sys/kernel/config
debugfs 0 0 0 - [......] /sys/kernel/debug
securityfs 0 0 0 - [......] /sys/kernel/security
/dev/xvdb 246G 16G 218G 6.4 [......] /tdm
|
[
{
"code": null,
"e": 1393,
"s": 1062,
"text": "When you code and execute a program on Windows, MAC or Linux, your Operating System creates a process(single).It uses system resources like CPU, RAM, Disk space and also data structures in the operating system’s kernel. A process is isolated from other processes—it can’t see what other processes are doing or interfere with them."
},
{
"code": null,
"e": 1494,
"s": 1393,
"text": "Note: This code has to be run on Linux like sytems. When executed on windows might throw exceptions."
},
{
"code": null,
"e": 1911,
"s": 1494,
"text": "The main twin goals of OS are to spread the work of the process fairly and be responsive to the user. These are acheived by keeping a track of all the running processes, giving each a little time to run and then switching to another. You can see the state of your processes with graphical interfaces such as the Task Manager on Windows-based computers, the Mac’s Activity Monitor (macOS),or the top command in Linux."
},
{
"code": null,
"e": 2067,
"s": 1911,
"text": "Being a programmer, we can access the process data from our own program. But How? Simply by using standard library OS module. I will show you few examples."
},
{
"code": null,
"e": 2293,
"s": 2067,
"text": "# This script works only on linux/unix\nimport os\nprint(f\" *** Process ID - {os.getpid()}\")\nprint(f\" *** My User ID - {os.getuid()} and My Group ID - {os.getgid()} \")\nprint(f\" *** Current Working Directory is - {os.getcwd()}\")"
},
{
"code": null,
"e": 2452,
"s": 2293,
"text": "Running and spinning up a new system process can be quite useful to developers and system administrators who want to automate specific operating system tasks."
},
{
"code": null,
"e": 2605,
"s": 2452,
"text": "Python has a subprocess module, which can spin a new processes, send and receive information from the processes, and also handle error and return codes."
},
{
"code": null,
"e": 2703,
"s": 2605,
"text": "The official Python documentation recommends the subprocess module for accessing system commands."
},
{
"code": null,
"e": 2877,
"s": 2703,
"text": "The subprocess call() function waits for the called command to finish reading the output. We will see couple of examples below to extract the systems disk space information."
},
{
"code": null,
"e": 3023,
"s": 2877,
"text": "Below code will execute df -h command and captures the information. The output is then captured to a pandas dataframe for any further processing."
},
{
"code": null,
"e": 3382,
"s": 3023,
"text": "# python code to create a subprocess for extracting disk space on linux using df -h\n\nfrom io import StringIO\nimport pandas as pd\nimport subprocess\nimport ast\ndiskspace = \"df\"\ndiskspace_arg = \"-h\"\n\nsp = subprocess.Popen([diskspace,diskspace_arg], stdout=subprocess.PIPE)\nb = StringIO(sp.communicate()[0].decode('utf-8'))\ndf = pd.read_csv(b, sep=\",\")\nprint(df)"
},
{
"code": null,
"e": 3694,
"s": 3382,
"text": "<_io.StringIO object at 0x7ff67ef52798>\nFilesystem Size Used Avail Use% Mounted on\n0 devtmpfs 7.8G 0 7.8G 0% /dev\n1 tmpfs 7.8G 0 7.8G 0% /dev/shm\n2 tmpfs 7.8G 33M 7.8G 1% /run\n3 tmpfs 7.8G 0 7.8G 0% /sys/fs/...\n4 /dev/xvda2 20G 16G 4.3G 79% /\n5 /dev/xvdb 246G 16G 218G 7% /tdm\n6 tmpfs 1.6G 0 1.6G 0% /run/use..."
},
{
"code": null,
"e": 3756,
"s": 3694,
"text": "To get a more detailed output with subprocess see below code."
},
{
"code": null,
"e": 4358,
"s": 3756,
"text": "from io import StringIO\nimport pandas as pd\nimport subprocess\ndef uname_func():\nuname = \"uname\"\nuname_arg = \"-a\"\nuser_info = subprocess.call([uname, uname_arg])\nreturn user_info\n\ndef disk_func():\ndiskspace = \"pydf\"\ndiskspace_arg = \"-a\"\ndiscinfo_df = diskspace\nstdout = subprocess.check_output([diskspace, diskspace_arg])\nreturn stdout\n\ndef main():\nuserinfo = uname_func()\ndiscinfo = disk_func()\nprint(\"Displaying values now... \")\n# print(stdout.decode('utf-8'))\nprint(discinfo.decode('utf-8'))\nprint(type(discinfo.decode('utf-8')))\ncontent = discinfo.decode('utf-8').split(\"\\n\")\nprint(content)\n\nmain()"
},
{
"code": null,
"e": 5779,
"s": 4358,
"text": "Linux ip-00-000-00-000.xxxx.xxxx.xx.xx 0.00.0-000.el7.x86_64 #1 SMP Tue Aug 18 14:50:17 EDT 2020 x86_64 x86_64 x86_64 GNU/Linux\nDisplaying values now...\nFilesystem Size Used Avail Use% Mounted on\n/dev/xvda2 20G 16G 4318M 78.9 [#####.] /\ndevtmpfs 7918M 0 7918M 0.0 [......] /dev\nhugetlbfs 0 0 0 - [......] /dev/hugepages\nmqueue 0 0 0 - [......] /dev/mqueue\ndevpts 0 0 0 - [......] /dev/pts\ntmpfs 7942M 0 7942M 0.0 [......] /dev/shm\nproc 0 0 0 - [......] /proc\nbinfmt_misc 0 0 0 - [......] /proc/sys/fs/binfmt_misc\ntmpfs 7942M 32M 7909M 0.4 [......] /run\ntmpfs 1588M 0 1588M 0.0 [......] /run/user/1000\nsysfs 0 0 0 - [......] /sys\ntmpfs 7942M 0 7942M 0.0 [......] /sys/fs/cgroup\ncgroup 0 0 0 - [......] /sys/fs/cgroup/blkio\ncgroup 0 0 0 - [......] /sys/fs/cgroup/cpu,cpuacct\ncgroup 0 0 0 - [......] /sys/fs/cgroup/cpuset\ncgroup 0 0 0 - [......] /sys/fs/cgroup/devices\ncgroup 0 0 0 - [......] /sys/fs/cgroup/freezer\ncgroup 0 0 0 - [......] /sys/fs/cgroup/hugetlb\ncgroup 0 0 0 - [......] /sys/fs/cgroup/memory\ncgroup 0 0 0 - [......] /sys/fs/cgroup/net_cls,net_prio\ncgroup 0 0 0 - [......] /sys/fs/cgroup/perf_event\ncgroup 0 0 0 - [......] /sys/fs/cgroup/pids\ncgroup 0 0 0 - [......] /sys/fs/cgroup/systemd\npstore 0 0 0 - [......] /sys/fs/pstore\nconfigfs 0 0 0 - [......] /sys/kernel/config\ndebugfs 0 0 0 - [......] /sys/kernel/debug\nsecurityfs 0 0 0 - [......] /sys/kernel/security\n/dev/xvdb 246G 16G 218G 6.4 [......] /tdm"
}
] |
How can we check the list of all triggers in a database?
|
With the help of the SHOW TRIGGERS statement, we can list all the triggers in a particular database. It can be illustrated with the help of the following example −
mysql> Show Triggers\G
*************************** 1. row ***************************
Trigger: trigger_before_delete_sample
Event: DELETE
Table: sample
Statement: BEGIN
SET @count = if (@count IS NULL, 1, (@count+1));
INSERT INTO sample_rowaffected values (@count);
END
Timing: BEFORE
Created: 2017-11-21 12:31:58.70
sql_mode:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERR
OR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Definer: root@localhost
character_set_client: cp850
collation_connection: cp850_general_ci
Database Collation: latin1_swedish_ci
*************************** 2. row ***************************
Trigger: before_inser_studentage
Event: INSERT
Table: student_age
Statement: IF NEW.age < 0 THEN SET NEW.age = 0;
END IF
Timing: BEFORE
Created: 2017-11-21 11:26:15.34
sql_mode:
ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERR
OR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION
Definer: root@localhost
character_set_client: cp850
collation_connection: cp850_general_ci
Database Collation: latin1_swedish_ci
2 rows in set (0.01 sec)
The above result set gives the list of triggers in the current database. Now, if we want to get the list of triggers in a particular database then we can use the following statement −
mysql> Show Triggers from tutorials\G
Empty set (0.00 sec)
The above result set shows that there is no trigger in the database named ‘tutorials’.
|
[
{
"code": null,
"e": 1226,
"s": 1062,
"text": "With the help of the SHOW TRIGGERS statement, we can list all the triggers in a particular database. It can be illustrated with the help of the following example −"
},
{
"code": null,
"e": 2416,
"s": 1226,
"text": "mysql> Show Triggers\\G\n*************************** 1. row ***************************\n Trigger: trigger_before_delete_sample\n Event: DELETE\n Table: sample\nStatement: BEGIN\n\nSET @count = if (@count IS NULL, 1, (@count+1));\nINSERT INTO sample_rowaffected values (@count);\nEND\n\n Timing: BEFORE\n Created: 2017-11-21 12:31:58.70\nsql_mode:\n\nONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERR\nOR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\n Definer: root@localhost\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n Database Collation: latin1_swedish_ci\n*************************** 2. row ***************************\n Trigger: before_inser_studentage\n Event: INSERT\n Table: student_age\nStatement: IF NEW.age < 0 THEN SET NEW.age = 0;\nEND IF\n Timing: BEFORE\n Created: 2017-11-21 11:26:15.34\nsql_mode:\n\nONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERR\nOR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION\n\n Definer: root@localhost\ncharacter_set_client: cp850\ncollation_connection: cp850_general_ci\n Database Collation: latin1_swedish_ci\n2 rows in set (0.01 sec)"
},
{
"code": null,
"e": 2600,
"s": 2416,
"text": "The above result set gives the list of triggers in the current database. Now, if we want to get the list of triggers in a particular database then we can use the following statement −"
},
{
"code": null,
"e": 2659,
"s": 2600,
"text": "mysql> Show Triggers from tutorials\\G\nEmpty set (0.00 sec)"
},
{
"code": null,
"e": 2746,
"s": 2659,
"text": "The above result set shows that there is no trigger in the database named ‘tutorials’."
}
] |
Teaching Cars To Drive Using Deep Learning — Steering Angle Prediction | by Eddie Forson | Towards Data Science
|
This is project 3 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
Over the recent years, and more particularly since the success of the Darpa Grand Challenge competitions a decade ago, the race towards the development of fully autonomous vehicles has accelerated tremendously. Many components make up an autonomous vehicle, and some of its most critical ones are the sensors and AI software that powers it. Moreover, with the increase in computational capabilities, we are now able to train complex and deep neural networks that are able to learn crucial details, visual and beyond, and become the brain of the car, understanding the vehicle’s environment and deciding on the next decisions to take.
In this writeup, we are going to cover how we can train a deep learning model to predict steering wheel angles and help a virtual car drive itself in a simulator. The model is created using Keras, relying on Tensorflow as the backend.
As part of this project, we are provided a simulator, written with Unity, that comes in two modes:
Training Mode: we manually drive the vehicle and collect data
Autonomous Mode: the vehicle drives itself based on a model trained from the collected data
The data log is saved in a csv file and contains the path to the images as well as steering wheel angle, throttle and speed. We are only concerned with the steering wheel angle and the images for this project.
As can be seen in the image below, the simulator contains 2 track. The track on the right (track 2) is much more difficult than track 1 as it contains slopes and sharp turns.
This project was in fact inspired by the paper “End To End Learning For Self Driving Cars” by researchers at NVIDIA, who managed to get a car to drive autonomously by training a convolutional neural network to predict steering wheel angles based on steering angle data and images captured by three cameras (left, center, right) mounted in front of the car. The trained model is able to accurately steer the car using only the center camera. The diagram below shows the process used to create such an efficient model.
Unlike NVIDIA, who were doing real-world autonomous driving, we are going to teach our car to drive in the simulator. However, the same principles should apply. We are further bolstered in this claim thanks to the recent coverage on how simulations play a critical role in the development of self-driving technology for companies such as Waymo.
We ended up using 4 datasets:
Udacity’s dataset on track 1A manually created dataset on track 1 (we name it Standard dataset)Another manually created dataset on track 1 where we drive close to the bounds and recover to teach the model how to avoid going out of bounds — in the real world this would be called reckless or drink drivingA manually created dataset on track 2
Udacity’s dataset on track 1
A manually created dataset on track 1 (we name it Standard dataset)
Another manually created dataset on track 1 where we drive close to the bounds and recover to teach the model how to avoid going out of bounds — in the real world this would be called reckless or drink driving
A manually created dataset on track 2
Note that in all our manually created datasets, we drive in both directions to help our model generalise.
However, upon analysing the steering angles captured across our datasets, we quickly realised we had a problem: the data is greatly imbalanced, with an overwhelming number of steering wheel data being neutral (i.e. 0). This means, that unless we take corrective measures, our model will be biased to driving straight.
Notice however, that the data on track 2 shows a lot more variability with many sharp turns, as we would expect from such a track. There is still a strong bias towards driving straight though, even in this case.
In the end, we decided to create an ensemble training dataset composed of the Udacity dataset, our Recovery dataset, and our dataset from track 2. We decided to use the Standard dataset from track 1 as the validation set.
frames = [recovery_csv, udacity_csv, track2_csv]ensemble_csv = pd.concat(frames)validation_csv = standard_csv
This helped us start with close to 55K training images and potentially 44K validation ones.
We have a good number of data points, but sadly as most of the them show the car driving with a neutral steering wheel angle, our car would tend to drive itself in a straight line. The example below shows our first model with no balancing of the training dataset:
Moreover, on the tracks there are also shadows which could throw the model into confusion. The model would also need to learn to steer correctly whether the car is on the left or right side of the road. Therefore, we must find a way to artificially increase and vary our images and steering angles. We turn to data augmentation techniques for this purpose.
First of all, we add a steering angle calibration offset to images captured by either left or right cameras:
for the left camera we want the car to steer to the right (positive offset)
for the right camera we want the car to steer to the left (negative offset)
st_angle_names = ["Center", "Left", "Right"]st_angle_calibrations = [0, 0.25, -0.25]
The values above are empirically chosen.
Since we want our car to be able to steer itself regardless of its position on the road, we apply a horizontal flip to a proportion of images, and naturally invert the original steering angle:
def fliph_image(img): """ Returns a horizontally flipped image """ return cv2.flip(img, 1)
Since some parts of our tracks are much darker, due to shadows or otherwise, we also darken a proportion of our images by multiplying all RGB color channels by a scalar randomly picked from a range:
def change_image_brightness_rgb(img, s_low=0.2, s_high=0.75): """ Changes the image brightness by multiplying all RGB values by the same scalacar in [s_low, s_high). Returns the brightness adjusted image in RGB format. """ img = img.astype(np.float32) s = np.random.uniform(s_low, s_high) img[:,:,:] *= s np.clip(img, 0, 255) return img.astype(np.uint8)
Since we sometimes have patches of the track covered by a shadow, we also have to train our model to recognise them and not be spooked by them.
def add_random_shadow(img, w_low=0.6, w_high=0.85): """ Overlays supplied image with a random shadow polygon The weight range (i.e. darkness) of the shadow can be configured via the interval [w_low, w_high) """ cols, rows = (img.shape[0], img.shape[1]) top_y = np.random.random_sample() * rows bottom_y = np.random.random_sample() * rows bottom_y_right = bottom_y + np.random.random_sample() * (rows - bottom_y) top_y_right = top_y + np.random.random_sample() * (rows - top_y) if np.random.random_sample() <= 0.5: bottom_y_right = bottom_y - np.random.random_sample() * (bottom_y) top_y_right = top_y - np.random.random_sample() * (top_y) poly = np.asarray([[ [top_y,0], [bottom_y, cols], [bottom_y_right, cols], [top_y_right,0]]], dtype=np.int32) mask_weight = np.random.uniform(w_low, w_high) origin_weight = 1 - mask_weight mask = np.copy(img).astype(np.int32) cv2.fillPoly(mask, poly, (0, 0, 0)) #masked_image = cv2.bitwise_and(img, mask) return cv2.addWeighted(img.astype(np.int32), origin_weight, mask, mask_weight, 0).astype(np.uint8)
To combat the high number of neutral angles, and provide more variety to the dataset, we apply random shifts to the image, and add a given offset to the steering angle for every pixel shifted laterally. In our case we empirically settled on adding (or subtracting) 0.0035 for every pixel shifted to the left or right. Shifting the image up/down should cause the model to believe it is on the upward/downward slope. From experimentation, we believe that these lateral shifts are possibly the most important augmentations needed to get the car to drive properly.
# Read more about it here: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.htmldef translate_image(img, st_angle, low_x_range, high_x_range, low_y_range, high_y_range, delta_st_angle_per_px): """ Shifts the image right, left, up or down. When performing a lateral shift, a delta proportional to the pixel shifts is added to the current steering angle """ rows, cols = (img.shape[0], img.shape[1]) translation_x = np.random.randint(low_x_range, high_x_range) translation_y = np.random.randint(low_y_range, high_y_range) st_angle += translation_x * delta_st_angle_per_px translation_matrix = np.float32([[1, 0, translation_x],[0, 1, translation_y]]) img = cv2.warpAffine(img, translation_matrix, (cols, rows)) return img, st_angle
Our image augmentation function is straightforward: each supplied image goes through a series of augmentations, each occurring with a probability p between 0 and 1. All the code of augmenting the image is delegated to the appropriate augmenter function presented above.
def augment_image(img, st_angle, p=1.0): """ Augment a given image, by applying a series of transformations, with a probability p. The steering angle may also be modified. Returns the tuple (augmented_image, new_steering_angle) """ aug_img = img if np.random.random_sample() <= p: aug_img = fliph_image(aug_img) st_angle = -st_angle if np.random.random_sample() <= p: aug_img = change_image_brightness_rgb(aug_img) if np.random.random_sample() <= p: aug_img = add_random_shadow(aug_img, w_low=0.45) if np.random.random_sample() <= p: aug_img, st_angle = translate_image(aug_img, st_angle, -60, 61, -20, 21, 0.35/100.0) return aug_img, st_angle
Since we are generating new and augmented images on the fly as we train the model, we create a Keras generator to produce new images at each batch:
def generate_images(df, target_dimensions, img_types, st_column, st_angle_calibrations, batch_size=100, shuffle=True, data_aug_pct=0.8, aug_likelihood=0.5, st_angle_threshold=0.05, neutral_drop_pct=0.25): """ Generates images whose paths and steering angle are stored in the supplied dataframe object df Returns the tuple (batch,steering_angles) """ # e.g. 160x320x3 for target_dimensions batch = np.zeros((batch_size, target_dimensions[0], target_dimensions[1], target_dimensions[2]), dtype=np.float32) steering_angles = np.zeros(batch_size) df_len = len(df) while True: k = 0 while k < batch_size: idx = np.random.randint(0, df_len) for img_t, st_calib in zip(img_types, st_angle_calibrations): if k >= batch_size: break row = df.iloc[idx] st_angle = row[st_column] # Drop neutral-ish steering angle images with some probability if abs(st_angle) < st_angle_threshold and np.random.random_sample() <= neutral_drop_pct : continue st_angle += st_calib img_type_path = row[img_t] img = read_img(img_type_path) # Resize image img, st_angle = augment_image(img, st_angle, p=aug_likelihood) if np.random.random_sample() <= data_aug_pct else (img, st_angle) batch[k] = img steering_angles[k] = st_angle k += 1 yield batch, np.clip(steering_angles, -1, 1)
Note that we have the ability to drop a proportion of neutral angles, as well as keeping (i.e. not augmenting) a proportion of images at each batch.
The following shows a small portion of augmented images from a batch:
Moreover, the accompanying histogram of steering angles of those augmented images shows much more balance:
We initially tried a variant of the VGG architecture, with less layers and no transfer learning, but struggled to get satisfying results. Ultimately, we settled on the architecture used in the NVIDIA paper as it gave us the best results:
However, we added some slight tweaks to the model:
We crop the top of the images so as to exclude the horizon (it does not play a role in immediately determining the steering angle)
We resize the images to 66x200 in the model, as one the early layers, to take advantage of the GPU
We apply BatchNormalization after each activation function for faster convergence
The second dense layer has output size 200 instead of 100
The full architecture of the model is as follows:
Input image is 160x320 (height x width format)
Image is vertically cropped at the top, by removing half of the height (80 pixels), resulting in an image of 80x320
Cropped image is normalized, to make sure the mean of our pixel distribution is 0
Cropped image is resized to 66x200, using Tensorflow’s tf.image.resize_images
We apply a series of 3 of 5x5 convolutional layers, using a stride of 2x2. Each convolutional layer is followed by a BatchNormalization operation to improve convergence. The respective depth of each layer is 24, 36 and 48 as we go deeper into the network
We apply a 2 consecutive 3x3 convolutional layers, with a depth of 64. Each convolutional layer is immediately followed by a BatchNormalization operation
We flatten the input at this stage and enter the fully connected phase
We apply a series of fully connected layers, of gradually decreasing sizes: 1164, 200, 50 and 10
The output layer is obviously of size 1, since we predict only one variable, the steering wheel angle.
The activation function used across all layers, bar the last one, is ReLU. We tried ELU as well but got better results with ReLU + BatchNormalization. We use the Mean Squared Error activation for the output layer since this is a regression problem, not a classification one.
As stated in the previous section, we employed BatchNormalization to hasten convergence. We did try some degree of Dropout but did not find any noticeable difference. We believe the fact that we are generating new images at every batch and discarding some of the neutral angle images help in reducing overfitting. Moreover, we did not apply any MaxPool operation to our NVIDIA network (although we tried on the VGG inspired one) as it would have required significant changes in the architecture since we would have reduced dimensionality much earlier. Moreover, we did not have the time to experiment with L2 regularisation, but plan to try it in the future.
We trained the model using Adam as the optimizer and a learning rate of 0.001. After much, tweaking of parameters, and experimentation of multiple models, we ended up with one that is able power our virtual car to drive autonomously on both tracks.
We can see how the vehicle effectively manages to drive down a steep slope on track 2.
We also show what the front camera sees when driving autonomously on track 2. We can see how the car tries to stick to the lane and not go in the middle, as we ourselves strived to drive on only one side of the road during our data collection phase. This shows the model has indeed learned to stay within its lane.
To top it all up, I even created a video montage for you, using Tron Legacy’s The Grid as background music. Enjoy!
We have shown that it is possible to create a model that reliably predicts steering wheel angles for a vehicle using a deep neural network and a plethora of data augmentation techniques. While we have obtained encouraging results, we would like in the future to explore the following:
Take into account speed and throttle in the model
Get the car to drive faster than 15–20MPH
Experiment with models based VGG/ResNets/Inception via transfer learning
Use Recurrent Neural Networks like in this paper from people using the Udacity dataset
Read the Learning A Driving Simulator paper by comma.ai and attempt to implement their model
Experiment with Reinforcement Learning
As can be seen, there are many areas we could explore to push this project further and obtain even more convincing results. One of the most important learnings from this project is that DATA IS KING: without all those images and steering angles, along with their potentially infinite augmentations, we would not have been able to build a robust enough model.
From a personal perspective, I have tremendously enjoyed this project, the hardest so far, as it enabled me to gain more practical experience of hyper-parameter tweaking, data augmentation, and dataset balancing among other important concepts. I feel my intuition of neural network architectures has deepened as well.
I would also like to thank my Udacity mentor Dylan for his support and sound advice, as well as the Udacity students before my cohort who explained how they approached this project via blog posts. I was inspired by reading their posts: they definitely helped me in developing a stronger grasp of the concepts needed to successfully complete this project.
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": 359,
"s": 172,
"text": "This is project 3 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": 413,
"s": 359,
"text": "project 1: Detecting Lane Lines Using Computer Vision"
},
{
"code": null,
"e": 472,
"s": 413,
"text": "project 2: Traffic Sign Classification Using Deep Learning"
},
{
"code": null,
"e": 1106,
"s": 472,
"text": "Over the recent years, and more particularly since the success of the Darpa Grand Challenge competitions a decade ago, the race towards the development of fully autonomous vehicles has accelerated tremendously. Many components make up an autonomous vehicle, and some of its most critical ones are the sensors and AI software that powers it. Moreover, with the increase in computational capabilities, we are now able to train complex and deep neural networks that are able to learn crucial details, visual and beyond, and become the brain of the car, understanding the vehicle’s environment and deciding on the next decisions to take."
},
{
"code": null,
"e": 1341,
"s": 1106,
"text": "In this writeup, we are going to cover how we can train a deep learning model to predict steering wheel angles and help a virtual car drive itself in a simulator. The model is created using Keras, relying on Tensorflow as the backend."
},
{
"code": null,
"e": 1440,
"s": 1341,
"text": "As part of this project, we are provided a simulator, written with Unity, that comes in two modes:"
},
{
"code": null,
"e": 1502,
"s": 1440,
"text": "Training Mode: we manually drive the vehicle and collect data"
},
{
"code": null,
"e": 1594,
"s": 1502,
"text": "Autonomous Mode: the vehicle drives itself based on a model trained from the collected data"
},
{
"code": null,
"e": 1804,
"s": 1594,
"text": "The data log is saved in a csv file and contains the path to the images as well as steering wheel angle, throttle and speed. We are only concerned with the steering wheel angle and the images for this project."
},
{
"code": null,
"e": 1979,
"s": 1804,
"text": "As can be seen in the image below, the simulator contains 2 track. The track on the right (track 2) is much more difficult than track 1 as it contains slopes and sharp turns."
},
{
"code": null,
"e": 2496,
"s": 1979,
"text": "This project was in fact inspired by the paper “End To End Learning For Self Driving Cars” by researchers at NVIDIA, who managed to get a car to drive autonomously by training a convolutional neural network to predict steering wheel angles based on steering angle data and images captured by three cameras (left, center, right) mounted in front of the car. The trained model is able to accurately steer the car using only the center camera. The diagram below shows the process used to create such an efficient model."
},
{
"code": null,
"e": 2841,
"s": 2496,
"text": "Unlike NVIDIA, who were doing real-world autonomous driving, we are going to teach our car to drive in the simulator. However, the same principles should apply. We are further bolstered in this claim thanks to the recent coverage on how simulations play a critical role in the development of self-driving technology for companies such as Waymo."
},
{
"code": null,
"e": 2871,
"s": 2841,
"text": "We ended up using 4 datasets:"
},
{
"code": null,
"e": 3213,
"s": 2871,
"text": "Udacity’s dataset on track 1A manually created dataset on track 1 (we name it Standard dataset)Another manually created dataset on track 1 where we drive close to the bounds and recover to teach the model how to avoid going out of bounds — in the real world this would be called reckless or drink drivingA manually created dataset on track 2"
},
{
"code": null,
"e": 3242,
"s": 3213,
"text": "Udacity’s dataset on track 1"
},
{
"code": null,
"e": 3310,
"s": 3242,
"text": "A manually created dataset on track 1 (we name it Standard dataset)"
},
{
"code": null,
"e": 3520,
"s": 3310,
"text": "Another manually created dataset on track 1 where we drive close to the bounds and recover to teach the model how to avoid going out of bounds — in the real world this would be called reckless or drink driving"
},
{
"code": null,
"e": 3558,
"s": 3520,
"text": "A manually created dataset on track 2"
},
{
"code": null,
"e": 3664,
"s": 3558,
"text": "Note that in all our manually created datasets, we drive in both directions to help our model generalise."
},
{
"code": null,
"e": 3982,
"s": 3664,
"text": "However, upon analysing the steering angles captured across our datasets, we quickly realised we had a problem: the data is greatly imbalanced, with an overwhelming number of steering wheel data being neutral (i.e. 0). This means, that unless we take corrective measures, our model will be biased to driving straight."
},
{
"code": null,
"e": 4194,
"s": 3982,
"text": "Notice however, that the data on track 2 shows a lot more variability with many sharp turns, as we would expect from such a track. There is still a strong bias towards driving straight though, even in this case."
},
{
"code": null,
"e": 4416,
"s": 4194,
"text": "In the end, we decided to create an ensemble training dataset composed of the Udacity dataset, our Recovery dataset, and our dataset from track 2. We decided to use the Standard dataset from track 1 as the validation set."
},
{
"code": null,
"e": 4526,
"s": 4416,
"text": "frames = [recovery_csv, udacity_csv, track2_csv]ensemble_csv = pd.concat(frames)validation_csv = standard_csv"
},
{
"code": null,
"e": 4618,
"s": 4526,
"text": "This helped us start with close to 55K training images and potentially 44K validation ones."
},
{
"code": null,
"e": 4882,
"s": 4618,
"text": "We have a good number of data points, but sadly as most of the them show the car driving with a neutral steering wheel angle, our car would tend to drive itself in a straight line. The example below shows our first model with no balancing of the training dataset:"
},
{
"code": null,
"e": 5239,
"s": 4882,
"text": "Moreover, on the tracks there are also shadows which could throw the model into confusion. The model would also need to learn to steer correctly whether the car is on the left or right side of the road. Therefore, we must find a way to artificially increase and vary our images and steering angles. We turn to data augmentation techniques for this purpose."
},
{
"code": null,
"e": 5348,
"s": 5239,
"text": "First of all, we add a steering angle calibration offset to images captured by either left or right cameras:"
},
{
"code": null,
"e": 5424,
"s": 5348,
"text": "for the left camera we want the car to steer to the right (positive offset)"
},
{
"code": null,
"e": 5500,
"s": 5424,
"text": "for the right camera we want the car to steer to the left (negative offset)"
},
{
"code": null,
"e": 5585,
"s": 5500,
"text": "st_angle_names = [\"Center\", \"Left\", \"Right\"]st_angle_calibrations = [0, 0.25, -0.25]"
},
{
"code": null,
"e": 5626,
"s": 5585,
"text": "The values above are empirically chosen."
},
{
"code": null,
"e": 5819,
"s": 5626,
"text": "Since we want our car to be able to steer itself regardless of its position on the road, we apply a horizontal flip to a proportion of images, and naturally invert the original steering angle:"
},
{
"code": null,
"e": 5922,
"s": 5819,
"text": "def fliph_image(img): \"\"\" Returns a horizontally flipped image \"\"\" return cv2.flip(img, 1)"
},
{
"code": null,
"e": 6121,
"s": 5922,
"text": "Since some parts of our tracks are much darker, due to shadows or otherwise, we also darken a proportion of our images by multiplying all RGB color channels by a scalar randomly picked from a range:"
},
{
"code": null,
"e": 6503,
"s": 6121,
"text": "def change_image_brightness_rgb(img, s_low=0.2, s_high=0.75): \"\"\" Changes the image brightness by multiplying all RGB values by the same scalacar in [s_low, s_high). Returns the brightness adjusted image in RGB format. \"\"\" img = img.astype(np.float32) s = np.random.uniform(s_low, s_high) img[:,:,:] *= s np.clip(img, 0, 255) return img.astype(np.uint8)"
},
{
"code": null,
"e": 6647,
"s": 6503,
"text": "Since we sometimes have patches of the track covered by a shadow, we also have to train our model to recognise them and not be spooked by them."
},
{
"code": null,
"e": 7778,
"s": 6647,
"text": "def add_random_shadow(img, w_low=0.6, w_high=0.85): \"\"\" Overlays supplied image with a random shadow polygon The weight range (i.e. darkness) of the shadow can be configured via the interval [w_low, w_high) \"\"\" cols, rows = (img.shape[0], img.shape[1]) top_y = np.random.random_sample() * rows bottom_y = np.random.random_sample() * rows bottom_y_right = bottom_y + np.random.random_sample() * (rows - bottom_y) top_y_right = top_y + np.random.random_sample() * (rows - top_y) if np.random.random_sample() <= 0.5: bottom_y_right = bottom_y - np.random.random_sample() * (bottom_y) top_y_right = top_y - np.random.random_sample() * (top_y) poly = np.asarray([[ [top_y,0], [bottom_y, cols], [bottom_y_right, cols], [top_y_right,0]]], dtype=np.int32) mask_weight = np.random.uniform(w_low, w_high) origin_weight = 1 - mask_weight mask = np.copy(img).astype(np.int32) cv2.fillPoly(mask, poly, (0, 0, 0)) #masked_image = cv2.bitwise_and(img, mask) return cv2.addWeighted(img.astype(np.int32), origin_weight, mask, mask_weight, 0).astype(np.uint8)"
},
{
"code": null,
"e": 8339,
"s": 7778,
"text": "To combat the high number of neutral angles, and provide more variety to the dataset, we apply random shifts to the image, and add a given offset to the steering angle for every pixel shifted laterally. In our case we empirically settled on adding (or subtracting) 0.0035 for every pixel shifted to the left or right. Shifting the image up/down should cause the model to believe it is on the upward/downward slope. From experimentation, we believe that these lateral shifts are possibly the most important augmentations needed to get the car to drive properly."
},
{
"code": null,
"e": 9183,
"s": 8339,
"text": "# Read more about it here: http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_imgproc/py_geometric_transformations/py_geometric_transformations.htmldef translate_image(img, st_angle, low_x_range, high_x_range, low_y_range, high_y_range, delta_st_angle_per_px): \"\"\" Shifts the image right, left, up or down. When performing a lateral shift, a delta proportional to the pixel shifts is added to the current steering angle \"\"\" rows, cols = (img.shape[0], img.shape[1]) translation_x = np.random.randint(low_x_range, high_x_range) translation_y = np.random.randint(low_y_range, high_y_range) st_angle += translation_x * delta_st_angle_per_px translation_matrix = np.float32([[1, 0, translation_x],[0, 1, translation_y]]) img = cv2.warpAffine(img, translation_matrix, (cols, rows)) return img, st_angle"
},
{
"code": null,
"e": 9453,
"s": 9183,
"text": "Our image augmentation function is straightforward: each supplied image goes through a series of augmentations, each occurring with a probability p between 0 and 1. All the code of augmenting the image is delegated to the appropriate augmenter function presented above."
},
{
"code": null,
"e": 10204,
"s": 9453,
"text": "def augment_image(img, st_angle, p=1.0): \"\"\" Augment a given image, by applying a series of transformations, with a probability p. The steering angle may also be modified. Returns the tuple (augmented_image, new_steering_angle) \"\"\" aug_img = img if np.random.random_sample() <= p: aug_img = fliph_image(aug_img) st_angle = -st_angle if np.random.random_sample() <= p: aug_img = change_image_brightness_rgb(aug_img) if np.random.random_sample() <= p: aug_img = add_random_shadow(aug_img, w_low=0.45) if np.random.random_sample() <= p: aug_img, st_angle = translate_image(aug_img, st_angle, -60, 61, -20, 21, 0.35/100.0) return aug_img, st_angle"
},
{
"code": null,
"e": 10352,
"s": 10204,
"text": "Since we are generating new and augmented images on the fly as we train the model, we create a Keras generator to produce new images at each batch:"
},
{
"code": null,
"e": 12159,
"s": 10352,
"text": "def generate_images(df, target_dimensions, img_types, st_column, st_angle_calibrations, batch_size=100, shuffle=True, data_aug_pct=0.8, aug_likelihood=0.5, st_angle_threshold=0.05, neutral_drop_pct=0.25): \"\"\" Generates images whose paths and steering angle are stored in the supplied dataframe object df Returns the tuple (batch,steering_angles) \"\"\" # e.g. 160x320x3 for target_dimensions batch = np.zeros((batch_size, target_dimensions[0], target_dimensions[1], target_dimensions[2]), dtype=np.float32) steering_angles = np.zeros(batch_size) df_len = len(df) while True: k = 0 while k < batch_size: idx = np.random.randint(0, df_len) for img_t, st_calib in zip(img_types, st_angle_calibrations): if k >= batch_size: break row = df.iloc[idx] st_angle = row[st_column] # Drop neutral-ish steering angle images with some probability if abs(st_angle) < st_angle_threshold and np.random.random_sample() <= neutral_drop_pct : continue st_angle += st_calib img_type_path = row[img_t] img = read_img(img_type_path) # Resize image img, st_angle = augment_image(img, st_angle, p=aug_likelihood) if np.random.random_sample() <= data_aug_pct else (img, st_angle) batch[k] = img steering_angles[k] = st_angle k += 1 yield batch, np.clip(steering_angles, -1, 1)"
},
{
"code": null,
"e": 12308,
"s": 12159,
"text": "Note that we have the ability to drop a proportion of neutral angles, as well as keeping (i.e. not augmenting) a proportion of images at each batch."
},
{
"code": null,
"e": 12378,
"s": 12308,
"text": "The following shows a small portion of augmented images from a batch:"
},
{
"code": null,
"e": 12485,
"s": 12378,
"text": "Moreover, the accompanying histogram of steering angles of those augmented images shows much more balance:"
},
{
"code": null,
"e": 12723,
"s": 12485,
"text": "We initially tried a variant of the VGG architecture, with less layers and no transfer learning, but struggled to get satisfying results. Ultimately, we settled on the architecture used in the NVIDIA paper as it gave us the best results:"
},
{
"code": null,
"e": 12774,
"s": 12723,
"text": "However, we added some slight tweaks to the model:"
},
{
"code": null,
"e": 12905,
"s": 12774,
"text": "We crop the top of the images so as to exclude the horizon (it does not play a role in immediately determining the steering angle)"
},
{
"code": null,
"e": 13004,
"s": 12905,
"text": "We resize the images to 66x200 in the model, as one the early layers, to take advantage of the GPU"
},
{
"code": null,
"e": 13086,
"s": 13004,
"text": "We apply BatchNormalization after each activation function for faster convergence"
},
{
"code": null,
"e": 13144,
"s": 13086,
"text": "The second dense layer has output size 200 instead of 100"
},
{
"code": null,
"e": 13194,
"s": 13144,
"text": "The full architecture of the model is as follows:"
},
{
"code": null,
"e": 13241,
"s": 13194,
"text": "Input image is 160x320 (height x width format)"
},
{
"code": null,
"e": 13357,
"s": 13241,
"text": "Image is vertically cropped at the top, by removing half of the height (80 pixels), resulting in an image of 80x320"
},
{
"code": null,
"e": 13439,
"s": 13357,
"text": "Cropped image is normalized, to make sure the mean of our pixel distribution is 0"
},
{
"code": null,
"e": 13517,
"s": 13439,
"text": "Cropped image is resized to 66x200, using Tensorflow’s tf.image.resize_images"
},
{
"code": null,
"e": 13772,
"s": 13517,
"text": "We apply a series of 3 of 5x5 convolutional layers, using a stride of 2x2. Each convolutional layer is followed by a BatchNormalization operation to improve convergence. The respective depth of each layer is 24, 36 and 48 as we go deeper into the network"
},
{
"code": null,
"e": 13926,
"s": 13772,
"text": "We apply a 2 consecutive 3x3 convolutional layers, with a depth of 64. Each convolutional layer is immediately followed by a BatchNormalization operation"
},
{
"code": null,
"e": 13997,
"s": 13926,
"text": "We flatten the input at this stage and enter the fully connected phase"
},
{
"code": null,
"e": 14094,
"s": 13997,
"text": "We apply a series of fully connected layers, of gradually decreasing sizes: 1164, 200, 50 and 10"
},
{
"code": null,
"e": 14197,
"s": 14094,
"text": "The output layer is obviously of size 1, since we predict only one variable, the steering wheel angle."
},
{
"code": null,
"e": 14472,
"s": 14197,
"text": "The activation function used across all layers, bar the last one, is ReLU. We tried ELU as well but got better results with ReLU + BatchNormalization. We use the Mean Squared Error activation for the output layer since this is a regression problem, not a classification one."
},
{
"code": null,
"e": 15131,
"s": 14472,
"text": "As stated in the previous section, we employed BatchNormalization to hasten convergence. We did try some degree of Dropout but did not find any noticeable difference. We believe the fact that we are generating new images at every batch and discarding some of the neutral angle images help in reducing overfitting. Moreover, we did not apply any MaxPool operation to our NVIDIA network (although we tried on the VGG inspired one) as it would have required significant changes in the architecture since we would have reduced dimensionality much earlier. Moreover, we did not have the time to experiment with L2 regularisation, but plan to try it in the future."
},
{
"code": null,
"e": 15380,
"s": 15131,
"text": "We trained the model using Adam as the optimizer and a learning rate of 0.001. After much, tweaking of parameters, and experimentation of multiple models, we ended up with one that is able power our virtual car to drive autonomously on both tracks."
},
{
"code": null,
"e": 15467,
"s": 15380,
"text": "We can see how the vehicle effectively manages to drive down a steep slope on track 2."
},
{
"code": null,
"e": 15782,
"s": 15467,
"text": "We also show what the front camera sees when driving autonomously on track 2. We can see how the car tries to stick to the lane and not go in the middle, as we ourselves strived to drive on only one side of the road during our data collection phase. This shows the model has indeed learned to stay within its lane."
},
{
"code": null,
"e": 15897,
"s": 15782,
"text": "To top it all up, I even created a video montage for you, using Tron Legacy’s The Grid as background music. Enjoy!"
},
{
"code": null,
"e": 16182,
"s": 15897,
"text": "We have shown that it is possible to create a model that reliably predicts steering wheel angles for a vehicle using a deep neural network and a plethora of data augmentation techniques. While we have obtained encouraging results, we would like in the future to explore the following:"
},
{
"code": null,
"e": 16232,
"s": 16182,
"text": "Take into account speed and throttle in the model"
},
{
"code": null,
"e": 16274,
"s": 16232,
"text": "Get the car to drive faster than 15–20MPH"
},
{
"code": null,
"e": 16347,
"s": 16274,
"text": "Experiment with models based VGG/ResNets/Inception via transfer learning"
},
{
"code": null,
"e": 16434,
"s": 16347,
"text": "Use Recurrent Neural Networks like in this paper from people using the Udacity dataset"
},
{
"code": null,
"e": 16527,
"s": 16434,
"text": "Read the Learning A Driving Simulator paper by comma.ai and attempt to implement their model"
},
{
"code": null,
"e": 16566,
"s": 16527,
"text": "Experiment with Reinforcement Learning"
},
{
"code": null,
"e": 16925,
"s": 16566,
"text": "As can be seen, there are many areas we could explore to push this project further and obtain even more convincing results. One of the most important learnings from this project is that DATA IS KING: without all those images and steering angles, along with their potentially infinite augmentations, we would not have been able to build a robust enough model."
},
{
"code": null,
"e": 17243,
"s": 16925,
"text": "From a personal perspective, I have tremendously enjoyed this project, the hardest so far, as it enabled me to gain more practical experience of hyper-parameter tweaking, data augmentation, and dataset balancing among other important concepts. I feel my intuition of neural network architectures has deepened as well."
},
{
"code": null,
"e": 17598,
"s": 17243,
"text": "I would also like to thank my Udacity mentor Dylan for his support and sound advice, as well as the Udacity students before my cohort who explained how they approached this project via blog posts. I was inspired by reading their posts: they definitely helped me in developing a stronger grasp of the concepts needed to successfully complete this project."
},
{
"code": null,
"e": 17884,
"s": 17598,
"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": 18026,
"s": 17884,
"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!"
}
] |
Queries to check if a number lies in N ranges of L-R - GeeksforGeeks
|
22 Jul, 2021
Given N ranges and Q queries consisting of numbers. Every range consists of L and R. The task is to check if the given number lies in any of the given ranges or not for every query.Note: There is no overlapping range.Examples:
Input: range[] = { {5, 6}, {1, 3}, {8, 10} Q = 4 1st query: 2 2nd query: 3 3rd query: 4 4th query: 7Output: Yes Yes No No1st query: 2 lies in a range 1-3 2nd query: 3 lies in a range 1-3 3rd query: 4 does not lie in any of the given range. 4th query: 7 does not lie in any of the given range.
Approach: Below is the step by step algorithm to solve this problem:
Hash the L of every range as 1, and hash the R of every range as 2.Push the L and R separately into a container.Sort the elements in the container, all the range L and R will be adjacent to each other as do not overlap.For every query, use binary search to find the first occurrence of a number same or greater than it. This can be done using the lower_bound function.If there is any value which is equal to the query, then the number overlaps the range.If there is no value which is equal to the query, then check if the greater element is hashed as 1 or 2.If it is hashed as 1, then the number does not overlaps, else it does overlap.
Hash the L of every range as 1, and hash the R of every range as 2.
Push the L and R separately into a container.
Sort the elements in the container, all the range L and R will be adjacent to each other as do not overlap.
For every query, use binary search to find the first occurrence of a number same or greater than it. This can be done using the lower_bound function.
If there is any value which is equal to the query, then the number overlaps the range.
If there is no value which is equal to the query, then check if the greater element is hashed as 1 or 2.
If it is hashed as 1, then the number does not overlaps, else it does overlap.
Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if the// number lies in given range#include <bits/stdc++.h> using namespace std; // Function that answers every queryvoid answerQueries(int a[][2], int n, int queries[], int q){ // container to store all range vector<int> v; // hash the L and R unordered_map<int, int> mpp; // Push the element to container // and hash the L and R for (int i = 0; i < n; i++) { v.push_back(a[i][0]); mpp[a[i][0]] = 1; v.push_back(a[i][1]); mpp[a[i][1]] = 2; } // sort the elements in container sort(v.begin(), v.end()); for (int i = 0; i < q; i++) { // each query int num = queries[i]; // get the number same or greater than integer int ind = lower_bound(v.begin(), v.end(), num) - v.begin(); // if it lies if (v[ind] == num) { cout << "Yes\n"; } else { // check if greater is hashed as 2 if (mpp[v[ind]] == 2) cout << "Yes\n"; else // check if greater is hashed as 1 cout << "No\n"; } }} // Driver codeint main(){ int a[][2] = { { 5, 6 }, { 1, 3 }, { 8, 10 } }; int n = 3; int queries[] = { 2, 3, 4, 7 }; int q = sizeof(queries) / sizeof(queries[0]); // function call to answer queries answerQueries(a, n, queries, q); return 0;}
// Java program to check if the// number lies in given rangeimport java.io.*;import java.util.*; class GFG{ // Function that answers every query static void answerQueries(int[][] a, int n, int[] queries, int q) { // container to store all range Vector<Integer> v = new Vector<>(); // hash the L and R HashMap<Integer, Integer> mpp = new HashMap<>(); // Push the element to container // and hash the L and R for (int i = 0; i < n; i++) { v.add(a[i][0]); mpp.put(a[i][0], 1); v.add(a[i][1]); mpp.put(a[i][1], 2); } // sort the elements in container Collections.sort(v); for (int i = 0; i < q; i++) { // each query int num = queries[i]; // get the number same or greater than integer int ind = lowerBound(v, num); // if it lies if (ind >= 0 && v.elementAt(ind) == num) System.out.println("Yes"); else { // check if greater is hashed as 2 if (ind >= 0 && mpp.get(v.elementAt(ind)) == 2) System.out.println("Yes"); else // check if greater is hashed as 1 System.out.println("No"); } } } // Lower bound implementation static int lowerBound(Vector<Integer> array, int value) { int low = 0; int high = array.size(); while (low < high) { final int mid = (low + high) / 2; if (value <= array.elementAt(mid)) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void main(String[] args) { int[][] a = {{ 5, 6 }, { 1, 3 }, { 8, 10 }}; int n = 3; int[] queries = {2, 3, 4, 7}; int q = queries.length; // function call to answer queries answerQueries(a, n, queries, q); }} // This code is contributed by// sanjeev2552
# Python program to check if the# number lies in given rangefrom bisect import bisect_left as lower_bound # Function that answers every querydef answerQueries(a: list, n, queries: list, q): # container to store all range v = list() # hash the L and R mpp = dict() # Push the element to container # and hash the L and R for i in range(n): v.append(a[i][0]) mpp[a[i][0]] = 1 v.append(a[i][1]) mpp[a[i][1]] = 2 # sort the elements in container v.sort() for i in range(q): # each query num = queries[i] # get the number same or greater than integer ind = lower_bound(v, num) # if it lies if v[ind] == num: print("Yes") else: # check if greater is hashed as 2 if mpp[v[ind]] == 2: print("Yes") # check if greater is hashed as 1 else: print("No") # Driver Codeif __name__ == "__main__": a = [[5, 6], [1, 3], [8, 10]] n = 3 queries = [2, 3, 4, 7] q = len(queries) # function call to answer queries answerQueries(a, n, queries, q) # This code is contributed by# sanjeev2552
// C# program to check if the// number lies in given rangeusing System;using System.Collections.Generic; class GFG{ // Function that answers every query static void answerQueries(int[,] a, int n, int[] queries, int q) { // container to store all range List<int> v = new List<int>(); // hash the L and R Dictionary<int, int> mpp = new Dictionary<int, int>(); // Push the element to container // and hash the L and R for (int i = 0; i < n; i++) { v.Add(a[i, 0]); if(!mpp.ContainsKey(a[i, 0])) mpp.Add(a[i, 0], 1); v.Add(a[i, 1]); if(!mpp.ContainsKey(a[i, 1])) mpp.Add(a[i, 1], 2); } // sort the elements in container v.Sort(); for (int i = 0; i < q; i++) { // each query int num = queries[i]; // get the number same or greater than integer int ind = lowerBound(v, num); // if it lies if (ind >= 0 && v[ind] == num) Console.WriteLine("Yes"); else { // check if greater is hashed as 2 if (ind >= 0 && mpp[v[ind]] == 2) Console.WriteLine("Yes"); else // check if greater is hashed as 1 Console.WriteLine("No"); } } } // Lower bound implementation static int lowerBound(List<int> array, int value) { int low = 0; int high = array.Count; while (low < high) { int mid = (low + high) / 2; if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void Main(String[] args) { int[,] a = {{ 5, 6 }, { 1, 3 }, { 8, 10 }}; int n = 3; int[] queries = {2, 3, 4, 7}; int q = queries.Length; // function call to answer queries answerQueries(a, n, queries, q); }} // This code is contributed by 29AjayKumar
<script>// Javascript program to check if the// number lies in given range // Function that answers every queryfunction answerQueries(a, n, queries, q){ // container to store all range let v = []; // hash the L and R let mpp = new Map(); // Push the element to container // and hash the L and R for (let i = 0; i < n; i++) { v.push(a[i][0]); mpp.set(a[i][0], 1); v.push(a[i][1]); mpp.set(a[i][1], 2); } // sort the elements in container v.sort(function(a,b){return a-b;}); for (let i = 0; i < q; i++) { // each query let num = queries[i]; // get the number same or greater than integer let ind = lowerBound(v, num); // if it lies if (ind >= 0 && v[ind] == num) document.write("Yes<br>"); else { // check if greater is hashed as 2 if (ind >= 0 && mpp.get(v[ind]) == 2) document.write("Yes<br>"); else // check if greater is hashed as 1 document.write("No<br>"); } }} // Lower bound implementationfunction lowerBound(array,value){ let low = 0; let high = array.length; while (low < high) { let mid = Math.floor((low + high) / 2); if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low;} // Driver Codelet a=[[ 5, 6 ], [ 1, 3 ], [ 8, 10 ]];let n = 3;let queries=[2, 3, 4, 7];let q = queries.length; // function call to answer queriesanswerQueries(a, n, queries, q); // This code is contributed by rag2127</script>
Yes
Yes
No
No
sanjeev2552
29AjayKumar
arorakashish0911
rag2127
array-range-queries
Binary Search
cpp-unordered_map
Searching
Sorting
Searching
Sorting
Binary Search
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Best First Search (Informed Search)
3 Different ways to print Fibonacci series in Java
Find whether an array is subset of another array | Added Method 5
Program to remove vowels from a String
Recursive Programs to find Minimum and Maximum elements of array
|
[
{
"code": null,
"e": 24615,
"s": 24587,
"text": "\n22 Jul, 2021"
},
{
"code": null,
"e": 24844,
"s": 24615,
"text": "Given N ranges and Q queries consisting of numbers. Every range consists of L and R. The task is to check if the given number lies in any of the given ranges or not for every query.Note: There is no overlapping range.Examples: "
},
{
"code": null,
"e": 25139,
"s": 24844,
"text": "Input: range[] = { {5, 6}, {1, 3}, {8, 10} Q = 4 1st query: 2 2nd query: 3 3rd query: 4 4th query: 7Output: Yes Yes No No1st query: 2 lies in a range 1-3 2nd query: 3 lies in a range 1-3 3rd query: 4 does not lie in any of the given range. 4th query: 7 does not lie in any of the given range. "
},
{
"code": null,
"e": 25212,
"s": 25141,
"text": "Approach: Below is the step by step algorithm to solve this problem: "
},
{
"code": null,
"e": 25849,
"s": 25212,
"text": "Hash the L of every range as 1, and hash the R of every range as 2.Push the L and R separately into a container.Sort the elements in the container, all the range L and R will be adjacent to each other as do not overlap.For every query, use binary search to find the first occurrence of a number same or greater than it. This can be done using the lower_bound function.If there is any value which is equal to the query, then the number overlaps the range.If there is no value which is equal to the query, then check if the greater element is hashed as 1 or 2.If it is hashed as 1, then the number does not overlaps, else it does overlap."
},
{
"code": null,
"e": 25917,
"s": 25849,
"text": "Hash the L of every range as 1, and hash the R of every range as 2."
},
{
"code": null,
"e": 25963,
"s": 25917,
"text": "Push the L and R separately into a container."
},
{
"code": null,
"e": 26071,
"s": 25963,
"text": "Sort the elements in the container, all the range L and R will be adjacent to each other as do not overlap."
},
{
"code": null,
"e": 26221,
"s": 26071,
"text": "For every query, use binary search to find the first occurrence of a number same or greater than it. This can be done using the lower_bound function."
},
{
"code": null,
"e": 26308,
"s": 26221,
"text": "If there is any value which is equal to the query, then the number overlaps the range."
},
{
"code": null,
"e": 26413,
"s": 26308,
"text": "If there is no value which is equal to the query, then check if the greater element is hashed as 1 or 2."
},
{
"code": null,
"e": 26492,
"s": 26413,
"text": "If it is hashed as 1, then the number does not overlaps, else it does overlap."
},
{
"code": null,
"e": 26540,
"s": 26492,
"text": "Below is the implementation of above approach: "
},
{
"code": null,
"e": 26544,
"s": 26540,
"text": "C++"
},
{
"code": null,
"e": 26549,
"s": 26544,
"text": "Java"
},
{
"code": null,
"e": 26557,
"s": 26549,
"text": "Python3"
},
{
"code": null,
"e": 26560,
"s": 26557,
"text": "C#"
},
{
"code": null,
"e": 26571,
"s": 26560,
"text": "Javascript"
},
{
"code": "// C++ program to check if the// number lies in given range#include <bits/stdc++.h> using namespace std; // Function that answers every queryvoid answerQueries(int a[][2], int n, int queries[], int q){ // container to store all range vector<int> v; // hash the L and R unordered_map<int, int> mpp; // Push the element to container // and hash the L and R for (int i = 0; i < n; i++) { v.push_back(a[i][0]); mpp[a[i][0]] = 1; v.push_back(a[i][1]); mpp[a[i][1]] = 2; } // sort the elements in container sort(v.begin(), v.end()); for (int i = 0; i < q; i++) { // each query int num = queries[i]; // get the number same or greater than integer int ind = lower_bound(v.begin(), v.end(), num) - v.begin(); // if it lies if (v[ind] == num) { cout << \"Yes\\n\"; } else { // check if greater is hashed as 2 if (mpp[v[ind]] == 2) cout << \"Yes\\n\"; else // check if greater is hashed as 1 cout << \"No\\n\"; } }} // Driver codeint main(){ int a[][2] = { { 5, 6 }, { 1, 3 }, { 8, 10 } }; int n = 3; int queries[] = { 2, 3, 4, 7 }; int q = sizeof(queries) / sizeof(queries[0]); // function call to answer queries answerQueries(a, n, queries, q); return 0;}",
"e": 27947,
"s": 26571,
"text": null
},
{
"code": "// Java program to check if the// number lies in given rangeimport java.io.*;import java.util.*; class GFG{ // Function that answers every query static void answerQueries(int[][] a, int n, int[] queries, int q) { // container to store all range Vector<Integer> v = new Vector<>(); // hash the L and R HashMap<Integer, Integer> mpp = new HashMap<>(); // Push the element to container // and hash the L and R for (int i = 0; i < n; i++) { v.add(a[i][0]); mpp.put(a[i][0], 1); v.add(a[i][1]); mpp.put(a[i][1], 2); } // sort the elements in container Collections.sort(v); for (int i = 0; i < q; i++) { // each query int num = queries[i]; // get the number same or greater than integer int ind = lowerBound(v, num); // if it lies if (ind >= 0 && v.elementAt(ind) == num) System.out.println(\"Yes\"); else { // check if greater is hashed as 2 if (ind >= 0 && mpp.get(v.elementAt(ind)) == 2) System.out.println(\"Yes\"); else // check if greater is hashed as 1 System.out.println(\"No\"); } } } // Lower bound implementation static int lowerBound(Vector<Integer> array, int value) { int low = 0; int high = array.size(); while (low < high) { final int mid = (low + high) / 2; if (value <= array.elementAt(mid)) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void main(String[] args) { int[][] a = {{ 5, 6 }, { 1, 3 }, { 8, 10 }}; int n = 3; int[] queries = {2, 3, 4, 7}; int q = queries.length; // function call to answer queries answerQueries(a, n, queries, q); }} // This code is contributed by// sanjeev2552",
"e": 30094,
"s": 27947,
"text": null
},
{
"code": "# Python program to check if the# number lies in given rangefrom bisect import bisect_left as lower_bound # Function that answers every querydef answerQueries(a: list, n, queries: list, q): # container to store all range v = list() # hash the L and R mpp = dict() # Push the element to container # and hash the L and R for i in range(n): v.append(a[i][0]) mpp[a[i][0]] = 1 v.append(a[i][1]) mpp[a[i][1]] = 2 # sort the elements in container v.sort() for i in range(q): # each query num = queries[i] # get the number same or greater than integer ind = lower_bound(v, num) # if it lies if v[ind] == num: print(\"Yes\") else: # check if greater is hashed as 2 if mpp[v[ind]] == 2: print(\"Yes\") # check if greater is hashed as 1 else: print(\"No\") # Driver Codeif __name__ == \"__main__\": a = [[5, 6], [1, 3], [8, 10]] n = 3 queries = [2, 3, 4, 7] q = len(queries) # function call to answer queries answerQueries(a, n, queries, q) # This code is contributed by# sanjeev2552",
"e": 31280,
"s": 30094,
"text": null
},
{
"code": "// C# program to check if the// number lies in given rangeusing System;using System.Collections.Generic; class GFG{ // Function that answers every query static void answerQueries(int[,] a, int n, int[] queries, int q) { // container to store all range List<int> v = new List<int>(); // hash the L and R Dictionary<int, int> mpp = new Dictionary<int, int>(); // Push the element to container // and hash the L and R for (int i = 0; i < n; i++) { v.Add(a[i, 0]); if(!mpp.ContainsKey(a[i, 0])) mpp.Add(a[i, 0], 1); v.Add(a[i, 1]); if(!mpp.ContainsKey(a[i, 1])) mpp.Add(a[i, 1], 2); } // sort the elements in container v.Sort(); for (int i = 0; i < q; i++) { // each query int num = queries[i]; // get the number same or greater than integer int ind = lowerBound(v, num); // if it lies if (ind >= 0 && v[ind] == num) Console.WriteLine(\"Yes\"); else { // check if greater is hashed as 2 if (ind >= 0 && mpp[v[ind]] == 2) Console.WriteLine(\"Yes\"); else // check if greater is hashed as 1 Console.WriteLine(\"No\"); } } } // Lower bound implementation static int lowerBound(List<int> array, int value) { int low = 0; int high = array.Count; while (low < high) { int mid = (low + high) / 2; if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low; } // Driver Code public static void Main(String[] args) { int[,] a = {{ 5, 6 }, { 1, 3 }, { 8, 10 }}; int n = 3; int[] queries = {2, 3, 4, 7}; int q = queries.Length; // function call to answer queries answerQueries(a, n, queries, q); }} // This code is contributed by 29AjayKumar",
"e": 33458,
"s": 31280,
"text": null
},
{
"code": "<script>// Javascript program to check if the// number lies in given range // Function that answers every queryfunction answerQueries(a, n, queries, q){ // container to store all range let v = []; // hash the L and R let mpp = new Map(); // Push the element to container // and hash the L and R for (let i = 0; i < n; i++) { v.push(a[i][0]); mpp.set(a[i][0], 1); v.push(a[i][1]); mpp.set(a[i][1], 2); } // sort the elements in container v.sort(function(a,b){return a-b;}); for (let i = 0; i < q; i++) { // each query let num = queries[i]; // get the number same or greater than integer let ind = lowerBound(v, num); // if it lies if (ind >= 0 && v[ind] == num) document.write(\"Yes<br>\"); else { // check if greater is hashed as 2 if (ind >= 0 && mpp.get(v[ind]) == 2) document.write(\"Yes<br>\"); else // check if greater is hashed as 1 document.write(\"No<br>\"); } }} // Lower bound implementationfunction lowerBound(array,value){ let low = 0; let high = array.length; while (low < high) { let mid = Math.floor((low + high) / 2); if (value <= array[mid]) { high = mid; } else { low = mid + 1; } } return low;} // Driver Codelet a=[[ 5, 6 ], [ 1, 3 ], [ 8, 10 ]];let n = 3;let queries=[2, 3, 4, 7];let q = queries.length; // function call to answer queriesanswerQueries(a, n, queries, q); // This code is contributed by rag2127</script>",
"e": 35291,
"s": 33458,
"text": null
},
{
"code": null,
"e": 35305,
"s": 35291,
"text": "Yes\nYes\nNo\nNo"
},
{
"code": null,
"e": 35319,
"s": 35307,
"text": "sanjeev2552"
},
{
"code": null,
"e": 35331,
"s": 35319,
"text": "29AjayKumar"
},
{
"code": null,
"e": 35348,
"s": 35331,
"text": "arorakashish0911"
},
{
"code": null,
"e": 35356,
"s": 35348,
"text": "rag2127"
},
{
"code": null,
"e": 35376,
"s": 35356,
"text": "array-range-queries"
},
{
"code": null,
"e": 35390,
"s": 35376,
"text": "Binary Search"
},
{
"code": null,
"e": 35408,
"s": 35390,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 35418,
"s": 35408,
"text": "Searching"
},
{
"code": null,
"e": 35426,
"s": 35418,
"text": "Sorting"
},
{
"code": null,
"e": 35436,
"s": 35426,
"text": "Searching"
},
{
"code": null,
"e": 35444,
"s": 35436,
"text": "Sorting"
},
{
"code": null,
"e": 35458,
"s": 35444,
"text": "Binary Search"
},
{
"code": null,
"e": 35556,
"s": 35458,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35565,
"s": 35556,
"text": "Comments"
},
{
"code": null,
"e": 35578,
"s": 35565,
"text": "Old Comments"
},
{
"code": null,
"e": 35614,
"s": 35578,
"text": "Best First Search (Informed Search)"
},
{
"code": null,
"e": 35665,
"s": 35614,
"text": "3 Different ways to print Fibonacci series in Java"
},
{
"code": null,
"e": 35731,
"s": 35665,
"text": "Find whether an array is subset of another array | Added Method 5"
},
{
"code": null,
"e": 35770,
"s": 35731,
"text": "Program to remove vowels from a String"
}
] |
How to set the page-break behavior inside an element with JavaScript?
|
Use the pageBreakInside property in JavaScript to set the page-break behavior inside an element. Use the auto property to insert page break inside an element. Use auto or avoid property value to automatically insert page break inside an element, if needed, or avoid a page break, respectively.
Note − The changes would be visible while printing or viewing the print preview.
You can try to run the following code to return the page-break behavior inside an element with JavaScript −
<!DOCTYPE html>
<html>
<body>
<h1>Heading 1</h1>
<p>This is demo text.</p>
<p>This is demo text.</p>
<p id = "myFooter">This if footer text.</p>
<button type = "button" onclick="display()"> Set page-break </button>
<script>
function display() {
document.getElementById("myFooter").style.pageBreakInside = "auto";
}
</script>
</body>
</html>
|
[
{
"code": null,
"e": 1356,
"s": 1062,
"text": "Use the pageBreakInside property in JavaScript to set the page-break behavior inside an element. Use the auto property to insert page break inside an element. Use auto or avoid property value to automatically insert page break inside an element, if needed, or avoid a page break, respectively."
},
{
"code": null,
"e": 1437,
"s": 1356,
"text": "Note − The changes would be visible while printing or viewing the print preview."
},
{
"code": null,
"e": 1545,
"s": 1437,
"text": "You can try to run the following code to return the page-break behavior inside an element with JavaScript −"
},
{
"code": null,
"e": 1970,
"s": 1545,
"text": "<!DOCTYPE html>\n<html>\n <body>\n <h1>Heading 1</h1>\n <p>This is demo text.</p>\n <p>This is demo text.</p>\n <p id = \"myFooter\">This if footer text.</p>\n <button type = \"button\" onclick=\"display()\"> Set page-break </button>\n \n <script>\n function display() {\n document.getElementById(\"myFooter\").style.pageBreakInside = \"auto\";\n }\n </script>\n </body>\n</html>"
}
] |
Matlab-Matrix - Create a Matrix
|
In MATLAB, you can create a matrix by entering the elements in each row as comma. You can also create a matrix with space delimited numbers and by using the semicolons to mark the end of each row.
Let us create a simple matrix in MATLAB that has a single row and three elements. Each element should have a space or comma.
Consider the below mentioned elements to create a matrix.
m=[2, 4, 6]
On execution in MATLAB it will display the following −
>>m = [2, 4, 6]
m =
2 4 6
>>
When you execute the code in MATLAB, the result of the matrix is displayed in the command window.
Let us now create a matrix with multiple rows. To do that, we need to separate each row with semicolon (;) as shown below −
m = [2 4 6; 3 6 9; 4 8 12]
Here 2 4 6 is the first row, 3 6 9 is the second row and 4 8 12 is the third row. The matrix will be as follows −
m = 2 4 6
3 6 9
4 8 12
Let us now execute the same in MATLAB command prompt, as mentioned below −
>> m = [2 4 6; 3 6 9; 4 8 12]
m =
2 4 6
3 6 9
4 8 12
>>
The 3x3 matrix is displayed as shown above in MATLAB.
Besides creating matrix with the values of your choice you can also make use of the built-in MATLAB functions zeros, rand or ones to create a matrix as shown below −
This will create matrix with all zeros with the given row/column size.
Example
You can use MATLAB zeros function as follows −
m0 = zeros(3,3)
Output
You will get the following output −
>> m0 = zeros(3,3)
m0 =
0 0 0
0 0 0
0 0 0
>>
The matrix created will have ones as the values.
Example
You can use MATLAB ones function as follows −
m1 = ones(3,3)
Output
You will get the following output −
>> m1 = ones(3,3)
m1 =
1 1 1
1 1 1
1 1 1
>>
The function rand() allows you to create a matrix with random elements for the size given. Here is an example for the same.
Example
m1 = rand(3,3)
Output
Let us now execute the same in MATLAB to see the results. The output is as follows −
>> m1 = rand(3,3)
m1 =
0.8147 0.9134 0.2785
0.9058 0.6324 0.5469
0.1270 0.0975 0.9575
>>
30 Lectures
4 hours
Nouman Azam
127 Lectures
12 hours
Nouman Azam
17 Lectures
3 hours
Sanjeev
37 Lectures
5 hours
TELCOMA Global
22 Lectures
4 hours
TELCOMA Global
18 Lectures
3 hours
Phinite Academy
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2196,
"s": 1999,
"text": "In MATLAB, you can create a matrix by entering the elements in each row as comma. You can also create a matrix with space delimited numbers and by using the semicolons to mark the end of each row."
},
{
"code": null,
"e": 2321,
"s": 2196,
"text": "Let us create a simple matrix in MATLAB that has a single row and three elements. Each element should have a space or comma."
},
{
"code": null,
"e": 2379,
"s": 2321,
"text": "Consider the below mentioned elements to create a matrix."
},
{
"code": null,
"e": 2391,
"s": 2379,
"text": "m=[2, 4, 6]"
},
{
"code": null,
"e": 2446,
"s": 2391,
"text": "On execution in MATLAB it will display the following −"
},
{
"code": null,
"e": 2484,
"s": 2446,
"text": ">>m = [2, 4, 6]\n \nm =\n\n 2 4 6\n>>\n"
},
{
"code": null,
"e": 2582,
"s": 2484,
"text": "When you execute the code in MATLAB, the result of the matrix is displayed in the command window."
},
{
"code": null,
"e": 2706,
"s": 2582,
"text": "Let us now create a matrix with multiple rows. To do that, we need to separate each row with semicolon (;) as shown below −"
},
{
"code": null,
"e": 2733,
"s": 2706,
"text": "m = [2 4 6; 3 6 9; 4 8 12]"
},
{
"code": null,
"e": 2847,
"s": 2733,
"text": "Here 2 4 6 is the first row, 3 6 9 is the second row and 4 8 12 is the third row. The matrix will be as follows −"
},
{
"code": null,
"e": 2884,
"s": 2847,
"text": "m = 2 4 6\n 3 6 9\n 4 8 12\n"
},
{
"code": null,
"e": 2959,
"s": 2884,
"text": "Let us now execute the same in MATLAB command prompt, as mentioned below −"
},
{
"code": null,
"e": 3036,
"s": 2959,
"text": ">> m = [2 4 6; 3 6 9; 4 8 12]\n\nm =\n\n 2 4 6\n 3 6 9\n 4 8 12\n \n>>\n"
},
{
"code": null,
"e": 3090,
"s": 3036,
"text": "The 3x3 matrix is displayed as shown above in MATLAB."
},
{
"code": null,
"e": 3256,
"s": 3090,
"text": "Besides creating matrix with the values of your choice you can also make use of the built-in MATLAB functions zeros, rand or ones to create a matrix as shown below −"
},
{
"code": null,
"e": 3327,
"s": 3256,
"text": "This will create matrix with all zeros with the given row/column size."
},
{
"code": null,
"e": 3335,
"s": 3327,
"text": "Example"
},
{
"code": null,
"e": 3382,
"s": 3335,
"text": "You can use MATLAB zeros function as follows −"
},
{
"code": null,
"e": 3398,
"s": 3382,
"text": "m0 = zeros(3,3)"
},
{
"code": null,
"e": 3405,
"s": 3398,
"text": "Output"
},
{
"code": null,
"e": 3441,
"s": 3405,
"text": "You will get the following output −"
},
{
"code": null,
"e": 3508,
"s": 3441,
"text": ">> m0 = zeros(3,3)\n\nm0 =\n\n 0 0 0\n 0 0 0\n 0 0 0\n \n>>\n"
},
{
"code": null,
"e": 3557,
"s": 3508,
"text": "The matrix created will have ones as the values."
},
{
"code": null,
"e": 3565,
"s": 3557,
"text": "Example"
},
{
"code": null,
"e": 3611,
"s": 3565,
"text": "You can use MATLAB ones function as follows −"
},
{
"code": null,
"e": 3626,
"s": 3611,
"text": "m1 = ones(3,3)"
},
{
"code": null,
"e": 3633,
"s": 3626,
"text": "Output"
},
{
"code": null,
"e": 3669,
"s": 3633,
"text": "You will get the following output −"
},
{
"code": null,
"e": 3734,
"s": 3669,
"text": ">> m1 = ones(3,3)\n\nm1 =\n 1 1 1\n 1 1 1\n 1 1 1\n \n>>\n"
},
{
"code": null,
"e": 3858,
"s": 3734,
"text": "The function rand() allows you to create a matrix with random elements for the size given. Here is an example for the same."
},
{
"code": null,
"e": 3866,
"s": 3858,
"text": "Example"
},
{
"code": null,
"e": 3881,
"s": 3866,
"text": "m1 = rand(3,3)"
},
{
"code": null,
"e": 3888,
"s": 3881,
"text": "Output"
},
{
"code": null,
"e": 3973,
"s": 3888,
"text": "Let us now execute the same in MATLAB to see the results. The output is as follows −"
},
{
"code": null,
"e": 4084,
"s": 3973,
"text": ">> m1 = rand(3,3)\n\nm1 =\n\n 0.8147 0.9134 0.2785\n 0.9058 0.6324 0.5469\n 0.1270 0.0975 0.9575\n \n>>\n"
},
{
"code": null,
"e": 4117,
"s": 4084,
"text": "\n 30 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4130,
"s": 4117,
"text": " Nouman Azam"
},
{
"code": null,
"e": 4165,
"s": 4130,
"text": "\n 127 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 4178,
"s": 4165,
"text": " Nouman Azam"
},
{
"code": null,
"e": 4211,
"s": 4178,
"text": "\n 17 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4220,
"s": 4211,
"text": " Sanjeev"
},
{
"code": null,
"e": 4253,
"s": 4220,
"text": "\n 37 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 4269,
"s": 4253,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4302,
"s": 4269,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 4318,
"s": 4302,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 4351,
"s": 4318,
"text": "\n 18 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4368,
"s": 4351,
"text": " Phinite Academy"
},
{
"code": null,
"e": 4375,
"s": 4368,
"text": " Print"
},
{
"code": null,
"e": 4386,
"s": 4375,
"text": " Add Notes"
}
] |
Sum from array values with similar key in JavaScript
|
Let’s say, here is an array that contains some data about the stocks sold and purchased by
some company over a period of time.
const transactions = [
['AAPL', 'buy', 100],
['WMT', 'sell', 75],
['MCD', 'buy', 125],
['GOOG', 'sell', 10],
['AAPL', 'buy', 100],
['AAPL', 'sell', 100],
['AAPL', 'sell', 20],
['DIS', 'buy', 15],
['MCD', 'buy', 10],
['WMT', 'buy', 50],
['MCD', 'sell', 90]
];
We want to write a function that takes in this data and returns an object of arrays with key as
stock name (like ‘AAPL’, ‘MCD’) and value as array of two numbers, where the first element
represents the total buy and second element represents the total sell. Therefore, the code for
doing this will be −
const transactions = [
['AAPL', 'buy', 100],
['WMT', 'sell', 75],
['MCD', 'buy', 125],
['GOOG', 'sell', 10],
['AAPL', 'buy', 100],
['AAPL', 'sell', 100],
['AAPL', 'sell', 20],
['DIS', 'buy', 15],
['MCD', 'buy', 10],
['WMT', 'buy', 50],
['MCD', 'sell', 90]
];
const digestTransactions = (arr) => {
return arr.reduce((acc, val, ind) => {
const [stock, type, amount] = val;
if(acc[stock]){
const [buy, sell] = acc[stock];
if(type === 'buy'){
acc[stock] = [buy+amount, sell];
}else{
acc[stock] = [buy, sell+amount];
}
}else{
if(type === 'buy'){
acc[stock] = [amount, 0];
}else{
acc[stock] = [0, amount];
}
}
return acc;
}, {});
};
console.log(digestTransactions(transactions));
The output in the console will be −
{
AAPL: [ 200, 120 ],
WMT: [ 50, 75 ],
MCD: [ 135, 90 ],
GOOG: [ 0, 10 ],
DIS: [ 15, 0 ]
}
|
[
{
"code": null,
"e": 1189,
"s": 1062,
"text": "Let’s say, here is an array that contains some data about the stocks sold and purchased by\nsome company over a period of time."
},
{
"code": null,
"e": 1481,
"s": 1189,
"text": "const transactions = [\n ['AAPL', 'buy', 100],\n ['WMT', 'sell', 75],\n ['MCD', 'buy', 125],\n ['GOOG', 'sell', 10],\n ['AAPL', 'buy', 100],\n ['AAPL', 'sell', 100],\n ['AAPL', 'sell', 20],\n ['DIS', 'buy', 15],\n ['MCD', 'buy', 10],\n ['WMT', 'buy', 50],\n ['MCD', 'sell', 90]\n];"
},
{
"code": null,
"e": 1784,
"s": 1481,
"text": "We want to write a function that takes in this data and returns an object of arrays with key as\nstock name (like ‘AAPL’, ‘MCD’) and value as array of two numbers, where the first element\nrepresents the total buy and second element represents the total sell. Therefore, the code for\ndoing this will be −"
},
{
"code": null,
"e": 2653,
"s": 1784,
"text": "const transactions = [\n ['AAPL', 'buy', 100],\n ['WMT', 'sell', 75],\n ['MCD', 'buy', 125],\n ['GOOG', 'sell', 10],\n ['AAPL', 'buy', 100],\n ['AAPL', 'sell', 100],\n ['AAPL', 'sell', 20],\n ['DIS', 'buy', 15],\n ['MCD', 'buy', 10],\n ['WMT', 'buy', 50],\n ['MCD', 'sell', 90]\n];\nconst digestTransactions = (arr) => {\n return arr.reduce((acc, val, ind) => {\n const [stock, type, amount] = val;\n if(acc[stock]){\n const [buy, sell] = acc[stock];\n if(type === 'buy'){\n acc[stock] = [buy+amount, sell];\n }else{\n acc[stock] = [buy, sell+amount];\n }\n }else{\n if(type === 'buy'){\n acc[stock] = [amount, 0];\n }else{\n acc[stock] = [0, amount];\n }\n }\n return acc;\n }, {});\n};\nconsole.log(digestTransactions(transactions));"
},
{
"code": null,
"e": 2689,
"s": 2653,
"text": "The output in the console will be −"
},
{
"code": null,
"e": 2795,
"s": 2689,
"text": "{\n AAPL: [ 200, 120 ],\n WMT: [ 50, 75 ],\n MCD: [ 135, 90 ],\n GOOG: [ 0, 10 ],\n DIS: [ 15, 0 ]\n}"
}
] |
Speeding Up and Perfecting Your Work Using Parallel Computing | by Yitong Ren | Towards Data Science
|
In science, behind every achievement is grinding, rigorous work. And success is unlikely to happen with one attempt. As a data scientist, you probably deal with huge amount of data and computations, perform repeated tests and experiments on your day-to-day work. Though you don’t want to turn your rewarding, stimulating job into tedious one by waiting the time-consuming operation repeating again and again, observation after observation.
The computers today have multiple processors to allow running multiple functions simultaneously. However, this doesn’t help if the programmer isn’t aware of it, or doesn’t know how to use it, which leads to me writing this post to demonstrate how to parallelize your process using Python multiprocessing and PySpark mapPartition.
Machine learning model
Data science is a varied field that includes a wide range of work. One important application is to build machine learning pipelines and personalized data products to better target customers and enable more accurate decision making. In this post, I choose the step of cross-validation with stratified sampling in building a machine learning model as an example to parallelize it in both Python and Spark environment. The data I use is bank marketing data set from UCI machine learning repository for its relatively clean nature.
Since this post focuses on parallelism, I skip the steps of data explorative analysis, feature engineering, and feature selection. After some pre-processing, I obtained the data on the left that is ready for modeling, column y is our target variable which is whether the client subscribed to a term deposit during the campaign.
Now let’s get into details of the model selection step with cross validation. As a common practice, I include most classifiers from scikit-learn into a list called classifiers, and use StratifiedShuffleSplit method from sklearn.model_selection to perform this step. For model comparison purpose, I calculated accuracy score, log loss and AUC. This step took 46s, below is the code:
sss = StratifiedShuffleSplit(n_splits = 10, test_size = 0.1, random_state = 0)start = time.time()res = []for train_index, test_index in sss.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] for clf in classifiers: name = clf.__class__.__name__ clf.fit(X_train, y_train) y_pred = clf.predict(X_test) y_pred_probas = clf.predict_proba(X_test) acc = accuracy_score(y_test, y_pred) loss = log_loss(y_test, y_pred) fpr, tpr, thresholds = roc_curve(y_test, y_pred_probas[:,1]) auc_score = auc(fpr, tpr) res.append([name, acc, loss, auc_score])print('The cross-validation with stratified sampling took time (s): {}'.format(time.time() - start))
Just like in many Kaggle competitions, the winner is again gradient boosting:
Python multiprocessing
In Python, the multiprocessing module is designed to divide work between multiple processes to improve the performance. Here I used the pool class with map method to split the iterable to separate tasks. Below code runs the same process using 4 processors, it completed within 20s.
import itertoolsimport multiprocessingfrom multiprocessing import Poolcv_index = [(i, j) for i, j in sss.split(X, y)]params = list(itertools.product(cv_index, classifiers))def cv_test(params): global X global y train_index = params[0][0] test_index = params[0][1] clf = params[1] X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] name = clf.__class__.__name__ clf.fit(X_train, y_train) y_pred = clf.predict(X_test) y_pred_probas = clf.predict_proba(X_test) acc = accuracy_score(y_test, y_pred) loss = log_loss(y_test, y_pred) fpr, tpr, thresholds = roc_curve(y_test, y_pred_probas[:,1]) auc_score = auc(fpr, tpr) return [name, acc, loss, auc_score]p = Pool(processes = 4)start = time.time()res = p.map(cv_test, params)p.close()p.join()print('The cross-validation with stratified sampling on 5 cores took time (s): {}'.format(time.time() - start))
Spark mapPartition
I am always a big fun of Spark. Rdd is the fundamental data structure of Spark. Imagine that rdd as a group of many rows, and Spark converts these rows into multiple partitions. mapPartition enables to call the function on each partition whose content is available as a sequential stream of values via the input argument iterator. Below code shows how to rewrite the same process in PySpark environment. It completed within 20s as well.
import pysparkfrom pyspark.sql import SparkSessionfrom pyspark import SparkContext, SparkConfspark = SparkSession.builder.appName("pyspark-test").getOrCreate()bc_X = spark.sparkContext.broadcast(X)bc_y = spark.sparkContext.broadcast(y)def map_partitions_exec(X, y): def cv_test(iterator): for i in iterator: train_index = i[0][0] test_index = i[0][1] clf = i[1] X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] name = clf.__class__.__name__ clf.fit(X_train, y_train) y_pred = clf.predict(X_test) y_pred_probas = clf.predict_proba(X_test) acc = accuracy_score(y_test, y_pred) loss = log_loss(y_test, y_pred) fpr, tpr, thresholds = roc_curve(y_test, y_pred_probas[:,1]) auc_score = auc(fpr, tpr) yield [name, acc, loss, auc_score] return cv_testparams_spark = spark.sparkContext.parallelize(params,4)res = params_spark.mapPartitions(map_partitions_exec(bc_X.value, bc_y.value))start = time.time()res = res.collect()print('The cross-validation with stratified sampling using spark took time (s): {}'.format(time.time() - start))
Hopefully, these little coding tricks can help be more productive in your daily work.
|
[
{
"code": null,
"e": 612,
"s": 172,
"text": "In science, behind every achievement is grinding, rigorous work. And success is unlikely to happen with one attempt. As a data scientist, you probably deal with huge amount of data and computations, perform repeated tests and experiments on your day-to-day work. Though you don’t want to turn your rewarding, stimulating job into tedious one by waiting the time-consuming operation repeating again and again, observation after observation."
},
{
"code": null,
"e": 942,
"s": 612,
"text": "The computers today have multiple processors to allow running multiple functions simultaneously. However, this doesn’t help if the programmer isn’t aware of it, or doesn’t know how to use it, which leads to me writing this post to demonstrate how to parallelize your process using Python multiprocessing and PySpark mapPartition."
},
{
"code": null,
"e": 965,
"s": 942,
"text": "Machine learning model"
},
{
"code": null,
"e": 1493,
"s": 965,
"text": "Data science is a varied field that includes a wide range of work. One important application is to build machine learning pipelines and personalized data products to better target customers and enable more accurate decision making. In this post, I choose the step of cross-validation with stratified sampling in building a machine learning model as an example to parallelize it in both Python and Spark environment. The data I use is bank marketing data set from UCI machine learning repository for its relatively clean nature."
},
{
"code": null,
"e": 1821,
"s": 1493,
"text": "Since this post focuses on parallelism, I skip the steps of data explorative analysis, feature engineering, and feature selection. After some pre-processing, I obtained the data on the left that is ready for modeling, column y is our target variable which is whether the client subscribed to a term deposit during the campaign."
},
{
"code": null,
"e": 2203,
"s": 1821,
"text": "Now let’s get into details of the model selection step with cross validation. As a common practice, I include most classifiers from scikit-learn into a list called classifiers, and use StratifiedShuffleSplit method from sklearn.model_selection to perform this step. For model comparison purpose, I calculated accuracy score, log loss and AUC. This step took 46s, below is the code:"
},
{
"code": null,
"e": 2972,
"s": 2203,
"text": "sss = StratifiedShuffleSplit(n_splits = 10, test_size = 0.1, random_state = 0)start = time.time()res = []for train_index, test_index in sss.split(X, y): X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] for clf in classifiers: name = clf.__class__.__name__ clf.fit(X_train, y_train) y_pred = clf.predict(X_test) y_pred_probas = clf.predict_proba(X_test) acc = accuracy_score(y_test, y_pred) loss = log_loss(y_test, y_pred) fpr, tpr, thresholds = roc_curve(y_test, y_pred_probas[:,1]) auc_score = auc(fpr, tpr) res.append([name, acc, loss, auc_score])print('The cross-validation with stratified sampling took time (s): {}'.format(time.time() - start))"
},
{
"code": null,
"e": 3050,
"s": 2972,
"text": "Just like in many Kaggle competitions, the winner is again gradient boosting:"
},
{
"code": null,
"e": 3073,
"s": 3050,
"text": "Python multiprocessing"
},
{
"code": null,
"e": 3355,
"s": 3073,
"text": "In Python, the multiprocessing module is designed to divide work between multiple processes to improve the performance. Here I used the pool class with map method to split the iterable to separate tasks. Below code runs the same process using 4 processors, it completed within 20s."
},
{
"code": null,
"e": 4296,
"s": 3355,
"text": "import itertoolsimport multiprocessingfrom multiprocessing import Poolcv_index = [(i, j) for i, j in sss.split(X, y)]params = list(itertools.product(cv_index, classifiers))def cv_test(params): global X global y train_index = params[0][0] test_index = params[0][1] clf = params[1] X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] name = clf.__class__.__name__ clf.fit(X_train, y_train) y_pred = clf.predict(X_test) y_pred_probas = clf.predict_proba(X_test) acc = accuracy_score(y_test, y_pred) loss = log_loss(y_test, y_pred) fpr, tpr, thresholds = roc_curve(y_test, y_pred_probas[:,1]) auc_score = auc(fpr, tpr) return [name, acc, loss, auc_score]p = Pool(processes = 4)start = time.time()res = p.map(cv_test, params)p.close()p.join()print('The cross-validation with stratified sampling on 5 cores took time (s): {}'.format(time.time() - start))"
},
{
"code": null,
"e": 4315,
"s": 4296,
"text": "Spark mapPartition"
},
{
"code": null,
"e": 4752,
"s": 4315,
"text": "I am always a big fun of Spark. Rdd is the fundamental data structure of Spark. Imagine that rdd as a group of many rows, and Spark converts these rows into multiple partitions. mapPartition enables to call the function on each partition whose content is available as a sequential stream of values via the input argument iterator. Below code shows how to rewrite the same process in PySpark environment. It completed within 20s as well."
},
{
"code": null,
"e": 5992,
"s": 4752,
"text": "import pysparkfrom pyspark.sql import SparkSessionfrom pyspark import SparkContext, SparkConfspark = SparkSession.builder.appName(\"pyspark-test\").getOrCreate()bc_X = spark.sparkContext.broadcast(X)bc_y = spark.sparkContext.broadcast(y)def map_partitions_exec(X, y): def cv_test(iterator): for i in iterator: train_index = i[0][0] test_index = i[0][1] clf = i[1] X_train, X_test = X[train_index], X[test_index] y_train, y_test = y[train_index], y[test_index] name = clf.__class__.__name__ clf.fit(X_train, y_train) y_pred = clf.predict(X_test) y_pred_probas = clf.predict_proba(X_test) acc = accuracy_score(y_test, y_pred) loss = log_loss(y_test, y_pred) fpr, tpr, thresholds = roc_curve(y_test, y_pred_probas[:,1]) auc_score = auc(fpr, tpr) yield [name, acc, loss, auc_score] return cv_testparams_spark = spark.sparkContext.parallelize(params,4)res = params_spark.mapPartitions(map_partitions_exec(bc_X.value, bc_y.value))start = time.time()res = res.collect()print('The cross-validation with stratified sampling using spark took time (s): {}'.format(time.time() - start))"
}
] |
Adding an image to SAP Adobe form from MIME repository
|
Note that Image must be uploaded from system to MIME beforehand.
Run Transaction SE78 → Upload (F5).
You have to declare 2 variables in the interface - global data with types string and xstring, You need to change the data declaration as below −
data: gv_bmp_watermark type xstring.
constants: gc_url_watermark type string
value '/BC/PUBLIC/MyImages/watermark100.bmp'.
You need to add the following under code initialization.
//* Read Images
data: lr_api type ref to if_mr_api.
lr_api = cl_mime_repository_api=>get_api( ).
lr_api->get( exporting i_url = gc_url_watermark
importing e_content = gv_bmp_watermark).
You also need to change context node a bit as mentioned below −
Name: WATERMARK
Graphic Type: GRAPHIC CONTENT
Field: GV_BMP_WATERMARK
MIME Type: 'image/bmp'
For more details, you can refer below lin −:
https://archive.sap.com/discussions/thread/3519383
https://wiki.scn.sap.com/wiki/display/profile/2007/11/01/Adding+Images+and+text+modules+in+Adobe+Forms
|
[
{
"code": null,
"e": 1127,
"s": 1062,
"text": "Note that Image must be uploaded from system to MIME beforehand."
},
{
"code": null,
"e": 1163,
"s": 1127,
"text": "Run Transaction SE78 → Upload (F5)."
},
{
"code": null,
"e": 1308,
"s": 1163,
"text": "You have to declare 2 variables in the interface - global data with types string and xstring, You need to change the data declaration as below −"
},
{
"code": null,
"e": 1431,
"s": 1308,
"text": "data: gv_bmp_watermark type xstring.\nconstants: gc_url_watermark type string\nvalue '/BC/PUBLIC/MyImages/watermark100.bmp'."
},
{
"code": null,
"e": 1488,
"s": 1431,
"text": "You need to add the following under code initialization."
},
{
"code": null,
"e": 1687,
"s": 1488,
"text": "//* Read Images\ndata: lr_api type ref to if_mr_api.\nlr_api = cl_mime_repository_api=>get_api( ).\nlr_api->get( exporting i_url = gc_url_watermark\n importing e_content = gv_bmp_watermark)."
},
{
"code": null,
"e": 1751,
"s": 1687,
"text": "You also need to change context node a bit as mentioned below −"
},
{
"code": null,
"e": 1868,
"s": 1751,
"text": "Name: WATERMARK \nGraphic Type: GRAPHIC CONTENT \nField: GV_BMP_WATERMARK \nMIME Type: 'image/bmp'"
},
{
"code": null,
"e": 1913,
"s": 1868,
"text": "For more details, you can refer below lin −:"
},
{
"code": null,
"e": 2067,
"s": 1913,
"text": "https://archive.sap.com/discussions/thread/3519383\nhttps://wiki.scn.sap.com/wiki/display/profile/2007/11/01/Adding+Images+and+text+modules+in+Adobe+Forms"
}
] |
FOCL Algorithm - GeeksforGeeks
|
26 Nov, 2020
Prerequisite : FOIL Algorithm
The First Order Combined Learner (FOCL) Algorithm is an extension of the purely inductive, FOIL Algorithm. It uses domain theory to further improve the search for the best-rule and greatly improves accuracy. It incorporates the methods of Explanation-Based learning (EBL) into the existing methods of FOIL. But before getting into the working of FOCL, let us first understand the following:
Domain Theory
Explanation-Based Learning
Explanation-Based Learning (EBL)
In simple terms, it is the ability to gain basic problem-solving techniques by observing and analyzing solutions to specific problems. In terms of Machine Learning, it is an algorithm that aims to understand why an example is a part of a particular concept to make generalizations or form concepts from training examples. For example, EBL uses a domain theory and creates a program that learns to play chess.
Intuition:
The objective of EBL is to understand the essential properties of a particular concept. So, we need to find out what makes an example, part of a particular concept. Unlike FOIL algorithm, here we focus on the one example instead of collecting multiple examples.
The ability to explain single examples is known as “Domain Theory”.
An EBL accepts 4 kinds of input:
i) A training example: what the learning model sees in the world.
ii) A goal concept: a high level description of what the model is supposed to learn.
iii) A operational criterion: states which other terms
can appear in the generalized result.
iv) A domain theory: set of rules that describe relationships between objects and actions in a domain.
From the above 4 parameters, EBL uses the domain theory to find that training example, that best describes the goal concept while abiding by the operational criterion and keeping our justification as general as possible.
EBL involves 2 steps:
Explanation — The domain theory is used to eliminate all the unimportant training example while retaining the important ones that best describe the goal concept.Generalization — The explanation of the goal concept is made as general and widely applicable as possible. This ensures that all cases are covered, not just certain specific ones.
Explanation — The domain theory is used to eliminate all the unimportant training example while retaining the important ones that best describe the goal concept.
Generalization — The explanation of the goal concept is made as general and widely applicable as possible. This ensures that all cases are covered, not just certain specific ones.
EBL Architecture:
EBL model during training During training, the model generalizes the training example in such a way that all scenarios lead to the Goal Concept, not just in specific cases. (As shown in Fig 1)
During training, the model generalizes the training example in such a way that all scenarios lead to the Goal Concept, not just in specific cases. (As shown in Fig 1)
Fig 1 : Training EBL Model
EBL model after training Post training, EBL model tends to directly reach the hypothesis space involving the goal concept. (As shown in Fig 2)
Post training, EBL model tends to directly reach the hypothesis space involving the goal concept. (As shown in Fig 2)
Fig 2 : Trained EBL Model
FOCL
The goal of FOCL, like FOIL, is to create a rule in terms of the extensionally defined predicates, that covers all the positive examples and none of the negative examples. Unlike FOIL, FOCL integrates background knowledge and EBL methods into it which leads to a much more efficient search of hypothesis space that fits the training data. (As shown in Fig 3)
Fig 3 – FOIL vs FOCL
FOCL: Intuition
Like FOIL, FOCL also tends to perform an iterative process of learning a set of best-rules to cover the training examples and then remove all the training examples covered by that best rule. (using a sequential covering algorithm)
However, what makes the FOCL algorithm more powerful is the approach that it adapts while searching for that best-rule.
A literal is called operational if it can describe the training example properly leading to the output hypothesis. In contrast, literals that occur only as intermediate features in the domain theory, but not as primitive attributes of the instances, are considered non-operational. Non-operational predicates are evaluated in the same manner as operational predicates in FOCL.
Algorithm Involved:
//Inputs Literal --> operationalized
List of positive examples
List of negative examples
//Output Literal --> operational form
Operationalize(Literal, Positive examples, Negative examples):
If(Literal = operational):
Return Literal
Initialize Operational_Literals to the empty set
For each clause in the definition of Literal
Compute information gain of the clause over Positive examples and Negative examples
For the clause with the maximum gain
For each literal L in the clause
Operational_Literals <-- Operationalize(L, Positive examples, Negative examples)
Working of the Algorithm
Fig 4 : FOCL Example
Step 1 – Use the same method as done in FOIL and add a single feature for each operational literal that is not part of the hypothesis space so as to create candidates for the best rule.(solid arrows in Fig.4 denote specializations of bottle)
Step 2 – Create an operational literal that is logically efficient to explain the goal concept according to the Domain Theory.(dashed arrows in Fig.4 denote domain theory based specializations of bottle)
Step 3 – Add this set of literals to the current preconditions of hypothesis.
Step 4 – Remove all those preconditions of hypothesis space that are unnecessary according to the training data.
Let us consider the example shown in Fig 4.
First, FOCL creates all the candidate literals that have the possibility of becoming the best-rule (all denoted by solid arrows). Something we have already seen in the FOIL algorithm. In addition, it creates several logically relevant candidate literals of its own. (the domain theory)
Then, it selects one of the literals from the domain theory whose precondition matches with the goal concept. If there are several such literals present, then it just selects one which gives the most information related to the goal concept.
For example,
If the bottle (goal concept) is made of steel (while satisfying the other domain theory preconditions),
then the algorithm will select that as it the most relevant information related to the goal concept.
i.e. the bottle.
Now, all those literals that removed unless the affect the classification accuracy over the training examples. This is done so that the domain theory doesn’t overspecialize the result by addition irrelevant literals. This set of literals is now added to the preconditions of the current hypothesis.
Finally, one candidate literal which provides the maximum information gain is selected out two specialization methods. (FOIL and domain theory)
FOCL is a powerful machine learning algorithm that uses EBL and domain theory techniques, reaching the hypothesis space quickly and efficiently. It has shown more improved and accurate results than the Inductive FOIL Algorithm. A study on “Legal Chessboard Positions” showed that on 60 training examples describing 30 legal and 30 illegal endgame board positions, FOIL accuracy was about 86% while that of FOCL was about 94%. Similar results have been obtained in other domains. For any doubt/query, comment below.
Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready.
Machine Learning
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Support Vector Machine Algorithm
Singular Value Decomposition (SVD)
k-nearest neighbor algorithm in Python
DBSCAN Clustering in ML | Density based clustering
ML | Stochastic Gradient Descent (SGD)
Bagging vs Boosting in Machine Learning
Intuition of Adam Optimizer
Principal Component Analysis with Python
Python | Decision Tree Regression using sklearn
CNN | Introduction to Pooling Layer
|
[
{
"code": null,
"e": 24264,
"s": 24236,
"text": "\n26 Nov, 2020"
},
{
"code": null,
"e": 24294,
"s": 24264,
"text": "Prerequisite : FOIL Algorithm"
},
{
"code": null,
"e": 24685,
"s": 24294,
"text": "The First Order Combined Learner (FOCL) Algorithm is an extension of the purely inductive, FOIL Algorithm. It uses domain theory to further improve the search for the best-rule and greatly improves accuracy. It incorporates the methods of Explanation-Based learning (EBL) into the existing methods of FOIL. But before getting into the working of FOCL, let us first understand the following:"
},
{
"code": null,
"e": 24699,
"s": 24685,
"text": "Domain Theory"
},
{
"code": null,
"e": 24726,
"s": 24699,
"text": "Explanation-Based Learning"
},
{
"code": null,
"e": 24759,
"s": 24726,
"text": "Explanation-Based Learning (EBL)"
},
{
"code": null,
"e": 25169,
"s": 24759,
"text": "In simple terms, it is the ability to gain basic problem-solving techniques by observing and analyzing solutions to specific problems. In terms of Machine Learning, it is an algorithm that aims to understand why an example is a part of a particular concept to make generalizations or form concepts from training examples. For example, EBL uses a domain theory and creates a program that learns to play chess. "
},
{
"code": null,
"e": 25181,
"s": 25169,
"text": "Intuition: "
},
{
"code": null,
"e": 25444,
"s": 25181,
"text": "The objective of EBL is to understand the essential properties of a particular concept. So, we need to find out what makes an example, part of a particular concept. Unlike FOIL algorithm, here we focus on the one example instead of collecting multiple examples. "
},
{
"code": null,
"e": 25512,
"s": 25444,
"text": "The ability to explain single examples is known as “Domain Theory”."
},
{
"code": null,
"e": 25545,
"s": 25512,
"text": "An EBL accepts 4 kinds of input:"
},
{
"code": null,
"e": 25894,
"s": 25545,
"text": "i) A training example: what the learning model sees in the world.\nii) A goal concept: a high level description of what the model is supposed to learn.\niii) A operational criterion: states which other terms\n can appear in the generalized result.\niv) A domain theory: set of rules that describe relationships between objects and actions in a domain.\n"
},
{
"code": null,
"e": 26117,
"s": 25894,
"text": "From the above 4 parameters, EBL uses the domain theory to find that training example, that best describes the goal concept while abiding by the operational criterion and keeping our justification as general as possible. "
},
{
"code": null,
"e": 26139,
"s": 26117,
"text": "EBL involves 2 steps:"
},
{
"code": null,
"e": 26481,
"s": 26139,
"text": "Explanation — The domain theory is used to eliminate all the unimportant training example while retaining the important ones that best describe the goal concept.Generalization — The explanation of the goal concept is made as general and widely applicable as possible. This ensures that all cases are covered, not just certain specific ones. "
},
{
"code": null,
"e": 26643,
"s": 26481,
"text": "Explanation — The domain theory is used to eliminate all the unimportant training example while retaining the important ones that best describe the goal concept."
},
{
"code": null,
"e": 26824,
"s": 26643,
"text": "Generalization — The explanation of the goal concept is made as general and widely applicable as possible. This ensures that all cases are covered, not just certain specific ones. "
},
{
"code": null,
"e": 26844,
"s": 26824,
"text": "EBL Architecture: "
},
{
"code": null,
"e": 27037,
"s": 26844,
"text": "EBL model during training During training, the model generalizes the training example in such a way that all scenarios lead to the Goal Concept, not just in specific cases. (As shown in Fig 1)"
},
{
"code": null,
"e": 27204,
"s": 27037,
"text": "During training, the model generalizes the training example in such a way that all scenarios lead to the Goal Concept, not just in specific cases. (As shown in Fig 1)"
},
{
"code": null,
"e": 27231,
"s": 27204,
"text": "Fig 1 : Training EBL Model"
},
{
"code": null,
"e": 27375,
"s": 27231,
"text": "EBL model after training Post training, EBL model tends to directly reach the hypothesis space involving the goal concept. (As shown in Fig 2)"
},
{
"code": null,
"e": 27494,
"s": 27375,
"text": "Post training, EBL model tends to directly reach the hypothesis space involving the goal concept. (As shown in Fig 2)"
},
{
"code": null,
"e": 27520,
"s": 27494,
"text": "Fig 2 : Trained EBL Model"
},
{
"code": null,
"e": 27525,
"s": 27520,
"text": "FOCL"
},
{
"code": null,
"e": 27884,
"s": 27525,
"text": "The goal of FOCL, like FOIL, is to create a rule in terms of the extensionally defined predicates, that covers all the positive examples and none of the negative examples. Unlike FOIL, FOCL integrates background knowledge and EBL methods into it which leads to a much more efficient search of hypothesis space that fits the training data. (As shown in Fig 3)"
},
{
"code": null,
"e": 27905,
"s": 27884,
"text": "Fig 3 – FOIL vs FOCL"
},
{
"code": null,
"e": 27921,
"s": 27905,
"text": "FOCL: Intuition"
},
{
"code": null,
"e": 28152,
"s": 27921,
"text": "Like FOIL, FOCL also tends to perform an iterative process of learning a set of best-rules to cover the training examples and then remove all the training examples covered by that best rule. (using a sequential covering algorithm)"
},
{
"code": null,
"e": 28273,
"s": 28152,
"text": "However, what makes the FOCL algorithm more powerful is the approach that it adapts while searching for that best-rule. "
},
{
"code": null,
"e": 28651,
"s": 28273,
"text": "A literal is called operational if it can describe the training example properly leading to the output hypothesis. In contrast, literals that occur only as intermediate features in the domain theory, but not as primitive attributes of the instances, are considered non-operational. Non-operational predicates are evaluated in the same manner as operational predicates in FOCL. "
},
{
"code": null,
"e": 28672,
"s": 28651,
"text": "Algorithm Involved: "
},
{
"code": null,
"e": 29288,
"s": 28672,
"text": "//Inputs Literal --> operationalized \nList of positive examples \nList of negative examples\n//Output Literal --> operational form\nOperationalize(Literal, Positive examples, Negative examples):\n If(Literal = operational):\n Return Literal\n Initialize Operational_Literals to the empty set\n For each clause in the definition of Literal\n Compute information gain of the clause over Positive examples and Negative examples\n For the clause with the maximum gain\n For each literal L in the clause\n Operational_Literals <-- Operationalize(L, Positive examples, Negative examples)\n"
},
{
"code": null,
"e": 29313,
"s": 29288,
"text": "Working of the Algorithm"
},
{
"code": null,
"e": 29335,
"s": 29313,
"text": "Fig 4 : FOCL Example "
},
{
"code": null,
"e": 29577,
"s": 29335,
"text": "Step 1 – Use the same method as done in FOIL and add a single feature for each operational literal that is not part of the hypothesis space so as to create candidates for the best rule.(solid arrows in Fig.4 denote specializations of bottle)"
},
{
"code": null,
"e": 29781,
"s": 29577,
"text": "Step 2 – Create an operational literal that is logically efficient to explain the goal concept according to the Domain Theory.(dashed arrows in Fig.4 denote domain theory based specializations of bottle)"
},
{
"code": null,
"e": 29859,
"s": 29781,
"text": "Step 3 – Add this set of literals to the current preconditions of hypothesis."
},
{
"code": null,
"e": 29972,
"s": 29859,
"text": "Step 4 – Remove all those preconditions of hypothesis space that are unnecessary according to the training data."
},
{
"code": null,
"e": 30017,
"s": 29972,
"text": "Let us consider the example shown in Fig 4. "
},
{
"code": null,
"e": 30304,
"s": 30017,
"text": "First, FOCL creates all the candidate literals that have the possibility of becoming the best-rule (all denoted by solid arrows). Something we have already seen in the FOIL algorithm. In addition, it creates several logically relevant candidate literals of its own. (the domain theory)"
},
{
"code": null,
"e": 30545,
"s": 30304,
"text": "Then, it selects one of the literals from the domain theory whose precondition matches with the goal concept. If there are several such literals present, then it just selects one which gives the most information related to the goal concept."
},
{
"code": null,
"e": 30795,
"s": 30545,
"text": "For example, \n If the bottle (goal concept) is made of steel (while satisfying the other domain theory preconditions),\n then the algorithm will select that as it the most relevant information related to the goal concept.\n i.e. the bottle.\n\n"
},
{
"code": null,
"e": 31095,
"s": 30795,
"text": "Now, all those literals that removed unless the affect the classification accuracy over the training examples. This is done so that the domain theory doesn’t overspecialize the result by addition irrelevant literals. This set of literals is now added to the preconditions of the current hypothesis. "
},
{
"code": null,
"e": 31239,
"s": 31095,
"text": "Finally, one candidate literal which provides the maximum information gain is selected out two specialization methods. (FOIL and domain theory)"
},
{
"code": null,
"e": 31755,
"s": 31239,
"text": "FOCL is a powerful machine learning algorithm that uses EBL and domain theory techniques, reaching the hypothesis space quickly and efficiently. It has shown more improved and accurate results than the Inductive FOIL Algorithm. A study on “Legal Chessboard Positions” showed that on 60 training examples describing 30 legal and 30 illegal endgame board positions, FOIL accuracy was about 86% while that of FOCL was about 94%. Similar results have been obtained in other domains. For any doubt/query, comment below. "
},
{
"code": null,
"e": 31953,
"s": 31755,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important Machine Learning Concepts with the Machine Learning Foundation Course at a student-friendly price and become industry ready."
},
{
"code": null,
"e": 31970,
"s": 31953,
"text": "Machine Learning"
},
{
"code": null,
"e": 31987,
"s": 31970,
"text": "Machine Learning"
},
{
"code": null,
"e": 32085,
"s": 31987,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32094,
"s": 32085,
"text": "Comments"
},
{
"code": null,
"e": 32107,
"s": 32094,
"text": "Old Comments"
},
{
"code": null,
"e": 32140,
"s": 32107,
"text": "Support Vector Machine Algorithm"
},
{
"code": null,
"e": 32175,
"s": 32140,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 32214,
"s": 32175,
"text": "k-nearest neighbor algorithm in Python"
},
{
"code": null,
"e": 32265,
"s": 32214,
"text": "DBSCAN Clustering in ML | Density based clustering"
},
{
"code": null,
"e": 32304,
"s": 32265,
"text": "ML | Stochastic Gradient Descent (SGD)"
},
{
"code": null,
"e": 32344,
"s": 32304,
"text": "Bagging vs Boosting in Machine Learning"
},
{
"code": null,
"e": 32372,
"s": 32344,
"text": "Intuition of Adam Optimizer"
},
{
"code": null,
"e": 32413,
"s": 32372,
"text": "Principal Component Analysis with Python"
},
{
"code": null,
"e": 32461,
"s": 32413,
"text": "Python | Decision Tree Regression using sklearn"
}
] |
Setup Sending Email in Django Project - GeeksforGeeks
|
11 May, 2020
Haven’t you observed, when you register on some websites, you get a mail from that company or institution? The email would be, verification email or welcome email, account creation successful email or thanks-regard email, etc. For example, when you create a Google account, the first mail you get would be something like, “Hi Xyz, Welcome to Google. Your new account comes with access to Google products, apps, and services.....” Sending these types of emails from your Django application is quite easy.Although you can refer to the documentation for knowing more about sending emails in Django, but this is remarkably condensed and made easier.
How to send simple emails to the registered users of your Django application
Illustration of Django emails using an example. Consider a project named geeksforgeeks having an app named geeks. Refer this to create Django project and apps. Now let’s demonstrate this in geeksforgeeks project. In your “geeks” app’s settings.py file, enter the following,
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_HOST = 'smtp.gmail.com'EMAIL_USE_TLS = TrueEMAIL_PORT = 587EMAIL_HOST_USER = #sender's email-idEMAIL_HOST_PASSWORD = #password associated with above email-id
In the above code, EMAIL_HOST_USER = ‘[email protected]’ and EMAIL_HOST_PASSWORD = ‘xyz123abc@’ are the lines where you need to add the sender’s mail id and password. [email protected] and xyz123abc@ are just examples.
Now to use this in our application, move to views.py and add these lines at the top section as below.
from django.conf import settingsfrom django.core.mail import send_mail
Generally, emails are sent to the users who signup right? So, in the signup view function, add these lines.
subject = 'welcome to GFG world'message = f'Hi {user.username}, thank you for registering in geeksforgeeks.'email_from = settings.EMAIL_HOST_USERrecipient_list = [user.email, ]send_mail( subject, message, email_from, recipient_list )
Now we will understand what exactly is happening. Here,
subject refers to the email subject.
message refers to the email message, the body of the email.
email_from refers to the sender’s details.This takes the EMAIL_HOST_USER from settings.py file, where you added those lines of code earlier.
recipient_list is the list of recipients to whom the mail has to be sent that is, whoever registers to your application they receive the email.
send_mail is an inbuilt Django function that takes subject, message, email_from, and recipient’s list as arguments, this is responsible to send emails.
After these extra lines of code has been added to your project, you can send emails now. But if you are using Gmail, then the first time you make these changes in your project and run, you might get SMTP error.
To correct that-1-Go to the Google account registered with the sender’s mail address and select Manage your account
2-Go to security section at the left nav and scroll down. In Less secure app access, turn on the access. By default, it would be turned off.
Finally run the application.Now, register any user to your application, and they will receive mail from the email account you had mentioned.
Python Django
Project
Python
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Banking Transaction System using Java
Student record management system using linked list
E-commerce Website using Django
Handling Ajax request in Django
How to write a good SRS for your Project
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
|
[
{
"code": null,
"e": 25723,
"s": 25695,
"text": "\n11 May, 2020"
},
{
"code": null,
"e": 26369,
"s": 25723,
"text": "Haven’t you observed, when you register on some websites, you get a mail from that company or institution? The email would be, verification email or welcome email, account creation successful email or thanks-regard email, etc. For example, when you create a Google account, the first mail you get would be something like, “Hi Xyz, Welcome to Google. Your new account comes with access to Google products, apps, and services.....” Sending these types of emails from your Django application is quite easy.Although you can refer to the documentation for knowing more about sending emails in Django, but this is remarkably condensed and made easier."
},
{
"code": null,
"e": 26446,
"s": 26369,
"text": "How to send simple emails to the registered users of your Django application"
},
{
"code": null,
"e": 26720,
"s": 26446,
"text": "Illustration of Django emails using an example. Consider a project named geeksforgeeks having an app named geeks. Refer this to create Django project and apps. Now let’s demonstrate this in geeksforgeeks project. In your “geeks” app’s settings.py file, enter the following,"
},
{
"code": "EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'EMAIL_HOST = 'smtp.gmail.com'EMAIL_USE_TLS = TrueEMAIL_PORT = 587EMAIL_HOST_USER = #sender's email-idEMAIL_HOST_PASSWORD = #password associated with above email-id",
"e": 26945,
"s": 26720,
"text": null
},
{
"code": null,
"e": 27166,
"s": 26945,
"text": "In the above code, EMAIL_HOST_USER = ‘[email protected]’ and EMAIL_HOST_PASSWORD = ‘xyz123abc@’ are the lines where you need to add the sender’s mail id and password. [email protected] and xyz123abc@ are just examples."
},
{
"code": null,
"e": 27268,
"s": 27166,
"text": "Now to use this in our application, move to views.py and add these lines at the top section as below."
},
{
"code": "from django.conf import settingsfrom django.core.mail import send_mail",
"e": 27339,
"s": 27268,
"text": null
},
{
"code": null,
"e": 27447,
"s": 27339,
"text": "Generally, emails are sent to the users who signup right? So, in the signup view function, add these lines."
},
{
"code": "subject = 'welcome to GFG world'message = f'Hi {user.username}, thank you for registering in geeksforgeeks.'email_from = settings.EMAIL_HOST_USERrecipient_list = [user.email, ]send_mail( subject, message, email_from, recipient_list )",
"e": 27681,
"s": 27447,
"text": null
},
{
"code": null,
"e": 27737,
"s": 27681,
"text": "Now we will understand what exactly is happening. Here,"
},
{
"code": null,
"e": 27774,
"s": 27737,
"text": "subject refers to the email subject."
},
{
"code": null,
"e": 27834,
"s": 27774,
"text": "message refers to the email message, the body of the email."
},
{
"code": null,
"e": 27975,
"s": 27834,
"text": "email_from refers to the sender’s details.This takes the EMAIL_HOST_USER from settings.py file, where you added those lines of code earlier."
},
{
"code": null,
"e": 28119,
"s": 27975,
"text": "recipient_list is the list of recipients to whom the mail has to be sent that is, whoever registers to your application they receive the email."
},
{
"code": null,
"e": 28271,
"s": 28119,
"text": "send_mail is an inbuilt Django function that takes subject, message, email_from, and recipient’s list as arguments, this is responsible to send emails."
},
{
"code": null,
"e": 28482,
"s": 28271,
"text": "After these extra lines of code has been added to your project, you can send emails now. But if you are using Gmail, then the first time you make these changes in your project and run, you might get SMTP error."
},
{
"code": null,
"e": 28598,
"s": 28482,
"text": "To correct that-1-Go to the Google account registered with the sender’s mail address and select Manage your account"
},
{
"code": null,
"e": 28739,
"s": 28598,
"text": "2-Go to security section at the left nav and scroll down. In Less secure app access, turn on the access. By default, it would be turned off."
},
{
"code": null,
"e": 28880,
"s": 28739,
"text": "Finally run the application.Now, register any user to your application, and they will receive mail from the email account you had mentioned."
},
{
"code": null,
"e": 28894,
"s": 28880,
"text": "Python Django"
},
{
"code": null,
"e": 28902,
"s": 28894,
"text": "Project"
},
{
"code": null,
"e": 28909,
"s": 28902,
"text": "Python"
},
{
"code": null,
"e": 28925,
"s": 28909,
"text": "Write From Home"
},
{
"code": null,
"e": 29023,
"s": 28925,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29061,
"s": 29023,
"text": "Banking Transaction System using Java"
},
{
"code": null,
"e": 29112,
"s": 29061,
"text": "Student record management system using linked list"
},
{
"code": null,
"e": 29144,
"s": 29112,
"text": "E-commerce Website using Django"
},
{
"code": null,
"e": 29176,
"s": 29144,
"text": "Handling Ajax request in Django"
},
{
"code": null,
"e": 29217,
"s": 29176,
"text": "How to write a good SRS for your Project"
},
{
"code": null,
"e": 29245,
"s": 29217,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 29295,
"s": 29245,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 29317,
"s": 29295,
"text": "Python map() function"
}
] |
Object Compression in Java with Examples - GeeksforGeeks
|
13 May, 2022
Object Compression is the process of reducing the size of the object with the help of various classes and methods. The receiver then retrieves full information by decompressing the object which is compressed by the sender. Take a look at below figure to distinguish the size of the file before compressing and the size the file after compressing:
Java object compression is very useful in the case where we need to transfer large amounts of objects through a network. Object compression is done at the sender side and uncompressed them at the other end i.e receiver side. By this, we can improve the performance and can send and receive the objects in heavy quantity between two ends.
Java object compression is done using the GZIPOutputStream class (this class implements a stream filter for writing compressed data in the GZIP file format) and passes it to the ObjectOutputStream class (this class extends OutputStream and implements ObjectOutput, ObjectStreamConstants) to write the object into an external file.
We need to extend the Serializable class because the object we are going to compress will be represented by the User object. That’s why we need to make the User object serializable.
Java
// Java Program to demonstrate// Object Compression import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.zip.GZIPOutputStream;import java.io.File; public class GFG { public static void main(String args[]) { // Creating objects of Java Class Bill Bill b1 = new Bill("176BU", "Abhishek Gupta"); Bill b2 = new Bill("176DA", "Sushant Singh"); FileOutputStream f = null; // Creates a GZIPOutputStream and // initialize it with null GZIPOutputStream g = null; // Creates an ObjectOutputStream and // initialise it with null // ObjectOutputStream writes to the // defined GZIPOutputStream. ObjectOutputStream o = null; // Write path of the file in the argument File newFile = new File("File.dat"); try { // Pass the File object // (newFile) to the // FileOutputStream f = new FileOutputStream(newFile); g = new GZIPOutputStream(f); // Now pass the GZIPOutputStream object // to the ObjectOutputStream o = new ObjectOutputStream(g); // Writes the object that are going // to be compressed to the // ObjectOutputStream using // writeObject(objectName) o.writeObject(b1); o.writeObject(b2); // flush() API methods of // ObjectOutputStream. o.flush(); System.out.println( "Process done.."); System.out.println( "Objects are compressed"); } catch ( FileNotFoundException e) { // Catch Block System.out.println( e.message()); } catch (IOException e) { // Catch Block System.out.println( e.message()); } finally { try { // Using their // close() API methods, // closes both // the GZIPOutputStream // and the // ObjectOutputStream if (o != null) o.close(); if (g != null) g.close(); } catch (Exception ex) { // Catch block System.out.println( ex.message()); } } }} class Bill implements Serializable { // Declaring the private variables private String billno; private String buyerName; // Creating constructor // of Java Class Bill public Bill( String bill, String buyer) { this.billno = bill; this.buyerName = buyer; } // Defining methods initializing // variables billno and buyerName public String getBill() { return billno; } public void setBill( String billno) { this.billno = billno; } public String getBuyerName() { return buyerName; } public void setBuyerName( String buyer) { this.buyerName = buyer; }}
Output:
Process done..
Objects are compressed.
Before Object Compression: After Object Compression: The size of the file can be compressed up to 70% of its initial size.
A large number of objects can be transferred over a network without any performance issue.No data is lost during the process of compression-decompression.
A large number of objects can be transferred over a network without any performance issue.
No data is lost during the process of compression-decompression.
It can take time in compression and decompression if the size of the file is very large.
It can take time in compression and decompression if the size of the file is very large.
vega
Java 8
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Interfaces in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Singleton Class in Java
Multidimensional Arrays in Java
Multithreading in Java
Collections in Java
Queue Interface In Java
|
[
{
"code": null,
"e": 25619,
"s": 25591,
"text": "\n13 May, 2022"
},
{
"code": null,
"e": 25967,
"s": 25619,
"text": "Object Compression is the process of reducing the size of the object with the help of various classes and methods. The receiver then retrieves full information by decompressing the object which is compressed by the sender. Take a look at below figure to distinguish the size of the file before compressing and the size the file after compressing: "
},
{
"code": null,
"e": 26306,
"s": 25967,
"text": "Java object compression is very useful in the case where we need to transfer large amounts of objects through a network. Object compression is done at the sender side and uncompressed them at the other end i.e receiver side. By this, we can improve the performance and can send and receive the objects in heavy quantity between two ends. "
},
{
"code": null,
"e": 26638,
"s": 26306,
"text": "Java object compression is done using the GZIPOutputStream class (this class implements a stream filter for writing compressed data in the GZIP file format) and passes it to the ObjectOutputStream class (this class extends OutputStream and implements ObjectOutput, ObjectStreamConstants) to write the object into an external file. "
},
{
"code": null,
"e": 26820,
"s": 26638,
"text": "We need to extend the Serializable class because the object we are going to compress will be represented by the User object. That’s why we need to make the User object serializable."
},
{
"code": null,
"e": 26825,
"s": 26820,
"text": "Java"
},
{
"code": "// Java Program to demonstrate// Object Compression import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.ObjectOutputStream;import java.io.Serializable;import java.util.zip.GZIPOutputStream;import java.io.File; public class GFG { public static void main(String args[]) { // Creating objects of Java Class Bill Bill b1 = new Bill(\"176BU\", \"Abhishek Gupta\"); Bill b2 = new Bill(\"176DA\", \"Sushant Singh\"); FileOutputStream f = null; // Creates a GZIPOutputStream and // initialize it with null GZIPOutputStream g = null; // Creates an ObjectOutputStream and // initialise it with null // ObjectOutputStream writes to the // defined GZIPOutputStream. ObjectOutputStream o = null; // Write path of the file in the argument File newFile = new File(\"File.dat\"); try { // Pass the File object // (newFile) to the // FileOutputStream f = new FileOutputStream(newFile); g = new GZIPOutputStream(f); // Now pass the GZIPOutputStream object // to the ObjectOutputStream o = new ObjectOutputStream(g); // Writes the object that are going // to be compressed to the // ObjectOutputStream using // writeObject(objectName) o.writeObject(b1); o.writeObject(b2); // flush() API methods of // ObjectOutputStream. o.flush(); System.out.println( \"Process done..\"); System.out.println( \"Objects are compressed\"); } catch ( FileNotFoundException e) { // Catch Block System.out.println( e.message()); } catch (IOException e) { // Catch Block System.out.println( e.message()); } finally { try { // Using their // close() API methods, // closes both // the GZIPOutputStream // and the // ObjectOutputStream if (o != null) o.close(); if (g != null) g.close(); } catch (Exception ex) { // Catch block System.out.println( ex.message()); } } }} class Bill implements Serializable { // Declaring the private variables private String billno; private String buyerName; // Creating constructor // of Java Class Bill public Bill( String bill, String buyer) { this.billno = bill; this.buyerName = buyer; } // Defining methods initializing // variables billno and buyerName public String getBill() { return billno; } public void setBill( String billno) { this.billno = billno; } public String getBuyerName() { return buyerName; } public void setBuyerName( String buyer) { this.buyerName = buyer; }}",
"e": 30061,
"s": 26825,
"text": null
},
{
"code": null,
"e": 30069,
"s": 30061,
"text": "Output:"
},
{
"code": null,
"e": 30108,
"s": 30069,
"text": "Process done..\nObjects are compressed."
},
{
"code": null,
"e": 30233,
"s": 30108,
"text": "Before Object Compression: After Object Compression: The size of the file can be compressed up to 70% of its initial size."
},
{
"code": null,
"e": 30388,
"s": 30233,
"text": "A large number of objects can be transferred over a network without any performance issue.No data is lost during the process of compression-decompression."
},
{
"code": null,
"e": 30479,
"s": 30388,
"text": "A large number of objects can be transferred over a network without any performance issue."
},
{
"code": null,
"e": 30544,
"s": 30479,
"text": "No data is lost during the process of compression-decompression."
},
{
"code": null,
"e": 30633,
"s": 30544,
"text": "It can take time in compression and decompression if the size of the file is very large."
},
{
"code": null,
"e": 30722,
"s": 30633,
"text": "It can take time in compression and decompression if the size of the file is very large."
},
{
"code": null,
"e": 30729,
"s": 30724,
"text": "vega"
},
{
"code": null,
"e": 30736,
"s": 30729,
"text": "Java 8"
},
{
"code": null,
"e": 30741,
"s": 30736,
"text": "Java"
},
{
"code": null,
"e": 30746,
"s": 30741,
"text": "Java"
},
{
"code": null,
"e": 30844,
"s": 30746,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30859,
"s": 30844,
"text": "Stream In Java"
},
{
"code": null,
"e": 30878,
"s": 30859,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 30896,
"s": 30878,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 30928,
"s": 30896,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 30948,
"s": 30928,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 30972,
"s": 30948,
"text": "Singleton Class in Java"
},
{
"code": null,
"e": 31004,
"s": 30972,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 31027,
"s": 31004,
"text": "Multithreading in Java"
},
{
"code": null,
"e": 31047,
"s": 31027,
"text": "Collections in Java"
}
] |
MongoDB: An introduction - GeeksforGeeks
|
15 Dec, 2021
MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format).
A simple MongoDB document Structure:
{
title: 'Geeksforgeeks',
by: 'Harshit Gupta',
url: 'https://www.geeksforgeeks.org',
type: 'NoSQL'
}
SQL databases store data in tabular format. This data is stored in a predefined data model which is not very much flexible for today’s real-world highly growing applications. Modern applications are more networked, social and interactive than ever. Applications are storing more and more data and are accessing it at higher rates.
Relational Database Management System(RDBMS) is not the correct choice when it comes to handling big data by the virtue of their design since they are not horizontally scalable. If the database runs on a single server, then it will reach a scaling limit. NoSQL databases are more scalable and provide superior performance. MongoDB is such a NoSQL database that scales by adding more and more servers and increases productivity with its flexible document model.
RDBMS vs MongoDB:
RDBMS has a typical schema design that shows number of tables and the relationship between these tables whereas MongoDB is document-oriented. There is no concept of schema or relationship.
Complex transactions are not supported in MongoDB because complex join operations are not available.
MongoDB allows a highly flexible and scalable document structure. For example, one data document of a collection in MongoDB can have two fields whereas the other document in the same collection can have four.
MongoDB is faster as compared to RDBMS due to efficient indexing and storage techniques.
There are a few terms that are related in both databases. What’s called Table in RDBMS is called a Collection in MongoDB. Similarly, a Tuple is called a Document and A Column is called a Field. MongoDB provides a default ‘_id’ (if not provided explicitly) which is a 12-byte hexadecimal number that assures the uniqueness of every document. It is similar to the Primary key in RDBMS.
Features of MongoDB:
Document Oriented: MongoDB stores the main subject in the minimal number of documents and not by breaking it up into multiple relational structures like RDBMS. For example, it stores all the information of a computer in a single document called Computer and not in distinct relational structures like CPU, RAM, Hard disk, etc.
Indexing: Without indexing, a database would have to scan every document of a collection to select those that match the query which would be inefficient. So, for efficient searching Indexing is a must and MongoDB uses it to process huge volumes of data in very less time.
Scalability: MongoDB scales horizontally using sharding (partitioning data across various servers). Data is partitioned into data chunks using the shard key, and these data chunks are evenly distributed across shards that reside across many physical servers. Also, new machines can be added to a running database.
Replication and High Availability: MongoDB increases the data availability with multiple copies of data on different servers. By providing redundancy, it protects the database from hardware failures. If one server goes down, the data can be retrieved easily from other active servers which also had the data stored on them.
Aggregation: Aggregation operations process data records and return the computed results. It is similar to the GROUPBY clause in SQL. A few aggregation expressions are sum, avg, min, max, etc
Where do we use MongoDB?
MongoDB is preferred over RDBMS in the following scenarios:
Big Data: If you have huge amount of data to be stored in tables, think of MongoDB before RDBMS databases. MongoDB has built-in solution for partitioning and sharding your database.
Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is schema-less. Adding a new field does not effect old documents and will be very easy.
Distributed data Since multiple copies of data are stored across different servers, recovery of data is instant and safe even if there is a hardware failure.
Language Support by MongoDB:
MongoDB currently provides official driver support for all popular programming languages like C, C++, Rust, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go, and Erlang.
Installing MongoDB:
Just go to http://www.mongodb.org/downloads and select your operating system out of Windows, Linux, Mac OS X and Solaris. A detailed explanation about the installation of MongoDB is given on their site.
For Windows, a few options for the 64-bit operating systems drops down. When you’re running on Windows 7, 8 or newer versions, select Windows 64-bit 2008 R2+. When you’re using Windows XP or Vista then select Windows 64-bit 2008 R2+ legacy.
Who’s using MongoDB?
MongoDB has been adopted as backend software by a number of major websites and services including EA, Cisco, Shutterfly, Adobe, Ericsson, Craigslist, eBay, and Foursquare.
Next Article : MongoDB and Python
For more information visit their website: https://www.mongodb.com/nosql-explained
About Author – Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks.
If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks.
shubham_singh
alispacea350
MongoDB
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Spring Boot JpaRepository with Example
Aggregation in MongoDB
Mongoose Populate() Method
MongoDB - Check the existence of the fields in the specified collection
How to build a basic CRUD app with Node.js and ReactJS ?
MongoDB - db.collection.Find() Method
How to connect MongoDB with ReactJS ?
Upsert in MongoDB
MongoDB - limit() Method
MongoDB - Distinct() Method
|
[
{
"code": null,
"e": 25244,
"s": 25216,
"text": "\n15 Dec, 2021"
},
{
"code": null,
"e": 25603,
"s": 25244,
"text": "MongoDB, the most popular NoSQL database, is an open-source document-oriented database. The term ‘NoSQL’ means ‘non-relational’. It means that MongoDB isn’t based on the table-like relational database structure but provides an altogether different mechanism for storage and retrieval of data. This format of storage is called BSON ( similar to JSON format). "
},
{
"code": null,
"e": 25641,
"s": 25603,
"text": "A simple MongoDB document Structure: "
},
{
"code": null,
"e": 25751,
"s": 25641,
"text": "{\n title: 'Geeksforgeeks',\n by: 'Harshit Gupta',\n url: 'https://www.geeksforgeeks.org',\n type: 'NoSQL'\n} "
},
{
"code": null,
"e": 26082,
"s": 25751,
"text": "SQL databases store data in tabular format. This data is stored in a predefined data model which is not very much flexible for today’s real-world highly growing applications. Modern applications are more networked, social and interactive than ever. Applications are storing more and more data and are accessing it at higher rates."
},
{
"code": null,
"e": 26543,
"s": 26082,
"text": "Relational Database Management System(RDBMS) is not the correct choice when it comes to handling big data by the virtue of their design since they are not horizontally scalable. If the database runs on a single server, then it will reach a scaling limit. NoSQL databases are more scalable and provide superior performance. MongoDB is such a NoSQL database that scales by adding more and more servers and increases productivity with its flexible document model."
},
{
"code": null,
"e": 26562,
"s": 26543,
"text": " RDBMS vs MongoDB:"
},
{
"code": null,
"e": 26751,
"s": 26562,
"text": "RDBMS has a typical schema design that shows number of tables and the relationship between these tables whereas MongoDB is document-oriented. There is no concept of schema or relationship."
},
{
"code": null,
"e": 26852,
"s": 26751,
"text": "Complex transactions are not supported in MongoDB because complex join operations are not available."
},
{
"code": null,
"e": 27061,
"s": 26852,
"text": "MongoDB allows a highly flexible and scalable document structure. For example, one data document of a collection in MongoDB can have two fields whereas the other document in the same collection can have four."
},
{
"code": null,
"e": 27150,
"s": 27061,
"text": "MongoDB is faster as compared to RDBMS due to efficient indexing and storage techniques."
},
{
"code": null,
"e": 27534,
"s": 27150,
"text": "There are a few terms that are related in both databases. What’s called Table in RDBMS is called a Collection in MongoDB. Similarly, a Tuple is called a Document and A Column is called a Field. MongoDB provides a default ‘_id’ (if not provided explicitly) which is a 12-byte hexadecimal number that assures the uniqueness of every document. It is similar to the Primary key in RDBMS."
},
{
"code": null,
"e": 27555,
"s": 27534,
"text": "Features of MongoDB:"
},
{
"code": null,
"e": 27882,
"s": 27555,
"text": "Document Oriented: MongoDB stores the main subject in the minimal number of documents and not by breaking it up into multiple relational structures like RDBMS. For example, it stores all the information of a computer in a single document called Computer and not in distinct relational structures like CPU, RAM, Hard disk, etc."
},
{
"code": null,
"e": 28154,
"s": 27882,
"text": "Indexing: Without indexing, a database would have to scan every document of a collection to select those that match the query which would be inefficient. So, for efficient searching Indexing is a must and MongoDB uses it to process huge volumes of data in very less time."
},
{
"code": null,
"e": 28468,
"s": 28154,
"text": "Scalability: MongoDB scales horizontally using sharding (partitioning data across various servers). Data is partitioned into data chunks using the shard key, and these data chunks are evenly distributed across shards that reside across many physical servers. Also, new machines can be added to a running database."
},
{
"code": null,
"e": 28792,
"s": 28468,
"text": "Replication and High Availability: MongoDB increases the data availability with multiple copies of data on different servers. By providing redundancy, it protects the database from hardware failures. If one server goes down, the data can be retrieved easily from other active servers which also had the data stored on them."
},
{
"code": null,
"e": 28984,
"s": 28792,
"text": "Aggregation: Aggregation operations process data records and return the computed results. It is similar to the GROUPBY clause in SQL. A few aggregation expressions are sum, avg, min, max, etc"
},
{
"code": null,
"e": 29009,
"s": 28984,
"text": "Where do we use MongoDB?"
},
{
"code": null,
"e": 29069,
"s": 29009,
"text": "MongoDB is preferred over RDBMS in the following scenarios:"
},
{
"code": null,
"e": 29251,
"s": 29069,
"text": "Big Data: If you have huge amount of data to be stored in tables, think of MongoDB before RDBMS databases. MongoDB has built-in solution for partitioning and sharding your database."
},
{
"code": null,
"e": 29409,
"s": 29251,
"text": "Unstable Schema: Adding a new column in RDBMS is hard whereas MongoDB is schema-less. Adding a new field does not effect old documents and will be very easy."
},
{
"code": null,
"e": 29567,
"s": 29409,
"text": "Distributed data Since multiple copies of data are stored across different servers, recovery of data is instant and safe even if there is a hardware failure."
},
{
"code": null,
"e": 29596,
"s": 29567,
"text": "Language Support by MongoDB:"
},
{
"code": null,
"e": 29771,
"s": 29596,
"text": "MongoDB currently provides official driver support for all popular programming languages like C, C++, Rust, C#, Java, Node.js, Perl, PHP, Python, Ruby, Scala, Go, and Erlang."
},
{
"code": null,
"e": 29791,
"s": 29771,
"text": "Installing MongoDB:"
},
{
"code": null,
"e": 29994,
"s": 29791,
"text": "Just go to http://www.mongodb.org/downloads and select your operating system out of Windows, Linux, Mac OS X and Solaris. A detailed explanation about the installation of MongoDB is given on their site."
},
{
"code": null,
"e": 30235,
"s": 29994,
"text": "For Windows, a few options for the 64-bit operating systems drops down. When you’re running on Windows 7, 8 or newer versions, select Windows 64-bit 2008 R2+. When you’re using Windows XP or Vista then select Windows 64-bit 2008 R2+ legacy."
},
{
"code": null,
"e": 30256,
"s": 30235,
"text": "Who’s using MongoDB?"
},
{
"code": null,
"e": 30428,
"s": 30256,
"text": "MongoDB has been adopted as backend software by a number of major websites and services including EA, Cisco, Shutterfly, Adobe, Ericsson, Craigslist, eBay, and Foursquare."
},
{
"code": null,
"e": 30463,
"s": 30428,
"text": "Next Article : MongoDB and Python "
},
{
"code": null,
"e": 30546,
"s": 30463,
"text": "For more information visit their website: https://www.mongodb.com/nosql-explained"
},
{
"code": null,
"e": 30871,
"s": 30546,
"text": "About Author – Kolkata based Harshit Gupta is an active blogger having keen interest in writing about current affairs, technical Blogs, stories, and personal life experiences. Besides passionate about writing, he also loves coding and dancing. Currently studying at IIEST, he is an active blog contributor at geeksforgeeks. "
},
{
"code": null,
"e": 30974,
"s": 30871,
"text": "If you also wish to showcase your blog here, please see GBlog for guest blog writing on GeeksforGeeks."
},
{
"code": null,
"e": 30990,
"s": 30976,
"text": "shubham_singh"
},
{
"code": null,
"e": 31003,
"s": 30990,
"text": "alispacea350"
},
{
"code": null,
"e": 31011,
"s": 31003,
"text": "MongoDB"
},
{
"code": null,
"e": 31019,
"s": 31011,
"text": "MongoDB"
},
{
"code": null,
"e": 31117,
"s": 31019,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31156,
"s": 31117,
"text": "Spring Boot JpaRepository with Example"
},
{
"code": null,
"e": 31179,
"s": 31156,
"text": "Aggregation in MongoDB"
},
{
"code": null,
"e": 31206,
"s": 31179,
"text": "Mongoose Populate() Method"
},
{
"code": null,
"e": 31278,
"s": 31206,
"text": "MongoDB - Check the existence of the fields in the specified collection"
},
{
"code": null,
"e": 31335,
"s": 31278,
"text": "How to build a basic CRUD app with Node.js and ReactJS ?"
},
{
"code": null,
"e": 31373,
"s": 31335,
"text": "MongoDB - db.collection.Find() Method"
},
{
"code": null,
"e": 31411,
"s": 31373,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 31429,
"s": 31411,
"text": "Upsert in MongoDB"
},
{
"code": null,
"e": 31454,
"s": 31429,
"text": "MongoDB - limit() Method"
}
] |
Introduction of General Register based CPU Organization - GeeksforGeeks
|
24 Feb, 2022
When we are using multiple general-purpose registers, instead of a single accumulator register, in the CPU Organization then this type of organization is known as General register-based CPU Organization. In this type of organization, the computer uses two or three address fields in their instruction format. Each address field may specify a general register or a memory word. If many CPU registers are available for heavily used variables and intermediate results, we can avoid memory references much of the time, thus vastly increasing program execution speed, and reducing program size.
For example:
MULT R1, R2, R3
This is an instruction of an arithmetic multiplication written in assembly language. It uses three address fields R1, R2, and R3. The meaning of this instruction is:
R1 <-- R2 * R3
This instruction also can be written using only two address fields as:
MULT R1, R2
In this instruction, the destination register is the same as one of the source registers. This means the operation
R1 <-- R1 * R2
The use of a large number of registers results in a short program with limited instructions.
Some examples of General register-based CPU Organizations are IBM 360 and PDP- 11.
The advantages of General register-based CPU organization –
The efficiency of the CPU increases as large number of registers are used in this organization.
Less memory space is used to store the program since the instructions are written in a compact way.
The disadvantages of General register based CPU organization –
Care should be taken to avoid unnecessary usage of registers. Thus, compilers need to be more intelligent in this aspect.
Since a large number of registers are used, thus extra cost is required in this organization.
General register CPU organization of two types:
Register-memory reference architecture (CPU with less register) – In this organization Source 1 is always required in the register, source 2 can be present either in the register or in memory. Here two address instruction formats are compatible instruction formats.Register-register reference architecture (CPU with more register) – In this organization, ALU operations are performed only on registered data. So operands are required in the register. After manipulation, the result is also placed in a register. Here three address instruction formats are the compatible instruction format.
Register-memory reference architecture (CPU with less register) – In this organization Source 1 is always required in the register, source 2 can be present either in the register or in memory. Here two address instruction formats are compatible instruction formats.
Register-register reference architecture (CPU with more register) – In this organization, ALU operations are performed only on registered data. So operands are required in the register. After manipulation, the result is also placed in a register. Here three address instruction formats are the compatible instruction format.
VaibhavRai3
vivekpal23123451254
Pushpender007
aadrika18
Computer Organization & Architecture
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program for Decimal to Binary Conversion
Logical and Physical Address in Operating System
Direct Access Media (DMA) Controller in Computer Architecture
Interrupts
Addressing modes in 8085 microprocessor
Flag register of 8086 microprocessor
Programmable peripheral interface 8255
Flag register in 8085 microprocessor
IEEE Standard 754 Floating Point Numbers
Addressing modes in 8086 microprocessor
|
[
{
"code": null,
"e": 28707,
"s": 28679,
"text": "\n24 Feb, 2022"
},
{
"code": null,
"e": 29298,
"s": 28707,
"text": "When we are using multiple general-purpose registers, instead of a single accumulator register, in the CPU Organization then this type of organization is known as General register-based CPU Organization. In this type of organization, the computer uses two or three address fields in their instruction format. Each address field may specify a general register or a memory word. If many CPU registers are available for heavily used variables and intermediate results, we can avoid memory references much of the time, thus vastly increasing program execution speed, and reducing program size. "
},
{
"code": null,
"e": 29312,
"s": 29298,
"text": "For example: "
},
{
"code": null,
"e": 29329,
"s": 29312,
"text": "MULT R1, R2, R3 "
},
{
"code": null,
"e": 29495,
"s": 29329,
"text": "This is an instruction of an arithmetic multiplication written in assembly language. It uses three address fields R1, R2, and R3. The meaning of this instruction is:"
},
{
"code": null,
"e": 29511,
"s": 29495,
"text": "R1 <-- R2 * R3 "
},
{
"code": null,
"e": 29583,
"s": 29511,
"text": "This instruction also can be written using only two address fields as: "
},
{
"code": null,
"e": 29596,
"s": 29583,
"text": "MULT R1, R2 "
},
{
"code": null,
"e": 29712,
"s": 29596,
"text": "In this instruction, the destination register is the same as one of the source registers. This means the operation "
},
{
"code": null,
"e": 29728,
"s": 29712,
"text": "R1 <-- R1 * R2 "
},
{
"code": null,
"e": 29822,
"s": 29728,
"text": "The use of a large number of registers results in a short program with limited instructions. "
},
{
"code": null,
"e": 29906,
"s": 29822,
"text": "Some examples of General register-based CPU Organizations are IBM 360 and PDP- 11. "
},
{
"code": null,
"e": 29967,
"s": 29906,
"text": "The advantages of General register-based CPU organization – "
},
{
"code": null,
"e": 30063,
"s": 29967,
"text": "The efficiency of the CPU increases as large number of registers are used in this organization."
},
{
"code": null,
"e": 30163,
"s": 30063,
"text": "Less memory space is used to store the program since the instructions are written in a compact way."
},
{
"code": null,
"e": 30227,
"s": 30163,
"text": "The disadvantages of General register based CPU organization – "
},
{
"code": null,
"e": 30349,
"s": 30227,
"text": "Care should be taken to avoid unnecessary usage of registers. Thus, compilers need to be more intelligent in this aspect."
},
{
"code": null,
"e": 30443,
"s": 30349,
"text": "Since a large number of registers are used, thus extra cost is required in this organization."
},
{
"code": null,
"e": 30491,
"s": 30443,
"text": "General register CPU organization of two types:"
},
{
"code": null,
"e": 31081,
"s": 30491,
"text": "Register-memory reference architecture (CPU with less register) – In this organization Source 1 is always required in the register, source 2 can be present either in the register or in memory. Here two address instruction formats are compatible instruction formats.Register-register reference architecture (CPU with more register) – In this organization, ALU operations are performed only on registered data. So operands are required in the register. After manipulation, the result is also placed in a register. Here three address instruction formats are the compatible instruction format."
},
{
"code": null,
"e": 31347,
"s": 31081,
"text": "Register-memory reference architecture (CPU with less register) – In this organization Source 1 is always required in the register, source 2 can be present either in the register or in memory. Here two address instruction formats are compatible instruction formats."
},
{
"code": null,
"e": 31672,
"s": 31347,
"text": "Register-register reference architecture (CPU with more register) – In this organization, ALU operations are performed only on registered data. So operands are required in the register. After manipulation, the result is also placed in a register. Here three address instruction formats are the compatible instruction format."
},
{
"code": null,
"e": 31684,
"s": 31672,
"text": "VaibhavRai3"
},
{
"code": null,
"e": 31704,
"s": 31684,
"text": "vivekpal23123451254"
},
{
"code": null,
"e": 31718,
"s": 31704,
"text": "Pushpender007"
},
{
"code": null,
"e": 31728,
"s": 31718,
"text": "aadrika18"
},
{
"code": null,
"e": 31765,
"s": 31728,
"text": "Computer Organization & Architecture"
},
{
"code": null,
"e": 31863,
"s": 31765,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31904,
"s": 31863,
"text": "Program for Decimal to Binary Conversion"
},
{
"code": null,
"e": 31953,
"s": 31904,
"text": "Logical and Physical Address in Operating System"
},
{
"code": null,
"e": 32015,
"s": 31953,
"text": "Direct Access Media (DMA) Controller in Computer Architecture"
},
{
"code": null,
"e": 32026,
"s": 32015,
"text": "Interrupts"
},
{
"code": null,
"e": 32066,
"s": 32026,
"text": "Addressing modes in 8085 microprocessor"
},
{
"code": null,
"e": 32103,
"s": 32066,
"text": "Flag register of 8086 microprocessor"
},
{
"code": null,
"e": 32142,
"s": 32103,
"text": "Programmable peripheral interface 8255"
},
{
"code": null,
"e": 32179,
"s": 32142,
"text": "Flag register in 8085 microprocessor"
},
{
"code": null,
"e": 32220,
"s": 32179,
"text": "IEEE Standard 754 Floating Point Numbers"
}
] |
Operators in C / C++ - GeeksforGeeks
|
23 Nov, 2021
Operators are the foundation of any programming language. We can define operators as symbols that help us to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. For example, ‘+’ is an operator used for addition, as shown below:
c = a + b;
Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’.
The functionality of the C/C++ programming language is incomplete without the use of operators.
C/C++ has many built-in operators and can be classified into 6 types:
Arithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsOther Operators
Arithmetic Operators
Relational Operators
Logical Operators
Bitwise Operators
Assignment Operators
Other Operators
The above operators have been discussed in detail:
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
1. Arithmetic Operators:
These operators are used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types:
a) Unary Operators: Operators that operate or work with a single operand are unary operators. For example: Increment(++) and Decrement(–) Operators
int val = 5;
++val; // 6
b) Binary Operators: Operators that operate or work with two operands are binary operators. For example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators
int a = 7;
int b = 2;
cout<<a+b; // 9
2. Relational Operators:
These are used for the comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not, etc. Some of the relational operators are (==, >= , <= )(See this article for more reference).
int a = 3;
int b = 5;
a < b;
// operator to check if a is smaller than b
3. Logical Operators:
Logical Operators are used to combining two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a Boolean value either true or false.
For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns true when both a and b are true (i.e. non-zero)(See this article for more reference).
(4 != 5) && (4 < 5); // true
4. Bitwise Operators:
The Bitwise operators are used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication, etc. can be performed at bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. (See this article for more reference).
int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)
cout << (a ^ b); // 00001100
cout <<(~a); // 11111010
5. Assignment Operators:
Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise an error.
Different types of assignment operators are shown below: a. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. For example:
a = 10;
b = 20;
ch = 'y';
b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. For example:
(a += b) can be written as (a = a + b)
If initially value stored in a is 5. Then (a += 6) = 11.
c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. For example:
(a -= b) can be written as (a = a - b)
If initially value stored in a is 8. Then (a -= 6) = 2.
d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. For example:
(a *= b) can be written as (a = a * b)
If initially, the value stored in a is 5. Then (a *= 6) = 30.
e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. For example:
(a /= b) can be written as (a = a / b)
If initially, the value stored in a is 6. Then (a /= 2) = 3.
6. Other Operators:
Apart from the above operators, there are some other operators available in C or C++ used to perform some specific tasks. Some of them are discussed here:
a. sizeof operator:
sizeof is much used in the C/C++ programming language.
It is a compile-time unary operator which can be used to compute the size of its operand.
The result of sizeof is of the unsigned integral type which is usually denoted by size_t.
Basically, the sizeof the operator is used to compute the size of the variable.(See this article for reference)
b. Comma Operator:
The comma operator (represented by the token) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type).
The comma operator has the lowest precedence of any C operator.
Comma acts as both operator and separator. (See this article for reference)
c. Conditional Operator:
The conditional operator is of the form Expression1? Expression2: Expression3.
Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3.
We may replace the use of if..else statements with conditional operators. (See this article for reference)
The below table describes the precedence order and associativity of operators in C / C++. The precedence of the operator decreases from top to bottom.
YouTube<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=WFy9SFJsAWQ" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
cuntgr1ll
Suyog_Sarda
Srinivas Nekkanti
12hb98
gabaa406
pujasingg43
anshikajain26
C Basics
CBSE - Class 11
CPP-Basics
school-programming
C Language
C++
Mathematical
School Programming
Mathematical
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Substring in C++
Converting Strings to Numbers in C/C++
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Virtual Function in C++
|
[
{
"code": null,
"e": 28283,
"s": 28255,
"text": "\n23 Nov, 2021"
},
{
"code": null,
"e": 28596,
"s": 28283,
"text": "Operators are the foundation of any programming language. We can define operators as symbols that help us to perform specific mathematical and logical computations on operands. In other words, we can say that an operator operates the operands. For example, ‘+’ is an operator used for addition, as shown below: "
},
{
"code": null,
"e": 28607,
"s": 28596,
"text": "c = a + b;"
},
{
"code": null,
"e": 28777,
"s": 28607,
"text": "Here, ‘+’ is the operator known as the addition operator and ‘a’ and ‘b’ are operands. The addition operator tells the compiler to add both of the operands ‘a’ and ‘b’. "
},
{
"code": null,
"e": 28873,
"s": 28777,
"text": "The functionality of the C/C++ programming language is incomplete without the use of operators."
},
{
"code": null,
"e": 28943,
"s": 28873,
"text": "C/C++ has many built-in operators and can be classified into 6 types:"
},
{
"code": null,
"e": 29053,
"s": 28943,
"text": "Arithmetic OperatorsRelational OperatorsLogical OperatorsBitwise OperatorsAssignment OperatorsOther Operators"
},
{
"code": null,
"e": 29074,
"s": 29053,
"text": "Arithmetic Operators"
},
{
"code": null,
"e": 29095,
"s": 29074,
"text": "Relational Operators"
},
{
"code": null,
"e": 29113,
"s": 29095,
"text": "Logical Operators"
},
{
"code": null,
"e": 29131,
"s": 29113,
"text": "Bitwise Operators"
},
{
"code": null,
"e": 29152,
"s": 29131,
"text": "Assignment Operators"
},
{
"code": null,
"e": 29168,
"s": 29152,
"text": "Other Operators"
},
{
"code": null,
"e": 29220,
"s": 29168,
"text": "The above operators have been discussed in detail: "
},
{
"code": null,
"e": 29229,
"s": 29220,
"text": "Chapters"
},
{
"code": null,
"e": 29256,
"s": 29229,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 29306,
"s": 29256,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 29329,
"s": 29306,
"text": "captions off, selected"
},
{
"code": null,
"e": 29337,
"s": 29329,
"text": "English"
},
{
"code": null,
"e": 29361,
"s": 29337,
"text": "This is a modal window."
},
{
"code": null,
"e": 29430,
"s": 29361,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 29452,
"s": 29430,
"text": "End of dialog window."
},
{
"code": null,
"e": 29478,
"s": 29452,
"text": "1. Arithmetic Operators: "
},
{
"code": null,
"e": 29634,
"s": 29478,
"text": "These operators are used to perform arithmetic/mathematical operations on operands. Examples: (+, -, *, /, %,++,–). Arithmetic operators are of two types: "
},
{
"code": null,
"e": 29782,
"s": 29634,
"text": "a) Unary Operators: Operators that operate or work with a single operand are unary operators. For example: Increment(++) and Decrement(–) Operators"
},
{
"code": null,
"e": 29808,
"s": 29782,
"text": "int val = 5;\n++val; // 6"
},
{
"code": null,
"e": 29983,
"s": 29808,
"text": "b) Binary Operators: Operators that operate or work with two operands are binary operators. For example: Addition(+), Subtraction(-), multiplication(*), Division(/) operators"
},
{
"code": null,
"e": 30021,
"s": 29983,
"text": "int a = 7;\nint b = 2;\ncout<<a+b; // 9"
},
{
"code": null,
"e": 30046,
"s": 30021,
"text": "2. Relational Operators:"
},
{
"code": null,
"e": 30334,
"s": 30046,
"text": "These are used for the comparison of the values of two operands. For example, checking if one operand is equal to the other operand or not, an operand is greater than the other operand or not, etc. Some of the relational operators are (==, >= , <= )(See this article for more reference)."
},
{
"code": null,
"e": 30407,
"s": 30334,
"text": "int a = 3;\nint b = 5;\na < b;\n// operator to check if a is smaller than b"
},
{
"code": null,
"e": 30429,
"s": 30407,
"text": "3. Logical Operators:"
},
{
"code": null,
"e": 30672,
"s": 30429,
"text": "Logical Operators are used to combining two or more conditions/constraints or to complement the evaluation of the original condition in consideration. The result of the operation of a logical operator is a Boolean value either true or false. "
},
{
"code": null,
"e": 30956,
"s": 30672,
"text": "For example, the logical AND represented as ‘&&’ operator in C or C++ returns true when both the conditions under consideration are satisfied. Otherwise, it returns false. Therefore, a && b returns true when both a and b are true (i.e. non-zero)(See this article for more reference)."
},
{
"code": null,
"e": 30989,
"s": 30956,
"text": "(4 != 5) && (4 < 5); // true"
},
{
"code": null,
"e": 31012,
"s": 30989,
"text": "4. Bitwise Operators: "
},
{
"code": null,
"e": 31553,
"s": 31012,
"text": "The Bitwise operators are used to perform bit-level operations on the operands. The operators are first converted to bit-level and then the calculation is performed on the operands. The mathematical operations such as addition, subtraction, multiplication, etc. can be performed at bit-level for faster processing. For example, the bitwise AND represented as & operator in C or C++ takes two numbers as operands and does AND on every bit of two numbers. The result of AND is 1 only if both bits are 1. (See this article for more reference)."
},
{
"code": null,
"e": 31672,
"s": 31553,
"text": "int a = 5, b = 9; // a = 5(00000101), b = 9(00001001)\ncout << (a ^ b); // 00001100\ncout <<(~a); // 11111010"
},
{
"code": null,
"e": 31698,
"s": 31672,
"text": "5. Assignment Operators: "
},
{
"code": null,
"e": 32027,
"s": 31698,
"text": "Assignment operators are used to assigning value to a variable. The left side operand of the assignment operator is a variable and the right side operand of the assignment operator is a value. The value on the right side must be of the same data type as the variable on the left side otherwise the compiler will raise an error. "
},
{
"code": null,
"e": 32232,
"s": 32027,
"text": "Different types of assignment operators are shown below: a. “=”: This is the simplest assignment operator. This operator is used to assign the value on the right to the variable on the left. For example: "
},
{
"code": null,
"e": 32258,
"s": 32232,
"text": "a = 10;\nb = 20;\nch = 'y';"
},
{
"code": null,
"e": 32485,
"s": 32258,
"text": "b. “+=”: This operator is combination of ‘+’ and ‘=’ operators. This operator first adds the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. For example:"
},
{
"code": null,
"e": 32581,
"s": 32485,
"text": "(a += b) can be written as (a = a + b)\nIf initially value stored in a is 5. Then (a += 6) = 11."
},
{
"code": null,
"e": 32818,
"s": 32581,
"text": "c. “-=”: This operator is a combination of ‘-‘ and ‘=’ operators. This operator first subtracts the value on the right from the current value of the variable on left and then assigns the result to the variable on the left. For example: "
},
{
"code": null,
"e": 32913,
"s": 32818,
"text": "(a -= b) can be written as (a = a - b)\nIf initially value stored in a is 8. Then (a -= 6) = 2."
},
{
"code": null,
"e": 33149,
"s": 32913,
"text": "d. “*=”: This operator is a combination of ‘*’ and ‘=’ operators. This operator first multiplies the current value of the variable on left to the value on the right and then assigns the result to the variable on the left. For example: "
},
{
"code": null,
"e": 33250,
"s": 33149,
"text": "(a *= b) can be written as (a = a * b)\nIf initially, the value stored in a is 5. Then (a *= 6) = 30."
},
{
"code": null,
"e": 33482,
"s": 33250,
"text": "e. “/=”: This operator is a combination of ‘/’ and ‘=’ operators. This operator first divides the current value of the variable on left by the value on the right and then assigns the result to the variable on the left. For example:"
},
{
"code": null,
"e": 33582,
"s": 33482,
"text": "(a /= b) can be written as (a = a / b)\nIf initially, the value stored in a is 6. Then (a /= 2) = 3."
},
{
"code": null,
"e": 33603,
"s": 33582,
"text": "6. Other Operators: "
},
{
"code": null,
"e": 33759,
"s": 33603,
"text": "Apart from the above operators, there are some other operators available in C or C++ used to perform some specific tasks. Some of them are discussed here: "
},
{
"code": null,
"e": 33780,
"s": 33759,
"text": "a. sizeof operator: "
},
{
"code": null,
"e": 33835,
"s": 33780,
"text": "sizeof is much used in the C/C++ programming language."
},
{
"code": null,
"e": 33925,
"s": 33835,
"text": "It is a compile-time unary operator which can be used to compute the size of its operand."
},
{
"code": null,
"e": 34015,
"s": 33925,
"text": "The result of sizeof is of the unsigned integral type which is usually denoted by size_t."
},
{
"code": null,
"e": 34127,
"s": 34015,
"text": "Basically, the sizeof the operator is used to compute the size of the variable.(See this article for reference)"
},
{
"code": null,
"e": 34147,
"s": 34127,
"text": "b. Comma Operator: "
},
{
"code": null,
"e": 34344,
"s": 34147,
"text": "The comma operator (represented by the token) is a binary operator that evaluates its first operand and discards the result, it then evaluates the second operand and returns this value (and type)."
},
{
"code": null,
"e": 34408,
"s": 34344,
"text": "The comma operator has the lowest precedence of any C operator."
},
{
"code": null,
"e": 34484,
"s": 34408,
"text": "Comma acts as both operator and separator. (See this article for reference)"
},
{
"code": null,
"e": 34510,
"s": 34484,
"text": "c. Conditional Operator: "
},
{
"code": null,
"e": 34589,
"s": 34510,
"text": "The conditional operator is of the form Expression1? Expression2: Expression3."
},
{
"code": null,
"e": 34845,
"s": 34589,
"text": "Here, Expression1 is the condition to be evaluated. If the condition(Expression1) is True then we will execute and return the result of Expression2 otherwise if the condition(Expression1) is false then we will execute and return the result of Expression3."
},
{
"code": null,
"e": 34952,
"s": 34845,
"text": "We may replace the use of if..else statements with conditional operators. (See this article for reference)"
},
{
"code": null,
"e": 35105,
"s": 34952,
"text": "The below table describes the precedence order and associativity of operators in C / C++. The precedence of the operator decreases from top to bottom. "
},
{
"code": null,
"e": 35397,
"s": 35105,
"text": "YouTube<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=WFy9SFJsAWQ\" 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": 35522,
"s": 35397,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 35532,
"s": 35522,
"text": "cuntgr1ll"
},
{
"code": null,
"e": 35544,
"s": 35532,
"text": "Suyog_Sarda"
},
{
"code": null,
"e": 35562,
"s": 35544,
"text": "Srinivas Nekkanti"
},
{
"code": null,
"e": 35569,
"s": 35562,
"text": "12hb98"
},
{
"code": null,
"e": 35578,
"s": 35569,
"text": "gabaa406"
},
{
"code": null,
"e": 35590,
"s": 35578,
"text": "pujasingg43"
},
{
"code": null,
"e": 35604,
"s": 35590,
"text": "anshikajain26"
},
{
"code": null,
"e": 35613,
"s": 35604,
"text": "C Basics"
},
{
"code": null,
"e": 35629,
"s": 35613,
"text": "CBSE - Class 11"
},
{
"code": null,
"e": 35640,
"s": 35629,
"text": "CPP-Basics"
},
{
"code": null,
"e": 35659,
"s": 35640,
"text": "school-programming"
},
{
"code": null,
"e": 35670,
"s": 35659,
"text": "C Language"
},
{
"code": null,
"e": 35674,
"s": 35670,
"text": "C++"
},
{
"code": null,
"e": 35687,
"s": 35674,
"text": "Mathematical"
},
{
"code": null,
"e": 35706,
"s": 35687,
"text": "School Programming"
},
{
"code": null,
"e": 35719,
"s": 35706,
"text": "Mathematical"
},
{
"code": null,
"e": 35723,
"s": 35719,
"text": "CPP"
},
{
"code": null,
"e": 35821,
"s": 35723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35899,
"s": 35821,
"text": "Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()"
},
{
"code": null,
"e": 35922,
"s": 35899,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 35949,
"s": 35922,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 35966,
"s": 35949,
"text": "Substring in C++"
},
{
"code": null,
"e": 36005,
"s": 35966,
"text": "Converting Strings to Numbers in C/C++"
},
{
"code": null,
"e": 36023,
"s": 36005,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 36069,
"s": 36023,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 36092,
"s": 36069,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 36119,
"s": 36092,
"text": "Bitwise Operators in C/C++"
}
] |
Python program to print all positive numbers in a range - GeeksforGeeks
|
26 Oct, 2018
Given start and end of a range, write a Python program to print all positive numbers in given range.
Example:
Input: start = -4, end = 5
Output: 0, 1, 2, 3, 4, 5
Input: start = -3, end = 4
Output: 0, 1, 2, 3, 4
Example #1: Print all positive numbers from given list using for loop
Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num is greater than or equeal to 0. If the condition satisfies, then only print the number.
# Python program to print positive Numbers in given range start, end = -4, 19 # iterating each number in listfor num in range(start, end + 1): # checking condition if num >= 0: print(num, end = " ")
Output:
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Example #2: Taking range limit from user input
# Python program to print positive Numbers in given range start = int(input("Enter the start of range: "))end = int(input("Enter the end of range: ")) # iterating each number in listfor num in range(start, end + 1): # checking condition if num >= 0: print(num, end = " ")
Output:
Enter the start of range: -215
Enter the end of range: 5
0 1 2 3 4 5
Python list-programs
python-list
Python
Python Programs
School Programming
python-list
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25561,
"s": 25533,
"text": "\n26 Oct, 2018"
},
{
"code": null,
"e": 25662,
"s": 25561,
"text": "Given start and end of a range, write a Python program to print all positive numbers in given range."
},
{
"code": null,
"e": 25671,
"s": 25662,
"text": "Example:"
},
{
"code": null,
"e": 25774,
"s": 25671,
"text": "Input: start = -4, end = 5\nOutput: 0, 1, 2, 3, 4, 5 \n\nInput: start = -3, end = 4\nOutput: 0, 1, 2, 3, 4"
},
{
"code": null,
"e": 25844,
"s": 25774,
"text": "Example #1: Print all positive numbers from given list using for loop"
},
{
"code": null,
"e": 26047,
"s": 25844,
"text": "Define start and end limit of range. Iterate from start till the range in the list using for loop and check if num is greater than or equeal to 0. If the condition satisfies, then only print the number."
},
{
"code": "# Python program to print positive Numbers in given range start, end = -4, 19 # iterating each number in listfor num in range(start, end + 1): # checking condition if num >= 0: print(num, end = \" \")",
"e": 26267,
"s": 26047,
"text": null
},
{
"code": null,
"e": 26275,
"s": 26267,
"text": "Output:"
},
{
"code": null,
"e": 26326,
"s": 26275,
"text": "0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 "
},
{
"code": null,
"e": 26374,
"s": 26326,
"text": " Example #2: Taking range limit from user input"
},
{
"code": "# Python program to print positive Numbers in given range start = int(input(\"Enter the start of range: \"))end = int(input(\"Enter the end of range: \")) # iterating each number in listfor num in range(start, end + 1): # checking condition if num >= 0: print(num, end = \" \")",
"e": 26667,
"s": 26374,
"text": null
},
{
"code": null,
"e": 26675,
"s": 26667,
"text": "Output:"
},
{
"code": null,
"e": 26745,
"s": 26675,
"text": "Enter the start of range: -215\nEnter the end of range: 5\n0 1 2 3 4 5 "
},
{
"code": null,
"e": 26766,
"s": 26745,
"text": "Python list-programs"
},
{
"code": null,
"e": 26778,
"s": 26766,
"text": "python-list"
},
{
"code": null,
"e": 26785,
"s": 26778,
"text": "Python"
},
{
"code": null,
"e": 26801,
"s": 26785,
"text": "Python Programs"
},
{
"code": null,
"e": 26820,
"s": 26801,
"text": "School Programming"
},
{
"code": null,
"e": 26832,
"s": 26820,
"text": "python-list"
},
{
"code": null,
"e": 26930,
"s": 26832,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26962,
"s": 26930,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27004,
"s": 26962,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27046,
"s": 27004,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27073,
"s": 27046,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27129,
"s": 27073,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27151,
"s": 27129,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27190,
"s": 27151,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27236,
"s": 27190,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27274,
"s": 27236,
"text": "Python | Convert a list to dictionary"
}
] |
Python Program to Reverse the Content of a File using Stack - GeeksforGeeks
|
04 Feb, 2022
Given a file, the task is to print as well as store the lines of that file in reverse order using Stack.Examples:
Input :
I am
new to this
world of
Python.
Output :
Python.
world of
new to this
I am
Input :
1
2
3
4
5
Output :
5
4
3
2
1
Approach:
Create an empty stack.
One by one push every line of the file to the stack.
One by one pop each line from the stack and put them back to the file.
Below is the implementation.Input File:
Python3
# Python3 code to reverse the lines# of a file using Stack. # Creating Stack class (LIFO rule)class Stack: def __init__(self): # Creating an empty stack self._arr = [] # Creating push() method. def push(self, val): self._arr.append(val) def is_empty(self): # Returns True if empty return len(self._arr) == 0 # Creating Pop method. def pop(self): if self.is_empty(): print("Stack is empty") return return self._arr.pop() # Creating a function which will reverse# the lines of a file and Overwrites the# given file with its contents line-by-line# reverseddef reverse_file(filename): S = Stack() original = open(filename) for line in original: S.push(line.rstrip("\n")) original.close() output = open(filename, 'w') while not S.is_empty(): output.write(S.pop()+"\n") output.close() # Driver Codefilename = "GFG.txt" # Calling the reverse_file functionreverse_file(filename) # Now reading the content of the filewith open(filename) as file: for f in file.readlines(): print(f, end ="")
Output:
This is a World of Geeks.
Welcome to GeeksforGeeks.
gulshankumarar231
Python DSA-exercises
Python file-handling-programs
python-file-handling
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python?
|
[
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n04 Feb, 2022"
},
{
"code": null,
"e": 25678,
"s": 25562,
"text": "Given a file, the task is to print as well as store the lines of that file in reverse order using Stack.Examples: "
},
{
"code": null,
"e": 25803,
"s": 25678,
"text": "Input :\nI am\nnew to this\nworld of\nPython.\n\nOutput :\nPython.\nworld of\nnew to this\nI am\n\n\nInput :\n1\n2\n3\n4\n5\nOutput :\n5\n4\n3\n2\n1"
},
{
"code": null,
"e": 25815,
"s": 25803,
"text": "Approach: "
},
{
"code": null,
"e": 25840,
"s": 25815,
"text": "Create an empty stack. "
},
{
"code": null,
"e": 25895,
"s": 25840,
"text": "One by one push every line of the file to the stack. "
},
{
"code": null,
"e": 25968,
"s": 25895,
"text": "One by one pop each line from the stack and put them back to the file. "
},
{
"code": null,
"e": 26009,
"s": 25968,
"text": "Below is the implementation.Input File: "
},
{
"code": null,
"e": 26019,
"s": 26011,
"text": "Python3"
},
{
"code": "# Python3 code to reverse the lines# of a file using Stack. # Creating Stack class (LIFO rule)class Stack: def __init__(self): # Creating an empty stack self._arr = [] # Creating push() method. def push(self, val): self._arr.append(val) def is_empty(self): # Returns True if empty return len(self._arr) == 0 # Creating Pop method. def pop(self): if self.is_empty(): print(\"Stack is empty\") return return self._arr.pop() # Creating a function which will reverse# the lines of a file and Overwrites the# given file with its contents line-by-line# reverseddef reverse_file(filename): S = Stack() original = open(filename) for line in original: S.push(line.rstrip(\"\\n\")) original.close() output = open(filename, 'w') while not S.is_empty(): output.write(S.pop()+\"\\n\") output.close() # Driver Codefilename = \"GFG.txt\" # Calling the reverse_file functionreverse_file(filename) # Now reading the content of the filewith open(filename) as file: for f in file.readlines(): print(f, end =\"\")",
"e": 27242,
"s": 26019,
"text": null
},
{
"code": null,
"e": 27251,
"s": 27242,
"text": "Output: "
},
{
"code": null,
"e": 27303,
"s": 27251,
"text": "This is a World of Geeks.\nWelcome to GeeksforGeeks."
},
{
"code": null,
"e": 27325,
"s": 27307,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 27346,
"s": 27325,
"text": "Python DSA-exercises"
},
{
"code": null,
"e": 27376,
"s": 27346,
"text": "Python file-handling-programs"
},
{
"code": null,
"e": 27397,
"s": 27376,
"text": "python-file-handling"
},
{
"code": null,
"e": 27404,
"s": 27397,
"text": "Python"
},
{
"code": null,
"e": 27420,
"s": 27404,
"text": "Python Programs"
},
{
"code": null,
"e": 27518,
"s": 27420,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27550,
"s": 27518,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27592,
"s": 27550,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27634,
"s": 27592,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27690,
"s": 27634,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27717,
"s": 27690,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27739,
"s": 27717,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27778,
"s": 27739,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27824,
"s": 27778,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27862,
"s": 27824,
"text": "Python | Convert a list to dictionary"
}
] |
Perl | Boolean Values - GeeksforGeeks
|
21 Aug, 2021
In most of the programming language True and False are considered as the boolean values. But Perl does not provide the type boolean for True and False. In general, a programmer can use the term “boolean” when a function returns either True or False. Like conditional statements(if, while, etc.) will return either true or false for the scalar values.
Example:
Perl
# Perl Code to demonstrate the boolean values # variable assigned value 0$k = 0; # checking whether k is true or falseif ($k){ print "k is True\n";}else{ print "k is False\n";} # variable assigned value 2$m = 2; # checking whether m is true or falseif ($m){ print "m is True\n";}else{ print "m is False\n";}
Output:
k is False
m is True
True Values: Any non-zero number i.e. except zero are True values in the Perl language. String constants like ‘true’, ‘false’, ‘ ‘(string having space as the character), ’00’(2 or more 0 characters) and “0\n”(a zero followed by a newline character in string) etc. also consider true values in Perl.
Example:
Perl
# Perl Code to demonstrate the True values # variable assigned value 5$a = 5; # checking whether a is true or falseif ($a){ print "a is True\n";}else{ print "a is False\n";} # string variable assigned white# space character$b = ' '; # checking whether b is true or falseif ($b){ print "b is True\n";}else{ print "b is False\n";} # string variable assigned 'false'# value to it$c = 'false'; # checking whether c is true or falseif ($c){ print "c is True\n";}else{ print "c is False\n";} # string variable assigned "0\n"# value to it$d = "0\n"; # checking whether d is true or falseif ($d){ print "d is True\n";}else{ print "d is False\n";}
Output:
a is True
b is True
c is True
d is True
False Values: Empty string or string contains single digit 0 or undef value and zero are considered as the false values in perl.
Example:
Perl
# Perl Code to demonstrate the False values # variable assigned value 0$a = 0; # checking whether a is true or falseif ($a){ print "a is True\n";}else{ print "a is False\n";} # string variable assigned empty string$b = ''; # checking whether b is true or falseif ($b){ print "b is True\n";}else{ print "b is False\n";} # string variable assigned undef$c = undef; # checking whether c is true or falseif ($c){ print "c is True\n";}else{ print "c is False\n";} # string variable assigned ""# value to it$d = ""; # checking whether d is true or falseif ($d){ print "d is True\n";}else{ print "d is False\n";}
Output:
a is False
b is False
c is False
d is False
Note: For the conditional check where the user has to compare two different variables, if they are not equal it returns False otherwise True.
Example:
Perl
# Perl Program demonstrate the conditional check # variable initialized with string$x = "GFG"; # using if statementif ($x eq "GFG"){ print "Return True\n";}else{ print "Return False\n";}
Output:
Return True
Aman Khare 1
gulshankumarar231
perl-basics
perl-data-types
Perl
Perl
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Perl | split() Function
Perl | push() Function
Perl | chomp() Function
Perl | grep() Function
Perl | substr() function
Perl | exists() Function
Perl | Removing leading and trailing white spaces (trim)
Perl Tutorial - Learn Perl With Examples
Use of print() and say() in Perl
Perl | length() Function
|
[
{
"code": null,
"e": 26551,
"s": 26523,
"text": "\n21 Aug, 2021"
},
{
"code": null,
"e": 26902,
"s": 26551,
"text": "In most of the programming language True and False are considered as the boolean values. But Perl does not provide the type boolean for True and False. In general, a programmer can use the term “boolean” when a function returns either True or False. Like conditional statements(if, while, etc.) will return either true or false for the scalar values."
},
{
"code": null,
"e": 26911,
"s": 26902,
"text": "Example:"
},
{
"code": null,
"e": 26916,
"s": 26911,
"text": "Perl"
},
{
"code": "# Perl Code to demonstrate the boolean values # variable assigned value 0$k = 0; # checking whether k is true or falseif ($k){ print \"k is True\\n\";}else{ print \"k is False\\n\";} # variable assigned value 2$m = 2; # checking whether m is true or falseif ($m){ print \"m is True\\n\";}else{ print \"m is False\\n\";}",
"e": 27236,
"s": 26916,
"text": null
},
{
"code": null,
"e": 27245,
"s": 27236,
"text": "Output: "
},
{
"code": null,
"e": 27266,
"s": 27245,
"text": "k is False\nm is True"
},
{
"code": null,
"e": 27565,
"s": 27266,
"text": "True Values: Any non-zero number i.e. except zero are True values in the Perl language. String constants like ‘true’, ‘false’, ‘ ‘(string having space as the character), ’00’(2 or more 0 characters) and “0\\n”(a zero followed by a newline character in string) etc. also consider true values in Perl."
},
{
"code": null,
"e": 27575,
"s": 27565,
"text": "Example: "
},
{
"code": null,
"e": 27580,
"s": 27575,
"text": "Perl"
},
{
"code": "# Perl Code to demonstrate the True values # variable assigned value 5$a = 5; # checking whether a is true or falseif ($a){ print \"a is True\\n\";}else{ print \"a is False\\n\";} # string variable assigned white# space character$b = ' '; # checking whether b is true or falseif ($b){ print \"b is True\\n\";}else{ print \"b is False\\n\";} # string variable assigned 'false'# value to it$c = 'false'; # checking whether c is true or falseif ($c){ print \"c is True\\n\";}else{ print \"c is False\\n\";} # string variable assigned \"0\\n\"# value to it$d = \"0\\n\"; # checking whether d is true or falseif ($d){ print \"d is True\\n\";}else{ print \"d is False\\n\";}",
"e": 28243,
"s": 27580,
"text": null
},
{
"code": null,
"e": 28252,
"s": 28243,
"text": "Output: "
},
{
"code": null,
"e": 28292,
"s": 28252,
"text": "a is True\nb is True\nc is True\nd is True"
},
{
"code": null,
"e": 28421,
"s": 28292,
"text": "False Values: Empty string or string contains single digit 0 or undef value and zero are considered as the false values in perl."
},
{
"code": null,
"e": 28431,
"s": 28421,
"text": "Example: "
},
{
"code": null,
"e": 28436,
"s": 28431,
"text": "Perl"
},
{
"code": "# Perl Code to demonstrate the False values # variable assigned value 0$a = 0; # checking whether a is true or falseif ($a){ print \"a is True\\n\";}else{ print \"a is False\\n\";} # string variable assigned empty string$b = ''; # checking whether b is true or falseif ($b){ print \"b is True\\n\";}else{ print \"b is False\\n\";} # string variable assigned undef$c = undef; # checking whether c is true or falseif ($c){ print \"c is True\\n\";}else{ print \"c is False\\n\";} # string variable assigned \"\"# value to it$d = \"\"; # checking whether d is true or falseif ($d){ print \"d is True\\n\";}else{ print \"d is False\\n\";}",
"e": 29066,
"s": 28436,
"text": null
},
{
"code": null,
"e": 29075,
"s": 29066,
"text": "Output: "
},
{
"code": null,
"e": 29119,
"s": 29075,
"text": "a is False\nb is False\nc is False\nd is False"
},
{
"code": null,
"e": 29261,
"s": 29119,
"text": "Note: For the conditional check where the user has to compare two different variables, if they are not equal it returns False otherwise True."
},
{
"code": null,
"e": 29271,
"s": 29261,
"text": "Example: "
},
{
"code": null,
"e": 29276,
"s": 29271,
"text": "Perl"
},
{
"code": "# Perl Program demonstrate the conditional check # variable initialized with string$x = \"GFG\"; # using if statementif ($x eq \"GFG\"){ print \"Return True\\n\";}else{ print \"Return False\\n\";}",
"e": 29469,
"s": 29276,
"text": null
},
{
"code": null,
"e": 29478,
"s": 29469,
"text": "Output: "
},
{
"code": null,
"e": 29490,
"s": 29478,
"text": "Return True"
},
{
"code": null,
"e": 29505,
"s": 29492,
"text": "Aman Khare 1"
},
{
"code": null,
"e": 29523,
"s": 29505,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 29535,
"s": 29523,
"text": "perl-basics"
},
{
"code": null,
"e": 29551,
"s": 29535,
"text": "perl-data-types"
},
{
"code": null,
"e": 29556,
"s": 29551,
"text": "Perl"
},
{
"code": null,
"e": 29561,
"s": 29556,
"text": "Perl"
},
{
"code": null,
"e": 29659,
"s": 29561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29683,
"s": 29659,
"text": "Perl | split() Function"
},
{
"code": null,
"e": 29706,
"s": 29683,
"text": "Perl | push() Function"
},
{
"code": null,
"e": 29730,
"s": 29706,
"text": "Perl | chomp() Function"
},
{
"code": null,
"e": 29753,
"s": 29730,
"text": "Perl | grep() Function"
},
{
"code": null,
"e": 29778,
"s": 29753,
"text": "Perl | substr() function"
},
{
"code": null,
"e": 29803,
"s": 29778,
"text": "Perl | exists() Function"
},
{
"code": null,
"e": 29860,
"s": 29803,
"text": "Perl | Removing leading and trailing white spaces (trim)"
},
{
"code": null,
"e": 29901,
"s": 29860,
"text": "Perl Tutorial - Learn Perl With Examples"
},
{
"code": null,
"e": 29934,
"s": 29901,
"text": "Use of print() and say() in Perl"
}
] |
Queries to find kth smallest element and point update : Ordered Set in C++ - GeeksforGeeks
|
14 Apr, 2020
Given an array arr[] of size N and a set Q[][] containing M queries, the task is to execute the queries on the given array such that there can be two types of queries:
Type 1: [i, x] – Update the element at ith index to x.
Type 2: [k] – Find the kth smallest element in the array.
Examples:
Input: arr[] = {4, 3, 6, 2}, Q[][] = {{1, 2, 5}, {2, 3}, {1, 1, 7}, {2, 1}}Output: 5 2Explanation:For the 1st query: arr[] = {4, 5, 6, 2}For the 2nd query: 3rd smallest element would be 5.For the 3rd query: arr[] = {7, 5, 6, 2}For the 4th query: 1st smallest element would be 2.
Input: arr[] = {1, 0, 4, 2, 0}, Q[][] = {{1, 2, 1}, {2, 2}, {1, 4, 5}, {1, 3, 7}, {2, 1}, {2, 5}}Output: 1 0 7
Naive Approach: The naive approach for this problem is to update the ith element in an array in constant time and use sorting to find the Kth smallest element.
Time Complexity: O(M * (N * log(N))) where M is the number of queries and N is the size of the array.
Efficient Approach: The idea is to use a policy-based data structure similar to a set.
Here, a tree based container is used to store the array in the form of a sorted tree such that all the nodes to the left are smaller than the root and all the nodes to the right are greater than the root. The following are the properties of the data structure:
It is indexed by maintaining node invariant where each node contains a count of nodes in its subtree.
Every time we insert a new node or delete a node, we can maintain the invariant in O(logN) time by bubbling up to the root.
So the count of the node in its left subtree gives the index of that node in sorted order because the value of every node of the left subtree is smaller than the parent node.
Therefore, the idea is to follow the following approach for each query:
Type 1: For this query, we update the ith element of the array. Therefore, we need to update the element both in the array and the data structure. In order to update the value in the tree container, the value arr[i] is found in the tree, deleted from the tree and the updated value is inserted back into the tree.Type 2: In order to find the Kth smallest element, find_by_order(K – 1) is used on the tree as the data is a sorted data. This is similar to Binary Search operation on the sorted array.
Type 1: For this query, we update the ith element of the array. Therefore, we need to update the element both in the array and the data structure. In order to update the value in the tree container, the value arr[i] is found in the tree, deleted from the tree and the updated value is inserted back into the tree.
Type 2: In order to find the Kth smallest element, find_by_order(K – 1) is used on the tree as the data is a sorted data. This is similar to Binary Search operation on the sorted array.
Below is the implementation of the above approach:
// C++ implementation of the above approach #include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace std;using namespace __gnu_pbds; // Defining the policy based Data Structuretypedef tree<pair<int, int>, null_type, less<pair<int, int> >, rb_tree_tag, tree_order_statistics_node_update> indexed_set; // Elements in the array are not unique,// so a pair is used to give uniqueness// by incrementing cnt and assigning// with array elements to insert in mySetint cnt = 0; // Variable to store the data in the// policy based Data Structureindexed_set mySet; // Function to insert the elements// of the array in mySetvoid insert(int n, int arr[]){ for (int i = 0; i < n; i++) { mySet.insert({ arr[i], cnt }); cnt++; }} // Function to update the value in// the data structurevoid update(int x, int y){ // Get the pointer of the element // in mySet which has to be updated auto it = mySet.lower_bound({ y, 0 }); // Delete from mySet mySet.erase(it); // Insert the updated value in mySet mySet.insert({ x, cnt }); cnt++;} // Function to find the K-th smallest// element in the setint get(int k){ // Find the pointer to the kth smallest element auto it = mySet.find_by_order(k - 1); return (it->first);} // Function to perform the queries on the setvoid operations(int arr[], int n, vector<vector<int> > query, int m){ // To insert the element in mySet insert(n, arr); // Iterating through the queries for (int i = 0; i < m; i++) { // Checking if the query is of type 1 // or type 2 if (query[i][0] == 1) { // The array is 0-indexed int j = query[i][1] - 1; int x = query[i][2]; // Update the element in mySet update(x, arr[j]); // Update the element in the array arr[j] = x; } else { int K = query[i][1]; // Print Kth smallest element cout << get(K) << endl; } }} // Driver codeint main(){ int n = 5, m = 6, arr[] = { 1, 0, 4, 2, 0 }; vector<vector<int> > query = { { 1, 2, 1 }, { 2, 2 }, { 1, 4, 5 }, { 1, 3, 7 }, { 2, 1 }, { 2, 5 } }; operations(arr, n, query, m); return 0;}
1
0
7
Time Complexity: Since every operation takes O(Log(N)) time and there are M queries, the overall time complexity is O(M * Log(N)).
array-range-queries
Advanced Data Structure
Competitive Programming
Tree
Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ordered Set and GNU C++ PBDS
2-3 Trees | (Search, Insert and Deletion)
Extendible Hashing (Dynamic approach to DBMS)
Suffix Array | Set 1 (Introduction)
Interval Tree
Competitive Programming - A Complete Guide
Practice for cracking any coding interview
Arrow operator -> in C/C++ with Examples
Prefix Sum Array - Implementation and Applications in Competitive Programming
Fast I/O for Competitive Programming
|
[
{
"code": null,
"e": 25731,
"s": 25703,
"text": "\n14 Apr, 2020"
},
{
"code": null,
"e": 25899,
"s": 25731,
"text": "Given an array arr[] of size N and a set Q[][] containing M queries, the task is to execute the queries on the given array such that there can be two types of queries:"
},
{
"code": null,
"e": 25954,
"s": 25899,
"text": "Type 1: [i, x] – Update the element at ith index to x."
},
{
"code": null,
"e": 26012,
"s": 25954,
"text": "Type 2: [k] – Find the kth smallest element in the array."
},
{
"code": null,
"e": 26022,
"s": 26012,
"text": "Examples:"
},
{
"code": null,
"e": 26301,
"s": 26022,
"text": "Input: arr[] = {4, 3, 6, 2}, Q[][] = {{1, 2, 5}, {2, 3}, {1, 1, 7}, {2, 1}}Output: 5 2Explanation:For the 1st query: arr[] = {4, 5, 6, 2}For the 2nd query: 3rd smallest element would be 5.For the 3rd query: arr[] = {7, 5, 6, 2}For the 4th query: 1st smallest element would be 2."
},
{
"code": null,
"e": 26412,
"s": 26301,
"text": "Input: arr[] = {1, 0, 4, 2, 0}, Q[][] = {{1, 2, 1}, {2, 2}, {1, 4, 5}, {1, 3, 7}, {2, 1}, {2, 5}}Output: 1 0 7"
},
{
"code": null,
"e": 26572,
"s": 26412,
"text": "Naive Approach: The naive approach for this problem is to update the ith element in an array in constant time and use sorting to find the Kth smallest element."
},
{
"code": null,
"e": 26674,
"s": 26572,
"text": "Time Complexity: O(M * (N * log(N))) where M is the number of queries and N is the size of the array."
},
{
"code": null,
"e": 26761,
"s": 26674,
"text": "Efficient Approach: The idea is to use a policy-based data structure similar to a set."
},
{
"code": null,
"e": 27022,
"s": 26761,
"text": "Here, a tree based container is used to store the array in the form of a sorted tree such that all the nodes to the left are smaller than the root and all the nodes to the right are greater than the root. The following are the properties of the data structure:"
},
{
"code": null,
"e": 27124,
"s": 27022,
"text": "It is indexed by maintaining node invariant where each node contains a count of nodes in its subtree."
},
{
"code": null,
"e": 27248,
"s": 27124,
"text": "Every time we insert a new node or delete a node, we can maintain the invariant in O(logN) time by bubbling up to the root."
},
{
"code": null,
"e": 27423,
"s": 27248,
"text": "So the count of the node in its left subtree gives the index of that node in sorted order because the value of every node of the left subtree is smaller than the parent node."
},
{
"code": null,
"e": 27495,
"s": 27423,
"text": "Therefore, the idea is to follow the following approach for each query:"
},
{
"code": null,
"e": 27994,
"s": 27495,
"text": "Type 1: For this query, we update the ith element of the array. Therefore, we need to update the element both in the array and the data structure. In order to update the value in the tree container, the value arr[i] is found in the tree, deleted from the tree and the updated value is inserted back into the tree.Type 2: In order to find the Kth smallest element, find_by_order(K – 1) is used on the tree as the data is a sorted data. This is similar to Binary Search operation on the sorted array."
},
{
"code": null,
"e": 28308,
"s": 27994,
"text": "Type 1: For this query, we update the ith element of the array. Therefore, we need to update the element both in the array and the data structure. In order to update the value in the tree container, the value arr[i] is found in the tree, deleted from the tree and the updated value is inserted back into the tree."
},
{
"code": null,
"e": 28494,
"s": 28308,
"text": "Type 2: In order to find the Kth smallest element, find_by_order(K – 1) is used on the tree as the data is a sorted data. This is similar to Binary Search operation on the sorted array."
},
{
"code": null,
"e": 28545,
"s": 28494,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// C++ implementation of the above approach #include <bits/stdc++.h>#include <ext/pb_ds/assoc_container.hpp>#include <ext/pb_ds/tree_policy.hpp>using namespace std;using namespace __gnu_pbds; // Defining the policy based Data Structuretypedef tree<pair<int, int>, null_type, less<pair<int, int> >, rb_tree_tag, tree_order_statistics_node_update> indexed_set; // Elements in the array are not unique,// so a pair is used to give uniqueness// by incrementing cnt and assigning// with array elements to insert in mySetint cnt = 0; // Variable to store the data in the// policy based Data Structureindexed_set mySet; // Function to insert the elements// of the array in mySetvoid insert(int n, int arr[]){ for (int i = 0; i < n; i++) { mySet.insert({ arr[i], cnt }); cnt++; }} // Function to update the value in// the data structurevoid update(int x, int y){ // Get the pointer of the element // in mySet which has to be updated auto it = mySet.lower_bound({ y, 0 }); // Delete from mySet mySet.erase(it); // Insert the updated value in mySet mySet.insert({ x, cnt }); cnt++;} // Function to find the K-th smallest// element in the setint get(int k){ // Find the pointer to the kth smallest element auto it = mySet.find_by_order(k - 1); return (it->first);} // Function to perform the queries on the setvoid operations(int arr[], int n, vector<vector<int> > query, int m){ // To insert the element in mySet insert(n, arr); // Iterating through the queries for (int i = 0; i < m; i++) { // Checking if the query is of type 1 // or type 2 if (query[i][0] == 1) { // The array is 0-indexed int j = query[i][1] - 1; int x = query[i][2]; // Update the element in mySet update(x, arr[j]); // Update the element in the array arr[j] = x; } else { int K = query[i][1]; // Print Kth smallest element cout << get(K) << endl; } }} // Driver codeint main(){ int n = 5, m = 6, arr[] = { 1, 0, 4, 2, 0 }; vector<vector<int> > query = { { 1, 2, 1 }, { 2, 2 }, { 1, 4, 5 }, { 1, 3, 7 }, { 2, 1 }, { 2, 5 } }; operations(arr, n, query, m); return 0;}",
"e": 31073,
"s": 28545,
"text": null
},
{
"code": null,
"e": 31080,
"s": 31073,
"text": "1\n0\n7\n"
},
{
"code": null,
"e": 31211,
"s": 31080,
"text": "Time Complexity: Since every operation takes O(Log(N)) time and there are M queries, the overall time complexity is O(M * Log(N))."
},
{
"code": null,
"e": 31231,
"s": 31211,
"text": "array-range-queries"
},
{
"code": null,
"e": 31255,
"s": 31231,
"text": "Advanced Data Structure"
},
{
"code": null,
"e": 31279,
"s": 31255,
"text": "Competitive Programming"
},
{
"code": null,
"e": 31284,
"s": 31279,
"text": "Tree"
},
{
"code": null,
"e": 31289,
"s": 31284,
"text": "Tree"
},
{
"code": null,
"e": 31387,
"s": 31289,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31416,
"s": 31387,
"text": "Ordered Set and GNU C++ PBDS"
},
{
"code": null,
"e": 31458,
"s": 31416,
"text": "2-3 Trees | (Search, Insert and Deletion)"
},
{
"code": null,
"e": 31504,
"s": 31458,
"text": "Extendible Hashing (Dynamic approach to DBMS)"
},
{
"code": null,
"e": 31540,
"s": 31504,
"text": "Suffix Array | Set 1 (Introduction)"
},
{
"code": null,
"e": 31554,
"s": 31540,
"text": "Interval Tree"
},
{
"code": null,
"e": 31597,
"s": 31554,
"text": "Competitive Programming - A Complete Guide"
},
{
"code": null,
"e": 31640,
"s": 31597,
"text": "Practice for cracking any coding interview"
},
{
"code": null,
"e": 31681,
"s": 31640,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 31759,
"s": 31681,
"text": "Prefix Sum Array - Implementation and Applications in Competitive Programming"
}
] |
Perfect Cubes in a Range | Practice | GeeksforGeeks
|
Given two given numbers a and b where 1<= a <= b, find the perfect cubes between a and b (a and b inclusive).
Example 1:
Input: a = 1, b = 100
Output: 1 8 27 64
Explaination: These are the proper cubes between
1 and 100.
Example 2:
Input: a = 24, b = 576
Output: 27 64 125 216 343 512
Explaination: These are the proper cubes between
24 and 576.
Your Task:
You do not need to read input or print anything. Your task is to complete the function properCubes() which takes a and b as input parameters and returns the proper cubes between a and b. The function returns -1 if there is no proper cube between the given values.
Expected Time Complexity: O(cuberoot(b))
Expected Auxiliary Space: O(1)
Constraints:
1 ≤ a ≤ b ≤ 104
0
Neeraj Kumar2 years ago
Neeraj Kumar
https://uploads.disquscdn.c...
Hii! This is my code, Solution in 0.01 seconds
0
Tokir Manva2 years ago
Tokir Manva
Execution Time:0.02Python3 code#codeimport mathfor _ in range(int(input())): a,b=map(int,input().split()) min=math.ceil((a**(1/3))) max=math.floor((b**(1/3))) if (math.floor((b**(1/3)))+1)**3 == b: max+=1 if min == max: print(min**3) elif min > max: print("No") else: for i in range(min,max+1): print(i**3,end=" ") print()
0
gunateja2 years ago
gunateja
t=int(input(""))while(t): a=[int(i) for i in input().split()] m=a[0] n=a[1] y=0 for i in range(1,n): k=pow(i,3) if(k>n): break if(k>=m): print(k,end=" ") y=1 if(y==0): print("No") else: print("\r") t-=1
Correct Answer.Correct AnswerExecution Time:0.02
0
Mahima Mahendru2 years ago
Mahima Mahendru
simple 0.01s solution c+ + ;)
https://ide.geeksforgeeks.o...
0
Chandra Shekhar Joshi
This comment was deleted.
0
Paras Jain2 years ago
Paras Jain
even my dev c++ giving correct output for input 78 541 and GFG is telling it wrong
please check my code :
//Perfect Cube#include<stdio.h>int main(){int t;scanf("%d",&t);while(t--){int a,b,i,c,count=0;scanf("%d%d",&a,&b);for(i=1;i<=b/3;i++){c=i*i*i;if(c>=a&&c<=b){printf("%d ",c);count=count+1;}}if(count==0){ printf("No\n");}printf("\n");}}
0
Akash3 years ago
Akash
https://ide.geeksforgeeks.o...why it is giving wrong output for input 78 541 while submitting?in other compiler it is giving correct output.
0
Pankaj Gupta3 years ago
Pankaj Gupta
it is the best soloution in python. Complexity=O(n)t=0.08 sec
t=int(input())for i in range(t): s,m=map(int,input().split()) c=0 for j in range(0,m//3): if (j**3>=s and j**3<=m): c=1 print(j**3,end=" ")
if c==0: print("No") else: print("\r")
0
Hodor
This comment was deleted.
0
shivani5 years ago
shivani
http://code.geeksforgeeks.o...what,s wrong in my code..???
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": 348,
"s": 238,
"text": "Given two given numbers a and b where 1<= a <= b, find the perfect cubes between a and b (a and b inclusive)."
},
{
"code": null,
"e": 359,
"s": 348,
"text": "Example 1:"
},
{
"code": null,
"e": 460,
"s": 359,
"text": "Input: a = 1, b = 100\nOutput: 1 8 27 64\nExplaination: These are the proper cubes between \n1 and 100."
},
{
"code": null,
"e": 471,
"s": 460,
"text": "Example 2:"
},
{
"code": null,
"e": 586,
"s": 471,
"text": "Input: a = 24, b = 576\nOutput: 27 64 125 216 343 512\nExplaination: These are the proper cubes between \n24 and 576."
},
{
"code": null,
"e": 861,
"s": 586,
"text": "Your Task:\nYou do not need to read input or print anything. Your task is to complete the function properCubes() which takes a and b as input parameters and returns the proper cubes between a and b. The function returns -1 if there is no proper cube between the given values."
},
{
"code": null,
"e": 933,
"s": 861,
"text": "Expected Time Complexity: O(cuberoot(b))\nExpected Auxiliary Space: O(1)"
},
{
"code": null,
"e": 963,
"s": 933,
"text": "Constraints:\n1 ≤ a ≤ b ≤ 104 "
},
{
"code": null,
"e": 965,
"s": 963,
"text": "0"
},
{
"code": null,
"e": 989,
"s": 965,
"text": "Neeraj Kumar2 years ago"
},
{
"code": null,
"e": 1002,
"s": 989,
"text": "Neeraj Kumar"
},
{
"code": null,
"e": 1033,
"s": 1002,
"text": "https://uploads.disquscdn.c..."
},
{
"code": null,
"e": 1080,
"s": 1033,
"text": "Hii! This is my code, Solution in 0.01 seconds"
},
{
"code": null,
"e": 1082,
"s": 1080,
"text": "0"
},
{
"code": null,
"e": 1105,
"s": 1082,
"text": "Tokir Manva2 years ago"
},
{
"code": null,
"e": 1117,
"s": 1105,
"text": "Tokir Manva"
},
{
"code": null,
"e": 1507,
"s": 1117,
"text": "Execution Time:0.02Python3 code#codeimport mathfor _ in range(int(input())): a,b=map(int,input().split()) min=math.ceil((a**(1/3))) max=math.floor((b**(1/3))) if (math.floor((b**(1/3)))+1)**3 == b: max+=1 if min == max: print(min**3) elif min > max: print(\"No\") else: for i in range(min,max+1): print(i**3,end=\" \") print()"
},
{
"code": null,
"e": 1509,
"s": 1507,
"text": "0"
},
{
"code": null,
"e": 1529,
"s": 1509,
"text": "gunateja2 years ago"
},
{
"code": null,
"e": 1538,
"s": 1529,
"text": "gunateja"
},
{
"code": null,
"e": 1833,
"s": 1538,
"text": "t=int(input(\"\"))while(t): a=[int(i) for i in input().split()] m=a[0] n=a[1] y=0 for i in range(1,n): k=pow(i,3) if(k>n): break if(k>=m): print(k,end=\" \") y=1 if(y==0): print(\"No\") else: print(\"\\r\") t-=1"
},
{
"code": null,
"e": 1882,
"s": 1833,
"text": "Correct Answer.Correct AnswerExecution Time:0.02"
},
{
"code": null,
"e": 1884,
"s": 1882,
"text": "0"
},
{
"code": null,
"e": 1911,
"s": 1884,
"text": "Mahima Mahendru2 years ago"
},
{
"code": null,
"e": 1927,
"s": 1911,
"text": "Mahima Mahendru"
},
{
"code": null,
"e": 1957,
"s": 1927,
"text": "simple 0.01s solution c+ + ;)"
},
{
"code": null,
"e": 1988,
"s": 1957,
"text": "https://ide.geeksforgeeks.o..."
},
{
"code": null,
"e": 1990,
"s": 1988,
"text": "0"
},
{
"code": null,
"e": 2012,
"s": 1990,
"text": "Chandra Shekhar Joshi"
},
{
"code": null,
"e": 2038,
"s": 2012,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2040,
"s": 2038,
"text": "0"
},
{
"code": null,
"e": 2062,
"s": 2040,
"text": "Paras Jain2 years ago"
},
{
"code": null,
"e": 2073,
"s": 2062,
"text": "Paras Jain"
},
{
"code": null,
"e": 2156,
"s": 2073,
"text": "even my dev c++ giving correct output for input 78 541 and GFG is telling it wrong"
},
{
"code": null,
"e": 2179,
"s": 2156,
"text": "please check my code :"
},
{
"code": null,
"e": 2417,
"s": 2179,
"text": "//Perfect Cube#include<stdio.h>int main(){int t;scanf(\"%d\",&t);while(t--){int a,b,i,c,count=0;scanf(\"%d%d\",&a,&b);for(i=1;i<=b/3;i++){c=i*i*i;if(c>=a&&c<=b){printf(\"%d \",c);count=count+1;}}if(count==0){ printf(\"No\\n\");}printf(\"\\n\");}}"
},
{
"code": null,
"e": 2419,
"s": 2417,
"text": "0"
},
{
"code": null,
"e": 2436,
"s": 2419,
"text": "Akash3 years ago"
},
{
"code": null,
"e": 2442,
"s": 2436,
"text": "Akash"
},
{
"code": null,
"e": 2583,
"s": 2442,
"text": "https://ide.geeksforgeeks.o...why it is giving wrong output for input 78 541 while submitting?in other compiler it is giving correct output."
},
{
"code": null,
"e": 2585,
"s": 2583,
"text": "0"
},
{
"code": null,
"e": 2609,
"s": 2585,
"text": "Pankaj Gupta3 years ago"
},
{
"code": null,
"e": 2622,
"s": 2609,
"text": "Pankaj Gupta"
},
{
"code": null,
"e": 2684,
"s": 2622,
"text": "it is the best soloution in python. Complexity=O(n)t=0.08 sec"
},
{
"code": null,
"e": 2862,
"s": 2684,
"text": "t=int(input())for i in range(t): s,m=map(int,input().split()) c=0 for j in range(0,m//3): if (j**3>=s and j**3<=m): c=1 print(j**3,end=\" \")"
},
{
"code": null,
"e": 2922,
"s": 2862,
"text": " if c==0: print(\"No\") else: print(\"\\r\")"
},
{
"code": null,
"e": 2924,
"s": 2922,
"text": "0"
},
{
"code": null,
"e": 2930,
"s": 2924,
"text": "Hodor"
},
{
"code": null,
"e": 2956,
"s": 2930,
"text": "This comment was deleted."
},
{
"code": null,
"e": 2958,
"s": 2956,
"text": "0"
},
{
"code": null,
"e": 2977,
"s": 2958,
"text": "shivani5 years ago"
},
{
"code": null,
"e": 2985,
"s": 2977,
"text": "shivani"
},
{
"code": null,
"e": 3044,
"s": 2985,
"text": "http://code.geeksforgeeks.o...what,s wrong in my code..???"
},
{
"code": null,
"e": 3190,
"s": 3044,
"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": 3226,
"s": 3190,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 3236,
"s": 3226,
"text": "\nProblem\n"
},
{
"code": null,
"e": 3246,
"s": 3236,
"text": "\nContest\n"
},
{
"code": null,
"e": 3309,
"s": 3246,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 3457,
"s": 3309,
"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": 3665,
"s": 3457,
"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": 3771,
"s": 3665,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Charset defaultCharset() method in Java with Examples - GeeksforGeeks
|
29 Mar, 2019
The defaultCharset() method is a built-in method of the java.nio.charset which returns the charset object for the default charset. The default charset is basically determined by the Java virtual machine and it basically depends on the charset which is in the underlying operating system of the machine. In short, the result will vary from machine to machine.
Syntax:
public static Charset defaultCharset()
Parameters: The function does not accepts any parameter.
Return Value: The function returns a charset object for the default charset.
Below is the implementation of the above function:
Program 1:
// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { // Get the default charset of the machine Charset cs = Charset.defaultCharset(); System.out.println("The default charset of the machine is :" + cs.displayName()); }}
The default charset of the machine is :US-ASCII
Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/Charset.html#defaultCharset()
Java-Charset
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
|
[
{
"code": null,
"e": 26293,
"s": 26265,
"text": "\n29 Mar, 2019"
},
{
"code": null,
"e": 26652,
"s": 26293,
"text": "The defaultCharset() method is a built-in method of the java.nio.charset which returns the charset object for the default charset. The default charset is basically determined by the Java virtual machine and it basically depends on the charset which is in the underlying operating system of the machine. In short, the result will vary from machine to machine."
},
{
"code": null,
"e": 26660,
"s": 26652,
"text": "Syntax:"
},
{
"code": null,
"e": 26699,
"s": 26660,
"text": "public static Charset defaultCharset()"
},
{
"code": null,
"e": 26756,
"s": 26699,
"text": "Parameters: The function does not accepts any parameter."
},
{
"code": null,
"e": 26833,
"s": 26756,
"text": "Return Value: The function returns a charset object for the default charset."
},
{
"code": null,
"e": 26884,
"s": 26833,
"text": "Below is the implementation of the above function:"
},
{
"code": null,
"e": 26895,
"s": 26884,
"text": "Program 1:"
},
{
"code": "// Java program to demonstrate// the above functionimport java.nio.charset.Charset;import java.util.Iterator;import java.util.Map; public class GFG { public static void main(String[] args) { // Get the default charset of the machine Charset cs = Charset.defaultCharset(); System.out.println(\"The default charset of the machine is :\" + cs.displayName()); }}",
"e": 27289,
"s": 26895,
"text": null
},
{
"code": null,
"e": 27338,
"s": 27289,
"text": "The default charset of the machine is :US-ASCII\n"
},
{
"code": null,
"e": 27439,
"s": 27338,
"text": "Reference: https://docs.oracle.com/javase/10/docs/api/java/nio/charset/Charset.html#defaultCharset()"
},
{
"code": null,
"e": 27452,
"s": 27439,
"text": "Java-Charset"
},
{
"code": null,
"e": 27467,
"s": 27452,
"text": "Java-Functions"
},
{
"code": null,
"e": 27484,
"s": 27467,
"text": "Java-NIO package"
},
{
"code": null,
"e": 27489,
"s": 27484,
"text": "Java"
},
{
"code": null,
"e": 27494,
"s": 27489,
"text": "Java"
},
{
"code": null,
"e": 27592,
"s": 27494,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27643,
"s": 27592,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27673,
"s": 27643,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27688,
"s": 27673,
"text": "Stream In Java"
},
{
"code": null,
"e": 27707,
"s": 27688,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27738,
"s": 27707,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27756,
"s": 27738,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27788,
"s": 27756,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27808,
"s": 27788,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27840,
"s": 27808,
"text": "Multidimensional Arrays in Java"
}
] |
Java Program to Create blank Excel Sheet - GeeksforGeeks
|
04 Mar, 2022
ApachePOI stands for poor obfuscation Implementation which is a Java API for reading and writing Microsoft documents. It contains classes and interfaces namely Wordbook, Sheet, Row, and Cell. Apache POI can be used to access ‘xlsx’ extension files and as well as ‘xlsx’ extension files
Concept: ApachePOI, jar files, and File methods are explained to a brim to show how they are connected and the procedural execution intercepting directories.
Step 1: To get the project ready to code. Once the package is created, still certain jar files are needed to access the Apache so do download the jar files before reading further. There are 4 jar files needed to access Excel using java or simply import all jar files of ‘usermodel’ during the java project creation.
Step 2: Create a new class and pay attention if any warning is showing that if anything is missing out or replacement issue. Once the new class is successfully created move on to the next step.
Step 3: import all the required files to interact with the java program with system libraries as per the demand. So, by now the first job would be to deal with file methods in the java program which later on is to build and run. For this FileInputStream concepts will be used to deal with the java program and secondary to create an object of type ‘XSSF wordbook’.
Java provides an in-built package ‘org.apache.poi.xssf.usermodel’ to create and work with blank Excel documents and files. This package contains a class XSSFWorkbook which can be used to create and process blank spreadsheet workbooks. The class also provides functionality to read, write, and work with new or existing sheets. Above here other packages required are the File and FIleOutputStream to create a file and then open a connection. It also facilitates the modification of contents, that is, appending, deleting, etc. from the file in Java.
The random directory chosen where a blank Excel file is created is C:/blankExcel.xlsx”.
Implementation:
Java
// Importing Excel interface// Importing generic java librariesimport java.io.File;// Importing File librariesimport java.io.FileOutputStream;import org.apache.poi.xssf.usermodel.*; public class GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating WorkBook XSSFWorkbook workbook = new XSSFWorkbook(); // Creating Spreadsheet by creating an object of // XSSFSheet and also give name XSSFSheet spreadsheet = workbook.createSheet("Sheet1"); String Location = "C:\\blankExcel.xlsx"; // Place the output file in location FileOutputStream outputfile = new FileOutputStream(Location); // Write to workbook workbook.write(outputfile); // Close the output file outputfile.close(); // Display message for console window when // program is successfully executed System.out.println( "blankExcel.xlsx is written successfully"); }}
Output: On the console window
blankExcel.xlsx is written successfully
Output: The above code creates a blank Excel file in the Windows directory named ”C:/ blankExcel.xlsx”
nandinigujral
Picked
Java
Java Programs
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
Initializing a List in Java
Convert a String to Character Array in Java
Java Programming Examples
Convert Double to Integer in Java
Implementing a Linked List in Java using Class
|
[
{
"code": null,
"e": 25647,
"s": 25619,
"text": "\n04 Mar, 2022"
},
{
"code": null,
"e": 25933,
"s": 25647,
"text": "ApachePOI stands for poor obfuscation Implementation which is a Java API for reading and writing Microsoft documents. It contains classes and interfaces namely Wordbook, Sheet, Row, and Cell. Apache POI can be used to access ‘xlsx’ extension files and as well as ‘xlsx’ extension files"
},
{
"code": null,
"e": 26092,
"s": 25933,
"text": "Concept: ApachePOI, jar files, and File methods are explained to a brim to show how they are connected and the procedural execution intercepting directories. "
},
{
"code": null,
"e": 26409,
"s": 26092,
"text": "Step 1: To get the project ready to code. Once the package is created, still certain jar files are needed to access the Apache so do download the jar files before reading further. There are 4 jar files needed to access Excel using java or simply import all jar files of ‘usermodel’ during the java project creation. "
},
{
"code": null,
"e": 26603,
"s": 26409,
"text": "Step 2: Create a new class and pay attention if any warning is showing that if anything is missing out or replacement issue. Once the new class is successfully created move on to the next step."
},
{
"code": null,
"e": 26969,
"s": 26603,
"text": "Step 3: import all the required files to interact with the java program with system libraries as per the demand. So, by now the first job would be to deal with file methods in the java program which later on is to build and run. For this FileInputStream concepts will be used to deal with the java program and secondary to create an object of type ‘XSSF wordbook’. "
},
{
"code": null,
"e": 27518,
"s": 26969,
"text": "Java provides an in-built package ‘org.apache.poi.xssf.usermodel’ to create and work with blank Excel documents and files. This package contains a class XSSFWorkbook which can be used to create and process blank spreadsheet workbooks. The class also provides functionality to read, write, and work with new or existing sheets. Above here other packages required are the File and FIleOutputStream to create a file and then open a connection. It also facilitates the modification of contents, that is, appending, deleting, etc. from the file in Java."
},
{
"code": null,
"e": 27606,
"s": 27518,
"text": "The random directory chosen where a blank Excel file is created is C:/blankExcel.xlsx”."
},
{
"code": null,
"e": 27622,
"s": 27606,
"text": "Implementation:"
},
{
"code": null,
"e": 27627,
"s": 27622,
"text": "Java"
},
{
"code": "// Importing Excel interface// Importing generic java librariesimport java.io.File;// Importing File librariesimport java.io.FileOutputStream;import org.apache.poi.xssf.usermodel.*; public class GFG { // Main driver method public static void main(String[] args) throws Exception { // Creating WorkBook XSSFWorkbook workbook = new XSSFWorkbook(); // Creating Spreadsheet by creating an object of // XSSFSheet and also give name XSSFSheet spreadsheet = workbook.createSheet(\"Sheet1\"); String Location = \"C:\\\\blankExcel.xlsx\"; // Place the output file in location FileOutputStream outputfile = new FileOutputStream(Location); // Write to workbook workbook.write(outputfile); // Close the output file outputfile.close(); // Display message for console window when // program is successfully executed System.out.println( \"blankExcel.xlsx is written successfully\"); }}",
"e": 28646,
"s": 27627,
"text": null
},
{
"code": null,
"e": 28676,
"s": 28646,
"text": "Output: On the console window"
},
{
"code": null,
"e": 28716,
"s": 28676,
"text": "blankExcel.xlsx is written successfully"
},
{
"code": null,
"e": 28820,
"s": 28716,
"text": "Output: The above code creates a blank Excel file in the Windows directory named ”C:/ blankExcel.xlsx” "
},
{
"code": null,
"e": 28836,
"s": 28822,
"text": "nandinigujral"
},
{
"code": null,
"e": 28843,
"s": 28836,
"text": "Picked"
},
{
"code": null,
"e": 28848,
"s": 28843,
"text": "Java"
},
{
"code": null,
"e": 28862,
"s": 28848,
"text": "Java Programs"
},
{
"code": null,
"e": 28867,
"s": 28862,
"text": "Java"
},
{
"code": null,
"e": 28965,
"s": 28867,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29016,
"s": 28965,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29046,
"s": 29016,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29061,
"s": 29046,
"text": "Stream In Java"
},
{
"code": null,
"e": 29080,
"s": 29061,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29111,
"s": 29080,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29139,
"s": 29111,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 29183,
"s": 29139,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 29209,
"s": 29183,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 29243,
"s": 29209,
"text": "Convert Double to Integer in Java"
}
] |
Moore Machines implementation in C++ - GeeksforGeeks
|
20 Aug, 2021
Moore Machines: A Moore Machine is basically a DFA with an output associated with every state. These machines can be used for a wide variety of tasks such as counting occurrences of a particular substring in a given string, finding 2’s complement of a binary number, etc.
Working of Moore Machine:
It has an output associated with each state.
On taking input, it goes to the next state.
On reaching the next state, it prints the output of the next state.
This continues until the end of input is reached.
Application 1: Given a string S consisting of a and b, and a substring “abb”, the task is to count the occurrence of the given substring str in the given string S using Moore Machines.
Examples:
Input: S = “babbbbabb” Output: 00010001 occurrences: 2 Explanation: The substring “abb” occurs two times in the given string. Hence, for every substring “abb” a ‘1’ is produced. The number of 1s is 2.Input: S = “ab” Output: 000 occurences: 0 Explanation: There is no occurrence of substring “abb” in the given string. Hence, the number of 1s is 0.
Approach:The required Moore Machine for this problem is given by:
The Transition table for the machine is given below:
To implement this, create a structure for mapping input to its next state:
struct item
{
int value;
State* next;
};
Then, include this struct as a data member to our class State. The class has three data members:
Input_1: This is a variable of type item defined above. It maps the first type of input ‘a’ to its next State.
Input_2: This is also a variable of type item. It maps the second type of input ‘b’ to its next State.
m_out: This is the output associated with each state of the Moore Machine.
Each object of the class behaves as a state. It takes input and goes to the appropriate next state. To go to the next state, an object pointer can be used. Every object also has an input associated with it.
The following member functions will be used to work on this data:
Initialize(): This initializes the class object(state) with inputs and corresponding next state(s).
Transition(): This acts as a transition table for machine. It takes a character from the input string and passes it to the current state which then goes into appropriate next state after producing an output.
Traverse(): This function takes an input string and character by character passes it into the transition function and return the output string.
mooreOut(): This function defines the required states(objects) and initializes them to required values. Then passes the input string to the traverse function and receives output string.
countStr(): This function counts the occurrences of 1 in the output string and returns it.
The next step is to store the current state of the machine while passing string inputs to it. This can be done by using a static Object pointer as a class data member:
Below is the implementation of the above approach:
C++14
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Define a class named Stateclass State {private: // Item struct item { char value; State* next; }; // Three states item Input1; item Input2; char m_out; public: // Constructor State() : Input1{ ' ', nullptr }, Input2{ ' ', nullptr }, m_out{ ' ' } { } // Member functions static State* m_ptr; void Initialize(item input1, item input2, char out); static char Transition(char x); static string Traverse(string& str, int n);}; // Global object pointer points to// current stateState* State::m_ptr{ nullptr }; // Function that initializes the states// with appropriate valuesvoid State::Initialize(item input1, item input2, char out){ Input1 = input1; Input2 = input2; m_out = out;} // Transition function that takes each// character of stringchar State::Transition(char x){ char ch{}; // Prints the output if ((*m_ptr).Input1.value == x) { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input1.next; } else { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input2.next; } // Return ch return ch;} // Takes the whole string and pass// it through machinestring State::Traverse(string& str, int n){ string str1{}; // Add all the transition state to // the string str1 for (int i = 0; i < n; i++) str1 += Transition(str[i]); // Append output str1 += (*m_ptr).m_out; cout << (*m_ptr).m_out << endl; // Return str1 return str1;} // Function that create states and// produce outputstring mooreOut(string str, int n){ State q1, q2, q3, q4; // Initializing the states q1.Initialize({ 'a', &q2 }, { 'b', &q1 }, '0'); q2.Initialize({ 'a', &q2 }, { 'b', &q3 }, '0'); q3.Initialize({ 'a', &q2 }, { 'b', &q4 }, '0'); q4.Initialize({ 'a', &q2 }, { 'b', &q1 }, '1'); State::m_ptr = &q1; // Traverse the string str1 string str1{ State::Traverse(str, n) }; return str1;} // Function that counts the occurrences// of 1 in the output stringint countStr(string& str, int n){ int count{}; // Count the 1s in str for (int i = 0; i < n; i++) { if (str[i] == '1') count++; } // Return count return count;} // Driver Codeint main(){ // Given string string str{ "babbabbabbb" }; int n{ static_cast<int>(str.length()) }; // Function Call string str1{ mooreOut(str, n) }; int n1{ static_cast<int>(str.length()) }; // Print the count of substring cout << "abb occurs " << countStr(str1, n1) << " times\n"; return 0;}
000010010010
abb occurs 3 times
Time Complexity: O(N) Auxiliary Space: O(N)Application 2: Given a binary string str, the task is to find the 2s complement of the given string str.
Input: str = “111010000” Output: 000110000Input: str = “111” Output: 001
Approach: The idea is to start from the rightmost bit and pass it into the machine giving the output. Pass the whole string like this, going from right to left. The following observations can be observed:For Example: The given string is “111010000”. Now, 2s compliment is given by 1s complement of(str) + 1. Therefore,
str = "111010000"
1s compliment = "000101111"
+ 1
---------------------------
2s complement = 000110000
Here we can observe that from the rightmost bit the bits are copied the same way until 1 appears. After that all the bits are reversed.Therefore, the idea is to define a Moore Machine to start to take input from the rightmost side. As long as the bit is 0 it gives the same output(0). When 1 is encountered then it gives 1 for that. After this, for any bit taken as input its inverse is given as output.
The Moore Machine for this problem is given below:
To implement this first, map the transition table for this machine. Three states are needed i.e. three objects of class State defined at the beginning:
State1 => Initialize( {‘0’, &State1}, {‘1’, &State2}, ‘0’)
State2 => Initialize( {‘0’, &State2}, {‘1’, &State3}, ‘1’)
State3 => Initialize( {‘0’, &State2}, {‘1’, &State3}, ‘0’)
After initialization, a Transition function is needed like the one defined above. It takes an input and for that prints output of the current state and goes to the next state by mapping input to the next state using the transition table defined above. Then to traverse the string, the transition begins from the rightmost bit and goes till the leftmost bit.
Below is the implementation of the above approach:
C++
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Define a class named Stateclass State {private: struct item { char value; State* next; }; item Input1; item Input2; char m_out; public: // Constructors State() : Input1{ ' ', nullptr }, Input2{ ' ', nullptr }, m_out{ ' ' } { } static State* m_ptr; // Member Functions void Initialize(item input1, item input2, char out); static char Transition(char x); static string Traverse(string& str, int n);}; // Global object pointer points to// current stateState* State::m_ptr{ nullptr }; // Function that initializes the states// with appropriate valuesvoid State::Initialize(item input1, item input2, char out){ Input1 = input1; Input2 = input2; m_out = out;} // Transition function takes each// character of stringchar State::Transition(char x){ char ch{}; // Prints the output if ((*m_ptr).Input1.value == x) { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input1.next; } else { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input2.next; } // Return ch return ch;} // Takes the whole string and passes// through machinestring State::Traverse(string& str, int n){ string str1{}; // Add all the transition state to // the string str1 for (int i = n - 1; i >= 0; i--) { str1 += Transition(str[i]); } // To read the characters from end // therefore we need to reverse reverse(str1.begin(), str1.end()); return str1;} // Function to create states and// produce outputstring mooreOut(string str, int n){ State q1, q2, q3; // Initializing the states q1.Initialize({ '0', &q1 }, { '1', &q2 }, '0'); q2.Initialize({ '0', &q2 }, { '1', &q3 }, '1'); q3.Initialize({ '0', &q2 }, { '1', &q3 }, '0'); State::m_ptr = &q1; return State::Traverse(str, n);} // Driver Codeint main(){ // Given string string str{ "111010000" }; int n{ static_cast<int>(str.length()) }; // Function Call string str1{ mooreOut(str, n) }; // Print the output cout << "2's complement: " << str1; return 0;}
2's complement: 000110000
Time Complexity: O(N), where N is the length of the given binary string. Auxiliary Space: O(N)
ruhelaa48
sweetyty
gulshankumarar231
GATE CS
Theory of Computation & Automata
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Differences between IPv4 and IPv6
Preemptive and Non-Preemptive Scheduling
Difference between Clustered and Non-clustered index
Phases of a Compiler
Introduction of Process Synchronization
Turing Machine in TOC
Introduction of Finite Automata
Difference between DFA and NFA
Introduction of Pushdown Automata
Construct Pushdown Automata for given languages
|
[
{
"code": null,
"e": 25627,
"s": 25599,
"text": "\n20 Aug, 2021"
},
{
"code": null,
"e": 25899,
"s": 25627,
"text": "Moore Machines: A Moore Machine is basically a DFA with an output associated with every state. These machines can be used for a wide variety of tasks such as counting occurrences of a particular substring in a given string, finding 2’s complement of a binary number, etc."
},
{
"code": null,
"e": 25925,
"s": 25899,
"text": "Working of Moore Machine:"
},
{
"code": null,
"e": 25970,
"s": 25925,
"text": "It has an output associated with each state."
},
{
"code": null,
"e": 26014,
"s": 25970,
"text": "On taking input, it goes to the next state."
},
{
"code": null,
"e": 26082,
"s": 26014,
"text": "On reaching the next state, it prints the output of the next state."
},
{
"code": null,
"e": 26132,
"s": 26082,
"text": "This continues until the end of input is reached."
},
{
"code": null,
"e": 26317,
"s": 26132,
"text": "Application 1: Given a string S consisting of a and b, and a substring “abb”, the task is to count the occurrence of the given substring str in the given string S using Moore Machines."
},
{
"code": null,
"e": 26328,
"s": 26317,
"text": "Examples: "
},
{
"code": null,
"e": 26678,
"s": 26328,
"text": "Input: S = “babbbbabb” Output: 00010001 occurrences: 2 Explanation: The substring “abb” occurs two times in the given string. Hence, for every substring “abb” a ‘1’ is produced. The number of 1s is 2.Input: S = “ab” Output: 000 occurences: 0 Explanation: There is no occurrence of substring “abb” in the given string. Hence, the number of 1s is 0. "
},
{
"code": null,
"e": 26746,
"s": 26678,
"text": "Approach:The required Moore Machine for this problem is given by: "
},
{
"code": null,
"e": 26801,
"s": 26746,
"text": "The Transition table for the machine is given below: "
},
{
"code": null,
"e": 26878,
"s": 26801,
"text": "To implement this, create a structure for mapping input to its next state: "
},
{
"code": null,
"e": 26929,
"s": 26878,
"text": "struct item\n{\n int value;\n State* next;\n};"
},
{
"code": null,
"e": 27026,
"s": 26929,
"text": "Then, include this struct as a data member to our class State. The class has three data members:"
},
{
"code": null,
"e": 27137,
"s": 27026,
"text": "Input_1: This is a variable of type item defined above. It maps the first type of input ‘a’ to its next State."
},
{
"code": null,
"e": 27240,
"s": 27137,
"text": "Input_2: This is also a variable of type item. It maps the second type of input ‘b’ to its next State."
},
{
"code": null,
"e": 27315,
"s": 27240,
"text": "m_out: This is the output associated with each state of the Moore Machine."
},
{
"code": null,
"e": 27522,
"s": 27315,
"text": "Each object of the class behaves as a state. It takes input and goes to the appropriate next state. To go to the next state, an object pointer can be used. Every object also has an input associated with it."
},
{
"code": null,
"e": 27588,
"s": 27522,
"text": "The following member functions will be used to work on this data:"
},
{
"code": null,
"e": 27688,
"s": 27588,
"text": "Initialize(): This initializes the class object(state) with inputs and corresponding next state(s)."
},
{
"code": null,
"e": 27896,
"s": 27688,
"text": "Transition(): This acts as a transition table for machine. It takes a character from the input string and passes it to the current state which then goes into appropriate next state after producing an output."
},
{
"code": null,
"e": 28040,
"s": 27896,
"text": "Traverse(): This function takes an input string and character by character passes it into the transition function and return the output string."
},
{
"code": null,
"e": 28226,
"s": 28040,
"text": "mooreOut(): This function defines the required states(objects) and initializes them to required values. Then passes the input string to the traverse function and receives output string."
},
{
"code": null,
"e": 28317,
"s": 28226,
"text": "countStr(): This function counts the occurrences of 1 in the output string and returns it."
},
{
"code": null,
"e": 28486,
"s": 28317,
"text": "The next step is to store the current state of the machine while passing string inputs to it. This can be done by using a static Object pointer as a class data member: "
},
{
"code": null,
"e": 28538,
"s": 28486,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 28544,
"s": 28538,
"text": "C++14"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Define a class named Stateclass State {private: // Item struct item { char value; State* next; }; // Three states item Input1; item Input2; char m_out; public: // Constructor State() : Input1{ ' ', nullptr }, Input2{ ' ', nullptr }, m_out{ ' ' } { } // Member functions static State* m_ptr; void Initialize(item input1, item input2, char out); static char Transition(char x); static string Traverse(string& str, int n);}; // Global object pointer points to// current stateState* State::m_ptr{ nullptr }; // Function that initializes the states// with appropriate valuesvoid State::Initialize(item input1, item input2, char out){ Input1 = input1; Input2 = input2; m_out = out;} // Transition function that takes each// character of stringchar State::Transition(char x){ char ch{}; // Prints the output if ((*m_ptr).Input1.value == x) { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input1.next; } else { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input2.next; } // Return ch return ch;} // Takes the whole string and pass// it through machinestring State::Traverse(string& str, int n){ string str1{}; // Add all the transition state to // the string str1 for (int i = 0; i < n; i++) str1 += Transition(str[i]); // Append output str1 += (*m_ptr).m_out; cout << (*m_ptr).m_out << endl; // Return str1 return str1;} // Function that create states and// produce outputstring mooreOut(string str, int n){ State q1, q2, q3, q4; // Initializing the states q1.Initialize({ 'a', &q2 }, { 'b', &q1 }, '0'); q2.Initialize({ 'a', &q2 }, { 'b', &q3 }, '0'); q3.Initialize({ 'a', &q2 }, { 'b', &q4 }, '0'); q4.Initialize({ 'a', &q2 }, { 'b', &q1 }, '1'); State::m_ptr = &q1; // Traverse the string str1 string str1{ State::Traverse(str, n) }; return str1;} // Function that counts the occurrences// of 1 in the output stringint countStr(string& str, int n){ int count{}; // Count the 1s in str for (int i = 0; i < n; i++) { if (str[i] == '1') count++; } // Return count return count;} // Driver Codeint main(){ // Given string string str{ \"babbabbabbb\" }; int n{ static_cast<int>(str.length()) }; // Function Call string str1{ mooreOut(str, n) }; int n1{ static_cast<int>(str.length()) }; // Print the count of substring cout << \"abb occurs \" << countStr(str1, n1) << \" times\\n\"; return 0;}",
"e": 31579,
"s": 28544,
"text": null
},
{
"code": null,
"e": 31611,
"s": 31579,
"text": "000010010010\nabb occurs 3 times"
},
{
"code": null,
"e": 31762,
"s": 31613,
"text": "Time Complexity: O(N) Auxiliary Space: O(N)Application 2: Given a binary string str, the task is to find the 2s complement of the given string str. "
},
{
"code": null,
"e": 31837,
"s": 31762,
"text": "Input: str = “111010000” Output: 000110000Input: str = “111” Output: 001 "
},
{
"code": null,
"e": 32158,
"s": 31837,
"text": "Approach: The idea is to start from the rightmost bit and pass it into the machine giving the output. Pass the whole string like this, going from right to left. The following observations can be observed:For Example: The given string is “111010000”. Now, 2s compliment is given by 1s complement of(str) + 1. Therefore, "
},
{
"code": null,
"e": 32296,
"s": 32158,
"text": "str = \"111010000\"\n1s compliment = \"000101111\"\n + 1\n---------------------------\n2s complement = 000110000"
},
{
"code": null,
"e": 32700,
"s": 32296,
"text": "Here we can observe that from the rightmost bit the bits are copied the same way until 1 appears. After that all the bits are reversed.Therefore, the idea is to define a Moore Machine to start to take input from the rightmost side. As long as the bit is 0 it gives the same output(0). When 1 is encountered then it gives 1 for that. After this, for any bit taken as input its inverse is given as output."
},
{
"code": null,
"e": 32751,
"s": 32700,
"text": "The Moore Machine for this problem is given below:"
},
{
"code": null,
"e": 32905,
"s": 32751,
"text": "To implement this first, map the transition table for this machine. Three states are needed i.e. three objects of class State defined at the beginning: "
},
{
"code": null,
"e": 32964,
"s": 32905,
"text": "State1 => Initialize( {‘0’, &State1}, {‘1’, &State2}, ‘0’)"
},
{
"code": null,
"e": 33023,
"s": 32964,
"text": "State2 => Initialize( {‘0’, &State2}, {‘1’, &State3}, ‘1’)"
},
{
"code": null,
"e": 33082,
"s": 33023,
"text": "State3 => Initialize( {‘0’, &State2}, {‘1’, &State3}, ‘0’)"
},
{
"code": null,
"e": 33440,
"s": 33082,
"text": "After initialization, a Transition function is needed like the one defined above. It takes an input and for that prints output of the current state and goes to the next state by mapping input to the next state using the transition table defined above. Then to traverse the string, the transition begins from the rightmost bit and goes till the leftmost bit."
},
{
"code": null,
"e": 33491,
"s": 33440,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 33495,
"s": 33491,
"text": "C++"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Define a class named Stateclass State {private: struct item { char value; State* next; }; item Input1; item Input2; char m_out; public: // Constructors State() : Input1{ ' ', nullptr }, Input2{ ' ', nullptr }, m_out{ ' ' } { } static State* m_ptr; // Member Functions void Initialize(item input1, item input2, char out); static char Transition(char x); static string Traverse(string& str, int n);}; // Global object pointer points to// current stateState* State::m_ptr{ nullptr }; // Function that initializes the states// with appropriate valuesvoid State::Initialize(item input1, item input2, char out){ Input1 = input1; Input2 = input2; m_out = out;} // Transition function takes each// character of stringchar State::Transition(char x){ char ch{}; // Prints the output if ((*m_ptr).Input1.value == x) { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input1.next; } else { // Output the current state cout << (*m_ptr).m_out; ch = (*m_ptr).m_out; // Next input state m_ptr = (*m_ptr).Input2.next; } // Return ch return ch;} // Takes the whole string and passes// through machinestring State::Traverse(string& str, int n){ string str1{}; // Add all the transition state to // the string str1 for (int i = n - 1; i >= 0; i--) { str1 += Transition(str[i]); } // To read the characters from end // therefore we need to reverse reverse(str1.begin(), str1.end()); return str1;} // Function to create states and// produce outputstring mooreOut(string str, int n){ State q1, q2, q3; // Initializing the states q1.Initialize({ '0', &q1 }, { '1', &q2 }, '0'); q2.Initialize({ '0', &q2 }, { '1', &q3 }, '1'); q3.Initialize({ '0', &q2 }, { '1', &q3 }, '0'); State::m_ptr = &q1; return State::Traverse(str, n);} // Driver Codeint main(){ // Given string string str{ \"111010000\" }; int n{ static_cast<int>(str.length()) }; // Function Call string str1{ mooreOut(str, n) }; // Print the output cout << \"2's complement: \" << str1; return 0;}",
"e": 36007,
"s": 33495,
"text": null
},
{
"code": null,
"e": 36033,
"s": 36007,
"text": "2's complement: 000110000"
},
{
"code": null,
"e": 36131,
"s": 36035,
"text": "Time Complexity: O(N), where N is the length of the given binary string. Auxiliary Space: O(N) "
},
{
"code": null,
"e": 36141,
"s": 36131,
"text": "ruhelaa48"
},
{
"code": null,
"e": 36150,
"s": 36141,
"text": "sweetyty"
},
{
"code": null,
"e": 36168,
"s": 36150,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 36176,
"s": 36168,
"text": "GATE CS"
},
{
"code": null,
"e": 36209,
"s": 36176,
"text": "Theory of Computation & Automata"
},
{
"code": null,
"e": 36307,
"s": 36209,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36341,
"s": 36307,
"text": "Differences between IPv4 and IPv6"
},
{
"code": null,
"e": 36382,
"s": 36341,
"text": "Preemptive and Non-Preemptive Scheduling"
},
{
"code": null,
"e": 36435,
"s": 36382,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 36456,
"s": 36435,
"text": "Phases of a Compiler"
},
{
"code": null,
"e": 36496,
"s": 36456,
"text": "Introduction of Process Synchronization"
},
{
"code": null,
"e": 36518,
"s": 36496,
"text": "Turing Machine in TOC"
},
{
"code": null,
"e": 36550,
"s": 36518,
"text": "Introduction of Finite Automata"
},
{
"code": null,
"e": 36581,
"s": 36550,
"text": "Difference between DFA and NFA"
},
{
"code": null,
"e": 36615,
"s": 36581,
"text": "Introduction of Pushdown Automata"
}
] |
Program for Picard's iterative method | Computational Mathematics - GeeksforGeeks
|
28 Jun, 2019
The Picard’s method is an iterative method and is primarily used for approximating solutions to differential equations.
This method of solving a differential equation approximately is one of successive approximation; that is, it is an iterative method in which the numerical results become more and more accurate, the more times it is used.
The Picard’s iterative method gives a sequence of approximations Y1(x), Y2(x), ...Yk(x) to the solution of differential equations such that the nth approximation is obtained from one or more previous approximations.
The Picard’s iterative series is relatively easy to implement and the solutions obtained through this numerical analysis are generally power series.
Picard’s iteration method formula:
Picard’s iteration formula.
Steps involved:
Step 1: An approximate value of y (taken, at first, to be a constant) is substituted into the right hand side of the differential equation:dy/dx= f(x, y).
Step 2: The equation is then integrated with respect to x giving y in terms of x as a second approximation, into which given numerical values are substituted and the result rounded off to an assigned number of decimal places or significant figures.
Step 3: The iterative process is continued until two consecutive numerical solutions are the same when rounded off to the required number of decimal places.
Picard’s iteration example:Given that:and that y = 0 when x = 0, determine the value of y when x = 0.3, correct to four places of decimals.
Solution:We may proceed as follows: where x0 = 0. Hence: where y0 = 0. which becomes:
First Iteration:We do not know y in terms of x yet, so we replace y by the constant value y0 in the function to be integrated.The result of the first iteration is thus given, at x = 0.3, by:
The result of the first iteration is thus given, at x = 0.3, by:
Second Iteration:Now, we use:Therefore, which gives:The result of the second iteration is thus given by: at x=0.3.
Therefore, which gives:
The result of the second iteration is thus given by: at x=0.3.
Third Iteration:Now we use:Therefore, which gives:The result of the third iteration is thus given by: at x = 0.3.
Therefore, which gives:
The result of the third iteration is thus given by: at x = 0.3.
Hence, y = 0.0451, correct upto four decimal places, at x = 0.3.
Program for Picard’s iterative method:
// C program for Picard's iterative method #include <math.h>#include <stdio.h> // required macros defined below:#define Y1(x) (1 + (x) + pow(x, 2) / 2)#define Y2(x) (1 + (x) + pow(x, 2) / 2 + pow(x, 3) / 3 + pow(x, 4) / 8)#define Y3(x) (1 + (x) + pow(x, 2) / 2 + pow(x, 3) / 3 + pow(x, 4) / 8 + pow(x, 5) / 15 + pow(x, 6) / 48) int main(){ double start_value = 0, end_value = 3, allowed_error = 0.4, temp; double y1[30], y2[30], y3[30]; int count; for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { y1[count] = Y1(temp); y2[count] = Y2(temp); y3[count] = Y3(temp); } printf("\nX\n"); for (temp = start_value; temp <= end_value; temp = temp + allowed_error) { // considering all values // upto 4 decimal places. printf("%.4lf ", temp); } printf("\n\nY(1)\n"); for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { printf("%.4lf ", y1[count]); } printf("\n\nY(2)\n"); for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { printf("%.4lf ", y2[count]); } printf("\n\nY(3)\n"); for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { printf("%.4lf ", y3[count]); } return 0;}
X
0.0000 0.4000 0.8000 1.2000 1.6000 2.0000 2.4000 2.8000
Y(1)
1.0000 1.4800 2.1200 2.9200 3.8800 5.0000 6.2800 7.7200
Y(2)
1.0000 1.5045 2.3419 3.7552 6.0645 9.6667 15.0352 22.7205
Y(3)
1.0000 1.5053 2.3692 3.9833 7.1131 13.1333 24.3249 44.2335
Engineering Mathematics
Mathematical
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Activation Functions
Arrow Symbols in LaTeX
Set Notations in LaTeX
Difference between Propositional Logic and Predicate Logic
Mathematics | Graph Isomorphisms and Connectivity
Program for Fibonacci numbers
Write a program to print all permutations of a given string
C++ Data Types
Set in C++ Standard Template Library (STL)
Coin Change | DP-7
|
[
{
"code": null,
"e": 26333,
"s": 26305,
"text": "\n28 Jun, 2019"
},
{
"code": null,
"e": 26453,
"s": 26333,
"text": "The Picard’s method is an iterative method and is primarily used for approximating solutions to differential equations."
},
{
"code": null,
"e": 26674,
"s": 26453,
"text": "This method of solving a differential equation approximately is one of successive approximation; that is, it is an iterative method in which the numerical results become more and more accurate, the more times it is used."
},
{
"code": null,
"e": 26890,
"s": 26674,
"text": "The Picard’s iterative method gives a sequence of approximations Y1(x), Y2(x), ...Yk(x) to the solution of differential equations such that the nth approximation is obtained from one or more previous approximations."
},
{
"code": null,
"e": 27039,
"s": 26890,
"text": "The Picard’s iterative series is relatively easy to implement and the solutions obtained through this numerical analysis are generally power series."
},
{
"code": null,
"e": 27074,
"s": 27039,
"text": "Picard’s iteration method formula:"
},
{
"code": null,
"e": 27102,
"s": 27074,
"text": "Picard’s iteration formula."
},
{
"code": null,
"e": 27118,
"s": 27102,
"text": "Steps involved:"
},
{
"code": null,
"e": 27273,
"s": 27118,
"text": "Step 1: An approximate value of y (taken, at first, to be a constant) is substituted into the right hand side of the differential equation:dy/dx= f(x, y)."
},
{
"code": null,
"e": 27522,
"s": 27273,
"text": "Step 2: The equation is then integrated with respect to x giving y in terms of x as a second approximation, into which given numerical values are substituted and the result rounded off to an assigned number of decimal places or significant figures."
},
{
"code": null,
"e": 27679,
"s": 27522,
"text": "Step 3: The iterative process is continued until two consecutive numerical solutions are the same when rounded off to the required number of decimal places."
},
{
"code": null,
"e": 27819,
"s": 27679,
"text": "Picard’s iteration example:Given that:and that y = 0 when x = 0, determine the value of y when x = 0.3, correct to four places of decimals."
},
{
"code": null,
"e": 27905,
"s": 27819,
"text": "Solution:We may proceed as follows: where x0 = 0. Hence: where y0 = 0. which becomes:"
},
{
"code": null,
"e": 28096,
"s": 27905,
"text": "First Iteration:We do not know y in terms of x yet, so we replace y by the constant value y0 in the function to be integrated.The result of the first iteration is thus given, at x = 0.3, by:"
},
{
"code": null,
"e": 28161,
"s": 28096,
"text": "The result of the first iteration is thus given, at x = 0.3, by:"
},
{
"code": null,
"e": 28276,
"s": 28161,
"text": "Second Iteration:Now, we use:Therefore, which gives:The result of the second iteration is thus given by: at x=0.3."
},
{
"code": null,
"e": 28300,
"s": 28276,
"text": "Therefore, which gives:"
},
{
"code": null,
"e": 28363,
"s": 28300,
"text": "The result of the second iteration is thus given by: at x=0.3."
},
{
"code": null,
"e": 28477,
"s": 28363,
"text": "Third Iteration:Now we use:Therefore, which gives:The result of the third iteration is thus given by: at x = 0.3."
},
{
"code": null,
"e": 28501,
"s": 28477,
"text": "Therefore, which gives:"
},
{
"code": null,
"e": 28565,
"s": 28501,
"text": "The result of the third iteration is thus given by: at x = 0.3."
},
{
"code": null,
"e": 28630,
"s": 28565,
"text": "Hence, y = 0.0451, correct upto four decimal places, at x = 0.3."
},
{
"code": null,
"e": 28669,
"s": 28630,
"text": "Program for Picard’s iterative method:"
},
{
"code": "// C program for Picard's iterative method #include <math.h>#include <stdio.h> // required macros defined below:#define Y1(x) (1 + (x) + pow(x, 2) / 2)#define Y2(x) (1 + (x) + pow(x, 2) / 2 + pow(x, 3) / 3 + pow(x, 4) / 8)#define Y3(x) (1 + (x) + pow(x, 2) / 2 + pow(x, 3) / 3 + pow(x, 4) / 8 + pow(x, 5) / 15 + pow(x, 6) / 48) int main(){ double start_value = 0, end_value = 3, allowed_error = 0.4, temp; double y1[30], y2[30], y3[30]; int count; for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { y1[count] = Y1(temp); y2[count] = Y2(temp); y3[count] = Y3(temp); } printf(\"\\nX\\n\"); for (temp = start_value; temp <= end_value; temp = temp + allowed_error) { // considering all values // upto 4 decimal places. printf(\"%.4lf \", temp); } printf(\"\\n\\nY(1)\\n\"); for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { printf(\"%.4lf \", y1[count]); } printf(\"\\n\\nY(2)\\n\"); for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { printf(\"%.4lf \", y2[count]); } printf(\"\\n\\nY(3)\\n\"); for (temp = start_value, count = 0; temp <= end_value; temp = temp + allowed_error, count++) { printf(\"%.4lf \", y3[count]); } return 0;}",
"e": 30135,
"s": 28669,
"text": null
},
{
"code": null,
"e": 30388,
"s": 30135,
"text": "X\n0.0000 0.4000 0.8000 1.2000 1.6000 2.0000 2.4000 2.8000 \n\nY(1)\n1.0000 1.4800 2.1200 2.9200 3.8800 5.0000 6.2800 7.7200 \n\nY(2)\n1.0000 1.5045 2.3419 3.7552 6.0645 9.6667 15.0352 22.7205 \n\nY(3)\n1.0000 1.5053 2.3692 3.9833 7.1131 13.1333 24.3249 44.2335\n"
},
{
"code": null,
"e": 30412,
"s": 30388,
"text": "Engineering Mathematics"
},
{
"code": null,
"e": 30425,
"s": 30412,
"text": "Mathematical"
},
{
"code": null,
"e": 30438,
"s": 30425,
"text": "Mathematical"
},
{
"code": null,
"e": 30536,
"s": 30438,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30557,
"s": 30536,
"text": "Activation Functions"
},
{
"code": null,
"e": 30580,
"s": 30557,
"text": "Arrow Symbols in LaTeX"
},
{
"code": null,
"e": 30603,
"s": 30580,
"text": "Set Notations in LaTeX"
},
{
"code": null,
"e": 30662,
"s": 30603,
"text": "Difference between Propositional Logic and Predicate Logic"
},
{
"code": null,
"e": 30712,
"s": 30662,
"text": "Mathematics | Graph Isomorphisms and Connectivity"
},
{
"code": null,
"e": 30742,
"s": 30712,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 30802,
"s": 30742,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 30817,
"s": 30802,
"text": "C++ Data Types"
},
{
"code": null,
"e": 30860,
"s": 30817,
"text": "Set in C++ Standard Template Library (STL)"
}
] |
Python | Numpy matrix.max() - GeeksforGeeks
|
15 Apr, 2019
With the help of Numpy matrix.max() method, we can get the maximum value from given matrix.
Syntax : matrix.max()
Return : Return maximum value from given matrix
Example #1 :In this example we can see that we are able to get the maximum value from a given matrix with the help of method matrix.max().
# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.max() methodgeeks = gfg.max() print(geeks)
64
Example #2 :
# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.max() methodgeeks = gfg.max() print(geeks)
9
Python numpy-Matrix Function
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | Get unique values from a list
Python | os.path.join() method
Defaultdict in Python
Create a directory in Python
Python | Pandas dataframe.groupby()
|
[
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n15 Apr, 2019"
},
{
"code": null,
"e": 25629,
"s": 25537,
"text": "With the help of Numpy matrix.max() method, we can get the maximum value from given matrix."
},
{
"code": null,
"e": 25651,
"s": 25629,
"text": "Syntax : matrix.max()"
},
{
"code": null,
"e": 25699,
"s": 25651,
"text": "Return : Return maximum value from given matrix"
},
{
"code": null,
"e": 25838,
"s": 25699,
"text": "Example #1 :In this example we can see that we are able to get the maximum value from a given matrix with the help of method matrix.max()."
},
{
"code": "# import the important module in pythonimport numpy as np # make matrix with numpygfg = np.matrix('[64, 1; 12, 3]') # applying matrix.max() methodgeeks = gfg.max() print(geeks)",
"e": 26036,
"s": 25838,
"text": null
},
{
"code": null,
"e": 26040,
"s": 26036,
"text": "64\n"
},
{
"code": null,
"e": 26053,
"s": 26040,
"text": "Example #2 :"
},
{
"code": "# import the important module in pythonimport numpy as np # make a matrix with numpygfg = np.matrix('[1, 2, 3; 4, 5, 6; 7, 8, 9]') # applying matrix.max() methodgeeks = gfg.max() print(geeks)",
"e": 26266,
"s": 26053,
"text": null
},
{
"code": null,
"e": 26269,
"s": 26266,
"text": "9\n"
},
{
"code": null,
"e": 26298,
"s": 26269,
"text": "Python numpy-Matrix Function"
},
{
"code": null,
"e": 26311,
"s": 26298,
"text": "Python-numpy"
},
{
"code": null,
"e": 26318,
"s": 26311,
"text": "Python"
},
{
"code": null,
"e": 26416,
"s": 26318,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26448,
"s": 26416,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26490,
"s": 26448,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 26532,
"s": 26490,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 26588,
"s": 26532,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 26615,
"s": 26588,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 26654,
"s": 26615,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 26685,
"s": 26654,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 26707,
"s": 26685,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26736,
"s": 26707,
"text": "Create a directory in Python"
}
] |
Up and running with Milvus. A Vector Similarity Search Engine... | by David Shvimer | Towards Data Science
|
A vector similarity search engine that seems to be production ready. According to the website:
It offers a variety of similarity metrics and index types.
Scales horizontally.
Reading and writing happens in near real time, this means we can insert records while the engine is online.
Exposes a REST interface.
Sounds pretty cool!
For those who don’t yet know, there are many use cases for a technology like this. With the help of machine learning, we can search images, video, and audio.
Say we train a CNN that classifies images. If we take a look at the output of any layer before the final output, we may find N-dimensional feature vectors that are describing the input. As we move through the network the features become more specific. In the beginning we can identify textures, shapes, etc. Towards the end we identify objects like cat ears and dog tails. We can take the output of any of these layers, flatten it by some method, and index it in a search engine! Voila! The layer chosen will have an effect on what is considered “similar”. This will vary by use case. This example is an application of Content Based Image Retrieval (CBIR).
A very simple implementation of CBIR using Milvus, in a Dockerized environment. Here is the complete repo and a list of the technologies we will be using. If you want to download the repo and just mess around, it’s ready to go.
github.com
Python — because
Docker — so everyone has a standard environment
PyTorch — because I always jump for Keras and wanted to learn something new.
Jupyter notebook — simple way to interact with Milvus
In a new directory, let’s create some more empty directories.
-project -notebook -milvus -conf
In the top level directory, create a file named docker-compose.yml with the following contents:
version: '2.0'services: notebook: build: context: ./notebook ports: - '8888:8888' volumes: - ./notebook:/home/jovyan links: - milvus milvus: image: milvusdb/milvus:0.9.1-cpu-d052920-e04ed5 ports: - '19530:19530' - '19121:19121' volumes: - ./milvus/db:/var/lib/milvus/db - ./milvus/conf:/var/lib/milvus/conf - ./milvus/logs:/var/lib/milvus/logs - ./milvus/wal:/var/lib/milvus/wal
We have defined two docker containers, one for Milvus, and another for our jupyter notebook. The Milvus container is visible to the notebook via the links attribute. The volumes we declared are so that the Milvus file system shares some folders with our operating system. This lets us configure and monitor Milvus with ease. Since we gave the notebook container a context to build from, we need to create a file named Dockerfile in the notebook directory with the following contents:
FROM jupyter/scipy-notebookRUN pip install pymilvus==0.2.12RUN conda install --quiet --yes pytorch torchvision -c pytorch
Not the prettiest way to declare dependencies, but that can be optimized later. We should also download some images to play with. Feel free to download the ones I used here: Place them into notebook/images.
Last step, download the starter Milvus config file and place it into milvus/conf/. Now as long as Docker is installed and running, we rundocker-compose up and we are live!
If you see the following lines in the console output:
milvus_1 | Milvus server exit...milvus_1 | Config check fail: Invalid cpu cache capacity: 1. Possible reason: sum of cache_config.cpu_cache_capacity and cache_config.insert_buffer_size exceeds system memory.milvus_1 | ERROR: Milvus server fail to load config file
It means Docker is not configured with enough memory to run Milvus. If we open the config file and search for “cpu_cache_capacity” we see some helpful documentation. “The sum of ‘insert_buffer_size’ and ‘cpu_cache_capacity’ must be less than system memory size.”
Set both values to 1, and then open Docker’s settings and make sure that it is configured to any value greater than 2GB (MUST BE GREATER THAN). Make sure to apply the settings and restart Docker. Then try docker-compose up again. If something else isn’t working, please let me know in the comments.
The fun stuff, here we go. Once everything is running, we should have a URL to access our jupyter instance. Let’s create a new notebook and get to coding. One cell at a time.
First the imports:
import torchimport torch.nn as nnimport torchvision.models as modelsimport torchvision.transforms as transformsfrom torch.autograd import Variablefrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np%matplotlib inline
Now lets define a helper class to extract the feature vectors:
Why did I pick ResNet18? Because it has a layer that outputs a flat vector with length 512. Convenient and easy is reasonable when learning something new. There is quite a bit of room to extend this class. We could extract features from multiple layers at once, and input multiple images at once. For the time being, this is good enough.
Now we can load our images and start looking at similarity:
feat_vec = FeatureVector()dog1 = Image.open('./images/dog1.jpg')dog2 = Image.open('./images/dog2.jpg')dog3 = Image.open('./images/dog3.jpg')cat1 = Image.open('./images/cat1.jpg')cat2 = Image.open('./images/cat2.jpg')person1 = Image.open('./images/person1.jpg')person2 = Image.open('./images/person2.jpg')def compare(a, b): plt.figure() plt.subplot(1, 2, 1) plt.imshow(a) plt.subplot(1, 2, 2) plt.imshow(b) a_v = feat_vec.get_vector(a) b_v = feat_vec.get_vector(b) print('Similarity: {}'.format(feat_vec.similarity(a_v, b_v)))compare(dog1, dog2)
In the first example, the puppy and adult golden retriever images get a similarity score ~0.79. When we compare a puppy golden retriever and a pug we get a similarity score ~0.58.
Let’s do what we came here to do. We start by connecting to Milvus, and creating a collection
from milvus import Milvus, IndexType, MetricType, Status# Milvus server IP address and port.# Because the link to milvus in docker-compose # was named `milvus`, thats what the hostname will be_HOST = 'milvus'_PORT = '19530' # default value# Vector parameters_DIM = 512 # dimension of vector_INDEX_FILE_SIZE = 32 # max file size of stored indexmilvus = Milvus(_HOST, _PORT, pool_size=10)# Create collection demo_collection if it dosen't exist.collection_name = 'resnet18_simple'status, ok = milvus.has_collection(collection_name)if not ok: param = { 'collection_name': collection_name, 'dimension': _DIM, 'index_file_size': _INDEX_FILE_SIZE, # optional 'metric_type': MetricType.L2 # optional }print(milvus.create_collection(param))# Milvus expo_, collection = milvus.get_collection_info(collection_name)print(collection)
Now we can insert the feature vectors from our images. We need to convert the vectors into python lists:
images = [ dog1, dog2, dog3, cat1, cat2, person1, person2]# 10000 vectors with 128 dimension# element per dimension is float32 type# vectors should be a 2-D arrayvectors = [feat_vec.get_vector(i).tolist() for i in images]# Insert vectors into demo_collection, return status and vectors id liststatus, ids = milvus.insert(collection_name=collection_name, records=vectors)if not status.OK(): print("Insert failed: {}".format(status))else: print(ids)
If this was successful, we should see a list of ID’s that Milvus uses to identify the images. They are in the same order as our list of images, so lets create a quick lookup table to easily access an image, given some ID:
lookup = {}for ID, img in zip(ids, images): lookup[ID] = imgfor k in lookup: print(k, lookup[k])
We can flush the new items onto the disk and get some info for the collection:
# Flush collection inserted data to disk.milvus.flush([collection_name])# Get demo_collection row countstatus, result = milvus.count_entities(collection_name)print(result)# present collection statistics info_, info = milvus.get_collection_stats(collection_name)print(info)
Lets search!
# execute vector similarity searchsearch_param = { "nprobe": 16}print("Searching ... ")param = { 'collection_name': collection_name, 'query_records': [vectors[0]], 'top_k': 10, 'params': search_param,}status, results = milvus.search(**param)if status.OK(): print(results)else: print("Search failed. ", status)
If we see a list of results that means all is well. We can visualize them with the following snippet
for neighbors in results: for n in neighbors: plt.figure() plt.subplot(1, 2, 1) plt.imshow(images[0]) plt.subplot(1, 2, 2) plt.imshow(lookup[n.id]) print('Distance: {}'.format(n.distance))
To drop the collection:
milvus.drop_collection(collection_name)
It was pretty easy to get up and running. Most of the Milvus related code here was from the getting started example available on the website. One of our vectors is about 1KB in size, so we could fit one million feature vectors into 1GB of memory. We didn’t use an index here, which would increase that cost, but it’s still quite an efficient way to index an image. The website docs are great, but I think reading through the config file is a great way to understand what this thing is capable of. We kept it very simple in this post, but here are some ideas for those who want to take it further:
Preprocess the feature vectors. (i.e. Normalizing)
Experiment with different layers, if they aren’t flat, try max pooling or average pooling followed by flattening
Applying dimensionality reduction techniques: tNSE, PCA, LDA
Preprocess using an Auto Encoder
This was my first post ever. So if you liked it let me know. If something didn’t work or the formatting was off, also let me know! Stay classy out there.
|
[
{
"code": null,
"e": 267,
"s": 172,
"text": "A vector similarity search engine that seems to be production ready. According to the website:"
},
{
"code": null,
"e": 326,
"s": 267,
"text": "It offers a variety of similarity metrics and index types."
},
{
"code": null,
"e": 347,
"s": 326,
"text": "Scales horizontally."
},
{
"code": null,
"e": 455,
"s": 347,
"text": "Reading and writing happens in near real time, this means we can insert records while the engine is online."
},
{
"code": null,
"e": 481,
"s": 455,
"text": "Exposes a REST interface."
},
{
"code": null,
"e": 501,
"s": 481,
"text": "Sounds pretty cool!"
},
{
"code": null,
"e": 659,
"s": 501,
"text": "For those who don’t yet know, there are many use cases for a technology like this. With the help of machine learning, we can search images, video, and audio."
},
{
"code": null,
"e": 1316,
"s": 659,
"text": "Say we train a CNN that classifies images. If we take a look at the output of any layer before the final output, we may find N-dimensional feature vectors that are describing the input. As we move through the network the features become more specific. In the beginning we can identify textures, shapes, etc. Towards the end we identify objects like cat ears and dog tails. We can take the output of any of these layers, flatten it by some method, and index it in a search engine! Voila! The layer chosen will have an effect on what is considered “similar”. This will vary by use case. This example is an application of Content Based Image Retrieval (CBIR)."
},
{
"code": null,
"e": 1544,
"s": 1316,
"text": "A very simple implementation of CBIR using Milvus, in a Dockerized environment. Here is the complete repo and a list of the technologies we will be using. If you want to download the repo and just mess around, it’s ready to go."
},
{
"code": null,
"e": 1555,
"s": 1544,
"text": "github.com"
},
{
"code": null,
"e": 1572,
"s": 1555,
"text": "Python — because"
},
{
"code": null,
"e": 1620,
"s": 1572,
"text": "Docker — so everyone has a standard environment"
},
{
"code": null,
"e": 1697,
"s": 1620,
"text": "PyTorch — because I always jump for Keras and wanted to learn something new."
},
{
"code": null,
"e": 1751,
"s": 1697,
"text": "Jupyter notebook — simple way to interact with Milvus"
},
{
"code": null,
"e": 1813,
"s": 1751,
"text": "In a new directory, let’s create some more empty directories."
},
{
"code": null,
"e": 1851,
"s": 1813,
"text": "-project -notebook -milvus -conf"
},
{
"code": null,
"e": 1947,
"s": 1851,
"text": "In the top level directory, create a file named docker-compose.yml with the following contents:"
},
{
"code": null,
"e": 2491,
"s": 1947,
"text": "version: '2.0'services: notebook: build: context: ./notebook ports: - '8888:8888' volumes: - ./notebook:/home/jovyan links: - milvus milvus: image: milvusdb/milvus:0.9.1-cpu-d052920-e04ed5 ports: - '19530:19530' - '19121:19121' volumes: - ./milvus/db:/var/lib/milvus/db - ./milvus/conf:/var/lib/milvus/conf - ./milvus/logs:/var/lib/milvus/logs - ./milvus/wal:/var/lib/milvus/wal"
},
{
"code": null,
"e": 2975,
"s": 2491,
"text": "We have defined two docker containers, one for Milvus, and another for our jupyter notebook. The Milvus container is visible to the notebook via the links attribute. The volumes we declared are so that the Milvus file system shares some folders with our operating system. This lets us configure and monitor Milvus with ease. Since we gave the notebook container a context to build from, we need to create a file named Dockerfile in the notebook directory with the following contents:"
},
{
"code": null,
"e": 3097,
"s": 2975,
"text": "FROM jupyter/scipy-notebookRUN pip install pymilvus==0.2.12RUN conda install --quiet --yes pytorch torchvision -c pytorch"
},
{
"code": null,
"e": 3304,
"s": 3097,
"text": "Not the prettiest way to declare dependencies, but that can be optimized later. We should also download some images to play with. Feel free to download the ones I used here: Place them into notebook/images."
},
{
"code": null,
"e": 3476,
"s": 3304,
"text": "Last step, download the starter Milvus config file and place it into milvus/conf/. Now as long as Docker is installed and running, we rundocker-compose up and we are live!"
},
{
"code": null,
"e": 3530,
"s": 3476,
"text": "If you see the following lines in the console output:"
},
{
"code": null,
"e": 3803,
"s": 3530,
"text": "milvus_1 | Milvus server exit...milvus_1 | Config check fail: Invalid cpu cache capacity: 1. Possible reason: sum of cache_config.cpu_cache_capacity and cache_config.insert_buffer_size exceeds system memory.milvus_1 | ERROR: Milvus server fail to load config file"
},
{
"code": null,
"e": 4066,
"s": 3803,
"text": "It means Docker is not configured with enough memory to run Milvus. If we open the config file and search for “cpu_cache_capacity” we see some helpful documentation. “The sum of ‘insert_buffer_size’ and ‘cpu_cache_capacity’ must be less than system memory size.”"
},
{
"code": null,
"e": 4365,
"s": 4066,
"text": "Set both values to 1, and then open Docker’s settings and make sure that it is configured to any value greater than 2GB (MUST BE GREATER THAN). Make sure to apply the settings and restart Docker. Then try docker-compose up again. If something else isn’t working, please let me know in the comments."
},
{
"code": null,
"e": 4540,
"s": 4365,
"text": "The fun stuff, here we go. Once everything is running, we should have a URL to access our jupyter instance. Let’s create a new notebook and get to coding. One cell at a time."
},
{
"code": null,
"e": 4559,
"s": 4540,
"text": "First the imports:"
},
{
"code": null,
"e": 4794,
"s": 4559,
"text": "import torchimport torch.nn as nnimport torchvision.models as modelsimport torchvision.transforms as transformsfrom torch.autograd import Variablefrom PIL import Imageimport matplotlib.pyplot as pltimport numpy as np%matplotlib inline"
},
{
"code": null,
"e": 4857,
"s": 4794,
"text": "Now lets define a helper class to extract the feature vectors:"
},
{
"code": null,
"e": 5195,
"s": 4857,
"text": "Why did I pick ResNet18? Because it has a layer that outputs a flat vector with length 512. Convenient and easy is reasonable when learning something new. There is quite a bit of room to extend this class. We could extract features from multiple layers at once, and input multiple images at once. For the time being, this is good enough."
},
{
"code": null,
"e": 5255,
"s": 5195,
"text": "Now we can load our images and start looking at similarity:"
},
{
"code": null,
"e": 5824,
"s": 5255,
"text": "feat_vec = FeatureVector()dog1 = Image.open('./images/dog1.jpg')dog2 = Image.open('./images/dog2.jpg')dog3 = Image.open('./images/dog3.jpg')cat1 = Image.open('./images/cat1.jpg')cat2 = Image.open('./images/cat2.jpg')person1 = Image.open('./images/person1.jpg')person2 = Image.open('./images/person2.jpg')def compare(a, b): plt.figure() plt.subplot(1, 2, 1) plt.imshow(a) plt.subplot(1, 2, 2) plt.imshow(b) a_v = feat_vec.get_vector(a) b_v = feat_vec.get_vector(b) print('Similarity: {}'.format(feat_vec.similarity(a_v, b_v)))compare(dog1, dog2)"
},
{
"code": null,
"e": 6004,
"s": 5824,
"text": "In the first example, the puppy and adult golden retriever images get a similarity score ~0.79. When we compare a puppy golden retriever and a pug we get a similarity score ~0.58."
},
{
"code": null,
"e": 6098,
"s": 6004,
"text": "Let’s do what we came here to do. We start by connecting to Milvus, and creating a collection"
},
{
"code": null,
"e": 6958,
"s": 6098,
"text": "from milvus import Milvus, IndexType, MetricType, Status# Milvus server IP address and port.# Because the link to milvus in docker-compose # was named `milvus`, thats what the hostname will be_HOST = 'milvus'_PORT = '19530' # default value# Vector parameters_DIM = 512 # dimension of vector_INDEX_FILE_SIZE = 32 # max file size of stored indexmilvus = Milvus(_HOST, _PORT, pool_size=10)# Create collection demo_collection if it dosen't exist.collection_name = 'resnet18_simple'status, ok = milvus.has_collection(collection_name)if not ok: param = { 'collection_name': collection_name, 'dimension': _DIM, 'index_file_size': _INDEX_FILE_SIZE, # optional 'metric_type': MetricType.L2 # optional }print(milvus.create_collection(param))# Milvus expo_, collection = milvus.get_collection_info(collection_name)print(collection)"
},
{
"code": null,
"e": 7063,
"s": 6958,
"text": "Now we can insert the feature vectors from our images. We need to convert the vectors into python lists:"
},
{
"code": null,
"e": 7535,
"s": 7063,
"text": "images = [ dog1, dog2, dog3, cat1, cat2, person1, person2]# 10000 vectors with 128 dimension# element per dimension is float32 type# vectors should be a 2-D arrayvectors = [feat_vec.get_vector(i).tolist() for i in images]# Insert vectors into demo_collection, return status and vectors id liststatus, ids = milvus.insert(collection_name=collection_name, records=vectors)if not status.OK(): print(\"Insert failed: {}\".format(status))else: print(ids)"
},
{
"code": null,
"e": 7757,
"s": 7535,
"text": "If this was successful, we should see a list of ID’s that Milvus uses to identify the images. They are in the same order as our list of images, so lets create a quick lookup table to easily access an image, given some ID:"
},
{
"code": null,
"e": 7860,
"s": 7757,
"text": "lookup = {}for ID, img in zip(ids, images): lookup[ID] = imgfor k in lookup: print(k, lookup[k])"
},
{
"code": null,
"e": 7939,
"s": 7860,
"text": "We can flush the new items onto the disk and get some info for the collection:"
},
{
"code": null,
"e": 8213,
"s": 7939,
"text": "# Flush collection inserted data to disk.milvus.flush([collection_name])# Get demo_collection row countstatus, result = milvus.count_entities(collection_name)print(result)# present collection statistics info_, info = milvus.get_collection_stats(collection_name)print(info)"
},
{
"code": null,
"e": 8226,
"s": 8213,
"text": "Lets search!"
},
{
"code": null,
"e": 8557,
"s": 8226,
"text": "# execute vector similarity searchsearch_param = { \"nprobe\": 16}print(\"Searching ... \")param = { 'collection_name': collection_name, 'query_records': [vectors[0]], 'top_k': 10, 'params': search_param,}status, results = milvus.search(**param)if status.OK(): print(results)else: print(\"Search failed. \", status)"
},
{
"code": null,
"e": 8658,
"s": 8557,
"text": "If we see a list of results that means all is well. We can visualize them with the following snippet"
},
{
"code": null,
"e": 8892,
"s": 8658,
"text": "for neighbors in results: for n in neighbors: plt.figure() plt.subplot(1, 2, 1) plt.imshow(images[0]) plt.subplot(1, 2, 2) plt.imshow(lookup[n.id]) print('Distance: {}'.format(n.distance))"
},
{
"code": null,
"e": 8916,
"s": 8892,
"text": "To drop the collection:"
},
{
"code": null,
"e": 8956,
"s": 8916,
"text": "milvus.drop_collection(collection_name)"
},
{
"code": null,
"e": 9553,
"s": 8956,
"text": "It was pretty easy to get up and running. Most of the Milvus related code here was from the getting started example available on the website. One of our vectors is about 1KB in size, so we could fit one million feature vectors into 1GB of memory. We didn’t use an index here, which would increase that cost, but it’s still quite an efficient way to index an image. The website docs are great, but I think reading through the config file is a great way to understand what this thing is capable of. We kept it very simple in this post, but here are some ideas for those who want to take it further:"
},
{
"code": null,
"e": 9604,
"s": 9553,
"text": "Preprocess the feature vectors. (i.e. Normalizing)"
},
{
"code": null,
"e": 9717,
"s": 9604,
"text": "Experiment with different layers, if they aren’t flat, try max pooling or average pooling followed by flattening"
},
{
"code": null,
"e": 9778,
"s": 9717,
"text": "Applying dimensionality reduction techniques: tNSE, PCA, LDA"
},
{
"code": null,
"e": 9811,
"s": 9778,
"text": "Preprocess using an Auto Encoder"
}
] |
Spring Cloud - Circuit Breaker using Hystrix
|
In a distributed environment, services need to communicate with each other. The communication can either happen synchronously or asynchronously. When services communicate synchronously, there can be multiple reasons where things can break. For example −
Callee service unavailable − The service which is being called is down for some reason, for example − bug, deployment, etc.
Callee service unavailable − The service which is being called is down for some reason, for example − bug, deployment, etc.
Callee service taking time to respond − The service which is being called can be slow due to high load or resource consumption or it is in the middle of initializing the services.
Callee service taking time to respond − The service which is being called can be slow due to high load or resource consumption or it is in the middle of initializing the services.
In either of the cases, it is waste of time and network resources for the caller to wait for the callee to respond. It makes more sense for the service to back off and give calls to the callee service after some time or share default response.
Netflix Hystrix, Resilince4j are two well-known circuit breakers which are used to handle such situations. In this tutorial, we will use Hystrix.
Let us use the case of Restaurant that we have been using earlier. Let us add hystrix dependency to our Restaurant Services which call the Customer Service. First, let us update the pom.xml of the service with the following dependency −
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-hystrix</artifactId>
<version>2.7.0.RELEASE</version>
</dependency>
And then, annotate our Spring application class with the correct annotation, i.e., @EnableHystrix
package com.tutorialspoint;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.netflix.hystrix.EnableHystrix;
import org.springframework.cloud.openfeign.EnableFeignClients;
@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
@EnableHystrix
public class RestaurantService{
public static void main(String[] args) {
SpringApplication.run(RestaurantService.class, args);
}
}
Points to Note
@ EnableDiscoveryClient and @EnableFeignCLient − We have already looked at these annotations in the previous chapter.
@ EnableDiscoveryClient and @EnableFeignCLient − We have already looked at these annotations in the previous chapter.
@EnableHystrix − This annotation scans our packages and looks out for methods which are using @HystrixCommand annotation.
@EnableHystrix − This annotation scans our packages and looks out for methods which are using @HystrixCommand annotation.
Once done, we will reuse the Feign client which we had defined for our customer service class earlier in the Restaurant service, no changes here −
package com.tutorialspoint;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "customer-service")
public interface CustomerService {
@RequestMapping("/customer/{id}")
public Customer getCustomerById(@PathVariable("id") Long id);
}
Now, let us define the service implementation class here which would use the Feign client. This would be a simple wrapper around the feign client.
package com.tutorialspoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@Service
public class CustomerServiceImpl implements CustomerService {
@Autowired
CustomerService customerService;
@HystrixCommand(fallbackMethod="defaultCustomerWithNYCity")
public Customer getCustomerById(Long id) {
return customerService.getCustomerById(id);
}
// assume customer resides in NY city
public Customer defaultCustomerWithNYCity(Long id) {
return new Customer(id, null, "NY");
}
}
Now, let us understand couple of points from the above code −
HystrixCommand annotation − This is responsible for wrapping the function call that is getCustomerById and provide a proxy around it. The proxy then gives various hooks through which we can control our call to the customer service. For example, timing out the request,pooling of request, providing a fallback method, etc.
HystrixCommand annotation − This is responsible for wrapping the function call that is getCustomerById and provide a proxy around it. The proxy then gives various hooks through which we can control our call to the customer service. For example, timing out the request,pooling of request, providing a fallback method, etc.
Fallback method − We can specify the method we want to call when Hystrix determines that something is wrong with the callee. This method needs to have same signature as the method which is annotated. In our case, we have decided to provide the data back to our controller for the NY city.
Fallback method − We can specify the method we want to call when Hystrix determines that something is wrong with the callee. This method needs to have same signature as the method which is annotated. In our case, we have decided to provide the data back to our controller for the NY city.
Couple of useful options this annotation provides −
Error threshold percent − Percentage of request allowed to fail before the circuit is tripped, that is, fallback methods are called. This can be controlled by using cicutiBreaker.errorThresholdPercentage
Error threshold percent − Percentage of request allowed to fail before the circuit is tripped, that is, fallback methods are called. This can be controlled by using cicutiBreaker.errorThresholdPercentage
Giving up on the network request after timeout − If the callee service, in our case Customer service, is slow, we can set the timeout after which we will drop the request and move to fallback method. This is controlled by setting execution.isolation.thread.timeoutInMilliseconds
Giving up on the network request after timeout − If the callee service, in our case Customer service, is slow, we can set the timeout after which we will drop the request and move to fallback method. This is controlled by setting execution.isolation.thread.timeoutInMilliseconds
And lastly, here is our controller which we call the CustomerServiceImpl
package com.tutorialspoint;
import java.util.HashMap;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
@RestController
class RestaurantController {
@Autowired
CustomerServiceImpl customerService;
static HashMap<Long, Restaurant> mockRestaurantData = new HashMap();
static{
mockRestaurantData.put(1L, new Restaurant(1, "Pandas", "DC"));
mockRestaurantData.put(2L, new Restaurant(2, "Indies", "SFO"));
mockRestaurantData.put(3L, new Restaurant(3, "Little Italy", "DC"));
mockRestaurantData.put(3L, new Restaurant(4, "Pizeeria", "NY"));
}
@RequestMapping("/restaurant/customer/{id}")
public List<Restaurant> getRestaurantForCustomer(@PathVariable("id") Long
id)
{
System.out.println("Got request for customer with id: " + id);
String customerCity = customerService.getCustomerById(id).getCity();
return mockRestaurantData.entrySet().stream().filter(
entry -> entry.getValue().getCity().equals(customerCity))
.map(entry -> entry.getValue())
.collect(Collectors.toList());
}
}
Now that we are done with the setup, let us give this a try. Just a bit background here, what we will do is the following −
Start the Eureka Server
Start the Eureka Server
Start the Customer Service
Start the Customer Service
Start the Restaurant Service which will internally call Customer Service.
Start the Restaurant Service which will internally call Customer Service.
Make an API call to Restaurant Service
Make an API call to Restaurant Service
Shut down the Customer Service
Shut down the Customer Service
Make an API call to Restaurant Service. Given that Customer Service is down, it would cause failure and ultimately, the fallback method would be called.
Make an API call to Restaurant Service. Given that Customer Service is down, it would cause failure and ultimately, the fallback method would be called.
Let us now compile the Restaurant Service code and execute with the following command −
java -Dapp_port=8082 -jar .\target\spring-cloud-feign-client-1.0.jar
Also, start the Customer Service and the Eureka server. Note that there are no changes in these services and they remain same as seen in the previous chapters.
Now, let us try to find restaurant for Jane who is based in DC.
{
"id": 1,
"name": "Jane",
"city": "DC"
}
For doing that, we will hit the following URL: http://localhost:8082/restaurant/customer/1
[
{
"id": 1,
"name": "Pandas",
"city": "DC"
},
{
"id": 3,
"name": "Little Italy",
"city": "DC"
}
]
So, nothing new here, we got the restaurants which are in DC. Now, let's move to the interesting part which is shutting down the Customer service. You can do that either by hitting Ctrl+C or simply killing the shell.
Now let us hit the same URL again − http://localhost:8082/restaurant/customer/1
{
"id": 4,
"name": "Pizzeria",
"city": "NY"
}
As is visible from the output, we have got the restaurants from NY, although our customer is from DC.This is because our fallback method returned a dummy customer who is situated in NY. Although, not useful, the above example displays that the fallback was called as expected.
To make the above method more useful, we can integrate caching when using Hystrix. This can be a useful pattern to provide better answers when the underlying service is not available.
First, let us create a cached version of the service.
package com.tutorialspoint;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
@Service
public class CustomerServiceCachedFallback implements CustomerService {
Map<Long, Customer> cachedCustomer = new HashMap<>();
@Autowired
CustomerService customerService;
@HystrixCommand(fallbackMethod="defaultToCachedData")
public Customer getCustomerById(Long id) {
Customer customer = customerService.getCustomerById(id);
// cache value for future reference
cachedCustomer.put(customer.getId(), customer);
return customer;
}
// get customer data from local cache
public Customer defaultToCachedData(Long id) {
return cachedCustomer.get(id);
}
}
We are using hashMap as the storage to cache the data. This for developmental purpose. In Production environment, we may want to use better caching solutions, for example, Redis, Hazelcast, etc.
Now, we just need to update one line in the controller to use the above service −
@RestController
class RestaurantController {
@Autowired
CustomerServiceCachedFallback customerService;
static HashMap<Long, Restaurant> mockRestaurantData = new HashMap();
...
}
We will follow the same steps as above −
Start the Eureka Server.
Start the Eureka Server.
Start the Customer Service.
Start the Customer Service.
Start the Restaurant Service which internally call Customer Service.
Start the Restaurant Service which internally call Customer Service.
Make an API call to the Restaurant Service.
Make an API call to the Restaurant Service.
Shut down the Customer Service.
Shut down the Customer Service.
Make an API call to the Restaurant Service. Given that Customer Service is down but the data is cached, we will get a valid set of data.
Make an API call to the Restaurant Service. Given that Customer Service is down but the data is cached, we will get a valid set of data.
Now, let us follow the same process till step 3.
Now hit the URL: http://localhost:8082/restaurant/customer/1
[
{
"id": 1,
"name": "Pandas",
"city": "DC"
},
{
"id": 3,
"name": "Little Italy",
"city": "DC"
}
]
So, nothing new here, we got the restaurants which are in DC. Now, let us move to the interesting part which is shutting down the Customer service. You can do that either by hitting Ctrl+C or simply killing the shell.
Now let us hit the same URL again − http://localhost:8082/restaurant/customer/1
[
{
"id": 1,
"name": "Pandas",
"city": "DC"
},
{
"id": 3,
"name": "Little Italy",
"city": "DC"
}
]
As is visible from the output, we have got the restaurants from DC which is what we expect as our customer is from DC. This is because our fallback method returned a cached customer data.
We saw how to use @HystrixCommand annotation to trip the circuit and provide a fallback. But we had to additionally define a Service class to wrap our Hystrix client. However, we can also achieve the same by simply passing correct arguments to Feign client. Let us try to do that. For that, first update our Feign client for CustomerService by adding a fallback class.
package com.tutorialspoint;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@FeignClient(name = "customer-service", fallback = FallBackHystrix.class)
public interface CustomerService {
@RequestMapping("/customer/{id}")
public Customer getCustomerById(@PathVariable("id") Long id);
}
Now, let us add the fallback class for the Feign client which will be called when the Hystrix circuit is tripped.
package com.tutorialspoint;
import org.springframework.stereotype.Component;
@Component
public class FallBackHystrix implements CustomerService{
@Override
public Customer getCustomerById(Long id) {
System.out.println("Fallback called....");
return new Customer(0, "Temp", "NY");
}
}
Lastly, we also need to create the application-circuit.yml to enable hystrix.
spring:
application:
name: restaurant-service
server:
port: ${app_port}
eureka:
client:
serviceURL:
defaultZone: http://localhost:8900/eureka
feign:
circuitbreaker:
enabled: true
Now, that we have the setup ready, let us test this out. We will follow these steps −
Start the Eureka Server.
Start the Eureka Server.
We do not start the Customer Service.
We do not start the Customer Service.
Start the Restaurant Service which will internally call Customer Service.
Start the Restaurant Service which will internally call Customer Service.
Make an API call to Restaurant Service. Given that Customer Service is down, we will notice the fallback.
Make an API call to Restaurant Service. Given that Customer Service is down, we will notice the fallback.
Assuming 1st step is already done, let's move to step 3. Let us compile the code and execute the following command −
java -Dapp_port=8082 -jar .\target\spring-cloud-feign-client-1.0.jar --
spring.config.location=classpath:application-circuit.yml
Let us now try to hit − http://localhost:8082/restaurant/customer/1
As we have not started Customer Service, fallback would be called and the fallback sends over NY as the city, which is why, we see NY restaurants in the following output.
{
"id": 4,
"name": "Pizzeria",
"city": "NY"
}
Also, to confirm, in the logs, we would see −
....
2021-03-13 16:27:02.887 WARN 21228 --- [reakerFactory-1]
.s.c.o.l.FeignBlockingLoadBalancerClient : Load balancer does not contain an
instance for the service customer-service
Fallback called....
2021-03-13 16:27:03.802 INFO 21228 --- [ main]
o.s.cloud.commons.util.InetUtils : Cannot determine local hostname
.....
102 Lectures
8 hours
Karthikeya T
39 Lectures
5 hours
Chaand Sheikh
73 Lectures
5.5 hours
Senol Atac
62 Lectures
4.5 hours
Senol Atac
67 Lectures
4.5 hours
Senol Atac
69 Lectures
5 hours
Senol Atac
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2132,
"s": 1878,
"text": "In a distributed environment, services need to communicate with each other. The communication can either happen synchronously or asynchronously. When services communicate synchronously, there can be multiple reasons where things can break. For example −"
},
{
"code": null,
"e": 2256,
"s": 2132,
"text": "Callee service unavailable − The service which is being called is down for some reason, for example − bug, deployment, etc."
},
{
"code": null,
"e": 2380,
"s": 2256,
"text": "Callee service unavailable − The service which is being called is down for some reason, for example − bug, deployment, etc."
},
{
"code": null,
"e": 2560,
"s": 2380,
"text": "Callee service taking time to respond − The service which is being called can be slow due to high load or resource consumption or it is in the middle of initializing the services."
},
{
"code": null,
"e": 2740,
"s": 2560,
"text": "Callee service taking time to respond − The service which is being called can be slow due to high load or resource consumption or it is in the middle of initializing the services."
},
{
"code": null,
"e": 2984,
"s": 2740,
"text": "In either of the cases, it is waste of time and network resources for the caller to wait for the callee to respond. It makes more sense for the service to back off and give calls to the callee service after some time or share default response."
},
{
"code": null,
"e": 3130,
"s": 2984,
"text": "Netflix Hystrix, Resilince4j are two well-known circuit breakers which are used to handle such situations. In this tutorial, we will use Hystrix."
},
{
"code": null,
"e": 3367,
"s": 3130,
"text": "Let us use the case of Restaurant that we have been using earlier. Let us add hystrix dependency to our Restaurant Services which call the Customer Service. First, let us update the pom.xml of the service with the following dependency −"
},
{
"code": null,
"e": 3543,
"s": 3367,
"text": "<dependency>\n <groupId>org.springframework.cloud</groupId>\n <artifactId>spring-cloud-starter-netflix-hystrix</artifactId>\n <version>2.7.0.RELEASE</version>\n</dependency>"
},
{
"code": null,
"e": 3641,
"s": 3543,
"text": "And then, annotate our Spring application class with the correct annotation, i.e., @EnableHystrix"
},
{
"code": null,
"e": 4290,
"s": 3641,
"text": "package com.tutorialspoint;\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;\nimport org.springframework.cloud.client.discovery.EnableDiscoveryClient;\nimport org.springframework.cloud.netflix.hystrix.EnableHystrix;\nimport org.springframework.cloud.openfeign.EnableFeignClients;\n@SpringBootApplication\n@EnableFeignClients\n@EnableDiscoveryClient\n@EnableHystrix\npublic class RestaurantService{\n public static void main(String[] args) {\n SpringApplication.run(RestaurantService.class, args);\n }\n}"
},
{
"code": null,
"e": 4305,
"s": 4290,
"text": "Points to Note"
},
{
"code": null,
"e": 4423,
"s": 4305,
"text": "@ EnableDiscoveryClient and @EnableFeignCLient − We have already looked at these annotations in the previous chapter."
},
{
"code": null,
"e": 4541,
"s": 4423,
"text": "@ EnableDiscoveryClient and @EnableFeignCLient − We have already looked at these annotations in the previous chapter."
},
{
"code": null,
"e": 4663,
"s": 4541,
"text": "@EnableHystrix − This annotation scans our packages and looks out for methods which are using @HystrixCommand annotation."
},
{
"code": null,
"e": 4785,
"s": 4663,
"text": "@EnableHystrix − This annotation scans our packages and looks out for methods which are using @HystrixCommand annotation."
},
{
"code": null,
"e": 4932,
"s": 4785,
"text": "Once done, we will reuse the Feign client which we had defined for our customer service class earlier in the Restaurant service, no changes here −"
},
{
"code": null,
"e": 5319,
"s": 4932,
"text": "package com.tutorialspoint;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\n@FeignClient(name = \"customer-service\")\npublic interface CustomerService {\n @RequestMapping(\"/customer/{id}\")\n public Customer getCustomerById(@PathVariable(\"id\") Long id);\n}"
},
{
"code": null,
"e": 5466,
"s": 5319,
"text": "Now, let us define the service implementation class here which would use the Feign client. This would be a simple wrapper around the feign client."
},
{
"code": null,
"e": 6107,
"s": 5466,
"text": "package com.tutorialspoint;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;\n@Service\npublic class CustomerServiceImpl implements CustomerService {\n @Autowired\n CustomerService customerService;\n @HystrixCommand(fallbackMethod=\"defaultCustomerWithNYCity\")\n public Customer getCustomerById(Long id) {\n return customerService.getCustomerById(id);\n }\n // assume customer resides in NY city\n public Customer defaultCustomerWithNYCity(Long id) {\n return new Customer(id, null, \"NY\");\n }\n}"
},
{
"code": null,
"e": 6169,
"s": 6107,
"text": "Now, let us understand couple of points from the above code −"
},
{
"code": null,
"e": 6491,
"s": 6169,
"text": "HystrixCommand annotation − This is responsible for wrapping the function call that is getCustomerById and provide a proxy around it. The proxy then gives various hooks through which we can control our call to the customer service. For example, timing out the request,pooling of request, providing a fallback method, etc."
},
{
"code": null,
"e": 6813,
"s": 6491,
"text": "HystrixCommand annotation − This is responsible for wrapping the function call that is getCustomerById and provide a proxy around it. The proxy then gives various hooks through which we can control our call to the customer service. For example, timing out the request,pooling of request, providing a fallback method, etc."
},
{
"code": null,
"e": 7102,
"s": 6813,
"text": "Fallback method − We can specify the method we want to call when Hystrix determines that something is wrong with the callee. This method needs to have same signature as the method which is annotated. In our case, we have decided to provide the data back to our controller for the NY city."
},
{
"code": null,
"e": 7391,
"s": 7102,
"text": "Fallback method − We can specify the method we want to call when Hystrix determines that something is wrong with the callee. This method needs to have same signature as the method which is annotated. In our case, we have decided to provide the data back to our controller for the NY city."
},
{
"code": null,
"e": 7443,
"s": 7391,
"text": "Couple of useful options this annotation provides −"
},
{
"code": null,
"e": 7647,
"s": 7443,
"text": "Error threshold percent − Percentage of request allowed to fail before the circuit is tripped, that is, fallback methods are called. This can be controlled by using cicutiBreaker.errorThresholdPercentage"
},
{
"code": null,
"e": 7851,
"s": 7647,
"text": "Error threshold percent − Percentage of request allowed to fail before the circuit is tripped, that is, fallback methods are called. This can be controlled by using cicutiBreaker.errorThresholdPercentage"
},
{
"code": null,
"e": 8130,
"s": 7851,
"text": "Giving up on the network request after timeout − If the callee service, in our case Customer service, is slow, we can set the timeout after which we will drop the request and move to fallback method. This is controlled by setting execution.isolation.thread.timeoutInMilliseconds"
},
{
"code": null,
"e": 8409,
"s": 8130,
"text": "Giving up on the network request after timeout − If the callee service, in our case Customer service, is slow, we can set the timeout after which we will drop the request and move to fallback method. This is controlled by setting execution.isolation.thread.timeoutInMilliseconds"
},
{
"code": null,
"e": 8482,
"s": 8409,
"text": "And lastly, here is our controller which we call the CustomerServiceImpl"
},
{
"code": null,
"e": 9789,
"s": 8482,
"text": "package com.tutorialspoint;\nimport java.util.HashMap;\nimport java.util.List;\nimport java.util.stream.Collectors;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\nimport org.springframework.web.bind.annotation.RestController;\n@RestController\nclass RestaurantController {\n @Autowired\n CustomerServiceImpl customerService;\n static HashMap<Long, Restaurant> mockRestaurantData = new HashMap();\n static{\n mockRestaurantData.put(1L, new Restaurant(1, \"Pandas\", \"DC\"));\n mockRestaurantData.put(2L, new Restaurant(2, \"Indies\", \"SFO\"));\n mockRestaurantData.put(3L, new Restaurant(3, \"Little Italy\", \"DC\"));\n mockRestaurantData.put(3L, new Restaurant(4, \"Pizeeria\", \"NY\"));\n }\n @RequestMapping(\"/restaurant/customer/{id}\")\n public List<Restaurant> getRestaurantForCustomer(@PathVariable(\"id\") Long\nid)\n{\n System.out.println(\"Got request for customer with id: \" + id);\n String customerCity = customerService.getCustomerById(id).getCity();\n return mockRestaurantData.entrySet().stream().filter(\n entry -> entry.getValue().getCity().equals(customerCity))\n .map(entry -> entry.getValue())\n .collect(Collectors.toList());\n }\n}"
},
{
"code": null,
"e": 9913,
"s": 9789,
"text": "Now that we are done with the setup, let us give this a try. Just a bit background here, what we will do is the following −"
},
{
"code": null,
"e": 9937,
"s": 9913,
"text": "Start the Eureka Server"
},
{
"code": null,
"e": 9961,
"s": 9937,
"text": "Start the Eureka Server"
},
{
"code": null,
"e": 9988,
"s": 9961,
"text": "Start the Customer Service"
},
{
"code": null,
"e": 10015,
"s": 9988,
"text": "Start the Customer Service"
},
{
"code": null,
"e": 10089,
"s": 10015,
"text": "Start the Restaurant Service which will internally call Customer Service."
},
{
"code": null,
"e": 10163,
"s": 10089,
"text": "Start the Restaurant Service which will internally call Customer Service."
},
{
"code": null,
"e": 10202,
"s": 10163,
"text": "Make an API call to Restaurant Service"
},
{
"code": null,
"e": 10241,
"s": 10202,
"text": "Make an API call to Restaurant Service"
},
{
"code": null,
"e": 10272,
"s": 10241,
"text": "Shut down the Customer Service"
},
{
"code": null,
"e": 10303,
"s": 10272,
"text": "Shut down the Customer Service"
},
{
"code": null,
"e": 10456,
"s": 10303,
"text": "Make an API call to Restaurant Service. Given that Customer Service is down, it would cause failure and ultimately, the fallback method would be called."
},
{
"code": null,
"e": 10609,
"s": 10456,
"text": "Make an API call to Restaurant Service. Given that Customer Service is down, it would cause failure and ultimately, the fallback method would be called."
},
{
"code": null,
"e": 10697,
"s": 10609,
"text": "Let us now compile the Restaurant Service code and execute with the following command −"
},
{
"code": null,
"e": 10767,
"s": 10697,
"text": "java -Dapp_port=8082 -jar .\\target\\spring-cloud-feign-client-1.0.jar\n"
},
{
"code": null,
"e": 10927,
"s": 10767,
"text": "Also, start the Customer Service and the Eureka server. Note that there are no changes in these services and they remain same as seen in the previous chapters."
},
{
"code": null,
"e": 10991,
"s": 10927,
"text": "Now, let us try to find restaurant for Jane who is based in DC."
},
{
"code": null,
"e": 11042,
"s": 10991,
"text": "{\n \"id\": 1,\n \"name\": \"Jane\",\n \"city\": \"DC\"\n}"
},
{
"code": null,
"e": 11133,
"s": 11042,
"text": "For doing that, we will hit the following URL: http://localhost:8082/restaurant/customer/1"
},
{
"code": null,
"e": 11280,
"s": 11133,
"text": "[\n {\n \"id\": 1,\n \"name\": \"Pandas\",\n \"city\": \"DC\"\n },\n {\n \"id\": 3,\n \"name\": \"Little Italy\",\n \"city\": \"DC\"\n }\n]"
},
{
"code": null,
"e": 11497,
"s": 11280,
"text": "So, nothing new here, we got the restaurants which are in DC. Now, let's move to the interesting part which is shutting down the Customer service. You can do that either by hitting Ctrl+C or simply killing the shell."
},
{
"code": null,
"e": 11577,
"s": 11497,
"text": "Now let us hit the same URL again − http://localhost:8082/restaurant/customer/1"
},
{
"code": null,
"e": 11632,
"s": 11577,
"text": "{\n \"id\": 4,\n \"name\": \"Pizzeria\",\n \"city\": \"NY\"\n}"
},
{
"code": null,
"e": 11909,
"s": 11632,
"text": "As is visible from the output, we have got the restaurants from NY, although our customer is from DC.This is because our fallback method returned a dummy customer who is situated in NY. Although, not useful, the above example displays that the fallback was called as expected."
},
{
"code": null,
"e": 12093,
"s": 11909,
"text": "To make the above method more useful, we can integrate caching when using Hystrix. This can be a useful pattern to provide better answers when the underlying service is not available."
},
{
"code": null,
"e": 12147,
"s": 12093,
"text": "First, let us create a cached version of the service."
},
{
"code": null,
"e": 13017,
"s": 12147,
"text": "package com.tutorialspoint;\nimport java.util.HashMap;\nimport java.util.Map;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.stereotype.Service;\nimport com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;\n@Service\npublic class CustomerServiceCachedFallback implements CustomerService {\n Map<Long, Customer> cachedCustomer = new HashMap<>();\n @Autowired\n CustomerService customerService;\n @HystrixCommand(fallbackMethod=\"defaultToCachedData\")\n public Customer getCustomerById(Long id) {\n Customer customer = customerService.getCustomerById(id);\n // cache value for future reference\n cachedCustomer.put(customer.getId(), customer);\n return customer;\n }\n // get customer data from local cache\n public Customer defaultToCachedData(Long id) {\n return cachedCustomer.get(id);\n }\n}"
},
{
"code": null,
"e": 13212,
"s": 13017,
"text": "We are using hashMap as the storage to cache the data. This for developmental purpose. In Production environment, we may want to use better caching solutions, for example, Redis, Hazelcast, etc."
},
{
"code": null,
"e": 13294,
"s": 13212,
"text": "Now, we just need to update one line in the controller to use the above service −"
},
{
"code": null,
"e": 13484,
"s": 13294,
"text": "@RestController\nclass RestaurantController {\n @Autowired\n CustomerServiceCachedFallback customerService;\n static HashMap<Long, Restaurant> mockRestaurantData = new HashMap();\n ...\n}"
},
{
"code": null,
"e": 13525,
"s": 13484,
"text": "We will follow the same steps as above −"
},
{
"code": null,
"e": 13550,
"s": 13525,
"text": "Start the Eureka Server."
},
{
"code": null,
"e": 13575,
"s": 13550,
"text": "Start the Eureka Server."
},
{
"code": null,
"e": 13603,
"s": 13575,
"text": "Start the Customer Service."
},
{
"code": null,
"e": 13631,
"s": 13603,
"text": "Start the Customer Service."
},
{
"code": null,
"e": 13700,
"s": 13631,
"text": "Start the Restaurant Service which internally call Customer Service."
},
{
"code": null,
"e": 13769,
"s": 13700,
"text": "Start the Restaurant Service which internally call Customer Service."
},
{
"code": null,
"e": 13813,
"s": 13769,
"text": "Make an API call to the Restaurant Service."
},
{
"code": null,
"e": 13857,
"s": 13813,
"text": "Make an API call to the Restaurant Service."
},
{
"code": null,
"e": 13889,
"s": 13857,
"text": "Shut down the Customer Service."
},
{
"code": null,
"e": 13921,
"s": 13889,
"text": "Shut down the Customer Service."
},
{
"code": null,
"e": 14058,
"s": 13921,
"text": "Make an API call to the Restaurant Service. Given that Customer Service is down but the data is cached, we will get a valid set of data."
},
{
"code": null,
"e": 14195,
"s": 14058,
"text": "Make an API call to the Restaurant Service. Given that Customer Service is down but the data is cached, we will get a valid set of data."
},
{
"code": null,
"e": 14244,
"s": 14195,
"text": "Now, let us follow the same process till step 3."
},
{
"code": null,
"e": 14305,
"s": 14244,
"text": "Now hit the URL: http://localhost:8082/restaurant/customer/1"
},
{
"code": null,
"e": 14452,
"s": 14305,
"text": "[\n {\n \"id\": 1,\n \"name\": \"Pandas\",\n \"city\": \"DC\"\n },\n {\n \"id\": 3,\n \"name\": \"Little Italy\",\n \"city\": \"DC\"\n }\n]"
},
{
"code": null,
"e": 14670,
"s": 14452,
"text": "So, nothing new here, we got the restaurants which are in DC. Now, let us move to the interesting part which is shutting down the Customer service. You can do that either by hitting Ctrl+C or simply killing the shell."
},
{
"code": null,
"e": 14750,
"s": 14670,
"text": "Now let us hit the same URL again − http://localhost:8082/restaurant/customer/1"
},
{
"code": null,
"e": 14897,
"s": 14750,
"text": "[\n {\n \"id\": 1,\n \"name\": \"Pandas\",\n \"city\": \"DC\"\n },\n {\n \"id\": 3,\n \"name\": \"Little Italy\",\n \"city\": \"DC\"\n }\n]"
},
{
"code": null,
"e": 15085,
"s": 14897,
"text": "As is visible from the output, we have got the restaurants from DC which is what we expect as our customer is from DC. This is because our fallback method returned a cached customer data."
},
{
"code": null,
"e": 15454,
"s": 15085,
"text": "We saw how to use @HystrixCommand annotation to trip the circuit and provide a fallback. But we had to additionally define a Service class to wrap our Hystrix client. However, we can also achieve the same by simply passing correct arguments to Feign client. Let us try to do that. For that, first update our Feign client for CustomerService by adding a fallback class."
},
{
"code": null,
"e": 15875,
"s": 15454,
"text": "package com.tutorialspoint;\nimport org.springframework.cloud.openfeign.FeignClient;\nimport org.springframework.web.bind.annotation.PathVariable;\nimport org.springframework.web.bind.annotation.RequestMapping;\n@FeignClient(name = \"customer-service\", fallback = FallBackHystrix.class)\npublic interface CustomerService {\n @RequestMapping(\"/customer/{id}\")\n public Customer getCustomerById(@PathVariable(\"id\") Long id);\n}"
},
{
"code": null,
"e": 15989,
"s": 15875,
"text": "Now, let us add the fallback class for the Feign client which will be called when the Hystrix circuit is tripped."
},
{
"code": null,
"e": 16293,
"s": 15989,
"text": "package com.tutorialspoint;\nimport org.springframework.stereotype.Component;\n@Component\npublic class FallBackHystrix implements CustomerService{\n @Override\n public Customer getCustomerById(Long id) {\n System.out.println(\"Fallback called....\");\n return new Customer(0, \"Temp\", \"NY\");\n }\n}"
},
{
"code": null,
"e": 16371,
"s": 16293,
"text": "Lastly, we also need to create the application-circuit.yml to enable hystrix."
},
{
"code": null,
"e": 16589,
"s": 16371,
"text": "spring:\n application:\n name: restaurant-service\nserver:\n port: ${app_port}\neureka:\n client:\n serviceURL:\n defaultZone: http://localhost:8900/eureka\nfeign:\n circuitbreaker:\n enabled: true"
},
{
"code": null,
"e": 16675,
"s": 16589,
"text": "Now, that we have the setup ready, let us test this out. We will follow these steps −"
},
{
"code": null,
"e": 16700,
"s": 16675,
"text": "Start the Eureka Server."
},
{
"code": null,
"e": 16725,
"s": 16700,
"text": "Start the Eureka Server."
},
{
"code": null,
"e": 16763,
"s": 16725,
"text": "We do not start the Customer Service."
},
{
"code": null,
"e": 16801,
"s": 16763,
"text": "We do not start the Customer Service."
},
{
"code": null,
"e": 16875,
"s": 16801,
"text": "Start the Restaurant Service which will internally call Customer Service."
},
{
"code": null,
"e": 16949,
"s": 16875,
"text": "Start the Restaurant Service which will internally call Customer Service."
},
{
"code": null,
"e": 17055,
"s": 16949,
"text": "Make an API call to Restaurant Service. Given that Customer Service is down, we will notice the fallback."
},
{
"code": null,
"e": 17161,
"s": 17055,
"text": "Make an API call to Restaurant Service. Given that Customer Service is down, we will notice the fallback."
},
{
"code": null,
"e": 17278,
"s": 17161,
"text": "Assuming 1st step is already done, let's move to step 3. Let us compile the code and execute the following command −"
},
{
"code": null,
"e": 17408,
"s": 17278,
"text": "java -Dapp_port=8082 -jar .\\target\\spring-cloud-feign-client-1.0.jar --\nspring.config.location=classpath:application-circuit.yml\n"
},
{
"code": null,
"e": 17476,
"s": 17408,
"text": "Let us now try to hit − http://localhost:8082/restaurant/customer/1"
},
{
"code": null,
"e": 17647,
"s": 17476,
"text": "As we have not started Customer Service, fallback would be called and the fallback sends over NY as the city, which is why, we see NY restaurants in the following output."
},
{
"code": null,
"e": 17703,
"s": 17647,
"text": "{\n \"id\": 4,\n \"name\": \"Pizzeria\",\n \"city\": \"NY\"\n}\n"
},
{
"code": null,
"e": 17749,
"s": 17703,
"text": "Also, to confirm, in the logs, we would see −"
},
{
"code": null,
"e": 18070,
"s": 17749,
"text": "....\n2021-03-13 16:27:02.887 WARN 21228 --- [reakerFactory-1]\n.s.c.o.l.FeignBlockingLoadBalancerClient : Load balancer does not contain an\ninstance for the service customer-service\nFallback called....\n2021-03-13 16:27:03.802 INFO 21228 --- [ main]\no.s.cloud.commons.util.InetUtils : Cannot determine local hostname\n....."
},
{
"code": null,
"e": 18104,
"s": 18070,
"text": "\n 102 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 18118,
"s": 18104,
"text": " Karthikeya T"
},
{
"code": null,
"e": 18151,
"s": 18118,
"text": "\n 39 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 18166,
"s": 18151,
"text": " Chaand Sheikh"
},
{
"code": null,
"e": 18201,
"s": 18166,
"text": "\n 73 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 18213,
"s": 18201,
"text": " Senol Atac"
},
{
"code": null,
"e": 18248,
"s": 18213,
"text": "\n 62 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 18260,
"s": 18248,
"text": " Senol Atac"
},
{
"code": null,
"e": 18295,
"s": 18260,
"text": "\n 67 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 18307,
"s": 18295,
"text": " Senol Atac"
},
{
"code": null,
"e": 18340,
"s": 18307,
"text": "\n 69 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 18352,
"s": 18340,
"text": " Senol Atac"
},
{
"code": null,
"e": 18359,
"s": 18352,
"text": " Print"
},
{
"code": null,
"e": 18370,
"s": 18359,
"text": " Add Notes"
}
] |
How to call an activity method from a fragment in Android App?
|
This example demonstrates how do I call an activity method from a fragment in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<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:padding="8dp"
tools:context=".MainActivity">
<FrameLayout
android:id="@+id/frameLayout"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import android.os.Bundle;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.replace(R.id.frameLayout, new SampleFragment()).commit();
}
public void FragmentMethod() {
Toast.makeText(MainActivity.this, "Method called From Fragment", Toast.LENGTH_LONG).show();
}
}
Step 4 − Create a new Fragment Activity and add the following codes −
SampleFragment.java −
import android.os.Bundle;
import androidx.fragment.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class SampleFragment extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_sample, container, false);
((MainActivity) getActivity()).FragmentMethod();
return view;
}
}
fragment_sample.xml −
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".SampleFragment">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Calling a simple method from Fragment"
android:textAlignment="center"
android:textSize="24sp"
android:textStyle="bold" />
</RelativeLayout>
Step 5 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<categoryandroid: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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1149,
"s": 1062,
"text": "This example demonstrates how do I call an activity method from a fragment in android."
},
{
"code": null,
"e": 1278,
"s": 1149,
"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": 1343,
"s": 1278,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1803,
"s": 1343,
"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:padding=\"8dp\"\n tools:context=\".MainActivity\">\n <FrameLayout\n android:id=\"@+id/frameLayout\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 1860,
"s": 1803,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2652,
"s": 1860,
"text": "import androidx.appcompat.app.AppCompatActivity;\nimport androidx.fragment.app.FragmentManager;\nimport androidx.fragment.app.FragmentTransaction;\nimport android.os.Bundle;\nimport android.widget.Toast;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n FragmentManager fragmentManager = getSupportFragmentManager();\n FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();\n fragmentTransaction.replace(R.id.frameLayout, new SampleFragment()).commit();\n }\n public void FragmentMethod() {\n Toast.makeText(MainActivity.this, \"Method called From Fragment\", Toast.LENGTH_LONG).show();\n }\n}"
},
{
"code": null,
"e": 2722,
"s": 2652,
"text": "Step 4 − Create a new Fragment Activity and add the following codes −"
},
{
"code": null,
"e": 2744,
"s": 2722,
"text": "SampleFragment.java −"
},
{
"code": null,
"e": 3226,
"s": 2744,
"text": "import android.os.Bundle;\nimport androidx.fragment.app.Fragment;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\npublic class SampleFragment extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n View view = inflater.inflate(R.layout.fragment_sample, container, false);\n ((MainActivity) getActivity()).FragmentMethod();\n return view;\n }\n}"
},
{
"code": null,
"e": 3248,
"s": 3226,
"text": "fragment_sample.xml −"
},
{
"code": null,
"e": 3803,
"s": 3248,
"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 tools:context=\".SampleFragment\">\n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Calling a simple method from Fragment\"\n android:textAlignment=\"center\"\n android:textSize=\"24sp\"\n android:textStyle=\"bold\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 3858,
"s": 3803,
"text": "Step 5 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 4530,
"s": 3858,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <categoryandroid:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 4881,
"s": 4530,
"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 the android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 4922,
"s": 4881,
"text": "Click here to download the project code."
}
] |
DivideByZeroException Class in C#
|
C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes.
System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero.
Live Demo
using System;
namespace ErrorHandlingApplication {
class DivNumbers {
int result;
DivNumbers() {
result = 0;
}
public void division(int num1, int num2) {
try {
result = num1 / num2;
} catch (DivideByZeroException e) {
Console.WriteLine("Exception caught: {0}", e);
} finally {
Console.WriteLine("Result: {0}", result);
}
}
static void Main(string[] args) {
DivNumbers d = new DivNumbers();
d.division(25, 0);
Console.ReadKey();
}
}
}
Exception caught: System.DivideByZeroException: Attempted to divide by zero.
at ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in <a9b37148b4814c1a849bf4ee94fbe889>:0
Result: 0
|
[
{
"code": null,
"e": 1349,
"s": 1062,
"text": "C# exceptions are represented by classes. The exception classes in C# are mainly directly or indirectly derived from the System.Exception class. Some of the exception classes derived from the System.Exception class are the System.ApplicationException and System.SystemException classes."
},
{
"code": null,
"e": 1455,
"s": 1349,
"text": "System.DivideByZeroException is a class that handles errors generated from dividing a dividend with zero."
},
{
"code": null,
"e": 1466,
"s": 1455,
"text": " Live Demo"
},
{
"code": null,
"e": 2056,
"s": 1466,
"text": "using System;\nnamespace ErrorHandlingApplication {\n class DivNumbers {\n int result;\n DivNumbers() {\n result = 0;\n }\n public void division(int num1, int num2) {\n try {\n result = num1 / num2;\n } catch (DivideByZeroException e) {\n Console.WriteLine(\"Exception caught: {0}\", e);\n } finally {\n Console.WriteLine(\"Result: {0}\", result);\n }\n }\n static void Main(string[] args) {\n DivNumbers d = new DivNumbers();\n d.division(25, 0);\n Console.ReadKey();\n }\n }\n}"
},
{
"code": null,
"e": 2280,
"s": 2056,
"text": "Exception caught: System.DivideByZeroException: Attempted to divide by zero.\nat ErrorHandlingApplication.DivNumbers.division (System.Int32 num1, System.Int32 num2) [0x00000] in <a9b37148b4814c1a849bf4ee94fbe889>:0\nResult: 0"
}
] |
Python Program to accept string ending with alphanumeric character
|
When it is required to check if a string ends with an alphanumeric character or not, the regular expression is used. A method is defined that checks to see an alphanumeric characters, and returns the string as output.
Below is a demonstration of the same
import re
regex_expression = '[a-zA-z0-9]$'
def check_string(my_string):
if(re.search(regex_expression, my_string)):
print("The string ends with alphanumeric character")
else:
print("The string doesnot end with alphanumeric character")
my_string_1 = "Python@"
print("The string is :")
print(my_string_1)
check_string(my_string_1)
my_string_2 = "Python1245"
print("\nThe string is :")
print(my_string_2)
check_string(my_string_2)
The string is :
Python@
The string doesn’t end with alphanumeric character
The string is :
Python1245
The string ends with alphanumeric character
The required packages are imported.
The required packages are imported.
A regular expression string is defined.
A regular expression string is defined.
A method named ‘check_string’ is defined, and it takes the string as a parameter.
A method named ‘check_string’ is defined, and it takes the string as a parameter.
The ‘search’ method is called and checked to see if a string ends with a specific character.
The ‘search’ method is called and checked to see if a string ends with a specific character.
Outside the method, the string is defined and displayed on the console.
Outside the method, the string is defined and displayed on the console.
The method is called by passing this string.
The method is called by passing this string.
The output is displayed on the console.
The output is displayed on the console.
|
[
{
"code": null,
"e": 1280,
"s": 1062,
"text": "When it is required to check if a string ends with an alphanumeric character or not, the regular expression is used. A method is defined that checks to see an alphanumeric characters, and returns the string as output."
},
{
"code": null,
"e": 1317,
"s": 1280,
"text": "Below is a demonstration of the same"
},
{
"code": null,
"e": 1771,
"s": 1317,
"text": "import re\n\nregex_expression = '[a-zA-z0-9]$'\n\ndef check_string(my_string):\n\n if(re.search(regex_expression, my_string)):\n print(\"The string ends with alphanumeric character\")\n\n else:\n print(\"The string doesnot end with alphanumeric character\")\n\n\nmy_string_1 = \"Python@\"\nprint(\"The string is :\")\nprint(my_string_1)\ncheck_string(my_string_1)\n\nmy_string_2 = \"Python1245\"\nprint(\"\\nThe string is :\")\nprint(my_string_2)\ncheck_string(my_string_2)"
},
{
"code": null,
"e": 1917,
"s": 1771,
"text": "The string is :\nPython@\nThe string doesn’t end with alphanumeric character\nThe string is :\nPython1245\nThe string ends with alphanumeric character"
},
{
"code": null,
"e": 1953,
"s": 1917,
"text": "The required packages are imported."
},
{
"code": null,
"e": 1989,
"s": 1953,
"text": "The required packages are imported."
},
{
"code": null,
"e": 2029,
"s": 1989,
"text": "A regular expression string is defined."
},
{
"code": null,
"e": 2069,
"s": 2029,
"text": "A regular expression string is defined."
},
{
"code": null,
"e": 2151,
"s": 2069,
"text": "A method named ‘check_string’ is defined, and it takes the string as a parameter."
},
{
"code": null,
"e": 2233,
"s": 2151,
"text": "A method named ‘check_string’ is defined, and it takes the string as a parameter."
},
{
"code": null,
"e": 2326,
"s": 2233,
"text": "The ‘search’ method is called and checked to see if a string ends with a specific character."
},
{
"code": null,
"e": 2419,
"s": 2326,
"text": "The ‘search’ method is called and checked to see if a string ends with a specific character."
},
{
"code": null,
"e": 2491,
"s": 2419,
"text": "Outside the method, the string is defined and displayed on the console."
},
{
"code": null,
"e": 2563,
"s": 2491,
"text": "Outside the method, the string is defined and displayed on the console."
},
{
"code": null,
"e": 2608,
"s": 2563,
"text": "The method is called by passing this string."
},
{
"code": null,
"e": 2653,
"s": 2608,
"text": "The method is called by passing this string."
},
{
"code": null,
"e": 2693,
"s": 2653,
"text": "The output is displayed on the console."
},
{
"code": null,
"e": 2733,
"s": 2693,
"text": "The output is displayed on the console."
}
] |
One Shot Learning with Siamese Networks using Keras | by Harshall Lamba | Towards Data Science
|
IntroductionPrerequisitesClassification vs One Shot LearningApplicationsOmniglot DatasetLoading the datasetMapping the problem to binary classification taskModel Architecture and TrainingValidating the ModelBaseline 1 — Nearest Neighbor ModelBaseline 2 — Random ModelTest Results and InferenceConclusionReferences
Introduction
Prerequisites
Classification vs One Shot Learning
Applications
Omniglot Dataset
Loading the dataset
Mapping the problem to binary classification task
Model Architecture and Training
Validating the Model
Baseline 1 — Nearest Neighbor Model
Baseline 2 — Random Model
Test Results and Inference
Conclusion
References
Deep Convolutional Neural Networks have become the state of the art methods for image classification tasks. However, one of the biggest limitations is they require a lots of labelled data. In many applications, collecting this much data is sometimes not feasible. One Shot Learning aims to solve this problem.
In this post, I will assume that you are already familiar with the basics of machine learning and you have some experience on using Convolutional Neural Networks for image classification using Python and Keras.
In case of standard classification, the input image is fed into a series of layers, and finally at the output we generate a probability distribution over all the classes (typically using a Softmax). For example, if we are trying to classify an image as cat or dog or horse or elephant, then for every input image, we generate 4 probabilities, indicating the probability of the image belonging to each of the 4 classes. Two important points must be noticed here. First, during the training process, we require a large number of images for each of the class (cats, dogs, horses and elephants). Second, if the network is trained only on the above 4 classes of images, then we cannot expect to test it on any other class, example “zebra”. If we want our model to classify the images of zebra as well, then we need to first get a lot of zebra images and then we must re-train the model again. There are applications wherein we neither have enough data for each class and the total number classes is huge as well as dynamically changing. Thus, the cost of data collection and periodical re-training is too high.
On the other hand, in a one shot classification, we require only one training example for each class. Yes you got that right, just one. Hence the name One Shot. Let’s try to understand with a real world practical example.
Assume that we want to build face recognition system for a small organization with only 10 employees (small numbers keep things simple). Using a traditional classification approach, we might come up with a system that looks as below:
Problems:
a) To train such a system, we first require a lot of different images of each of the 10 persons in the organization which might not be feasible. (Imagine if you are doing this for an organization with thousands of employees).
b) What if a new person joins or leaves the organization? You need to take the pain of collecting data again and re-train the entire model again. This is practically not possible specially for large organizations where recruitment and attrition is happening almost every week.
Now let’s understand how do we approach this problem using one shot classification which helps to solve both of the above issues:
Instead of directly classifying an input(test) image to one of the 10 people in the organization, this network instead takes an extra reference image of the person as input and will produce a similarity score denoting the chances that the two input images belong to the same person. Typically the similarity score is squished between 0 and 1 using a sigmoid function; wherein 0 denotes no similarity and 1 denotes full similarity. Any number between 0 and 1 is interpreted accordingly.
Notice that this network is not learning to classify an image directly to any of the output classes. Rather, it is learning a similarity function, which takes two images as input and expresses how similar they are.
How does this solve the two problems we discussed above?
a) In a short while we will see that to train this network, you do not require too many instances of a class and only few are enough to build a good model.
b) But the biggest advantage is that , let’s say in case of face recognition, we have a new employee who has joined the organization. Now in order for the network to detect his face, we only require a single image of his face which will be stored in the database. Using this as the reference image, the network will calculate the similarity for any new instance presented to it. Thus we say that network predicts the score in one shot.
Don’t worry if the above details seem a bit abstract at the moment, just continue ahead and we will solve a problem in full detail and I promise you will develop an in-depth understanding of the subject matter.
Before we proceed, I would like to mention a few applications of one shot learning in order to motivate you so that you develop more keen interest in understanding this technology.
a. As I have already mentioned about face recognition above, just go to this link wherein the AI Guru Andrew Ng demonstrates how Baidu (the Chinese Search Giant) has developed a face recognition system for the employees in their organization.
b. Read this blog to understand how one shot learning is applied to drug discovery where data is very scarce.
c. In this paper, the authors have used one shot learning to build an offline signature verification system which is very useful for Banks and other Government and also private institutions.
For the purpose of this blog, we will use the Omniglot dataset which is a collection of 1623 hand drawn characters from 50 different alphabets. For every character there are just 20 examples, each drawn by a different person. Each image is a gray scale image of resolution 105x105.
Before I continue, I would like to clarify the difference between a character and an alphabet. In case of English the set A to Z is called as the alphabet while each of the letter A, B, etc. is called a character. Thus we say that the English alphabet contains 26 characters (or letters).
So I hope this clarifies the point when I say 1623 characters spanning over 50 different alphabets.
Let’s look at some images of characters from different alphabets to get a better feel of the dataset.
Thus we have 1623 different classes(each character can be treated as a separate class) and for each class we have only 20 images. Clearly, if we try to solve this problem using the traditional image classification method then definitely we won’t be able to build a good generalized model. And with such less number of images available for each class, the model will easily overfit.
You can download the dataset by cloning this GitHub repository. The folder named “Python” contains two zip files: images_background.zip and images_evaluation.zip. Just unzip these two files.
images_background folder contains characters from 30 alphabets and will be used to train the model, while images_evaluation folder contains characters from the other 20 alphabets which we will use to test our system.
Once you unzip the files, you will see below folders (alphabets) in the images_background folder(used for training purpose):
And you will see below folders (alphabets) in the images_evaluation folder (used for testing purpose):
Notice that we will train the system on one set of characters and then test it on a completely different set of characters which were never used during the training. This is not possible in a traditional classification cycle.
First we need to load the images into tensors and later use these tensors to provide data in batches to the model.
We use below function to load images into tensors:
To call this function as follows, pass the path of the train directory as the parameter as follows:
X,y,c = loadimgs(train_folder)
The function returns a tuple of 3 variables. I won’t go through each line of the code, but I will provide you some intuition what exactly the function is doing by understanding the values it returns. Given this explanation you should be in a good position to understand the above function, once you go through it.
Let’s understand what is present in ‘X’:
X.shape(964, 20, 105, 105)
This means we have 964 characters (or letters or categories) spanning across 30 different alphabets. For each of this character, we have 20 images, and each image is a gray scale image of resolution 105x105. Hence the shape (964, 20, 105, 105).
Let’s now understand how the labels ‘y’ are populated:
y.shape(19280, 1)
Total number of images = 964 * 20 = 19280. All the images for one letter have the same label., i.e. The first 20 images have the label 0, the next 20 have the label 1, and so on, ... the last 20 images have the label 963.
Finally the last variable ‘c’ stands for categories and it is a dictionary as follows:
c.keys() # 'c' for categoriesdict_keys(['Alphabet_of_the_Magi', 'Anglo-Saxon_Futhorc', 'Arcadian', 'Armenian', 'Asomtavruli_(Georgian)', 'Balinese', 'Bengali', 'Blackfoot_(Canadian_Aboriginal_Syllabics)', 'Braille', 'Burmese_(Myanmar)', 'Cyrillic', 'Early_Aramaic', 'Futurama', 'Grantha', 'Greek', 'Gujarati', 'Hebrew', 'Inuktitut_(Canadian_Aboriginal_Syllabics)', 'Japanese_(hiragana)', 'Japanese_(katakana)', 'Korean', 'Latin', 'Malay_(Jawi_-_Arabic)', 'Mkhedruli_(Georgian)', 'N_Ko', 'Ojibwe_(Canadian_Aboriginal_Syllabics)', 'Sanskrit', 'Syriac_(Estrangelo)', 'Tagalog', 'Tifinagh'])c['Alphabet_of_the_Magi'][0, 19]c['Anglo-Saxon_Futhorc'][20, 48]
Since there are 30 different alphabets, this dictionary ‘c’ contains 30 items. The key for each item is the name of the alphabet. The value for each item is a list of two numbers: [low, high], where ‘low’ is the label of the first character in that alphabet and ‘high’ is the label of the last character in that alphabet.
Once we load the train and test images, we save the tensors on the disk in a pickle file, so that we can utilize them later directly without having to load the images again.
Let’s understand how can we map this problem into a supervised learning task where our dataset contains pairs of (Xi, Yi) where ‘Xi’ is the input and ‘Yi’ is the output.
Recall that the input to our system will be a pair of images and the output will be a similarity score between 0 and 1.
Xi = Pair of images
Yi = 1 ; if both images contain the same character
Yi = 0; if both images contain different characters
Let’s have a better understanding by visualizing the dataset below:
Thus we need to create pairs of images along with the target variable, as shown above, to be fed as input to the Siamese Network. Note that even though characters from Sanskrit alphabet are shown above, but in practice we will generate pairs randomly from all the alphabets in the training data.
The code to generate these pairs and targets is shown below:
We need to call the above function by passing the batch_size and it will return “batch_size” number of image pairs along with their target variables.
We will use the below generator function to generate data in batches during the training of the network.
This code is an implementation of the methodology described in this research paper by Gregory Koch et al. Model architecture and hyper-parameters that I have used are all as described in the paper.
Let’s first understand the architecture on a high level before diving into the details. Below I present an intuition of the architecture.
Intuition: The term Siamese means twins. The two Convolutional Neural Networks shown above are not different networks but are two copies of the same network, hence the name Siamese Networks. Basically they share the same parameters. The two input images (x1 and x2) are passed through the ConvNet to generate a fixed length feature vector for each (h(x1) and h(x2)). Assuming the neural network model is trained properly, we can make the following hypothesis: If the two input images belong to the same character, then their feature vectors must also be similar, while if the two input images belong to the different characters, then their feature vectors will also be different. Thus the element-wise absolute difference between the two feature vectors must be very different in both the above cases. And hence the similarity score generated by the output sigmoid layer must also be different in these two cases. This is the central idea behind the Siamese Networks.
Given the above intuition let’s look at the picture of the architecture with more finer details taken from the research paper itself:
The below function is used to create the model architecture:
Notice that there is no predefined layer in Keras to compute the absolute difference between two tensors. We do this using the Lambda layer in Keras which is used to add customized layers in Keras.
To understand the shape of the tensors passed at different layers, refer the below image generated using the plot_model utility of Keras.
The model was compiled using the adam optimizer and binary cross entropy loss function as shown below. Learning rate was kept low as it was found that with high learning rate, the model took a lot of time to converge. However these parameters can well be tuned further to improve the present settings.
optimizer = Adam(lr = 0.00006)model.compile(loss="binary_crossentropy",optimizer=optimizer)
The model was trained for 20000 iterations with batch size of 32.
After every 200 iterations, model validation was done using 20-way one shot learning and the accuracy was calculated over 250 trials. This concept is explained in the next section.
Now that we have understood how to prepare the data for training, model architecture and training; it’s time we must think about a strategy to validate and test our model.
Note that, for every pair of input images, our model generates a similarity score between 0 and 1. But just looking at the score its difficult to ascertain whether the model is really able to recognize similar characters and distinguish dissimilar ones.
A nice way to judge the model is N-way one shot learning. Don’t worry, it’s much easier than what it sounds to be.
An example of 4-way one shot learning:
We create a dataset of 4 pairs of images as follows:
Basically the same character is compared to 4 different characters out of which only one of them matches the original character. Let’s say by doing the above 4 comparisons we get 4 similarity scores S1, S2, S3 and S4 as shown. Now if the model is trained properly, we expect that S1 is the maximum of all the 4 similarity scores because the first pair of images is the only one where we have two same characters.
Thus if S1 happens to be the maximum score, we treat this as a correct prediction otherwise we consider this as an incorrect prediction. Repeating this procedure ‘k’ times, we can calculate the percentage of correct predictions as follows:
percent_correct = (100 * n_correct) / k
where k => total no. of trials and n_correct => no. of correct predictions out of k trials.
Similarly a 9-way one shot learning will look as follows:
A 16-way one shot leaning will be as shown below:
Below is how a 25-way one shot learning would look like:
Note that the value of ’N’ in N-way one shot learning need not necessarily be a perfect square. The reason for me taking values 4, 9, 16 and 25 was because it just looks good for presentation when the square is filled completely.
It’s quite obvious that smaller values of ’N’ will lead to more correct predictions and larger values of ’N’ will lead to relatively less correct predictions when repeated multiple times.
Just a reminder again: All the examples shown above are from the Sanskrit Alphabet but in practice we will generate the test image and the support set randomly from all the alphabets of the test/validation dataset images.
The code to generate the test image along with the support set is as follows:
It is always a good practice to create simple baseline models and compare their results with complex model you are trying to build.
Our first baseline model is the Nearest Neighbor approach. If you are familiar with K-Nearest Neighbor algorithm, then this is just the same thing.
As discussed above, in an N-way one shot learning, we compare a test image with N different images and select that image which has highest similarity with the test image as the prediction.
This is intuitively similar to the KNN with K=1. Let’s understand in detail how this approach works.
You might have studied how we can compute the L2 distance (also called as the Euclidean distance) between two vectors. If you do not recall, below is how it is done:
Let’s say we compare L2 distance of a vector X with 3 other vectors say A, B and C. Then one way to compute the most similar vector to X is check which vector has the least L2 distance with X. Because distance is inversely proportional to similarity. Thus for example if the L2 distance between X and B is minimum, we say that the similarity between X and B is maximum.
However, in our case we do not have vectors but gray scale images, which can be represented as matrices and not vectors. Then how do we compute L2 distance between matrices?
That’s simple, just flatten the matrices into vectors and then compute the L2 distance between these vectors. For example:
Thus in N-way One Shot learning, we compare the L2 distance of the test image with all the images in the Support Set. Then we check the character for which we got the minimum L2 distance. If this character is the same as the character in the test image, then the prediction is correct, else the prediction is incorrect. For example:
Similar to N way one shot learning, we repeat this for multiple trials and compute the average prediction score over all the trials. The code for nearest neighbor approach is below:
Creating a random model which makes prediction at random is a very common technique to make sure that the model we created is at least better than a model which makes completely random predictions. It’s working can be summarized in the below diagram:
The N-way testing was done for N = 1, 3, 5, ...., 19.
For each N-way testing, 50 trials were performed and the average accuracy was computed over these 50 trials.
Below is the comparison between the 4 models:
Inference: Clearly the Siamese Model performed much better than the Random Model and the Nearest Neighbor Model. However there is some gap between the results on training set and validation set which indicate that model is over fitting.
This is just a first cut solution and many of the hyper parameters can be tuned in order to avoid over fitting. Also more rigorous testing can be done by increasing the value of ’N’ in N-way testing and by increasing the number of trials.
I hope this helped you in understanding the one shot learning methodology using Deep Learning.
Source Code: Please refer my source code in Jupyter Notebook on my GitHub Repository here.
Note: The model was trained on Cloud with a P4000 GPU. If you train it on a CPU, then you need to be very patient.
Comments, suggestions, criticism are welcomed. Thanks.
a. https://github.com/akshaysharma096/Siamese-Networks
b. https://sorenbouma.github.io/blog/oneshot/
c. https://www.cs.cmu.edu/~rsalakhu/papers/oneshot1.pdf
d. Andrew Ng’s deeplearning.ai Specialization Course on Coursera
|
[
{
"code": null,
"e": 486,
"s": 172,
"text": "IntroductionPrerequisitesClassification vs One Shot LearningApplicationsOmniglot DatasetLoading the datasetMapping the problem to binary classification taskModel Architecture and TrainingValidating the ModelBaseline 1 — Nearest Neighbor ModelBaseline 2 — Random ModelTest Results and InferenceConclusionReferences"
},
{
"code": null,
"e": 499,
"s": 486,
"text": "Introduction"
},
{
"code": null,
"e": 513,
"s": 499,
"text": "Prerequisites"
},
{
"code": null,
"e": 549,
"s": 513,
"text": "Classification vs One Shot Learning"
},
{
"code": null,
"e": 562,
"s": 549,
"text": "Applications"
},
{
"code": null,
"e": 579,
"s": 562,
"text": "Omniglot Dataset"
},
{
"code": null,
"e": 599,
"s": 579,
"text": "Loading the dataset"
},
{
"code": null,
"e": 649,
"s": 599,
"text": "Mapping the problem to binary classification task"
},
{
"code": null,
"e": 681,
"s": 649,
"text": "Model Architecture and Training"
},
{
"code": null,
"e": 702,
"s": 681,
"text": "Validating the Model"
},
{
"code": null,
"e": 738,
"s": 702,
"text": "Baseline 1 — Nearest Neighbor Model"
},
{
"code": null,
"e": 764,
"s": 738,
"text": "Baseline 2 — Random Model"
},
{
"code": null,
"e": 791,
"s": 764,
"text": "Test Results and Inference"
},
{
"code": null,
"e": 802,
"s": 791,
"text": "Conclusion"
},
{
"code": null,
"e": 813,
"s": 802,
"text": "References"
},
{
"code": null,
"e": 1123,
"s": 813,
"text": "Deep Convolutional Neural Networks have become the state of the art methods for image classification tasks. However, one of the biggest limitations is they require a lots of labelled data. In many applications, collecting this much data is sometimes not feasible. One Shot Learning aims to solve this problem."
},
{
"code": null,
"e": 1334,
"s": 1123,
"text": "In this post, I will assume that you are already familiar with the basics of machine learning and you have some experience on using Convolutional Neural Networks for image classification using Python and Keras."
},
{
"code": null,
"e": 2440,
"s": 1334,
"text": "In case of standard classification, the input image is fed into a series of layers, and finally at the output we generate a probability distribution over all the classes (typically using a Softmax). For example, if we are trying to classify an image as cat or dog or horse or elephant, then for every input image, we generate 4 probabilities, indicating the probability of the image belonging to each of the 4 classes. Two important points must be noticed here. First, during the training process, we require a large number of images for each of the class (cats, dogs, horses and elephants). Second, if the network is trained only on the above 4 classes of images, then we cannot expect to test it on any other class, example “zebra”. If we want our model to classify the images of zebra as well, then we need to first get a lot of zebra images and then we must re-train the model again. There are applications wherein we neither have enough data for each class and the total number classes is huge as well as dynamically changing. Thus, the cost of data collection and periodical re-training is too high."
},
{
"code": null,
"e": 2662,
"s": 2440,
"text": "On the other hand, in a one shot classification, we require only one training example for each class. Yes you got that right, just one. Hence the name One Shot. Let’s try to understand with a real world practical example."
},
{
"code": null,
"e": 2896,
"s": 2662,
"text": "Assume that we want to build face recognition system for a small organization with only 10 employees (small numbers keep things simple). Using a traditional classification approach, we might come up with a system that looks as below:"
},
{
"code": null,
"e": 2906,
"s": 2896,
"text": "Problems:"
},
{
"code": null,
"e": 3132,
"s": 2906,
"text": "a) To train such a system, we first require a lot of different images of each of the 10 persons in the organization which might not be feasible. (Imagine if you are doing this for an organization with thousands of employees)."
},
{
"code": null,
"e": 3409,
"s": 3132,
"text": "b) What if a new person joins or leaves the organization? You need to take the pain of collecting data again and re-train the entire model again. This is practically not possible specially for large organizations where recruitment and attrition is happening almost every week."
},
{
"code": null,
"e": 3539,
"s": 3409,
"text": "Now let’s understand how do we approach this problem using one shot classification which helps to solve both of the above issues:"
},
{
"code": null,
"e": 4025,
"s": 3539,
"text": "Instead of directly classifying an input(test) image to one of the 10 people in the organization, this network instead takes an extra reference image of the person as input and will produce a similarity score denoting the chances that the two input images belong to the same person. Typically the similarity score is squished between 0 and 1 using a sigmoid function; wherein 0 denotes no similarity and 1 denotes full similarity. Any number between 0 and 1 is interpreted accordingly."
},
{
"code": null,
"e": 4240,
"s": 4025,
"text": "Notice that this network is not learning to classify an image directly to any of the output classes. Rather, it is learning a similarity function, which takes two images as input and expresses how similar they are."
},
{
"code": null,
"e": 4297,
"s": 4240,
"text": "How does this solve the two problems we discussed above?"
},
{
"code": null,
"e": 4453,
"s": 4297,
"text": "a) In a short while we will see that to train this network, you do not require too many instances of a class and only few are enough to build a good model."
},
{
"code": null,
"e": 4889,
"s": 4453,
"text": "b) But the biggest advantage is that , let’s say in case of face recognition, we have a new employee who has joined the organization. Now in order for the network to detect his face, we only require a single image of his face which will be stored in the database. Using this as the reference image, the network will calculate the similarity for any new instance presented to it. Thus we say that network predicts the score in one shot."
},
{
"code": null,
"e": 5100,
"s": 4889,
"text": "Don’t worry if the above details seem a bit abstract at the moment, just continue ahead and we will solve a problem in full detail and I promise you will develop an in-depth understanding of the subject matter."
},
{
"code": null,
"e": 5281,
"s": 5100,
"text": "Before we proceed, I would like to mention a few applications of one shot learning in order to motivate you so that you develop more keen interest in understanding this technology."
},
{
"code": null,
"e": 5524,
"s": 5281,
"text": "a. As I have already mentioned about face recognition above, just go to this link wherein the AI Guru Andrew Ng demonstrates how Baidu (the Chinese Search Giant) has developed a face recognition system for the employees in their organization."
},
{
"code": null,
"e": 5634,
"s": 5524,
"text": "b. Read this blog to understand how one shot learning is applied to drug discovery where data is very scarce."
},
{
"code": null,
"e": 5825,
"s": 5634,
"text": "c. In this paper, the authors have used one shot learning to build an offline signature verification system which is very useful for Banks and other Government and also private institutions."
},
{
"code": null,
"e": 6107,
"s": 5825,
"text": "For the purpose of this blog, we will use the Omniglot dataset which is a collection of 1623 hand drawn characters from 50 different alphabets. For every character there are just 20 examples, each drawn by a different person. Each image is a gray scale image of resolution 105x105."
},
{
"code": null,
"e": 6396,
"s": 6107,
"text": "Before I continue, I would like to clarify the difference between a character and an alphabet. In case of English the set A to Z is called as the alphabet while each of the letter A, B, etc. is called a character. Thus we say that the English alphabet contains 26 characters (or letters)."
},
{
"code": null,
"e": 6496,
"s": 6396,
"text": "So I hope this clarifies the point when I say 1623 characters spanning over 50 different alphabets."
},
{
"code": null,
"e": 6598,
"s": 6496,
"text": "Let’s look at some images of characters from different alphabets to get a better feel of the dataset."
},
{
"code": null,
"e": 6980,
"s": 6598,
"text": "Thus we have 1623 different classes(each character can be treated as a separate class) and for each class we have only 20 images. Clearly, if we try to solve this problem using the traditional image classification method then definitely we won’t be able to build a good generalized model. And with such less number of images available for each class, the model will easily overfit."
},
{
"code": null,
"e": 7171,
"s": 6980,
"text": "You can download the dataset by cloning this GitHub repository. The folder named “Python” contains two zip files: images_background.zip and images_evaluation.zip. Just unzip these two files."
},
{
"code": null,
"e": 7388,
"s": 7171,
"text": "images_background folder contains characters from 30 alphabets and will be used to train the model, while images_evaluation folder contains characters from the other 20 alphabets which we will use to test our system."
},
{
"code": null,
"e": 7513,
"s": 7388,
"text": "Once you unzip the files, you will see below folders (alphabets) in the images_background folder(used for training purpose):"
},
{
"code": null,
"e": 7616,
"s": 7513,
"text": "And you will see below folders (alphabets) in the images_evaluation folder (used for testing purpose):"
},
{
"code": null,
"e": 7842,
"s": 7616,
"text": "Notice that we will train the system on one set of characters and then test it on a completely different set of characters which were never used during the training. This is not possible in a traditional classification cycle."
},
{
"code": null,
"e": 7957,
"s": 7842,
"text": "First we need to load the images into tensors and later use these tensors to provide data in batches to the model."
},
{
"code": null,
"e": 8008,
"s": 7957,
"text": "We use below function to load images into tensors:"
},
{
"code": null,
"e": 8108,
"s": 8008,
"text": "To call this function as follows, pass the path of the train directory as the parameter as follows:"
},
{
"code": null,
"e": 8139,
"s": 8108,
"text": "X,y,c = loadimgs(train_folder)"
},
{
"code": null,
"e": 8453,
"s": 8139,
"text": "The function returns a tuple of 3 variables. I won’t go through each line of the code, but I will provide you some intuition what exactly the function is doing by understanding the values it returns. Given this explanation you should be in a good position to understand the above function, once you go through it."
},
{
"code": null,
"e": 8494,
"s": 8453,
"text": "Let’s understand what is present in ‘X’:"
},
{
"code": null,
"e": 8521,
"s": 8494,
"text": "X.shape(964, 20, 105, 105)"
},
{
"code": null,
"e": 8766,
"s": 8521,
"text": "This means we have 964 characters (or letters or categories) spanning across 30 different alphabets. For each of this character, we have 20 images, and each image is a gray scale image of resolution 105x105. Hence the shape (964, 20, 105, 105)."
},
{
"code": null,
"e": 8821,
"s": 8766,
"text": "Let’s now understand how the labels ‘y’ are populated:"
},
{
"code": null,
"e": 8839,
"s": 8821,
"text": "y.shape(19280, 1)"
},
{
"code": null,
"e": 9061,
"s": 8839,
"text": "Total number of images = 964 * 20 = 19280. All the images for one letter have the same label., i.e. The first 20 images have the label 0, the next 20 have the label 1, and so on, ... the last 20 images have the label 963."
},
{
"code": null,
"e": 9148,
"s": 9061,
"text": "Finally the last variable ‘c’ stands for categories and it is a dictionary as follows:"
},
{
"code": null,
"e": 9800,
"s": 9148,
"text": "c.keys() # 'c' for categoriesdict_keys(['Alphabet_of_the_Magi', 'Anglo-Saxon_Futhorc', 'Arcadian', 'Armenian', 'Asomtavruli_(Georgian)', 'Balinese', 'Bengali', 'Blackfoot_(Canadian_Aboriginal_Syllabics)', 'Braille', 'Burmese_(Myanmar)', 'Cyrillic', 'Early_Aramaic', 'Futurama', 'Grantha', 'Greek', 'Gujarati', 'Hebrew', 'Inuktitut_(Canadian_Aboriginal_Syllabics)', 'Japanese_(hiragana)', 'Japanese_(katakana)', 'Korean', 'Latin', 'Malay_(Jawi_-_Arabic)', 'Mkhedruli_(Georgian)', 'N_Ko', 'Ojibwe_(Canadian_Aboriginal_Syllabics)', 'Sanskrit', 'Syriac_(Estrangelo)', 'Tagalog', 'Tifinagh'])c['Alphabet_of_the_Magi'][0, 19]c['Anglo-Saxon_Futhorc'][20, 48]"
},
{
"code": null,
"e": 10122,
"s": 9800,
"text": "Since there are 30 different alphabets, this dictionary ‘c’ contains 30 items. The key for each item is the name of the alphabet. The value for each item is a list of two numbers: [low, high], where ‘low’ is the label of the first character in that alphabet and ‘high’ is the label of the last character in that alphabet."
},
{
"code": null,
"e": 10296,
"s": 10122,
"text": "Once we load the train and test images, we save the tensors on the disk in a pickle file, so that we can utilize them later directly without having to load the images again."
},
{
"code": null,
"e": 10466,
"s": 10296,
"text": "Let’s understand how can we map this problem into a supervised learning task where our dataset contains pairs of (Xi, Yi) where ‘Xi’ is the input and ‘Yi’ is the output."
},
{
"code": null,
"e": 10586,
"s": 10466,
"text": "Recall that the input to our system will be a pair of images and the output will be a similarity score between 0 and 1."
},
{
"code": null,
"e": 10606,
"s": 10586,
"text": "Xi = Pair of images"
},
{
"code": null,
"e": 10657,
"s": 10606,
"text": "Yi = 1 ; if both images contain the same character"
},
{
"code": null,
"e": 10709,
"s": 10657,
"text": "Yi = 0; if both images contain different characters"
},
{
"code": null,
"e": 10777,
"s": 10709,
"text": "Let’s have a better understanding by visualizing the dataset below:"
},
{
"code": null,
"e": 11073,
"s": 10777,
"text": "Thus we need to create pairs of images along with the target variable, as shown above, to be fed as input to the Siamese Network. Note that even though characters from Sanskrit alphabet are shown above, but in practice we will generate pairs randomly from all the alphabets in the training data."
},
{
"code": null,
"e": 11134,
"s": 11073,
"text": "The code to generate these pairs and targets is shown below:"
},
{
"code": null,
"e": 11284,
"s": 11134,
"text": "We need to call the above function by passing the batch_size and it will return “batch_size” number of image pairs along with their target variables."
},
{
"code": null,
"e": 11389,
"s": 11284,
"text": "We will use the below generator function to generate data in batches during the training of the network."
},
{
"code": null,
"e": 11587,
"s": 11389,
"text": "This code is an implementation of the methodology described in this research paper by Gregory Koch et al. Model architecture and hyper-parameters that I have used are all as described in the paper."
},
{
"code": null,
"e": 11725,
"s": 11587,
"text": "Let’s first understand the architecture on a high level before diving into the details. Below I present an intuition of the architecture."
},
{
"code": null,
"e": 12693,
"s": 11725,
"text": "Intuition: The term Siamese means twins. The two Convolutional Neural Networks shown above are not different networks but are two copies of the same network, hence the name Siamese Networks. Basically they share the same parameters. The two input images (x1 and x2) are passed through the ConvNet to generate a fixed length feature vector for each (h(x1) and h(x2)). Assuming the neural network model is trained properly, we can make the following hypothesis: If the two input images belong to the same character, then their feature vectors must also be similar, while if the two input images belong to the different characters, then their feature vectors will also be different. Thus the element-wise absolute difference between the two feature vectors must be very different in both the above cases. And hence the similarity score generated by the output sigmoid layer must also be different in these two cases. This is the central idea behind the Siamese Networks."
},
{
"code": null,
"e": 12827,
"s": 12693,
"text": "Given the above intuition let’s look at the picture of the architecture with more finer details taken from the research paper itself:"
},
{
"code": null,
"e": 12888,
"s": 12827,
"text": "The below function is used to create the model architecture:"
},
{
"code": null,
"e": 13086,
"s": 12888,
"text": "Notice that there is no predefined layer in Keras to compute the absolute difference between two tensors. We do this using the Lambda layer in Keras which is used to add customized layers in Keras."
},
{
"code": null,
"e": 13224,
"s": 13086,
"text": "To understand the shape of the tensors passed at different layers, refer the below image generated using the plot_model utility of Keras."
},
{
"code": null,
"e": 13526,
"s": 13224,
"text": "The model was compiled using the adam optimizer and binary cross entropy loss function as shown below. Learning rate was kept low as it was found that with high learning rate, the model took a lot of time to converge. However these parameters can well be tuned further to improve the present settings."
},
{
"code": null,
"e": 13618,
"s": 13526,
"text": "optimizer = Adam(lr = 0.00006)model.compile(loss=\"binary_crossentropy\",optimizer=optimizer)"
},
{
"code": null,
"e": 13684,
"s": 13618,
"text": "The model was trained for 20000 iterations with batch size of 32."
},
{
"code": null,
"e": 13865,
"s": 13684,
"text": "After every 200 iterations, model validation was done using 20-way one shot learning and the accuracy was calculated over 250 trials. This concept is explained in the next section."
},
{
"code": null,
"e": 14037,
"s": 13865,
"text": "Now that we have understood how to prepare the data for training, model architecture and training; it’s time we must think about a strategy to validate and test our model."
},
{
"code": null,
"e": 14291,
"s": 14037,
"text": "Note that, for every pair of input images, our model generates a similarity score between 0 and 1. But just looking at the score its difficult to ascertain whether the model is really able to recognize similar characters and distinguish dissimilar ones."
},
{
"code": null,
"e": 14406,
"s": 14291,
"text": "A nice way to judge the model is N-way one shot learning. Don’t worry, it’s much easier than what it sounds to be."
},
{
"code": null,
"e": 14445,
"s": 14406,
"text": "An example of 4-way one shot learning:"
},
{
"code": null,
"e": 14498,
"s": 14445,
"text": "We create a dataset of 4 pairs of images as follows:"
},
{
"code": null,
"e": 14911,
"s": 14498,
"text": "Basically the same character is compared to 4 different characters out of which only one of them matches the original character. Let’s say by doing the above 4 comparisons we get 4 similarity scores S1, S2, S3 and S4 as shown. Now if the model is trained properly, we expect that S1 is the maximum of all the 4 similarity scores because the first pair of images is the only one where we have two same characters."
},
{
"code": null,
"e": 15151,
"s": 14911,
"text": "Thus if S1 happens to be the maximum score, we treat this as a correct prediction otherwise we consider this as an incorrect prediction. Repeating this procedure ‘k’ times, we can calculate the percentage of correct predictions as follows:"
},
{
"code": null,
"e": 15191,
"s": 15151,
"text": "percent_correct = (100 * n_correct) / k"
},
{
"code": null,
"e": 15283,
"s": 15191,
"text": "where k => total no. of trials and n_correct => no. of correct predictions out of k trials."
},
{
"code": null,
"e": 15341,
"s": 15283,
"text": "Similarly a 9-way one shot learning will look as follows:"
},
{
"code": null,
"e": 15391,
"s": 15341,
"text": "A 16-way one shot leaning will be as shown below:"
},
{
"code": null,
"e": 15448,
"s": 15391,
"text": "Below is how a 25-way one shot learning would look like:"
},
{
"code": null,
"e": 15678,
"s": 15448,
"text": "Note that the value of ’N’ in N-way one shot learning need not necessarily be a perfect square. The reason for me taking values 4, 9, 16 and 25 was because it just looks good for presentation when the square is filled completely."
},
{
"code": null,
"e": 15866,
"s": 15678,
"text": "It’s quite obvious that smaller values of ’N’ will lead to more correct predictions and larger values of ’N’ will lead to relatively less correct predictions when repeated multiple times."
},
{
"code": null,
"e": 16088,
"s": 15866,
"text": "Just a reminder again: All the examples shown above are from the Sanskrit Alphabet but in practice we will generate the test image and the support set randomly from all the alphabets of the test/validation dataset images."
},
{
"code": null,
"e": 16166,
"s": 16088,
"text": "The code to generate the test image along with the support set is as follows:"
},
{
"code": null,
"e": 16298,
"s": 16166,
"text": "It is always a good practice to create simple baseline models and compare their results with complex model you are trying to build."
},
{
"code": null,
"e": 16446,
"s": 16298,
"text": "Our first baseline model is the Nearest Neighbor approach. If you are familiar with K-Nearest Neighbor algorithm, then this is just the same thing."
},
{
"code": null,
"e": 16635,
"s": 16446,
"text": "As discussed above, in an N-way one shot learning, we compare a test image with N different images and select that image which has highest similarity with the test image as the prediction."
},
{
"code": null,
"e": 16736,
"s": 16635,
"text": "This is intuitively similar to the KNN with K=1. Let’s understand in detail how this approach works."
},
{
"code": null,
"e": 16902,
"s": 16736,
"text": "You might have studied how we can compute the L2 distance (also called as the Euclidean distance) between two vectors. If you do not recall, below is how it is done:"
},
{
"code": null,
"e": 17272,
"s": 16902,
"text": "Let’s say we compare L2 distance of a vector X with 3 other vectors say A, B and C. Then one way to compute the most similar vector to X is check which vector has the least L2 distance with X. Because distance is inversely proportional to similarity. Thus for example if the L2 distance between X and B is minimum, we say that the similarity between X and B is maximum."
},
{
"code": null,
"e": 17446,
"s": 17272,
"text": "However, in our case we do not have vectors but gray scale images, which can be represented as matrices and not vectors. Then how do we compute L2 distance between matrices?"
},
{
"code": null,
"e": 17569,
"s": 17446,
"text": "That’s simple, just flatten the matrices into vectors and then compute the L2 distance between these vectors. For example:"
},
{
"code": null,
"e": 17902,
"s": 17569,
"text": "Thus in N-way One Shot learning, we compare the L2 distance of the test image with all the images in the Support Set. Then we check the character for which we got the minimum L2 distance. If this character is the same as the character in the test image, then the prediction is correct, else the prediction is incorrect. For example:"
},
{
"code": null,
"e": 18084,
"s": 17902,
"text": "Similar to N way one shot learning, we repeat this for multiple trials and compute the average prediction score over all the trials. The code for nearest neighbor approach is below:"
},
{
"code": null,
"e": 18335,
"s": 18084,
"text": "Creating a random model which makes prediction at random is a very common technique to make sure that the model we created is at least better than a model which makes completely random predictions. It’s working can be summarized in the below diagram:"
},
{
"code": null,
"e": 18389,
"s": 18335,
"text": "The N-way testing was done for N = 1, 3, 5, ...., 19."
},
{
"code": null,
"e": 18498,
"s": 18389,
"text": "For each N-way testing, 50 trials were performed and the average accuracy was computed over these 50 trials."
},
{
"code": null,
"e": 18544,
"s": 18498,
"text": "Below is the comparison between the 4 models:"
},
{
"code": null,
"e": 18781,
"s": 18544,
"text": "Inference: Clearly the Siamese Model performed much better than the Random Model and the Nearest Neighbor Model. However there is some gap between the results on training set and validation set which indicate that model is over fitting."
},
{
"code": null,
"e": 19020,
"s": 18781,
"text": "This is just a first cut solution and many of the hyper parameters can be tuned in order to avoid over fitting. Also more rigorous testing can be done by increasing the value of ’N’ in N-way testing and by increasing the number of trials."
},
{
"code": null,
"e": 19115,
"s": 19020,
"text": "I hope this helped you in understanding the one shot learning methodology using Deep Learning."
},
{
"code": null,
"e": 19206,
"s": 19115,
"text": "Source Code: Please refer my source code in Jupyter Notebook on my GitHub Repository here."
},
{
"code": null,
"e": 19321,
"s": 19206,
"text": "Note: The model was trained on Cloud with a P4000 GPU. If you train it on a CPU, then you need to be very patient."
},
{
"code": null,
"e": 19376,
"s": 19321,
"text": "Comments, suggestions, criticism are welcomed. Thanks."
},
{
"code": null,
"e": 19431,
"s": 19376,
"text": "a. https://github.com/akshaysharma096/Siamese-Networks"
},
{
"code": null,
"e": 19477,
"s": 19431,
"text": "b. https://sorenbouma.github.io/blog/oneshot/"
},
{
"code": null,
"e": 19533,
"s": 19477,
"text": "c. https://www.cs.cmu.edu/~rsalakhu/papers/oneshot1.pdf"
}
] |
How to create chart using bootstrap ? - GeeksforGeeks
|
09 Jul, 2021
A chart in bootstrap is a graphical representation for data visualization, in which the data is represented by symbols. The various types of charts like a bar chart, line chart, pie chart, donut chart, etc are created with the help of Bootstrap. In other words, we can say that chart is a type of diagram or graph, that organizes and represents a set of numerical or qualitative data.
Example 1: We are creating a line chart by using bootstrap and JavaScript. In this example, we have used the chart.js file for creating a chart. The data is created according to the type of chart. The following chart has the type “line” with 2 different data both for working hours vs free hours.
HTML
<html> <link rel="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js" type="text/javascript" ></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js"></script> <style> .container { width: 70%; margin: 15px auto; } body { text-align: center; color: green; } h2 { text-align: center; font-family: "Verdana", sans-serif; font-size: 30px; } </style> <body> <div class="container"> <h2>Line Chart</h2> <div> <canvas id="myChart"></canvas> </div> </div> </body> <script> var ctx = document.getElementById("myChart").getContext("2d"); var myChart = new Chart(ctx, { type: "line", data: { labels: [ "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday", ], datasets: [ { label: "work load", data: [2, 9, 3, 17, 6, 3, 7], backgroundColor: "rgba(153,205,1,0.6)", }, { label: "free hours", data: [2, 2, 5, 5, 2, 1, 10], backgroundColor: "rgba(155,153,10,0.6)", }, ], }, }); </script></html>
Output:
line chart with working and free hours
Example 2: In the following example, we created a donut chart by using bootstrap and JavaScript. In this example also, we have used the chart.js file for creating a donut chart. Doughnut charts are the modified version of Pie Charts with the area of center cut out.
HTML
<html> <script src="https://d3js.org/d3.v4.min.js"></script> <script src="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.js"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css" /> <link rel="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" type="text/css" /> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"> </script> <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js"> </script> <style> body { text-align: center; color: green; } h2 { text-align: center; font-family: "Verdana", sans-serif; font-size: 40px; } </style> <body> <div class="col-xs-12 text-center"> <h2>Donut Chart</h2> </div> <div id="donut-chart"></div> <script> var chart = bb.generate({ data: { columns: [ ["Blue", 2], ["orange", 4], ["green", 3], ], type: "donut", onclick: function (d, i) { console.log("onclick", d, i); }, onover: function (d, i) { console.log("onover", d, i); }, onout: function (d, i) { console.log("onout", d, i); }, }, donut: { title: "70", }, bindto: "#donut-chart", }); </script> </body></html>
Output:
Doughnut chart
Bootstrap-Questions
JavaScript-Questions
Picked
Bootstrap
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Show Images on Click using HTML ?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Use Bootstrap with React?
Tailwind CSS vs Bootstrap
How to keep gap between columns using Bootstrap?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript?
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
File uploading in React.js
|
[
{
"code": null,
"e": 25620,
"s": 25592,
"text": "\n09 Jul, 2021"
},
{
"code": null,
"e": 26005,
"s": 25620,
"text": "A chart in bootstrap is a graphical representation for data visualization, in which the data is represented by symbols. The various types of charts like a bar chart, line chart, pie chart, donut chart, etc are created with the help of Bootstrap. In other words, we can say that chart is a type of diagram or graph, that organizes and represents a set of numerical or qualitative data."
},
{
"code": null,
"e": 26302,
"s": 26005,
"text": "Example 1: We are creating a line chart by using bootstrap and JavaScript. In this example, we have used the chart.js file for creating a chart. The data is created according to the type of chart. The following chart has the type “line” with 2 different data both for working hours vs free hours."
},
{
"code": null,
"e": 26307,
"s": 26302,
"text": "HTML"
},
{
"code": "<html> <link rel=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" type=\"text/css\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/modernizr/2.8.3/modernizr.min.js\" type=\"text/javascript\" ></script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.2.2/Chart.min.js\"></script> <style> .container { width: 70%; margin: 15px auto; } body { text-align: center; color: green; } h2 { text-align: center; font-family: \"Verdana\", sans-serif; font-size: 30px; } </style> <body> <div class=\"container\"> <h2>Line Chart</h2> <div> <canvas id=\"myChart\"></canvas> </div> </div> </body> <script> var ctx = document.getElementById(\"myChart\").getContext(\"2d\"); var myChart = new Chart(ctx, { type: \"line\", data: { labels: [ \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\", \"Sunday\", ], datasets: [ { label: \"work load\", data: [2, 9, 3, 17, 6, 3, 7], backgroundColor: \"rgba(153,205,1,0.6)\", }, { label: \"free hours\", data: [2, 2, 5, 5, 2, 1, 10], backgroundColor: \"rgba(155,153,10,0.6)\", }, ], }, }); </script></html>",
"e": 27878,
"s": 26307,
"text": null
},
{
"code": null,
"e": 27887,
"s": 27878,
"text": "Output: "
},
{
"code": null,
"e": 27926,
"s": 27887,
"text": "line chart with working and free hours"
},
{
"code": null,
"e": 28192,
"s": 27926,
"text": "Example 2: In the following example, we created a donut chart by using bootstrap and JavaScript. In this example also, we have used the chart.js file for creating a donut chart. Doughnut charts are the modified version of Pie Charts with the area of center cut out."
},
{
"code": null,
"e": 28197,
"s": 28192,
"text": "HTML"
},
{
"code": "<html> <script src=\"https://d3js.org/d3.v4.min.js\"></script> <script src=\"https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.js\"></script> <link rel=\"stylesheet\" href=\"https://cdn.jsdelivr.net/npm/billboard.js/dist/billboard.min.css\" /> <link rel=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css\" type=\"text/css\" /> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js\"> </script> <script src=\"https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js\"> </script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/Chart.js/1.0.1/Chart.min.js\"> </script> <style> body { text-align: center; color: green; } h2 { text-align: center; font-family: \"Verdana\", sans-serif; font-size: 40px; } </style> <body> <div class=\"col-xs-12 text-center\"> <h2>Donut Chart</h2> </div> <div id=\"donut-chart\"></div> <script> var chart = bb.generate({ data: { columns: [ [\"Blue\", 2], [\"orange\", 4], [\"green\", 3], ], type: \"donut\", onclick: function (d, i) { console.log(\"onclick\", d, i); }, onover: function (d, i) { console.log(\"onover\", d, i); }, onout: function (d, i) { console.log(\"onout\", d, i); }, }, donut: { title: \"70\", }, bindto: \"#donut-chart\", }); </script> </body></html>",
"e": 29726,
"s": 28197,
"text": null
},
{
"code": null,
"e": 29734,
"s": 29726,
"text": "Output:"
},
{
"code": null,
"e": 29749,
"s": 29734,
"text": "Doughnut chart"
},
{
"code": null,
"e": 29769,
"s": 29749,
"text": "Bootstrap-Questions"
},
{
"code": null,
"e": 29790,
"s": 29769,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 29797,
"s": 29790,
"text": "Picked"
},
{
"code": null,
"e": 29807,
"s": 29797,
"text": "Bootstrap"
},
{
"code": null,
"e": 29818,
"s": 29807,
"text": "JavaScript"
},
{
"code": null,
"e": 29835,
"s": 29818,
"text": "Web Technologies"
},
{
"code": null,
"e": 29933,
"s": 29835,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29942,
"s": 29933,
"text": "Comments"
},
{
"code": null,
"e": 29955,
"s": 29942,
"text": "Old Comments"
},
{
"code": null,
"e": 29996,
"s": 29955,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 30059,
"s": 29996,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 30092,
"s": 30059,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 30118,
"s": 30092,
"text": "Tailwind CSS vs Bootstrap"
},
{
"code": null,
"e": 30167,
"s": 30118,
"text": "How to keep gap between columns using Bootstrap?"
},
{
"code": null,
"e": 30212,
"s": 30167,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 30281,
"s": 30212,
"text": "How to calculate the number of days between two dates in javascript?"
},
{
"code": null,
"e": 30342,
"s": 30281,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 30414,
"s": 30342,
"text": "Differences between Functional Components and Class Components in React"
}
] |
What is the difference between = and: = assignment operators?
|
Actually, they both are assignment operator and used to assign values but the significant difference between them is as follows −
= operator assigns a value either as a part of the SET statement or as a part of the SET clause in an UPDATE statement, in any other case = operator is interpreted as a comparison operator. On the other hand, := operator assigns a value and it is never interpreted as a comparison operator.
mysql> Update estimated_cost1 SET Tender_value = '8570.000' where id = 2;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
mysql> Update estimated_cost1 SET Tender_value := '8575.000' where id = 2;
Query OK, 1 row affected (0.06 sec)
Rows matched: 1 Changed: 1 Warnings: 0
In the above two queries, we have used the = operator as well as: = operator to UPDATE the value of the table.
mysql> Set @A = 100;
Query OK, 0 rows affected (0.01 sec)
mysql> Select @A;
+------+
| @A |
+------+
| 100 |
+------+
1 row in set (0.00 sec)
mysql> Set @B := 100;
Query OK, 0 rows affected (0.00 sec)
mysql> Select @B;
+------+
| @B |
+------+
| 100 |
+------+
1 row in set (0.00 sec)
In the above two queries, we used = operator and: = operator to assign a value to a user variable. We can see that in both the situations = operator and: = operator have the same usage and functionality. But in the following query = operator, works as a comparison operator and give the result as ‘TRUE’ i.e. both the user variables @A and @B are having same values.
mysql> Select @A = @B;
+---------+
| @A = @B |
+---------+
| 1 |
+---------+
1 row in set (0.00 sec)
|
[
{
"code": null,
"e": 1192,
"s": 1062,
"text": "Actually, they both are assignment operator and used to assign values but the significant difference between them is as follows −"
},
{
"code": null,
"e": 1483,
"s": 1192,
"text": "= operator assigns a value either as a part of the SET statement or as a part of the SET clause in an UPDATE statement, in any other case = operator is interpreted as a comparison operator. On the other hand, := operator assigns a value and it is never interpreted as a comparison operator."
},
{
"code": null,
"e": 1783,
"s": 1483,
"text": "mysql> Update estimated_cost1 SET Tender_value = '8570.000' where id = 2;\nQuery OK, 1 row affected (0.06 sec)\nRows matched: 1 Changed: 1 Warnings: 0\n\nmysql> Update estimated_cost1 SET Tender_value := '8575.000' where id = 2;\nQuery OK, 1 row affected (0.06 sec)\nRows matched: 1 Changed: 1 Warnings: 0"
},
{
"code": null,
"e": 1894,
"s": 1783,
"text": "In the above two queries, we have used the = operator as well as: = operator to UPDATE the value of the table."
},
{
"code": null,
"e": 2188,
"s": 1894,
"text": "mysql> Set @A = 100;\nQuery OK, 0 rows affected (0.01 sec)\n\nmysql> Select @A;\n+------+\n| @A |\n+------+\n| 100 |\n+------+\n1 row in set (0.00 sec)\n\nmysql> Set @B := 100;\nQuery OK, 0 rows affected (0.00 sec)\n\nmysql> Select @B;\n+------+\n| @B |\n+------+\n| 100 |\n+------+\n1 row in set (0.00 sec)"
},
{
"code": null,
"e": 2555,
"s": 2188,
"text": "In the above two queries, we used = operator and: = operator to assign a value to a user variable. We can see that in both the situations = operator and: = operator have the same usage and functionality. But in the following query = operator, works as a comparison operator and give the result as ‘TRUE’ i.e. both the user variables @A and @B are having same values."
},
{
"code": null,
"e": 2662,
"s": 2555,
"text": "mysql> Select @A = @B;\n+---------+\n| @A = @B |\n+---------+\n| 1 |\n+---------+\n1 row in set (0.00 sec)"
}
] |
Getting started with PyTorch. Learn the basics through examples | by André Ribeiro | Towards Data Science
|
In my previous post “Getting started with Tensorflow” I mentioned that both Tensorflow and PyTorch are great choices if you want to build small or large scale deep learning solutions. Both platforms are widely used in academia and industry, are well maintained and open-source, provide simple APIs and high-level functionality.
In here, we will explore the PyTorch API. In a parallel to the “Getting started with Tensorflow” we will discuss how PyTorch came about and how to use it for deep learning.
Around the time PyTorch 0.1.1 version was released in September 20161, there were multiple deep learning frameworks available, providing low and high level wrappers for building and training complex models.
Caffe, Chainer, Theano, Tensorflow, CNTK, MXNet and Torch were just a few of the low-level libraries researchers would use to build increasingly more complicated networks23.
On the other hand, Lasagne and Keras focused on creating high-level wrappers that could use one of many low-level libraries. This approach was greatly supported by practitioners as it allowed them to abstract from the low-level syntax of languages such as Tensorflow, CNTK or Theano23.
In the following years the landscape changed drastically with the abandon and consolidation of frameworks4:
Keras was incorporated into Tensorflow and greatly changed its direction;
Caffe 2 was incorporated into PyTorch and replaced part of the original Lua implementation from the Torch ancestor;
Theano, CNTK and Chainer development and support stopped.
By June 2021, more than 99% of the Google searches for major deep learning frameworks contained either Tensorflow/Keras or PyTorch/Caffe, where the first one is still noticeably more popular (see graph).
In the following sub-sections I am going to introduce the key concepts to build two simple neural networks in PyTorch (one for regression, and one for classification).
To make this tutorial comparable with my previous post “Getting started with Tensorflow” I am going to re-use the same simulated datasets. To make this tutorial self-contained I am going to re-introduce them again here.
In this example, we will build a simple 1 layer Neural Network in PyTorch to solve a linear regression problem. This will explain how to initialise your weights (aka the regression coefficients), and how to update them through backpropagation.
The first thing we need is a dataset. Here, we will simulate a noisy linear model as
where Y is our target, X is our input, w is the coefficient we want to determine, and N is a Gaussian distributed noise variable. To do so, in the first cell of your notebook paste and run the following snippet.
This will display a scatter plot of the relation between X and Y, clearly indicating a linear correlation under some Gaussian noise. Here, we would expect a reasonable model to estimate 2 as the ideal regression coefficient.
In PyTorch we typically use tensors to represent our inputs, targets and regression coefficients (here on called weights). A tensor is a multidimensional array of elements represented by a ‘torch.Tensor’ object. A tensor has a single data type and a shape.
Let’s now convert our inputs (x) and target (y) into Torch tensors. To do this, copy and run the following snippet in Colab.
This will return the class (torch.Tensor), shape, size and values for the input and target tensors.
Describing the features...<class 'torch.Tensor'>torch.float64torch.Size([1000])tensor([0.0000, 0.0010, 0.0020, 0.0030, 0.0040, 0.0050, 0.0060, 0.0070, 0.0080, 0.0090], dtype=torch.float64)Describing the target...<class 'torch.Tensor'>torch.float64torch.Size([1000])tensor([ 0.1587, -0.6984, 0.1692, 0.1368, 0.1386, 0.0854, 0.2807, 0.2895, 0.5358, 0.3550], dtype=torch.float64)
Let’s now initiate our weight with a constant number (0.1). To do this we call ‘torch.tensor’ with the default 0.1 value, the desired datatype (float) and the device in which we want the tensor to be stored. In this example, we will be performing all operations in ‘cpu’. To improve performance for large NN models we could move tensors to ‘gpu’.
Running this snippet will output the class, shape, type and value of the weight tensor. Note that this tensor has a ‘[]’ shape indicating that its a 0 dimensional vector.
Describing the weights... <class ‘torch.Tensor’> torch.float32 torch.Size([]) tensor(0.1000, requires_grad=True)
To obtain the predicted Y (Yhat) given the initialised weight tensor and the input X we can simply call ‘Yhat = x * w_tensor.detach().numpy()’. The ‘.detach().numpy()’ is used to convert the weight vector to a numpy array. Copy and run the following snippet to see how the initialised weight fits the data.
As you can observe the current value of ‘w_tensor’ is far from ideal. The regression line does fit the data at all.
To find the optimal value for ‘w_tensor’ we need to define a loss metric and an optimiser. Here, we will use the Mean Squared Error (MSE) as our loss metric, and the Stochastic Gradient Descent (SGD) as our optimiser.
We now have all the pieces in place to optimise our ‘w_tensor’. The optimisation loop requires the definition of the custom ‘forward’ step, a call to ‘backward’ step method from our loss metric, and a call to the ‘step’ method from our optimiser.
The custom ‘forward’ step tells the model how to combine the input with the weight tensor and how to calculate the error between our target and the predicted target (line 5 to 8 in the snippet below). In a more complex example, this would be a set of instructions that define the computational graph from the input X to the target Y.
The ‘backward’ step tells the model to backpropagate the errors to each layer in the network (line 22 in the snippet below).
Finally, the ‘optimizer.step()’ tells the model to calculate and apply the weight changes for this iteration (line 23 in the snippet below). Note that in most cases you need to clear the gradients before calling the optimizer step (line 21 in the snippet below).
By the end of the train loop your weight should be reasonably close to 2 (ideal value). To use this model for inference (i.e. to predict the Y variable given an X value) you can simply do ‘Yhat = x * w_tensor.detach().numpy()’.
In this example, we will introduce the PyTorch NN Sequential model definition to create a more complex Neural Network. If you are used to Keras, this module will look very familiar. We will apply this model to a linearly separable classification problem.
As before, let’s start by building our dataset. In the snippet below, we create two clusters of points centered at (0.2, 0.2) for the first cluster, and (0.8, 0.8) for the second cluster.
We can quickly observe that a model that linearly separates the two datasets by a line at equal distance to both clusters would be ideal.
Let’s start by defining the custom NN model to solve this problem. We’ll define a 5 layer neural network as follows:
Linear layer with 10 nodes. This will have a shape of 2 x 10 (input_shape x layer_size).Batch Normalisation layer. This layer will normalise the output of the first layer for each batch, avoiding exploding / vanishing gradients.Relu activation layer. This layer will provide a non-linear capability to our network. Note that we only use this as an example. A relu layer is unnecessary for this problem as it is linearly separable.Linear layer with 2 nodes. This will have a shape of 10 x 2 (layer_size x output_shape).Softmax layer. This layer will convert the output from layer 4 into a softmax.
Linear layer with 10 nodes. This will have a shape of 2 x 10 (input_shape x layer_size).
Batch Normalisation layer. This layer will normalise the output of the first layer for each batch, avoiding exploding / vanishing gradients.
Relu activation layer. This layer will provide a non-linear capability to our network. Note that we only use this as an example. A relu layer is unnecessary for this problem as it is linearly separable.
Linear layer with 2 nodes. This will have a shape of 10 x 2 (layer_size x output_shape).
Softmax layer. This layer will convert the output from layer 4 into a softmax.
As before, let’s also convert the x and y numpy arrays to tensors to make them available to PyTorch, and then define our loss metric and optimizer. In this example we should use a classification loss metric such as the Cross Entropy.
For the optimizer we could use the SGD as before. However, the vanilla SGD is incredibly slow to converge. Instead, we will use a more recent adaptive gradient descent approach (RMSProp).
Like before, let’s first check how our network performs before training. To use the model for inference we can simply type ‘yhat = model(x)’. Now, copy the snippet below to visualise the network output.
As you can confirm the network is not good at all. It clearly needs some training to properly separate the two classes.
To train the Sequential PyTorch model we follow the same steps as in the first example, but replacing the custom ‘forward’ step by the model call. Add the snippet below to your notebook to train the model.
By the end of the train loop your network should be reasonably good at separating both classes. To use this model for inference (i.e. to predict the Y variable given an X value) you can simply do ‘yhat = model(x)’.
For the full script go to my github page by following this link:
github.com
Or go directly to the Google Colab notebook by following this link:
colab.research.google.com
PyTorch is one of the best deep learning frameworks right now to develop custom deep learning solutions (with the other being Tensorflow). In this blog, I introduced the key concepts to build two simple NN models in PyTorch.
Warning!!! Just like I mentioned in my “Getting started with Tensorflow” your learning just started. To get better you will need to keep practicing. The official Pytorch website provides a good source of examples from beginner to expert level, as well as the official documentation to the PyTorch package. Good Luck!
[1] Chintala, Soumith. “PyTorch Alpha-1 release” (September 2016)https://github.com/pytorch/pytorch/releases/tag/v0.1.1
[2] Indra den Bakker. “Battle of the Deep Learning frameworks — Part I: 2017, even more frameworks and interfaces”https://towardsdatascience.com/battle-of-the-deep-learning-frameworks-part-i-cff0e3841750
[3] Madison May. “An Overview of Python Deep Learning Frameworks”https://www.kdnuggets.com/2017/02/python-deep-learning-frameworks-overview.html
[4] Eli Stevens, Luca Antiga, Thomas Viehmann. “Deep Learning with PyTorch”https://pytorch.org/assets/deep-learning/Deep-Learning-with-PyTorch.pdf
|
[
{
"code": null,
"e": 500,
"s": 172,
"text": "In my previous post “Getting started with Tensorflow” I mentioned that both Tensorflow and PyTorch are great choices if you want to build small or large scale deep learning solutions. Both platforms are widely used in academia and industry, are well maintained and open-source, provide simple APIs and high-level functionality."
},
{
"code": null,
"e": 673,
"s": 500,
"text": "In here, we will explore the PyTorch API. In a parallel to the “Getting started with Tensorflow” we will discuss how PyTorch came about and how to use it for deep learning."
},
{
"code": null,
"e": 880,
"s": 673,
"text": "Around the time PyTorch 0.1.1 version was released in September 20161, there were multiple deep learning frameworks available, providing low and high level wrappers for building and training complex models."
},
{
"code": null,
"e": 1054,
"s": 880,
"text": "Caffe, Chainer, Theano, Tensorflow, CNTK, MXNet and Torch were just a few of the low-level libraries researchers would use to build increasingly more complicated networks23."
},
{
"code": null,
"e": 1340,
"s": 1054,
"text": "On the other hand, Lasagne and Keras focused on creating high-level wrappers that could use one of many low-level libraries. This approach was greatly supported by practitioners as it allowed them to abstract from the low-level syntax of languages such as Tensorflow, CNTK or Theano23."
},
{
"code": null,
"e": 1448,
"s": 1340,
"text": "In the following years the landscape changed drastically with the abandon and consolidation of frameworks4:"
},
{
"code": null,
"e": 1522,
"s": 1448,
"text": "Keras was incorporated into Tensorflow and greatly changed its direction;"
},
{
"code": null,
"e": 1638,
"s": 1522,
"text": "Caffe 2 was incorporated into PyTorch and replaced part of the original Lua implementation from the Torch ancestor;"
},
{
"code": null,
"e": 1696,
"s": 1638,
"text": "Theano, CNTK and Chainer development and support stopped."
},
{
"code": null,
"e": 1900,
"s": 1696,
"text": "By June 2021, more than 99% of the Google searches for major deep learning frameworks contained either Tensorflow/Keras or PyTorch/Caffe, where the first one is still noticeably more popular (see graph)."
},
{
"code": null,
"e": 2068,
"s": 1900,
"text": "In the following sub-sections I am going to introduce the key concepts to build two simple neural networks in PyTorch (one for regression, and one for classification)."
},
{
"code": null,
"e": 2288,
"s": 2068,
"text": "To make this tutorial comparable with my previous post “Getting started with Tensorflow” I am going to re-use the same simulated datasets. To make this tutorial self-contained I am going to re-introduce them again here."
},
{
"code": null,
"e": 2532,
"s": 2288,
"text": "In this example, we will build a simple 1 layer Neural Network in PyTorch to solve a linear regression problem. This will explain how to initialise your weights (aka the regression coefficients), and how to update them through backpropagation."
},
{
"code": null,
"e": 2617,
"s": 2532,
"text": "The first thing we need is a dataset. Here, we will simulate a noisy linear model as"
},
{
"code": null,
"e": 2829,
"s": 2617,
"text": "where Y is our target, X is our input, w is the coefficient we want to determine, and N is a Gaussian distributed noise variable. To do so, in the first cell of your notebook paste and run the following snippet."
},
{
"code": null,
"e": 3054,
"s": 2829,
"text": "This will display a scatter plot of the relation between X and Y, clearly indicating a linear correlation under some Gaussian noise. Here, we would expect a reasonable model to estimate 2 as the ideal regression coefficient."
},
{
"code": null,
"e": 3311,
"s": 3054,
"text": "In PyTorch we typically use tensors to represent our inputs, targets and regression coefficients (here on called weights). A tensor is a multidimensional array of elements represented by a ‘torch.Tensor’ object. A tensor has a single data type and a shape."
},
{
"code": null,
"e": 3436,
"s": 3311,
"text": "Let’s now convert our inputs (x) and target (y) into Torch tensors. To do this, copy and run the following snippet in Colab."
},
{
"code": null,
"e": 3536,
"s": 3436,
"text": "This will return the class (torch.Tensor), shape, size and values for the input and target tensors."
},
{
"code": null,
"e": 3935,
"s": 3536,
"text": "Describing the features...<class 'torch.Tensor'>torch.float64torch.Size([1000])tensor([0.0000, 0.0010, 0.0020, 0.0030, 0.0040, 0.0050, 0.0060, 0.0070, 0.0080, 0.0090], dtype=torch.float64)Describing the target...<class 'torch.Tensor'>torch.float64torch.Size([1000])tensor([ 0.1587, -0.6984, 0.1692, 0.1368, 0.1386, 0.0854, 0.2807, 0.2895, 0.5358, 0.3550], dtype=torch.float64)"
},
{
"code": null,
"e": 4282,
"s": 3935,
"text": "Let’s now initiate our weight with a constant number (0.1). To do this we call ‘torch.tensor’ with the default 0.1 value, the desired datatype (float) and the device in which we want the tensor to be stored. In this example, we will be performing all operations in ‘cpu’. To improve performance for large NN models we could move tensors to ‘gpu’."
},
{
"code": null,
"e": 4453,
"s": 4282,
"text": "Running this snippet will output the class, shape, type and value of the weight tensor. Note that this tensor has a ‘[]’ shape indicating that its a 0 dimensional vector."
},
{
"code": null,
"e": 4566,
"s": 4453,
"text": "Describing the weights... <class ‘torch.Tensor’> torch.float32 torch.Size([]) tensor(0.1000, requires_grad=True)"
},
{
"code": null,
"e": 4873,
"s": 4566,
"text": "To obtain the predicted Y (Yhat) given the initialised weight tensor and the input X we can simply call ‘Yhat = x * w_tensor.detach().numpy()’. The ‘.detach().numpy()’ is used to convert the weight vector to a numpy array. Copy and run the following snippet to see how the initialised weight fits the data."
},
{
"code": null,
"e": 4989,
"s": 4873,
"text": "As you can observe the current value of ‘w_tensor’ is far from ideal. The regression line does fit the data at all."
},
{
"code": null,
"e": 5207,
"s": 4989,
"text": "To find the optimal value for ‘w_tensor’ we need to define a loss metric and an optimiser. Here, we will use the Mean Squared Error (MSE) as our loss metric, and the Stochastic Gradient Descent (SGD) as our optimiser."
},
{
"code": null,
"e": 5454,
"s": 5207,
"text": "We now have all the pieces in place to optimise our ‘w_tensor’. The optimisation loop requires the definition of the custom ‘forward’ step, a call to ‘backward’ step method from our loss metric, and a call to the ‘step’ method from our optimiser."
},
{
"code": null,
"e": 5788,
"s": 5454,
"text": "The custom ‘forward’ step tells the model how to combine the input with the weight tensor and how to calculate the error between our target and the predicted target (line 5 to 8 in the snippet below). In a more complex example, this would be a set of instructions that define the computational graph from the input X to the target Y."
},
{
"code": null,
"e": 5913,
"s": 5788,
"text": "The ‘backward’ step tells the model to backpropagate the errors to each layer in the network (line 22 in the snippet below)."
},
{
"code": null,
"e": 6176,
"s": 5913,
"text": "Finally, the ‘optimizer.step()’ tells the model to calculate and apply the weight changes for this iteration (line 23 in the snippet below). Note that in most cases you need to clear the gradients before calling the optimizer step (line 21 in the snippet below)."
},
{
"code": null,
"e": 6404,
"s": 6176,
"text": "By the end of the train loop your weight should be reasonably close to 2 (ideal value). To use this model for inference (i.e. to predict the Y variable given an X value) you can simply do ‘Yhat = x * w_tensor.detach().numpy()’."
},
{
"code": null,
"e": 6659,
"s": 6404,
"text": "In this example, we will introduce the PyTorch NN Sequential model definition to create a more complex Neural Network. If you are used to Keras, this module will look very familiar. We will apply this model to a linearly separable classification problem."
},
{
"code": null,
"e": 6847,
"s": 6659,
"text": "As before, let’s start by building our dataset. In the snippet below, we create two clusters of points centered at (0.2, 0.2) for the first cluster, and (0.8, 0.8) for the second cluster."
},
{
"code": null,
"e": 6985,
"s": 6847,
"text": "We can quickly observe that a model that linearly separates the two datasets by a line at equal distance to both clusters would be ideal."
},
{
"code": null,
"e": 7102,
"s": 6985,
"text": "Let’s start by defining the custom NN model to solve this problem. We’ll define a 5 layer neural network as follows:"
},
{
"code": null,
"e": 7699,
"s": 7102,
"text": "Linear layer with 10 nodes. This will have a shape of 2 x 10 (input_shape x layer_size).Batch Normalisation layer. This layer will normalise the output of the first layer for each batch, avoiding exploding / vanishing gradients.Relu activation layer. This layer will provide a non-linear capability to our network. Note that we only use this as an example. A relu layer is unnecessary for this problem as it is linearly separable.Linear layer with 2 nodes. This will have a shape of 10 x 2 (layer_size x output_shape).Softmax layer. This layer will convert the output from layer 4 into a softmax."
},
{
"code": null,
"e": 7788,
"s": 7699,
"text": "Linear layer with 10 nodes. This will have a shape of 2 x 10 (input_shape x layer_size)."
},
{
"code": null,
"e": 7929,
"s": 7788,
"text": "Batch Normalisation layer. This layer will normalise the output of the first layer for each batch, avoiding exploding / vanishing gradients."
},
{
"code": null,
"e": 8132,
"s": 7929,
"text": "Relu activation layer. This layer will provide a non-linear capability to our network. Note that we only use this as an example. A relu layer is unnecessary for this problem as it is linearly separable."
},
{
"code": null,
"e": 8221,
"s": 8132,
"text": "Linear layer with 2 nodes. This will have a shape of 10 x 2 (layer_size x output_shape)."
},
{
"code": null,
"e": 8300,
"s": 8221,
"text": "Softmax layer. This layer will convert the output from layer 4 into a softmax."
},
{
"code": null,
"e": 8534,
"s": 8300,
"text": "As before, let’s also convert the x and y numpy arrays to tensors to make them available to PyTorch, and then define our loss metric and optimizer. In this example we should use a classification loss metric such as the Cross Entropy."
},
{
"code": null,
"e": 8722,
"s": 8534,
"text": "For the optimizer we could use the SGD as before. However, the vanilla SGD is incredibly slow to converge. Instead, we will use a more recent adaptive gradient descent approach (RMSProp)."
},
{
"code": null,
"e": 8925,
"s": 8722,
"text": "Like before, let’s first check how our network performs before training. To use the model for inference we can simply type ‘yhat = model(x)’. Now, copy the snippet below to visualise the network output."
},
{
"code": null,
"e": 9045,
"s": 8925,
"text": "As you can confirm the network is not good at all. It clearly needs some training to properly separate the two classes."
},
{
"code": null,
"e": 9251,
"s": 9045,
"text": "To train the Sequential PyTorch model we follow the same steps as in the first example, but replacing the custom ‘forward’ step by the model call. Add the snippet below to your notebook to train the model."
},
{
"code": null,
"e": 9466,
"s": 9251,
"text": "By the end of the train loop your network should be reasonably good at separating both classes. To use this model for inference (i.e. to predict the Y variable given an X value) you can simply do ‘yhat = model(x)’."
},
{
"code": null,
"e": 9531,
"s": 9466,
"text": "For the full script go to my github page by following this link:"
},
{
"code": null,
"e": 9542,
"s": 9531,
"text": "github.com"
},
{
"code": null,
"e": 9610,
"s": 9542,
"text": "Or go directly to the Google Colab notebook by following this link:"
},
{
"code": null,
"e": 9636,
"s": 9610,
"text": "colab.research.google.com"
},
{
"code": null,
"e": 9861,
"s": 9636,
"text": "PyTorch is one of the best deep learning frameworks right now to develop custom deep learning solutions (with the other being Tensorflow). In this blog, I introduced the key concepts to build two simple NN models in PyTorch."
},
{
"code": null,
"e": 10178,
"s": 9861,
"text": "Warning!!! Just like I mentioned in my “Getting started with Tensorflow” your learning just started. To get better you will need to keep practicing. The official Pytorch website provides a good source of examples from beginner to expert level, as well as the official documentation to the PyTorch package. Good Luck!"
},
{
"code": null,
"e": 10298,
"s": 10178,
"text": "[1] Chintala, Soumith. “PyTorch Alpha-1 release” (September 2016)https://github.com/pytorch/pytorch/releases/tag/v0.1.1"
},
{
"code": null,
"e": 10502,
"s": 10298,
"text": "[2] Indra den Bakker. “Battle of the Deep Learning frameworks — Part I: 2017, even more frameworks and interfaces”https://towardsdatascience.com/battle-of-the-deep-learning-frameworks-part-i-cff0e3841750"
},
{
"code": null,
"e": 10647,
"s": 10502,
"text": "[3] Madison May. “An Overview of Python Deep Learning Frameworks”https://www.kdnuggets.com/2017/02/python-deep-learning-frameworks-overview.html"
}
] |
Add dictionary to tuple in Python
|
When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used.
A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on).
The 'append' method adds elements to the end of the list.
Below is a demonstration of the same −
Live Demo
my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)
print ("The tuple is : " )
print(my_tuple_1)
my_dict = {"Hey" : 11, "there" : 31, "Jane" : 23}
print("The dictionary is : ")
print(my_dict)
my_tuple_1 = list(my_tuple_1)
my_tuple_1.append(my_dict)
my_tuple_1 = tuple(my_tuple_1)
print("The tuple after adding the dictionary elements is : ")
print(my_tuple_1)
The tuple is :
(7, 8, 0, 3, 45, 3, 2, 22, 4)
The dictionary is :
{'Hey': 11, 'there': 31, 'Jane': 23}
The tuple after adding the dictionary elements is :
(7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})
A tuple is defined and is displayed on the console.
A dictionary is defined and is displayed on the console.
The tuple is converted to a list, and the dictionary is added to it using the 'append' method.
Then, this resultant data is converted to a tuple.
This result is assigned to a value.
It is displayed as output on the console.
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "When it is required to add a dictionary to a tuple, the 'list' method, the 'append', and the 'tuple' method can be used."
},
{
"code": null,
"e": 1310,
"s": 1183,
"text": "A list can be used to store heterogeneous values (i.e data of any data type like integer, floating point, strings, and so on)."
},
{
"code": null,
"e": 1368,
"s": 1310,
"text": "The 'append' method adds elements to the end of the list."
},
{
"code": null,
"e": 1407,
"s": 1368,
"text": "Below is a demonstration of the same −"
},
{
"code": null,
"e": 1417,
"s": 1407,
"text": "Live Demo"
},
{
"code": null,
"e": 1773,
"s": 1417,
"text": "my_tuple_1 = (7, 8, 0, 3, 45, 3, 2, 22, 4)\n\nprint (\"The tuple is : \" )\nprint(my_tuple_1)\n\nmy_dict = {\"Hey\" : 11, \"there\" : 31, \"Jane\" : 23}\n\nprint(\"The dictionary is : \")\nprint(my_dict)\n\nmy_tuple_1 = list(my_tuple_1)\nmy_tuple_1.append(my_dict)\nmy_tuple_1 = tuple(my_tuple_1)\n\nprint(\"The tuple after adding the dictionary elements is : \")\nprint(my_tuple_1)"
},
{
"code": null,
"e": 1995,
"s": 1773,
"text": "The tuple is :\n(7, 8, 0, 3, 45, 3, 2, 22, 4)\nThe dictionary is :\n{'Hey': 11, 'there': 31, 'Jane': 23}\nThe tuple after adding the dictionary elements is :\n(7, 8, 0, 3, 45, 3, 2, 22, 4, {'Hey': 11, 'there': 31, 'Jane': 23})"
},
{
"code": null,
"e": 2047,
"s": 1995,
"text": "A tuple is defined and is displayed on the console."
},
{
"code": null,
"e": 2104,
"s": 2047,
"text": "A dictionary is defined and is displayed on the console."
},
{
"code": null,
"e": 2199,
"s": 2104,
"text": "The tuple is converted to a list, and the dictionary is added to it using the 'append' method."
},
{
"code": null,
"e": 2250,
"s": 2199,
"text": "Then, this resultant data is converted to a tuple."
},
{
"code": null,
"e": 2286,
"s": 2250,
"text": "This result is assigned to a value."
},
{
"code": null,
"e": 2328,
"s": 2286,
"text": "It is displayed as output on the console."
}
] |
What are Forward declarations in C++ - GeeksforGeeks
|
28 Nov, 2019
Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program).Example:
// Forward Declaration of the sum()
void sum(int, int);
// Usage of the sum
void sum(int a, int b)
{
// Body
}
In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this.
Example:
// Forward Declaration class A
class A;
// Definition of class A
class A{
// Body
};
Need for Forward Declarations:
Let us understand the need for forward declaration with an example.
Example 1:
.// C++ program to show// the need for Forward Declaration #include <iostream> using namespace std; class B { public: int x; void getdata(int n) { x = n; } friend int sum(A, B);}; class A {public: int y; void getdata(int m) { y = m; } friend int sum(A, B);}; int sum(A m, B n){ int result; result = m.y + n.x; return result;} int main(){ B b; A a; a.getdata(5); b.getdata(4); cout << "The sum is : " << sum(a, b); return 0;}
Output:
Compile Errors :
prog.cpp:14:18: error: 'A' has not been declared
friend int sum(A, B);
^
Explanation: Here the compiler throws this error because, in class B, the object of class A is being used, which has no declaration till that line. Hence compiler couldn’t find class A. So what if class A is written before class B? Let’s find out in the next example.
Example 2:
.// C++ program to show// the need for Forward Declaration #include <iostream> using namespace std; class A {public: int y; void getdata(int m) { y = m; } friend int sum(A, B);}; class B { public: int x; void getdata(int n) { x = n; } friend int sum(A, B);}; int sum(A m, B n){ int result; result = m.y + n.x; return result;} int main(){ B b; A a; a.getdata(5); b.getdata(4); cout << "The sum is : " << sum(a, b); return 0;}
Output:
Compile Errors :
prog.cpp:16:23: error: 'B' has not been declared
friend int sum(A, B);
^
Explanation: Here the compiler throws this error because, in class A, the object of class B is being used, which has no declaration till that line. Hence compiler couldn’t find class B.
Now it is clear that any of the above codes wouldn’t work, no matter in which order the classes are written. Hence this problem needs a new solution- Forward Declaration.
Let us add the forward declaration to the above example and check the output again.
Example 3:
#include <iostream>using namespace std; // Forward declarationclass A;class B; class B { int x; public: void getdata(int n) { x = n; } friend int sum(A, B);}; class A { int y; public: void getdata(int m) { y = m; } friend int sum(A, B);};int sum(A m, B n){ int result; result = m.y + n.x; return result;} int main(){ B b; A a; a.getdata(5); b.getdata(4); cout << "The sum is : " << sum(a, b); return 0;}
The sum is : 9
The program runs without any errors now. A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types.
CPP-Basics
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
C++ Classes and Objects
Operator Overloading in C++
Socket Programming in C/C++
Multidimensional Arrays in C / C++
Templates in C++ with Examples
rand() and srand() in C/C++
C++ Data Types
getline (string) in C++
Left Shift and Right Shift Operators in C/C++
unordered_map in C++ STL
|
[
{
"code": null,
"e": 24175,
"s": 24147,
"text": "\n28 Nov, 2019"
},
{
"code": null,
"e": 24365,
"s": 24175,
"text": "Forward Declaration refers to the beforehand declaration of the syntax or signature of an identifier, variable, function, class, etc. prior to its usage (done later in the program).Example:"
},
{
"code": null,
"e": 24482,
"s": 24365,
"text": "// Forward Declaration of the sum()\nvoid sum(int, int);\n\n// Usage of the sum\nvoid sum(int a, int b)\n{\n // Body\n}\n"
},
{
"code": null,
"e": 24671,
"s": 24482,
"text": "In C++, Forward declarations are usually used for Classes. In this, the class is pre-defined before its use so that it can be called and used by other classes that are defined before this."
},
{
"code": null,
"e": 24680,
"s": 24671,
"text": "Example:"
},
{
"code": null,
"e": 24771,
"s": 24680,
"text": "// Forward Declaration class A\nclass A;\n\n// Definition of class A\nclass A{\n // Body\n};\n"
},
{
"code": null,
"e": 24802,
"s": 24771,
"text": "Need for Forward Declarations:"
},
{
"code": null,
"e": 24870,
"s": 24802,
"text": "Let us understand the need for forward declaration with an example."
},
{
"code": null,
"e": 24881,
"s": 24870,
"text": "Example 1:"
},
{
"code": ".// C++ program to show// the need for Forward Declaration #include <iostream> using namespace std; class B { public: int x; void getdata(int n) { x = n; } friend int sum(A, B);}; class A {public: int y; void getdata(int m) { y = m; } friend int sum(A, B);}; int sum(A m, B n){ int result; result = m.y + n.x; return result;} int main(){ B b; A a; a.getdata(5); b.getdata(4); cout << \"The sum is : \" << sum(a, b); return 0;}",
"e": 25390,
"s": 24881,
"text": null
},
{
"code": null,
"e": 25398,
"s": 25390,
"text": "Output:"
},
{
"code": null,
"e": 25510,
"s": 25398,
"text": "Compile Errors :\nprog.cpp:14:18: error: 'A' has not been declared\n friend int sum(A, B);\n ^\n"
},
{
"code": null,
"e": 25778,
"s": 25510,
"text": "Explanation: Here the compiler throws this error because, in class B, the object of class A is being used, which has no declaration till that line. Hence compiler couldn’t find class A. So what if class A is written before class B? Let’s find out in the next example."
},
{
"code": null,
"e": 25789,
"s": 25778,
"text": "Example 2:"
},
{
"code": ".// C++ program to show// the need for Forward Declaration #include <iostream> using namespace std; class A {public: int y; void getdata(int m) { y = m; } friend int sum(A, B);}; class B { public: int x; void getdata(int n) { x = n; } friend int sum(A, B);}; int sum(A m, B n){ int result; result = m.y + n.x; return result;} int main(){ B b; A a; a.getdata(5); b.getdata(4); cout << \"The sum is : \" << sum(a, b); return 0;}",
"e": 26298,
"s": 25789,
"text": null
},
{
"code": null,
"e": 26306,
"s": 26298,
"text": "Output:"
},
{
"code": null,
"e": 26425,
"s": 26306,
"text": "Compile Errors :\nprog.cpp:16:23: error: 'B' has not been declared\n friend int sum(A, B);\n ^\n"
},
{
"code": null,
"e": 26611,
"s": 26425,
"text": "Explanation: Here the compiler throws this error because, in class A, the object of class B is being used, which has no declaration till that line. Hence compiler couldn’t find class B."
},
{
"code": null,
"e": 26782,
"s": 26611,
"text": "Now it is clear that any of the above codes wouldn’t work, no matter in which order the classes are written. Hence this problem needs a new solution- Forward Declaration."
},
{
"code": null,
"e": 26866,
"s": 26782,
"text": "Let us add the forward declaration to the above example and check the output again."
},
{
"code": null,
"e": 26877,
"s": 26866,
"text": "Example 3:"
},
{
"code": "#include <iostream>using namespace std; // Forward declarationclass A;class B; class B { int x; public: void getdata(int n) { x = n; } friend int sum(A, B);}; class A { int y; public: void getdata(int m) { y = m; } friend int sum(A, B);};int sum(A m, B n){ int result; result = m.y + n.x; return result;} int main(){ B b; A a; a.getdata(5); b.getdata(4); cout << \"The sum is : \" << sum(a, b); return 0;}",
"e": 27358,
"s": 26877,
"text": null
},
{
"code": null,
"e": 27374,
"s": 27358,
"text": "The sum is : 9\n"
},
{
"code": null,
"e": 27643,
"s": 27374,
"text": "The program runs without any errors now. A forward declaration tells the compiler about the existence of an entity before actually defining the entity. Forward declarations can also be used with other entity in C++, such as functions, variables and user-defined types."
},
{
"code": null,
"e": 27654,
"s": 27643,
"text": "CPP-Basics"
},
{
"code": null,
"e": 27658,
"s": 27654,
"text": "C++"
},
{
"code": null,
"e": 27662,
"s": 27658,
"text": "CPP"
},
{
"code": null,
"e": 27760,
"s": 27662,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27784,
"s": 27760,
"text": "C++ Classes and Objects"
},
{
"code": null,
"e": 27812,
"s": 27784,
"text": "Operator Overloading in C++"
},
{
"code": null,
"e": 27840,
"s": 27812,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 27875,
"s": 27840,
"text": "Multidimensional Arrays in C / C++"
},
{
"code": null,
"e": 27906,
"s": 27875,
"text": "Templates in C++ with Examples"
},
{
"code": null,
"e": 27934,
"s": 27906,
"text": "rand() and srand() in C/C++"
},
{
"code": null,
"e": 27949,
"s": 27934,
"text": "C++ Data Types"
},
{
"code": null,
"e": 27973,
"s": 27949,
"text": "getline (string) in C++"
},
{
"code": null,
"e": 28019,
"s": 27973,
"text": "Left Shift and Right Shift Operators in C/C++"
}
] |
GATE | GATE-CS-2015 (Set 2) | Question 29 - GeeksforGeeks
|
07 Sep, 2021
Match the following:
List-I List-II
A. Lexical analysis 1. Graph coloring
B. Parsing 2. DFA minimization
C. Register allocation 3. Post-order traversal
D. Expression evaluation 4. Production tree
Codes:
A B C D
(a) 2 3 1 4
(b) 2 1 4 3
(c) 2 4 1 3
(d) 2 3 4 1
(A) a(B) b(C) c(D) dAnswer: (C)Explanation:
Register allocation is a variation of Graph Coloring problem.
Lexical Analysis uses DFA.
Parsing makes production tree
Expression evaluation is done using tree traversal
YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0016:20 / 44:16•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=9LF8Bby1Qhc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question
GATE-CS-2015 (Set 2)
GATE-GATE-CS-2015 (Set 2)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2011 | Question 7
GATE | GATE CS 2010 | Question 24
GATE | GATE-CS-2016 (Set 2) | Question 61
GATE | GATE-CS-2015 (Set 3) | Question 65
GATE | GATE-CS-2016 (Set 1) | Question 65
GATE | GATE-CS-2014-(Set-3) | Question 38
GATE | GATE-CS-2016 (Set 1) | Question 56
|
[
{
"code": null,
"e": 24536,
"s": 24508,
"text": "\n07 Sep, 2021"
},
{
"code": null,
"e": 24557,
"s": 24536,
"text": "Match the following:"
},
{
"code": null,
"e": 24780,
"s": 24557,
"text": " List-I List-II\nA. Lexical analysis 1. Graph coloring\nB. Parsing 2. DFA minimization\nC. Register allocation 3. Post-order traversal\nD. Expression evaluation 4. Production tree"
},
{
"code": null,
"e": 24847,
"s": 24780,
"text": "Codes:\n A B C D\n(a) 2 3 1 4\n(b) 2 1 4 3\n(c) 2 4 1 3\n(d) 2 3 4 1"
},
{
"code": null,
"e": 24891,
"s": 24847,
"text": "(A) a(B) b(C) c(D) dAnswer: (C)Explanation:"
},
{
"code": null,
"e": 25065,
"s": 24891,
"text": "Register allocation is a variation of Graph Coloring problem.\n\nLexical Analysis uses DFA.\n\nParsing makes production tree\n\nExpression evaluation is done using tree traversal "
},
{
"code": null,
"e": 25971,
"s": 25065,
"text": "YouTubeGeeksforGeeks GATE Computer Science16.1K subscribersPYQ - Parsing and SDT (Continued) with Joyojyoti Acharya | GeeksforGeeks GATEWatch 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:0016:20 / 44:16•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=9LF8Bby1Qhc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>Quiz of this Question"
},
{
"code": null,
"e": 25992,
"s": 25971,
"text": "GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 26018,
"s": 25992,
"text": "GATE-GATE-CS-2015 (Set 2)"
},
{
"code": null,
"e": 26023,
"s": 26018,
"text": "GATE"
},
{
"code": null,
"e": 26121,
"s": 26023,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26155,
"s": 26121,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 26189,
"s": 26155,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 26231,
"s": 26189,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 26264,
"s": 26231,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 26298,
"s": 26264,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 26340,
"s": 26298,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 61"
},
{
"code": null,
"e": 26382,
"s": 26340,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 26424,
"s": 26382,
"text": "GATE | GATE-CS-2016 (Set 1) | Question 65"
},
{
"code": null,
"e": 26466,
"s": 26424,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 38"
}
] |
Interrupts in Arduino
|
As the name suggests, interrupts are routines that interrupt the normal code flow. An interrupt routine contains a piece of code that the microcontroller on your board should execute whenever an event occurs. Take the air-conditioner example. Suppose it has the following temperature control settings: Switch off cooling whenever temperature reaches 18 degrees C. Now, there will be a temperature sensor that keeps measuring the temperature. Whenever it reports a temperature of 18 degrees Celsius, the normal code running on the AC microcontroller is interrupted, it executes the code to turn off cooling, and then the normal code resumes.
There are various ways of triggering interrupts. You can have an interrupt triggered when a button is pressed (basically when there is change in state of a pin from HIGH to LOW or LOW to HIGH). You can have timer-based interrupts, which get triggered at regular intervals, you can have an interrupt when data is received via UART, or SPI, or Wire, and so on. The available list of interrupts can be found here: http://gammon.com.au/interrupts
The code that gets executed whenever an interrupt even occurs, is stored inside a special kind of function called as the Interrupt Service Routine. They have the following limitations −
They should not take in any parameters/ arguments
They cannot return anything
If there are multiple interrupts in your code, each having its own Interrupt Service Routine (ISR), then only one ISR can run at a time. Also, note the following (sourced from Arduino documentation) −
millis() will not increment inside an ISR, since it relies on interrupts for incrementing itself. Since two ISRs cannot run simultaneously, millis cannot increment within an ISR
Similarly, delay() will not work within an interrupt because it requires interrupts to work
delayMicroseconds() doesn't require interrupts to work, so it will work normally within an interrupt
micros() works in the beginning, but the behaviour is unpredictable after 1-2 ms
If you wish to change the value of a variable within an ISR, you need to declare the variable as volatile.
Thus,
int p1 = 1;
becomes
volatile int p1 = 1;
We will consider button interrupts. More specifically, interrupts that are triggered when a rising or falling edge is detected on one of the pins. Now, not all pins of your board can be used for interrupting the code. Each board has some specific pins reserved for external interrupts. The list can be found here: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/
As you can see from the above link, pins 2 and 3 can be used for external interrupts on Arduino Uno.
Now, interrupts are supposed to be executed very fast. Therefore, all we will do inside the interrupt is set a flag. And in the loop, we will print a statement whenever the flag is set, and then set the flag back to 0.
The main function of importance is attachInterrupt().
The syntax is −
attachInterrupt(digitalPinToInterrupt(pin), ISR, mode)
Here, pin is the pin number, ISR is the name of the ISR function, and the mode can be one of the following −
RISING: Whenever a low to high transition is seen on the pin
FALLING: Whenever a high to low transition is seen on the pin
LOW: Whenever the pin is at low voltage
CHANGE: Whenever the pin sees a change in voltage (high to low or low to high)
On some board (Due, MKR1000 and Zero), you can also have the HIGH mode: Whenever the pin is at high voltage.
The circuit diagram and the example code is given below.
As you can see from the circuit diagram below, whenever the button switch is pressed, pin 2 gets connected to GND, and a falling edge (HIGH to LOW) would be observed on that pin, because it is pulled up normally (mode INPUT_PULLUP). This falling edge will generate the interrupt.
const int interruptPin = 2;
volatile bool isButtonPressed = false;
void setup() {
Serial.begin(9600);
pinMode(interruptPin, INPUT_PULLUP);
attachInterrupt(digitalPinToInterrupt(interruptPin), button_pressed, FALLING);
}
void loop() {
if(isButtonPressed){
Serial.println("Button Pressed!");
isButtonPressed = false;
}
}
void button_pressed() {
isButtonPressed = true;
}
|
[
{
"code": null,
"e": 1703,
"s": 1062,
"text": "As the name suggests, interrupts are routines that interrupt the normal code flow. An interrupt routine contains a piece of code that the microcontroller on your board should execute whenever an event occurs. Take the air-conditioner example. Suppose it has the following temperature control settings: Switch off cooling whenever temperature reaches 18 degrees C. Now, there will be a temperature sensor that keeps measuring the temperature. Whenever it reports a temperature of 18 degrees Celsius, the normal code running on the AC microcontroller is interrupted, it executes the code to turn off cooling, and then the normal code resumes."
},
{
"code": null,
"e": 2147,
"s": 1703,
"text": "There are various ways of triggering interrupts. You can have an interrupt triggered when a button is pressed (basically when there is change in state of a pin from HIGH to LOW or LOW to HIGH). You can have timer-based interrupts, which get triggered at regular intervals, you can have an interrupt when data is received via UART, or SPI, or Wire, and so on. The available list of interrupts can be found here: http://gammon.com.au/interrupts"
},
{
"code": null,
"e": 2333,
"s": 2147,
"text": "The code that gets executed whenever an interrupt even occurs, is stored inside a special kind of function called as the Interrupt Service Routine. They have the following limitations −"
},
{
"code": null,
"e": 2383,
"s": 2333,
"text": "They should not take in any parameters/ arguments"
},
{
"code": null,
"e": 2411,
"s": 2383,
"text": "They cannot return anything"
},
{
"code": null,
"e": 2612,
"s": 2411,
"text": "If there are multiple interrupts in your code, each having its own Interrupt Service Routine (ISR), then only one ISR can run at a time. Also, note the following (sourced from Arduino documentation) −"
},
{
"code": null,
"e": 2790,
"s": 2612,
"text": "millis() will not increment inside an ISR, since it relies on interrupts for incrementing itself. Since two ISRs cannot run simultaneously, millis cannot increment within an ISR"
},
{
"code": null,
"e": 2882,
"s": 2790,
"text": "Similarly, delay() will not work within an interrupt because it requires interrupts to work"
},
{
"code": null,
"e": 2983,
"s": 2882,
"text": "delayMicroseconds() doesn't require interrupts to work, so it will work normally within an interrupt"
},
{
"code": null,
"e": 3064,
"s": 2983,
"text": "micros() works in the beginning, but the behaviour is unpredictable after 1-2 ms"
},
{
"code": null,
"e": 3171,
"s": 3064,
"text": "If you wish to change the value of a variable within an ISR, you need to declare the variable as volatile."
},
{
"code": null,
"e": 3177,
"s": 3171,
"text": "Thus,"
},
{
"code": null,
"e": 3189,
"s": 3177,
"text": "int p1 = 1;"
},
{
"code": null,
"e": 3197,
"s": 3189,
"text": "becomes"
},
{
"code": null,
"e": 3218,
"s": 3197,
"text": "volatile int p1 = 1;"
},
{
"code": null,
"e": 3624,
"s": 3218,
"text": "We will consider button interrupts. More specifically, interrupts that are triggered when a rising or falling edge is detected on one of the pins. Now, not all pins of your board can be used for interrupting the code. Each board has some specific pins reserved for external interrupts. The list can be found here: https://www.arduino.cc/reference/en/language/functions/external-interrupts/attachinterrupt/"
},
{
"code": null,
"e": 3725,
"s": 3624,
"text": "As you can see from the above link, pins 2 and 3 can be used for external interrupts on Arduino Uno."
},
{
"code": null,
"e": 3944,
"s": 3725,
"text": "Now, interrupts are supposed to be executed very fast. Therefore, all we will do inside the interrupt is set a flag. And in the loop, we will print a statement whenever the flag is set, and then set the flag back to 0."
},
{
"code": null,
"e": 3998,
"s": 3944,
"text": "The main function of importance is attachInterrupt()."
},
{
"code": null,
"e": 4014,
"s": 3998,
"text": "The syntax is −"
},
{
"code": null,
"e": 4069,
"s": 4014,
"text": "attachInterrupt(digitalPinToInterrupt(pin), ISR, mode)"
},
{
"code": null,
"e": 4178,
"s": 4069,
"text": "Here, pin is the pin number, ISR is the name of the ISR function, and the mode can be one of the following −"
},
{
"code": null,
"e": 4239,
"s": 4178,
"text": "RISING: Whenever a low to high transition is seen on the pin"
},
{
"code": null,
"e": 4301,
"s": 4239,
"text": "FALLING: Whenever a high to low transition is seen on the pin"
},
{
"code": null,
"e": 4341,
"s": 4301,
"text": "LOW: Whenever the pin is at low voltage"
},
{
"code": null,
"e": 4420,
"s": 4341,
"text": "CHANGE: Whenever the pin sees a change in voltage (high to low or low to high)"
},
{
"code": null,
"e": 4529,
"s": 4420,
"text": "On some board (Due, MKR1000 and Zero), you can also have the HIGH mode: Whenever the pin is at high voltage."
},
{
"code": null,
"e": 4586,
"s": 4529,
"text": "The circuit diagram and the example code is given below."
},
{
"code": null,
"e": 4866,
"s": 4586,
"text": "As you can see from the circuit diagram below, whenever the button switch is pressed, pin 2 gets connected to GND, and a falling edge (HIGH to LOW) would be observed on that pin, because it is pulled up normally (mode INPUT_PULLUP). This falling edge will generate the interrupt."
},
{
"code": null,
"e": 5265,
"s": 4866,
"text": "const int interruptPin = 2;\nvolatile bool isButtonPressed = false;\nvoid setup() {\n Serial.begin(9600);\n pinMode(interruptPin, INPUT_PULLUP);\n attachInterrupt(digitalPinToInterrupt(interruptPin), button_pressed, FALLING);\n}\nvoid loop() {\n if(isButtonPressed){\n Serial.println(\"Button Pressed!\");\n isButtonPressed = false;\n }\n}\nvoid button_pressed() {\n isButtonPressed = true;\n}"
}
] |
Count of all possible combinations of K numbers that sums to N - GeeksforGeeks
|
03 Jan, 2022
Given a number N, the task is to count the combinations of K numbers from 1 to N having a sum equal to N, with duplicates allowed.
Example:
Input: N = 7, K = 3Output:15Explanation:The combinations which lead to the sum N = 7 are: {1, 1, 5}, {1, 5, 1}, {5, 1, 1}, {2, 1, 4}, {1, 2, 4}, {1, 4, 2}, {2, 4, 1}, {4, 1, 2}, {4, 2, 1}, {3, 1, 3}, {1, 3, 3}, {3, 3, 1}, {2, 2, 3}, {2, 3, 2}, {3, 2, 2}
Input: N = 5, K = 5Output: 1Explanation: {1, 1, 1, 1, 1} is the only combination.
Naive Approach: This problem can be solved using recursion and then memoising the result to improve time complexity. To solve this problem, follow the below steps:
Create a function, say countWaysUtil which will accept four parameters that are N, K, sum, and dp. Here N is the sum that K elements are required to have, K is the number of elements consumed, sum is the sum accumulated till now and dp is the matrix to memoise the result. This function will give the number of ways to get the sum in K numbers.Now initially call countWaysUtil with arguments N, K, sum=0 and dp as a matrix filled with all -1.In each recursive call:Check for the base cases:If the sum is equal to N and K become 0, then return 1.If the sum exceeds N and K is still greater than 0, then return 0.Now, run a for loop from 1 to N, to check the result for each outcome.Sum all the results in a variable cnt and return cnt after memoising.Print the answer according to the above observation.
Create a function, say countWaysUtil which will accept four parameters that are N, K, sum, and dp. Here N is the sum that K elements are required to have, K is the number of elements consumed, sum is the sum accumulated till now and dp is the matrix to memoise the result. This function will give the number of ways to get the sum in K numbers.
Now initially call countWaysUtil with arguments N, K, sum=0 and dp as a matrix filled with all -1.
In each recursive call:Check for the base cases:If the sum is equal to N and K become 0, then return 1.If the sum exceeds N and K is still greater than 0, then return 0.Now, run a for loop from 1 to N, to check the result for each outcome.Sum all the results in a variable cnt and return cnt after memoising.
Check for the base cases:If the sum is equal to N and K become 0, then return 1.If the sum exceeds N and K is still greater than 0, then return 0.
If the sum is equal to N and K become 0, then return 1.
If the sum exceeds N and K is still greater than 0, then return 0.
Now, run a for loop from 1 to N, to check the result for each outcome.
Sum all the results in a variable cnt and return cnt after memoising.
Print the answer according to the above observation.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count// all the possible combinations// of K numbers having sum equals to Nint countWaysUtil(int N, int K, int sum, vector<vector<int> >& dp){ // Base Cases if (sum == N and K == 0) { return 1; } if (sum >= N and K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum][K] != -1) { return dp[sum][K]; } // Recursive Calls int cnt = 0; for (int i = 1; i <= N; i++) { cnt += countWaysUtil( N, K - 1, sum + i, dp); } // Returning answer return dp[sum][K] = cnt;} void countWays(int N, int K){ vector<vector<int> > dp(N + 1, vector<int>( K + 1, -1)); cout << countWaysUtil(N, K, 0, dp);} // Driver Codeint main(){ int N = 7, K = 3; countWays(N, K);}
// Java implementation for the above approachclass GFG { // Function to count // all the possible combinations // of K numbers having sum equals to N static int countWaysUtil(int N, int K, int sum, int[][] dp) { // Base Cases if (sum == N && K == 0) { return 1; } if (sum >= N && K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum][K] != -1) { return dp[sum][K]; } // Recursive Calls int cnt = 0; for (int i = 1; i <= N; i++) { cnt += countWaysUtil(N, K - 1, sum + i, dp); } // Returning answer return dp[sum][K] = cnt; } static void countWays(int N, int K) { int[][] dp = new int[N + 1][K + 1]; for (int i = 0; i < N + 1; i++) { for (int j = 0; j < K + 1; j++) { dp[i][j] = -1; } } System.out.print(countWaysUtil(N, K, 0, dp)); } // Driver Code public static void main(String[] args) { int N = 7, K = 3; countWays(N, K); }} // This code is contributed by ukasp.
# Python3 program for the above approach # Function to count all the possible# combinations of K numbers having# sum equals to Ndef countWaysUtil(N, K, sum, dp): # Base Cases if (sum == N and K == 0): return 1 if (sum >= N and K >= 0): return 0 if (K < 0): return 0 # If the result is already memoised if (dp[sum][K] != -1): return dp[sum][K] # Recursive Calls cnt = 0 for i in range(1, N+1): cnt += countWaysUtil(N, K - 1, sum + i, dp) # Returning answer dp[sum][K] = cnt return dp[sum][K] def countWays(N, K): dp = [[-1 for _ in range(K + 1)] for _ in range(N + 1)] print(countWaysUtil(N, K, 0, dp)) # Driver Codeif __name__ == "__main__": N = 7 K = 3 countWays(N, K) # This code is contributed by rakeshsahni
// C# implementation for the above approachusing System;class GFG{ // Function to count// all the possible combinations// of K numbers having sum equals to Nstatic int countWaysUtil(int N, int K, int sum, int [,]dp){ // Base Cases if (sum == N && K == 0) { return 1; } if (sum >= N && K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum, K] != -1) { return dp[sum, K]; } // Recursive Calls int cnt = 0; for (int i = 1; i <= N; i++) { cnt += countWaysUtil( N, K - 1, sum + i, dp); } // Returning answer return dp[sum, K] = cnt;} static void countWays(int N, int K){ int [,]dp = new int[N + 1, K + 1]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < K + 1; j++) { dp[i, j] = -1; } } Console.Write(countWaysUtil(N, K, 0, dp));} // Driver Codepublic static void Main(){ int N = 7, K = 3; countWays(N, K);}} // This code is contributed by Samim Hossain Mondal.
<script>// Javascript program for the above approach // Function to count// all the possible combinations// of K numbers having sum equals to Nfunction countWaysUtil(N, K, sum, dp) { // Base Cases if (sum == N && K == 0) { return 1; } if (sum >= N && K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum][K] != -1) { return dp[sum][K]; } // Recursive Calls let cnt = 0; for (let i = 1; i <= N; i++) { cnt += countWaysUtil( N, K - 1, sum + i, dp); } // Returning answer return dp[sum][K] = cnt;} function countWays(N, K) { let dp = new Array(N + 1).fill(0).map(() => new Array(K + 1).fill(-1)) document.write(countWaysUtil(N, K, 0, dp));} // Driver Codelet N = 7, K = 3;countWays(N, K); // This code is contributed by saurabh_jaiswal.</script>
15
Time Complexity: O(N*K)Space Complexity: O(N*K)
Efficient Approach: This problem can also be solved using the binomial theorem. As the required sum is N with K elements, so suppose the K numbers are:
a1 + a2 + a3 + a4 + ........ + aK = NAccording to the standard principle of partitioning in the binomial theorem, the above equation has a solution which is N+K-1CK-1, where K>=0.But in our case, K>=1.So, therefore N should be substituted with N-K and the equation becomes N-1CK-1
Below is the implementation of the above approach:
C++
C
Java
Python3
C#
Javascript
// C++ program for the above approach#include <iostream>using namespace std; // Method to find factorial of given numberint factorial(int n){ if (n == 0) return 1; return n * factorial(n - 1);} // Function to count all the possible// combinations of K numbers having// sum equals to Nint totalWays(int N, int K){ // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1) * factorial(N - K); int ans = (n1 / n2); // Returning answer return ans;} // Driver codeint main(){ int N = 7; int K = 3; int ans = totalWays(N, K); cout << ans; return 0;} // This code is contributed by Shubham Singh
// C Program for the above approach#include <stdio.h> // method to find factorial of given number int factorial(int n) { if (n == 0) return 1; return n*factorial(n - 1); } // Function to count // all the possible combinations // of K numbers having sum equals to N int totalWays(int N, int K) { // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1)*factorial(N - K); int ans = (n1/n2); // Returning answer return ans; } // Driver method int main() { int N = 7; int K = 3; int ans = totalWays(N, K); printf("%d",ans); return 0; } // This code is contributed by Shubham Singh
// Java Program for the above approachclass Solution{ // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n - 1); } // Function to count // all the possible combinations // of K numbers having sum equals to N static int totalWays(int N, int K) { // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1)*factorial(N - K); int ans = (n1/n2); // Returning answer return ans; } // Driver method public static void main(String[] args) { int N = 7; int K = 3; int ans = totalWays(N, K); System.out.println(ans); }} // This code is contributed by umadevi9616
# Python Program for the above approach from math import factorial class Solution: # Function to count # all the possible combinations # of K numbers having sum equals to N def totalWays(self, N, K): # If N<K if (N < K): return 0 # Storing numerator n1 = factorial(N-1) # Storing denominator n2 = factorial(K-1)*factorial(N-K) ans = (n1//n2) # Returning answer return ans # Driver Codeif __name__ == '__main__': N = 7 K = 3 ob = Solution() ans = ob.totalWays(N, K) print(ans)
// C# Program for the above approachusing System;public class Solution { // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } // Function to count // all the possible combinations // of K numbers having sum equals to N static int totalWays(int N, int K) { // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1) * factorial(N - K); int ans = (n1 / n2); // Returning answer return ans; } // Driver method public static void Main(String[] args) { int N = 7; int K = 3; int ans = totalWays(N, K); Console.WriteLine(ans); }} // This code is contributed by umadevi9616
<script>// Javascript program for the above approach // Method to find factorial of given numberfunction factorial(n){ if (n == 0) return 1; return n * factorial(n - 1);} // Function to count all the possible// combinations of K numbers having// sum equals to Nfunction totalWays( N, K){ // If N<K if (N < K) return 0; // Storing numerator let n1 = factorial(N - 1); // Storing denominator let n2 = factorial(K - 1) * factorial(N - K); let ans = (n1 / n2); // Returning answer return ans;} // Driver codelet N = 7;let K = 3;let ans = totalWays(N, K); document.write(ans); // This code is contributed by Shubham Singh</script>
15
Time complexity: O(N)Auxiliary Space: O(1)
rakeshsahni
_saurabh_jaiswal
samim2000
ukasp
umadevi9616
SHUBHAMSINGH10
binomial coefficient
Memoization
Combinatorial
Mathematical
Mathematical
Combinatorial
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Combinational Sum
Lexicographic rank of a string
Count of subsets with sum equal to X
Print all permutations in sorted (lexicographic) order
Print all possible strings of length k that can be formed from a set of n characters
C++ Data Types
Set in C++ Standard Template Library (STL)
Program to find GCD or HCF of two numbers
Modulo Operator (%) in C/C++ with Examples
Merge two sorted arrays
|
[
{
"code": null,
"e": 25088,
"s": 25060,
"text": "\n03 Jan, 2022"
},
{
"code": null,
"e": 25219,
"s": 25088,
"text": "Given a number N, the task is to count the combinations of K numbers from 1 to N having a sum equal to N, with duplicates allowed."
},
{
"code": null,
"e": 25228,
"s": 25219,
"text": "Example:"
},
{
"code": null,
"e": 25482,
"s": 25228,
"text": "Input: N = 7, K = 3Output:15Explanation:The combinations which lead to the sum N = 7 are: {1, 1, 5}, {1, 5, 1}, {5, 1, 1}, {2, 1, 4}, {1, 2, 4}, {1, 4, 2}, {2, 4, 1}, {4, 1, 2}, {4, 2, 1}, {3, 1, 3}, {1, 3, 3}, {3, 3, 1}, {2, 2, 3}, {2, 3, 2}, {3, 2, 2}"
},
{
"code": null,
"e": 25564,
"s": 25482,
"text": "Input: N = 5, K = 5Output: 1Explanation: {1, 1, 1, 1, 1} is the only combination."
},
{
"code": null,
"e": 25728,
"s": 25564,
"text": "Naive Approach: This problem can be solved using recursion and then memoising the result to improve time complexity. To solve this problem, follow the below steps:"
},
{
"code": null,
"e": 26531,
"s": 25728,
"text": "Create a function, say countWaysUtil which will accept four parameters that are N, K, sum, and dp. Here N is the sum that K elements are required to have, K is the number of elements consumed, sum is the sum accumulated till now and dp is the matrix to memoise the result. This function will give the number of ways to get the sum in K numbers.Now initially call countWaysUtil with arguments N, K, sum=0 and dp as a matrix filled with all -1.In each recursive call:Check for the base cases:If the sum is equal to N and K become 0, then return 1.If the sum exceeds N and K is still greater than 0, then return 0.Now, run a for loop from 1 to N, to check the result for each outcome.Sum all the results in a variable cnt and return cnt after memoising.Print the answer according to the above observation."
},
{
"code": null,
"e": 26876,
"s": 26531,
"text": "Create a function, say countWaysUtil which will accept four parameters that are N, K, sum, and dp. Here N is the sum that K elements are required to have, K is the number of elements consumed, sum is the sum accumulated till now and dp is the matrix to memoise the result. This function will give the number of ways to get the sum in K numbers."
},
{
"code": null,
"e": 26975,
"s": 26876,
"text": "Now initially call countWaysUtil with arguments N, K, sum=0 and dp as a matrix filled with all -1."
},
{
"code": null,
"e": 27284,
"s": 26975,
"text": "In each recursive call:Check for the base cases:If the sum is equal to N and K become 0, then return 1.If the sum exceeds N and K is still greater than 0, then return 0.Now, run a for loop from 1 to N, to check the result for each outcome.Sum all the results in a variable cnt and return cnt after memoising."
},
{
"code": null,
"e": 27431,
"s": 27284,
"text": "Check for the base cases:If the sum is equal to N and K become 0, then return 1.If the sum exceeds N and K is still greater than 0, then return 0."
},
{
"code": null,
"e": 27487,
"s": 27431,
"text": "If the sum is equal to N and K become 0, then return 1."
},
{
"code": null,
"e": 27554,
"s": 27487,
"text": "If the sum exceeds N and K is still greater than 0, then return 0."
},
{
"code": null,
"e": 27625,
"s": 27554,
"text": "Now, run a for loop from 1 to N, to check the result for each outcome."
},
{
"code": null,
"e": 27695,
"s": 27625,
"text": "Sum all the results in a variable cnt and return cnt after memoising."
},
{
"code": null,
"e": 27748,
"s": 27695,
"text": "Print the answer according to the above observation."
},
{
"code": null,
"e": 27799,
"s": 27748,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 27803,
"s": 27799,
"text": "C++"
},
{
"code": null,
"e": 27808,
"s": 27803,
"text": "Java"
},
{
"code": null,
"e": 27816,
"s": 27808,
"text": "Python3"
},
{
"code": null,
"e": 27819,
"s": 27816,
"text": "C#"
},
{
"code": null,
"e": 27830,
"s": 27819,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to count// all the possible combinations// of K numbers having sum equals to Nint countWaysUtil(int N, int K, int sum, vector<vector<int> >& dp){ // Base Cases if (sum == N and K == 0) { return 1; } if (sum >= N and K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum][K] != -1) { return dp[sum][K]; } // Recursive Calls int cnt = 0; for (int i = 1; i <= N; i++) { cnt += countWaysUtil( N, K - 1, sum + i, dp); } // Returning answer return dp[sum][K] = cnt;} void countWays(int N, int K){ vector<vector<int> > dp(N + 1, vector<int>( K + 1, -1)); cout << countWaysUtil(N, K, 0, dp);} // Driver Codeint main(){ int N = 7, K = 3; countWays(N, K);}",
"e": 28811,
"s": 27830,
"text": null
},
{
"code": "// Java implementation for the above approachclass GFG { // Function to count // all the possible combinations // of K numbers having sum equals to N static int countWaysUtil(int N, int K, int sum, int[][] dp) { // Base Cases if (sum == N && K == 0) { return 1; } if (sum >= N && K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum][K] != -1) { return dp[sum][K]; } // Recursive Calls int cnt = 0; for (int i = 1; i <= N; i++) { cnt += countWaysUtil(N, K - 1, sum + i, dp); } // Returning answer return dp[sum][K] = cnt; } static void countWays(int N, int K) { int[][] dp = new int[N + 1][K + 1]; for (int i = 0; i < N + 1; i++) { for (int j = 0; j < K + 1; j++) { dp[i][j] = -1; } } System.out.print(countWaysUtil(N, K, 0, dp)); } // Driver Code public static void main(String[] args) { int N = 7, K = 3; countWays(N, K); }} // This code is contributed by ukasp.",
"e": 30041,
"s": 28811,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to count all the possible# combinations of K numbers having# sum equals to Ndef countWaysUtil(N, K, sum, dp): # Base Cases if (sum == N and K == 0): return 1 if (sum >= N and K >= 0): return 0 if (K < 0): return 0 # If the result is already memoised if (dp[sum][K] != -1): return dp[sum][K] # Recursive Calls cnt = 0 for i in range(1, N+1): cnt += countWaysUtil(N, K - 1, sum + i, dp) # Returning answer dp[sum][K] = cnt return dp[sum][K] def countWays(N, K): dp = [[-1 for _ in range(K + 1)] for _ in range(N + 1)] print(countWaysUtil(N, K, 0, dp)) # Driver Codeif __name__ == \"__main__\": N = 7 K = 3 countWays(N, K) # This code is contributed by rakeshsahni",
"e": 30869,
"s": 30041,
"text": null
},
{
"code": "// C# implementation for the above approachusing System;class GFG{ // Function to count// all the possible combinations// of K numbers having sum equals to Nstatic int countWaysUtil(int N, int K, int sum, int [,]dp){ // Base Cases if (sum == N && K == 0) { return 1; } if (sum >= N && K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum, K] != -1) { return dp[sum, K]; } // Recursive Calls int cnt = 0; for (int i = 1; i <= N; i++) { cnt += countWaysUtil( N, K - 1, sum + i, dp); } // Returning answer return dp[sum, K] = cnt;} static void countWays(int N, int K){ int [,]dp = new int[N + 1, K + 1]; for(int i = 0; i < N + 1; i++) { for(int j = 0; j < K + 1; j++) { dp[i, j] = -1; } } Console.Write(countWaysUtil(N, K, 0, dp));} // Driver Codepublic static void Main(){ int N = 7, K = 3; countWays(N, K);}} // This code is contributed by Samim Hossain Mondal.",
"e": 31960,
"s": 30869,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Function to count// all the possible combinations// of K numbers having sum equals to Nfunction countWaysUtil(N, K, sum, dp) { // Base Cases if (sum == N && K == 0) { return 1; } if (sum >= N && K >= 0) { return 0; } if (K < 0) { return 0; } // If the result is already memoised if (dp[sum][K] != -1) { return dp[sum][K]; } // Recursive Calls let cnt = 0; for (let i = 1; i <= N; i++) { cnt += countWaysUtil( N, K - 1, sum + i, dp); } // Returning answer return dp[sum][K] = cnt;} function countWays(N, K) { let dp = new Array(N + 1).fill(0).map(() => new Array(K + 1).fill(-1)) document.write(countWaysUtil(N, K, 0, dp));} // Driver Codelet N = 7, K = 3;countWays(N, K); // This code is contributed by saurabh_jaiswal.</script>",
"e": 32862,
"s": 31960,
"text": null
},
{
"code": null,
"e": 32865,
"s": 32862,
"text": "15"
},
{
"code": null,
"e": 32913,
"s": 32865,
"text": "Time Complexity: O(N*K)Space Complexity: O(N*K)"
},
{
"code": null,
"e": 33066,
"s": 32913,
"text": "Efficient Approach: This problem can also be solved using the binomial theorem. As the required sum is N with K elements, so suppose the K numbers are:"
},
{
"code": null,
"e": 33349,
"s": 33066,
"text": "a1 + a2 + a3 + a4 + ........ + aK = NAccording to the standard principle of partitioning in the binomial theorem, the above equation has a solution which is N+K-1CK-1, where K>=0.But in our case, K>=1.So, therefore N should be substituted with N-K and the equation becomes N-1CK-1"
},
{
"code": null,
"e": 33400,
"s": 33349,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 33404,
"s": 33400,
"text": "C++"
},
{
"code": null,
"e": 33406,
"s": 33404,
"text": "C"
},
{
"code": null,
"e": 33411,
"s": 33406,
"text": "Java"
},
{
"code": null,
"e": 33419,
"s": 33411,
"text": "Python3"
},
{
"code": null,
"e": 33422,
"s": 33419,
"text": "C#"
},
{
"code": null,
"e": 33433,
"s": 33422,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <iostream>using namespace std; // Method to find factorial of given numberint factorial(int n){ if (n == 0) return 1; return n * factorial(n - 1);} // Function to count all the possible// combinations of K numbers having// sum equals to Nint totalWays(int N, int K){ // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1) * factorial(N - K); int ans = (n1 / n2); // Returning answer return ans;} // Driver codeint main(){ int N = 7; int K = 3; int ans = totalWays(N, K); cout << ans; return 0;} // This code is contributed by Shubham Singh",
"e": 34194,
"s": 33433,
"text": null
},
{
"code": "// C Program for the above approach#include <stdio.h> // method to find factorial of given number int factorial(int n) { if (n == 0) return 1; return n*factorial(n - 1); } // Function to count // all the possible combinations // of K numbers having sum equals to N int totalWays(int N, int K) { // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1)*factorial(N - K); int ans = (n1/n2); // Returning answer return ans; } // Driver method int main() { int N = 7; int K = 3; int ans = totalWays(N, K); printf(\"%d\",ans); return 0; } // This code is contributed by Shubham Singh",
"e": 34916,
"s": 34194,
"text": null
},
{
"code": "// Java Program for the above approachclass Solution{ // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n*factorial(n - 1); } // Function to count // all the possible combinations // of K numbers having sum equals to N static int totalWays(int N, int K) { // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1)*factorial(N - K); int ans = (n1/n2); // Returning answer return ans; } // Driver method public static void main(String[] args) { int N = 7; int K = 3; int ans = totalWays(N, K); System.out.println(ans); }} // This code is contributed by umadevi9616",
"e": 35681,
"s": 34916,
"text": null
},
{
"code": "# Python Program for the above approach from math import factorial class Solution: # Function to count # all the possible combinations # of K numbers having sum equals to N def totalWays(self, N, K): # If N<K if (N < K): return 0 # Storing numerator n1 = factorial(N-1) # Storing denominator n2 = factorial(K-1)*factorial(N-K) ans = (n1//n2) # Returning answer return ans # Driver Codeif __name__ == '__main__': N = 7 K = 3 ob = Solution() ans = ob.totalWays(N, K) print(ans)",
"e": 36266,
"s": 35681,
"text": null
},
{
"code": "// C# Program for the above approachusing System;public class Solution { // method to find factorial of given number static int factorial(int n) { if (n == 0) return 1; return n * factorial(n - 1); } // Function to count // all the possible combinations // of K numbers having sum equals to N static int totalWays(int N, int K) { // If N<K if (N < K) return 0; // Storing numerator int n1 = factorial(N - 1); // Storing denominator int n2 = factorial(K - 1) * factorial(N - K); int ans = (n1 / n2); // Returning answer return ans; } // Driver method public static void Main(String[] args) { int N = 7; int K = 3; int ans = totalWays(N, K); Console.WriteLine(ans); }} // This code is contributed by umadevi9616",
"e": 37051,
"s": 36266,
"text": null
},
{
"code": "<script>// Javascript program for the above approach // Method to find factorial of given numberfunction factorial(n){ if (n == 0) return 1; return n * factorial(n - 1);} // Function to count all the possible// combinations of K numbers having// sum equals to Nfunction totalWays( N, K){ // If N<K if (N < K) return 0; // Storing numerator let n1 = factorial(N - 1); // Storing denominator let n2 = factorial(K - 1) * factorial(N - K); let ans = (n1 / n2); // Returning answer return ans;} // Driver codelet N = 7;let K = 3;let ans = totalWays(N, K); document.write(ans); // This code is contributed by Shubham Singh</script>",
"e": 37754,
"s": 37051,
"text": null
},
{
"code": null,
"e": 37757,
"s": 37754,
"text": "15"
},
{
"code": null,
"e": 37800,
"s": 37757,
"text": "Time complexity: O(N)Auxiliary Space: O(1)"
},
{
"code": null,
"e": 37812,
"s": 37800,
"text": "rakeshsahni"
},
{
"code": null,
"e": 37829,
"s": 37812,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 37839,
"s": 37829,
"text": "samim2000"
},
{
"code": null,
"e": 37845,
"s": 37839,
"text": "ukasp"
},
{
"code": null,
"e": 37857,
"s": 37845,
"text": "umadevi9616"
},
{
"code": null,
"e": 37872,
"s": 37857,
"text": "SHUBHAMSINGH10"
},
{
"code": null,
"e": 37893,
"s": 37872,
"text": "binomial coefficient"
},
{
"code": null,
"e": 37905,
"s": 37893,
"text": "Memoization"
},
{
"code": null,
"e": 37919,
"s": 37905,
"text": "Combinatorial"
},
{
"code": null,
"e": 37932,
"s": 37919,
"text": "Mathematical"
},
{
"code": null,
"e": 37945,
"s": 37932,
"text": "Mathematical"
},
{
"code": null,
"e": 37959,
"s": 37945,
"text": "Combinatorial"
},
{
"code": null,
"e": 38057,
"s": 37959,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 38075,
"s": 38057,
"text": "Combinational Sum"
},
{
"code": null,
"e": 38106,
"s": 38075,
"text": "Lexicographic rank of a string"
},
{
"code": null,
"e": 38143,
"s": 38106,
"text": "Count of subsets with sum equal to X"
},
{
"code": null,
"e": 38198,
"s": 38143,
"text": "Print all permutations in sorted (lexicographic) order"
},
{
"code": null,
"e": 38283,
"s": 38198,
"text": "Print all possible strings of length k that can be formed from a set of n characters"
},
{
"code": null,
"e": 38298,
"s": 38283,
"text": "C++ Data Types"
},
{
"code": null,
"e": 38341,
"s": 38298,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 38383,
"s": 38341,
"text": "Program to find GCD or HCF of two numbers"
},
{
"code": null,
"e": 38426,
"s": 38383,
"text": "Modulo Operator (%) in C/C++ with Examples"
}
] |
Classify Toxic Online Comments with LSTM and GloVe | by Susan Li | Towards Data Science
|
This article shows how to use a simple LSTM and one of the pre-trained GloVe files to create a strong baseline for the toxic comments classification problem.
The article consist of 4 main sections:
Preparing the data
Implementing a simple LSTM (RNN) model
Training the model
Evaluating the model
In the following steps, we will set the key model parameters and split the data.
“MAX_NB_WORDS” sets the maximum number of words to consider as features for tokenizer.
“MAX_SEQUENCE_LENGTH” cuts off texts after this number of words (among the MAX_NB_WORDS most common words).
“VALIDATION_SPLIT” sets a portion of data for validation and not used in training.
“EMBEDDING_DIM” defines the size of the “vector space”.
“GLOVE_DIR” defines the GloVe file directory.
Split the data into the texts and the labels.
In the following step, we remove stopwords, punctuation and make everything lowercase.
Have a look a sample data.
print('Sample data:', texts[1], y[1])
We create a tokenizer, configured to only take into account the MAX_NB_WORDS most common words.
We build the word index.
We can recover the word index that was computed.
tokenizer = Tokenizer(num_words=MAX_NB_WORDS)tokenizer.fit_on_texts(texts)sequences = tokenizer.texts_to_sequences(texts)word_index = tokenizer.word_indexprint('Vocabulary size:', len(word_index))
Turns the lists of integers into a 2D integer tensor of shape (samples, maxlen)
Pad after each sequence.
data = pad_sequences(sequences, padding = 'post', maxlen = MAX_SEQUENCE_LENGTH)print('Shape of data tensor:', data.shape)print('Shape of label tensor:', y.shape)
Shuffle the data.
indices = np.arange(data.shape[0])np.random.shuffle(indices)data = data[indices]labels = y[indices]
Create the train-validation split.
num_validation_samples = int(VALIDATION_SPLIT*data.shape[0])x_train = data[: -num_validation_samples]y_train = labels[: -num_validation_samples]x_val = data[-num_validation_samples: ]y_val = labels[-num_validation_samples: ]print('Number of entries in each category:')print('training: ', y_train.sum(axis=0))print('validation: ', y_val.sum(axis=0))
This is what the data looks like:
print('Tokenized sentences: \n', data[10])print('One hot label: \n', labels[10])
We will use pre-trained GloVe vectors from Stanford to create an index of words mapped to known embeddings, by parsing the data dump of pre-trained embeddings.
Then load word embeddings into an embeddings_index
Create the embedding layers.
Specifies the maximum input length to the Embedding layer.
Make use of the output from the previous embedding layer which outputs a 3-D tensor into the LSTM layer.
Use a Global Max Pooling layer to to reshape the 3D tensor into a 2D one.
We set the dropout layer to drop out 10% of the nodes.
We define the Dense layer to produce a output dimension of 50.
We feed the output into a Dropout layer again.
Finally, we feed the output into a “Sigmoid” layer.
Its time to Compile the model into a static graph for training.
Define the inputs, outputs and configure the learning process.
Set the model to optimize our loss function using “Adam” optimizer, define the loss function to be “binary_crossentropy” .
model = Model(sequence_input, preds)model.compile(loss = 'binary_crossentropy', optimizer='adam', metrics = ['accuracy'])
We can visualize the model’s architect.
tf.keras.utils.plot_model(model)
Feed in a list of 32 padded, indexed sentence for each batch. The validation set will be used to assess whether the model has overfitted.
The model will run for 2 epochs, because even 2 epochs is enough to overfit.
print('Training progress:')history = model.fit(x_train, y_train, epochs = 2, batch_size=32, validation_data=(x_val, y_val))
loss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(loss)+1)plt.plot(epochs, loss, label='Training loss')plt.plot(epochs, val_loss, label='Validation loss')plt.title('Training and validation loss')plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()plt.show();
accuracy = history.history['accuracy']val_accuracy = history.history['val_accuracy']plt.plot(epochs, accuracy, label='Training accuracy')plt.plot(epochs, val_accuracy, label='Validation accuracy')plt.title('Training and validation accuracy')plt.ylabel('Accuracy')plt.xlabel('Epochs')plt.legend()plt.show();
Jupyter notebook can be found on Github. Happy Monday!
|
[
{
"code": null,
"e": 330,
"s": 172,
"text": "This article shows how to use a simple LSTM and one of the pre-trained GloVe files to create a strong baseline for the toxic comments classification problem."
},
{
"code": null,
"e": 370,
"s": 330,
"text": "The article consist of 4 main sections:"
},
{
"code": null,
"e": 389,
"s": 370,
"text": "Preparing the data"
},
{
"code": null,
"e": 428,
"s": 389,
"text": "Implementing a simple LSTM (RNN) model"
},
{
"code": null,
"e": 447,
"s": 428,
"text": "Training the model"
},
{
"code": null,
"e": 468,
"s": 447,
"text": "Evaluating the model"
},
{
"code": null,
"e": 549,
"s": 468,
"text": "In the following steps, we will set the key model parameters and split the data."
},
{
"code": null,
"e": 636,
"s": 549,
"text": "“MAX_NB_WORDS” sets the maximum number of words to consider as features for tokenizer."
},
{
"code": null,
"e": 744,
"s": 636,
"text": "“MAX_SEQUENCE_LENGTH” cuts off texts after this number of words (among the MAX_NB_WORDS most common words)."
},
{
"code": null,
"e": 827,
"s": 744,
"text": "“VALIDATION_SPLIT” sets a portion of data for validation and not used in training."
},
{
"code": null,
"e": 883,
"s": 827,
"text": "“EMBEDDING_DIM” defines the size of the “vector space”."
},
{
"code": null,
"e": 929,
"s": 883,
"text": "“GLOVE_DIR” defines the GloVe file directory."
},
{
"code": null,
"e": 975,
"s": 929,
"text": "Split the data into the texts and the labels."
},
{
"code": null,
"e": 1062,
"s": 975,
"text": "In the following step, we remove stopwords, punctuation and make everything lowercase."
},
{
"code": null,
"e": 1089,
"s": 1062,
"text": "Have a look a sample data."
},
{
"code": null,
"e": 1127,
"s": 1089,
"text": "print('Sample data:', texts[1], y[1])"
},
{
"code": null,
"e": 1223,
"s": 1127,
"text": "We create a tokenizer, configured to only take into account the MAX_NB_WORDS most common words."
},
{
"code": null,
"e": 1248,
"s": 1223,
"text": "We build the word index."
},
{
"code": null,
"e": 1297,
"s": 1248,
"text": "We can recover the word index that was computed."
},
{
"code": null,
"e": 1494,
"s": 1297,
"text": "tokenizer = Tokenizer(num_words=MAX_NB_WORDS)tokenizer.fit_on_texts(texts)sequences = tokenizer.texts_to_sequences(texts)word_index = tokenizer.word_indexprint('Vocabulary size:', len(word_index))"
},
{
"code": null,
"e": 1574,
"s": 1494,
"text": "Turns the lists of integers into a 2D integer tensor of shape (samples, maxlen)"
},
{
"code": null,
"e": 1599,
"s": 1574,
"text": "Pad after each sequence."
},
{
"code": null,
"e": 1761,
"s": 1599,
"text": "data = pad_sequences(sequences, padding = 'post', maxlen = MAX_SEQUENCE_LENGTH)print('Shape of data tensor:', data.shape)print('Shape of label tensor:', y.shape)"
},
{
"code": null,
"e": 1779,
"s": 1761,
"text": "Shuffle the data."
},
{
"code": null,
"e": 1879,
"s": 1779,
"text": "indices = np.arange(data.shape[0])np.random.shuffle(indices)data = data[indices]labels = y[indices]"
},
{
"code": null,
"e": 1914,
"s": 1879,
"text": "Create the train-validation split."
},
{
"code": null,
"e": 2263,
"s": 1914,
"text": "num_validation_samples = int(VALIDATION_SPLIT*data.shape[0])x_train = data[: -num_validation_samples]y_train = labels[: -num_validation_samples]x_val = data[-num_validation_samples: ]y_val = labels[-num_validation_samples: ]print('Number of entries in each category:')print('training: ', y_train.sum(axis=0))print('validation: ', y_val.sum(axis=0))"
},
{
"code": null,
"e": 2297,
"s": 2263,
"text": "This is what the data looks like:"
},
{
"code": null,
"e": 2378,
"s": 2297,
"text": "print('Tokenized sentences: \\n', data[10])print('One hot label: \\n', labels[10])"
},
{
"code": null,
"e": 2538,
"s": 2378,
"text": "We will use pre-trained GloVe vectors from Stanford to create an index of words mapped to known embeddings, by parsing the data dump of pre-trained embeddings."
},
{
"code": null,
"e": 2589,
"s": 2538,
"text": "Then load word embeddings into an embeddings_index"
},
{
"code": null,
"e": 2618,
"s": 2589,
"text": "Create the embedding layers."
},
{
"code": null,
"e": 2677,
"s": 2618,
"text": "Specifies the maximum input length to the Embedding layer."
},
{
"code": null,
"e": 2782,
"s": 2677,
"text": "Make use of the output from the previous embedding layer which outputs a 3-D tensor into the LSTM layer."
},
{
"code": null,
"e": 2856,
"s": 2782,
"text": "Use a Global Max Pooling layer to to reshape the 3D tensor into a 2D one."
},
{
"code": null,
"e": 2911,
"s": 2856,
"text": "We set the dropout layer to drop out 10% of the nodes."
},
{
"code": null,
"e": 2974,
"s": 2911,
"text": "We define the Dense layer to produce a output dimension of 50."
},
{
"code": null,
"e": 3021,
"s": 2974,
"text": "We feed the output into a Dropout layer again."
},
{
"code": null,
"e": 3073,
"s": 3021,
"text": "Finally, we feed the output into a “Sigmoid” layer."
},
{
"code": null,
"e": 3137,
"s": 3073,
"text": "Its time to Compile the model into a static graph for training."
},
{
"code": null,
"e": 3200,
"s": 3137,
"text": "Define the inputs, outputs and configure the learning process."
},
{
"code": null,
"e": 3323,
"s": 3200,
"text": "Set the model to optimize our loss function using “Adam” optimizer, define the loss function to be “binary_crossentropy” ."
},
{
"code": null,
"e": 3469,
"s": 3323,
"text": "model = Model(sequence_input, preds)model.compile(loss = 'binary_crossentropy', optimizer='adam', metrics = ['accuracy'])"
},
{
"code": null,
"e": 3509,
"s": 3469,
"text": "We can visualize the model’s architect."
},
{
"code": null,
"e": 3542,
"s": 3509,
"text": "tf.keras.utils.plot_model(model)"
},
{
"code": null,
"e": 3680,
"s": 3542,
"text": "Feed in a list of 32 padded, indexed sentence for each batch. The validation set will be used to assess whether the model has overfitted."
},
{
"code": null,
"e": 3757,
"s": 3680,
"text": "The model will run for 2 epochs, because even 2 epochs is enough to overfit."
},
{
"code": null,
"e": 3881,
"s": 3757,
"text": "print('Training progress:')history = model.fit(x_train, y_train, epochs = 2, batch_size=32, validation_data=(x_val, y_val))"
},
{
"code": null,
"e": 4178,
"s": 3881,
"text": "loss = history.history['loss']val_loss = history.history['val_loss']epochs = range(1, len(loss)+1)plt.plot(epochs, loss, label='Training loss')plt.plot(epochs, val_loss, label='Validation loss')plt.title('Training and validation loss')plt.xlabel('Epochs')plt.ylabel('Loss')plt.legend()plt.show();"
},
{
"code": null,
"e": 4485,
"s": 4178,
"text": "accuracy = history.history['accuracy']val_accuracy = history.history['val_accuracy']plt.plot(epochs, accuracy, label='Training accuracy')plt.plot(epochs, val_accuracy, label='Validation accuracy')plt.title('Training and validation accuracy')plt.ylabel('Accuracy')plt.xlabel('Epochs')plt.legend()plt.show();"
}
] |
Custom fonts in Power BI — everything you wanted to know! | by Nikola Ilic | Towards Data Science
|
I like Power BI, I really do! If you follow my articles carefully, you would have realized that I truly consider Power BI as an awesome tool — because it gives you an infinite number of possibilities to tell your data story. And, I’m not referring only to out-of-the-box solutions, but also custom-made ones.
However, I’ve recently come across an interesting problem (or, to be brutally honest, it didn’t look so interesting why I was trying to solve it). So, what was it all about?
I was helping my client to build a Power BI report, and one of the main requests was that all visuals should use Roboto font. If you ask yourselves why — the answer is quite simple — they are using Roboto font in all their visual solutions, branding, etc. And, they want their Power BI report to follow that pattern and fit into a general solution. Fair enough...
Now, when you open Power BI Desktop and go to the Format pane of the visual, you can choose between 25 different fonts:
However, there is no Roboto here! So, what should we do?
For those of you who don’t know, you can switch between different themes in your Power BI report. Moreover, since the Power BI theme is nothing more than a simple JSON file, you can create your own theme, or additionally customize the existing one!
I’ve already explained how you can embed a background image in your theme and reuse it for visual branding. Now, we will try to extend our theme with a custom font. Under the View tab, I will choose to Save the current theme, so I can edit the source JSON file directly.
You can also use the built-in Power BI Customize current theme feature to perform a lot of adjustments, but you can’t use it to import custom font in it. I also strongly suggest checking a wonderful tool from powerbi.tips for creating your own theme, but we still need something that doesn’t exist out-of-the-box, so we will have to manually implement our adjustments.
When I open my JSON theme file in Notepad++, I see the current settings for my theme:
The property that I need to use in order to apply font settings is called: “visualStyles”. Let’s add this property and define our requirements:
{"name":"Data Mozart","visualStyles":{"*":{"*":{"*":[{"fontSize":12,"fontFamily":"Roboto","color":{"solid":{}}}]}}},"dataColors":["#8BC7F7","#46B3F3","#009FEF","#008CEE","#0078ED","#0050EB","#0641C8","#0B31A5","#46647C","#235A7A","#005078","#004677","#003C77","#002876","#032164","#061953","#FDAB89","#B687AC","#28738A","#A78F8F","#168980","#293537","#BB4A4A","#B59525","#475052","#6A9FB0","#BD7150","#7B4F71","#1B4D5C","#706060","#0F5C55","#1C2325"],"tableAccent":"#8BC7F7","maximum":"#8BC7F7","center":"#0B31A5","minimum":"#D2D3D5"}
Let me briefly explain what this “visualStyles” definition means: using it, we instructed Power BI to apply Roboto font of size 12 and solid color to ALL of our report visuals! Those stars at the beginning mean — apply this to all visual elements!
Save the JSON file and let’s go back to our Power BI report and import this theme:
You can immediately notice that all my visuals changed to reflect new settings:
If you want to confirm that this is true, just open again Format pane of the visual, and you should see that Roboto font was applied to a visual:
Here, our predefined size of 12pt couldn’t be applied because of other X-axis settings (you see this small yellow exclamation mark warning), but if you check for the title, you should see that it was automatically set to 12, as we intended.
Ok, it worked like a charm for the existing visuals, but what will happen if I insert a brand new visual on my report canvas.
I’ve placed a simple Card visual on the report and dragged my Sales Amount measure:
Roboto 12? Power BI — I love you:)
That worked perfectly! However, there are some potential caveats and limitations to this, that you should be aware of. For example, if you want to apply a specific custom font to titles only (all titles within your report), you should write something like:
{"name":"Data Mozart 2","visualStyles":{"*":{"*":{"title":[{"fontSize":18,"fontFamily":"Roboto","color":{"solid":{}}}]}}},"dataColors":["#8BC7F7","#46B3F3","#009FEF","#008CEE","#0078ED","#0050EB","#0641C8","#0B31A5","#46647C","#235A7A","#005078","#004677","#003C77","#002876","#032164","#061953","#FDAB89","#B687AC","#28738A","#A78F8F","#168980","#293537","#BB4A4A","#B59525","#475052","#6A9FB0","#BD7150","#7B4F71","#1B4D5C","#706060","#0F5C55","#1C2325"],"tableAccent":"#8BC7F7","maximum":"#8BC7F7","center":"#0B31A5","minimum":"#D2D3D5"}
As you see, in “visualStyles” property, I’ve set Roboto font size 18 for all the titles in my report. And, if we go back to a Power BI report, you can see that this works just fine:
But...If you want to adjust “normal” labels, such as axis, data labels, category, etc...
There is no more Roboto in the Fonts drop-down list! As we explicitly instructed Power BI that we want to use Roboto font for titles exclusively, this font will not be available for other visual elements.
One more important thing to keep in mind: if you manually change the font of the visual once you open your .pbix file, BEFORE importing the theme, and then import the theme, changes will not be applied! I don’t know if it is a bug or what, but let me show you what’s the issue:
So, be careful when playing with theme files, as there are obviously some caveats with their usage! The possible solution to this challenge could be: format everything as you like, save the .pbix file, open it, and immediately apply a customized theme! And then, don’t touch anything:)))
Like I said in the very beginning, I like the flexibility that Power BI gives you in order to present your data story in the most appealing way.
As you witnessed, we were able to extend the standard Power BI font library and use a custom font to enhance our report and satisfy the client’s needs.
On the other hand, keep your eyes open when applying adjustments via theme file — there are some obvious limitations (or bugs) that can bring confusion, and you should definitely be aware of them.
Thanks for reading!
Become a member and read every story on Medium!
|
[
{
"code": null,
"e": 481,
"s": 172,
"text": "I like Power BI, I really do! If you follow my articles carefully, you would have realized that I truly consider Power BI as an awesome tool — because it gives you an infinite number of possibilities to tell your data story. And, I’m not referring only to out-of-the-box solutions, but also custom-made ones."
},
{
"code": null,
"e": 655,
"s": 481,
"text": "However, I’ve recently come across an interesting problem (or, to be brutally honest, it didn’t look so interesting why I was trying to solve it). So, what was it all about?"
},
{
"code": null,
"e": 1019,
"s": 655,
"text": "I was helping my client to build a Power BI report, and one of the main requests was that all visuals should use Roboto font. If you ask yourselves why — the answer is quite simple — they are using Roboto font in all their visual solutions, branding, etc. And, they want their Power BI report to follow that pattern and fit into a general solution. Fair enough..."
},
{
"code": null,
"e": 1139,
"s": 1019,
"text": "Now, when you open Power BI Desktop and go to the Format pane of the visual, you can choose between 25 different fonts:"
},
{
"code": null,
"e": 1196,
"s": 1139,
"text": "However, there is no Roboto here! So, what should we do?"
},
{
"code": null,
"e": 1445,
"s": 1196,
"text": "For those of you who don’t know, you can switch between different themes in your Power BI report. Moreover, since the Power BI theme is nothing more than a simple JSON file, you can create your own theme, or additionally customize the existing one!"
},
{
"code": null,
"e": 1716,
"s": 1445,
"text": "I’ve already explained how you can embed a background image in your theme and reuse it for visual branding. Now, we will try to extend our theme with a custom font. Under the View tab, I will choose to Save the current theme, so I can edit the source JSON file directly."
},
{
"code": null,
"e": 2085,
"s": 1716,
"text": "You can also use the built-in Power BI Customize current theme feature to perform a lot of adjustments, but you can’t use it to import custom font in it. I also strongly suggest checking a wonderful tool from powerbi.tips for creating your own theme, but we still need something that doesn’t exist out-of-the-box, so we will have to manually implement our adjustments."
},
{
"code": null,
"e": 2171,
"s": 2085,
"text": "When I open my JSON theme file in Notepad++, I see the current settings for my theme:"
},
{
"code": null,
"e": 2315,
"s": 2171,
"text": "The property that I need to use in order to apply font settings is called: “visualStyles”. Let’s add this property and define our requirements:"
},
{
"code": null,
"e": 2850,
"s": 2315,
"text": "{\"name\":\"Data Mozart\",\"visualStyles\":{\"*\":{\"*\":{\"*\":[{\"fontSize\":12,\"fontFamily\":\"Roboto\",\"color\":{\"solid\":{}}}]}}},\"dataColors\":[\"#8BC7F7\",\"#46B3F3\",\"#009FEF\",\"#008CEE\",\"#0078ED\",\"#0050EB\",\"#0641C8\",\"#0B31A5\",\"#46647C\",\"#235A7A\",\"#005078\",\"#004677\",\"#003C77\",\"#002876\",\"#032164\",\"#061953\",\"#FDAB89\",\"#B687AC\",\"#28738A\",\"#A78F8F\",\"#168980\",\"#293537\",\"#BB4A4A\",\"#B59525\",\"#475052\",\"#6A9FB0\",\"#BD7150\",\"#7B4F71\",\"#1B4D5C\",\"#706060\",\"#0F5C55\",\"#1C2325\"],\"tableAccent\":\"#8BC7F7\",\"maximum\":\"#8BC7F7\",\"center\":\"#0B31A5\",\"minimum\":\"#D2D3D5\"}"
},
{
"code": null,
"e": 3098,
"s": 2850,
"text": "Let me briefly explain what this “visualStyles” definition means: using it, we instructed Power BI to apply Roboto font of size 12 and solid color to ALL of our report visuals! Those stars at the beginning mean — apply this to all visual elements!"
},
{
"code": null,
"e": 3181,
"s": 3098,
"text": "Save the JSON file and let’s go back to our Power BI report and import this theme:"
},
{
"code": null,
"e": 3261,
"s": 3181,
"text": "You can immediately notice that all my visuals changed to reflect new settings:"
},
{
"code": null,
"e": 3407,
"s": 3261,
"text": "If you want to confirm that this is true, just open again Format pane of the visual, and you should see that Roboto font was applied to a visual:"
},
{
"code": null,
"e": 3648,
"s": 3407,
"text": "Here, our predefined size of 12pt couldn’t be applied because of other X-axis settings (you see this small yellow exclamation mark warning), but if you check for the title, you should see that it was automatically set to 12, as we intended."
},
{
"code": null,
"e": 3774,
"s": 3648,
"text": "Ok, it worked like a charm for the existing visuals, but what will happen if I insert a brand new visual on my report canvas."
},
{
"code": null,
"e": 3858,
"s": 3774,
"text": "I’ve placed a simple Card visual on the report and dragged my Sales Amount measure:"
},
{
"code": null,
"e": 3893,
"s": 3858,
"text": "Roboto 12? Power BI — I love you:)"
},
{
"code": null,
"e": 4150,
"s": 3893,
"text": "That worked perfectly! However, there are some potential caveats and limitations to this, that you should be aware of. For example, if you want to apply a specific custom font to titles only (all titles within your report), you should write something like:"
},
{
"code": null,
"e": 4691,
"s": 4150,
"text": "{\"name\":\"Data Mozart 2\",\"visualStyles\":{\"*\":{\"*\":{\"title\":[{\"fontSize\":18,\"fontFamily\":\"Roboto\",\"color\":{\"solid\":{}}}]}}},\"dataColors\":[\"#8BC7F7\",\"#46B3F3\",\"#009FEF\",\"#008CEE\",\"#0078ED\",\"#0050EB\",\"#0641C8\",\"#0B31A5\",\"#46647C\",\"#235A7A\",\"#005078\",\"#004677\",\"#003C77\",\"#002876\",\"#032164\",\"#061953\",\"#FDAB89\",\"#B687AC\",\"#28738A\",\"#A78F8F\",\"#168980\",\"#293537\",\"#BB4A4A\",\"#B59525\",\"#475052\",\"#6A9FB0\",\"#BD7150\",\"#7B4F71\",\"#1B4D5C\",\"#706060\",\"#0F5C55\",\"#1C2325\"],\"tableAccent\":\"#8BC7F7\",\"maximum\":\"#8BC7F7\",\"center\":\"#0B31A5\",\"minimum\":\"#D2D3D5\"}"
},
{
"code": null,
"e": 4873,
"s": 4691,
"text": "As you see, in “visualStyles” property, I’ve set Roboto font size 18 for all the titles in my report. And, if we go back to a Power BI report, you can see that this works just fine:"
},
{
"code": null,
"e": 4962,
"s": 4873,
"text": "But...If you want to adjust “normal” labels, such as axis, data labels, category, etc..."
},
{
"code": null,
"e": 5167,
"s": 4962,
"text": "There is no more Roboto in the Fonts drop-down list! As we explicitly instructed Power BI that we want to use Roboto font for titles exclusively, this font will not be available for other visual elements."
},
{
"code": null,
"e": 5445,
"s": 5167,
"text": "One more important thing to keep in mind: if you manually change the font of the visual once you open your .pbix file, BEFORE importing the theme, and then import the theme, changes will not be applied! I don’t know if it is a bug or what, but let me show you what’s the issue:"
},
{
"code": null,
"e": 5733,
"s": 5445,
"text": "So, be careful when playing with theme files, as there are obviously some caveats with their usage! The possible solution to this challenge could be: format everything as you like, save the .pbix file, open it, and immediately apply a customized theme! And then, don’t touch anything:)))"
},
{
"code": null,
"e": 5878,
"s": 5733,
"text": "Like I said in the very beginning, I like the flexibility that Power BI gives you in order to present your data story in the most appealing way."
},
{
"code": null,
"e": 6030,
"s": 5878,
"text": "As you witnessed, we were able to extend the standard Power BI font library and use a custom font to enhance our report and satisfy the client’s needs."
},
{
"code": null,
"e": 6227,
"s": 6030,
"text": "On the other hand, keep your eyes open when applying adjustments via theme file — there are some obvious limitations (or bugs) that can bring confusion, and you should definitely be aware of them."
},
{
"code": null,
"e": 6247,
"s": 6227,
"text": "Thanks for reading!"
}
] |
How to use PowerShell Break with the Label.
|
When the break statement is mentioned with the Label, PowerShell exits to the label instead of exiting the current loop.
$i = 1
while ($i -lt 10) {
Write-Output "i = $i"
if($i -eq 5){
Write-Output "Break statement executed"
Break :mylable
}
$i++
}
Write-Output "Entering to another loop"
$j = 1
:mylable while($j -lt 3){
Write-Output "j = $j"
$j++
}
i = 1
i = 2
i = 3
i = 4
i = 5
Break statement executed
Entering to another loop
j = 1
j = 2
As you can see in the above example when the value of 5 executed, the block containing label (mylable) is also executed and execution moves to another loop.
|
[
{
"code": null,
"e": 1183,
"s": 1062,
"text": "When the break statement is mentioned with the Label, PowerShell exits to the label instead of exiting the current loop."
},
{
"code": null,
"e": 1442,
"s": 1183,
"text": "$i = 1\nwhile ($i -lt 10) {\n Write-Output \"i = $i\"\n if($i -eq 5){\n Write-Output \"Break statement executed\"\n Break :mylable\n }\n $i++\n}\nWrite-Output \"Entering to another loop\"\n$j = 1\n:mylable while($j -lt 3){\n Write-Output \"j = $j\"\n $j++\n}"
},
{
"code": null,
"e": 1534,
"s": 1442,
"text": "i = 1\ni = 2\ni = 3\ni = 4\ni = 5\nBreak statement executed\nEntering to another loop\nj = 1\nj = 2"
},
{
"code": null,
"e": 1691,
"s": 1534,
"text": "As you can see in the above example when the value of 5 executed, the block containing label (mylable) is also executed and execution moves to another loop."
}
] |
How to use Python Numpy to generate Random Numbers?
|
The random module in Numpy package contains many functions for generation of random numbers
numpy.random.rand() − Create an array of the given shape and populate it with random samples
>>> import numpy as np
>>> np.random.rand(3,2)
array([[0.10339983, 0.54395499],
[0.31719352, 0.51220189],
[0.98935914, 0.8240609 ]])
numpy.random.randn() − Return a sample (or samples) from the “standard normal” distribution.
>>> np.random.randn()
-0.6808986872330651
numpy.random.randint() − Return random integers from low (inclusive) to high (exclusive).
>>> np.random.randint(5, size=(2, 4))
array([[2, 4, 0, 4],
[3, 4, 1, 2]])
numpy.random.random() − Return random floats in the half-open interval [0.0, 1.0).
>>> np.random.random_sample()
0.054638060174776126
|
[
{
"code": null,
"e": 1154,
"s": 1062,
"text": "The random module in Numpy package contains many functions for generation of random numbers"
},
{
"code": null,
"e": 1247,
"s": 1154,
"text": "numpy.random.rand() − Create an array of the given shape and populate it with random samples"
},
{
"code": null,
"e": 1380,
"s": 1247,
"text": ">>> import numpy as np\n>>> np.random.rand(3,2)\narray([[0.10339983, 0.54395499],\n[0.31719352, 0.51220189],\n[0.98935914, 0.8240609 ]])"
},
{
"code": null,
"e": 1473,
"s": 1380,
"text": "numpy.random.randn() − Return a sample (or samples) from the “standard normal” distribution."
},
{
"code": null,
"e": 1515,
"s": 1473,
"text": ">>> np.random.randn()\n-0.6808986872330651"
},
{
"code": null,
"e": 1605,
"s": 1515,
"text": "numpy.random.randint() − Return random integers from low (inclusive) to high (exclusive)."
},
{
"code": null,
"e": 1679,
"s": 1605,
"text": ">>> np.random.randint(5, size=(2, 4))\narray([[2, 4, 0, 4],\n[3, 4, 1, 2]])"
},
{
"code": null,
"e": 1762,
"s": 1679,
"text": "numpy.random.random() − Return random floats in the half-open interval [0.0, 1.0)."
},
{
"code": null,
"e": 1815,
"s": 1762,
"text": ">>> np.random.random_sample()\n0.054638060174776126\n\n"
}
] |
DAX Time Intelligence - TOTALMTD function
|
Evaluates the value of the expression for the month to date, in the current context.
TOTALMTD (<expression>, <dates>, [<filter>])
expression
An expression that returns a scalar value.
dates
A column that contains dates.
filter
Optional.
An expression that specifies a filter to apply to the current context.
A scalar value.
The dates parameter can be any of the following −
A reference to a date/time column.
A reference to a date/time column.
A table expression that returns a single column of date/time values.
A table expression that returns a single column of date/time values.
A Boolean expression that defines a single-column table of date/time values.
A Boolean expression that defines a single-column table of date/time values.
Constraints on Boolean expressions −
The expression cannot reference a calculated field.
The expression cannot reference a calculated field.
The expression cannot use CALCULATE function.
The expression cannot use CALCULATE function.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
The expression cannot use any function that scans a table or returns a table, including aggregation functions.
However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value.
The filter parameter can be a Boolean expression or a table expression that defines a filter.
If the data has been filtered, the function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter parameter, any existing filters on that column are removed, and the filter used in the filter parameter is applied instead.
Month Running Sum:= TOTALMTD (SUM (Sales[Sales Amount]),Sales[Date])
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2086,
"s": 2001,
"text": "Evaluates the value of the expression for the month to date, in the current context."
},
{
"code": null,
"e": 2133,
"s": 2086,
"text": "TOTALMTD (<expression>, <dates>, [<filter>]) \n"
},
{
"code": null,
"e": 2144,
"s": 2133,
"text": "expression"
},
{
"code": null,
"e": 2187,
"s": 2144,
"text": "An expression that returns a scalar value."
},
{
"code": null,
"e": 2193,
"s": 2187,
"text": "dates"
},
{
"code": null,
"e": 2223,
"s": 2193,
"text": "A column that contains dates."
},
{
"code": null,
"e": 2230,
"s": 2223,
"text": "filter"
},
{
"code": null,
"e": 2240,
"s": 2230,
"text": "Optional."
},
{
"code": null,
"e": 2311,
"s": 2240,
"text": "An expression that specifies a filter to apply to the current context."
},
{
"code": null,
"e": 2327,
"s": 2311,
"text": "A scalar value."
},
{
"code": null,
"e": 2377,
"s": 2327,
"text": "The dates parameter can be any of the following −"
},
{
"code": null,
"e": 2412,
"s": 2377,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2447,
"s": 2412,
"text": "A reference to a date/time column."
},
{
"code": null,
"e": 2516,
"s": 2447,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2585,
"s": 2516,
"text": "A table expression that returns a single column of date/time values."
},
{
"code": null,
"e": 2662,
"s": 2585,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2739,
"s": 2662,
"text": "A Boolean expression that defines a single-column table of date/time values."
},
{
"code": null,
"e": 2776,
"s": 2739,
"text": "Constraints on Boolean expressions −"
},
{
"code": null,
"e": 2828,
"s": 2776,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2880,
"s": 2828,
"text": "The expression cannot reference a calculated field."
},
{
"code": null,
"e": 2926,
"s": 2880,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 2972,
"s": 2926,
"text": "The expression cannot use CALCULATE function."
},
{
"code": null,
"e": 3083,
"s": 2972,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3194,
"s": 3083,
"text": "The expression cannot use any function that scans a table or returns a table, including aggregation functions."
},
{
"code": null,
"e": 3310,
"s": 3194,
"text": "However, a Boolean expression can use any function that looks up a single value, or that calculates a scalar value."
},
{
"code": null,
"e": 3404,
"s": 3310,
"text": "The filter parameter can be a Boolean expression or a table expression that defines a filter."
},
{
"code": null,
"e": 3722,
"s": 3404,
"text": "If the data has been filtered, the function changes the context in which the data is filtered, and evaluates the expression in the new context that you specify. For each column used in a filter parameter, any existing filters on that column are removed, and the filter used in the filter parameter is applied instead."
},
{
"code": null,
"e": 3792,
"s": 3722,
"text": "Month Running Sum:= TOTALMTD (SUM (Sales[Sales Amount]),Sales[Date]) "
},
{
"code": null,
"e": 3827,
"s": 3792,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3841,
"s": 3827,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3874,
"s": 3841,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3888,
"s": 3874,
"text": " Randy Minder"
},
{
"code": null,
"e": 3923,
"s": 3888,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3937,
"s": 3923,
"text": " Randy Minder"
},
{
"code": null,
"e": 3944,
"s": 3937,
"text": " Print"
},
{
"code": null,
"e": 3955,
"s": 3944,
"text": " Add Notes"
}
] |
Return pointer from functions in C
|
We have seen in the last chapter how C programming allows to return an array from a function. Similarly, C also allows to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example −
int * myFunction() {
.
.
.
}
Second point to remember is that, it is not a good idea to return the address of a local variable outside the function, so you would have to define the local variable as static variable.
Now, consider the following function which will generate 10 random numbers and return them using an array name which represents a pointer, i.e., address of first array element.
#include <stdio.h>
#include <time.h>
/* function to generate and return random numbers. */
int * getRandom( ) {
static int r[10];
int i;
/* set the seed */
srand( (unsigned)time( NULL ) );
for ( i = 0; i < 10; ++i) {
r[i] = rand();
printf("%d\n", r[i] );
}
return r;
}
/* main function to call above defined function */
int main () {
/* a pointer to an int */
int *p;
int i;
p = getRandom();
for ( i = 0; i < 10; i++ ) {
printf("*(p + [%d]) : %d\n", i, *(p + i) );
}
return 0;
}
When the above code is compiled together and executed, it produces the following result −
1523198053
1187214107
1108300978
430494959
1421301276
930971084
123250484
106932140
1604461820
149169022
*(p + [0]) : 1523198053
*(p + [1]) : 1187214107
*(p + [2]) : 1108300978
*(p + [3]) : 430494959
*(p + [4]) : 1421301276
*(p + [5]) : 930971084
*(p + [6]) : 123250484
*(p + [7]) : 106932140
*(p + [8]) : 1604461820
*(p + [9]) : 149169022
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 2337,
"s": 2084,
"text": "We have seen in the last chapter how C programming allows to return an array from a function. Similarly, C also allows to return a pointer from a function. To do so, you would have to declare a function returning a pointer as in the following example −"
},
{
"code": null,
"e": 2375,
"s": 2337,
"text": "int * myFunction() {\n .\n .\n .\n}"
},
{
"code": null,
"e": 2562,
"s": 2375,
"text": "Second point to remember is that, it is not a good idea to return the address of a local variable outside the function, so you would have to define the local variable as static variable."
},
{
"code": null,
"e": 2739,
"s": 2562,
"text": "Now, consider the following function which will generate 10 random numbers and return them using an array name which represents a pointer, i.e., address of first array element."
},
{
"code": null,
"e": 3296,
"s": 2739,
"text": "#include <stdio.h>\n#include <time.h>\n \n/* function to generate and return random numbers. */\nint * getRandom( ) {\n\n static int r[10];\n int i;\n \n /* set the seed */\n srand( (unsigned)time( NULL ) );\n\t\n for ( i = 0; i < 10; ++i) {\n r[i] = rand();\n printf(\"%d\\n\", r[i] );\n }\n \n return r;\n}\n \n/* main function to call above defined function */\nint main () {\n\n /* a pointer to an int */\n int *p;\n int i;\n\n p = getRandom();\n\t\n for ( i = 0; i < 10; i++ ) {\n printf(\"*(p + [%d]) : %d\\n\", i, *(p + i) );\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3386,
"s": 3296,
"text": "When the above code is compiled together and executed, it produces the following result −"
},
{
"code": null,
"e": 3727,
"s": 3386,
"text": "1523198053\n1187214107\n1108300978\n430494959\n1421301276\n930971084\n123250484\n106932140\n1604461820\n149169022\n*(p + [0]) : 1523198053\n*(p + [1]) : 1187214107\n*(p + [2]) : 1108300978\n*(p + [3]) : 430494959\n*(p + [4]) : 1421301276\n*(p + [5]) : 930971084\n*(p + [6]) : 123250484\n*(p + [7]) : 106932140\n*(p + [8]) : 1604461820\n*(p + [9]) : 149169022\n"
},
{
"code": null,
"e": 3734,
"s": 3727,
"text": " Print"
},
{
"code": null,
"e": 3745,
"s": 3734,
"text": " Add Notes"
}
] |
CSV file management using C++ - GeeksforGeeks
|
25 Jun, 2020
CSV is a simple file format used to store tabular data such as a spreadsheet or a database. CSV stands for Comma Separated Values. The data fields in a CSV file are separated/delimited by a comma (‘, ‘) and the individual rows are separated by a newline (‘\n’). CSV File management in C++ is similar to text-type file management, except for a few modifications.
This article discusses about how to create, update and delete records in a CSV file:
Note: Here, a reportcard.csv file has been created to store the student’s roll number, name and marks in math, physics, chemistry and biology.
Create operation:The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\n’ after the end of each row.CREATECREATEvoid create(){ // file pointer fstream fout; // opens an existing csv file or creates a new file. fout.open("reportcard.csv", ios::out | ios::app); cout << "Enter the details of 5 students:" << " roll name maths phy chem bio"; << endl; int i, roll, phy, chem, math, bio; string name; // Read the input for (i = 0; i < 5; i++) { cin >> roll >> name >> math >> phy >> chem >> bio; // Insert the data to file fout << roll << ", " << name << ", " << math << ", " << phy << ", " << chem << ", " << bio << "\n"; }}Output:Read a particular record:In reading a CSV file, the following approach is implemented:-Using getline(), file pointer and ‘\n’ as the delimiter, read an entire row and store it in a string variable.Using stringstream, separate the row into words.Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc.READREADvoid read_record(){ // File pointer fstream fin; // Open an existing file fin.open("reportcard.csv", ios::in); // Get the roll number // of which the data is required int rollnum, roll2, count = 0; cout << "Enter the roll number " << "of the student to display details: "; cin >> rollnum; // Read the Data from the file // as String Vector vector<string> row; string line, word, temp; while (fin >> temp) { row.clear(); // read an entire row and // store it in a string variable 'line' getline(fin, line); // used for breaking words stringstream s(line); // read every column data of a row and // store it in a string variable, 'word' while (getline(s, word, ', ')) { // add all the column data // of a row to a vector row.push_back(word); } // convert string to integer for comparision roll2 = stoi(row[0]); // Compare the roll number if (roll2 == rollnum) { // Print the found data count = 1; cout << "Details of Roll " << row[0] << " : \n"; cout << "Name: " << row[1] << "\n"; cout << "Maths: " << row[2] << "\n"; cout << "Physics: " << row[3] << "\n"; cout << "Chemistry: " << row[4] << "\n"; cout << "Biology: " << row[5] << "\n"; break; } } if (count == 0) cout << "Record not found\n";}Output:Update a record:The following approach is implemented while updating a record:-Read data from a file and compare it with the user input, as explained under read operation.Ask the user to enter new values for the record to be updated.update row[index] with the new data. Here, index refers to the required column field that is to be updated.Write the updated record and all other records into a new file(‘reportcardnew.csv’).At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’UPDATEUPDATEvoid update_recode(){ // File pointer fstream fin, fout; // Open an existing record fin.open("reportcard.csv", ios::in); // Create a new file to store updated data fout.open("reportcardnew.csv", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number from the user cout << "Enter the roll number " << "of the record to be updated: "; cin >> rollnum; // Get the data to be updated cout << "Enter the subject " << "to be updated(M/P/C/B): "; cin >> sub; // Determine the index of the subject // where Maths has index 2, // Physics has index 3, and so on if (sub == 'm' || sub == 'M') index = 2; else if (sub == 'p' || sub == 'P') index = 3; else if (sub == 'c' || sub == 'C') index = 4; else if (sub == 'b' || sub == 'B') index = 5; else { cout << "Wrong choice.Enter again\n"; update_record(); } // Get the new marks cout << "Enter new marks: "; cin >> new_marks; // Traverse the file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } roll1 = stoi(row[0]); int row_size = row.size(); if (roll1 == rollnum) { count = 1; stringstream convert; // sending a number as a stream into output string convert << new_marks; // the str() converts number into string row[index] = convert.str(); if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // write the updated data // into a new file 'reportcardnew.csv' // using fout fout << row[i] << ", "; } fout << row[row_size - 1] << "\n"; } } else { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // writing other existing records // into the new file using fout. fout << row[i] << ", "; } // the last column data ends with a '\n' fout << row[row_size - 1] << "\n"; } } if (fin.eof()) break; } if (count == 0) cout << "Record not found\n"; fin.close(); fout.close(); // removing the existing file remove("reportcard.csv"); // renaming the updated file with the existing file name rename("reportcardnew.csv", "reportcard.csv");}Output:Delete a record:The following approach is implemented while deleting a recordRead data from a file and compare it with the user input, as explained under read and update operation.Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).Remove the old file, and rename the new file, with the old file’s name.DELETEDELETEvoid delete_record(){ // Open FIle pointers fstream fin, fout; // Open the existing file fin.open("reportcard.csv", ios::in); // Create a new file to store the non-deleted data fout.open("reportcardnew.csv", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number // to decide the data to be deleted cout << "Enter the roll number " << "of the record to be deleted: "; cin >> rollnum; // Check if this record exists // If exists, leave it and // add all other data to the new file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } int row_size = row.size(); roll1 = stoi(row[0]); // writing all records, // except the record to be deleted, // into the new file 'reportcardnew.csv' // using fout pointer if (roll1 != rollnum) { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { fout << row[i] << ", "; } fout << row[row_size - 1] << "\n"; } } else { count = 1; } if (fin.eof()) break; } if (count == 1) cout << "Record deleted\n"; else cout << "Record not found\n"; // Close the pointers fin.close(); fout.close(); // removing the existing file remove("reportcard.csv"); // renaming the new file with the existing file name rename("reportcardnew.csv", "reportcard.csv");}Output:
Create operation:The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\n’ after the end of each row.CREATECREATEvoid create(){ // file pointer fstream fout; // opens an existing csv file or creates a new file. fout.open("reportcard.csv", ios::out | ios::app); cout << "Enter the details of 5 students:" << " roll name maths phy chem bio"; << endl; int i, roll, phy, chem, math, bio; string name; // Read the input for (i = 0; i < 5; i++) { cin >> roll >> name >> math >> phy >> chem >> bio; // Insert the data to file fout << roll << ", " << name << ", " << math << ", " << phy << ", " << chem << ", " << bio << "\n"; }}Output:
The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\n’ after the end of each row.
CREATE
void create(){ // file pointer fstream fout; // opens an existing csv file or creates a new file. fout.open("reportcard.csv", ios::out | ios::app); cout << "Enter the details of 5 students:" << " roll name maths phy chem bio"; << endl; int i, roll, phy, chem, math, bio; string name; // Read the input for (i = 0; i < 5; i++) { cin >> roll >> name >> math >> phy >> chem >> bio; // Insert the data to file fout << roll << ", " << name << ", " << math << ", " << phy << ", " << chem << ", " << bio << "\n"; }}
Output:
Read a particular record:In reading a CSV file, the following approach is implemented:-Using getline(), file pointer and ‘\n’ as the delimiter, read an entire row and store it in a string variable.Using stringstream, separate the row into words.Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc.READREADvoid read_record(){ // File pointer fstream fin; // Open an existing file fin.open("reportcard.csv", ios::in); // Get the roll number // of which the data is required int rollnum, roll2, count = 0; cout << "Enter the roll number " << "of the student to display details: "; cin >> rollnum; // Read the Data from the file // as String Vector vector<string> row; string line, word, temp; while (fin >> temp) { row.clear(); // read an entire row and // store it in a string variable 'line' getline(fin, line); // used for breaking words stringstream s(line); // read every column data of a row and // store it in a string variable, 'word' while (getline(s, word, ', ')) { // add all the column data // of a row to a vector row.push_back(word); } // convert string to integer for comparision roll2 = stoi(row[0]); // Compare the roll number if (roll2 == rollnum) { // Print the found data count = 1; cout << "Details of Roll " << row[0] << " : \n"; cout << "Name: " << row[1] << "\n"; cout << "Maths: " << row[2] << "\n"; cout << "Physics: " << row[3] << "\n"; cout << "Chemistry: " << row[4] << "\n"; cout << "Biology: " << row[5] << "\n"; break; } } if (count == 0) cout << "Record not found\n";}Output:
In reading a CSV file, the following approach is implemented:-
Using getline(), file pointer and ‘\n’ as the delimiter, read an entire row and store it in a string variable.Using stringstream, separate the row into words.Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.
Using getline(), file pointer and ‘\n’ as the delimiter, read an entire row and store it in a string variable.
Using stringstream, separate the row into words.
Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.
Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.
Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc.
READ
void read_record(){ // File pointer fstream fin; // Open an existing file fin.open("reportcard.csv", ios::in); // Get the roll number // of which the data is required int rollnum, roll2, count = 0; cout << "Enter the roll number " << "of the student to display details: "; cin >> rollnum; // Read the Data from the file // as String Vector vector<string> row; string line, word, temp; while (fin >> temp) { row.clear(); // read an entire row and // store it in a string variable 'line' getline(fin, line); // used for breaking words stringstream s(line); // read every column data of a row and // store it in a string variable, 'word' while (getline(s, word, ', ')) { // add all the column data // of a row to a vector row.push_back(word); } // convert string to integer for comparision roll2 = stoi(row[0]); // Compare the roll number if (roll2 == rollnum) { // Print the found data count = 1; cout << "Details of Roll " << row[0] << " : \n"; cout << "Name: " << row[1] << "\n"; cout << "Maths: " << row[2] << "\n"; cout << "Physics: " << row[3] << "\n"; cout << "Chemistry: " << row[4] << "\n"; cout << "Biology: " << row[5] << "\n"; break; } } if (count == 0) cout << "Record not found\n";}
Output:
Update a record:The following approach is implemented while updating a record:-Read data from a file and compare it with the user input, as explained under read operation.Ask the user to enter new values for the record to be updated.update row[index] with the new data. Here, index refers to the required column field that is to be updated.Write the updated record and all other records into a new file(‘reportcardnew.csv’).At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’UPDATEUPDATEvoid update_recode(){ // File pointer fstream fin, fout; // Open an existing record fin.open("reportcard.csv", ios::in); // Create a new file to store updated data fout.open("reportcardnew.csv", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number from the user cout << "Enter the roll number " << "of the record to be updated: "; cin >> rollnum; // Get the data to be updated cout << "Enter the subject " << "to be updated(M/P/C/B): "; cin >> sub; // Determine the index of the subject // where Maths has index 2, // Physics has index 3, and so on if (sub == 'm' || sub == 'M') index = 2; else if (sub == 'p' || sub == 'P') index = 3; else if (sub == 'c' || sub == 'C') index = 4; else if (sub == 'b' || sub == 'B') index = 5; else { cout << "Wrong choice.Enter again\n"; update_record(); } // Get the new marks cout << "Enter new marks: "; cin >> new_marks; // Traverse the file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } roll1 = stoi(row[0]); int row_size = row.size(); if (roll1 == rollnum) { count = 1; stringstream convert; // sending a number as a stream into output string convert << new_marks; // the str() converts number into string row[index] = convert.str(); if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // write the updated data // into a new file 'reportcardnew.csv' // using fout fout << row[i] << ", "; } fout << row[row_size - 1] << "\n"; } } else { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // writing other existing records // into the new file using fout. fout << row[i] << ", "; } // the last column data ends with a '\n' fout << row[row_size - 1] << "\n"; } } if (fin.eof()) break; } if (count == 0) cout << "Record not found\n"; fin.close(); fout.close(); // removing the existing file remove("reportcard.csv"); // renaming the updated file with the existing file name rename("reportcardnew.csv", "reportcard.csv");}Output:
The following approach is implemented while updating a record:-
Read data from a file and compare it with the user input, as explained under read operation.Ask the user to enter new values for the record to be updated.update row[index] with the new data. Here, index refers to the required column field that is to be updated.Write the updated record and all other records into a new file(‘reportcardnew.csv’).At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’
Read data from a file and compare it with the user input, as explained under read operation.
Ask the user to enter new values for the record to be updated.
update row[index] with the new data. Here, index refers to the required column field that is to be updated.
Write the updated record and all other records into a new file(‘reportcardnew.csv’).
At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’
UPDATE
void update_recode(){ // File pointer fstream fin, fout; // Open an existing record fin.open("reportcard.csv", ios::in); // Create a new file to store updated data fout.open("reportcardnew.csv", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number from the user cout << "Enter the roll number " << "of the record to be updated: "; cin >> rollnum; // Get the data to be updated cout << "Enter the subject " << "to be updated(M/P/C/B): "; cin >> sub; // Determine the index of the subject // where Maths has index 2, // Physics has index 3, and so on if (sub == 'm' || sub == 'M') index = 2; else if (sub == 'p' || sub == 'P') index = 3; else if (sub == 'c' || sub == 'C') index = 4; else if (sub == 'b' || sub == 'B') index = 5; else { cout << "Wrong choice.Enter again\n"; update_record(); } // Get the new marks cout << "Enter new marks: "; cin >> new_marks; // Traverse the file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } roll1 = stoi(row[0]); int row_size = row.size(); if (roll1 == rollnum) { count = 1; stringstream convert; // sending a number as a stream into output string convert << new_marks; // the str() converts number into string row[index] = convert.str(); if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // write the updated data // into a new file 'reportcardnew.csv' // using fout fout << row[i] << ", "; } fout << row[row_size - 1] << "\n"; } } else { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // writing other existing records // into the new file using fout. fout << row[i] << ", "; } // the last column data ends with a '\n' fout << row[row_size - 1] << "\n"; } } if (fin.eof()) break; } if (count == 0) cout << "Record not found\n"; fin.close(); fout.close(); // removing the existing file remove("reportcard.csv"); // renaming the updated file with the existing file name rename("reportcardnew.csv", "reportcard.csv");}
Output:
Delete a record:The following approach is implemented while deleting a recordRead data from a file and compare it with the user input, as explained under read and update operation.Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).Remove the old file, and rename the new file, with the old file’s name.DELETEDELETEvoid delete_record(){ // Open FIle pointers fstream fin, fout; // Open the existing file fin.open("reportcard.csv", ios::in); // Create a new file to store the non-deleted data fout.open("reportcardnew.csv", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number // to decide the data to be deleted cout << "Enter the roll number " << "of the record to be deleted: "; cin >> rollnum; // Check if this record exists // If exists, leave it and // add all other data to the new file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } int row_size = row.size(); roll1 = stoi(row[0]); // writing all records, // except the record to be deleted, // into the new file 'reportcardnew.csv' // using fout pointer if (roll1 != rollnum) { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { fout << row[i] << ", "; } fout << row[row_size - 1] << "\n"; } } else { count = 1; } if (fin.eof()) break; } if (count == 1) cout << "Record deleted\n"; else cout << "Record not found\n"; // Close the pointers fin.close(); fout.close(); // removing the existing file remove("reportcard.csv"); // renaming the new file with the existing file name rename("reportcardnew.csv", "reportcard.csv");}Output:
The following approach is implemented while deleting a record
Read data from a file and compare it with the user input, as explained under read and update operation.Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).Remove the old file, and rename the new file, with the old file’s name.
Read data from a file and compare it with the user input, as explained under read and update operation.
Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).
Remove the old file, and rename the new file, with the old file’s name.
DELETE
void delete_record(){ // Open FIle pointers fstream fin, fout; // Open the existing file fin.open("reportcard.csv", ios::in); // Create a new file to store the non-deleted data fout.open("reportcardnew.csv", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number // to decide the data to be deleted cout << "Enter the roll number " << "of the record to be deleted: "; cin >> rollnum; // Check if this record exists // If exists, leave it and // add all other data to the new file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } int row_size = row.size(); roll1 = stoi(row[0]); // writing all records, // except the record to be deleted, // into the new file 'reportcardnew.csv' // using fout pointer if (roll1 != rollnum) { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { fout << row[i] << ", "; } fout << row[row_size - 1] << "\n"; } } else { count = 1; } if (fin.eof()) break; } if (count == 1) cout << "Record deleted\n"; else cout << "Record not found\n"; // Close the pointers fin.close(); fout.close(); // removing the existing file remove("reportcard.csv"); // renaming the new file with the existing file name rename("reportcardnew.csv", "reportcard.csv");}
Output:
References: https://www.geeksforgeeks.org/file-handling-c-classes/, https://www.geeksforgeeks.org/stringstream-c-applications/
nidhi_biet
cpp-file-handling
Technical Scripter 2018
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Vector in C++ STL
Initialize a vector in C++ (6 different ways)
std::sort() in C++ STL
Bitwise Operators in C/C++
Socket Programming in C/C++
Header files in C/C++ and its uses
How to return multiple values from a function in C or C++?
C++ Program for QuickSort
Program to print ASCII Value of a character
Sorting a Map by value in C++ STL
|
[
{
"code": null,
"e": 26960,
"s": 26932,
"text": "\n25 Jun, 2020"
},
{
"code": null,
"e": 27322,
"s": 26960,
"text": "CSV is a simple file format used to store tabular data such as a spreadsheet or a database. CSV stands for Comma Separated Values. The data fields in a CSV file are separated/delimited by a comma (‘, ‘) and the individual rows are separated by a newline (‘\\n’). CSV File management in C++ is similar to text-type file management, except for a few modifications."
},
{
"code": null,
"e": 27407,
"s": 27322,
"text": "This article discusses about how to create, update and delete records in a CSV file:"
},
{
"code": null,
"e": 27550,
"s": 27407,
"text": "Note: Here, a reportcard.csv file has been created to store the student’s roll number, name and marks in math, physics, chemistry and biology."
},
{
"code": null,
"e": 36323,
"s": 27550,
"text": "Create operation:The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\\n’ after the end of each row.CREATECREATEvoid create(){ // file pointer fstream fout; // opens an existing csv file or creates a new file. fout.open(\"reportcard.csv\", ios::out | ios::app); cout << \"Enter the details of 5 students:\" << \" roll name maths phy chem bio\"; << endl; int i, roll, phy, chem, math, bio; string name; // Read the input for (i = 0; i < 5; i++) { cin >> roll >> name >> math >> phy >> chem >> bio; // Insert the data to file fout << roll << \", \" << name << \", \" << math << \", \" << phy << \", \" << chem << \", \" << bio << \"\\n\"; }}Output:Read a particular record:In reading a CSV file, the following approach is implemented:-Using getline(), file pointer and ‘\\n’ as the delimiter, read an entire row and store it in a string variable.Using stringstream, separate the row into words.Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc.READREADvoid read_record(){ // File pointer fstream fin; // Open an existing file fin.open(\"reportcard.csv\", ios::in); // Get the roll number // of which the data is required int rollnum, roll2, count = 0; cout << \"Enter the roll number \" << \"of the student to display details: \"; cin >> rollnum; // Read the Data from the file // as String Vector vector<string> row; string line, word, temp; while (fin >> temp) { row.clear(); // read an entire row and // store it in a string variable 'line' getline(fin, line); // used for breaking words stringstream s(line); // read every column data of a row and // store it in a string variable, 'word' while (getline(s, word, ', ')) { // add all the column data // of a row to a vector row.push_back(word); } // convert string to integer for comparision roll2 = stoi(row[0]); // Compare the roll number if (roll2 == rollnum) { // Print the found data count = 1; cout << \"Details of Roll \" << row[0] << \" : \\n\"; cout << \"Name: \" << row[1] << \"\\n\"; cout << \"Maths: \" << row[2] << \"\\n\"; cout << \"Physics: \" << row[3] << \"\\n\"; cout << \"Chemistry: \" << row[4] << \"\\n\"; cout << \"Biology: \" << row[5] << \"\\n\"; break; } } if (count == 0) cout << \"Record not found\\n\";}Output:Update a record:The following approach is implemented while updating a record:-Read data from a file and compare it with the user input, as explained under read operation.Ask the user to enter new values for the record to be updated.update row[index] with the new data. Here, index refers to the required column field that is to be updated.Write the updated record and all other records into a new file(‘reportcardnew.csv’).At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’UPDATEUPDATEvoid update_recode(){ // File pointer fstream fin, fout; // Open an existing record fin.open(\"reportcard.csv\", ios::in); // Create a new file to store updated data fout.open(\"reportcardnew.csv\", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number from the user cout << \"Enter the roll number \" << \"of the record to be updated: \"; cin >> rollnum; // Get the data to be updated cout << \"Enter the subject \" << \"to be updated(M/P/C/B): \"; cin >> sub; // Determine the index of the subject // where Maths has index 2, // Physics has index 3, and so on if (sub == 'm' || sub == 'M') index = 2; else if (sub == 'p' || sub == 'P') index = 3; else if (sub == 'c' || sub == 'C') index = 4; else if (sub == 'b' || sub == 'B') index = 5; else { cout << \"Wrong choice.Enter again\\n\"; update_record(); } // Get the new marks cout << \"Enter new marks: \"; cin >> new_marks; // Traverse the file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } roll1 = stoi(row[0]); int row_size = row.size(); if (roll1 == rollnum) { count = 1; stringstream convert; // sending a number as a stream into output string convert << new_marks; // the str() converts number into string row[index] = convert.str(); if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // write the updated data // into a new file 'reportcardnew.csv' // using fout fout << row[i] << \", \"; } fout << row[row_size - 1] << \"\\n\"; } } else { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // writing other existing records // into the new file using fout. fout << row[i] << \", \"; } // the last column data ends with a '\\n' fout << row[row_size - 1] << \"\\n\"; } } if (fin.eof()) break; } if (count == 0) cout << \"Record not found\\n\"; fin.close(); fout.close(); // removing the existing file remove(\"reportcard.csv\"); // renaming the updated file with the existing file name rename(\"reportcardnew.csv\", \"reportcard.csv\");}Output:Delete a record:The following approach is implemented while deleting a recordRead data from a file and compare it with the user input, as explained under read and update operation.Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).Remove the old file, and rename the new file, with the old file’s name.DELETEDELETEvoid delete_record(){ // Open FIle pointers fstream fin, fout; // Open the existing file fin.open(\"reportcard.csv\", ios::in); // Create a new file to store the non-deleted data fout.open(\"reportcardnew.csv\", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number // to decide the data to be deleted cout << \"Enter the roll number \" << \"of the record to be deleted: \"; cin >> rollnum; // Check if this record exists // If exists, leave it and // add all other data to the new file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } int row_size = row.size(); roll1 = stoi(row[0]); // writing all records, // except the record to be deleted, // into the new file 'reportcardnew.csv' // using fout pointer if (roll1 != rollnum) { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { fout << row[i] << \", \"; } fout << row[row_size - 1] << \"\\n\"; } } else { count = 1; } if (fin.eof()) break; } if (count == 1) cout << \"Record deleted\\n\"; else cout << \"Record not found\\n\"; // Close the pointers fin.close(); fout.close(); // removing the existing file remove(\"reportcard.csv\"); // renaming the new file with the existing file name rename(\"reportcardnew.csv\", \"reportcard.csv\");}Output:"
},
{
"code": null,
"e": 37302,
"s": 36323,
"text": "Create operation:The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\\n’ after the end of each row.CREATECREATEvoid create(){ // file pointer fstream fout; // opens an existing csv file or creates a new file. fout.open(\"reportcard.csv\", ios::out | ios::app); cout << \"Enter the details of 5 students:\" << \" roll name maths phy chem bio\"; << endl; int i, roll, phy, chem, math, bio; string name; // Read the input for (i = 0; i < 5; i++) { cin >> roll >> name >> math >> phy >> chem >> bio; // Insert the data to file fout << roll << \", \" << name << \", \" << math << \", \" << phy << \", \" << chem << \", \" << bio << \"\\n\"; }}Output:"
},
{
"code": null,
"e": 37536,
"s": 37302,
"text": "The create operation is similar to creating a text file, i.e. input data from the user and write it to the csv file using the file pointer and appropriate delimiters(‘, ‘) between different columns and ‘\\n’ after the end of each row."
},
{
"code": null,
"e": 37543,
"s": 37536,
"text": "CREATE"
},
{
"code": "void create(){ // file pointer fstream fout; // opens an existing csv file or creates a new file. fout.open(\"reportcard.csv\", ios::out | ios::app); cout << \"Enter the details of 5 students:\" << \" roll name maths phy chem bio\"; << endl; int i, roll, phy, chem, math, bio; string name; // Read the input for (i = 0; i < 5; i++) { cin >> roll >> name >> math >> phy >> chem >> bio; // Insert the data to file fout << roll << \", \" << name << \", \" << math << \", \" << phy << \", \" << chem << \", \" << bio << \"\\n\"; }}",
"e": 38253,
"s": 37543,
"text": null
},
{
"code": null,
"e": 38261,
"s": 38253,
"text": "Output:"
},
{
"code": null,
"e": 40629,
"s": 38261,
"text": "Read a particular record:In reading a CSV file, the following approach is implemented:-Using getline(), file pointer and ‘\\n’ as the delimiter, read an entire row and store it in a string variable.Using stringstream, separate the row into words.Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop.Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc.READREADvoid read_record(){ // File pointer fstream fin; // Open an existing file fin.open(\"reportcard.csv\", ios::in); // Get the roll number // of which the data is required int rollnum, roll2, count = 0; cout << \"Enter the roll number \" << \"of the student to display details: \"; cin >> rollnum; // Read the Data from the file // as String Vector vector<string> row; string line, word, temp; while (fin >> temp) { row.clear(); // read an entire row and // store it in a string variable 'line' getline(fin, line); // used for breaking words stringstream s(line); // read every column data of a row and // store it in a string variable, 'word' while (getline(s, word, ', ')) { // add all the column data // of a row to a vector row.push_back(word); } // convert string to integer for comparision roll2 = stoi(row[0]); // Compare the roll number if (roll2 == rollnum) { // Print the found data count = 1; cout << \"Details of Roll \" << row[0] << \" : \\n\"; cout << \"Name: \" << row[1] << \"\\n\"; cout << \"Maths: \" << row[2] << \"\\n\"; cout << \"Physics: \" << row[3] << \"\\n\"; cout << \"Chemistry: \" << row[4] << \"\\n\"; cout << \"Biology: \" << row[5] << \"\\n\"; break; } } if (count == 0) cout << \"Record not found\\n\";}Output:"
},
{
"code": null,
"e": 40692,
"s": 40629,
"text": "In reading a CSV file, the following approach is implemented:-"
},
{
"code": null,
"e": 41269,
"s": 40692,
"text": "Using getline(), file pointer and ‘\\n’ as the delimiter, read an entire row and store it in a string variable.Using stringstream, separate the row into words.Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector.Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop."
},
{
"code": null,
"e": 41380,
"s": 41269,
"text": "Using getline(), file pointer and ‘\\n’ as the delimiter, read an entire row and store it in a string variable."
},
{
"code": null,
"e": 41429,
"s": 41380,
"text": "Using stringstream, separate the row into words."
},
{
"code": null,
"e": 41603,
"s": 41429,
"text": "Now using getline(), the stringstream pointer and ‘, ‘ as the delimiter, read every word in the row, store it in a string variable and push that variable to a string vector."
},
{
"code": null,
"e": 41849,
"s": 41603,
"text": "Retrieve a required column data through row[index]. Here, row[0] always stores the roll number of a student, so compare row[0] with the roll number input by the user, and if it matches, display the details of the student and break from the loop."
},
{
"code": null,
"e": 42020,
"s": 41849,
"text": "Note: Here, since whatever data reading from the file, is stored in string format, so always convert string to the required datatype before comparing or calculating, etc."
},
{
"code": null,
"e": 42025,
"s": 42020,
"text": "READ"
},
{
"code": "void read_record(){ // File pointer fstream fin; // Open an existing file fin.open(\"reportcard.csv\", ios::in); // Get the roll number // of which the data is required int rollnum, roll2, count = 0; cout << \"Enter the roll number \" << \"of the student to display details: \"; cin >> rollnum; // Read the Data from the file // as String Vector vector<string> row; string line, word, temp; while (fin >> temp) { row.clear(); // read an entire row and // store it in a string variable 'line' getline(fin, line); // used for breaking words stringstream s(line); // read every column data of a row and // store it in a string variable, 'word' while (getline(s, word, ', ')) { // add all the column data // of a row to a vector row.push_back(word); } // convert string to integer for comparision roll2 = stoi(row[0]); // Compare the roll number if (roll2 == rollnum) { // Print the found data count = 1; cout << \"Details of Roll \" << row[0] << \" : \\n\"; cout << \"Name: \" << row[1] << \"\\n\"; cout << \"Maths: \" << row[2] << \"\\n\"; cout << \"Physics: \" << row[3] << \"\\n\"; cout << \"Chemistry: \" << row[4] << \"\\n\"; cout << \"Biology: \" << row[5] << \"\\n\"; break; } } if (count == 0) cout << \"Record not found\\n\";}",
"e": 43545,
"s": 42025,
"text": null
},
{
"code": null,
"e": 43553,
"s": 43545,
"text": "Output:"
},
{
"code": null,
"e": 46901,
"s": 43553,
"text": "Update a record:The following approach is implemented while updating a record:-Read data from a file and compare it with the user input, as explained under read operation.Ask the user to enter new values for the record to be updated.update row[index] with the new data. Here, index refers to the required column field that is to be updated.Write the updated record and all other records into a new file(‘reportcardnew.csv’).At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’UPDATEUPDATEvoid update_recode(){ // File pointer fstream fin, fout; // Open an existing record fin.open(\"reportcard.csv\", ios::in); // Create a new file to store updated data fout.open(\"reportcardnew.csv\", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number from the user cout << \"Enter the roll number \" << \"of the record to be updated: \"; cin >> rollnum; // Get the data to be updated cout << \"Enter the subject \" << \"to be updated(M/P/C/B): \"; cin >> sub; // Determine the index of the subject // where Maths has index 2, // Physics has index 3, and so on if (sub == 'm' || sub == 'M') index = 2; else if (sub == 'p' || sub == 'P') index = 3; else if (sub == 'c' || sub == 'C') index = 4; else if (sub == 'b' || sub == 'B') index = 5; else { cout << \"Wrong choice.Enter again\\n\"; update_record(); } // Get the new marks cout << \"Enter new marks: \"; cin >> new_marks; // Traverse the file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } roll1 = stoi(row[0]); int row_size = row.size(); if (roll1 == rollnum) { count = 1; stringstream convert; // sending a number as a stream into output string convert << new_marks; // the str() converts number into string row[index] = convert.str(); if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // write the updated data // into a new file 'reportcardnew.csv' // using fout fout << row[i] << \", \"; } fout << row[row_size - 1] << \"\\n\"; } } else { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // writing other existing records // into the new file using fout. fout << row[i] << \", \"; } // the last column data ends with a '\\n' fout << row[row_size - 1] << \"\\n\"; } } if (fin.eof()) break; } if (count == 0) cout << \"Record not found\\n\"; fin.close(); fout.close(); // removing the existing file remove(\"reportcard.csv\"); // renaming the updated file with the existing file name rename(\"reportcardnew.csv\", \"reportcard.csv\");}Output:"
},
{
"code": null,
"e": 46965,
"s": 46901,
"text": "The following approach is implemented while updating a record:-"
},
{
"code": null,
"e": 47486,
"s": 46965,
"text": "Read data from a file and compare it with the user input, as explained under read operation.Ask the user to enter new values for the record to be updated.update row[index] with the new data. Here, index refers to the required column field that is to be updated.Write the updated record and all other records into a new file(‘reportcardnew.csv’).At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’"
},
{
"code": null,
"e": 47579,
"s": 47486,
"text": "Read data from a file and compare it with the user input, as explained under read operation."
},
{
"code": null,
"e": 47642,
"s": 47579,
"text": "Ask the user to enter new values for the record to be updated."
},
{
"code": null,
"e": 47750,
"s": 47642,
"text": "update row[index] with the new data. Here, index refers to the required column field that is to be updated."
},
{
"code": null,
"e": 47835,
"s": 47750,
"text": "Write the updated record and all other records into a new file(‘reportcardnew.csv’)."
},
{
"code": null,
"e": 48011,
"s": 47835,
"text": "At the end of operation, remove the old file and rename the new file, with the old file name, i.e. remove ‘reportcard.csv’ and rename ‘reportcardnew.csv’ with ‘reportcard.csv’"
},
{
"code": null,
"e": 48018,
"s": 48011,
"text": "UPDATE"
},
{
"code": "void update_recode(){ // File pointer fstream fin, fout; // Open an existing record fin.open(\"reportcard.csv\", ios::in); // Create a new file to store updated data fout.open(\"reportcardnew.csv\", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number from the user cout << \"Enter the roll number \" << \"of the record to be updated: \"; cin >> rollnum; // Get the data to be updated cout << \"Enter the subject \" << \"to be updated(M/P/C/B): \"; cin >> sub; // Determine the index of the subject // where Maths has index 2, // Physics has index 3, and so on if (sub == 'm' || sub == 'M') index = 2; else if (sub == 'p' || sub == 'P') index = 3; else if (sub == 'c' || sub == 'C') index = 4; else if (sub == 'b' || sub == 'B') index = 5; else { cout << \"Wrong choice.Enter again\\n\"; update_record(); } // Get the new marks cout << \"Enter new marks: \"; cin >> new_marks; // Traverse the file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } roll1 = stoi(row[0]); int row_size = row.size(); if (roll1 == rollnum) { count = 1; stringstream convert; // sending a number as a stream into output string convert << new_marks; // the str() converts number into string row[index] = convert.str(); if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // write the updated data // into a new file 'reportcardnew.csv' // using fout fout << row[i] << \", \"; } fout << row[row_size - 1] << \"\\n\"; } } else { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { // writing other existing records // into the new file using fout. fout << row[i] << \", \"; } // the last column data ends with a '\\n' fout << row[row_size - 1] << \"\\n\"; } } if (fin.eof()) break; } if (count == 0) cout << \"Record not found\\n\"; fin.close(); fout.close(); // removing the existing file remove(\"reportcard.csv\"); // renaming the updated file with the existing file name rename(\"reportcardnew.csv\", \"reportcard.csv\");}",
"e": 50748,
"s": 48018,
"text": null
},
{
"code": null,
"e": 50756,
"s": 50748,
"text": "Output:"
},
{
"code": null,
"e": 52837,
"s": 50756,
"text": "Delete a record:The following approach is implemented while deleting a recordRead data from a file and compare it with the user input, as explained under read and update operation.Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).Remove the old file, and rename the new file, with the old file’s name.DELETEDELETEvoid delete_record(){ // Open FIle pointers fstream fin, fout; // Open the existing file fin.open(\"reportcard.csv\", ios::in); // Create a new file to store the non-deleted data fout.open(\"reportcardnew.csv\", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number // to decide the data to be deleted cout << \"Enter the roll number \" << \"of the record to be deleted: \"; cin >> rollnum; // Check if this record exists // If exists, leave it and // add all other data to the new file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } int row_size = row.size(); roll1 = stoi(row[0]); // writing all records, // except the record to be deleted, // into the new file 'reportcardnew.csv' // using fout pointer if (roll1 != rollnum) { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { fout << row[i] << \", \"; } fout << row[row_size - 1] << \"\\n\"; } } else { count = 1; } if (fin.eof()) break; } if (count == 1) cout << \"Record deleted\\n\"; else cout << \"Record not found\\n\"; // Close the pointers fin.close(); fout.close(); // removing the existing file remove(\"reportcard.csv\"); // renaming the new file with the existing file name rename(\"reportcardnew.csv\", \"reportcard.csv\");}Output:"
},
{
"code": null,
"e": 52899,
"s": 52837,
"text": "The following approach is implemented while deleting a record"
},
{
"code": null,
"e": 53171,
"s": 52899,
"text": "Read data from a file and compare it with the user input, as explained under read and update operation.Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv).Remove the old file, and rename the new file, with the old file’s name."
},
{
"code": null,
"e": 53275,
"s": 53171,
"text": "Read data from a file and compare it with the user input, as explained under read and update operation."
},
{
"code": null,
"e": 53373,
"s": 53275,
"text": "Write all the updated records, except the data to be deleted, onto a new file(reportcardnew.csv)."
},
{
"code": null,
"e": 53445,
"s": 53373,
"text": "Remove the old file, and rename the new file, with the old file’s name."
},
{
"code": null,
"e": 53452,
"s": 53445,
"text": "DELETE"
},
{
"code": "void delete_record(){ // Open FIle pointers fstream fin, fout; // Open the existing file fin.open(\"reportcard.csv\", ios::in); // Create a new file to store the non-deleted data fout.open(\"reportcardnew.csv\", ios::out); int rollnum, roll1, marks, count = 0, i; char sub; int index, new_marks; string line, word; vector<string> row; // Get the roll number // to decide the data to be deleted cout << \"Enter the roll number \" << \"of the record to be deleted: \"; cin >> rollnum; // Check if this record exists // If exists, leave it and // add all other data to the new file while (!fin.eof()) { row.clear(); getline(fin, line); stringstream s(line); while (getline(s, word, ', ')) { row.push_back(word); } int row_size = row.size(); roll1 = stoi(row[0]); // writing all records, // except the record to be deleted, // into the new file 'reportcardnew.csv' // using fout pointer if (roll1 != rollnum) { if (!fin.eof()) { for (i = 0; i < row_size - 1; i++) { fout << row[i] << \", \"; } fout << row[row_size - 1] << \"\\n\"; } } else { count = 1; } if (fin.eof()) break; } if (count == 1) cout << \"Record deleted\\n\"; else cout << \"Record not found\\n\"; // Close the pointers fin.close(); fout.close(); // removing the existing file remove(\"reportcard.csv\"); // renaming the new file with the existing file name rename(\"reportcardnew.csv\", \"reportcard.csv\");}",
"e": 55166,
"s": 53452,
"text": null
},
{
"code": null,
"e": 55174,
"s": 55166,
"text": "Output:"
},
{
"code": null,
"e": 55301,
"s": 55174,
"text": "References: https://www.geeksforgeeks.org/file-handling-c-classes/, https://www.geeksforgeeks.org/stringstream-c-applications/"
},
{
"code": null,
"e": 55312,
"s": 55301,
"text": "nidhi_biet"
},
{
"code": null,
"e": 55330,
"s": 55312,
"text": "cpp-file-handling"
},
{
"code": null,
"e": 55354,
"s": 55330,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 55358,
"s": 55354,
"text": "C++"
},
{
"code": null,
"e": 55371,
"s": 55358,
"text": "C++ Programs"
},
{
"code": null,
"e": 55375,
"s": 55371,
"text": "CPP"
},
{
"code": null,
"e": 55473,
"s": 55375,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 55491,
"s": 55473,
"text": "Vector in C++ STL"
},
{
"code": null,
"e": 55537,
"s": 55491,
"text": "Initialize a vector in C++ (6 different ways)"
},
{
"code": null,
"e": 55560,
"s": 55537,
"text": "std::sort() in C++ STL"
},
{
"code": null,
"e": 55587,
"s": 55560,
"text": "Bitwise Operators in C/C++"
},
{
"code": null,
"e": 55615,
"s": 55587,
"text": "Socket Programming in C/C++"
},
{
"code": null,
"e": 55650,
"s": 55615,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 55709,
"s": 55650,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 55735,
"s": 55709,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 55779,
"s": 55735,
"text": "Program to print ASCII Value of a character"
}
] |
Check if there exists any sub-sequence in a string which is not palindrome - GeeksforGeeks
|
10 Aug, 2021
Given a string of lowercase English alphabets. The task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 subsequence that is not a palindrome then print YES, otherwise print NO.Examples:
Input : str = "abaab"
Output : YES
Subsequences "ab" or "abaa" or "aab", are not palindrome.
Input : str = "zzzz"
Output : NO
All possible subsequences are palindrome.
The main observation is that if the string contains at least two distinct characters, then there will always be a subsequence of length at least two which is not a palindrome. Only if all the characters of the string are the same then there will not be any subsequence that is not a palindrome. Because in an optimal way we can choose any two distinct characters from a string and place them in same order one after each to form a non-palindromic string.Below is the implementation of above approach:
C++
Java
Python3
C#
Javascript
// C++ program to check if there exists// at least 1 sub-sequence in a string// which is not palindrome #include <bits/stdc++.h>using namespace std; // Function to check if there exists// at least 1 sub-sequence in a string// which is not palindromebool isAnyNotPalindrome(string s){ // use set to count number of // distinct characters set<char> unique; // insert each character in set for (int i = 0; i < s.length(); i++) unique.insert(s[i]); // If there is more than 1 unique // characters, return true if (unique.size() > 1) return true; // Else, return false else return false;} // Driver codeint main(){ string s = "aaaaab"; if (isAnyNotPalindrome(s)) cout << "YES"; else cout << "NO"; return 0;}
// Java program to check if there exists// at least 1 sub-sequence in a string// which is not palindrome import java.util.*;class GFG{ // Function to check if there exists // at least 1 sub-sequence in a string // which is not palindrome static boolean isAnyNotPalindrome(String s) { // use set to count number of // distinct characters Set<Character> unique=new HashSet<Character>(); // insert each character in set for (int i = 0; i < s.length(); i++) unique.add(s.charAt(i)); // If there is more than 1 unique // characters, return true if (unique.size() > 1) return true; // Else, return false else return false; } // Driver code public static void main(String []args) { String s = "aaaaab"; if (isAnyNotPalindrome(s)) System.out.println("YES"); else System.out.println("NO"); }}
# Python3 program to check if there exists# at least 1 sub-sequence in a string# which is not palindrome # Function to check if there exists# at least 1 sub-sequence in a string# which is not palindromedef isAnyNotPalindrome(s): # use set to count number of # distinct characters unique=set() # insert each character in set for i in range(0,len(s)): unique.add(s[i]) # If there is more than 1 unique # characters, return true if (len(unique) > 1): return True # Else, return false else: return False # Driver codeif __name__=='__main__': s = "aaaaab" if (isAnyNotPalindrome(s)): print("YES") else: print("NO") # This code is contributed by# ihritik
// C# program to check if there exists// at least 1 sub-sequence in a string// which is not palindromeusing System;using System.Collections.Generic; class GFG{ // Function to check if there exists // at least 1 sub-sequence in a string // which is not palindrome static bool isAnyNotPalindrome(String s) { // use set to count number of // distinct characters HashSet<char> unique=new HashSet<char>(); // insert each character in set for (int i = 0; i < s.Length; i++) unique.Add(s[i]); // If there is more than 1 unique // characters, return true if (unique.Count > 1) return true; // Else, return false else return false; } // Driver code public static void Main(String []args) { String s = "aaaaab"; if (isAnyNotPalindrome(s)) Console.WriteLine("YES"); else Console.WriteLine("NO"); }} // This code contributed by Rajput-Ji
<script> // JavaScript program to check if there exists// at least 1 sub-sequence in a string// which is not palindrome // Function to check if there exists// at least 1 sub-sequence in a string// which is not palindromefunction isAnyNotPalindrome(s){ // use set to count number of // distinct characters var unique = new Set(); // insert each character in set for (var i = 0; i < s.length; i++) unique.add(s[i]); // If there is more than 1 unique // characters, return true if (unique.size > 1) return true; // Else, return false else return false;} // Driver codevar s = "aaaaab";if (isAnyNotPalindrome(s)) document.write( "YES");else document.write( "NO"); </script>
YES
Time Complexity: O(N * logN), where N is the length of the string.Auxiliary Space: O(N)
ihritik
Rajput-Ji
rutvik_56
pankajsharmagfg
palindrome
subsequence
Data Structures
Strings
Data Structures
Strings
palindrome
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to Tree Data Structure
Program to implement Singly Linked List in C++ using class
Hash Functions and list/types of Hash functions
Insertion in a B+ tree
Shortest path in a directed graph by Dijkstra’s algorithm
Write a program to reverse an array or string
Reverse a string in Java
Longest Common Subsequence | DP-4
Write a program to print all permutations of a given string
C++ Data Types
|
[
{
"code": null,
"e": 25028,
"s": 25000,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 25276,
"s": 25028,
"text": "Given a string of lowercase English alphabets. The task is to check if there exists any subsequence in the string which is not a palindrome. If there is at least 1 subsequence that is not a palindrome then print YES, otherwise print NO.Examples: "
},
{
"code": null,
"e": 25445,
"s": 25276,
"text": "Input : str = \"abaab\"\nOutput : YES\nSubsequences \"ab\" or \"abaa\" or \"aab\", are not palindrome.\n\nInput : str = \"zzzz\"\nOutput : NO\nAll possible subsequences are palindrome."
},
{
"code": null,
"e": 25950,
"s": 25447,
"text": "The main observation is that if the string contains at least two distinct characters, then there will always be a subsequence of length at least two which is not a palindrome. Only if all the characters of the string are the same then there will not be any subsequence that is not a palindrome. Because in an optimal way we can choose any two distinct characters from a string and place them in same order one after each to form a non-palindromic string.Below is the implementation of above approach: "
},
{
"code": null,
"e": 25954,
"s": 25950,
"text": "C++"
},
{
"code": null,
"e": 25959,
"s": 25954,
"text": "Java"
},
{
"code": null,
"e": 25967,
"s": 25959,
"text": "Python3"
},
{
"code": null,
"e": 25970,
"s": 25967,
"text": "C#"
},
{
"code": null,
"e": 25981,
"s": 25970,
"text": "Javascript"
},
{
"code": "// C++ program to check if there exists// at least 1 sub-sequence in a string// which is not palindrome #include <bits/stdc++.h>using namespace std; // Function to check if there exists// at least 1 sub-sequence in a string// which is not palindromebool isAnyNotPalindrome(string s){ // use set to count number of // distinct characters set<char> unique; // insert each character in set for (int i = 0; i < s.length(); i++) unique.insert(s[i]); // If there is more than 1 unique // characters, return true if (unique.size() > 1) return true; // Else, return false else return false;} // Driver codeint main(){ string s = \"aaaaab\"; if (isAnyNotPalindrome(s)) cout << \"YES\"; else cout << \"NO\"; return 0;}",
"e": 26765,
"s": 25981,
"text": null
},
{
"code": "// Java program to check if there exists// at least 1 sub-sequence in a string// which is not palindrome import java.util.*;class GFG{ // Function to check if there exists // at least 1 sub-sequence in a string // which is not palindrome static boolean isAnyNotPalindrome(String s) { // use set to count number of // distinct characters Set<Character> unique=new HashSet<Character>(); // insert each character in set for (int i = 0; i < s.length(); i++) unique.add(s.charAt(i)); // If there is more than 1 unique // characters, return true if (unique.size() > 1) return true; // Else, return false else return false; } // Driver code public static void main(String []args) { String s = \"aaaaab\"; if (isAnyNotPalindrome(s)) System.out.println(\"YES\"); else System.out.println(\"NO\"); }}",
"e": 27755,
"s": 26765,
"text": null
},
{
"code": "# Python3 program to check if there exists# at least 1 sub-sequence in a string# which is not palindrome # Function to check if there exists# at least 1 sub-sequence in a string# which is not palindromedef isAnyNotPalindrome(s): # use set to count number of # distinct characters unique=set() # insert each character in set for i in range(0,len(s)): unique.add(s[i]) # If there is more than 1 unique # characters, return true if (len(unique) > 1): return True # Else, return false else: return False # Driver codeif __name__=='__main__': s = \"aaaaab\" if (isAnyNotPalindrome(s)): print(\"YES\") else: print(\"NO\") # This code is contributed by# ihritik",
"e": 28493,
"s": 27755,
"text": null
},
{
"code": "// C# program to check if there exists// at least 1 sub-sequence in a string// which is not palindromeusing System;using System.Collections.Generic; class GFG{ // Function to check if there exists // at least 1 sub-sequence in a string // which is not palindrome static bool isAnyNotPalindrome(String s) { // use set to count number of // distinct characters HashSet<char> unique=new HashSet<char>(); // insert each character in set for (int i = 0; i < s.Length; i++) unique.Add(s[i]); // If there is more than 1 unique // characters, return true if (unique.Count > 1) return true; // Else, return false else return false; } // Driver code public static void Main(String []args) { String s = \"aaaaab\"; if (isAnyNotPalindrome(s)) Console.WriteLine(\"YES\"); else Console.WriteLine(\"NO\"); }} // This code contributed by Rajput-Ji",
"e": 29520,
"s": 28493,
"text": null
},
{
"code": "<script> // JavaScript program to check if there exists// at least 1 sub-sequence in a string// which is not palindrome // Function to check if there exists// at least 1 sub-sequence in a string// which is not palindromefunction isAnyNotPalindrome(s){ // use set to count number of // distinct characters var unique = new Set(); // insert each character in set for (var i = 0; i < s.length; i++) unique.add(s[i]); // If there is more than 1 unique // characters, return true if (unique.size > 1) return true; // Else, return false else return false;} // Driver codevar s = \"aaaaab\";if (isAnyNotPalindrome(s)) document.write( \"YES\");else document.write( \"NO\"); </script>",
"e": 30250,
"s": 29520,
"text": null
},
{
"code": null,
"e": 30254,
"s": 30250,
"text": "YES"
},
{
"code": null,
"e": 30344,
"s": 30256,
"text": "Time Complexity: O(N * logN), where N is the length of the string.Auxiliary Space: O(N)"
},
{
"code": null,
"e": 30352,
"s": 30344,
"text": "ihritik"
},
{
"code": null,
"e": 30362,
"s": 30352,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 30372,
"s": 30362,
"text": "rutvik_56"
},
{
"code": null,
"e": 30388,
"s": 30372,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 30399,
"s": 30388,
"text": "palindrome"
},
{
"code": null,
"e": 30411,
"s": 30399,
"text": "subsequence"
},
{
"code": null,
"e": 30427,
"s": 30411,
"text": "Data Structures"
},
{
"code": null,
"e": 30435,
"s": 30427,
"text": "Strings"
},
{
"code": null,
"e": 30451,
"s": 30435,
"text": "Data Structures"
},
{
"code": null,
"e": 30459,
"s": 30451,
"text": "Strings"
},
{
"code": null,
"e": 30470,
"s": 30459,
"text": "palindrome"
},
{
"code": null,
"e": 30568,
"s": 30470,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30604,
"s": 30568,
"text": "Introduction to Tree Data Structure"
},
{
"code": null,
"e": 30663,
"s": 30604,
"text": "Program to implement Singly Linked List in C++ using class"
},
{
"code": null,
"e": 30711,
"s": 30663,
"text": "Hash Functions and list/types of Hash functions"
},
{
"code": null,
"e": 30734,
"s": 30711,
"text": "Insertion in a B+ tree"
},
{
"code": null,
"e": 30792,
"s": 30734,
"text": "Shortest path in a directed graph by Dijkstra’s algorithm"
},
{
"code": null,
"e": 30838,
"s": 30792,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 30863,
"s": 30838,
"text": "Reverse a string in Java"
},
{
"code": null,
"e": 30897,
"s": 30863,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 30957,
"s": 30897,
"text": "Write a program to print all permutations of a given string"
}
] |
How to check if multiple strings exist in another string in Python?
|
To check if any of the strings in an array exists in another string, you can use the any function.
arr = ['a', 'e', 'i', 'o', 'u']
str = "hello people"
if any(c in str for c in arr):
print "Found a match"
This will give you the output:
Found a match
Though an overkill, you can also use regex to match the array. For example:
import re
arr = ['a', 'e', 'i', 'o', 'u']
str = "hello people"
if any(re.findall('|'.join(arr), str)):
print 'Found a match'
This will give you the output:
Found a match
|
[
{
"code": null,
"e": 1162,
"s": 1062,
"text": "To check if any of the strings in an array exists in another string, you can use the any function. "
},
{
"code": null,
"e": 1272,
"s": 1162,
"text": "arr = ['a', 'e', 'i', 'o', 'u']\nstr = \"hello people\"\nif any(c in str for c in arr):\n print \"Found a match\""
},
{
"code": null,
"e": 1303,
"s": 1272,
"text": "This will give you the output:"
},
{
"code": null,
"e": 1317,
"s": 1303,
"text": "Found a match"
},
{
"code": null,
"e": 1393,
"s": 1317,
"text": "Though an overkill, you can also use regex to match the array. For example:"
},
{
"code": null,
"e": 1522,
"s": 1393,
"text": "import re\narr = ['a', 'e', 'i', 'o', 'u']\nstr = \"hello people\"\nif any(re.findall('|'.join(arr), str)):\n print 'Found a match'"
},
{
"code": null,
"e": 1553,
"s": 1522,
"text": "This will give you the output:"
},
{
"code": null,
"e": 1567,
"s": 1553,
"text": "Found a match"
}
] |
How to set background color of a view in Android App
|
This example demonstrates about How do I change the color of Button in Android when clicked.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_margin="16dp"
android:background="#046B5F"
android:padding="16dp"
android:text="My View Background color"
android:textColor="#fff" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
package app.com.sample;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
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.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −
Click here to download the project code.
|
[
{
"code": null,
"e": 1155,
"s": 1062,
"text": "This example demonstrates about How do I change the color of Button in Android when clicked."
},
{
"code": null,
"e": 1284,
"s": 1155,
"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": 1349,
"s": 1284,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 1964,
"s": 1349,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_centerInParent=\"true\"\n android:layout_margin=\"16dp\"\n android:background=\"#046B5F\"\n android:padding=\"16dp\"\n android:text=\"My View Background color\"\n android:textColor=\"#fff\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2021,
"s": 1964,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2338,
"s": 2021,
"text": "package app.com.sample;\nimport androidx.appcompat.app.AppCompatActivity;\nimport android.os.Bundle;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n }\n}"
},
{
"code": null,
"e": 2393,
"s": 2338,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3063,
"s": 2393,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <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": 3410,
"s": 3063,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen −"
},
{
"code": null,
"e": 3451,
"s": 3410,
"text": "Click here to download the project code."
}
] |
GATE | GATE-CS-2015 (Set 1) | Question 65 - GeeksforGeeks
|
23 Dec, 2020
Consider a non-pipelined processor with a clock rate of 2.5 gigahertz and average cycles per instruction of four. The same processor is upgraded to a pipelined processor with five stages; but due to the internal pipeline delay, the clock speed is reduced to 2 gigahertz. Assume that there are no stalls in the pipeline. The speed up achieved in this pipelined processor is __________.(A) 3.2(B) 3.0(C) 2.2(D) 2.0Answer: (A)Explanation:
Speedup = ExecutionTimeOld / ExecutionTimeNew
ExecutionTimeOld = CPIOld * CycleTimeOld
[Here CPI is Cycles Per Instruction]
= CPIOld * CycleTimeOld
= 4 * 1/2.5 Nanoseconds
= 1.6 ns
Since there are no stalls, CPInew can be assumed 1 on average.
ExecutionTimeNew = CPInew * CycleTimenew
= 1 * 1/2
= 0.5
Speedup = 1.6 / 0.5 = 3.2
Refer http://www.cs.berkeley.edu/~pattrsn/252F96/Lecture2a.pdf for more information on this topic.Quiz of this Question
vivekyemul786
GATE-CS-2015 (Set 1)
GATE-GATE-CS-2015 (Set 1)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2016 (Set 2) | Question 61
|
[
{
"code": null,
"e": 24506,
"s": 24478,
"text": "\n23 Dec, 2020"
},
{
"code": null,
"e": 24942,
"s": 24506,
"text": "Consider a non-pipelined processor with a clock rate of 2.5 gigahertz and average cycles per instruction of four. The same processor is upgraded to a pipelined processor with five stages; but due to the internal pipeline delay, the clock speed is reduced to 2 gigahertz. Assume that there are no stalls in the pipeline. The speed up achieved in this pipelined processor is __________.(A) 3.2(B) 3.0(C) 2.2(D) 2.0Answer: (A)Explanation:"
},
{
"code": null,
"e": 25375,
"s": 24942,
"text": "Speedup = ExecutionTimeOld / ExecutionTimeNew\n\nExecutionTimeOld = CPIOld * CycleTimeOld\n [Here CPI is Cycles Per Instruction]\n = CPIOld * CycleTimeOld\n = 4 * 1/2.5 Nanoseconds\n = 1.6 ns\n\nSince there are no stalls, CPInew can be assumed 1 on average.\nExecutionTimeNew = CPInew * CycleTimenew\n = 1 * 1/2\n = 0.5\n\nSpeedup = 1.6 / 0.5 = 3.2"
},
{
"code": null,
"e": 25495,
"s": 25375,
"text": "Refer http://www.cs.berkeley.edu/~pattrsn/252F96/Lecture2a.pdf for more information on this topic.Quiz of this Question"
},
{
"code": null,
"e": 25509,
"s": 25495,
"text": "vivekyemul786"
},
{
"code": null,
"e": 25530,
"s": 25509,
"text": "GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 25556,
"s": 25530,
"text": "GATE-GATE-CS-2015 (Set 1)"
},
{
"code": null,
"e": 25561,
"s": 25556,
"text": "GATE"
},
{
"code": null,
"e": 25659,
"s": 25561,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25693,
"s": 25659,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25735,
"s": 25693,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25777,
"s": 25735,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25811,
"s": 25777,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25844,
"s": 25811,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25878,
"s": 25844,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25911,
"s": 25878,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25945,
"s": 25911,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 25979,
"s": 25945,
"text": "GATE | GATE CS 2012 | Question 54"
}
] |
RSpec - Expectations
|
When you learn RSpec, you may read a lot about expectations and it can be a bit confusing at first. There are two main details you should keep in mind when you see the term Expectation −
An Expectation is simply a statement in an it block that uses the expect() method. That’s it. It’s no more complicated than that. When you have code like this: expect(1 + 1).to eq(2), you have an Expectation in your example. You are expecting that the expression 1 + 1 evaluates to 2. The wording is important though since RSpec is a BDD test framework. By calling this statement an Expectation, it is clear that your RSpec code is describing the “behavior” of the code it’s testing. The idea is that you are expressing how the code should behave, in a way that reads like documentation.
An Expectation is simply a statement in an it block that uses the expect() method. That’s it. It’s no more complicated than that. When you have code like this: expect(1 + 1).to eq(2), you have an Expectation in your example. You are expecting that the expression 1 + 1 evaluates to 2. The wording is important though since RSpec is a BDD test framework. By calling this statement an Expectation, it is clear that your RSpec code is describing the “behavior” of the code it’s testing. The idea is that you are expressing how the code should behave, in a way that reads like documentation.
The Expectation syntax is relatively new. Before the expect() method was introduced (back in 2012), RSpec used a different syntax that was based on the should() method. The above Expectation is written like this in the old syntax: (1 + 1).should eq(2).
The Expectation syntax is relatively new. Before the expect() method was introduced (back in 2012), RSpec used a different syntax that was based on the should() method. The above Expectation is written like this in the old syntax: (1 + 1).should eq(2).
You may encounter the old RSpec syntax for Expectations when working with an older code based or an older version of RSpec. If you use the old syntax with a new version of RSpec, you will see a warning.
For example, with this code −
RSpec.describe "An RSpec file that uses the old syntax" do
it 'you should see a warning when you run this Example' do
(1 + 1).should eq(2)
end
end
When you run it, you will get an output that looks like this −
. Deprecation Warnings:
Using `should` from rspec-expectations' old `:should`
syntax without explicitly enabling the syntax is deprecated.
Use the new `:expect` syntax or explicitly enable
`:should` with `config.expect_with( :rspec) { |c| c.syntax = :should }`
instead. Called from C:/rspec_tutorial/spec/old_expectation.rb:3 :in
`block (2 levels) in <top (required)>'.
If you need more of the backtrace for any of these deprecations to
identify where to make the necessary changes, you can configure
`config.raise_errors_for_deprecations!`, and it will turn the deprecation
warnings into errors, giving you the full backtrace.
1 deprecation warning total
Finished in 0.001 seconds (files took 0.11201 seconds to load)
1 example, 0 failures
Unless you are required to use the old syntax, it is highly recommended that you use expect() instead of should().
9 Lectures
37 mins
Harshit Srivastava
27 Lectures
7 hours
Atul Tiwari
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1981,
"s": 1794,
"text": "When you learn RSpec, you may read a lot about expectations and it can be a bit confusing at first. There are two main details you should keep in mind when you see the term Expectation −"
},
{
"code": null,
"e": 2569,
"s": 1981,
"text": "An Expectation is simply a statement in an it block that uses the expect() method. That’s it. It’s no more complicated than that. When you have code like this: expect(1 + 1).to eq(2), you have an Expectation in your example. You are expecting that the expression 1 + 1 evaluates to 2. The wording is important though since RSpec is a BDD test framework. By calling this statement an Expectation, it is clear that your RSpec code is describing the “behavior” of the code it’s testing. The idea is that you are expressing how the code should behave, in a way that reads like documentation."
},
{
"code": null,
"e": 3157,
"s": 2569,
"text": "An Expectation is simply a statement in an it block that uses the expect() method. That’s it. It’s no more complicated than that. When you have code like this: expect(1 + 1).to eq(2), you have an Expectation in your example. You are expecting that the expression 1 + 1 evaluates to 2. The wording is important though since RSpec is a BDD test framework. By calling this statement an Expectation, it is clear that your RSpec code is describing the “behavior” of the code it’s testing. The idea is that you are expressing how the code should behave, in a way that reads like documentation."
},
{
"code": null,
"e": 3410,
"s": 3157,
"text": "The Expectation syntax is relatively new. Before the expect() method was introduced (back in 2012), RSpec used a different syntax that was based on the should() method. The above Expectation is written like this in the old syntax: (1 + 1).should eq(2)."
},
{
"code": null,
"e": 3663,
"s": 3410,
"text": "The Expectation syntax is relatively new. Before the expect() method was introduced (back in 2012), RSpec used a different syntax that was based on the should() method. The above Expectation is written like this in the old syntax: (1 + 1).should eq(2)."
},
{
"code": null,
"e": 3866,
"s": 3663,
"text": "You may encounter the old RSpec syntax for Expectations when working with an older code based or an older version of RSpec. If you use the old syntax with a new version of RSpec, you will see a warning."
},
{
"code": null,
"e": 3896,
"s": 3866,
"text": "For example, with this code −"
},
{
"code": null,
"e": 4058,
"s": 3896,
"text": "RSpec.describe \"An RSpec file that uses the old syntax\" do\n it 'you should see a warning when you run this Example' do \n (1 + 1).should eq(2) \n end \nend"
},
{
"code": null,
"e": 4121,
"s": 4058,
"text": "When you run it, you will get an output that looks like this −"
},
{
"code": null,
"e": 4894,
"s": 4121,
"text": ". Deprecation Warnings:\n\nUsing `should` from rspec-expectations' old `:should` \n syntax without explicitly enabling the syntax is deprecated. \n Use the new `:expect` syntax or explicitly enable \n\t\n`:should` with `config.expect_with( :rspec) { |c| c.syntax = :should }`\n instead. Called from C:/rspec_tutorial/spec/old_expectation.rb:3 :in \n `block (2 levels) in <top (required)>'.\n\nIf you need more of the backtrace for any of these deprecations to\n identify where to make the necessary changes, you can configure \n`config.raise_errors_for_deprecations!`, and it will turn the deprecation \n warnings into errors, giving you the full backtrace.\n\n1 deprecation warning total \nFinished in 0.001 seconds (files took 0.11201 seconds to load) \n1 example, 0 failures\n"
},
{
"code": null,
"e": 5009,
"s": 4894,
"text": "Unless you are required to use the old syntax, it is highly recommended that you use expect() instead of should()."
},
{
"code": null,
"e": 5040,
"s": 5009,
"text": "\n 9 Lectures \n 37 mins\n"
},
{
"code": null,
"e": 5060,
"s": 5040,
"text": " Harshit Srivastava"
},
{
"code": null,
"e": 5093,
"s": 5060,
"text": "\n 27 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5106,
"s": 5093,
"text": " Atul Tiwari"
},
{
"code": null,
"e": 5113,
"s": 5106,
"text": " Print"
},
{
"code": null,
"e": 5124,
"s": 5113,
"text": " Add Notes"
}
] |
RxJS - Transformation Operator groupBy
|
In groupBy operator, the output is grouped based on a specific condition and these group items are emitted as GroupedObservable.
groupBy(keySelector_func: (value: T) => K):GroupedObservables
keySelector_func − A function that gives the key for each item from the source observable.
The return value is an Observable that emits values as a GroupedObservables.
import { of , from} from 'rxjs';
import { groupBy } from 'rxjs/operators';
const data = [
{groupId: "QA", value: 1},
{groupId: "Development", value: 3},
{groupId: "QA", value: 5},
{groupId: "Development", value: 6},
{groupId: "QA", value: 2},
];
from(data).pipe(
groupBy(item => item.groupId)
)
.subscribe(x => console.log(x));
If you see the output, it is an observable wherein the items are grouped. The data we have given has 2 groups QA and Development. The output shows the grouping of the same as shown below −
51 Lectures
4 hours
Daniel Stern
Print
Add Notes
Bookmark this page
|
[
{
"code": null,
"e": 1953,
"s": 1824,
"text": "In groupBy operator, the output is grouped based on a specific condition and these group items are emitted as GroupedObservable."
},
{
"code": null,
"e": 2016,
"s": 1953,
"text": "groupBy(keySelector_func: (value: T) => K):GroupedObservables\n"
},
{
"code": null,
"e": 2107,
"s": 2016,
"text": "keySelector_func − A function that gives the key for each item from the source observable."
},
{
"code": null,
"e": 2184,
"s": 2107,
"text": "The return value is an Observable that emits values as a GroupedObservables."
},
{
"code": null,
"e": 2532,
"s": 2184,
"text": "import { of , from} from 'rxjs';\nimport { groupBy } from 'rxjs/operators';\n\nconst data = [\n {groupId: \"QA\", value: 1},\n {groupId: \"Development\", value: 3},\n {groupId: \"QA\", value: 5},\n {groupId: \"Development\", value: 6},\n {groupId: \"QA\", value: 2},\n];\n\nfrom(data).pipe(\n groupBy(item => item.groupId)\n)\n.subscribe(x => console.log(x));"
},
{
"code": null,
"e": 2721,
"s": 2532,
"text": "If you see the output, it is an observable wherein the items are grouped. The data we have given has 2 groups QA and Development. The output shows the grouping of the same as shown below −"
},
{
"code": null,
"e": 2754,
"s": 2721,
"text": "\n 51 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 2768,
"s": 2754,
"text": " Daniel Stern"
},
{
"code": null,
"e": 2775,
"s": 2768,
"text": " Print"
},
{
"code": null,
"e": 2786,
"s": 2775,
"text": " Add Notes"
}
] |
5 Levels of Generating Weighted Random Numbers in Python | by Yang Zhou | Towards Data Science
|
To get a random number in Python is simple, since there is a built-in module called random. But how about weighted random numbers?
Let’s see a real interview question:
There is a dictionary as following:
my_nums = {'A': 5, 'B': 2, 'C': 2, 'D': 1}
The keys are four letters and the values are their weights.
Please design a function that can generate a letter randomly based on the weights.
(In other words, this function should have 50% probability to generate “A”, 20% probability to generate “B”, 20% probability to generate “C”, and 10% probability to generate “D”.)
If you are very familiar with Python, you may know that we can solve the problem with a method called random.choices() introduced from Python 3.6, or a similar method in Numpy.
However, a technical interview is not to test if you can remember a special API or not. It aims to test whether you can design and implement an algorithm by yourself. So, the interviewer probably will ask you:
“Can you design and implement the method by yourself?”
In fact, this is a very good interview question. Because programmers of different levels will have different ideas for it. So it will be easy to distinguish between junior and senior Python developers.
This article will dive into 5 different solutions for this problem, from the most intuitive but inefficient way to the best answer.
If our candidate list contains the expected number of every letter, it will become a simple problem.
As shown above, the most intuitive solution is to generate a list which includes the expected number of every letter based on their weights, then just choose randomly from this list.
However, if there are many letters and their weights are bigger numbers, this solution is obviously not very efficient. Cause we will waste lots of time to generate the list.
Actually, the previous solution’s list is not necessary.
Since the total weight is 10 (5+2+2+1). We can just generate a random integer between 1 and 10 firstly, then return a letter based on this number:
The above code avoids generating a list like the previous solution, so it’s more efficient.
But we have to write much if-elif-else code, this looks ugly.
In fact, we don’t have to compare the r with all ranges.
As the following example, we can just subtract one weight from r in turn, anytime the result is less than or equal to zero, we return it:
Obviously, as to the previous solution, the faster r reaches 0, the more efficient our algorithm will be.
So, how can we make the r reach 0 faster?
Intuitively, if the r always subtract the current largest weight, it will reach 0 more quickly. So, before running the weighted_random() function, we can sort my_nums according to the weights from large to small.
If you know the mathematical expectation, we can prove this idea by it.
For example, the follows are my_nums dictionaries with different item orders. For each dictionary, let’s calculate its mathematical expectation about how many steps needed to get a random letter.
{A:5, B:2, C:2, D:1}
E = 5/10*1 + 2/10*2 + 2/10*3 + 1/10*4 = 19/10
{B:2, C:2, A:5, D:1}
E = 2/10*1+ 2/10*2 + 5 /10*3 + 1/10*4 = 25/10
{ D:1, B:2, C:2, A:5}
E = 1/10*1 + 2/10*2 + 2/10*2 + 5/10*5 = 34/10
As shown above, the best order, which sorts weights from large to small, needs the least average steps to get the result.
Our solution is good enough so far. But there still are spaces to make it better.
The level 4 solution, in fact, introduces a new time-consuming step. Cause we have to sort the my_nums dictionary at first. When this is a larger dictionary, it’s totally not efficient enough.
Under the hood, the built-in Python function random.choices() applies a smarter idea. It uses the cumulative weights instead of the original weights. And since the cumulative weights are in ascending order, we can use binary search to find the location faster.
Based on our problem, let’s implement this great idea:
Now, this solution applies the same idea of Python’s random.choices() method. (By the way, we can check the source code of this built-in method on GitHub.)
If we can design our solution at this level, we definitely will ace the technical interview.
To ace technical interviews, just remembering a special built-in method is not enough. You need to know how it works under the hood and it will be great if you can implement it by yourself.
Thanks for reading. If you like it, please follow me and become a Medium member to enjoy more great articles about programming and technologies!
More interesting Python posts for you:
|
[
{
"code": null,
"e": 177,
"s": 46,
"text": "To get a random number in Python is simple, since there is a built-in module called random. But how about weighted random numbers?"
},
{
"code": null,
"e": 214,
"s": 177,
"text": "Let’s see a real interview question:"
},
{
"code": null,
"e": 250,
"s": 214,
"text": "There is a dictionary as following:"
},
{
"code": null,
"e": 293,
"s": 250,
"text": "my_nums = {'A': 5, 'B': 2, 'C': 2, 'D': 1}"
},
{
"code": null,
"e": 353,
"s": 293,
"text": "The keys are four letters and the values are their weights."
},
{
"code": null,
"e": 436,
"s": 353,
"text": "Please design a function that can generate a letter randomly based on the weights."
},
{
"code": null,
"e": 616,
"s": 436,
"text": "(In other words, this function should have 50% probability to generate “A”, 20% probability to generate “B”, 20% probability to generate “C”, and 10% probability to generate “D”.)"
},
{
"code": null,
"e": 793,
"s": 616,
"text": "If you are very familiar with Python, you may know that we can solve the problem with a method called random.choices() introduced from Python 3.6, or a similar method in Numpy."
},
{
"code": null,
"e": 1003,
"s": 793,
"text": "However, a technical interview is not to test if you can remember a special API or not. It aims to test whether you can design and implement an algorithm by yourself. So, the interviewer probably will ask you:"
},
{
"code": null,
"e": 1058,
"s": 1003,
"text": "“Can you design and implement the method by yourself?”"
},
{
"code": null,
"e": 1260,
"s": 1058,
"text": "In fact, this is a very good interview question. Because programmers of different levels will have different ideas for it. So it will be easy to distinguish between junior and senior Python developers."
},
{
"code": null,
"e": 1392,
"s": 1260,
"text": "This article will dive into 5 different solutions for this problem, from the most intuitive but inefficient way to the best answer."
},
{
"code": null,
"e": 1493,
"s": 1392,
"text": "If our candidate list contains the expected number of every letter, it will become a simple problem."
},
{
"code": null,
"e": 1676,
"s": 1493,
"text": "As shown above, the most intuitive solution is to generate a list which includes the expected number of every letter based on their weights, then just choose randomly from this list."
},
{
"code": null,
"e": 1851,
"s": 1676,
"text": "However, if there are many letters and their weights are bigger numbers, this solution is obviously not very efficient. Cause we will waste lots of time to generate the list."
},
{
"code": null,
"e": 1908,
"s": 1851,
"text": "Actually, the previous solution’s list is not necessary."
},
{
"code": null,
"e": 2055,
"s": 1908,
"text": "Since the total weight is 10 (5+2+2+1). We can just generate a random integer between 1 and 10 firstly, then return a letter based on this number:"
},
{
"code": null,
"e": 2147,
"s": 2055,
"text": "The above code avoids generating a list like the previous solution, so it’s more efficient."
},
{
"code": null,
"e": 2209,
"s": 2147,
"text": "But we have to write much if-elif-else code, this looks ugly."
},
{
"code": null,
"e": 2266,
"s": 2209,
"text": "In fact, we don’t have to compare the r with all ranges."
},
{
"code": null,
"e": 2404,
"s": 2266,
"text": "As the following example, we can just subtract one weight from r in turn, anytime the result is less than or equal to zero, we return it:"
},
{
"code": null,
"e": 2510,
"s": 2404,
"text": "Obviously, as to the previous solution, the faster r reaches 0, the more efficient our algorithm will be."
},
{
"code": null,
"e": 2552,
"s": 2510,
"text": "So, how can we make the r reach 0 faster?"
},
{
"code": null,
"e": 2765,
"s": 2552,
"text": "Intuitively, if the r always subtract the current largest weight, it will reach 0 more quickly. So, before running the weighted_random() function, we can sort my_nums according to the weights from large to small."
},
{
"code": null,
"e": 2837,
"s": 2765,
"text": "If you know the mathematical expectation, we can prove this idea by it."
},
{
"code": null,
"e": 3033,
"s": 2837,
"text": "For example, the follows are my_nums dictionaries with different item orders. For each dictionary, let’s calculate its mathematical expectation about how many steps needed to get a random letter."
},
{
"code": null,
"e": 3054,
"s": 3033,
"text": "{A:5, B:2, C:2, D:1}"
},
{
"code": null,
"e": 3100,
"s": 3054,
"text": "E = 5/10*1 + 2/10*2 + 2/10*3 + 1/10*4 = 19/10"
},
{
"code": null,
"e": 3121,
"s": 3100,
"text": "{B:2, C:2, A:5, D:1}"
},
{
"code": null,
"e": 3167,
"s": 3121,
"text": "E = 2/10*1+ 2/10*2 + 5 /10*3 + 1/10*4 = 25/10"
},
{
"code": null,
"e": 3189,
"s": 3167,
"text": "{ D:1, B:2, C:2, A:5}"
},
{
"code": null,
"e": 3235,
"s": 3189,
"text": "E = 1/10*1 + 2/10*2 + 2/10*2 + 5/10*5 = 34/10"
},
{
"code": null,
"e": 3357,
"s": 3235,
"text": "As shown above, the best order, which sorts weights from large to small, needs the least average steps to get the result."
},
{
"code": null,
"e": 3439,
"s": 3357,
"text": "Our solution is good enough so far. But there still are spaces to make it better."
},
{
"code": null,
"e": 3632,
"s": 3439,
"text": "The level 4 solution, in fact, introduces a new time-consuming step. Cause we have to sort the my_nums dictionary at first. When this is a larger dictionary, it’s totally not efficient enough."
},
{
"code": null,
"e": 3893,
"s": 3632,
"text": "Under the hood, the built-in Python function random.choices() applies a smarter idea. It uses the cumulative weights instead of the original weights. And since the cumulative weights are in ascending order, we can use binary search to find the location faster."
},
{
"code": null,
"e": 3948,
"s": 3893,
"text": "Based on our problem, let’s implement this great idea:"
},
{
"code": null,
"e": 4104,
"s": 3948,
"text": "Now, this solution applies the same idea of Python’s random.choices() method. (By the way, we can check the source code of this built-in method on GitHub.)"
},
{
"code": null,
"e": 4197,
"s": 4104,
"text": "If we can design our solution at this level, we definitely will ace the technical interview."
},
{
"code": null,
"e": 4387,
"s": 4197,
"text": "To ace technical interviews, just remembering a special built-in method is not enough. You need to know how it works under the hood and it will be great if you can implement it by yourself."
},
{
"code": null,
"e": 4532,
"s": 4387,
"text": "Thanks for reading. If you like it, please follow me and become a Medium member to enjoy more great articles about programming and technologies!"
}
] |
Using Python and Monte Carlo to predict my Student Loan Repayment | by Luke Vassor | Towards Data Science
|
I became frustrated with the numbers not making sense on my Student Loan statements and speculative opinions about why you should not try to pay it off quicker if you are able to. I wanted to gauge my likelihood of paying off the full loan and practice my Data Science skills, so I simulated my earnings using Monte Carlo written in Python. Here I give a walk-through and evaluation of the findings.
Full code available on my GitHub.
Skip to Method and Results if you’re short of time!
In the UK, students can take out university loans for both tuition fees and living costs with Student Finance England, who provide loans underwritten by the Student Loans Company. Once you enter employment as a graduate, you then begin to pay off your loan on a monthly schedule as part of your tax deductions. Crucially, if you do not pay off your loan, plus interest, in 30 years, your loan is cancelled. They’re also substantial — approximately £42,000 one year after graduating in many cases.
I found documentation surrounding repayment murky and dense. It’s confusing, and no-one online or in my circle could give me clear answers.
Conflicting opinions surrounding repayment— “it comes out of my tax so I don’t even notice it” and “most students won’t pay it off and it will get cancelled, so paying extra upfront might be wasting your money” — but this paints “most students” with a broad brush, which spans a huge variance in earnings (and therefore amortisation) between subjects, university attended and industry.
I wanted to cut through the noise and capture the dynamics between the accruing interest and monthly tax repayments to quantify my own probability of paying it off.
1. How likely am I to pay off my student loan inside of the 30-year payment window, given my probable salary progression?2. If you manage to save money, or come across a sum of money (e.g. inheritance), should you pay off some or all of your loan in the form of voluntary payments?
Students taking out loans since 2012 are on “Plan 2” loans, and they are split up into instalments which you receive throughout your degree.
Graduates only start paying back towards their loan when they earn more than £2,214 a month or £26,568 a year (pre-tax) as of the date this article was published.
Loan repayments are deducted from your salary when you are paid by your employer (in the UK, usually the last working day of the month) — these are due the April after graduating if you earn above the threshold.
You begin accruing interest from the day of your first loan instalment (i.e., shortly after arriving at university).
Interest accrues daily.
Plan 2 loans are written off 30 years after the April you were first due to repay if you are still repaying.
The amount you pay back on your Student Loan is calculated as a percentage of how much you earn above a threshold, so it behaves much more like a tax, rather than regular loan repayments.
Interest rates are variable, not fixed — they are calculated as the RPI (Retail Price Index) measure of inflation, plus 3%, so rates have been as high as 6.6% in recent years.
Interest rates change each academic year (September 1st), using the RPI inflation for the financial year ending in the previous March (i.e., March 2019 RPI is used for the rate set on September 1st 2020).
Build a simulator in Python which runs through 30 years of payments towards the loan, with the loan simultaneously accruing interest daily.
Simulate across many different salary trajectories, using Monte Carlo (more below).
import os
import pandas as pd
import numpy as np
# Working with datetime objects
from datetime import date, timedelta
from pandas.tseries.offsets import BMonthEnd
# Scraping interest rates off the web
import requests
from bs4 import BeautifulSoup
# Plotting
import matplotlib.pyplot as plt
%matplotlib inline
def calc_student_finance_PM(grossSalaryPA):
'''
Calculates student finance payments per month deducted
from gross salary based on thresholds published by
Student Finance England.
'''
grossSalaryPM = grossSalaryPA/12
thresholdPM = 2143
if grossSalaryPM > thresholdPM:
StudentFinPM = 0.09*(grossSalaryPM-thresholdPM)
else:
StudentFinPM = 0
return StudentFinPM
Get interest rates for past academic years from the government website, using a simple web scraper (BeautifulSoup library) and store them in a lookup dictionary.Build a function which could take any date during my degree and find the interest rate for instalments paid at that point in time from the dictionary.
Get interest rates for past academic years from the government website, using a simple web scraper (BeautifulSoup library) and store them in a lookup dictionary.
Build a function which could take any date during my degree and find the interest rate for instalments paid at that point in time from the dictionary.
## Web scrape historic interest rates
url = 'https://www.gov.uk/guidance/how-interest-is-calculated-plan-2'
headers = {'User-Agent': 'Mozilla/5.0'}
page = requests.get(url, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')
results = soup.find('table')
table_rows = results.find_all('tr')
# Store interest rates in dictionary of academic years
historicInterest = {}
for tr in table_rows:
td = tr.find_all('td')
row = [i.text for i in td]
if len(row) > 0:
row[0] = row[0].split('to')
row[0][0] = pd.Timestamp(row[0][0])
row[0][1] = pd.Timestamp(row[0][1])
year = str(row[0][0].year)
historicInterest.setdefault(year, 0)
historicInterest[year] = {}
historicInterest[year].setdefault("start", 0)
historicInterest[year]["start"] = row[0][0].date()
historicInterest[year].setdefault("end", 0)
historicInterest[year]["end"] = row[0][1].date()
historicInterest[year].setdefault("rate", 0)
historicInterest[year]["rate"] = float(row[1][:-1])/100
def find_interest_rate(paymentDate):
'''
Finds interest rate for a date which falls in
a given academic year using a lookup dictionary.
'''
try:
year = paymentDate.year
sdate = historicInterest[str(year)]["start"]
edate = historicInterest[str(year)]["end"]
delta = edate - sdate
allDates = [sdate + timedelta(days=i) for i in range(delta.days+1)] # create list of all dates in date range sdate to edate
# Dates in the second semester are in the next calendar year but same academic year
# in this case, take the rate of the previous calendar year
if paymentDate in allDates:
rate = historicInterest[str(year)]["rate"]
else:
rate = historicInterest[str(year-1)]["rate"]
except KeyError: # error for dates in next calendar year but in an academic year which exceeds the last year of the dictionary
rate = historicInterest[str(year-1)]["rate"]
return rate
To calculate how much I owed after university I simulated each passing day’s interest plus any new instalments arriving from Student Finance England throughout university, using a Pandas dataframe of payments (digitised from my paper statements).
def graduate_amount(simEnd, employmentStart, myPayments=None): '''
calculate total student debt owed at employment,
end of graduation year or at final instalment manually (using simEnd)
Alternatively can take manually input total
'''
cumulativeTotal = 0
interestRate = 0
if myPayments is not None:
startDate = myPayments.index.min()
if simEnd == "yearEnd":
graduationYear = myPayments.index.max().year # assumes that final payment occurs during graduation year
yearEnd = str(graduationYear)+"-08-31"
endDate = pd.Timestamp(yearEnd) # simulation ends at end of academic year of final payment
elif simEnd == "employment":
endDate = pd.Timestamp(employmentStart)
else:
endDate = myPayments.index.max() # simulation ends at final payment
delta = timedelta(days=1)
## Simulate through dates in date period,
## compounding interest each day and adding installments
while startDate <= endDate: # simulate interest compounding up to and including last day
interestRate = find_interest_rate(startDate)
cumulativeTotal *= (1+(interestRate/365)) # apply interest on previous payments before new payment
if startDate in myPayments.index: # check if there was a loan instalment on this day
cumulativeTotal += myPayments.loc[startDate]["Gross"]
startDate += delta
else:
print("Please enter your net total of Student Debt at graduation")
cumulativeTotal = input()
return cumulativeTotal
Using the above functions, the value owed in Student Finance loans at the start of employment can be calculated. After the April following graduation, you begin paying back towards your loan in the style of a monthly tax. In this simulation interest accrues on the loan daily and on the last working day of the month (BMonthEnd) your repayment comes out of your salary, as in reality.
Monte Carlo methods are a class of algorithms that rely on repeated random sampling to obtain numerical results — by the law of large numbers, the expected value of a random variable can be approximated by taking the sample mean of independent samples. In plain English: “while we don’t know what the correct answer or strategy is, we can simulate many attempts and the average will approximate the right answer”. Monte Carlo can be used for many problems with a probabilistic element or “risk”, such as gambling, or stock market and portfolio performance in finance. Here is a great example.
Since the amount of student finance I will pay across my working life (through monthly payments) is based on what I earn at time t, and I don’t know what I will earn, I can simulate my career earnings using Monte Carlo. In the simulation:
The starting salary (£29,000) is the median graduate starting salary, based on graduate schemes of employment — reported by the Institute of Student Employers (ISE).
I divide the 30-year payment period of the loan into different salary bands for my career.
I chose 6 separate bands, each 5 years long (but this can be varied).
Each salary band represents a salary increase at time t — the increase is taken from a Gaussian distribution centred around a mean which is a percentage of my gross salary at time t-1.
This percentage decreases the further the simulation runs into my career i.e., most salary growth occurs in early years (high % increase), then it slows (low % increase). e.g., in the below table (0,1) = 37.49% salary increase.
I simulate my career according to these salary bands 100,000 times.
The loan’s interest rate is set at 5.5% — RPI of 2.5% plus 3% (government method). To inform this I used a 5-year moving average of historic UK RPI values, which I downloaded from the Office for National Statistics (ONS). Whilst predicted RPI estimates are available, the current COVID-19 crisis and its economic implications will likely affect these predictions, thus I took the pre-COVID19 value which has remained around 2.5% in recent years.
I calculate what the average loan value and cumulative sum of repayments (lifetime contribution) are across all salary trajectories after the 30-year payment period.
Translation:
As a graduate earner, most salary growth occurs in the early years (high % increase) before levelling off (low % increase) — see this incredibly thorough new report The impact of undergraduate degree on lifetime earnings by the Institute for Fiscal Studies.
A pay-rise of x% in 5 years is not certain —it could be slightly less than or greater than x%, or you could have a series of smaller or larger pay-rises (the aggregate of which are represented in the 5-year jump). Monte Carlo helps to mitigate this by drawing many salary values (k = 100,000) from a normal distribution for each band. These average x%, but can be less than or greater than x%. I simulate all these trajectories and the monthly payments towards my loan and work out in how many of the simulations I pay off my entire loan.
As you can see in the top plot, only a small proportion of loans are ever paid off via monthly deductions. These loans are identifiable as the trajectories which cross the zero-line (marked in red) and correspond to the largest salaries. The lowest salaries across all years result in loans which continue to grow in value.
For 100,000 simulations, after the 30 year payment period:
the average loan value is: £60,600.74
only in 3.54% of salary trajectories was the loan completely paid off i.e., crossed the red zero line in the plot (3,543/100,000)
the average total amount of money paid towards the loan is: £99,691.01
DISCLAIMER: I am not a financial adviser — any ideas here are purely hypothetical based off simulations with a suite of assumptions & caveats. These are simply my thoughts on potentially effective strategies, as part of a conceptual exercise. If you are unsure about your own personal financial situation, seek the advice of a qualified financial adviser.
This simulation, of course, contains several caveats:
Salary bands: I assume 6 x 5-year salary bands — there is no guarantee that graduate earnings will follow this format. There are not adequate data on regular salary progressions for a particular field in the UK, as salary increases and promotions are subject to many variables, including academic qualifications (e.g. BSc vs MSc vs PhD), field, company, and the performance of the individual themselves. Whilst there are data on average graduate earnings per subject, these data do not capture the many routes/fields that a graduate with a particular degree can take. After conversations with senior roles in my network, I determined that approximate 5-year frequencies for salary increases and the percentages chosen are close to reality, on average, for a STEM graduate.Interest rate: This simulation assumes that recent RPI values will remain constant in future years, however the real interest rate on the loan changes every academic year because of changing RPI, which will affect how quickly the interest of the loan compounds.Starting salary: I used the average starting salary based on graduate schemes, but this is not representative of all graduate salaries — which affects repayment.Other compensation: The simulation only considers base salary, without bonuses, company shares or other forms of renumeration.
Salary bands: I assume 6 x 5-year salary bands — there is no guarantee that graduate earnings will follow this format. There are not adequate data on regular salary progressions for a particular field in the UK, as salary increases and promotions are subject to many variables, including academic qualifications (e.g. BSc vs MSc vs PhD), field, company, and the performance of the individual themselves. Whilst there are data on average graduate earnings per subject, these data do not capture the many routes/fields that a graduate with a particular degree can take. After conversations with senior roles in my network, I determined that approximate 5-year frequencies for salary increases and the percentages chosen are close to reality, on average, for a STEM graduate.
Interest rate: This simulation assumes that recent RPI values will remain constant in future years, however the real interest rate on the loan changes every academic year because of changing RPI, which will affect how quickly the interest of the loan compounds.
Starting salary: I used the average starting salary based on graduate schemes, but this is not representative of all graduate salaries — which affects repayment.
Other compensation: The simulation only considers base salary, without bonuses, company shares or other forms of renumeration.
So what is the conclusion here? What strategy should you take with regard to paying off your student loan?
Firstly, it should be highlighted that debt repayment is a blend of arithmetic and also psychology, because as complex creatures, our emotional welfare with regard to debt is affected by multiple factors. There are different debt consolidation strategies if you have multiple debt repayments to make e.g. Snowball or Avalanche methods.
Secondly, in a purely mathematical sense, the optimum strategy for paying the minimum amount on the student loan would be to remain at a salary below the repayment threshold for the entire 30-year payment period, thereby receiving the degree for free, as you never pay a penny for it. However, this is only when considering the loan in isolation from other factors, and obviously does not reflect the real life ambitions of a typical graduate. With this in mind I consider strategies that assume progressive career growth which includes repaying your loan.
Practically and in isolation, yes, you should try and pay it off with any extra money you encounter, because the Results show, on average, you will pay for the loan more than twice over across your working life time (99,691.01/42,000 = 2.37).
Crucially, the major factor affecting amortisation in this problem is the dynamics between the interest and the monthly repayments. If the interest on the loan accrued in a given month is £20, you need to pay more than £20 in repayments at the end of the month to decrease the principal amount — this is basic mathematics.
The key factor is the rate at which your salary increases, because of the powers of compound growth. Your repayments need to chip off the interest plus more to start decreasing the principal amount. But, if your salary means you don’t manage to overcome the interest early on, even if your salary rises to a substantial amount later in life, the loan will have grown to an amount which demands a disproportionately higher salary to conquer the later monthly interest, which will be much greater due to the non-linearity of compound growth. Therefore, to successfully pay off your loan only through monthly tax repayments, the salary must grow fast enough in the early years such that repayments quickly overcome the interest and the debt is not “allowed” to grow. The other option is that if your salary is too low to achieve this, you make voluntary repayments each month to make up the difference.
Of course in reality, your loan repayment is not in isolation of other factors. It’s a multi-dimensional problem! It comes down to what else you can invest any extra money in for the long term, because of the time-value of money and opportunity cost. Time-value of money is the concept that the same sum of money is worth more now than later on in life because of its earning potential and inflation.
If you come across a sum of money that affords you the ability to pay off the loan (either from a savings account, inheritance etc.), you could invest it and grow it, utilising compound growth rather than only being a victim of it.
I did a post-hoc analysis to show this. Suppose instead of paying off the loan, you use a long term, sit-and-hold strategy in an investment with a higher average return than the amount you pay towards the loan through monthly salary deductions — either with a lump sum equivalent to the value of the loan (£42,000), or — since this situation will be very rare for the typical graduate — with an initial investment of £1,000 and monthly deposits of any savings (£200).
3 scenarios:
You encounter £42,000 and pay off the loan immediately. Monthly repayments (blue line) would cost you approx. £100,000 over your lifetime, which you’ve avoided. £100,000 — £42,000 = £58,000 “profit”.You encounter £42,000 and invest it at a 5.0% return (after inflation) and leave it to grow for the 30-years instead (orange line). After 30 years this is worth approx £187,000. £187,000 — £100,000 = £87,000 profit.You invest £1,000 and use money you save each month (e.g. £200) to top up the investment monthly (green line). After 30 years this is worth approx £170,000. £170,000–£100,000 = £70,000 profit.
You encounter £42,000 and pay off the loan immediately. Monthly repayments (blue line) would cost you approx. £100,000 over your lifetime, which you’ve avoided. £100,000 — £42,000 = £58,000 “profit”.
You encounter £42,000 and invest it at a 5.0% return (after inflation) and leave it to grow for the 30-years instead (orange line). After 30 years this is worth approx £187,000. £187,000 — £100,000 = £87,000 profit.
You invest £1,000 and use money you save each month (e.g. £200) to top up the investment monthly (green line). After 30 years this is worth approx £170,000. £170,000–£100,000 = £70,000 profit.
As these results show, even if the simulated graduate doesn’t have a large lump sum available and uses a much more modest amount to begin investing their monthly savings, they could still end up in greater profit than if they paid off the loan completely. In most cases, graduates are unlikely to encounter this kind of lump sum, and to attempt to save money after your living costs to then pay towards the student loan could leave you forever chasing your own tail as the loan interest simultaneously compounds more than you can save — you would be better off investing it.
This opportunity cost applies to other investments, like purchasing a house and leveraging its appreciation in value and even to investment in yourself, such as courses, seminars and conferences, which develop your skills and grow your network. Whilst this is hard to capture in monetary terms, it will generate more opportunity, and likely greater profit.
It’s not a crystal-clear conclusion— there are a lot of “‘ifs”:
If the interest on the loan were much lower, it would be clear to simply pay through monthly deductions with less concern for added investment as you would be a lot less likely to overpay.
If you encounter a sum of money that approximates the value of your student debt or if you save money each month, it could be more profitable to invest it, as paying off the loan would incur huge opportunity cost. As a young graduate you are in a strong position— the time/effort/money invested in your first few years can affect the course of your career, and years of delayed investment for the future could drastically reduce your ROI later in life.
If you have the money but don’t invest it, then you would be better off paying off the loan with this money, otherwise you could pay several times over through monthly repayments, plus this liquid money will lose value each year due to inflation.
These results will undoubtedly inform my personal finance decisions in the near future.
What is also reassuring is that the report mentioned above found that even after accounting for taxes and Student Finance repayments, UK graduates are still at least £100,000 better off, on average, for getting a degree, because of the additional, net take-home salary that they earn.
This project has certainly shown me that the notion of “don’t pay off the loan in full as it gets cancelled later on” is misguided in its lack of elaboration — it completely depends on salary, because this determines if you under- or over-pay for your degree. If lifetime salary is low enough, then you could underpay for the degree via monthly repayments, in which case you should not pay extra or worry about investing. However, these simulations suggest that if you end up earning in the average (densest) region (see salary step plot in Results) then you should invest any extra money and pay the minimum on your loan. This is because you will need investments later on to counterbalance the over-payment of your degree. Of course, these conclusions are hypothetical and are drawn from the predicted interest rate and simulated salaries, which could be different.
Apart from the greater understanding of the student loans system I have gained, this exercise did highlight something important. We do not have enough publicly available and consumable data tracking graduate lifetime earnings for different fields or careers. The report mentioned analyses longitudinal data for graduates and non-graduates from a particular cohort, and was very recently published — research like this needs to be made available and digestible to prospective undergraduates. Undergraduate university courses in the UK now cost up to £9,250 per year, which you may pay for several times over as we have seen. We need data on what graduates of a particular course at a particular university go on to earn so candidates can judge for themselves what the ROI for their course and university would be, in light of the huge loan they would be taking on, rather than simply being dazzled by universities on Open Days.
I hope this article has been insightful! Onto the next project...
|
[
{
"code": null,
"e": 446,
"s": 46,
"text": "I became frustrated with the numbers not making sense on my Student Loan statements and speculative opinions about why you should not try to pay it off quicker if you are able to. I wanted to gauge my likelihood of paying off the full loan and practice my Data Science skills, so I simulated my earnings using Monte Carlo written in Python. Here I give a walk-through and evaluation of the findings."
},
{
"code": null,
"e": 480,
"s": 446,
"text": "Full code available on my GitHub."
},
{
"code": null,
"e": 532,
"s": 480,
"text": "Skip to Method and Results if you’re short of time!"
},
{
"code": null,
"e": 1029,
"s": 532,
"text": "In the UK, students can take out university loans for both tuition fees and living costs with Student Finance England, who provide loans underwritten by the Student Loans Company. Once you enter employment as a graduate, you then begin to pay off your loan on a monthly schedule as part of your tax deductions. Crucially, if you do not pay off your loan, plus interest, in 30 years, your loan is cancelled. They’re also substantial — approximately £42,000 one year after graduating in many cases."
},
{
"code": null,
"e": 1169,
"s": 1029,
"text": "I found documentation surrounding repayment murky and dense. It’s confusing, and no-one online or in my circle could give me clear answers."
},
{
"code": null,
"e": 1555,
"s": 1169,
"text": "Conflicting opinions surrounding repayment— “it comes out of my tax so I don’t even notice it” and “most students won’t pay it off and it will get cancelled, so paying extra upfront might be wasting your money” — but this paints “most students” with a broad brush, which spans a huge variance in earnings (and therefore amortisation) between subjects, university attended and industry."
},
{
"code": null,
"e": 1720,
"s": 1555,
"text": "I wanted to cut through the noise and capture the dynamics between the accruing interest and monthly tax repayments to quantify my own probability of paying it off."
},
{
"code": null,
"e": 2002,
"s": 1720,
"text": "1. How likely am I to pay off my student loan inside of the 30-year payment window, given my probable salary progression?2. If you manage to save money, or come across a sum of money (e.g. inheritance), should you pay off some or all of your loan in the form of voluntary payments?"
},
{
"code": null,
"e": 2143,
"s": 2002,
"text": "Students taking out loans since 2012 are on “Plan 2” loans, and they are split up into instalments which you receive throughout your degree."
},
{
"code": null,
"e": 2306,
"s": 2143,
"text": "Graduates only start paying back towards their loan when they earn more than £2,214 a month or £26,568 a year (pre-tax) as of the date this article was published."
},
{
"code": null,
"e": 2518,
"s": 2306,
"text": "Loan repayments are deducted from your salary when you are paid by your employer (in the UK, usually the last working day of the month) — these are due the April after graduating if you earn above the threshold."
},
{
"code": null,
"e": 2635,
"s": 2518,
"text": "You begin accruing interest from the day of your first loan instalment (i.e., shortly after arriving at university)."
},
{
"code": null,
"e": 2659,
"s": 2635,
"text": "Interest accrues daily."
},
{
"code": null,
"e": 2768,
"s": 2659,
"text": "Plan 2 loans are written off 30 years after the April you were first due to repay if you are still repaying."
},
{
"code": null,
"e": 2956,
"s": 2768,
"text": "The amount you pay back on your Student Loan is calculated as a percentage of how much you earn above a threshold, so it behaves much more like a tax, rather than regular loan repayments."
},
{
"code": null,
"e": 3132,
"s": 2956,
"text": "Interest rates are variable, not fixed — they are calculated as the RPI (Retail Price Index) measure of inflation, plus 3%, so rates have been as high as 6.6% in recent years."
},
{
"code": null,
"e": 3337,
"s": 3132,
"text": "Interest rates change each academic year (September 1st), using the RPI inflation for the financial year ending in the previous March (i.e., March 2019 RPI is used for the rate set on September 1st 2020)."
},
{
"code": null,
"e": 3477,
"s": 3337,
"text": "Build a simulator in Python which runs through 30 years of payments towards the loan, with the loan simultaneously accruing interest daily."
},
{
"code": null,
"e": 3561,
"s": 3477,
"text": "Simulate across many different salary trajectories, using Monte Carlo (more below)."
},
{
"code": null,
"e": 3874,
"s": 3561,
"text": "import os\nimport pandas as pd\nimport numpy as np\n\n# Working with datetime objects\nfrom datetime import date, timedelta\nfrom pandas.tseries.offsets import BMonthEnd\n\n# Scraping interest rates off the web\nimport requests\nfrom bs4 import BeautifulSoup\n\n# Plotting\nimport matplotlib.pyplot as plt\n%matplotlib inline\n"
},
{
"code": null,
"e": 4289,
"s": 3874,
"text": "def calc_student_finance_PM(grossSalaryPA):\n '''\n Calculates student finance payments per month deducted\n from gross salary based on thresholds published by\n Student Finance England.\n '''\n grossSalaryPM = grossSalaryPA/12\n thresholdPM = 2143\n if grossSalaryPM > thresholdPM:\n StudentFinPM = 0.09*(grossSalaryPM-thresholdPM)\n else:\n StudentFinPM = 0\n return StudentFinPM\n"
},
{
"code": null,
"e": 4601,
"s": 4289,
"text": "Get interest rates for past academic years from the government website, using a simple web scraper (BeautifulSoup library) and store them in a lookup dictionary.Build a function which could take any date during my degree and find the interest rate for instalments paid at that point in time from the dictionary."
},
{
"code": null,
"e": 4763,
"s": 4601,
"text": "Get interest rates for past academic years from the government website, using a simple web scraper (BeautifulSoup library) and store them in a lookup dictionary."
},
{
"code": null,
"e": 4914,
"s": 4763,
"text": "Build a function which could take any date during my degree and find the interest rate for instalments paid at that point in time from the dictionary."
},
{
"code": null,
"e": 6980,
"s": 4914,
"text": "## Web scrape historic interest rates\n\nurl = 'https://www.gov.uk/guidance/how-interest-is-calculated-plan-2'\nheaders = {'User-Agent': 'Mozilla/5.0'}\npage = requests.get(url, headers=headers)\nsoup = BeautifulSoup(page.content, 'html.parser')\nresults = soup.find('table')\ntable_rows = results.find_all('tr')\n\n# Store interest rates in dictionary of academic years\nhistoricInterest = {}\nfor tr in table_rows:\n td = tr.find_all('td')\n row = [i.text for i in td]\n if len(row) > 0:\n row[0] = row[0].split('to')\n row[0][0] = pd.Timestamp(row[0][0])\n row[0][1] = pd.Timestamp(row[0][1])\n year = str(row[0][0].year)\n historicInterest.setdefault(year, 0)\n historicInterest[year] = {}\n historicInterest[year].setdefault(\"start\", 0)\n historicInterest[year][\"start\"] = row[0][0].date()\n historicInterest[year].setdefault(\"end\", 0)\n historicInterest[year][\"end\"] = row[0][1].date()\n historicInterest[year].setdefault(\"rate\", 0)\n historicInterest[year][\"rate\"] = float(row[1][:-1])/100\n\ndef find_interest_rate(paymentDate):\n '''\n Finds interest rate for a date which falls in \n a given academic year using a lookup dictionary.\n '''\n try:\n year = paymentDate.year\n sdate = historicInterest[str(year)][\"start\"]\n edate = historicInterest[str(year)][\"end\"]\n delta = edate - sdate\n \n allDates = [sdate + timedelta(days=i) for i in range(delta.days+1)] # create list of all dates in date range sdate to edate\n \n # Dates in the second semester are in the next calendar year but same academic year\n # in this case, take the rate of the previous calendar year\n if paymentDate in allDates:\n rate = historicInterest[str(year)][\"rate\"]\n else:\n rate = historicInterest[str(year-1)][\"rate\"]\n except KeyError: # error for dates in next calendar year but in an academic year which exceeds the last year of the dictionary\n rate = historicInterest[str(year-1)][\"rate\"]\n return rate\n"
},
{
"code": null,
"e": 7227,
"s": 6980,
"text": "To calculate how much I owed after university I simulated each passing day’s interest plus any new instalments arriving from Student Finance England throughout university, using a Pandas dataframe of payments (digitised from my paper statements)."
},
{
"code": null,
"e": 8899,
"s": 7227,
"text": "def graduate_amount(simEnd, employmentStart, myPayments=None): '''\n calculate total student debt owed at employment, \n end of graduation year or at final instalment manually (using simEnd)\n Alternatively can take manually input total\n '''\n \n cumulativeTotal = 0\n interestRate = 0\n if myPayments is not None:\n startDate = myPayments.index.min()\n if simEnd == \"yearEnd\":\n graduationYear = myPayments.index.max().year # assumes that final payment occurs during graduation year\n yearEnd = str(graduationYear)+\"-08-31\"\n endDate = pd.Timestamp(yearEnd) # simulation ends at end of academic year of final payment\n elif simEnd == \"employment\":\n endDate = pd.Timestamp(employmentStart)\n else:\n endDate = myPayments.index.max() # simulation ends at final payment\n\n delta = timedelta(days=1)\n \n ## Simulate through dates in date period, \n ## compounding interest each day and adding installments\n \n while startDate <= endDate: # simulate interest compounding up to and including last day\n interestRate = find_interest_rate(startDate)\n cumulativeTotal *= (1+(interestRate/365)) # apply interest on previous payments before new payment\n if startDate in myPayments.index: # check if there was a loan instalment on this day\n cumulativeTotal += myPayments.loc[startDate][\"Gross\"]\n startDate += delta \n \n else:\n print(\"Please enter your net total of Student Debt at graduation\")\n cumulativeTotal = input()\n return cumulativeTotal\n"
},
{
"code": null,
"e": 9284,
"s": 8899,
"text": "Using the above functions, the value owed in Student Finance loans at the start of employment can be calculated. After the April following graduation, you begin paying back towards your loan in the style of a monthly tax. In this simulation interest accrues on the loan daily and on the last working day of the month (BMonthEnd) your repayment comes out of your salary, as in reality."
},
{
"code": null,
"e": 9877,
"s": 9284,
"text": "Monte Carlo methods are a class of algorithms that rely on repeated random sampling to obtain numerical results — by the law of large numbers, the expected value of a random variable can be approximated by taking the sample mean of independent samples. In plain English: “while we don’t know what the correct answer or strategy is, we can simulate many attempts and the average will approximate the right answer”. Monte Carlo can be used for many problems with a probabilistic element or “risk”, such as gambling, or stock market and portfolio performance in finance. Here is a great example."
},
{
"code": null,
"e": 10116,
"s": 9877,
"text": "Since the amount of student finance I will pay across my working life (through monthly payments) is based on what I earn at time t, and I don’t know what I will earn, I can simulate my career earnings using Monte Carlo. In the simulation:"
},
{
"code": null,
"e": 10282,
"s": 10116,
"text": "The starting salary (£29,000) is the median graduate starting salary, based on graduate schemes of employment — reported by the Institute of Student Employers (ISE)."
},
{
"code": null,
"e": 10373,
"s": 10282,
"text": "I divide the 30-year payment period of the loan into different salary bands for my career."
},
{
"code": null,
"e": 10443,
"s": 10373,
"text": "I chose 6 separate bands, each 5 years long (but this can be varied)."
},
{
"code": null,
"e": 10628,
"s": 10443,
"text": "Each salary band represents a salary increase at time t — the increase is taken from a Gaussian distribution centred around a mean which is a percentage of my gross salary at time t-1."
},
{
"code": null,
"e": 10856,
"s": 10628,
"text": "This percentage decreases the further the simulation runs into my career i.e., most salary growth occurs in early years (high % increase), then it slows (low % increase). e.g., in the below table (0,1) = 37.49% salary increase."
},
{
"code": null,
"e": 10924,
"s": 10856,
"text": "I simulate my career according to these salary bands 100,000 times."
},
{
"code": null,
"e": 11370,
"s": 10924,
"text": "The loan’s interest rate is set at 5.5% — RPI of 2.5% plus 3% (government method). To inform this I used a 5-year moving average of historic UK RPI values, which I downloaded from the Office for National Statistics (ONS). Whilst predicted RPI estimates are available, the current COVID-19 crisis and its economic implications will likely affect these predictions, thus I took the pre-COVID19 value which has remained around 2.5% in recent years."
},
{
"code": null,
"e": 11536,
"s": 11370,
"text": "I calculate what the average loan value and cumulative sum of repayments (lifetime contribution) are across all salary trajectories after the 30-year payment period."
},
{
"code": null,
"e": 11549,
"s": 11536,
"text": "Translation:"
},
{
"code": null,
"e": 11807,
"s": 11549,
"text": "As a graduate earner, most salary growth occurs in the early years (high % increase) before levelling off (low % increase) — see this incredibly thorough new report The impact of undergraduate degree on lifetime earnings by the Institute for Fiscal Studies."
},
{
"code": null,
"e": 12346,
"s": 11807,
"text": "A pay-rise of x% in 5 years is not certain —it could be slightly less than or greater than x%, or you could have a series of smaller or larger pay-rises (the aggregate of which are represented in the 5-year jump). Monte Carlo helps to mitigate this by drawing many salary values (k = 100,000) from a normal distribution for each band. These average x%, but can be less than or greater than x%. I simulate all these trajectories and the monthly payments towards my loan and work out in how many of the simulations I pay off my entire loan."
},
{
"code": null,
"e": 12670,
"s": 12346,
"text": "As you can see in the top plot, only a small proportion of loans are ever paid off via monthly deductions. These loans are identifiable as the trajectories which cross the zero-line (marked in red) and correspond to the largest salaries. The lowest salaries across all years result in loans which continue to grow in value."
},
{
"code": null,
"e": 12729,
"s": 12670,
"text": "For 100,000 simulations, after the 30 year payment period:"
},
{
"code": null,
"e": 12767,
"s": 12729,
"text": "the average loan value is: £60,600.74"
},
{
"code": null,
"e": 12897,
"s": 12767,
"text": "only in 3.54% of salary trajectories was the loan completely paid off i.e., crossed the red zero line in the plot (3,543/100,000)"
},
{
"code": null,
"e": 12968,
"s": 12897,
"text": "the average total amount of money paid towards the loan is: £99,691.01"
},
{
"code": null,
"e": 13324,
"s": 12968,
"text": "DISCLAIMER: I am not a financial adviser — any ideas here are purely hypothetical based off simulations with a suite of assumptions & caveats. These are simply my thoughts on potentially effective strategies, as part of a conceptual exercise. If you are unsure about your own personal financial situation, seek the advice of a qualified financial adviser."
},
{
"code": null,
"e": 13378,
"s": 13324,
"text": "This simulation, of course, contains several caveats:"
},
{
"code": null,
"e": 14699,
"s": 13378,
"text": "Salary bands: I assume 6 x 5-year salary bands — there is no guarantee that graduate earnings will follow this format. There are not adequate data on regular salary progressions for a particular field in the UK, as salary increases and promotions are subject to many variables, including academic qualifications (e.g. BSc vs MSc vs PhD), field, company, and the performance of the individual themselves. Whilst there are data on average graduate earnings per subject, these data do not capture the many routes/fields that a graduate with a particular degree can take. After conversations with senior roles in my network, I determined that approximate 5-year frequencies for salary increases and the percentages chosen are close to reality, on average, for a STEM graduate.Interest rate: This simulation assumes that recent RPI values will remain constant in future years, however the real interest rate on the loan changes every academic year because of changing RPI, which will affect how quickly the interest of the loan compounds.Starting salary: I used the average starting salary based on graduate schemes, but this is not representative of all graduate salaries — which affects repayment.Other compensation: The simulation only considers base salary, without bonuses, company shares or other forms of renumeration."
},
{
"code": null,
"e": 15472,
"s": 14699,
"text": "Salary bands: I assume 6 x 5-year salary bands — there is no guarantee that graduate earnings will follow this format. There are not adequate data on regular salary progressions for a particular field in the UK, as salary increases and promotions are subject to many variables, including academic qualifications (e.g. BSc vs MSc vs PhD), field, company, and the performance of the individual themselves. Whilst there are data on average graduate earnings per subject, these data do not capture the many routes/fields that a graduate with a particular degree can take. After conversations with senior roles in my network, I determined that approximate 5-year frequencies for salary increases and the percentages chosen are close to reality, on average, for a STEM graduate."
},
{
"code": null,
"e": 15734,
"s": 15472,
"text": "Interest rate: This simulation assumes that recent RPI values will remain constant in future years, however the real interest rate on the loan changes every academic year because of changing RPI, which will affect how quickly the interest of the loan compounds."
},
{
"code": null,
"e": 15896,
"s": 15734,
"text": "Starting salary: I used the average starting salary based on graduate schemes, but this is not representative of all graduate salaries — which affects repayment."
},
{
"code": null,
"e": 16023,
"s": 15896,
"text": "Other compensation: The simulation only considers base salary, without bonuses, company shares or other forms of renumeration."
},
{
"code": null,
"e": 16130,
"s": 16023,
"text": "So what is the conclusion here? What strategy should you take with regard to paying off your student loan?"
},
{
"code": null,
"e": 16466,
"s": 16130,
"text": "Firstly, it should be highlighted that debt repayment is a blend of arithmetic and also psychology, because as complex creatures, our emotional welfare with regard to debt is affected by multiple factors. There are different debt consolidation strategies if you have multiple debt repayments to make e.g. Snowball or Avalanche methods."
},
{
"code": null,
"e": 17023,
"s": 16466,
"text": "Secondly, in a purely mathematical sense, the optimum strategy for paying the minimum amount on the student loan would be to remain at a salary below the repayment threshold for the entire 30-year payment period, thereby receiving the degree for free, as you never pay a penny for it. However, this is only when considering the loan in isolation from other factors, and obviously does not reflect the real life ambitions of a typical graduate. With this in mind I consider strategies that assume progressive career growth which includes repaying your loan."
},
{
"code": null,
"e": 17266,
"s": 17023,
"text": "Practically and in isolation, yes, you should try and pay it off with any extra money you encounter, because the Results show, on average, you will pay for the loan more than twice over across your working life time (99,691.01/42,000 = 2.37)."
},
{
"code": null,
"e": 17589,
"s": 17266,
"text": "Crucially, the major factor affecting amortisation in this problem is the dynamics between the interest and the monthly repayments. If the interest on the loan accrued in a given month is £20, you need to pay more than £20 in repayments at the end of the month to decrease the principal amount — this is basic mathematics."
},
{
"code": null,
"e": 18489,
"s": 17589,
"text": "The key factor is the rate at which your salary increases, because of the powers of compound growth. Your repayments need to chip off the interest plus more to start decreasing the principal amount. But, if your salary means you don’t manage to overcome the interest early on, even if your salary rises to a substantial amount later in life, the loan will have grown to an amount which demands a disproportionately higher salary to conquer the later monthly interest, which will be much greater due to the non-linearity of compound growth. Therefore, to successfully pay off your loan only through monthly tax repayments, the salary must grow fast enough in the early years such that repayments quickly overcome the interest and the debt is not “allowed” to grow. The other option is that if your salary is too low to achieve this, you make voluntary repayments each month to make up the difference."
},
{
"code": null,
"e": 18890,
"s": 18489,
"text": "Of course in reality, your loan repayment is not in isolation of other factors. It’s a multi-dimensional problem! It comes down to what else you can invest any extra money in for the long term, because of the time-value of money and opportunity cost. Time-value of money is the concept that the same sum of money is worth more now than later on in life because of its earning potential and inflation."
},
{
"code": null,
"e": 19122,
"s": 18890,
"text": "If you come across a sum of money that affords you the ability to pay off the loan (either from a savings account, inheritance etc.), you could invest it and grow it, utilising compound growth rather than only being a victim of it."
},
{
"code": null,
"e": 19590,
"s": 19122,
"text": "I did a post-hoc analysis to show this. Suppose instead of paying off the loan, you use a long term, sit-and-hold strategy in an investment with a higher average return than the amount you pay towards the loan through monthly salary deductions — either with a lump sum equivalent to the value of the loan (£42,000), or — since this situation will be very rare for the typical graduate — with an initial investment of £1,000 and monthly deposits of any savings (£200)."
},
{
"code": null,
"e": 19603,
"s": 19590,
"text": "3 scenarios:"
},
{
"code": null,
"e": 20210,
"s": 19603,
"text": "You encounter £42,000 and pay off the loan immediately. Monthly repayments (blue line) would cost you approx. £100,000 over your lifetime, which you’ve avoided. £100,000 — £42,000 = £58,000 “profit”.You encounter £42,000 and invest it at a 5.0% return (after inflation) and leave it to grow for the 30-years instead (orange line). After 30 years this is worth approx £187,000. £187,000 — £100,000 = £87,000 profit.You invest £1,000 and use money you save each month (e.g. £200) to top up the investment monthly (green line). After 30 years this is worth approx £170,000. £170,000–£100,000 = £70,000 profit."
},
{
"code": null,
"e": 20410,
"s": 20210,
"text": "You encounter £42,000 and pay off the loan immediately. Monthly repayments (blue line) would cost you approx. £100,000 over your lifetime, which you’ve avoided. £100,000 — £42,000 = £58,000 “profit”."
},
{
"code": null,
"e": 20626,
"s": 20410,
"text": "You encounter £42,000 and invest it at a 5.0% return (after inflation) and leave it to grow for the 30-years instead (orange line). After 30 years this is worth approx £187,000. £187,000 — £100,000 = £87,000 profit."
},
{
"code": null,
"e": 20819,
"s": 20626,
"text": "You invest £1,000 and use money you save each month (e.g. £200) to top up the investment monthly (green line). After 30 years this is worth approx £170,000. £170,000–£100,000 = £70,000 profit."
},
{
"code": null,
"e": 21394,
"s": 20819,
"text": "As these results show, even if the simulated graduate doesn’t have a large lump sum available and uses a much more modest amount to begin investing their monthly savings, they could still end up in greater profit than if they paid off the loan completely. In most cases, graduates are unlikely to encounter this kind of lump sum, and to attempt to save money after your living costs to then pay towards the student loan could leave you forever chasing your own tail as the loan interest simultaneously compounds more than you can save — you would be better off investing it."
},
{
"code": null,
"e": 21751,
"s": 21394,
"text": "This opportunity cost applies to other investments, like purchasing a house and leveraging its appreciation in value and even to investment in yourself, such as courses, seminars and conferences, which develop your skills and grow your network. Whilst this is hard to capture in monetary terms, it will generate more opportunity, and likely greater profit."
},
{
"code": null,
"e": 21815,
"s": 21751,
"text": "It’s not a crystal-clear conclusion— there are a lot of “‘ifs”:"
},
{
"code": null,
"e": 22004,
"s": 21815,
"text": "If the interest on the loan were much lower, it would be clear to simply pay through monthly deductions with less concern for added investment as you would be a lot less likely to overpay."
},
{
"code": null,
"e": 22457,
"s": 22004,
"text": "If you encounter a sum of money that approximates the value of your student debt or if you save money each month, it could be more profitable to invest it, as paying off the loan would incur huge opportunity cost. As a young graduate you are in a strong position— the time/effort/money invested in your first few years can affect the course of your career, and years of delayed investment for the future could drastically reduce your ROI later in life."
},
{
"code": null,
"e": 22704,
"s": 22457,
"text": "If you have the money but don’t invest it, then you would be better off paying off the loan with this money, otherwise you could pay several times over through monthly repayments, plus this liquid money will lose value each year due to inflation."
},
{
"code": null,
"e": 22792,
"s": 22704,
"text": "These results will undoubtedly inform my personal finance decisions in the near future."
},
{
"code": null,
"e": 23077,
"s": 22792,
"text": "What is also reassuring is that the report mentioned above found that even after accounting for taxes and Student Finance repayments, UK graduates are still at least £100,000 better off, on average, for getting a degree, because of the additional, net take-home salary that they earn."
},
{
"code": null,
"e": 23945,
"s": 23077,
"text": "This project has certainly shown me that the notion of “don’t pay off the loan in full as it gets cancelled later on” is misguided in its lack of elaboration — it completely depends on salary, because this determines if you under- or over-pay for your degree. If lifetime salary is low enough, then you could underpay for the degree via monthly repayments, in which case you should not pay extra or worry about investing. However, these simulations suggest that if you end up earning in the average (densest) region (see salary step plot in Results) then you should invest any extra money and pay the minimum on your loan. This is because you will need investments later on to counterbalance the over-payment of your degree. Of course, these conclusions are hypothetical and are drawn from the predicted interest rate and simulated salaries, which could be different."
},
{
"code": null,
"e": 24872,
"s": 23945,
"text": "Apart from the greater understanding of the student loans system I have gained, this exercise did highlight something important. We do not have enough publicly available and consumable data tracking graduate lifetime earnings for different fields or careers. The report mentioned analyses longitudinal data for graduates and non-graduates from a particular cohort, and was very recently published — research like this needs to be made available and digestible to prospective undergraduates. Undergraduate university courses in the UK now cost up to £9,250 per year, which you may pay for several times over as we have seen. We need data on what graduates of a particular course at a particular university go on to earn so candidates can judge for themselves what the ROI for their course and university would be, in light of the huge loan they would be taking on, rather than simply being dazzled by universities on Open Days."
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.