title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to convert a String representation of a Dictionary to a dictionary in Python? | Dictionary object is easily convertible to string by str() function.
>>> D1={'1':1, '2':2, '3':3}
>>> D1
{'1': 1, '2': 2, '3': 3}
>>> str(D1)
"{'1': 1, '2': 2, '3': 3}"
To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function.
>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> s
"{'1': 1, '2': 2, '3': 3}"
>>> D2=eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3}
Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure.
>>> D1={'1':1, '2':2, '3':3}
>>> s=str(D1)
>>> import ast
>>> D2=ast.literal_eval(s)
>>> D2
{'1': 1, '2': 2, '3': 3} | [
{
"code": null,
"e": 1131,
"s": 1062,
"text": "Dictionary object is easily convertible to string by str() function."
},
{
"code": null,
"e": 1231,
"s": 1131,
"text": ">>> D1={'1':1, '2':2, '3':3}\n>>> D1\n{'1': 1, '2': 2, '3': 3}\n>>> str(D1)\n\"{'1': 1, '2': 2, '3': 3}\""
},
{
"code": null,
"e": 1384,
"s": 1231,
"text": "To convert a string to dictionary, we have to ensure that the string contains a valid representation of dictionary. This can be done by eval() function."
},
{
"code": null,
"e": 1507,
"s": 1384,
"text": ">>> D1={'1':1, '2':2, '3':3}\n>>> s=str(D1)\n>>> s\n\"{'1': 1, '2': 2, '3': 3}\"\n>>> D2=eval(s)\n>>> D2\n{'1': 1, '2': 2, '3': 3}"
},
{
"code": null,
"e": 1632,
"s": 1507,
"text": "Abstract Syntax Tree (ast) module of Python has literal_eval() method which safely evaluates valid Python literal structure."
},
{
"code": null,
"e": 1751,
"s": 1632,
"text": ">>> D1={'1':1, '2':2, '3':3}\n>>> s=str(D1)\n>>> import ast\n>>> D2=ast.literal_eval(s)\n>>> D2\n{'1': 1, '2': 2, '3': 3}\n\n"
}
] |
Scylla – Phone Number & User Information Gathering Tool in Kali Linux - GeeksforGeeks | 30 Apr, 2021
Scylla is a free and open-source tool available on Github. Scylla is based upon the concept of Open Source Intelligence (OSINT). This tool is used for information gathering. Scylla is written in python language. You must have python language installed in your Kali Linux in order to use the Scylla tool. Scylla is an advanced tool that allows it’s used to perform advanced information gathering. Scylla is also called The Information Gathering Engine. Scylla is used to find all social media accounts of a person who is assigned to a particular username. Scylla is used to find account information of the account of Instagram. Twitter accounts, websites/web servers, phone numbers, and names.
Scylla has a drastic support IoT search engine Shodan. This search engine lets you know about devices all over the internet. Scylla also has in-depth geolocation capabilities which makes it more powerful. Scylla has financial modules which allow the user to check whether their credit/debit card details have been leaked or not in a pasted data breach of companies. This tool makes it easy to search for a person on social media platform by just knowing his/her number or username. You have to give your username to Scylla and this tool will give you all the social media accounts information of the target.
Features of Scylla:
Scylla is a free tool You can download and use it free of cost.
Scylla is open source tool. Scylla’s source code is available on GitHub you can check it and contribute to it.
Scylla works on the concept of Open Source Intelligence (OSINT).
Scylla is used for information gathering.
Scylla is an advanced tool used for advance searching on the internet.
Scylla is written in python language. You must have python language installed into your Kali Linux operating system in order to use Scylla.
Scylla is also called an information gathering Engine.
Uses of Scylla:
For information gathering.
To search accounts on social media platforms associated with a number.
To search IoT devices.
To get account information on Instagram.
To get account information on Twitter.
Get the Google account details of any user.
To see webcams that are open on the internet. You can see these webcams by using shodan search engine API key.
To get information about specific IP addresses. Scylla will give you the exact street, city, state, country, and zip/postal along with longitude and latitude.
To get information about credit cards and debit cards.
To check whether the card information leaked in past or not.
To get information on that phone number which you have provided for eg (Carrier, Location, etc.)
Step 1: Open your Kali Linux operating system. Move to desktop. Here you have to create a directory called Scylla. To move to desktop use the following command.
cd Desktop
Step 2: Now you are on the desktop. Here you have to create a directory Scylla. To create the Scylla directory using the following command.
mkdir Scylla
Step 3: You have created a directory. Now use the following command to move into that directory.
cd Scylla
Step 4: Now you are in Scylla directory. Now you have to install the tool using the following command.
git clone https://www.github.com/DoubleThreatSecurity/Scylla
Step 5: You have downloaded the tool use the following command to list out the contents of the tool.
ls
Step 6: In order to use scylla we will have to move to the scylla directory. Use the following command to move in this directory.
cd scylla
Step 7: Now you are in the directory called scylla. Use the following command to list out the contents of the directory.
ls
Step 8: You can see many files in this directory. These are the files of the tool. Now you have to install the requirements of the tool. Use the following command to install requirements.
python3 -m pip install -r requirments.txt
Step 9: All the requirements have been installed. Now you have to run the tool using the following command.
python3 scylla.py
Step 10: The tool is running finally. To get the help of the tool uses the following command.
python3 scylla.py --help
1. Use the Scylla tool to get information about Instagram account of a user.
python3 scylla.py --instagram < username >
This command is used to target Instagram accounts of users.
2. Use the Scylla tool to get information about the social media accounts of a user.
python3 scylla.py --username < username >
3. Use the Scylla tool to get information about the phone numbers.
python3 scylla.py -r +918439xxxxxx
4. Use the Scylla tool to get information about geolocation of an IP-address.
python3 scylla.py -g <your ip address>
Cyber-security
Kali-Linux
Linux-Tools
Linux-Unix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
TCP Server-Client implementation in C
UDP Server-Client implementation in C
tar command in Linux with examples
'crontab' in Linux with Examples
Named Pipe or FIFO with example C program
Cat command in Linux with examples
Mutex lock for Linux Thread Synchronization
echo command in Linux with Examples
Thread functions in C/C++
Conditional Statements | Shell Script | [
{
"code": null,
"e": 24552,
"s": 24524,
"text": "\n30 Apr, 2021"
},
{
"code": null,
"e": 25245,
"s": 24552,
"text": "Scylla is a free and open-source tool available on Github. Scylla is based upon the concept of Open Source Intelligence (OSINT). This tool is used for information gathering. Scylla is written in python language. You must have python language installed in your Kali Linux in order to use the Scylla tool. Scylla is an advanced tool that allows it’s used to perform advanced information gathering. Scylla is also called The Information Gathering Engine. Scylla is used to find all social media accounts of a person who is assigned to a particular username. Scylla is used to find account information of the account of Instagram. Twitter accounts, websites/web servers, phone numbers, and names."
},
{
"code": null,
"e": 25853,
"s": 25245,
"text": "Scylla has a drastic support IoT search engine Shodan. This search engine lets you know about devices all over the internet. Scylla also has in-depth geolocation capabilities which makes it more powerful. Scylla has financial modules which allow the user to check whether their credit/debit card details have been leaked or not in a pasted data breach of companies. This tool makes it easy to search for a person on social media platform by just knowing his/her number or username. You have to give your username to Scylla and this tool will give you all the social media accounts information of the target."
},
{
"code": null,
"e": 25873,
"s": 25853,
"text": "Features of Scylla:"
},
{
"code": null,
"e": 25937,
"s": 25873,
"text": "Scylla is a free tool You can download and use it free of cost."
},
{
"code": null,
"e": 26048,
"s": 25937,
"text": "Scylla is open source tool. Scylla’s source code is available on GitHub you can check it and contribute to it."
},
{
"code": null,
"e": 26113,
"s": 26048,
"text": "Scylla works on the concept of Open Source Intelligence (OSINT)."
},
{
"code": null,
"e": 26155,
"s": 26113,
"text": "Scylla is used for information gathering."
},
{
"code": null,
"e": 26226,
"s": 26155,
"text": "Scylla is an advanced tool used for advance searching on the internet."
},
{
"code": null,
"e": 26366,
"s": 26226,
"text": "Scylla is written in python language. You must have python language installed into your Kali Linux operating system in order to use Scylla."
},
{
"code": null,
"e": 26421,
"s": 26366,
"text": "Scylla is also called an information gathering Engine."
},
{
"code": null,
"e": 26437,
"s": 26421,
"text": "Uses of Scylla:"
},
{
"code": null,
"e": 26464,
"s": 26437,
"text": "For information gathering."
},
{
"code": null,
"e": 26535,
"s": 26464,
"text": "To search accounts on social media platforms associated with a number."
},
{
"code": null,
"e": 26558,
"s": 26535,
"text": "To search IoT devices."
},
{
"code": null,
"e": 26599,
"s": 26558,
"text": "To get account information on Instagram."
},
{
"code": null,
"e": 26638,
"s": 26599,
"text": "To get account information on Twitter."
},
{
"code": null,
"e": 26682,
"s": 26638,
"text": "Get the Google account details of any user."
},
{
"code": null,
"e": 26793,
"s": 26682,
"text": "To see webcams that are open on the internet. You can see these webcams by using shodan search engine API key."
},
{
"code": null,
"e": 26952,
"s": 26793,
"text": "To get information about specific IP addresses. Scylla will give you the exact street, city, state, country, and zip/postal along with longitude and latitude."
},
{
"code": null,
"e": 27007,
"s": 26952,
"text": "To get information about credit cards and debit cards."
},
{
"code": null,
"e": 27068,
"s": 27007,
"text": "To check whether the card information leaked in past or not."
},
{
"code": null,
"e": 27165,
"s": 27068,
"text": "To get information on that phone number which you have provided for eg (Carrier, Location, etc.)"
},
{
"code": null,
"e": 27326,
"s": 27165,
"text": "Step 1: Open your Kali Linux operating system. Move to desktop. Here you have to create a directory called Scylla. To move to desktop use the following command."
},
{
"code": null,
"e": 27337,
"s": 27326,
"text": "cd Desktop"
},
{
"code": null,
"e": 27477,
"s": 27337,
"text": "Step 2: Now you are on the desktop. Here you have to create a directory Scylla. To create the Scylla directory using the following command."
},
{
"code": null,
"e": 27490,
"s": 27477,
"text": "mkdir Scylla"
},
{
"code": null,
"e": 27587,
"s": 27490,
"text": "Step 3: You have created a directory. Now use the following command to move into that directory."
},
{
"code": null,
"e": 27597,
"s": 27587,
"text": "cd Scylla"
},
{
"code": null,
"e": 27700,
"s": 27597,
"text": "Step 4: Now you are in Scylla directory. Now you have to install the tool using the following command."
},
{
"code": null,
"e": 27761,
"s": 27700,
"text": "git clone https://www.github.com/DoubleThreatSecurity/Scylla"
},
{
"code": null,
"e": 27862,
"s": 27761,
"text": "Step 5: You have downloaded the tool use the following command to list out the contents of the tool."
},
{
"code": null,
"e": 27865,
"s": 27862,
"text": "ls"
},
{
"code": null,
"e": 27995,
"s": 27865,
"text": "Step 6: In order to use scylla we will have to move to the scylla directory. Use the following command to move in this directory."
},
{
"code": null,
"e": 28005,
"s": 27995,
"text": "cd scylla"
},
{
"code": null,
"e": 28126,
"s": 28005,
"text": "Step 7: Now you are in the directory called scylla. Use the following command to list out the contents of the directory."
},
{
"code": null,
"e": 28129,
"s": 28126,
"text": "ls"
},
{
"code": null,
"e": 28317,
"s": 28129,
"text": "Step 8: You can see many files in this directory. These are the files of the tool. Now you have to install the requirements of the tool. Use the following command to install requirements."
},
{
"code": null,
"e": 28359,
"s": 28317,
"text": "python3 -m pip install -r requirments.txt"
},
{
"code": null,
"e": 28467,
"s": 28359,
"text": "Step 9: All the requirements have been installed. Now you have to run the tool using the following command."
},
{
"code": null,
"e": 28485,
"s": 28467,
"text": "python3 scylla.py"
},
{
"code": null,
"e": 28579,
"s": 28485,
"text": "Step 10: The tool is running finally. To get the help of the tool uses the following command."
},
{
"code": null,
"e": 28605,
"s": 28579,
"text": "python3 scylla.py --help"
},
{
"code": null,
"e": 28682,
"s": 28605,
"text": "1. Use the Scylla tool to get information about Instagram account of a user."
},
{
"code": null,
"e": 28725,
"s": 28682,
"text": "python3 scylla.py --instagram < username >"
},
{
"code": null,
"e": 28785,
"s": 28725,
"text": "This command is used to target Instagram accounts of users."
},
{
"code": null,
"e": 28870,
"s": 28785,
"text": "2. Use the Scylla tool to get information about the social media accounts of a user."
},
{
"code": null,
"e": 28912,
"s": 28870,
"text": "python3 scylla.py --username < username >"
},
{
"code": null,
"e": 28979,
"s": 28912,
"text": "3. Use the Scylla tool to get information about the phone numbers."
},
{
"code": null,
"e": 29014,
"s": 28979,
"text": "python3 scylla.py -r +918439xxxxxx"
},
{
"code": null,
"e": 29092,
"s": 29014,
"text": "4. Use the Scylla tool to get information about geolocation of an IP-address."
},
{
"code": null,
"e": 29131,
"s": 29092,
"text": "python3 scylla.py -g <your ip address>"
},
{
"code": null,
"e": 29146,
"s": 29131,
"text": "Cyber-security"
},
{
"code": null,
"e": 29157,
"s": 29146,
"text": "Kali-Linux"
},
{
"code": null,
"e": 29169,
"s": 29157,
"text": "Linux-Tools"
},
{
"code": null,
"e": 29180,
"s": 29169,
"text": "Linux-Unix"
},
{
"code": null,
"e": 29278,
"s": 29180,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29287,
"s": 29278,
"text": "Comments"
},
{
"code": null,
"e": 29300,
"s": 29287,
"text": "Old Comments"
},
{
"code": null,
"e": 29338,
"s": 29300,
"text": "TCP Server-Client implementation in C"
},
{
"code": null,
"e": 29376,
"s": 29338,
"text": "UDP Server-Client implementation in C"
},
{
"code": null,
"e": 29411,
"s": 29376,
"text": "tar command in Linux with examples"
},
{
"code": null,
"e": 29444,
"s": 29411,
"text": "'crontab' in Linux with Examples"
},
{
"code": null,
"e": 29486,
"s": 29444,
"text": "Named Pipe or FIFO with example C program"
},
{
"code": null,
"e": 29521,
"s": 29486,
"text": "Cat command in Linux with examples"
},
{
"code": null,
"e": 29565,
"s": 29521,
"text": "Mutex lock for Linux Thread Synchronization"
},
{
"code": null,
"e": 29601,
"s": 29565,
"text": "echo command in Linux with Examples"
},
{
"code": null,
"e": 29627,
"s": 29601,
"text": "Thread functions in C/C++"
}
] |
Setting the name of the axes in Pandas DataFrame - GeeksforGeeks | 23 Jan, 2019
There are multiple operations which can be performed over the exes in Pandas. Let’s see how to operate on row and column index with examples.
For link to the CSV file used in the code, click here.
Code #1 : We can reset the name of the DataFrame index by using df.index.name attribute.
# importing pandas as pdimport pandas as pd # read the csv file and create DataFramedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df)
Output :
# set the index namedf.index.name = 'Index_name' # Print the DataFrameprint(df)
Output :
Code #2 : We can reset the name of the DataFrame index by using df.rename_axis() function.
# importing pandas as pdimport pandas as pd # read the csv file and create DataFramedf = pd.read_csv('nba.csv') # reset the index namedf.rename_axis('Index_name', axis = 'rows') # Print the DataFrameprint(df)
Output :
Code #1 : We can reset the name of the DataFrame column axes by using df.rename_axis() function.
# importing pandas as pdimport pandas as pd # read the csv file and create DataFramedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df)
Output :
As we can see in the output, column axes of the df DataFrame does not have any name. So, we will set the name using df.rename_axis() function.
# set the name of column axesdf.rename_axis('Column_Index_name', axis = 'columns') # Print the DataFrameprint(df)
Output :
Python pandas-dataFrame
Python pandas-indexing
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25555,
"s": 25527,
"text": "\n23 Jan, 2019"
},
{
"code": null,
"e": 25697,
"s": 25555,
"text": "There are multiple operations which can be performed over the exes in Pandas. Let’s see how to operate on row and column index with examples."
},
{
"code": null,
"e": 25752,
"s": 25697,
"text": "For link to the CSV file used in the code, click here."
},
{
"code": null,
"e": 25841,
"s": 25752,
"text": "Code #1 : We can reset the name of the DataFrame index by using df.index.name attribute."
},
{
"code": "# importing pandas as pdimport pandas as pd # read the csv file and create DataFramedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df)",
"e": 25990,
"s": 25841,
"text": null
},
{
"code": null,
"e": 25999,
"s": 25990,
"text": "Output :"
},
{
"code": "# set the index namedf.index.name = 'Index_name' # Print the DataFrameprint(df)",
"e": 26080,
"s": 25999,
"text": null
},
{
"code": null,
"e": 26089,
"s": 26080,
"text": "Output :"
},
{
"code": null,
"e": 26182,
"s": 26091,
"text": "Code #2 : We can reset the name of the DataFrame index by using df.rename_axis() function."
},
{
"code": "# importing pandas as pdimport pandas as pd # read the csv file and create DataFramedf = pd.read_csv('nba.csv') # reset the index namedf.rename_axis('Index_name', axis = 'rows') # Print the DataFrameprint(df)",
"e": 26394,
"s": 26182,
"text": null
},
{
"code": null,
"e": 26403,
"s": 26394,
"text": "Output :"
},
{
"code": null,
"e": 26500,
"s": 26403,
"text": "Code #1 : We can reset the name of the DataFrame column axes by using df.rename_axis() function."
},
{
"code": "# importing pandas as pdimport pandas as pd # read the csv file and create DataFramedf = pd.read_csv('nba.csv') # Visualize the dataframeprint(df)",
"e": 26649,
"s": 26500,
"text": null
},
{
"code": null,
"e": 26658,
"s": 26649,
"text": "Output :"
},
{
"code": null,
"e": 26801,
"s": 26658,
"text": "As we can see in the output, column axes of the df DataFrame does not have any name. So, we will set the name using df.rename_axis() function."
},
{
"code": "# set the name of column axesdf.rename_axis('Column_Index_name', axis = 'columns') # Print the DataFrameprint(df)",
"e": 26916,
"s": 26801,
"text": null
},
{
"code": null,
"e": 26925,
"s": 26916,
"text": "Output :"
},
{
"code": null,
"e": 26949,
"s": 26925,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 26972,
"s": 26949,
"text": "Python pandas-indexing"
},
{
"code": null,
"e": 26986,
"s": 26972,
"text": "Python-pandas"
},
{
"code": null,
"e": 26993,
"s": 26986,
"text": "Python"
},
{
"code": null,
"e": 27091,
"s": 26993,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27123,
"s": 27091,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27165,
"s": 27123,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27207,
"s": 27165,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27263,
"s": 27207,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27290,
"s": 27263,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27321,
"s": 27290,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27360,
"s": 27321,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27389,
"s": 27360,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27411,
"s": 27389,
"text": "Defaultdict in Python"
}
] |
What are the differences between JavaScript Primitive Data Types and Objects? | Before beginning with the difference, let’s learn what are Primitive Datatypes. Primitive defines immutable values and introduced recently by ECMAScript standard.
JavaScript allows you to work with three primitive data types,
Numbers, eg. 3, 310.20 etc.
Strings of text e.g. "This text string" etc.
Boolean e.g. true or false.
JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as the object.After datatypes, let us discuss about Objects:
Objects
In JavaScript, objects are considered a collection of properties. Identify properties using key values. It has two types:
Data Property
It associates a key with a value.Let’s say we take an example of a string with primitive data type and object:
For Primitive Datatype,
var str = "Demo string!";
For Object,
var str = new String("Demo string!");
Accessor Property
It associates a key with accessor functions. This is to store a value. | [
{
"code": null,
"e": 1225,
"s": 1062,
"text": "Before beginning with the difference, let’s learn what are Primitive Datatypes. Primitive defines immutable values and introduced recently by ECMAScript standard."
},
{
"code": null,
"e": 1288,
"s": 1225,
"text": "JavaScript allows you to work with three primitive data types,"
},
{
"code": null,
"e": 1316,
"s": 1288,
"text": "Numbers, eg. 3, 310.20 etc."
},
{
"code": null,
"e": 1361,
"s": 1316,
"text": "Strings of text e.g. \"This text string\" etc."
},
{
"code": null,
"e": 1389,
"s": 1361,
"text": "Boolean e.g. true or false."
},
{
"code": null,
"e": 1652,
"s": 1389,
"text": "JavaScript also defines two trivial data types, null and undefined, each of which defines only a single value. In addition to these primitive data types, JavaScript supports a composite data type known as the object.After datatypes, let us discuss about Objects:"
},
{
"code": null,
"e": 1661,
"s": 1652,
"text": "Objects "
},
{
"code": null,
"e": 1783,
"s": 1661,
"text": "In JavaScript, objects are considered a collection of properties. Identify properties using key values. It has two types:"
},
{
"code": null,
"e": 1798,
"s": 1783,
"text": "Data Property "
},
{
"code": null,
"e": 1910,
"s": 1798,
"text": "It associates a key with a value.Let’s say we take an example of a string with primitive data type and object: "
},
{
"code": null,
"e": 1934,
"s": 1910,
"text": "For Primitive Datatype,"
},
{
"code": null,
"e": 1960,
"s": 1934,
"text": "var str = \"Demo string!\";"
},
{
"code": null,
"e": 1972,
"s": 1960,
"text": "For Object,"
},
{
"code": null,
"e": 2010,
"s": 1972,
"text": "var str = new String(\"Demo string!\");"
},
{
"code": null,
"e": 2028,
"s": 2010,
"text": "Accessor Property"
},
{
"code": null,
"e": 2099,
"s": 2028,
"text": "It associates a key with accessor functions. This is to store a value."
}
] |
Python IMDbPY – Getting released year of movie from movie object - GeeksforGeeks | 22 Apr, 2020
In this article we will see how we can get the released year of movie from the movie object, we can get movie object with the help of search_movie and get_movie method to find movies.
search_movie method returns list and each element of list work as a dictionary similarly get_movie method return a movie object which work as dictionary i.e. they can be queried by giving the key of the data, here key will be year.
Syntax : movie[‘year’]
Here movie is the imdb Movie object
Return : It returns integer which is the release year
Below is the implementation
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting the movie with idsearch = ia.get_movie("0111161") # getting movie yearyear = search['year'] # printing movie name and yearprint(search['title'] + " : " + str(year))
Output :
The Shawshank Redemption : 1994
Another example
# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting the movie with namesearch = ia.search_movie("3 Idiots") # getting movie yearyear = search[0]['year'] # printing movie name and yearprint(search[0]['title'] + " : " + str(year))
Output :
3 Idiots : 2009
Python IMDbPY-module
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace()
Reading and Writing to text files in Python
*args and **kwargs in Python
Create a Pandas DataFrame from Lists
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 26429,
"s": 26401,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 26613,
"s": 26429,
"text": "In this article we will see how we can get the released year of movie from the movie object, we can get movie object with the help of search_movie and get_movie method to find movies."
},
{
"code": null,
"e": 26845,
"s": 26613,
"text": "search_movie method returns list and each element of list work as a dictionary similarly get_movie method return a movie object which work as dictionary i.e. they can be queried by giving the key of the data, here key will be year."
},
{
"code": null,
"e": 26868,
"s": 26845,
"text": "Syntax : movie[‘year’]"
},
{
"code": null,
"e": 26904,
"s": 26868,
"text": "Here movie is the imdb Movie object"
},
{
"code": null,
"e": 26958,
"s": 26904,
"text": "Return : It returns integer which is the release year"
},
{
"code": null,
"e": 26986,
"s": 26958,
"text": "Below is the implementation"
},
{
"code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting the movie with idsearch = ia.get_movie(\"0111161\") # getting movie yearyear = search['year'] # printing movie name and yearprint(search['title'] + \" : \" + str(year))",
"e": 27245,
"s": 26986,
"text": null
},
{
"code": null,
"e": 27254,
"s": 27245,
"text": "Output :"
},
{
"code": null,
"e": 27286,
"s": 27254,
"text": "The Shawshank Redemption : 1994"
},
{
"code": null,
"e": 27302,
"s": 27286,
"text": "Another example"
},
{
"code": "# importing the moduleimport imdb # creating instance of IMDbia = imdb.IMDb() # getting the movie with namesearch = ia.search_movie(\"3 Idiots\") # getting movie yearyear = search[0]['year'] # printing movie name and yearprint(search[0]['title'] + \" : \" + str(year))",
"e": 27573,
"s": 27302,
"text": null
},
{
"code": null,
"e": 27582,
"s": 27573,
"text": "Output :"
},
{
"code": null,
"e": 27598,
"s": 27582,
"text": "3 Idiots : 2009"
},
{
"code": null,
"e": 27619,
"s": 27598,
"text": "Python IMDbPY-module"
},
{
"code": null,
"e": 27626,
"s": 27619,
"text": "Python"
},
{
"code": null,
"e": 27724,
"s": 27626,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27742,
"s": 27724,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27774,
"s": 27742,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27796,
"s": 27774,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27838,
"s": 27796,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27868,
"s": 27838,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27894,
"s": 27868,
"text": "Python String | replace()"
},
{
"code": null,
"e": 27938,
"s": 27894,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 27967,
"s": 27938,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 28004,
"s": 27967,
"text": "Create a Pandas DataFrame from Lists"
}
] |
MomentJS - Examples | Till now, we have learnt many concepts in MomentJS. This chapter gives you further examples for a better understanding.
This is an example which displays the dates between two given dates.
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript" src="MomentJS.js"></script>
<style>
table, td {
border: 1px solid #F1E8E8;
border-collapse: collapse;
padding: 4px;
}
table tr:nth-child(odd) {
background-color: #CFCACA;
}
table tr:nth-child(even) {
background-color: #C4B4B4;
}
</style>
</head>
<body>
<h1>Dates display between 2014-05-01 and 2014-05-16</h1>
<div id="container">
<table id="datedetails" ></table>
</div>
<script type="text/JavaScript">
function getDaterange(start, end, arr) {
if (!moment(start).isSameOrAfter(end)) {
if (arr.length==0) arr.push(moment(start).format("dddd, MMMM Do YYYY, h:mm:ss a"));
var next = moment(start).add(1, 'd');
arr.push(next.format("dddd, MMMM Do YYYY, h:mm:ss a"));
getDaterange(next, end, arr);
} else {
return arr;
}
return arr;
}
var a = getDaterange("2014-05-01", "2014-05-16", []);
var tr = "";
for (var i = 0; i<a.length;i++ ) {
tr += "<tr><td>"+a[i]+"</td></tr>";
}
document.getElementById("datedetails").innerHTML = tr;
</script>
</body>
</html>
We want to display all the dates between 2014-05-01 to 2014-05-16. We have used date query isSameOrAfter, date addition and date format to achieve what we want.
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript" src="MomentJS.js"></script>
<style>
table, td {
border: 1px solid #F1E8E8;
border-collapse: collapse;
padding: 4px;
}
table tr:nth-child(odd) {
background-color: #CFCACA;
}
table tr:nth-child(even) {
background-color: #C4B4B4;
}
</style>
</head>
<body>
<h1>Sundays between 2014-05-01 and 2014-08-16</h1>
<div id="container">
<table id="datedetails"></table>
</div>
<script type="text/JavaScript">
function getDaterange(start, end, arr) {
if (!moment(start).isSameOrAfter(end)) {
if (arr.length==0) {
if (moment(start).format("dddd") === "Sunday") {
arr.push(moment(start).format("dddd, MMMM Do YYYY, h:mm:ss a"));
}
}
var next = moment(start).add(1, 'd');
if (moment(next).format("dddd") === "Sunday") {
arr.push(next.format("dddd, MMMM Do YYYY, h:mm:ss a"));
}
getDaterange(next, end, arr);
} else {
return arr;
}
return arr;
}
var a = getDaterange("2014-05-01", "2014-08-16", []);
var tr = "";
for (var i = 0; i<a.length;i++ ) {
tr += "<tr><td>"+a[i]+"</td></tr>";
}
document.getElementById("datedetails").innerHTML = tr;
</script>
</body>
</html>
Here we are using moment.locale script which has all the locales.
<!DOCTYPE html>
<html>
<head>
<script type="text/JavaScript" src="MomentJS.js"></script>
<script type="text/JavaScript" src="momentlocale.js" charset="UTF-8"></script>
<style type="text/css">
div {
margin-top: 16px!important;
margin-bottom: 16px!important;
width:100%;
}
table, td {
border: 1px solid #F1E8E8;
border-collapse: collapse;
padding: 4px;
}
table tr:nth-child(odd) {
background-color: #CFCACA;
}
table tr:nth-child(even) {
background-color: #C4B4B4;
}
</style>
</head>
<body>
<div >
Select Locale : <select id="locale" onchange="updatelocale()" style="width:200px;">
<option value="en">English</option>
<option value="fr">French</option>
<option value="fr-ca">French Canada</option>
<option value="cs">Czech</option>
<option value="zh-cn">Chinese</option>
<option value="nl">Dutch< /option>
<option value="ka">Georgian</option>
<option value="he">Hebrew</option>
<option value="hi">Hindi</option>
<option value="id">Indonesian</option>
<option value="it">Italian</option>
<option value="jv";Japanese</option>
<option value="ko";Korean</option>
</select>
</div>
<br/>
<br/>>
Display Date is different formats as per locale :<span id="localeid"></span><br/>
<div>
<table>
<tr>
<th>Format</th>
<th>Display</th>
</tr>
<tr>
<td><i>dddd, MMMM Do YYYY, h:mm:ss a</i></td>
<td>
<div id="ldate"></div>
</td>
</tr>
<tr>
<td><i>LLLL</i></td>
<td>
<div id="ldate1"></div>
</td>
</tr>
<tr>
<td><i>moment().format()</i></td>
<td>
<div id="ldate2"></div>
</td>
</tr>
<tr>
<td><i>moment().calendar()</i></td>
<td>
<div id="ldate3"></div>
</td>
</tr>
<tr>
<td><i>Months</i></td>
<td>
<div id="ldate4"></div>
</td>
</tr>
<tr>
<td><i>Weekdays</i></td>
<td>
<div id="ldate5"></div>
</td>
</tr>
</table>
</div>
<script type="text/JavaScript">
var updatelocale = function() {
var a = moment.locale(document.getElementById("locale").value);
var k = moment().format("dddd, MMMM Do YYYY, h:mm:ss a");
var k1 = moment().format("LLLL");
var k2 = moment().format();
var k3 = moment().calendar();
var k4 = moment.months();
var k5 = moment.weekdays();
document.getElementById("localeid").innerHTML = "<b>"+a+"</b>";
document.getElementById("ldate").innerHTML = k;
document.getElementById("ldate1").innerHTML = k1;
document.getElementById("ldate2").innerHTML = k2;
document.getElementById("ldate3").innerHTML = k3;
document.getElementById("ldate4").innerHTML = k4;
document.getElementById("ldate5").innerHTML = k5;
};
updatelocale();
</script>
</body>
</html>
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2080,
"s": 1960,
"text": "Till now, we have learnt many concepts in MomentJS. This chapter gives you further examples for a better understanding."
},
{
"code": null,
"e": 2149,
"s": 2080,
"text": "This is an example which displays the dates between two given dates."
},
{
"code": null,
"e": 3547,
"s": 2149,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script type=\"text/JavaScript\" src=\"MomentJS.js\"></script>\n <style>\n table, td {\n border: 1px solid #F1E8E8;\n border-collapse: collapse;\n padding: 4px;\n }\n table tr:nth-child(odd) {\n background-color: #CFCACA;\n }\n table tr:nth-child(even) {\n background-color: #C4B4B4;\n }\n </style>\n </head>\n \n <body>\n <h1>Dates display between 2014-05-01 and 2014-05-16</h1>\n <div id=\"container\">\n <table id=\"datedetails\" ></table>\n </div>\n <script type=\"text/JavaScript\">\n function getDaterange(start, end, arr) {\n if (!moment(start).isSameOrAfter(end)) {\n if (arr.length==0) arr.push(moment(start).format(\"dddd, MMMM Do YYYY, h:mm:ss a\"));\n var next = moment(start).add(1, 'd');\n arr.push(next.format(\"dddd, MMMM Do YYYY, h:mm:ss a\"));\n getDaterange(next, end, arr);\n } else {\n return arr;\n }\n return arr;\n }\n var a = getDaterange(\"2014-05-01\", \"2014-05-16\", []);\n var tr = \"\";\n for (var i = 0; i<a.length;i++ ) {\n tr += \"<tr><td>\"+a[i]+\"</td></tr>\";\n }\n document.getElementById(\"datedetails\").innerHTML = tr;\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 3708,
"s": 3547,
"text": "We want to display all the dates between 2014-05-01 to 2014-05-16. We have used date query isSameOrAfter, date addition and date format to achieve what we want."
},
{
"code": null,
"e": 5309,
"s": 3708,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script type=\"text/JavaScript\" src=\"MomentJS.js\"></script>\n <style>\n table, td {\n border: 1px solid #F1E8E8;\n border-collapse: collapse;\n padding: 4px;\n }\n table tr:nth-child(odd) {\n background-color: #CFCACA;\n }\n table tr:nth-child(even) {\n background-color: #C4B4B4;\n }\n </style>\n </head>\n \n <body>\n <h1>Sundays between 2014-05-01 and 2014-08-16</h1>\n <div id=\"container\">\n <table id=\"datedetails\"></table>\n </div>\n <script type=\"text/JavaScript\">\n function getDaterange(start, end, arr) {\n if (!moment(start).isSameOrAfter(end)) {\n if (arr.length==0) {\n if (moment(start).format(\"dddd\") === \"Sunday\") {\n arr.push(moment(start).format(\"dddd, MMMM Do YYYY, h:mm:ss a\"));\n }\n }\n var next = moment(start).add(1, 'd');\n if (moment(next).format(\"dddd\") === \"Sunday\") {\n arr.push(next.format(\"dddd, MMMM Do YYYY, h:mm:ss a\"));\n }\n getDaterange(next, end, arr);\n } else {\n return arr;\n }\n return arr;\n }\n var a = getDaterange(\"2014-05-01\", \"2014-08-16\", []);\n var tr = \"\";\n for (var i = 0; i<a.length;i++ ) {\n tr += \"<tr><td>\"+a[i]+\"</td></tr>\";\n }\n document.getElementById(\"datedetails\").innerHTML = tr;\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 5375,
"s": 5309,
"text": "Here we are using moment.locale script which has all the locales."
},
{
"code": null,
"e": 9043,
"s": 5375,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <script type=\"text/JavaScript\" src=\"MomentJS.js\"></script>\n <script type=\"text/JavaScript\" src=\"momentlocale.js\" charset=\"UTF-8\"></script>\n <style type=\"text/css\">\n div {\n margin-top: 16px!important;\n margin-bottom: 16px!important;\n width:100%;\n }\n table, td {\n border: 1px solid #F1E8E8;\n border-collapse: collapse;\n padding: 4px;\n }\n table tr:nth-child(odd) {\n background-color: #CFCACA;\n }\n table tr:nth-child(even) {\n background-color: #C4B4B4;\n }\n </style>\n </head>\n \n <body>\n <div >\n Select Locale : <select id=\"locale\" onchange=\"updatelocale()\" style=\"width:200px;\">\n <option value=\"en\">English</option>\n <option value=\"fr\">French</option>\n <option value=\"fr-ca\">French Canada</option>\n <option value=\"cs\">Czech</option>\n <option value=\"zh-cn\">Chinese</option>\n <option value=\"nl\">Dutch< /option>\n <option value=\"ka\">Georgian</option>\n <option value=\"he\">Hebrew</option>\n <option value=\"hi\">Hindi</option>\n <option value=\"id\">Indonesian</option>\n <option value=\"it\">Italian</option>\n <option value=\"jv\";Japanese</option>\n <option value=\"ko\";Korean</option>\n </select>\n </div>\n <br/>\n <br/>>\n Display Date is different formats as per locale :<span id=\"localeid\"></span><br/>\n <div>\n <table>\n <tr>\n <th>Format</th>\n <th>Display</th>\n </tr>\n <tr>\n <td><i>dddd, MMMM Do YYYY, h:mm:ss a</i></td>\n <td>\n <div id=\"ldate\"></div>\n </td>\n </tr>\n <tr>\n <td><i>LLLL</i></td>\n <td>\n <div id=\"ldate1\"></div>\n </td>\n </tr>\n <tr>\n <td><i>moment().format()</i></td>\n <td>\n <div id=\"ldate2\"></div>\n </td>\n </tr>\n <tr>\n <td><i>moment().calendar()</i></td>\n <td>\n <div id=\"ldate3\"></div>\n </td>\n </tr>\n <tr>\n <td><i>Months</i></td>\n <td>\n <div id=\"ldate4\"></div>\n </td>\n </tr>\n <tr>\n <td><i>Weekdays</i></td>\n <td>\n <div id=\"ldate5\"></div>\n </td>\n </tr>\n </table>\n </div>\n <script type=\"text/JavaScript\">\n var updatelocale = function() {\n var a = moment.locale(document.getElementById(\"locale\").value);\n var k = moment().format(\"dddd, MMMM Do YYYY, h:mm:ss a\");\n var k1 = moment().format(\"LLLL\");\n var k2 = moment().format();\n var k3 = moment().calendar();\n var k4 = moment.months();\n var k5 = moment.weekdays();\n document.getElementById(\"localeid\").innerHTML = \"<b>\"+a+\"</b>\";\n document.getElementById(\"ldate\").innerHTML = k;\n document.getElementById(\"ldate1\").innerHTML = k1;\n document.getElementById(\"ldate2\").innerHTML = k2;\n document.getElementById(\"ldate3\").innerHTML = k3;\n document.getElementById(\"ldate4\").innerHTML = k4;\n document.getElementById(\"ldate5\").innerHTML = k5;\n };\n updatelocale();\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 9050,
"s": 9043,
"text": " Print"
},
{
"code": null,
"e": 9061,
"s": 9050,
"text": " Add Notes"
}
] |
Classifying Loans based on the risk of defaulting | by Vidhur Kumar | Towards Data Science | Classification is one of the classical problems in Supervised Learning where we attempt to train a model to classify data points into *n* distinct classes. As I was browsing through datasets online, I came across one that contained information on 1000 loan applicants (from both urban and rural areas). One of the columns in the data table was whether or not the loan was approved. An idea immediately struck me:
What if we could build a model to predict whether an applicant’s loan would be approved or denied depending on his or her risk of defaulting?
This would be a garden-variety classification problem, where we have 2 distinct classes to group our data by: a loan approval or a loan denial.
It is important to not be hasty and start training models on the raw and unexplored data. Preprocessing the data not only helps us smooth out inconsistencies (missing values and outliers), but also gives us a comprehensive understanding of the data which in turn aids us in our model selection process.
This end-to-end Machine Learning project is primarily based on Python. I have used the following libraries to help me achieve the objective:
1. Numpy for mathematical operations.
2. Pandas for data exploration and analysis
3. Matplotlib and Seaborn for data visualization
4. Scikit-learn for model training, cross-validation, and evaluation metrics.
Let us perform all the necessary imports beforehand.
import numpy as npnp.seterr(divide='ignore')import mathimport pandas as pdfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OneHotEncoderfrom sklearn import metricsimport matplotlib.pyplot as pltimport seaborn as sns
Once we have all the libraries necessary, we can read the data in from CSV file using Pandas.
data = pd.read_csv('credit_risk.csv')
Before moving forward with the data exploration, I always like to understand the features that I will be dealing with on a superficial level. Doing this will help us put into words any mathematical interpretations we make. The following are the list of features that we have from our dataset:
Loan ID: The ID given by the bank to the loan request.Gender: The gender of the primary applicant.Married: Binary variable indicating the marital status of the primary applicant.Dependents: Number of dependents of the primary applicant.Education: Binary variable indicating whether or not the primary applicant has graduated high school.Self_Employed: Binary variable indicating whether or not the individual is self-employed.Applicant Income: The income of the primary applicant.Co-Applicant Income: The income of the co-applicant.Loan Amount: The amount the applicant wants to borrow.Loan Amount Term: The term over which the applicant would repay the loan.Credit History: Binary variable representing whether the client had a good history or a bad history.Property Area: Categorical variable indicating whether the applicant was from an urban, semiurban, or a rural area.Loan Status: Variable indicating whether the loan was approved or denied. This will be our output (dependent) variable.
Loan ID: The ID given by the bank to the loan request.
Gender: The gender of the primary applicant.
Married: Binary variable indicating the marital status of the primary applicant.
Dependents: Number of dependents of the primary applicant.
Education: Binary variable indicating whether or not the primary applicant has graduated high school.
Self_Employed: Binary variable indicating whether or not the individual is self-employed.
Applicant Income: The income of the primary applicant.
Co-Applicant Income: The income of the co-applicant.
Loan Amount: The amount the applicant wants to borrow.
Loan Amount Term: The term over which the applicant would repay the loan.
Credit History: Binary variable representing whether the client had a good history or a bad history.
Property Area: Categorical variable indicating whether the applicant was from an urban, semiurban, or a rural area.
Loan Status: Variable indicating whether the loan was approved or denied. This will be our output (dependent) variable.
Of all these variables, I have chosen the Gender, Applicant Income, Loan Amount, and Property Area as the ones to delve deeper into. It is important to look at the data from multiple angles, i.e., independently and in relation to the other variables. This points out any red flags in the distributions of the variables and also reveals interesting relationships amongst them.
Humans are visual creatures, and a majority of us process information better when we see it. Thus, when it comes to understanding our data, taking a visual approach is far more effective than manually crunching hundreds of rows worth of numbers. I have plotted visualizations that show the distributions of important features as well as interesting relationships between some of the features. How did I decide which features are important? I used the correlation matrix, where the value at (i, j) represents how strongly feature i is correlated to feature j.
We can use seaborn’s heatmap visualization to help us understand the correlation matrix.
sns.heatmap(data.corr())
Before we begin exploring our feature variables, I wanted to have a look at our dependent variable, i.e., the one we are attempting to predict using the model. Shown below is a simple countplot by class.
There is a clear imbalance between the classes, and that can be very dangerous! Our model may end up highly biased towards the majority class, which is not ideal when it comes to the model’s generalization capabilities. For that reason, we will perform feature scaling to ensure uniformity, and also make sure that the algorithm we use to build the model is ‘aware’ that the classes are imbalanced.
I was also curious about how the property area and the loan amount jointly affected the authorization of the loan. Let us have a look at a relational plot of the loan amount against approval separated by the property area.
It will help if we divide the data into approved and unapproved loans and look at the count of how many of those loan applications came from each property area.
From the looks of it, it looks like a higher fraction of the rural loan applications are denied. I calculated the ratio of approved loans from each property area, and the numbers corroborate our hypothesis.
Urban Approval Ratio: 0.7368421052631579Semiurban Approval Ratio: 0.7822349570200573Rural Approval Ratio: 0.6448275862068965
Urban Approval Ratio: 0.7368421052631579
Semiurban Approval Ratio: 0.7822349570200573
Rural Approval Ratio: 0.6448275862068965
Now that we’ve explored the data visually to better understand what we’re dealing with, its time to preprocess our data in order to make sure that the model we train is not subject to any noisy training instances (in the context of ML, the term “training instance” refers to a single data point that is part of the dataset used to train and test the model.) I have divided our preprocessing step into the following substeps:
Check for and replace missing values if necessary.Remove unncessary features.Encode categorical features to make sure they are properly interpreted.
Check for and replace missing values if necessary.
Remove unncessary features.
Encode categorical features to make sure they are properly interpreted.
# Replace the categorical values with the numeric equivalents that we have abovecategoricalFeatures = ['Property_Area', 'Gender', 'Married', 'Dependents', 'Education', 'Self_Employed']# Iterate through the list of categorical features and one hot encode them.for feature in categoricalFeatures: onehot = pd.get_dummies(data[feature], prefix=feature) data = data.drop(feature, axis=1) data = data.join(onehot)
Note that data preprocessing is by no means formulaic, and the steps that I am about to take are subjective.
Finally, the exciting bit! We have our data prepared, and we shall serve it to our model to devour! The algorithm that I chose for this particular case was Logistic Regression. It is one of the simpler supervised learning algorithms but has proven to be extremely reliant in a variety of instances.
Before we train the model, we shall utilize Scikit-learn’s inbuilt train-test split module to randomly split our dataset into training and testing subsets. We shall split it according to the 80–20 rule (this seems an arbitrary and scientifically ungrounded choice, but it is known to “just work” when it comes to training models).
Let us begin by instantiating a Logistic Regression object (we will be using scikit-learn’s module) and split the dataset in the aforementioned way.
# Liblinear is a solver that is effective for relatively smaller datasets.lr = LogisticRegression(solver='liblinear', class_weight='balanced')
Notice that we specify that the weights of the classes in question have to be balanced. This ensures that the classes are appropriately weighted, thereby eliminating any bias created by an imbalance in the classes. If you are curious as to how the classes are weighted, this article by Chris Albon provides a comprehensive explanation.
Before we pass in the data, let us perform feature scaling using Scikit-learn’s Standard Scaler.
scaler = StandardScaler()data_std = scaler.fit_transform(data)# We will follow an 80-20 split pattern for our training and test dataX_train,X_test,y_train,y_test = train_test_split(data, y, test_size=0.2, random_state = 0)
Now that we have everything we need, we fit the model to the training data.
lr.fit(X_train, y_train)
It is just as (if not more) important to evaluate the performance of algorithms as it is understanding and implementing them. I’ve provided a brief but comprehensive introduction to the confusion matrix and the three fundamental evaluation metrics for classification.
A Confusion matrix is simply a tabular visualization of the error rates of the matrix that is widely used to evaluate the performance of a classification algorithm. The rows of the matrix represent the actual label of the instance, while the columns reprsent the predicted label. In our case, we have a 2x2 matrix as we are performing binary classification. To generalize, an “n-ary” classification problem will have an nxn confusion matrix.
The (m, n) entry of the confusion matrix tells us how many instances whose correct label is class m was classified into class n. So, the diagonal entries of our matrix represent correct classifications and the rest represent the incorrect ones. In binary classification, the diagonal entries are commonly referred to as the true positives and the true negatives, and the other two are the false positives and false negatives.
Now that the model has been trained, we will use the test data that we sieved from the original dataset to evaluate how well our model generalizes to the data. I have divided the evaluation process in the following way:
Vectorize the predictions made by the model and build a confusion matrix.Use the confusion matrix
Vectorize the predictions made by the model and build a confusion matrix.
Use the confusion matrix
# We will compare this vector of predictions to the actual target vector to determine the model performance.y_pred = lr.predict(X_test)# Build the confusion matrix.confusion_matrix = metrics.confusion_matrix(y_test, y_pred)class_names=[0,1] # name of classesfig, ax = plt.subplots()tick_marks = np.arange(len(class_names))plt.xticks(tick_marks, class_names)plt.yticks(tick_marks, class_names)# The heatmap requires that we pass in a dataframe as the argumentsns.heatmap(pd.DataFrame(confusion_matrix), annot=True, cmap="YlGnBu", fmt="g")# Configure the heatmap parametersax.xaxis.set_label_position("top")plt.tight_layout()plt.title('Confusion matrix', y=1.1)plt.ylabel('Actual label')plt.xlabel('Predicted label')
At a glance, most of our classifications seem to be concentrated in the diagonal entries. An excellent start! Recall that we said the matrix gave us the error rates. But it's hard to gain a concrete numerical measure of the model’s performance from the matrix alone. Thus, we use the values from the matrix to compute the three fundamental classification performance measures: accuracy, precision, and recall.
Scikit-learn’s inbuilt metrics module lets us compute these metrics in a single line of code!
# Print out our performance metricsprint("Accuracy:",metrics.accuracy_score(y_test, y_pred))print("Precision:",metrics.precision_score(y_test, y_pred, pos_label='Y'))print("Recall:",metrics.recall_score(y_test, y_pred, pos_label='Y'))
For our model, the metrics’ values turned out to be:
Accuracy: 0.8116883116883117Precision: 0.875Recall: 0.8504672897196262
Accuracy: 0.8116883116883117
Precision: 0.875
Recall: 0.8504672897196262
It is an accepted practice to use precision and recall in conjunction to gauge the performance of a classification model as one could simply use instances that he or she knows would result in a correct prediction to gain a perfect precision score. In other words, if I have one training instance that I knew belonged to the positive class I would make sure that the model classifies only that instance into the positive class. The F1 score is a metric that is a harmonic sum of the precision and recall. It is a singular measure of a model’s performance and takes into account both the precision and recall, thus making sure that we do not have to go through the hassle of interpreting the numbers manually. Yet again, Scikitl-learn’s metrics module comes to the rescue!
print("F1 Score:",metrics.f1_score(y_test, y_pred, pos_label='Y'))
F1 Score: 0.8625592417061612
Alright, awesome! We sucessfully trained a model that can predict the response to a loan applicant based on the data we have on them. To do this at scale would be futile for us humans, but the performance of the classifier shows us just how powerful these techniques can be. Classification is but one of the multitude of techniques available as part of the Predictive Modeling toolbox. I hope that this has proven to be an informative and engaging introduction to the topic.
Happy coding!
Credit Risk Dataset: https://docs.google.com/spreadsheets/d/1em8nMTOH5_GpHVI_EowBkUjDViDTNc5YKbFUihjwk-g/edit?usp=sharing | [
{
"code": null,
"e": 585,
"s": 172,
"text": "Classification is one of the classical problems in Supervised Learning where we attempt to train a model to classify data points into *n* distinct classes. As I was browsing through datasets online, I came across one that contained information on 1000 loan applicants (from both urban and rural areas). One of the columns in the data table was whether or not the loan was approved. An idea immediately struck me:"
},
{
"code": null,
"e": 727,
"s": 585,
"text": "What if we could build a model to predict whether an applicant’s loan would be approved or denied depending on his or her risk of defaulting?"
},
{
"code": null,
"e": 871,
"s": 727,
"text": "This would be a garden-variety classification problem, where we have 2 distinct classes to group our data by: a loan approval or a loan denial."
},
{
"code": null,
"e": 1174,
"s": 871,
"text": "It is important to not be hasty and start training models on the raw and unexplored data. Preprocessing the data not only helps us smooth out inconsistencies (missing values and outliers), but also gives us a comprehensive understanding of the data which in turn aids us in our model selection process."
},
{
"code": null,
"e": 1315,
"s": 1174,
"text": "This end-to-end Machine Learning project is primarily based on Python. I have used the following libraries to help me achieve the objective:"
},
{
"code": null,
"e": 1353,
"s": 1315,
"text": "1. Numpy for mathematical operations."
},
{
"code": null,
"e": 1397,
"s": 1353,
"text": "2. Pandas for data exploration and analysis"
},
{
"code": null,
"e": 1446,
"s": 1397,
"text": "3. Matplotlib and Seaborn for data visualization"
},
{
"code": null,
"e": 1524,
"s": 1446,
"text": "4. Scikit-learn for model training, cross-validation, and evaluation metrics."
},
{
"code": null,
"e": 1577,
"s": 1524,
"text": "Let us perform all the necessary imports beforehand."
},
{
"code": null,
"e": 1881,
"s": 1577,
"text": "import numpy as npnp.seterr(divide='ignore')import mathimport pandas as pdfrom sklearn.linear_model import LogisticRegressionfrom sklearn.model_selection import train_test_splitfrom sklearn.preprocessing import OneHotEncoderfrom sklearn import metricsimport matplotlib.pyplot as pltimport seaborn as sns"
},
{
"code": null,
"e": 1975,
"s": 1881,
"text": "Once we have all the libraries necessary, we can read the data in from CSV file using Pandas."
},
{
"code": null,
"e": 2013,
"s": 1975,
"text": "data = pd.read_csv('credit_risk.csv')"
},
{
"code": null,
"e": 2306,
"s": 2013,
"text": "Before moving forward with the data exploration, I always like to understand the features that I will be dealing with on a superficial level. Doing this will help us put into words any mathematical interpretations we make. The following are the list of features that we have from our dataset:"
},
{
"code": null,
"e": 3300,
"s": 2306,
"text": "Loan ID: The ID given by the bank to the loan request.Gender: The gender of the primary applicant.Married: Binary variable indicating the marital status of the primary applicant.Dependents: Number of dependents of the primary applicant.Education: Binary variable indicating whether or not the primary applicant has graduated high school.Self_Employed: Binary variable indicating whether or not the individual is self-employed.Applicant Income: The income of the primary applicant.Co-Applicant Income: The income of the co-applicant.Loan Amount: The amount the applicant wants to borrow.Loan Amount Term: The term over which the applicant would repay the loan.Credit History: Binary variable representing whether the client had a good history or a bad history.Property Area: Categorical variable indicating whether the applicant was from an urban, semiurban, or a rural area.Loan Status: Variable indicating whether the loan was approved or denied. This will be our output (dependent) variable."
},
{
"code": null,
"e": 3355,
"s": 3300,
"text": "Loan ID: The ID given by the bank to the loan request."
},
{
"code": null,
"e": 3400,
"s": 3355,
"text": "Gender: The gender of the primary applicant."
},
{
"code": null,
"e": 3481,
"s": 3400,
"text": "Married: Binary variable indicating the marital status of the primary applicant."
},
{
"code": null,
"e": 3540,
"s": 3481,
"text": "Dependents: Number of dependents of the primary applicant."
},
{
"code": null,
"e": 3642,
"s": 3540,
"text": "Education: Binary variable indicating whether or not the primary applicant has graduated high school."
},
{
"code": null,
"e": 3732,
"s": 3642,
"text": "Self_Employed: Binary variable indicating whether or not the individual is self-employed."
},
{
"code": null,
"e": 3787,
"s": 3732,
"text": "Applicant Income: The income of the primary applicant."
},
{
"code": null,
"e": 3840,
"s": 3787,
"text": "Co-Applicant Income: The income of the co-applicant."
},
{
"code": null,
"e": 3895,
"s": 3840,
"text": "Loan Amount: The amount the applicant wants to borrow."
},
{
"code": null,
"e": 3969,
"s": 3895,
"text": "Loan Amount Term: The term over which the applicant would repay the loan."
},
{
"code": null,
"e": 4070,
"s": 3969,
"text": "Credit History: Binary variable representing whether the client had a good history or a bad history."
},
{
"code": null,
"e": 4186,
"s": 4070,
"text": "Property Area: Categorical variable indicating whether the applicant was from an urban, semiurban, or a rural area."
},
{
"code": null,
"e": 4306,
"s": 4186,
"text": "Loan Status: Variable indicating whether the loan was approved or denied. This will be our output (dependent) variable."
},
{
"code": null,
"e": 4682,
"s": 4306,
"text": "Of all these variables, I have chosen the Gender, Applicant Income, Loan Amount, and Property Area as the ones to delve deeper into. It is important to look at the data from multiple angles, i.e., independently and in relation to the other variables. This points out any red flags in the distributions of the variables and also reveals interesting relationships amongst them."
},
{
"code": null,
"e": 5241,
"s": 4682,
"text": "Humans are visual creatures, and a majority of us process information better when we see it. Thus, when it comes to understanding our data, taking a visual approach is far more effective than manually crunching hundreds of rows worth of numbers. I have plotted visualizations that show the distributions of important features as well as interesting relationships between some of the features. How did I decide which features are important? I used the correlation matrix, where the value at (i, j) represents how strongly feature i is correlated to feature j."
},
{
"code": null,
"e": 5330,
"s": 5241,
"text": "We can use seaborn’s heatmap visualization to help us understand the correlation matrix."
},
{
"code": null,
"e": 5355,
"s": 5330,
"text": "sns.heatmap(data.corr())"
},
{
"code": null,
"e": 5559,
"s": 5355,
"text": "Before we begin exploring our feature variables, I wanted to have a look at our dependent variable, i.e., the one we are attempting to predict using the model. Shown below is a simple countplot by class."
},
{
"code": null,
"e": 5958,
"s": 5559,
"text": "There is a clear imbalance between the classes, and that can be very dangerous! Our model may end up highly biased towards the majority class, which is not ideal when it comes to the model’s generalization capabilities. For that reason, we will perform feature scaling to ensure uniformity, and also make sure that the algorithm we use to build the model is ‘aware’ that the classes are imbalanced."
},
{
"code": null,
"e": 6181,
"s": 5958,
"text": "I was also curious about how the property area and the loan amount jointly affected the authorization of the loan. Let us have a look at a relational plot of the loan amount against approval separated by the property area."
},
{
"code": null,
"e": 6342,
"s": 6181,
"text": "It will help if we divide the data into approved and unapproved loans and look at the count of how many of those loan applications came from each property area."
},
{
"code": null,
"e": 6549,
"s": 6342,
"text": "From the looks of it, it looks like a higher fraction of the rural loan applications are denied. I calculated the ratio of approved loans from each property area, and the numbers corroborate our hypothesis."
},
{
"code": null,
"e": 6674,
"s": 6549,
"text": "Urban Approval Ratio: 0.7368421052631579Semiurban Approval Ratio: 0.7822349570200573Rural Approval Ratio: 0.6448275862068965"
},
{
"code": null,
"e": 6715,
"s": 6674,
"text": "Urban Approval Ratio: 0.7368421052631579"
},
{
"code": null,
"e": 6760,
"s": 6715,
"text": "Semiurban Approval Ratio: 0.7822349570200573"
},
{
"code": null,
"e": 6801,
"s": 6760,
"text": "Rural Approval Ratio: 0.6448275862068965"
},
{
"code": null,
"e": 7226,
"s": 6801,
"text": "Now that we’ve explored the data visually to better understand what we’re dealing with, its time to preprocess our data in order to make sure that the model we train is not subject to any noisy training instances (in the context of ML, the term “training instance” refers to a single data point that is part of the dataset used to train and test the model.) I have divided our preprocessing step into the following substeps:"
},
{
"code": null,
"e": 7375,
"s": 7226,
"text": "Check for and replace missing values if necessary.Remove unncessary features.Encode categorical features to make sure they are properly interpreted."
},
{
"code": null,
"e": 7426,
"s": 7375,
"text": "Check for and replace missing values if necessary."
},
{
"code": null,
"e": 7454,
"s": 7426,
"text": "Remove unncessary features."
},
{
"code": null,
"e": 7526,
"s": 7454,
"text": "Encode categorical features to make sure they are properly interpreted."
},
{
"code": null,
"e": 7944,
"s": 7526,
"text": "# Replace the categorical values with the numeric equivalents that we have abovecategoricalFeatures = ['Property_Area', 'Gender', 'Married', 'Dependents', 'Education', 'Self_Employed']# Iterate through the list of categorical features and one hot encode them.for feature in categoricalFeatures: onehot = pd.get_dummies(data[feature], prefix=feature) data = data.drop(feature, axis=1) data = data.join(onehot)"
},
{
"code": null,
"e": 8053,
"s": 7944,
"text": "Note that data preprocessing is by no means formulaic, and the steps that I am about to take are subjective."
},
{
"code": null,
"e": 8352,
"s": 8053,
"text": "Finally, the exciting bit! We have our data prepared, and we shall serve it to our model to devour! The algorithm that I chose for this particular case was Logistic Regression. It is one of the simpler supervised learning algorithms but has proven to be extremely reliant in a variety of instances."
},
{
"code": null,
"e": 8683,
"s": 8352,
"text": "Before we train the model, we shall utilize Scikit-learn’s inbuilt train-test split module to randomly split our dataset into training and testing subsets. We shall split it according to the 80–20 rule (this seems an arbitrary and scientifically ungrounded choice, but it is known to “just work” when it comes to training models)."
},
{
"code": null,
"e": 8832,
"s": 8683,
"text": "Let us begin by instantiating a Logistic Regression object (we will be using scikit-learn’s module) and split the dataset in the aforementioned way."
},
{
"code": null,
"e": 8975,
"s": 8832,
"text": "# Liblinear is a solver that is effective for relatively smaller datasets.lr = LogisticRegression(solver='liblinear', class_weight='balanced')"
},
{
"code": null,
"e": 9311,
"s": 8975,
"text": "Notice that we specify that the weights of the classes in question have to be balanced. This ensures that the classes are appropriately weighted, thereby eliminating any bias created by an imbalance in the classes. If you are curious as to how the classes are weighted, this article by Chris Albon provides a comprehensive explanation."
},
{
"code": null,
"e": 9408,
"s": 9311,
"text": "Before we pass in the data, let us perform feature scaling using Scikit-learn’s Standard Scaler."
},
{
"code": null,
"e": 9631,
"s": 9408,
"text": "scaler = StandardScaler()data_std = scaler.fit_transform(data)# We will follow an 80-20 split pattern for our training and test dataX_train,X_test,y_train,y_test = train_test_split(data, y, test_size=0.2, random_state = 0)"
},
{
"code": null,
"e": 9707,
"s": 9631,
"text": "Now that we have everything we need, we fit the model to the training data."
},
{
"code": null,
"e": 9732,
"s": 9707,
"text": "lr.fit(X_train, y_train)"
},
{
"code": null,
"e": 10000,
"s": 9732,
"text": "It is just as (if not more) important to evaluate the performance of algorithms as it is understanding and implementing them. I’ve provided a brief but comprehensive introduction to the confusion matrix and the three fundamental evaluation metrics for classification."
},
{
"code": null,
"e": 10442,
"s": 10000,
"text": "A Confusion matrix is simply a tabular visualization of the error rates of the matrix that is widely used to evaluate the performance of a classification algorithm. The rows of the matrix represent the actual label of the instance, while the columns reprsent the predicted label. In our case, we have a 2x2 matrix as we are performing binary classification. To generalize, an “n-ary” classification problem will have an nxn confusion matrix."
},
{
"code": null,
"e": 10868,
"s": 10442,
"text": "The (m, n) entry of the confusion matrix tells us how many instances whose correct label is class m was classified into class n. So, the diagonal entries of our matrix represent correct classifications and the rest represent the incorrect ones. In binary classification, the diagonal entries are commonly referred to as the true positives and the true negatives, and the other two are the false positives and false negatives."
},
{
"code": null,
"e": 11088,
"s": 10868,
"text": "Now that the model has been trained, we will use the test data that we sieved from the original dataset to evaluate how well our model generalizes to the data. I have divided the evaluation process in the following way:"
},
{
"code": null,
"e": 11186,
"s": 11088,
"text": "Vectorize the predictions made by the model and build a confusion matrix.Use the confusion matrix"
},
{
"code": null,
"e": 11260,
"s": 11186,
"text": "Vectorize the predictions made by the model and build a confusion matrix."
},
{
"code": null,
"e": 11285,
"s": 11260,
"text": "Use the confusion matrix"
},
{
"code": null,
"e": 12000,
"s": 11285,
"text": "# We will compare this vector of predictions to the actual target vector to determine the model performance.y_pred = lr.predict(X_test)# Build the confusion matrix.confusion_matrix = metrics.confusion_matrix(y_test, y_pred)class_names=[0,1] # name of classesfig, ax = plt.subplots()tick_marks = np.arange(len(class_names))plt.xticks(tick_marks, class_names)plt.yticks(tick_marks, class_names)# The heatmap requires that we pass in a dataframe as the argumentsns.heatmap(pd.DataFrame(confusion_matrix), annot=True, cmap=\"YlGnBu\", fmt=\"g\")# Configure the heatmap parametersax.xaxis.set_label_position(\"top\")plt.tight_layout()plt.title('Confusion matrix', y=1.1)plt.ylabel('Actual label')plt.xlabel('Predicted label')"
},
{
"code": null,
"e": 12410,
"s": 12000,
"text": "At a glance, most of our classifications seem to be concentrated in the diagonal entries. An excellent start! Recall that we said the matrix gave us the error rates. But it's hard to gain a concrete numerical measure of the model’s performance from the matrix alone. Thus, we use the values from the matrix to compute the three fundamental classification performance measures: accuracy, precision, and recall."
},
{
"code": null,
"e": 12504,
"s": 12410,
"text": "Scikit-learn’s inbuilt metrics module lets us compute these metrics in a single line of code!"
},
{
"code": null,
"e": 12739,
"s": 12504,
"text": "# Print out our performance metricsprint(\"Accuracy:\",metrics.accuracy_score(y_test, y_pred))print(\"Precision:\",metrics.precision_score(y_test, y_pred, pos_label='Y'))print(\"Recall:\",metrics.recall_score(y_test, y_pred, pos_label='Y'))"
},
{
"code": null,
"e": 12792,
"s": 12739,
"text": "For our model, the metrics’ values turned out to be:"
},
{
"code": null,
"e": 12863,
"s": 12792,
"text": "Accuracy: 0.8116883116883117Precision: 0.875Recall: 0.8504672897196262"
},
{
"code": null,
"e": 12892,
"s": 12863,
"text": "Accuracy: 0.8116883116883117"
},
{
"code": null,
"e": 12909,
"s": 12892,
"text": "Precision: 0.875"
},
{
"code": null,
"e": 12936,
"s": 12909,
"text": "Recall: 0.8504672897196262"
},
{
"code": null,
"e": 13707,
"s": 12936,
"text": "It is an accepted practice to use precision and recall in conjunction to gauge the performance of a classification model as one could simply use instances that he or she knows would result in a correct prediction to gain a perfect precision score. In other words, if I have one training instance that I knew belonged to the positive class I would make sure that the model classifies only that instance into the positive class. The F1 score is a metric that is a harmonic sum of the precision and recall. It is a singular measure of a model’s performance and takes into account both the precision and recall, thus making sure that we do not have to go through the hassle of interpreting the numbers manually. Yet again, Scikitl-learn’s metrics module comes to the rescue!"
},
{
"code": null,
"e": 13774,
"s": 13707,
"text": "print(\"F1 Score:\",metrics.f1_score(y_test, y_pred, pos_label='Y'))"
},
{
"code": null,
"e": 13803,
"s": 13774,
"text": "F1 Score: 0.8625592417061612"
},
{
"code": null,
"e": 14278,
"s": 13803,
"text": "Alright, awesome! We sucessfully trained a model that can predict the response to a loan applicant based on the data we have on them. To do this at scale would be futile for us humans, but the performance of the classifier shows us just how powerful these techniques can be. Classification is but one of the multitude of techniques available as part of the Predictive Modeling toolbox. I hope that this has proven to be an informative and engaging introduction to the topic."
},
{
"code": null,
"e": 14292,
"s": 14278,
"text": "Happy coding!"
}
] |
__new__ in Python - GeeksforGeeks | 25 Nov, 2019
Python is an Object oriented programming language i.e everything in Python is an object. There are special kind of methods in Python known as magic methods or dunder methods (dunder here means “Double Underscores”). Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. These are commonly used for operator overloading.Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc.
Note: To know more about Magic methods click here.
Syntax:
class class_name:
def __new__(cls, *args, **kwargs):
statements
.
.
return super(class_name, cls).__new__(cls, *args, **kwargs)
Note: Instance can be created inside __new__ method either by using super function or by directly calling __new__ method over object, where if parent class is object. That is instance = super(MyClass, cls).__new__(cls, *args, **kwargs) or instance = object.__new__(cls, *args, **kwargs)
If both __init__ method and __new__ method exists in the class, then the __new__ method is executed first and decides whether to use __init__ method or not, because other class constructors can be called by __new__ method or it can simply return other objects as an instance of this class.
Example:
# Python program to # demonstrate __new__ # don't forget the object specified as baseclass A(object): def __new__(cls): print("Creating instance") return super(A, cls).__new__(cls) def __init__(self): print("Init is called") A()
Output:
Creating instance
Init is called
The above example shows that __new__ method is called automatically when calling the class name, whereas __init__ method is called every time an instance of the class is returned by __new__ method, passing the returned instance to __init__ as the self parameter, therefore even if you were to save the instance somewhere globally/statically and return it every time from __new__, then __init__ will be called every time you do just that.
This means that if the super is omitted for __new__ method the __init__ method will not be executed. Let’s see if that is the case.
# Python program to# demonstrate __new__ class A(object): def __new__(cls): print("Creating instance") # It is not called def __init__(self): print("Init is called") print(A())
Output:
Creating instance
None
In the above example, it can be seen that __init__ method is not called and the instantiation is evaluated to be None because the constructor is not returning anything. Let’s see what happens if both the __new__ and __init__ methods are returning something.
# Python program to# demonstrate __new__ class A(object): # new method returning a string def __new__(cls): print("Creating instance") return "GeeksforGeeks" class B(object): # init method returning a string def __init__(self): print("Initializing instance") return "GeeksforGeeks" print(A())print(B())
Output:
Creating instance
GeeksforGeeks
Initializing instance
Traceback (most recent call last):
File "/home/62216eb30d3856048eff916fb8d4c32d.py", line 17, in
print(B())
TypeError: __init__() should return None, not 'str'
This TypeError is raised by the handler that calls __init__ method and it wouldn’t even make sense to return anything from __init__ method since it’s purpose is just to alter the fresh state of the newly created instance.
Let’s try an example in which __new__ method returns an instance of a different class.Example:
# Python program to# demonstrate __new__ method # class whose object# is returnedclass GeeksforGeeks(object): def __str__(self): return "GeeksforGeeks" # class returning object# of different classclass Geek(object): def __new__(cls): return GeeksforGeeks() def __init__(self): print("Inside init") print(Geek())
Output:
GeeksforGeeks
Python-Functions
Python-OOP
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Read a file line by line in Python
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python program to convert a list to string
Reading and Writing to text files in Python
Python OOPs Concepts
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 24348,
"s": 24320,
"text": "\n25 Nov, 2019"
},
{
"code": null,
"e": 24802,
"s": 24348,
"text": "Python is an Object oriented programming language i.e everything in Python is an object. There are special kind of methods in Python known as magic methods or dunder methods (dunder here means “Double Underscores”). Dunder or magic methods in Python are the methods having two prefix and suffix underscores in the method name. These are commonly used for operator overloading.Few examples for magic methods are: __init__, __add__, __len__, __repr__ etc."
},
{
"code": null,
"e": 24853,
"s": 24802,
"text": "Note: To know more about Magic methods click here."
},
{
"code": null,
"e": 24861,
"s": 24853,
"text": "Syntax:"
},
{
"code": null,
"e": 25026,
"s": 24861,
"text": "class class_name:\n def __new__(cls, *args, **kwargs):\n statements\n .\n .\n return super(class_name, cls).__new__(cls, *args, **kwargs)\n"
},
{
"code": null,
"e": 25313,
"s": 25026,
"text": "Note: Instance can be created inside __new__ method either by using super function or by directly calling __new__ method over object, where if parent class is object. That is instance = super(MyClass, cls).__new__(cls, *args, **kwargs) or instance = object.__new__(cls, *args, **kwargs)"
},
{
"code": null,
"e": 25603,
"s": 25313,
"text": "If both __init__ method and __new__ method exists in the class, then the __new__ method is executed first and decides whether to use __init__ method or not, because other class constructors can be called by __new__ method or it can simply return other objects as an instance of this class."
},
{
"code": null,
"e": 25612,
"s": 25603,
"text": "Example:"
},
{
"code": "# Python program to # demonstrate __new__ # don't forget the object specified as baseclass A(object): def __new__(cls): print(\"Creating instance\") return super(A, cls).__new__(cls) def __init__(self): print(\"Init is called\") A()",
"e": 25874,
"s": 25612,
"text": null
},
{
"code": null,
"e": 25882,
"s": 25874,
"text": "Output:"
},
{
"code": null,
"e": 25916,
"s": 25882,
"text": "Creating instance\nInit is called\n"
},
{
"code": null,
"e": 26354,
"s": 25916,
"text": "The above example shows that __new__ method is called automatically when calling the class name, whereas __init__ method is called every time an instance of the class is returned by __new__ method, passing the returned instance to __init__ as the self parameter, therefore even if you were to save the instance somewhere globally/statically and return it every time from __new__, then __init__ will be called every time you do just that."
},
{
"code": null,
"e": 26486,
"s": 26354,
"text": "This means that if the super is omitted for __new__ method the __init__ method will not be executed. Let’s see if that is the case."
},
{
"code": "# Python program to# demonstrate __new__ class A(object): def __new__(cls): print(\"Creating instance\") # It is not called def __init__(self): print(\"Init is called\") print(A())",
"e": 26690,
"s": 26486,
"text": null
},
{
"code": null,
"e": 26698,
"s": 26690,
"text": "Output:"
},
{
"code": null,
"e": 26722,
"s": 26698,
"text": "Creating instance\nNone\n"
},
{
"code": null,
"e": 26980,
"s": 26722,
"text": "In the above example, it can be seen that __init__ method is not called and the instantiation is evaluated to be None because the constructor is not returning anything. Let’s see what happens if both the __new__ and __init__ methods are returning something."
},
{
"code": "# Python program to# demonstrate __new__ class A(object): # new method returning a string def __new__(cls): print(\"Creating instance\") return \"GeeksforGeeks\" class B(object): # init method returning a string def __init__(self): print(\"Initializing instance\") return \"GeeksforGeeks\" print(A())print(B())",
"e": 27326,
"s": 26980,
"text": null
},
{
"code": null,
"e": 27334,
"s": 27326,
"text": "Output:"
},
{
"code": null,
"e": 27389,
"s": 27334,
"text": "Creating instance\nGeeksforGeeks\nInitializing instance\n"
},
{
"code": null,
"e": 27557,
"s": 27389,
"text": "Traceback (most recent call last):\n File \"/home/62216eb30d3856048eff916fb8d4c32d.py\", line 17, in \n print(B())\nTypeError: __init__() should return None, not 'str'\n"
},
{
"code": null,
"e": 27779,
"s": 27557,
"text": "This TypeError is raised by the handler that calls __init__ method and it wouldn’t even make sense to return anything from __init__ method since it’s purpose is just to alter the fresh state of the newly created instance."
},
{
"code": null,
"e": 27874,
"s": 27779,
"text": "Let’s try an example in which __new__ method returns an instance of a different class.Example:"
},
{
"code": "# Python program to# demonstrate __new__ method # class whose object# is returnedclass GeeksforGeeks(object): def __str__(self): return \"GeeksforGeeks\" # class returning object# of different classclass Geek(object): def __new__(cls): return GeeksforGeeks() def __init__(self): print(\"Inside init\") print(Geek())",
"e": 28245,
"s": 27874,
"text": null
},
{
"code": null,
"e": 28253,
"s": 28245,
"text": "Output:"
},
{
"code": null,
"e": 28268,
"s": 28253,
"text": "GeeksforGeeks\n"
},
{
"code": null,
"e": 28285,
"s": 28268,
"text": "Python-Functions"
},
{
"code": null,
"e": 28296,
"s": 28285,
"text": "Python-OOP"
},
{
"code": null,
"e": 28303,
"s": 28296,
"text": "Python"
},
{
"code": null,
"e": 28401,
"s": 28303,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28410,
"s": 28401,
"text": "Comments"
},
{
"code": null,
"e": 28423,
"s": 28410,
"text": "Old Comments"
},
{
"code": null,
"e": 28441,
"s": 28423,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28473,
"s": 28441,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28495,
"s": 28473,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 28530,
"s": 28495,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 28560,
"s": 28530,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 28602,
"s": 28560,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28645,
"s": 28602,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 28689,
"s": 28645,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 28710,
"s": 28689,
"text": "Python OOPs Concepts"
}
] |
Audio Classification using FastAI and On-the-Fly Frequency Transforms | by John Hartquist | Towards Data Science | While deep learning models are able to help tackle many different types of problems, image classification is the most prevalent example for courses and frameworks, often acting as the “hello, world” introduction. FastAI is a high-level library built on top of PyTorch that makes it extremely easy to get started classifying images, with an example showing how train an accurate model in only four lines of code. With the new v1 release of the library, an API called data_block allows users a flexible way to simplify the data loading process. After competing in the Freesound General-Purpose Audio Tagging Kaggle competition over the summer, I decided to repurpose some of my code to take advantage of fastai’s benefits for audio classification as well. This article will give a quick introduction to working with audio files in Python, give some background around creating spectrogram images, and then show how to leverage pretrained image models without actually having to generate images beforehand.
All the code used to generate the content of this post will be available in this repository, complete with example notebooks.
At first, it may seem a little strange to classify audio files as images. Images are 2-dimensional after all (with a possible 3rd dimension for RGBA channels), and audio files have a single time dimension (with a possible 2nd dimension for channels, for example stereo vs mono). In this post, we’ll only be looking at audio files with a single channel. Every audio file also has an associated sample rate, which is the number of samples per second of audio. If a 3 second audio clip has a sample rate of 44,100 Hz, that means it is made up of 3*44,100 = 132,300 consecutive numbers representing changes in air pressure. One of the best libraries for manipulating audio in Python is called librosa.
clip, sample_rate = librosa.load(filename, sr=None)clip = clip[:132300] # first three seconds of file
While this representation does give us a sense of how loud or quiet a clip is at any point in time, it gives us very little information about which frequencies are present. A very common solution to this problem is to take small overlapping chunks of the signal, and run them through a Fast Fourier Transform (FFT) to convert them from the time domain to the frequency domain. After running each section through an FFT, we can convert the result to polar coordinates, giving us magnitudes and phases of different frequencies. While the phases information can be useful in some contexts, we mostly use the magnitudes, and convert them to decibel units because our ears percieve sound on a logarithmic scale.
n_fft = 1024 # frame length start = 45000 # start at a part of the sound thats not silencex = clip[start:start+n_fft]X = fft(x, n_fft)X_magnitude, X_phase = librosa.magphase(X)X_magnitude_db = librosa.amplitude_to_db(X_magnitude)
Taking an FFT of size 1024 will result in a frequency spectrum with 1024 frequency bins. The second half of the spectrum is redundant however, so in practice we only use the first (N/2)+1 bins, which is 513 in this case.
To generate information about the whole file, we can take an FFT of a 1024 sample window, and slide it by 512 samples (hop length) so that the windows overlap with each other. For this three second file, that will give us 259 frequency spectrums, which we can then view as a 2-dimensional image. This is called a short-time Fourier Transform (STFT), and it allows us to see how different frequencies change over time.
stft = librosa.stft(clip, n_fft=n_fft, hop_length=hop_length)stft_magnitude, stft_phase = librosa.magphase(stft)stft_magnitude_db = librosa.amplitude_to_db(stft_magnitude)
In this example, we can see that almost all of the interesting frequency data is below 12,500 Hz. In addition to there being a lot of wasted bins, this does not accurately display how humans perceive frequencies. Along with loudness, we also hear frequencies on a logarithmic scale. We would hear the same “distance” of frequencies from 50 Hz to 100 Hz as we would between 400 Hz and 800 Hz.
These are some of the reasons why many people use melspectrograms which transform the frequency bins into the mel scale. Librosa allows us to easily convert a regular spectrogram into a melspectrogram, and lets us define how many “bins” we want to have. We can also specify a minimum and maximum frequency that we want our bins to be divided into.
mel_spec = librosa.feature.melspectrogram(clip, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels, sr=sample_rate, power=1.0, fmin=fmin, fmax=fmax)mel_spec_db = librosa.amplitude_to_db(mel_spec, ref=np.max)
In each of these melspectrograms, I used 64 frequency bins (n_mels). The only difference is that on the right, I specified that I only care about frequencies between 20Hz and 8000Hz. This greatly reduces the size of each transform from the original 513 bins per time step.
While it is possible to classify raw audio waveform data, it is very popular to use image classifiers to classify melspectrograms, and it works pretty well. In order to do this we have to convert our whole dataset to image files using similar code as above. This took me about 10 minutes of processing time using all the CPUs on my GCP instance. I used the following parameters for generating the melspectrogram images:
n_fft = 1024hop_length = 256n_mels = 40f_min = 20f_max = 8000sample_rate = 16000
For the rest of this post, I’ve used the NSynth Dataset by the Magenta team at Google. It is an interesting dataset composed of 305,979 musical notes, each 4 seconds long. I trimmed the dataset down to only the acoustically generated notes to make things a little more manageable. The goal was to classify which instrument family each note was generated with out of 10 possible instrument families.
Using fastai’s new data_block API, it becomes very easy to build a DataBunch object with all the spectrogram image data along with their labels — in this example I grabbed all of the labels using a regex over the filenames.
NSYNTH_IMAGES = 'data/nsynth_acoustic_images'instrument_family_pattern = r'(\w+)_\w+_\d+-\d+-\d+.png$'data = (ImageItemList.from_folder(NSYNTH_IMAGES) .split_by_folder() .label_from_re(instrument_family_pattern) .databunch())
Once I had my data loaded, I instantiated a pretrained Convolutional Neural Network (CNN) called resnet18, and fine-tuned it on the spectrograms.
learn = create_cnn(data, models.resnet18, metrics=accuracy)learn.fit_one_cycle(3)
In only 2 minutes and 14 seconds I was left with a model that scored 84% accuracy on the validation set (a completely separate set of instruments from the training set). While this model is definitely overfitting, this is without data augmentation or regularization of any kind, a pretty good start!
By utilizing fastai’s ClassificationInterpretation class, we can take a look at where the mistakes are coming from.
interp = ClassificationInterpretation.from_learner(learn)interp.plot_confusion_matrix(figsize=(10, 10), dpi=60)
It looks like mallets are getting confused with guitars, and reeds are being confused with brass instruments the most. Using this information, we could look more closely at the spectrograms of those instruments, and try to decide if there are better parameters we could use to differentiate between them.
If classifying audio from images works so well, you might ask why it would be beneficial to generate spectrograms during training (as opposed to before). There are a few good reasons for this:
Time to generate imagesIn the previous example, it took me over 10 minutes to generate all the spectrogram images. Every time I want to try out a different set of parameters, or maybe generate a plain STFT instead of melspectrogram, I’d have to regenerate all those images. This makes it hard to test a lot of different configurations quickly.Disk spaceSimilarly, every time I generate a new set of images, they can take up large amounts of hard-drive space depending on the size of the transforms and the dataset itself. In this case, my generated images took up over 1GB of storage.Data AugmentationOne of the most effective strategies for improving performance with image classifiers is to use data augmentation. The regular image transforms however, (rotating, flipping, cropping, etc) do not make as much sense for spectrograms. It would be better to transform audio files in the time domain, and then convert them to spectrograms right before sending them to a classifier.GPU vs CPUIn the past, I always did the frequency transforms using librosa on CPU, but it would be nice to utilize PyTorch’s stft method on the GPU since it should be much faster, and be able to process batches at a time (as opposed to 1 image at a time).
Time to generate imagesIn the previous example, it took me over 10 minutes to generate all the spectrogram images. Every time I want to try out a different set of parameters, or maybe generate a plain STFT instead of melspectrogram, I’d have to regenerate all those images. This makes it hard to test a lot of different configurations quickly.
Disk spaceSimilarly, every time I generate a new set of images, they can take up large amounts of hard-drive space depending on the size of the transforms and the dataset itself. In this case, my generated images took up over 1GB of storage.
Data AugmentationOne of the most effective strategies for improving performance with image classifiers is to use data augmentation. The regular image transforms however, (rotating, flipping, cropping, etc) do not make as much sense for spectrograms. It would be better to transform audio files in the time domain, and then convert them to spectrograms right before sending them to a classifier.
GPU vs CPUIn the past, I always did the frequency transforms using librosa on CPU, but it would be nice to utilize PyTorch’s stft method on the GPU since it should be much faster, and be able to process batches at a time (as opposed to 1 image at a time).
Over the past few days I’ve been experimenting with an idea to create a new fastai module for audio files. After reading the great new fastai documentation, I was able to write some basic classes to load raw audio files and generate the spectrograms as batches on the GPU using PyTorch. I also wrote a custom create_cnn function that would take pretrained image classifiers, and modify them to work on a single channel (spectrogram) instead of the 3 channels they were originally trained for. To my surprise, the code runs almost as fast as the image classification equivalent, with no extra step of generating actual images. Setting up my data now looks like this:
tfms = get_frequency_batch_transforms(n_fft=n_fft, n_hop=n_hop, n_mels=n_mels, sample_rate=sample_rate)data = (AudioItemList .from_folder(NSYNTH_AUDIO) .split_by_folder() .label_from_re(instrument_family_pattern) .databunch(bs=batch_size, tfms=tfms))
The fastai library supports a nice way to preview batches as well:
data.show_batch(3)
Fine-tuning on a pretrained model is exactly the same as before, only this time the first convolutional layer is being modified to accept a single input channel (thanks to David Gutman on the fastai forums).
learn = create_cnn(data, models.resnet18, metrics=accuracy)learn.fit_one_cycle(3)
This time the training takes only 30 seconds longer, and has only slightly lower accuracy after 3 epochs with 80% on the validation set! Generating images on the CPU before took over 10 minutes when doing it one at time. This opens up the possibility for much more rapid experimentation with tuning spectrogram parameters and as well as computing spectrograms from augmented audio files.
Now that its possible to generate different spectral representations on the fly, I’m very interested in trying to get data augmentation working for raw audio files. From pitch shifting, to time stretching (methods available in librosa), to simply taking random segments of audio clips, there is a lot to experiment with.
I am also interested in how much better the results would be the pretrained models used here had actually been trained on audio files and not image files.
Thanks for taking the time to read my first blog post! Please let me know if you have any corrections or comments. Once again, you can view all the code and full notebooks over at https://github.com/jhartquist/fastai_audio.
FastAI docs
PyTorch v1.0 docs
torchaudio: Heavy inspiration for this article
Great intro to Fourier Transform: https://jackschaedler.github.io/circles-sines-signals/dft_introduction.html
Speech Processing for Machine Learning: Filter banks, Mel-Frequency Cepstral Coefficients (MFCCs) and What’s In Between
Highly recommended course on audio signal processing in Python: Audio Signal Processing for Musical Applications | [
{
"code": null,
"e": 1175,
"s": 172,
"text": "While deep learning models are able to help tackle many different types of problems, image classification is the most prevalent example for courses and frameworks, often acting as the “hello, world” introduction. FastAI is a high-level library built on top of PyTorch that makes it extremely easy to get started classifying images, with an example showing how train an accurate model in only four lines of code. With the new v1 release of the library, an API called data_block allows users a flexible way to simplify the data loading process. After competing in the Freesound General-Purpose Audio Tagging Kaggle competition over the summer, I decided to repurpose some of my code to take advantage of fastai’s benefits for audio classification as well. This article will give a quick introduction to working with audio files in Python, give some background around creating spectrogram images, and then show how to leverage pretrained image models without actually having to generate images beforehand."
},
{
"code": null,
"e": 1301,
"s": 1175,
"text": "All the code used to generate the content of this post will be available in this repository, complete with example notebooks."
},
{
"code": null,
"e": 1999,
"s": 1301,
"text": "At first, it may seem a little strange to classify audio files as images. Images are 2-dimensional after all (with a possible 3rd dimension for RGBA channels), and audio files have a single time dimension (with a possible 2nd dimension for channels, for example stereo vs mono). In this post, we’ll only be looking at audio files with a single channel. Every audio file also has an associated sample rate, which is the number of samples per second of audio. If a 3 second audio clip has a sample rate of 44,100 Hz, that means it is made up of 3*44,100 = 132,300 consecutive numbers representing changes in air pressure. One of the best libraries for manipulating audio in Python is called librosa."
},
{
"code": null,
"e": 2101,
"s": 1999,
"text": "clip, sample_rate = librosa.load(filename, sr=None)clip = clip[:132300] # first three seconds of file"
},
{
"code": null,
"e": 2808,
"s": 2101,
"text": "While this representation does give us a sense of how loud or quiet a clip is at any point in time, it gives us very little information about which frequencies are present. A very common solution to this problem is to take small overlapping chunks of the signal, and run them through a Fast Fourier Transform (FFT) to convert them from the time domain to the frequency domain. After running each section through an FFT, we can convert the result to polar coordinates, giving us magnitudes and phases of different frequencies. While the phases information can be useful in some contexts, we mostly use the magnitudes, and convert them to decibel units because our ears percieve sound on a logarithmic scale."
},
{
"code": null,
"e": 3039,
"s": 2808,
"text": "n_fft = 1024 # frame length start = 45000 # start at a part of the sound thats not silencex = clip[start:start+n_fft]X = fft(x, n_fft)X_magnitude, X_phase = librosa.magphase(X)X_magnitude_db = librosa.amplitude_to_db(X_magnitude)"
},
{
"code": null,
"e": 3260,
"s": 3039,
"text": "Taking an FFT of size 1024 will result in a frequency spectrum with 1024 frequency bins. The second half of the spectrum is redundant however, so in practice we only use the first (N/2)+1 bins, which is 513 in this case."
},
{
"code": null,
"e": 3678,
"s": 3260,
"text": "To generate information about the whole file, we can take an FFT of a 1024 sample window, and slide it by 512 samples (hop length) so that the windows overlap with each other. For this three second file, that will give us 259 frequency spectrums, which we can then view as a 2-dimensional image. This is called a short-time Fourier Transform (STFT), and it allows us to see how different frequencies change over time."
},
{
"code": null,
"e": 3850,
"s": 3678,
"text": "stft = librosa.stft(clip, n_fft=n_fft, hop_length=hop_length)stft_magnitude, stft_phase = librosa.magphase(stft)stft_magnitude_db = librosa.amplitude_to_db(stft_magnitude)"
},
{
"code": null,
"e": 4242,
"s": 3850,
"text": "In this example, we can see that almost all of the interesting frequency data is below 12,500 Hz. In addition to there being a lot of wasted bins, this does not accurately display how humans perceive frequencies. Along with loudness, we also hear frequencies on a logarithmic scale. We would hear the same “distance” of frequencies from 50 Hz to 100 Hz as we would between 400 Hz and 800 Hz."
},
{
"code": null,
"e": 4590,
"s": 4242,
"text": "These are some of the reasons why many people use melspectrograms which transform the frequency bins into the mel scale. Librosa allows us to easily convert a regular spectrogram into a melspectrogram, and lets us define how many “bins” we want to have. We can also specify a minimum and maximum frequency that we want our bins to be divided into."
},
{
"code": null,
"e": 4797,
"s": 4590,
"text": "mel_spec = librosa.feature.melspectrogram(clip, n_fft=n_fft, hop_length=hop_length, n_mels=n_mels, sr=sample_rate, power=1.0, fmin=fmin, fmax=fmax)mel_spec_db = librosa.amplitude_to_db(mel_spec, ref=np.max)"
},
{
"code": null,
"e": 5070,
"s": 4797,
"text": "In each of these melspectrograms, I used 64 frequency bins (n_mels). The only difference is that on the right, I specified that I only care about frequencies between 20Hz and 8000Hz. This greatly reduces the size of each transform from the original 513 bins per time step."
},
{
"code": null,
"e": 5490,
"s": 5070,
"text": "While it is possible to classify raw audio waveform data, it is very popular to use image classifiers to classify melspectrograms, and it works pretty well. In order to do this we have to convert our whole dataset to image files using similar code as above. This took me about 10 minutes of processing time using all the CPUs on my GCP instance. I used the following parameters for generating the melspectrogram images:"
},
{
"code": null,
"e": 5571,
"s": 5490,
"text": "n_fft = 1024hop_length = 256n_mels = 40f_min = 20f_max = 8000sample_rate = 16000"
},
{
"code": null,
"e": 5970,
"s": 5571,
"text": "For the rest of this post, I’ve used the NSynth Dataset by the Magenta team at Google. It is an interesting dataset composed of 305,979 musical notes, each 4 seconds long. I trimmed the dataset down to only the acoustically generated notes to make things a little more manageable. The goal was to classify which instrument family each note was generated with out of 10 possible instrument families."
},
{
"code": null,
"e": 6194,
"s": 5970,
"text": "Using fastai’s new data_block API, it becomes very easy to build a DataBunch object with all the spectrogram image data along with their labels — in this example I grabbed all of the labels using a regex over the filenames."
},
{
"code": null,
"e": 6447,
"s": 6194,
"text": "NSYNTH_IMAGES = 'data/nsynth_acoustic_images'instrument_family_pattern = r'(\\w+)_\\w+_\\d+-\\d+-\\d+.png$'data = (ImageItemList.from_folder(NSYNTH_IMAGES) .split_by_folder() .label_from_re(instrument_family_pattern) .databunch())"
},
{
"code": null,
"e": 6593,
"s": 6447,
"text": "Once I had my data loaded, I instantiated a pretrained Convolutional Neural Network (CNN) called resnet18, and fine-tuned it on the spectrograms."
},
{
"code": null,
"e": 6675,
"s": 6593,
"text": "learn = create_cnn(data, models.resnet18, metrics=accuracy)learn.fit_one_cycle(3)"
},
{
"code": null,
"e": 6975,
"s": 6675,
"text": "In only 2 minutes and 14 seconds I was left with a model that scored 84% accuracy on the validation set (a completely separate set of instruments from the training set). While this model is definitely overfitting, this is without data augmentation or regularization of any kind, a pretty good start!"
},
{
"code": null,
"e": 7091,
"s": 6975,
"text": "By utilizing fastai’s ClassificationInterpretation class, we can take a look at where the mistakes are coming from."
},
{
"code": null,
"e": 7203,
"s": 7091,
"text": "interp = ClassificationInterpretation.from_learner(learn)interp.plot_confusion_matrix(figsize=(10, 10), dpi=60)"
},
{
"code": null,
"e": 7508,
"s": 7203,
"text": "It looks like mallets are getting confused with guitars, and reeds are being confused with brass instruments the most. Using this information, we could look more closely at the spectrograms of those instruments, and try to decide if there are better parameters we could use to differentiate between them."
},
{
"code": null,
"e": 7701,
"s": 7508,
"text": "If classifying audio from images works so well, you might ask why it would be beneficial to generate spectrograms during training (as opposed to before). There are a few good reasons for this:"
},
{
"code": null,
"e": 8935,
"s": 7701,
"text": "Time to generate imagesIn the previous example, it took me over 10 minutes to generate all the spectrogram images. Every time I want to try out a different set of parameters, or maybe generate a plain STFT instead of melspectrogram, I’d have to regenerate all those images. This makes it hard to test a lot of different configurations quickly.Disk spaceSimilarly, every time I generate a new set of images, they can take up large amounts of hard-drive space depending on the size of the transforms and the dataset itself. In this case, my generated images took up over 1GB of storage.Data AugmentationOne of the most effective strategies for improving performance with image classifiers is to use data augmentation. The regular image transforms however, (rotating, flipping, cropping, etc) do not make as much sense for spectrograms. It would be better to transform audio files in the time domain, and then convert them to spectrograms right before sending them to a classifier.GPU vs CPUIn the past, I always did the frequency transforms using librosa on CPU, but it would be nice to utilize PyTorch’s stft method on the GPU since it should be much faster, and be able to process batches at a time (as opposed to 1 image at a time)."
},
{
"code": null,
"e": 9279,
"s": 8935,
"text": "Time to generate imagesIn the previous example, it took me over 10 minutes to generate all the spectrogram images. Every time I want to try out a different set of parameters, or maybe generate a plain STFT instead of melspectrogram, I’d have to regenerate all those images. This makes it hard to test a lot of different configurations quickly."
},
{
"code": null,
"e": 9521,
"s": 9279,
"text": "Disk spaceSimilarly, every time I generate a new set of images, they can take up large amounts of hard-drive space depending on the size of the transforms and the dataset itself. In this case, my generated images took up over 1GB of storage."
},
{
"code": null,
"e": 9916,
"s": 9521,
"text": "Data AugmentationOne of the most effective strategies for improving performance with image classifiers is to use data augmentation. The regular image transforms however, (rotating, flipping, cropping, etc) do not make as much sense for spectrograms. It would be better to transform audio files in the time domain, and then convert them to spectrograms right before sending them to a classifier."
},
{
"code": null,
"e": 10172,
"s": 9916,
"text": "GPU vs CPUIn the past, I always did the frequency transforms using librosa on CPU, but it would be nice to utilize PyTorch’s stft method on the GPU since it should be much faster, and be able to process batches at a time (as opposed to 1 image at a time)."
},
{
"code": null,
"e": 10838,
"s": 10172,
"text": "Over the past few days I’ve been experimenting with an idea to create a new fastai module for audio files. After reading the great new fastai documentation, I was able to write some basic classes to load raw audio files and generate the spectrograms as batches on the GPU using PyTorch. I also wrote a custom create_cnn function that would take pretrained image classifiers, and modify them to work on a single channel (spectrogram) instead of the 3 channels they were originally trained for. To my surprise, the code runs almost as fast as the image classification equivalent, with no extra step of generating actual images. Setting up my data now looks like this:"
},
{
"code": null,
"e": 11246,
"s": 10838,
"text": "tfms = get_frequency_batch_transforms(n_fft=n_fft, n_hop=n_hop, n_mels=n_mels, sample_rate=sample_rate)data = (AudioItemList .from_folder(NSYNTH_AUDIO) .split_by_folder() .label_from_re(instrument_family_pattern) .databunch(bs=batch_size, tfms=tfms))"
},
{
"code": null,
"e": 11313,
"s": 11246,
"text": "The fastai library supports a nice way to preview batches as well:"
},
{
"code": null,
"e": 11332,
"s": 11313,
"text": "data.show_batch(3)"
},
{
"code": null,
"e": 11540,
"s": 11332,
"text": "Fine-tuning on a pretrained model is exactly the same as before, only this time the first convolutional layer is being modified to accept a single input channel (thanks to David Gutman on the fastai forums)."
},
{
"code": null,
"e": 11622,
"s": 11540,
"text": "learn = create_cnn(data, models.resnet18, metrics=accuracy)learn.fit_one_cycle(3)"
},
{
"code": null,
"e": 12010,
"s": 11622,
"text": "This time the training takes only 30 seconds longer, and has only slightly lower accuracy after 3 epochs with 80% on the validation set! Generating images on the CPU before took over 10 minutes when doing it one at time. This opens up the possibility for much more rapid experimentation with tuning spectrogram parameters and as well as computing spectrograms from augmented audio files."
},
{
"code": null,
"e": 12331,
"s": 12010,
"text": "Now that its possible to generate different spectral representations on the fly, I’m very interested in trying to get data augmentation working for raw audio files. From pitch shifting, to time stretching (methods available in librosa), to simply taking random segments of audio clips, there is a lot to experiment with."
},
{
"code": null,
"e": 12486,
"s": 12331,
"text": "I am also interested in how much better the results would be the pretrained models used here had actually been trained on audio files and not image files."
},
{
"code": null,
"e": 12710,
"s": 12486,
"text": "Thanks for taking the time to read my first blog post! Please let me know if you have any corrections or comments. Once again, you can view all the code and full notebooks over at https://github.com/jhartquist/fastai_audio."
},
{
"code": null,
"e": 12722,
"s": 12710,
"text": "FastAI docs"
},
{
"code": null,
"e": 12740,
"s": 12722,
"text": "PyTorch v1.0 docs"
},
{
"code": null,
"e": 12787,
"s": 12740,
"text": "torchaudio: Heavy inspiration for this article"
},
{
"code": null,
"e": 12897,
"s": 12787,
"text": "Great intro to Fourier Transform: https://jackschaedler.github.io/circles-sines-signals/dft_introduction.html"
},
{
"code": null,
"e": 13017,
"s": 12897,
"text": "Speech Processing for Machine Learning: Filter banks, Mel-Frequency Cepstral Coefficients (MFCCs) and What’s In Between"
}
] |
Lolcode - Loops | Loops are used in programming languages to execute a set of statements multiple times. For example, if you want to print the digit 5 for five times, then instead of writing the VISIBLE “5” statement five times, you can run a loop with single VISIBLE “5” statement for five times.
Simple loops are represented with IM IN YR <label> and IM OUTTA YR <label>. Loops defined in this way are infinite loops and they should be terminated with a GTFO break statement.
Iteration loops have the following structure−
IM IN YR <label> <any_operation> YR <any_variable> [TIL|WILE <expression>]
<code block to execute inside the loop multiple times>
IM OUTTA YR <label>
Please note that inside the function body, UPPIN (increment by one), NERFIN (decrement by one), or any unary function can be used.
The TIL keyword calculates the expression as a TROOF: if it evaluates as FAIL, the loop continues once more, if it evaluates as WIN, then the loop execution stops, and continues after the matching IM OUTTA YR statement.
The WILE keyword is the opposite of TIL keyword, if the expression is WIN, execution continues, otherwise the loop exits.
HAI 1.2
I HAS A VAR ITZ 0
IM IN YR LOOPY UPPIN YR VAR TIL BOTH SAEM VAR AN 10
VISIBLE SUM OF VAR AN 1
IM OUTTA YR LOOPY
KTHXBYE
When the above code is compiled on any LOLCODE compiler, or on our online codingground, this will produce the following output.
sh-
4.3$ lci main.lo
1
2
3
4
5
6
7
8
9
10
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2120,
"s": 1840,
"text": "Loops are used in programming languages to execute a set of statements multiple times. For example, if you want to print the digit 5 for five times, then instead of writing the VISIBLE “5” statement five times, you can run a loop with single VISIBLE “5” statement for five times."
},
{
"code": null,
"e": 2300,
"s": 2120,
"text": "Simple loops are represented with IM IN YR <label> and IM OUTTA YR <label>. Loops defined in this way are infinite loops and they should be terminated with a GTFO break statement."
},
{
"code": null,
"e": 2346,
"s": 2300,
"text": "Iteration loops have the following structure−"
},
{
"code": null,
"e": 2500,
"s": 2346,
"text": "IM IN YR <label> <any_operation> YR <any_variable> [TIL|WILE <expression>]\n <code block to execute inside the loop multiple times>\nIM OUTTA YR <label>\n"
},
{
"code": null,
"e": 2631,
"s": 2500,
"text": "Please note that inside the function body, UPPIN (increment by one), NERFIN (decrement by one), or any unary function can be used."
},
{
"code": null,
"e": 2851,
"s": 2631,
"text": "The TIL keyword calculates the expression as a TROOF: if it evaluates as FAIL, the loop continues once more, if it evaluates as WIN, then the loop execution stops, and continues after the matching IM OUTTA YR statement."
},
{
"code": null,
"e": 2973,
"s": 2851,
"text": "The WILE keyword is the opposite of TIL keyword, if the expression is WIN, execution continues, otherwise the loop exits."
},
{
"code": null,
"e": 3104,
"s": 2973,
"text": "HAI 1.2\nI HAS A VAR ITZ 0\nIM IN YR LOOPY UPPIN YR VAR TIL BOTH SAEM VAR AN 10\n VISIBLE SUM OF VAR AN 1\nIM OUTTA YR LOOPY\nKTHXBYE"
},
{
"code": null,
"e": 3232,
"s": 3104,
"text": "When the above code is compiled on any LOLCODE compiler, or on our online codingground, this will produce the following output."
},
{
"code": null,
"e": 3284,
"s": 3232,
"text": "sh-\n4.3$ lci main.lo\n1\n\n2\n\n3\n\n4\n\n5\n\n6\n\n7\n\n8\n\n9\n\n10\n"
},
{
"code": null,
"e": 3291,
"s": 3284,
"text": " Print"
},
{
"code": null,
"e": 3302,
"s": 3291,
"text": " Add Notes"
}
] |
Connecting to SAP R/3 system via JCo client and JCo Server | In JCo3.0, Java client JCO.Client is replaced by JCoDestinations. You can connect to SAP system via Inbound RFC Communication (Java calls ABAP) or via Outbound RFC Communication (ABAP calls Java).
For inbound RFC communication, you need to use JCoDestination for executing a remote function module at ABAP side. To use inbound RFCs, you have to use “JCoDestination” which executes a Function module remotely at ABAP side and while using outbound RFCs, you have to configure a JCoServer at the SAP gateway that is responsible to receive incoming requests from ABAP side and process remote function module at Java side.
To know more about configuring JCo connection for inbound and outbound processing, you can refer below link:
https://help.sap.com/saphelp_nwpi711/helpdata/en/48/70792c872c1b5ae10000000a42189c/frameset.htm | [
{
"code": null,
"e": 1259,
"s": 1062,
"text": "In JCo3.0, Java client JCO.Client is replaced by JCoDestinations. You can connect to SAP system via Inbound RFC Communication (Java calls ABAP) or via Outbound RFC Communication (ABAP calls Java)."
},
{
"code": null,
"e": 1680,
"s": 1259,
"text": "For inbound RFC communication, you need to use JCoDestination for executing a remote function module at ABAP side. To use inbound RFCs, you have to use “JCoDestination” which executes a Function module remotely at ABAP side and while using outbound RFCs, you have to configure a JCoServer at the SAP gateway that is responsible to receive incoming requests from ABAP side and process remote function module at Java side."
},
{
"code": null,
"e": 1789,
"s": 1680,
"text": "To know more about configuring JCo connection for inbound and outbound processing, you can refer below link:"
},
{
"code": null,
"e": 1885,
"s": 1789,
"text": "https://help.sap.com/saphelp_nwpi711/helpdata/en/48/70792c872c1b5ae10000000a42189c/frameset.htm"
}
] |
Divide the array in K segments such that the sum of minimums is maximized | 26 May, 2022
Given an array a of size N and an integer K, the task is to divide the array into K segments such that sum of the minimum of K segments is maximized. Examples:
Input: a[] = {5, 7, 4, 2, 8, 1, 6}, K = 3 Output: 7 Divide the array at indexes 0 and 1. Then the segments are {5}, {7}, {4, 2, 8, 1, 6}. Sum of the minimum is 5 + 7 + 1 = 13 Input: a[] = {6, 5, 3, 8, 9, 10, 4, 7, 10}, K = 4 Output: 27
Approach: The problem can be solved using Dynamic Programming. Try all the possible partitions that are possible using recursion. Let dp[i][k] be the maximum sum of minimums till index i with k partitions. Hence the possible states will be partition at every index from the index i till n. The maximum sum of minimums of all those states will be our answer. After writing this recurrence, we can use memoization.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to find the sum of// the minimum of all the segments#include <bits/stdc++.h>using namespace std;const int MAX = 10; // Function to maximize the sum of the minimumsint maximizeSum(int a[], int n, int ind, int k, int dp[MAX][MAX]){ // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1e9; } // If at the end but // k segments are not formed else if (ind == n) return -1e9; // If the state has not been visited yet else if (dp[ind][k] != -1) return dp[ind][k]; // If the state has not been visited else { int ans = 0; // Get the minimum element in the segment int mini = a[ind]; // Iterate and try to break at every index // and create a segment for (int i = ind; i < n; i++) { // Find the minimum element in the segment mini = min(mini, a[i]); // Find the sum of all the segments trying all // the possible combinations ans = max(ans, maximizeSum( a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind][k] = ans; }} // Driver Codeint main(){ int a[] = { 5, 7, 4, 2, 8, 1, 6 }; int k = 3; int n = sizeof(a) / sizeof(a[0]); // Initialize dp array with -1 int dp[MAX][MAX]; memset(dp, -1, sizeof dp); cout << maximizeSum(a, n, 0, k, dp); return 0;}
// Java program to find the sum of// the minimum of all the segments class GFG{ static int MAX = 10; // Function to maximize the // sum of the minimums public static int maximizeSum( int[] a, int n, int ind, int k, int[][] dp) { // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1000000000; } // If at the end but // k segments are not formed else if (ind == n) return -1000000000; // If the state has not // been visited yet else if (dp[ind][k] != -1) return dp[ind][k]; // If the state has // not been visited else { int ans = 0; // Get the minimum // element in the segment int mini = a[ind]; // Iterate and try to break // at every index // and create a segment for (int i = ind; i < n; i++) { // Find the minimum element // in the segment mini = Math.min(mini, a[i]); // Find the sum of all the // segments trying all // the possible combinations ans = Math.max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind][k] = ans; } } // Driver Code public static void main(String[] args) { int[] a = { 5, 7, 4, 2, 8, 1, 6 }; int k = 3; int n = a.length; // Initialize dp array with -1 int[][] dp = new int[MAX][MAX]; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) dp[i][j] = -1; } System.out.println( maximizeSum(a, n, 0, k, dp)); }} // This code is contributed by// sanjeev2552
# Python 3 program to find the sum of# the minimum of all the segmentsMAX = 10 # Function to maximize the# sum of the minimumsdef maximizeSum(a,n, ind, k, dp): # If k segments have been divided if (k == 0): # If we are at the end if (ind == n): return 0 # If we donot reach the end # then return a negative number # that cannot be the sum else: return -1e9 # If at the end but # k segments are not formed elif (ind == n): return -1e9 # If the state has been visited already elif (dp[ind][k] != -1): return dp[ind][k] # If the state has not been visited else: ans = 0 # Get the minimum element # in the segment mini = a[ind] # Iterate and try to break # at every index # and create a segment for i in range(ind,n,1): # Find the minimum element # in the segment mini = min(mini, a[i]) # Find the sum of all the # segments trying all # the possible combinations ans = max(ans, maximizeSum(\ a, n, i + 1, k - 1, dp) + mini) # Return the answer by # memoizing it dp[ind][k] = ans return ans # Driver Codeif __name__ == '__main__': a = [5, 7, 4, 2, 1, 6] k = 3 n = len(a) # Initialize dp array with -1 dp = [[-1 for i in range(MAX)]\ for j in range(MAX)] print(maximizeSum(a, n, 0, k, dp)) # This code is contributed by# Surendra_Gangwar
// C# program to find the sum of// the minimum of all the segmentsusing System; class GFG{ static int MAX = 10; // Function to maximize the sum of the minimums public static int maximizeSum( int[] a, int n, int ind, int k, int[] dp) { // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1000000000; } // If at the end but // k segments are not formed else if (ind == n) return -1000000000; // If the state has not // been visited yet else if (dp[ind, k] != -1) return dp[ind, k]; // If the state has not been visited else { int ans = 0; // Get the minimum element // in the segment int mini = a[ind]; // Iterate and try to break // at every index // and create a segment for (int i = ind; i < n; i++) { // Find the minimum element // in the segment mini = Math.Min(mini, a[i]); // Find the sum of all the // segments trying all // the possible combinations ans = Math.Max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind,k] = ans; } } // Driver Code public static void Main(String[] args) { int[] a = { 5, 7, 4, 2, 8, 1, 6 }; int k = 3; int n = a.Length; // Initialize dp array with -1 int[,] dp = new int[MAX, MAX]; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) dp[i, j] = -1; } Console.WriteLine( maximizeSum(a, n, 0, k, dp)); }} // This code is contributed by 29AjayKumar
<script> // JavaScript program to find the sum of// the minimum of all the segments var MAX = 10; // Function to maximize the // sum of the minimums function maximizeSum(a , n , ind , k, dp) { // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1000000000; } // If at the end but // k segments are not formed else if (ind == n) return -1000000000; // If the state has not // been visited yet else if (dp[ind][k] != -1) return dp[ind][k]; // If the state has // not been visited else { var ans = 0; // Get the minimum // element in the segment var mini = a[ind]; // Iterate and try to break // at every index // and create a segment for (i = ind; i < n; i++) { // Find the minimum element // in the segment mini = Math.min(mini, a[i]); // Find the sum of all the // segments trying all // the possible combinations ans = Math.max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind][k] = ans; } } // Driver Code var a = [ 5, 7, 4, 2, 8, 1, 6 ]; var k = 3; var n = a.length; // Initialize dp array with -1 var dp = Array(MAX).fill().map(()=>Array(MAX).fill(0)); for (var i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) dp[i][j] = -1; } document.write(maximizeSum(a, n, 0, k, dp)); // This code contributed by Rajput-Ji </script>
13
Time Complexity: O(N * N * K) Auxiliary Space: O(N * K)
SURENDRA_GANGWAR
sanjeev2552
29AjayKumar
shubhamjain0594
Rajput-Ji
sumitgumber28
jainlovely450
Arrays
Dynamic Programming
Recursion
Arrays
Dynamic Programming
Recursion
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n26 May, 2022"
},
{
"code": null,
"e": 214,
"s": 52,
"text": "Given an array a of size N and an integer K, the task is to divide the array into K segments such that sum of the minimum of K segments is maximized. Examples: "
},
{
"code": null,
"e": 451,
"s": 214,
"text": "Input: a[] = {5, 7, 4, 2, 8, 1, 6}, K = 3 Output: 7 Divide the array at indexes 0 and 1. Then the segments are {5}, {7}, {4, 2, 8, 1, 6}. Sum of the minimum is 5 + 7 + 1 = 13 Input: a[] = {6, 5, 3, 8, 9, 10, 4, 7, 10}, K = 4 Output: 27 "
},
{
"code": null,
"e": 865,
"s": 451,
"text": "Approach: The problem can be solved using Dynamic Programming. Try all the possible partitions that are possible using recursion. Let dp[i][k] be the maximum sum of minimums till index i with k partitions. Hence the possible states will be partition at every index from the index i till n. The maximum sum of minimums of all those states will be our answer. After writing this recurrence, we can use memoization. "
},
{
"code": null,
"e": 917,
"s": 865,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 921,
"s": 917,
"text": "C++"
},
{
"code": null,
"e": 926,
"s": 921,
"text": "Java"
},
{
"code": null,
"e": 934,
"s": 926,
"text": "Python3"
},
{
"code": null,
"e": 937,
"s": 934,
"text": "C#"
},
{
"code": null,
"e": 948,
"s": 937,
"text": "Javascript"
},
{
"code": "// C++ program to find the sum of// the minimum of all the segments#include <bits/stdc++.h>using namespace std;const int MAX = 10; // Function to maximize the sum of the minimumsint maximizeSum(int a[], int n, int ind, int k, int dp[MAX][MAX]){ // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1e9; } // If at the end but // k segments are not formed else if (ind == n) return -1e9; // If the state has not been visited yet else if (dp[ind][k] != -1) return dp[ind][k]; // If the state has not been visited else { int ans = 0; // Get the minimum element in the segment int mini = a[ind]; // Iterate and try to break at every index // and create a segment for (int i = ind; i < n; i++) { // Find the minimum element in the segment mini = min(mini, a[i]); // Find the sum of all the segments trying all // the possible combinations ans = max(ans, maximizeSum( a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind][k] = ans; }} // Driver Codeint main(){ int a[] = { 5, 7, 4, 2, 8, 1, 6 }; int k = 3; int n = sizeof(a) / sizeof(a[0]); // Initialize dp array with -1 int dp[MAX][MAX]; memset(dp, -1, sizeof dp); cout << maximizeSum(a, n, 0, k, dp); return 0;}",
"e": 2589,
"s": 948,
"text": null
},
{
"code": "// Java program to find the sum of// the minimum of all the segments class GFG{ static int MAX = 10; // Function to maximize the // sum of the minimums public static int maximizeSum( int[] a, int n, int ind, int k, int[][] dp) { // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1000000000; } // If at the end but // k segments are not formed else if (ind == n) return -1000000000; // If the state has not // been visited yet else if (dp[ind][k] != -1) return dp[ind][k]; // If the state has // not been visited else { int ans = 0; // Get the minimum // element in the segment int mini = a[ind]; // Iterate and try to break // at every index // and create a segment for (int i = ind; i < n; i++) { // Find the minimum element // in the segment mini = Math.min(mini, a[i]); // Find the sum of all the // segments trying all // the possible combinations ans = Math.max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind][k] = ans; } } // Driver Code public static void main(String[] args) { int[] a = { 5, 7, 4, 2, 8, 1, 6 }; int k = 3; int n = a.length; // Initialize dp array with -1 int[][] dp = new int[MAX][MAX]; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) dp[i][j] = -1; } System.out.println( maximizeSum(a, n, 0, k, dp)); }} // This code is contributed by// sanjeev2552",
"e": 4773,
"s": 2589,
"text": null
},
{
"code": "# Python 3 program to find the sum of# the minimum of all the segmentsMAX = 10 # Function to maximize the# sum of the minimumsdef maximizeSum(a,n, ind, k, dp): # If k segments have been divided if (k == 0): # If we are at the end if (ind == n): return 0 # If we donot reach the end # then return a negative number # that cannot be the sum else: return -1e9 # If at the end but # k segments are not formed elif (ind == n): return -1e9 # If the state has been visited already elif (dp[ind][k] != -1): return dp[ind][k] # If the state has not been visited else: ans = 0 # Get the minimum element # in the segment mini = a[ind] # Iterate and try to break # at every index # and create a segment for i in range(ind,n,1): # Find the minimum element # in the segment mini = min(mini, a[i]) # Find the sum of all the # segments trying all # the possible combinations ans = max(ans, maximizeSum(\\ a, n, i + 1, k - 1, dp) + mini) # Return the answer by # memoizing it dp[ind][k] = ans return ans # Driver Codeif __name__ == '__main__': a = [5, 7, 4, 2, 1, 6] k = 3 n = len(a) # Initialize dp array with -1 dp = [[-1 for i in range(MAX)]\\ for j in range(MAX)] print(maximizeSum(a, n, 0, k, dp)) # This code is contributed by# Surendra_Gangwar",
"e": 6328,
"s": 4773,
"text": null
},
{
"code": "// C# program to find the sum of// the minimum of all the segmentsusing System; class GFG{ static int MAX = 10; // Function to maximize the sum of the minimums public static int maximizeSum( int[] a, int n, int ind, int k, int[] dp) { // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1000000000; } // If at the end but // k segments are not formed else if (ind == n) return -1000000000; // If the state has not // been visited yet else if (dp[ind, k] != -1) return dp[ind, k]; // If the state has not been visited else { int ans = 0; // Get the minimum element // in the segment int mini = a[ind]; // Iterate and try to break // at every index // and create a segment for (int i = ind; i < n; i++) { // Find the minimum element // in the segment mini = Math.Min(mini, a[i]); // Find the sum of all the // segments trying all // the possible combinations ans = Math.Max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind,k] = ans; } } // Driver Code public static void Main(String[] args) { int[] a = { 5, 7, 4, 2, 8, 1, 6 }; int k = 3; int n = a.Length; // Initialize dp array with -1 int[,] dp = new int[MAX, MAX]; for (int i = 0; i < MAX; i++) { for (int j = 0; j < MAX; j++) dp[i, j] = -1; } Console.WriteLine( maximizeSum(a, n, 0, k, dp)); }} // This code is contributed by 29AjayKumar",
"e": 8504,
"s": 6328,
"text": null
},
{
"code": "<script> // JavaScript program to find the sum of// the minimum of all the segments var MAX = 10; // Function to maximize the // sum of the minimums function maximizeSum(a , n , ind , k, dp) { // If k segments have been divided if (k == 0) { // If we are at the end if (ind == n) return 0; // If we donot reach the end // then return a negative number // that cannot be the sum else return -1000000000; } // If at the end but // k segments are not formed else if (ind == n) return -1000000000; // If the state has not // been visited yet else if (dp[ind][k] != -1) return dp[ind][k]; // If the state has // not been visited else { var ans = 0; // Get the minimum // element in the segment var mini = a[ind]; // Iterate and try to break // at every index // and create a segment for (i = ind; i < n; i++) { // Find the minimum element // in the segment mini = Math.min(mini, a[i]); // Find the sum of all the // segments trying all // the possible combinations ans = Math.max(ans, maximizeSum(a, n, i + 1, k - 1, dp) + mini); } // Return the answer by // memoizing it return dp[ind][k] = ans; } } // Driver Code var a = [ 5, 7, 4, 2, 8, 1, 6 ]; var k = 3; var n = a.length; // Initialize dp array with -1 var dp = Array(MAX).fill().map(()=>Array(MAX).fill(0)); for (var i = 0; i < MAX; i++) { for (j = 0; j < MAX; j++) dp[i][j] = -1; } document.write(maximizeSum(a, n, 0, k, dp)); // This code contributed by Rajput-Ji </script>",
"e": 10522,
"s": 8504,
"text": null
},
{
"code": null,
"e": 10525,
"s": 10522,
"text": "13"
},
{
"code": null,
"e": 10581,
"s": 10525,
"text": "Time Complexity: O(N * N * K) Auxiliary Space: O(N * K)"
},
{
"code": null,
"e": 10598,
"s": 10581,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 10610,
"s": 10598,
"text": "sanjeev2552"
},
{
"code": null,
"e": 10622,
"s": 10610,
"text": "29AjayKumar"
},
{
"code": null,
"e": 10638,
"s": 10622,
"text": "shubhamjain0594"
},
{
"code": null,
"e": 10648,
"s": 10638,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 10662,
"s": 10648,
"text": "sumitgumber28"
},
{
"code": null,
"e": 10676,
"s": 10662,
"text": "jainlovely450"
},
{
"code": null,
"e": 10683,
"s": 10676,
"text": "Arrays"
},
{
"code": null,
"e": 10703,
"s": 10683,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10713,
"s": 10703,
"text": "Recursion"
},
{
"code": null,
"e": 10720,
"s": 10713,
"text": "Arrays"
},
{
"code": null,
"e": 10740,
"s": 10720,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 10750,
"s": 10740,
"text": "Recursion"
}
] |
Why Python is called Dynamically Typed? | 16 Sep, 2018
Python variable assignment is different from some of the popular languages like c, c++ and java. There is no declaration of a variable, just an assignment statement.
Let us see why?When we declare a variable in C or alike languages, this sets aside an area of memory for holding values allowed by the data type of the variable. The memory allocated will be interpreted as the data type suggests. If it’s an integer variable the memory allocated will be read as an integer and so on. When we assign or initialize it with some value, that value will get stored at that memory location. At compile time, initial value or assigned value will be checked. So we cannot mix types. Example: initializing a string value to an int variable is not allowed and the program will not compile.
But Python is a dynamically typed language. It doesn’t know about the type of the variable until the code is run. So declaration is of no use. What it does is, It stores that value at some memory location and then binds that variable name to that memory container. And makes the contents of the container accessible through that variable name. So the data type does not matter. As it will get to know the type of the value at run-time.
# This will store 6 in the memory and binds the# name x to it. After it runs, type of x will# be int.x = 6 print(type(x)) # This will store 'hello' at some location int # the memory and binds name x to it. After it# runs type of x will be str.x = 'hello' print(type(x))
<class 'int'>
<class 'str'>
python-basics
Python-Data Type
Python-datatype
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n16 Sep, 2018"
},
{
"code": null,
"e": 220,
"s": 54,
"text": "Python variable assignment is different from some of the popular languages like c, c++ and java. There is no declaration of a variable, just an assignment statement."
},
{
"code": null,
"e": 833,
"s": 220,
"text": "Let us see why?When we declare a variable in C or alike languages, this sets aside an area of memory for holding values allowed by the data type of the variable. The memory allocated will be interpreted as the data type suggests. If it’s an integer variable the memory allocated will be read as an integer and so on. When we assign or initialize it with some value, that value will get stored at that memory location. At compile time, initial value or assigned value will be checked. So we cannot mix types. Example: initializing a string value to an int variable is not allowed and the program will not compile."
},
{
"code": null,
"e": 1269,
"s": 833,
"text": "But Python is a dynamically typed language. It doesn’t know about the type of the variable until the code is run. So declaration is of no use. What it does is, It stores that value at some memory location and then binds that variable name to that memory container. And makes the contents of the container accessible through that variable name. So the data type does not matter. As it will get to know the type of the value at run-time."
},
{
"code": "# This will store 6 in the memory and binds the# name x to it. After it runs, type of x will# be int.x = 6 print(type(x)) # This will store 'hello' at some location int # the memory and binds name x to it. After it# runs type of x will be str.x = 'hello' print(type(x))",
"e": 1546,
"s": 1269,
"text": null
},
{
"code": null,
"e": 1575,
"s": 1546,
"text": "<class 'int'>\n<class 'str'>\n"
},
{
"code": null,
"e": 1589,
"s": 1575,
"text": "python-basics"
},
{
"code": null,
"e": 1606,
"s": 1589,
"text": "Python-Data Type"
},
{
"code": null,
"e": 1622,
"s": 1606,
"text": "Python-datatype"
},
{
"code": null,
"e": 1629,
"s": 1622,
"text": "Python"
},
{
"code": null,
"e": 1645,
"s": 1629,
"text": "Python Programs"
}
] |
How to send email verification link with firebase using ReactJS? | 12 Apr, 2021
In this article we are going to see how to send an email verification link with firebase using React.js.
For Setup a firebase (Setup a Firebase for your React Project).
Creating React Application And Installing Module.
Step 1: Create a React myapp using the following command.npx create-react-app myapp
Step 1: Create a React myapp using the following command.
npx create-react-app myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command.cd myapp
Step 2: After creating your project folder i.e. myapp, move to it using the following command.
cd myapp
Project structure: The project structure will look like this.
Step 3: After creating the ReactJS application, Install the firebase module using the following command.
npm install [email protected] --save
Step 4: Go to your firebase dashboard and create a new project and copy your credentials.
const firebaseConfig = {
apiKey: "your api key",
authDomain: "your credentials",
projectId: "your credentials",
storageBucket: "your credentials",
messagingSenderId: "your credentials",
appId: "your credentials"
};
Step 5: Now Enable the sign in with email and password from your sign-in method.
Example: Initialize the firebase into your project by creating firebase.js file with the following code.
firebase.js
import firebase from 'firebase'; const firebaseConfig = { // Your credentials}; firebase.initializeApp(firebaseConfig);var auth = firebase.auth();export default auth;
Now write some code into your App.js file.
App.js
import auth from './firebase';import './App.css';import {useState} from 'react'; function App() { const [email , setemail] = useState(''); const [password , setpassword] = useState(''); const signup = ()=>{ auth.createUserWithEmailAndPassword(email , password) .then((userCredential)=>{ // send verification mail. userCredential.user.sendEmailVerification(); auth.signOut(); alert("Email sent"); }) .catch(alert); } return ( <div className="App"> <br/><br/> <input type="email" placeholder="Email" onChange={(e)=>{setemail(e.target.value)}}> </input> <br/><br/> <input type="password" placeholder="password" onChange={(e)=>{setpassword(e.target.value)}}> </input> <br/><br/> <button onClick={signup}>Sign-up</button> </div> );} export default App;
Output :
Here, When you click on sign-up button the verification email is send to the provided email address.
Here is the verification mail.
Firebase
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n12 Apr, 2021"
},
{
"code": null,
"e": 160,
"s": 54,
"text": "In this article we are going to see how to send an email verification link with firebase using React.js. "
},
{
"code": null,
"e": 224,
"s": 160,
"text": "For Setup a firebase (Setup a Firebase for your React Project)."
},
{
"code": null,
"e": 274,
"s": 224,
"text": "Creating React Application And Installing Module."
},
{
"code": null,
"e": 358,
"s": 274,
"text": "Step 1: Create a React myapp using the following command.npx create-react-app myapp"
},
{
"code": null,
"e": 416,
"s": 358,
"text": "Step 1: Create a React myapp using the following command."
},
{
"code": null,
"e": 443,
"s": 416,
"text": "npx create-react-app myapp"
},
{
"code": null,
"e": 546,
"s": 443,
"text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command.cd myapp"
},
{
"code": null,
"e": 641,
"s": 546,
"text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command."
},
{
"code": null,
"e": 650,
"s": 641,
"text": "cd myapp"
},
{
"code": null,
"e": 712,
"s": 650,
"text": "Project structure: The project structure will look like this."
},
{
"code": null,
"e": 817,
"s": 712,
"text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command."
},
{
"code": null,
"e": 851,
"s": 817,
"text": "npm install [email protected] --save"
},
{
"code": null,
"e": 941,
"s": 851,
"text": "Step 4: Go to your firebase dashboard and create a new project and copy your credentials."
},
{
"code": null,
"e": 1192,
"s": 941,
"text": "const firebaseConfig = {\n apiKey: \"your api key\",\n authDomain: \"your credentials\",\n projectId: \"your credentials\",\n storageBucket: \"your credentials\",\n messagingSenderId: \"your credentials\",\n appId: \"your credentials\"\n};"
},
{
"code": null,
"e": 1273,
"s": 1192,
"text": "Step 5: Now Enable the sign in with email and password from your sign-in method."
},
{
"code": null,
"e": 1378,
"s": 1273,
"text": "Example: Initialize the firebase into your project by creating firebase.js file with the following code."
},
{
"code": null,
"e": 1390,
"s": 1378,
"text": "firebase.js"
},
{
"code": "import firebase from 'firebase'; const firebaseConfig = { // Your credentials}; firebase.initializeApp(firebaseConfig);var auth = firebase.auth();export default auth;",
"e": 1562,
"s": 1390,
"text": null
},
{
"code": null,
"e": 1606,
"s": 1562,
"text": "Now write some code into your App.js file. "
},
{
"code": null,
"e": 1613,
"s": 1606,
"text": "App.js"
},
{
"code": "import auth from './firebase';import './App.css';import {useState} from 'react'; function App() { const [email , setemail] = useState(''); const [password , setpassword] = useState(''); const signup = ()=>{ auth.createUserWithEmailAndPassword(email , password) .then((userCredential)=>{ // send verification mail. userCredential.user.sendEmailVerification(); auth.signOut(); alert(\"Email sent\"); }) .catch(alert); } return ( <div className=\"App\"> <br/><br/> <input type=\"email\" placeholder=\"Email\" onChange={(e)=>{setemail(e.target.value)}}> </input> <br/><br/> <input type=\"password\" placeholder=\"password\" onChange={(e)=>{setpassword(e.target.value)}}> </input> <br/><br/> <button onClick={signup}>Sign-up</button> </div> );} export default App;",
"e": 2483,
"s": 1613,
"text": null
},
{
"code": null,
"e": 2493,
"s": 2483,
"text": "Output : "
},
{
"code": null,
"e": 2594,
"s": 2493,
"text": "Here, When you click on sign-up button the verification email is send to the provided email address."
},
{
"code": null,
"e": 2626,
"s": 2594,
"text": "Here is the verification mail. "
},
{
"code": null,
"e": 2635,
"s": 2626,
"text": "Firebase"
},
{
"code": null,
"e": 2651,
"s": 2635,
"text": "React-Questions"
},
{
"code": null,
"e": 2659,
"s": 2651,
"text": "ReactJS"
},
{
"code": null,
"e": 2676,
"s": 2659,
"text": "Web Technologies"
}
] |
Set in C++ Standard Template Library (STL)
| 06 Jul, 2022
Sets are a type of associative containers in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order.
Syntax:
set<datatype> setname;
Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc.
Example:
set<int> val; // defining an empty set
set<int> val = {6, 10, 5, 1}; // defining a set with values
Note: set<datatype, greater<datatype>> setname; is used for storing values in a set in descending order.
Properties:
The set stores the elements in sorted order.
All the elements in a set have unique values.
The value of the element cannot be modified once it is added to the set, though it is possible to remove and then add the modified value of that element. Thus, the values are immutable.
Sets follow the Binary search tree implementation.
The values in a set are unindexed.
The set stores the elements in sorted order.
All the elements in a set have unique values.
The value of the element cannot be modified once it is added to the set, though it is possible to remove and then add the modified value of that element. Thus, the values are immutable.
Sets follow the Binary search tree implementation.
The values in a set are unindexed.
Note: To store the elements in an unsorted(random) order, unordered_set() can be used.
Some Basic Functions Associated with Set:
begin() – Returns an iterator to the first element in the set.
end() – Returns an iterator to the theoretical element that follows the last element in the set.
size() – Returns the number of elements in the set.
max_size() – Returns the maximum number of elements that the set can hold.
empty() – Returns whether the set is empty.
The time complexities for doing various operations on sets are –
Insertion of Elements – O(log N)
Deletion of Elements – O(log N)
CPP
// CPP program to demonstrate various functions of
// Set in C++ STL
#include <iostream>
#include <iterator>
#include <set>
using namespace std;
int main()
{
// empty set container
set<int, greater<int> > s1;
// insert elements in random order
s1.insert(40);
s1.insert(30);
s1.insert(60);
s1.insert(20);
s1.insert(50);
// only one 50 will be added to the set
s1.insert(50);
s1.insert(10);
// printing set s1
set<int, greater<int> >::iterator itr;
cout << "\nThe set s1 is : \n";
for (itr = s1.begin(); itr != s1.end(); itr++) {
cout << *itr << " ";
}
cout << endl;
// assigning the elements from s1 to s2
set<int> s2(s1.begin(), s1.end());
// print all elements of the set s2
cout << "\nThe set s2 after assign from s1 is : \n";
for (itr = s2.begin(); itr != s2.end(); itr++) {
cout << *itr << " ";
}
cout << endl;
// remove all elements up to 30 in s2
cout << "\ns2 after removal of elements less than 30 "
":\n";
s2.erase(s2.begin(), s2.find(30));
for (itr = s2.begin(); itr != s2.end(); itr++) {
cout << *itr << " ";
}
// remove element with value 50 in s2
int num;
num = s2.erase(50);
cout << "\ns2.erase(50) : ";
cout << num << " removed\n";
for (itr = s2.begin(); itr != s2.end(); itr++) {
cout << *itr << " ";
}
cout << endl;
// lower bound and upper bound for set s1
cout << "s1.lower_bound(40) : \n"
<< *s1.lower_bound(40) << endl;
cout << "s1.upper_bound(40) : \n"
<< *s1.upper_bound(40) << endl;
// lower bound and upper bound for set s2
cout << "s2.lower_bound(40) :\n"
<< *s2.lower_bound(40) << endl;
cout << "s2.upper_bound(40) : \n"
<< *s2.upper_bound(40) << endl;
return 0;
}
The set s1 is :
60 50 40 30 20 10
The set s2 after assign from s1 is :
10 20 30 40 50 60
s2 after removal of elements less than 30 :
30 40 50 60
s2.erase(50) : 1 removed
30 40 60
s1.lower_bound(40) :
40
s1.upper_bound(40) :
30
s2.lower_bound(40) :
40
s2.upper_bound(40) :
60
Must Read: Sets vs Unordered Set
C++ Programming Language Tutorial | Set in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersC++ Programming Language Tutorial | Set in C++ STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:55•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=YuZPHhniZtw" 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
BabisSarantoglou
sriphanivardhan
soumelzutshi
prateeksharan4
akgupta0777
yashvardhanudia
anshikajain26
utkarshgupta110092
cpp-containers-library
cpp-set
STL
C++
Mathematical
Mathematical
STL
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 57,
"s": 26,
"text": " \n06 Jul, 2022\n"
},
{
"code": null,
"e": 230,
"s": 57,
"text": "Sets are a type of associative containers in which each element has to be unique because the value of the element identifies it. The values are stored in a specific order. "
},
{
"code": null,
"e": 238,
"s": 230,
"text": "Syntax:"
},
{
"code": null,
"e": 261,
"s": 238,
"text": "set<datatype> setname;"
},
{
"code": null,
"e": 351,
"s": 261,
"text": "Datatype: Set can take any data type depending on the values, e.g. int, char, float, etc."
},
{
"code": null,
"e": 360,
"s": 351,
"text": "Example:"
},
{
"code": null,
"e": 459,
"s": 360,
"text": "set<int> val; // defining an empty set\nset<int> val = {6, 10, 5, 1}; // defining a set with values"
},
{
"code": null,
"e": 564,
"s": 459,
"text": "Note: set<datatype, greater<datatype>> setname; is used for storing values in a set in descending order."
},
{
"code": null,
"e": 576,
"s": 564,
"text": "Properties:"
},
{
"code": null,
"e": 941,
"s": 576,
"text": "\nThe set stores the elements in sorted order.\nAll the elements in a set have unique values.\nThe value of the element cannot be modified once it is added to the set, though it is possible to remove and then add the modified value of that element. Thus, the values are immutable.\nSets follow the Binary search tree implementation.\nThe values in a set are unindexed.\n"
},
{
"code": null,
"e": 986,
"s": 941,
"text": "The set stores the elements in sorted order."
},
{
"code": null,
"e": 1032,
"s": 986,
"text": "All the elements in a set have unique values."
},
{
"code": null,
"e": 1218,
"s": 1032,
"text": "The value of the element cannot be modified once it is added to the set, though it is possible to remove and then add the modified value of that element. Thus, the values are immutable."
},
{
"code": null,
"e": 1269,
"s": 1218,
"text": "Sets follow the Binary search tree implementation."
},
{
"code": null,
"e": 1304,
"s": 1269,
"text": "The values in a set are unindexed."
},
{
"code": null,
"e": 1392,
"s": 1304,
"text": "Note: To store the elements in an unsorted(random) order, unordered_set() can be used."
},
{
"code": null,
"e": 1435,
"s": 1392,
"text": "Some Basic Functions Associated with Set: "
},
{
"code": null,
"e": 1498,
"s": 1435,
"text": "begin() – Returns an iterator to the first element in the set."
},
{
"code": null,
"e": 1595,
"s": 1498,
"text": "end() – Returns an iterator to the theoretical element that follows the last element in the set."
},
{
"code": null,
"e": 1647,
"s": 1595,
"text": "size() – Returns the number of elements in the set."
},
{
"code": null,
"e": 1722,
"s": 1647,
"text": "max_size() – Returns the maximum number of elements that the set can hold."
},
{
"code": null,
"e": 1766,
"s": 1722,
"text": "empty() – Returns whether the set is empty."
},
{
"code": null,
"e": 1831,
"s": 1766,
"text": "The time complexities for doing various operations on sets are –"
},
{
"code": null,
"e": 1864,
"s": 1831,
"text": "Insertion of Elements – O(log N)"
},
{
"code": null,
"e": 1896,
"s": 1864,
"text": "Deletion of Elements – O(log N)"
},
{
"code": null,
"e": 1900,
"s": 1896,
"text": "CPP"
},
{
"code": "\n\n\n\n\n\n\n// CPP program to demonstrate various functions of \n// Set in C++ STL \n#include <iostream> \n#include <iterator> \n#include <set> \n \nusing namespace std; \n \nint main() \n{ \n // empty set container \n set<int, greater<int> > s1; \n \n // insert elements in random order \n s1.insert(40); \n s1.insert(30); \n s1.insert(60); \n s1.insert(20); \n s1.insert(50); \n \n // only one 50 will be added to the set \n s1.insert(50); \n s1.insert(10); \n \n // printing set s1 \n set<int, greater<int> >::iterator itr; \n cout << \"\\nThe set s1 is : \\n\"; \n for (itr = s1.begin(); itr != s1.end(); itr++) { \n cout << *itr << \" \"; \n } \n cout << endl; \n \n // assigning the elements from s1 to s2 \n set<int> s2(s1.begin(), s1.end()); \n \n // print all elements of the set s2 \n cout << \"\\nThe set s2 after assign from s1 is : \\n\"; \n for (itr = s2.begin(); itr != s2.end(); itr++) { \n cout << *itr << \" \"; \n } \n cout << endl; \n \n // remove all elements up to 30 in s2 \n cout << \"\\ns2 after removal of elements less than 30 \"\n \":\\n\"; \n s2.erase(s2.begin(), s2.find(30)); \n for (itr = s2.begin(); itr != s2.end(); itr++) { \n cout << *itr << \" \"; \n } \n \n // remove element with value 50 in s2 \n int num; \n num = s2.erase(50); \n cout << \"\\ns2.erase(50) : \"; \n cout << num << \" removed\\n\"; \n for (itr = s2.begin(); itr != s2.end(); itr++) { \n cout << *itr << \" \"; \n } \n \n cout << endl; \n \n // lower bound and upper bound for set s1 \n cout << \"s1.lower_bound(40) : \\n\"\n << *s1.lower_bound(40) << endl; \n cout << \"s1.upper_bound(40) : \\n\"\n << *s1.upper_bound(40) << endl; \n \n // lower bound and upper bound for set s2 \n cout << \"s2.lower_bound(40) :\\n\"\n << *s2.lower_bound(40) << endl; \n cout << \"s2.upper_bound(40) : \\n\"\n << *s2.upper_bound(40) << endl; \n \n return 0; \n}\n\n\n\n\n\n",
"e": 3866,
"s": 1910,
"text": null
},
{
"code": null,
"e": 4152,
"s": 3866,
"text": "The set s1 is : \n60 50 40 30 20 10 \n\nThe set s2 after assign from s1 is : \n10 20 30 40 50 60 \n\ns2 after removal of elements less than 30 :\n30 40 50 60 \ns2.erase(50) : 1 removed\n30 40 60 \ns1.lower_bound(40) : \n40\ns1.upper_bound(40) : \n30\ns2.lower_bound(40) :\n40\ns2.upper_bound(40) : \n60"
},
{
"code": null,
"e": 4185,
"s": 4152,
"text": "Must Read: Sets vs Unordered Set"
},
{
"code": null,
"e": 5103,
"s": 4185,
"text": "C++ Programming Language Tutorial | Set in C++ STL | GeeksforGeeks - YouTubeGeeksforGeeks532K subscribersC++ Programming Language Tutorial | Set in C++ STL | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 2:55•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=YuZPHhniZtw\" 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": 5227,
"s": 5103,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above"
},
{
"code": null,
"e": 5244,
"s": 5227,
"text": "BabisSarantoglou"
},
{
"code": null,
"e": 5260,
"s": 5244,
"text": "sriphanivardhan"
},
{
"code": null,
"e": 5273,
"s": 5260,
"text": "soumelzutshi"
},
{
"code": null,
"e": 5288,
"s": 5273,
"text": "prateeksharan4"
},
{
"code": null,
"e": 5300,
"s": 5288,
"text": "akgupta0777"
},
{
"code": null,
"e": 5316,
"s": 5300,
"text": "yashvardhanudia"
},
{
"code": null,
"e": 5330,
"s": 5316,
"text": "anshikajain26"
},
{
"code": null,
"e": 5349,
"s": 5330,
"text": "utkarshgupta110092"
},
{
"code": null,
"e": 5374,
"s": 5349,
"text": "\ncpp-containers-library\n"
},
{
"code": null,
"e": 5384,
"s": 5374,
"text": "\ncpp-set\n"
},
{
"code": null,
"e": 5390,
"s": 5384,
"text": "\nSTL\n"
},
{
"code": null,
"e": 5396,
"s": 5390,
"text": "\nC++\n"
},
{
"code": null,
"e": 5411,
"s": 5396,
"text": "\nMathematical\n"
},
{
"code": null,
"e": 5424,
"s": 5411,
"text": "Mathematical"
},
{
"code": null,
"e": 5428,
"s": 5424,
"text": "STL"
},
{
"code": null,
"e": 5432,
"s": 5428,
"text": "CPP"
}
] |
ord() function in Python | 23 Sep, 2021
Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a Unicode object, or the value of the byte when the argument is an 8-bit string.
Syntax: ord(ch)
ch – A unicode character
For example, ord(‘a’) returns the integer 97, ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive.
Note: If the string length is more than one, and a TypeError will be raised. The syntax can be ord(“a”) or ord(‘a’), both will give same results.
Python
# inbuilt function return an# integer representing the Unicode codevalue = ord("A") # writing in ' ' gives the same resultvalue1 = ord('A') # prints the unicode valueprint (value, value1)
Output:
65 65
A TypeError is raised when the length of the string is not equal to 1 as shown below:
Python3
# inbuilt function return an# integer representing the Unicode code# demonstrating exception # Raises Exceptionvalue1 = ord('AB') # prints the unicode valueprint(value1)
Output:
Traceback (most recent call last):
File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in
value1 = ord(‘AB’)
TypeError: ord() expected a character, but string of length 2 found
The chr() method returns a string representing a character whose Unicode code point is an integer.
Syntax: chr(num)
num : integer value
Where ord() methods work on opposite for chr() function:
Python3
# inbuilt function return an# integer representing the Unicode codevalue = ord("A") # prints the unicode valueprint (value) # print the characterprint(chr(value))
Output:
65
A
manjeet_04
RajuKumar19
kumar_satyam
gabaa406
Python-Built-in-functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n23 Sep, 2021"
},
{
"code": null,
"e": 482,
"s": 54,
"text": "Python ord() function returns the Unicode code from a given character. This function accepts a string of unit length as an argument and returns the Unicode equivalence of the passed argument. In other words, given a string of length 1, the ord() function returns an integer representing the Unicode code point of the character when an argument is a Unicode object, or the value of the byte when the argument is an 8-bit string."
},
{
"code": null,
"e": 499,
"s": 482,
"text": "Syntax: ord(ch)"
},
{
"code": null,
"e": 524,
"s": 499,
"text": "ch – A unicode character"
},
{
"code": null,
"e": 835,
"s": 524,
"text": "For example, ord(‘a’) returns the integer 97, ord(‘€’) (Euro sign) returns 8364. This is the inverse of chr() for 8-bit strings and of unichr() for Unicode objects. If a Unicode argument is given and Python is built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive. "
},
{
"code": null,
"e": 982,
"s": 835,
"text": "Note: If the string length is more than one, and a TypeError will be raised. The syntax can be ord(“a”) or ord(‘a’), both will give same results. "
},
{
"code": null,
"e": 989,
"s": 982,
"text": "Python"
},
{
"code": "# inbuilt function return an# integer representing the Unicode codevalue = ord(\"A\") # writing in ' ' gives the same resultvalue1 = ord('A') # prints the unicode valueprint (value, value1)",
"e": 1177,
"s": 989,
"text": null
},
{
"code": null,
"e": 1186,
"s": 1177,
"text": "Output: "
},
{
"code": null,
"e": 1192,
"s": 1186,
"text": "65 65"
},
{
"code": null,
"e": 1278,
"s": 1192,
"text": "A TypeError is raised when the length of the string is not equal to 1 as shown below:"
},
{
"code": null,
"e": 1286,
"s": 1278,
"text": "Python3"
},
{
"code": "# inbuilt function return an# integer representing the Unicode code# demonstrating exception # Raises Exceptionvalue1 = ord('AB') # prints the unicode valueprint(value1)",
"e": 1456,
"s": 1286,
"text": null
},
{
"code": null,
"e": 1464,
"s": 1456,
"text": "Output:"
},
{
"code": null,
"e": 1499,
"s": 1464,
"text": "Traceback (most recent call last):"
},
{
"code": null,
"e": 1563,
"s": 1499,
"text": " File “/home/f988dfe667cdc9a8e5658464c87ccd18.py”, line 6, in "
},
{
"code": null,
"e": 1586,
"s": 1563,
"text": " value1 = ord(‘AB’)"
},
{
"code": null,
"e": 1654,
"s": 1586,
"text": "TypeError: ord() expected a character, but string of length 2 found"
},
{
"code": null,
"e": 1753,
"s": 1654,
"text": "The chr() method returns a string representing a character whose Unicode code point is an integer."
},
{
"code": null,
"e": 1770,
"s": 1753,
"text": "Syntax: chr(num)"
},
{
"code": null,
"e": 1790,
"s": 1770,
"text": "num : integer value"
},
{
"code": null,
"e": 1847,
"s": 1790,
"text": "Where ord() methods work on opposite for chr() function:"
},
{
"code": null,
"e": 1855,
"s": 1847,
"text": "Python3"
},
{
"code": "# inbuilt function return an# integer representing the Unicode codevalue = ord(\"A\") # prints the unicode valueprint (value) # print the characterprint(chr(value))",
"e": 2018,
"s": 1855,
"text": null
},
{
"code": null,
"e": 2026,
"s": 2018,
"text": "Output:"
},
{
"code": null,
"e": 2031,
"s": 2026,
"text": "65\nA"
},
{
"code": null,
"e": 2042,
"s": 2031,
"text": "manjeet_04"
},
{
"code": null,
"e": 2054,
"s": 2042,
"text": "RajuKumar19"
},
{
"code": null,
"e": 2067,
"s": 2054,
"text": "kumar_satyam"
},
{
"code": null,
"e": 2076,
"s": 2067,
"text": "gabaa406"
},
{
"code": null,
"e": 2102,
"s": 2076,
"text": "Python-Built-in-functions"
},
{
"code": null,
"e": 2109,
"s": 2102,
"text": "Python"
}
] |
Mosaic Plot in R Programming | 30 Jun, 2021
Mosaic Plots are used to show symmetries for tables that are divided into two or more conditional distributions. Mosaic plots are a great way to visualize hierarchical data. A collection of rectangles represents all the elements to be visualized with the rectangles of different sizes and colors makes a table, but what makes these mosaic charts unique is the arrangement of the elements where there is a hierarchy those elements are collected and labeled together, perhaps even with subcategories. So mosaic plots can be used for plotting categorical data very effectively, with the area of the data showing the relative proportions.
In this article, we will learn how to create a mosaic plot in R programming language. The package that is used for this is vcd.
The function used for creating a mosaic plot in R programming language is mosaic().
Syntax:
mosaic(x,shade=NULL,legend=NULL, main = NULL,..)
Parameters:
x: Here, x is pointing to the variable that holds the dataset/table. We passed our dataset name here.
shade: shade is a boolean variable, if it is set to be true then we will get a colored plot. Its default value is NULL.
legend: the legend is a boolean variable, if it is set to be true then we will be able to see legends alongside our mosaic plot. Its default value is NULL.
main: main is a string variable, here we pass the title of our mosaic plot.
To create a plot, first the package is loaded into space, and the dataset is created. The created dataset is passed to the function.
Example 1:
R
library('vcd') # creating a random dataset # creating 6 rowsdata_values <- matrix(c(80, 10, 15, 70, 86, 18, 60, 30, 12, 90, 20, 25, 60, 96, 88, 50, 20, 32)) # creating dataset with above valuesdata <- as.table( matrix( data_values, # specifying the number of rows nrow = 6, byrow = TRUE, # creating two lists one for rows # and one for columns dimnames = list( Random_Rows = c('A','B','C', 'D', 'E', 'F'), Random_Columns = c('col_1', 'col_2', 'col_3') ) ) ) # plotting the mosaic chartmosaic(data)
Output:
simple mosaic plot
A mosaic plot can also be drawn with custom features to make it more presentable.
Example 2:
R
library('vcd') # creating a random dataset # creating 6 rowsdata_values <- matrix(c(80, 10, 15, 70, 86, 18, 60, 30, 12, 90, 20, 25, 60, 96, 88, 50, 20, 32)) # creating dataset with above valuesdata <- as.table( matrix( data_values, # specifying the number of rows nrow = 6, byrow = TRUE, # creating two lists one for rows # and one for columns dimnames = list( Random_Rows = c('A','B','C', 'D', 'E', 'F'), Random_Columns = c('col_1', 'col_2', 'col_3') ) ) ) # plotting the mosaic chartmosaic(data, # shade is used to plot colored chart shade=TRUE, # adding title to the chart main = "A Mosaic Plot")
Output:
A simple mosaic plot
Picked
R-Charts
R-Graphs
R-plots
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 663,
"s": 28,
"text": "Mosaic Plots are used to show symmetries for tables that are divided into two or more conditional distributions. Mosaic plots are a great way to visualize hierarchical data. A collection of rectangles represents all the elements to be visualized with the rectangles of different sizes and colors makes a table, but what makes these mosaic charts unique is the arrangement of the elements where there is a hierarchy those elements are collected and labeled together, perhaps even with subcategories. So mosaic plots can be used for plotting categorical data very effectively, with the area of the data showing the relative proportions."
},
{
"code": null,
"e": 791,
"s": 663,
"text": "In this article, we will learn how to create a mosaic plot in R programming language. The package that is used for this is vcd."
},
{
"code": null,
"e": 875,
"s": 791,
"text": "The function used for creating a mosaic plot in R programming language is mosaic()."
},
{
"code": null,
"e": 883,
"s": 875,
"text": "Syntax:"
},
{
"code": null,
"e": 932,
"s": 883,
"text": "mosaic(x,shade=NULL,legend=NULL, main = NULL,..)"
},
{
"code": null,
"e": 944,
"s": 932,
"text": "Parameters:"
},
{
"code": null,
"e": 1046,
"s": 944,
"text": "x: Here, x is pointing to the variable that holds the dataset/table. We passed our dataset name here."
},
{
"code": null,
"e": 1166,
"s": 1046,
"text": "shade: shade is a boolean variable, if it is set to be true then we will get a colored plot. Its default value is NULL."
},
{
"code": null,
"e": 1322,
"s": 1166,
"text": "legend: the legend is a boolean variable, if it is set to be true then we will be able to see legends alongside our mosaic plot. Its default value is NULL."
},
{
"code": null,
"e": 1398,
"s": 1322,
"text": "main: main is a string variable, here we pass the title of our mosaic plot."
},
{
"code": null,
"e": 1531,
"s": 1398,
"text": "To create a plot, first the package is loaded into space, and the dataset is created. The created dataset is passed to the function."
},
{
"code": null,
"e": 1542,
"s": 1531,
"text": "Example 1:"
},
{
"code": null,
"e": 1544,
"s": 1542,
"text": "R"
},
{
"code": "library('vcd') # creating a random dataset # creating 6 rowsdata_values <- matrix(c(80, 10, 15, 70, 86, 18, 60, 30, 12, 90, 20, 25, 60, 96, 88, 50, 20, 32)) # creating dataset with above valuesdata <- as.table( matrix( data_values, # specifying the number of rows nrow = 6, byrow = TRUE, # creating two lists one for rows # and one for columns dimnames = list( Random_Rows = c('A','B','C', 'D', 'E', 'F'), Random_Columns = c('col_1', 'col_2', 'col_3') ) ) ) # plotting the mosaic chartmosaic(data)",
"e": 2215,
"s": 1544,
"text": null
},
{
"code": null,
"e": 2223,
"s": 2215,
"text": "Output:"
},
{
"code": null,
"e": 2242,
"s": 2223,
"text": "simple mosaic plot"
},
{
"code": null,
"e": 2324,
"s": 2242,
"text": "A mosaic plot can also be drawn with custom features to make it more presentable."
},
{
"code": null,
"e": 2335,
"s": 2324,
"text": "Example 2:"
},
{
"code": null,
"e": 2337,
"s": 2335,
"text": "R"
},
{
"code": "library('vcd') # creating a random dataset # creating 6 rowsdata_values <- matrix(c(80, 10, 15, 70, 86, 18, 60, 30, 12, 90, 20, 25, 60, 96, 88, 50, 20, 32)) # creating dataset with above valuesdata <- as.table( matrix( data_values, # specifying the number of rows nrow = 6, byrow = TRUE, # creating two lists one for rows # and one for columns dimnames = list( Random_Rows = c('A','B','C', 'D', 'E', 'F'), Random_Columns = c('col_1', 'col_2', 'col_3') ) ) ) # plotting the mosaic chartmosaic(data, # shade is used to plot colored chart shade=TRUE, # adding title to the chart main = \"A Mosaic Plot\")",
"e": 3152,
"s": 2337,
"text": null
},
{
"code": null,
"e": 3160,
"s": 3152,
"text": "Output:"
},
{
"code": null,
"e": 3181,
"s": 3160,
"text": "A simple mosaic plot"
},
{
"code": null,
"e": 3188,
"s": 3181,
"text": "Picked"
},
{
"code": null,
"e": 3197,
"s": 3188,
"text": "R-Charts"
},
{
"code": null,
"e": 3206,
"s": 3197,
"text": "R-Graphs"
},
{
"code": null,
"e": 3214,
"s": 3206,
"text": "R-plots"
},
{
"code": null,
"e": 3225,
"s": 3214,
"text": "R Language"
}
] |
How to create a translucent text input in ReactJS ? | 14 Jan, 2022
In this article, we are going to learn how to create a translucent text input in ReactJS.
Prerequisites:
Knowledge of JavaScript (ES6)Knowledge of HTML/CSS.Basic knowledge of ReactJS.
Knowledge of JavaScript (ES6)
Knowledge of HTML/CSS.
Basic knowledge of ReactJS.
React hooks used in building this application are:
React useState
JavaScript modules:
styled-components
framer-motion
Creating React Application and Installing Modules:
Step 1: Now, you will start a new project using create-react-app so open your terminal and type:
npx create-react-app translucent-input-box
Step 2: After creating your project folder i.e. translucent-input-box , move to it using the following command.
cd translucent-input-box
Step 3: Add the npm packages you will need during the project:
npm install framer-motion styled-components
Step 5: Now open your newly created project and open the src folder and delete the following files (Optional):
logo.svgserviceWorker.jssetupTests.jsindex.cssApp.test.js (if any)
logo.svg
serviceWorker.js
setupTests.js
index.css
App.test.js (if any)
Create a folder named Input and create the following files:
Component.jsx
Component.motion.js
Component.styles.js
Project structure: It will look like this.
Project structure
Approach:
We are going to create a translucent animated text input using framer-motion and styled components.
Wrapper, Input, Label, Underline are the styled components used to make the text input box collectively in Component.jsx file.
In Component.jsx file, we use framer-motion with custom animation variants from the Component.motion.js file to animate the text input box.
React useState hook is used to manage the state of value that is used as a placeholder attribute & also to set it as a label when active.
Framer-motion useCycle hook is similar to react useState hook. It cycles through a series of visual properties used for animation. It is used to toggle between or cycle through animation variants.
import React, { useState } from "react";
import "./App.css";
import Input from "./Input";
const App = () => {
// The useState hook is used to manage the state of
// "value" that is used as placeholder attribute
// and also to set it as a label when clicked
const [value, setValue] = useState("");
return (
<div className="App">
<div className="container">
{/* "Input" component created using styled-components
and animated using framer-motion
*/}
<Input
value={value}
onChange={(id, value) => setValue(value)}
label={"First name"}
/>
</div>
</div>
);
};
export default App;
import React from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
rootElement
);
.App {
font-family: "Times New Roman", Times, serif;
text-align: center;
width: auto;
height: 98vh;
display: flex;
justify-content: center;
align-items: center;
overflow: hidden;
background: #1e9600; /* fallback for old browsers */
background: -webkit-linear-gradient(
to right,
#ff0000,
#fff200,
#1e9600
); /* Chrome 10-25, Safari 5.1-6 */
background: linear-gradient(
to right,
#ff0000,
#fff200,
#1e9600
);
}
.container {
border-radius: 25px;
width: 50vw;
height: 20vh;
display: flex;
justify-content: center;
align-items: center;
opacity: 0.5;
background-color: #f1f1f1;
}
Input {
text-decoration: none;
background-color: #f1f1f1;
width: 40%;
}
import React from "react";
import { Wrapper, Input, Label, Underline } from "./Component.styles";
import { motionLabel, motionUnderline } from "./Component.motion";
import { useCycle } from "framer-motion";
export default ({ label, value, onChange, id, errors }) => {
const onTapStart = (event, info) => {
focus === "inactive" && cycleFocus();
return blur === "inactive" && cycleBlur();
};
const onBlur = event => {
value === "" && cycleFocus();
cycleBlur();
};
const [focus, cycleFocus] = useCycle("inactive", "active");
const [blur, cycleBlur] = useCycle("inactive", "active");
return (
{/* Wrapper,Label,Underline - custom styled-components with
some of its attributes
*/}
{/* These all collectively make the animated input box which
then given transluscent background using CSS
*/}
<Wrapper>
<Input
onTap={onTapStart}
placeholder={label}
onBlur={e => onBlur(id)}
onChange={e => onChange(id, e.target.value)}
type={"text"}
required
value={value}
/>
<Label {...motionLabel(focus)}>{label}</Label>
<Underline {...motionUnderline(blur)} />
</Wrapper>
);
};
const variantsWrapper = {
initial: {},
in: {},
out: {},
hover: {},
tap: {}
};
const variantsLabel = {
active: {
x: -15,
y: -20,
scale: 0.7
},
inactive: { x: 0, y: 0, scale: 1 }
};
const variantsUnderline = {
active: {
width: "100%",
transition: {
ease: "easeIn",
duration: 0.2
}
},
inactive: {
width: "0",
transition: {
ease: "easeIn",
duration: 0.1
}
}
};
export const motionLabel = state => {
return {
animate: state,
variants: variantsLabel
};
};
export const motionUnderline = state => {
return {
animate: state,
variants: variantsUnderline
};
};
export const animationWrapper = {
initial: "initial",
animate: "in",
exit: "out",
whileHover: "hover",
whileTap: "tap",
variants: variantsWrapper
};
import styled from "styled-components";
import { motion } from "framer-motion";
// Below are the styled-components used to
// make the animated text input box
export const Wrapper = styled(motion.div)`
position: relative;
width: 80%;
padding: 18px;
padding-bottom: 30px;
border-bottom: 1px solid #2f528f;
`;
export const Label = styled(motion.span)`
align-self: center;
position: absolute;
left: 0;
top: 50%;
grid-area: input;
font-family: Montserrat;
font-size: 18px;
line-height: 18px;
text-align: left;
pointer-events: none;
font-weight: normal;
/* background: green; */
`;
export const Input = styled(motion.input)`
height: 18px;
font-size: 18px;
-webkit-appearance: none;
background: transparent !important;
position: absolute;
left: 0;
top: 50%;
padding: 0;
padding-bottom: 5px;
margin: 0;
color: black;
border: none;
box-shadow: none !important;
font-weight: normal;
&:focus {
outline: none;
}
&::placeholder {
color: #f1f1f1;
}
`;
export const Underline = styled(motion.div)`
position: absolute;
background-color: #2f528f;
bottom: 0;
left: 0;
width: 100%;
height: 3px;
`;
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:
adnanirshad158
Picked
React-Hooks
React-Questions
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Jan, 2022"
},
{
"code": null,
"e": 118,
"s": 28,
"text": "In this article, we are going to learn how to create a translucent text input in ReactJS."
},
{
"code": null,
"e": 133,
"s": 118,
"text": "Prerequisites:"
},
{
"code": null,
"e": 212,
"s": 133,
"text": "Knowledge of JavaScript (ES6)Knowledge of HTML/CSS.Basic knowledge of ReactJS."
},
{
"code": null,
"e": 242,
"s": 212,
"text": "Knowledge of JavaScript (ES6)"
},
{
"code": null,
"e": 265,
"s": 242,
"text": "Knowledge of HTML/CSS."
},
{
"code": null,
"e": 293,
"s": 265,
"text": "Basic knowledge of ReactJS."
},
{
"code": null,
"e": 344,
"s": 293,
"text": "React hooks used in building this application are:"
},
{
"code": null,
"e": 359,
"s": 344,
"text": "React useState"
},
{
"code": null,
"e": 379,
"s": 359,
"text": "JavaScript modules:"
},
{
"code": null,
"e": 397,
"s": 379,
"text": "styled-components"
},
{
"code": null,
"e": 412,
"s": 397,
"text": "framer-motion "
},
{
"code": null,
"e": 467,
"s": 416,
"text": "Creating React Application and Installing Modules:"
},
{
"code": null,
"e": 566,
"s": 469,
"text": "Step 1: Now, you will start a new project using create-react-app so open your terminal and type:"
},
{
"code": null,
"e": 611,
"s": 568,
"text": "npx create-react-app translucent-input-box"
},
{
"code": null,
"e": 723,
"s": 611,
"text": "Step 2: After creating your project folder i.e. translucent-input-box , move to it using the following command."
},
{
"code": null,
"e": 750,
"s": 725,
"text": "cd translucent-input-box"
},
{
"code": null,
"e": 813,
"s": 750,
"text": "Step 3: Add the npm packages you will need during the project:"
},
{
"code": null,
"e": 859,
"s": 815,
"text": "npm install framer-motion styled-components"
},
{
"code": null,
"e": 971,
"s": 859,
"text": "Step 5: Now open your newly created project and open the src folder and delete the following files (Optional): "
},
{
"code": null,
"e": 1038,
"s": 971,
"text": "logo.svgserviceWorker.jssetupTests.jsindex.cssApp.test.js (if any)"
},
{
"code": null,
"e": 1047,
"s": 1038,
"text": "logo.svg"
},
{
"code": null,
"e": 1064,
"s": 1047,
"text": "serviceWorker.js"
},
{
"code": null,
"e": 1078,
"s": 1064,
"text": "setupTests.js"
},
{
"code": null,
"e": 1088,
"s": 1078,
"text": "index.css"
},
{
"code": null,
"e": 1109,
"s": 1088,
"text": "App.test.js (if any)"
},
{
"code": null,
"e": 1171,
"s": 1111,
"text": "Create a folder named Input and create the following files:"
},
{
"code": null,
"e": 1187,
"s": 1173,
"text": "Component.jsx"
},
{
"code": null,
"e": 1207,
"s": 1187,
"text": "Component.motion.js"
},
{
"code": null,
"e": 1227,
"s": 1207,
"text": "Component.styles.js"
},
{
"code": null,
"e": 1270,
"s": 1227,
"text": "Project structure: It will look like this."
},
{
"code": null,
"e": 1290,
"s": 1272,
"text": "Project structure"
},
{
"code": null,
"e": 1305,
"s": 1294,
"text": "Approach: "
},
{
"code": null,
"e": 1407,
"s": 1307,
"text": "We are going to create a translucent animated text input using framer-motion and styled components."
},
{
"code": null,
"e": 1534,
"s": 1407,
"text": "Wrapper, Input, Label, Underline are the styled components used to make the text input box collectively in Component.jsx file."
},
{
"code": null,
"e": 1674,
"s": 1534,
"text": "In Component.jsx file, we use framer-motion with custom animation variants from the Component.motion.js file to animate the text input box."
},
{
"code": null,
"e": 1812,
"s": 1674,
"text": "React useState hook is used to manage the state of value that is used as a placeholder attribute & also to set it as a label when active."
},
{
"code": null,
"e": 2009,
"s": 1812,
"text": "Framer-motion useCycle hook is similar to react useState hook. It cycles through a series of visual properties used for animation. It is used to toggle between or cycle through animation variants."
},
{
"code": null,
"e": 2692,
"s": 2011,
"text": "import React, { useState } from \"react\";\nimport \"./App.css\";\n\nimport Input from \"./Input\";\n\nconst App = () => {\n // The useState hook is used to manage the state of \n // \"value\" that is used as placeholder attribute\n // and also to set it as a label when clicked\n const [value, setValue] = useState(\"\");\n \n return (\n <div className=\"App\">\n <div className=\"container\">\n {/* \"Input\" component created using styled-components\n and animated using framer-motion\n */}\n <Input\n value={value}\n onChange={(id, value) => setValue(value)}\n label={\"First name\"}\n />\n </div>\n </div>\n );\n};\n\nexport default App;\n"
},
{
"code": null,
"e": 2924,
"s": 2692,
"text": "import React from \"react\";\nimport ReactDOM from \"react-dom\";\n\nimport App from \"./App\";\n\nconst rootElement = document.getElementById(\"root\");\nReactDOM.render(\n <React.StrictMode>\n <App />\n </React.StrictMode>,\n rootElement\n);\n"
},
{
"code": null,
"e": 3660,
"s": 2924,
"text": ".App {\n font-family: \"Times New Roman\", Times, serif;\n text-align: center;\n\n width: auto;\n height: 98vh;\n\n display: flex;\n justify-content: center;\n align-items: center;\n\n overflow: hidden;\n background: #1e9600; /* fallback for old browsers */\n background: -webkit-linear-gradient(\n to right,\n #ff0000,\n #fff200,\n #1e9600\n ); /* Chrome 10-25, Safari 5.1-6 */\n background: linear-gradient(\n to right,\n #ff0000,\n #fff200,\n #1e9600\n );\n}\n\n.container {\n border-radius: 25px;\n\n width: 50vw;\n height: 20vh;\n\n display: flex;\n justify-content: center;\n align-items: center;\n\n opacity: 0.5;\n background-color: #f1f1f1;\n}\n\nInput {\n text-decoration: none;\n background-color: #f1f1f1;\n width: 40%;\n}"
},
{
"code": null,
"e": 4867,
"s": 3660,
"text": "import React from \"react\";\nimport { Wrapper, Input, Label, Underline } from \"./Component.styles\";\nimport { motionLabel, motionUnderline } from \"./Component.motion\";\nimport { useCycle } from \"framer-motion\";\n\nexport default ({ label, value, onChange, id, errors }) => {\n const onTapStart = (event, info) => {\n focus === \"inactive\" && cycleFocus();\n return blur === \"inactive\" && cycleBlur();\n };\n const onBlur = event => {\n value === \"\" && cycleFocus();\n cycleBlur();\n };\n const [focus, cycleFocus] = useCycle(\"inactive\", \"active\");\n const [blur, cycleBlur] = useCycle(\"inactive\", \"active\");\n return (\n {/* Wrapper,Label,Underline - custom styled-components with \n some of its attributes\n */}\n {/* These all collectively make the animated input box which \n then given transluscent background using CSS\n */} \n <Wrapper>\n <Input\n onTap={onTapStart}\n placeholder={label}\n onBlur={e => onBlur(id)}\n onChange={e => onChange(id, e.target.value)}\n type={\"text\"}\n required\n value={value}\n />\n <Label {...motionLabel(focus)}>{label}</Label>\n <Underline {...motionUnderline(blur)} />\n </Wrapper>\n );\n};\n"
},
{
"code": null,
"e": 5692,
"s": 4867,
"text": "const variantsWrapper = {\n initial: {},\n in: {},\n out: {},\n hover: {},\n tap: {}\n};\n\nconst variantsLabel = {\n active: {\n x: -15,\n y: -20,\n scale: 0.7\n },\n inactive: { x: 0, y: 0, scale: 1 }\n};\nconst variantsUnderline = {\n active: {\n width: \"100%\",\n transition: {\n ease: \"easeIn\",\n duration: 0.2\n }\n },\n inactive: {\n width: \"0\",\n transition: {\n ease: \"easeIn\",\n duration: 0.1\n }\n }\n};\n\nexport const motionLabel = state => {\n return {\n animate: state,\n variants: variantsLabel\n };\n};\n\nexport const motionUnderline = state => {\n return {\n animate: state,\n variants: variantsUnderline\n };\n};\n\nexport const animationWrapper = {\n initial: \"initial\",\n animate: \"in\",\n exit: \"out\",\n whileHover: \"hover\",\n whileTap: \"tap\",\n variants: variantsWrapper\n};\n"
},
{
"code": null,
"e": 6869,
"s": 5692,
"text": "import styled from \"styled-components\";\nimport { motion } from \"framer-motion\";\n\n// Below are the styled-components used to \n// make the animated text input box\n\nexport const Wrapper = styled(motion.div)`\n position: relative;\n width: 80%;\n padding: 18px;\n padding-bottom: 30px;\n border-bottom: 1px solid #2f528f;\n`;\n\nexport const Label = styled(motion.span)`\n align-self: center;\n position: absolute;\n left: 0;\n top: 50%;\n grid-area: input;\n font-family: Montserrat;\n font-size: 18px;\n line-height: 18px;\n text-align: left;\n pointer-events: none;\n font-weight: normal;\n /* background: green; */\n`;\n\nexport const Input = styled(motion.input)`\n height: 18px;\n font-size: 18px;\n -webkit-appearance: none;\n background: transparent !important;\n position: absolute;\n left: 0;\n top: 50%;\n padding: 0;\n padding-bottom: 5px;\n margin: 0;\n color: black;\n border: none;\n box-shadow: none !important;\n font-weight: normal;\n &:focus {\n outline: none;\n }\n &::placeholder {\n color: #f1f1f1;\n }\n`;\n\nexport const Underline = styled(motion.div)`\n position: absolute;\n background-color: #2f528f;\n bottom: 0;\n left: 0;\n width: 100%;\n height: 3px;\n`;\n"
},
{
"code": null,
"e": 6983,
"s": 6869,
"text": "Step to Run Application: Run the application using the following command from the root directory of the project :"
},
{
"code": null,
"e": 6993,
"s": 6983,
"text": "npm start"
},
{
"code": null,
"e": 7092,
"s": 6993,
"text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:"
},
{
"code": null,
"e": 7107,
"s": 7092,
"text": "adnanirshad158"
},
{
"code": null,
"e": 7114,
"s": 7107,
"text": "Picked"
},
{
"code": null,
"e": 7126,
"s": 7114,
"text": "React-Hooks"
},
{
"code": null,
"e": 7142,
"s": 7126,
"text": "React-Questions"
},
{
"code": null,
"e": 7150,
"s": 7142,
"text": "ReactJS"
},
{
"code": null,
"e": 7167,
"s": 7150,
"text": "Web Technologies"
}
] |
What is Event bubbling and Event Capturing in JavaScript ? | 14 Sep, 2021
Event bubbling and event capturing are the two interesting concepts of JavaScript. Before diving deep into these fascinating concepts, let us first know about what an event listener is? An event listener is basically a function that waits for an event to occur. That event can be anything like a mouse click event, submitting a form, pressing keys of a keyboard, etc.
An event listener contains three parameters and it can be defined using the following syntax.
<element>.addEventListener(<eventName>,
<callbackFunction>, {capture : boolean});
<element>: The element to which an event listener is attached.
<eventName>: It can be ‘click’,’key up’,’key down’ etc. events.
<callbackFunction>: This function fires after the event happened.
{capture: boolean}: It tells whether the event will be in the capture phase or in the bubbling phase (optional)
Example 1: Let’s take an example to understand event bubbling and event capturing.
HTML
<!DOCTYPE html><html> <head> <script src="https://code.jquery.com/jquery-3.6.0.min.js"> </script> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id="grandparent">GrandParent <div id="parent">Parent <div id="child">Child</div> </div> </div> </div> <script> const grandParent = document.getElementById("grandparent"); const parent = document.getElementById("parent"); const child = document.getElementById("child"); grandParent.addEventListener("click", (e) => { console.log("GrandParent"); }, { capture: false }); parent.addEventListener("click", (e) => { console.log("Parent"); }, { capture: false }); child.addEventListener("click", (e) => { console.log("Child"); }, { capture: false }); </script></body></html>
Output:
When we clicked on the div with the child as its id, we should get the output as ‘child’ on our console. But unexpectedly, we are receiving a different output even we have not clicked on divs with parent and grandparent as their id. The concept of event bubbling comes into the picture. The child div lies inside the parent div as well as in the grandparent div. So, when the child div clicked, we indirectly clicked on both parent div and grandparent div. Thus, propagation is moving from inside to outside in the DOM or we can say events are getting bubble up.
Therefore, the process of propagating from the closest element to the farthest away element in the DOM (Document Object Modal) is called event bubbling.
Example 2: In the above example, let us change the value of the third parameter of addEventListener() and see what changes will be made in the output.
HTML
<!DOCTYPE html><html><head> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id="grandparent">GrandParent <div id="parent">Parent <div id="child"> Child</div> </div> </div> </div> <script> const grandParent = document.getElementById("grandparent"); const parent = document.getElementById("parent"); const child = document.getElementById("child"); // Changing value of capture parameter as 'true' grandParent.addEventListener("click", (e) => { console.log("GrandParent"); }, { capture: true }); parent.addEventListener("click", (e) => { console.log("Parent"); }, { capture: true }); child.addEventListener("click", (e) => { console.log("Child"); }, { capture: true }); </script></body> </html>
It’s clearly visible that the ancestor divs of the child div were printing first and then the child div itself. So, the process of propagating from the farthest element to the closest element in the DOM is called event capturing. Both terms are just opposite of each other.
Example 3: Let’s play around more with the code for better understanding.
HTML
<!DOCTYPE html><html> <head> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id="grandparent">GrandParent <div id="parent">Parent <div id="child"> Child</div> </div> </div> </div> <script> const grandParent = document.getElementById("grandparent"); const parent = document.getElementById("parent"); const child = document.getElementById("child"); document.addEventListener("click", (e) => { console.log("Document capturing"); }, { capture: true }); grandParent.addEventListener("click", (e) => { console.log("GrandParent capturing"); }, { capture: true }); parent.addEventListener("click", (e) => { console.log("Parent capturing"); }, { capture: true }); child.addEventListener("click", (e) => { console.log("Child capturing"); }, { capture: true }); document.addEventListener("click", (e) => { console.log("Document bubbling"); }, { capture: false }); grandParent.addEventListener("click", (e) => { console.log("GrandParent bubbling"); }, { capture: false }); parent.addEventListener("click", (e) => { console.log("Parent bubbling"); }, { capture: false }); child.addEventListener("click", (e) => { console.log("Child bubbling"); }, { capture: false }); </script></body> </html>
Output: If we clicked on the div with id child, then this will be the output.
We can see that the event capturing of event listeners happened first and then the event bubbling happened. This means the propagation of event listeners first goes from outside to inside and then from inside to outside in the DOM.
How to stop event bubbling and event capturing?
In the above example, we can see a parameter “e” (or sometimes called as “event”) in the callback function of addEventListener(). It is an event object which automatically defines when we add an event listener to an element. This object ‘e’ has a function called stopPropagation() which helps to prevent this annoying behavior.
Example 4: Let’s see what will happen when we will click on child div in the below code.
HTML
<!DOCTYPE html><html> <head> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id="grandparent">GrandParent <div id="parent">Parent <div id="child"> Child</div> </div> </div> </div> <script> const grandParent = document.getElementById("grandparent"); const parent = document.getElementById("parent"); const child = document.getElementById("child"); grandParent.addEventListener("click", (e) => { console.log("GrandParent bubbling"); }); parent.addEventListener("click", (e) => { e.stopPropagation(); //syntax to stop event bubbling console.log("Parent bubbling"); }); child.addEventListener("click", (e) => { console.log("Child bubbling"); }); </script></body> </html>
Output:
If we clicked on child div, the propagation is stopped on parent div and does not move to grandparent div. Hence, the event bubbling is prevented.
Note: The event capturing can also be prevented using the same way.
Important points to remember:
If we do not mention any third parameter in addEventListener(), then by default event bubbling will happen.
Event bubbling and event capturing happen only when the element and it’s all ancestors have the same event listener (in our case, ‘click’ event) attach to them.
Conclusion: We have learned about event bubbling and event capturing and these are some key points.
Event capturing means propagation of event is done from ancestor elements to child element in the DOM while event bubbling means propagation is done from child element to ancestor elements in the DOM.
The event capturing occurs followed by event bubbling.
If {capture: true} ,event capturing will occur else event bubbling will occur.
Both can be prevented by using the stopPropagation() method.
satyanarayanpatra5495
arorakashish0911
CSS-Properties
CSS-Questions
HTML-Questions
JavaScript-Events
JavaScript-Questions
Picked
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to set space between the flexbox ?
Design a Tribute Page using HTML & CSS
How to position a div at the bottom of its container using CSS?
How to Upload Image into Database and Display it using PHP ?
CSS | :not(:last-child):after Selector
REST API (Introduction)
Hide or show elements in HTML using display property
How to set the default value for an HTML <select> element ?
How to set input type date in dd-mm-yyyy format using HTML ?
HTTP headers | Content-Type | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n14 Sep, 2021"
},
{
"code": null,
"e": 422,
"s": 54,
"text": "Event bubbling and event capturing are the two interesting concepts of JavaScript. Before diving deep into these fascinating concepts, let us first know about what an event listener is? An event listener is basically a function that waits for an event to occur. That event can be anything like a mouse click event, submitting a form, pressing keys of a keyboard, etc."
},
{
"code": null,
"e": 516,
"s": 422,
"text": "An event listener contains three parameters and it can be defined using the following syntax."
},
{
"code": null,
"e": 603,
"s": 516,
"text": "<element>.addEventListener(<eventName>, \n <callbackFunction>, {capture : boolean});"
},
{
"code": null,
"e": 666,
"s": 603,
"text": "<element>: The element to which an event listener is attached."
},
{
"code": null,
"e": 730,
"s": 666,
"text": "<eventName>: It can be ‘click’,’key up’,’key down’ etc. events."
},
{
"code": null,
"e": 796,
"s": 730,
"text": "<callbackFunction>: This function fires after the event happened."
},
{
"code": null,
"e": 908,
"s": 796,
"text": "{capture: boolean}: It tells whether the event will be in the capture phase or in the bubbling phase (optional)"
},
{
"code": null,
"e": 991,
"s": 908,
"text": "Example 1: Let’s take an example to understand event bubbling and event capturing."
},
{
"code": null,
"e": 996,
"s": 991,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <script src=\"https://code.jquery.com/jquery-3.6.0.min.js\"> </script> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id=\"grandparent\">GrandParent <div id=\"parent\">Parent <div id=\"child\">Child</div> </div> </div> </div> <script> const grandParent = document.getElementById(\"grandparent\"); const parent = document.getElementById(\"parent\"); const child = document.getElementById(\"child\"); grandParent.addEventListener(\"click\", (e) => { console.log(\"GrandParent\"); }, { capture: false }); parent.addEventListener(\"click\", (e) => { console.log(\"Parent\"); }, { capture: false }); child.addEventListener(\"click\", (e) => { console.log(\"Child\"); }, { capture: false }); </script></body></html>",
"e": 2470,
"s": 996,
"text": null
},
{
"code": null,
"e": 2478,
"s": 2470,
"text": "Output:"
},
{
"code": null,
"e": 3042,
"s": 2478,
"text": "When we clicked on the div with the child as its id, we should get the output as ‘child’ on our console. But unexpectedly, we are receiving a different output even we have not clicked on divs with parent and grandparent as their id. The concept of event bubbling comes into the picture. The child div lies inside the parent div as well as in the grandparent div. So, when the child div clicked, we indirectly clicked on both parent div and grandparent div. Thus, propagation is moving from inside to outside in the DOM or we can say events are getting bubble up. "
},
{
"code": null,
"e": 3195,
"s": 3042,
"text": "Therefore, the process of propagating from the closest element to the farthest away element in the DOM (Document Object Modal) is called event bubbling."
},
{
"code": null,
"e": 3346,
"s": 3195,
"text": "Example 2: In the above example, let us change the value of the third parameter of addEventListener() and see what changes will be made in the output."
},
{
"code": null,
"e": 3351,
"s": 3346,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html><head> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id=\"grandparent\">GrandParent <div id=\"parent\">Parent <div id=\"child\"> Child</div> </div> </div> </div> <script> const grandParent = document.getElementById(\"grandparent\"); const parent = document.getElementById(\"parent\"); const child = document.getElementById(\"child\"); // Changing value of capture parameter as 'true' grandParent.addEventListener(\"click\", (e) => { console.log(\"GrandParent\"); }, { capture: true }); parent.addEventListener(\"click\", (e) => { console.log(\"Parent\"); }, { capture: true }); child.addEventListener(\"click\", (e) => { console.log(\"Child\"); }, { capture: true }); </script></body> </html>",
"e": 4815,
"s": 3351,
"text": null
},
{
"code": null,
"e": 5089,
"s": 4815,
"text": "It’s clearly visible that the ancestor divs of the child div were printing first and then the child div itself. So, the process of propagating from the farthest element to the closest element in the DOM is called event capturing. Both terms are just opposite of each other."
},
{
"code": null,
"e": 5163,
"s": 5089,
"text": "Example 3: Let’s play around more with the code for better understanding."
},
{
"code": null,
"e": 5168,
"s": 5163,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id=\"grandparent\">GrandParent <div id=\"parent\">Parent <div id=\"child\"> Child</div> </div> </div> </div> <script> const grandParent = document.getElementById(\"grandparent\"); const parent = document.getElementById(\"parent\"); const child = document.getElementById(\"child\"); document.addEventListener(\"click\", (e) => { console.log(\"Document capturing\"); }, { capture: true }); grandParent.addEventListener(\"click\", (e) => { console.log(\"GrandParent capturing\"); }, { capture: true }); parent.addEventListener(\"click\", (e) => { console.log(\"Parent capturing\"); }, { capture: true }); child.addEventListener(\"click\", (e) => { console.log(\"Child capturing\"); }, { capture: true }); document.addEventListener(\"click\", (e) => { console.log(\"Document bubbling\"); }, { capture: false }); grandParent.addEventListener(\"click\", (e) => { console.log(\"GrandParent bubbling\"); }, { capture: false }); parent.addEventListener(\"click\", (e) => { console.log(\"Parent bubbling\"); }, { capture: false }); child.addEventListener(\"click\", (e) => { console.log(\"Child bubbling\"); }, { capture: false }); </script></body> </html>",
"e": 7293,
"s": 5168,
"text": null
},
{
"code": null,
"e": 7371,
"s": 7293,
"text": "Output: If we clicked on the div with id child, then this will be the output."
},
{
"code": null,
"e": 7604,
"s": 7371,
"text": "We can see that the event capturing of event listeners happened first and then the event bubbling happened. This means the propagation of event listeners first goes from outside to inside and then from inside to outside in the DOM. "
},
{
"code": null,
"e": 7652,
"s": 7604,
"text": "How to stop event bubbling and event capturing?"
},
{
"code": null,
"e": 7980,
"s": 7652,
"text": "In the above example, we can see a parameter “e” (or sometimes called as “event”) in the callback function of addEventListener(). It is an event object which automatically defines when we add an event listener to an element. This object ‘e’ has a function called stopPropagation() which helps to prevent this annoying behavior."
},
{
"code": null,
"e": 8069,
"s": 7980,
"text": "Example 4: Let’s see what will happen when we will click on child div in the below code."
},
{
"code": null,
"e": 8074,
"s": 8069,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> div { color: white; display: flex; justify-content: center; align-items: center; flex-direction: column; } h2 { color: black; } #grandparent { background-color: green; width: 300px; height: 300px; } #parent { background-color: blue; width: 200px; height: 200px; } #child { background-color: red; width: 100px; height: 100px; } </style></head> <body> <div> <h2>Welcome To GFG</h2> <div id=\"grandparent\">GrandParent <div id=\"parent\">Parent <div id=\"child\"> Child</div> </div> </div> </div> <script> const grandParent = document.getElementById(\"grandparent\"); const parent = document.getElementById(\"parent\"); const child = document.getElementById(\"child\"); grandParent.addEventListener(\"click\", (e) => { console.log(\"GrandParent bubbling\"); }); parent.addEventListener(\"click\", (e) => { e.stopPropagation(); //syntax to stop event bubbling console.log(\"Parent bubbling\"); }); child.addEventListener(\"click\", (e) => { console.log(\"Child bubbling\"); }); </script></body> </html>",
"e": 9506,
"s": 8074,
"text": null
},
{
"code": null,
"e": 9514,
"s": 9506,
"text": "Output:"
},
{
"code": null,
"e": 9662,
"s": 9514,
"text": "If we clicked on child div, the propagation is stopped on parent div and does not move to grandparent div. Hence, the event bubbling is prevented. "
},
{
"code": null,
"e": 9730,
"s": 9662,
"text": "Note: The event capturing can also be prevented using the same way."
},
{
"code": null,
"e": 9760,
"s": 9730,
"text": "Important points to remember:"
},
{
"code": null,
"e": 9868,
"s": 9760,
"text": "If we do not mention any third parameter in addEventListener(), then by default event bubbling will happen."
},
{
"code": null,
"e": 10029,
"s": 9868,
"text": "Event bubbling and event capturing happen only when the element and it’s all ancestors have the same event listener (in our case, ‘click’ event) attach to them."
},
{
"code": null,
"e": 10129,
"s": 10029,
"text": "Conclusion: We have learned about event bubbling and event capturing and these are some key points."
},
{
"code": null,
"e": 10330,
"s": 10129,
"text": "Event capturing means propagation of event is done from ancestor elements to child element in the DOM while event bubbling means propagation is done from child element to ancestor elements in the DOM."
},
{
"code": null,
"e": 10385,
"s": 10330,
"text": "The event capturing occurs followed by event bubbling."
},
{
"code": null,
"e": 10464,
"s": 10385,
"text": "If {capture: true} ,event capturing will occur else event bubbling will occur."
},
{
"code": null,
"e": 10525,
"s": 10464,
"text": "Both can be prevented by using the stopPropagation() method."
},
{
"code": null,
"e": 10547,
"s": 10525,
"text": "satyanarayanpatra5495"
},
{
"code": null,
"e": 10564,
"s": 10547,
"text": "arorakashish0911"
},
{
"code": null,
"e": 10579,
"s": 10564,
"text": "CSS-Properties"
},
{
"code": null,
"e": 10593,
"s": 10579,
"text": "CSS-Questions"
},
{
"code": null,
"e": 10608,
"s": 10593,
"text": "HTML-Questions"
},
{
"code": null,
"e": 10626,
"s": 10608,
"text": "JavaScript-Events"
},
{
"code": null,
"e": 10647,
"s": 10626,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 10654,
"s": 10647,
"text": "Picked"
},
{
"code": null,
"e": 10658,
"s": 10654,
"text": "CSS"
},
{
"code": null,
"e": 10663,
"s": 10658,
"text": "HTML"
},
{
"code": null,
"e": 10674,
"s": 10663,
"text": "JavaScript"
},
{
"code": null,
"e": 10691,
"s": 10674,
"text": "Web Technologies"
},
{
"code": null,
"e": 10696,
"s": 10691,
"text": "HTML"
},
{
"code": null,
"e": 10794,
"s": 10696,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 10833,
"s": 10794,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 10872,
"s": 10833,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 10936,
"s": 10872,
"text": "How to position a div at the bottom of its container using CSS?"
},
{
"code": null,
"e": 10997,
"s": 10936,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 11036,
"s": 10997,
"text": "CSS | :not(:last-child):after Selector"
},
{
"code": null,
"e": 11060,
"s": 11036,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 11113,
"s": 11060,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 11173,
"s": 11113,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 11234,
"s": 11173,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Giuga Numbers | 07 Jul, 2021
Given a number N, the task is to check if N is an Giuga Number or not. If N is an Giuga Number then print “Yes” else print “No”.
A Giuga Number is a composite number N such that p divides (N/p – 1) for every prime factor p of N.
Examples:
Input: N = 30 Output: Yes Explanation: 30 is a composite number whose prime divisors are {2, 3, 5}, such that 2 divides 30/2 – 1 = 14, 3 divides 30/3 – 1 = 9, and 5 divides 30/5 – 1 = 5.
Input: N = 161 Output: No
Approach: The idea is to check if N is composite number or not. If not then print “No”. If N is a composite number then find the prime factors of a number and for each prime factor p check if the condition p divides (n/p – 1) holds true or not. If the above condition holds true then print “Yes” else print “No”.
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 n is// a composite numberbool isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberbool isGiugaNum(int n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; int N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver Codeint main(){ // Given Number N int N = 30; // Function Call if (isGiugaNum(N)) cout << "Yes"; else cout << "No";}
// Java program for the above approachclass GFG{ // Function to check if n is// a composite numberstatic boolean isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for(int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberstatic boolean isGiugaNum(int n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; int N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for(int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver codepublic static void main(String[] args){ // Given Number N int n = 30; // Function Call if (isGiugaNum(n)) System.out.println("Yes"); else System.out.println("No");}} // This code is contributed by Pratima Pandey
# Python program for the above approachimport math # Function to check if n is# a composite numberdef isComposite(n): # Corner cases if(n <= 1): return False if(n <= 3): return False # This is checked to skip # middle 5 numbers if(n % 2 == 0 or n % 3 == 0): return True i = 5 while(i * i <= n): if(n % i == 0 or n % (i + 2) == 0): return True i += 6 return False # Function to check if N is a# Giuga Numberdef isGiugaNum(n): # N should be composite to be # a Giuga Number if(not(isComposite(n))): return False N = n # Print the number of 2s # that divide n while(n % 2 == 0): if((int(N / 2) - 1) % 2 != 0): return False n = int(n / 2) # N must be odd at this point. # So we can skip one element for i in range(3, int(math.sqrt(n)) + 1, 2): # While i divides n, # print i and divide n while(n % i == 0): if((int(N / i) - 1) % i != 0): return False n = int(n / i) # This condition is to handle # the case when n # is a prime number > 2 if(n > 2): if((int(N / n) - 1) % n != 0): return False return True # Driver code # Given Number Nn = 30if(isGiugaNum(n)): print("Yes")else: print("No") # This code is contributed by avanitrachhadiya2155
// C# program for the above approachusing System;class GFG{ // Function to check if n is// a composite numberstatic bool isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for(int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberstatic bool isGiugaNum(int n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; int N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for(int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver codestatic void Main(){ // Given Number N int N = 30; // Function Call if (isGiugaNum(N)) Console.Write("Yes"); else Console.Write("No");}} // This code is contributed by divyeshrabadiya07
<script> // JavaScript program for the above approach // Function to check if n is// a composite numberfunction isComposite(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for(let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberfunction isGiugaNum(n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; let N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for(let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver Code // Given Number Nlet n = 30; // Function Callif (isGiugaNum(n)) document.write("Yes");else document.write("No"); // This code is contributed by susmitakundugoaldanga </script>
Yes
dewantipandeydp
divyeshrabadiya07
avanitrachhadiya2155
susmitakundugoaldanga
ankita_saini
sweetyty
series
Mathematical
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2021"
},
{
"code": null,
"e": 157,
"s": 28,
"text": "Given a number N, the task is to check if N is an Giuga Number or not. If N is an Giuga Number then print “Yes” else print “No”."
},
{
"code": null,
"e": 259,
"s": 157,
"text": "A Giuga Number is a composite number N such that p divides (N/p – 1) for every prime factor p of N. "
},
{
"code": null,
"e": 271,
"s": 259,
"text": "Examples: "
},
{
"code": null,
"e": 458,
"s": 271,
"text": "Input: N = 30 Output: Yes Explanation: 30 is a composite number whose prime divisors are {2, 3, 5}, such that 2 divides 30/2 – 1 = 14, 3 divides 30/3 – 1 = 9, and 5 divides 30/5 – 1 = 5."
},
{
"code": null,
"e": 485,
"s": 458,
"text": "Input: N = 161 Output: No "
},
{
"code": null,
"e": 798,
"s": 485,
"text": "Approach: The idea is to check if N is composite number or not. If not then print “No”. If N is a composite number then find the prime factors of a number and for each prime factor p check if the condition p divides (n/p – 1) holds true or not. If the above condition holds true then print “Yes” else print “No”."
},
{
"code": null,
"e": 850,
"s": 798,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 854,
"s": 850,
"text": "C++"
},
{
"code": null,
"e": 859,
"s": 854,
"text": "Java"
},
{
"code": null,
"e": 867,
"s": 859,
"text": "Python3"
},
{
"code": null,
"e": 870,
"s": 867,
"text": "C#"
},
{
"code": null,
"e": 881,
"s": 870,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to check if n is// a composite numberbool isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for (int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberbool isGiugaNum(int n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; int N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for (int i = 3; i <= sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver Codeint main(){ // Given Number N int N = 30; // Function Call if (isGiugaNum(N)) cout << \"Yes\"; else cout << \"No\";}",
"e": 2354,
"s": 881,
"text": null
},
{
"code": "// Java program for the above approachclass GFG{ // Function to check if n is// a composite numberstatic boolean isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for(int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberstatic boolean isGiugaNum(int n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; int N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for(int i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver codepublic static void main(String[] args){ // Given Number N int n = 30; // Function Call if (isGiugaNum(n)) System.out.println(\"Yes\"); else System.out.println(\"No\");}} // This code is contributed by Pratima Pandey",
"e": 3966,
"s": 2354,
"text": null
},
{
"code": "# Python program for the above approachimport math # Function to check if n is# a composite numberdef isComposite(n): # Corner cases if(n <= 1): return False if(n <= 3): return False # This is checked to skip # middle 5 numbers if(n % 2 == 0 or n % 3 == 0): return True i = 5 while(i * i <= n): if(n % i == 0 or n % (i + 2) == 0): return True i += 6 return False # Function to check if N is a# Giuga Numberdef isGiugaNum(n): # N should be composite to be # a Giuga Number if(not(isComposite(n))): return False N = n # Print the number of 2s # that divide n while(n % 2 == 0): if((int(N / 2) - 1) % 2 != 0): return False n = int(n / 2) # N must be odd at this point. # So we can skip one element for i in range(3, int(math.sqrt(n)) + 1, 2): # While i divides n, # print i and divide n while(n % i == 0): if((int(N / i) - 1) % i != 0): return False n = int(n / i) # This condition is to handle # the case when n # is a prime number > 2 if(n > 2): if((int(N / n) - 1) % n != 0): return False return True # Driver code # Given Number Nn = 30if(isGiugaNum(n)): print(\"Yes\")else: print(\"No\") # This code is contributed by avanitrachhadiya2155",
"e": 5358,
"s": 3966,
"text": null
},
{
"code": "// C# program for the above approachusing System;class GFG{ // Function to check if n is// a composite numberstatic bool isComposite(int n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for(int i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberstatic bool isGiugaNum(int n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; int N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for(int i = 3; i <= Math.Sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver codestatic void Main(){ // Given Number N int N = 30; // Function Call if (isGiugaNum(N)) Console.Write(\"Yes\"); else Console.Write(\"No\");}} // This code is contributed by divyeshrabadiya07",
"e": 6971,
"s": 5358,
"text": null
},
{
"code": "<script> // JavaScript program for the above approach // Function to check if n is// a composite numberfunction isComposite(n){ // Corner cases if (n <= 1) return false; if (n <= 3) return false; // This is checked to skip // middle 5 numbers if (n % 2 == 0 || n % 3 == 0) return true; for(let i = 5; i * i <= n; i = i + 6) if (n % i == 0 || n % (i + 2) == 0) return true; return false;} // Function to check if N is a// Giuga Numberfunction isGiugaNum(n){ // N should be composite to be // a Giuga Number if (!(isComposite(n))) return false; let N = n; // Print the number of 2s // that divide n while (n % 2 == 0) { if ((N / 2 - 1) % 2 != 0) return false; n = n / 2; } // N must be odd at this point. // So we can skip one element for(let i = 3; i <= Math.sqrt(n); i = i + 2) { // While i divides n, // print i and divide n while (n % i == 0) { if ((N / i - 1) % i != 0) return false; n = n / i; } } // This condition is to handle // the case when n // is a prime number > 2 if (n > 2) if ((N / n - 1) % n != 0) return false; return true;} // Driver Code // Given Number Nlet n = 30; // Function Callif (isGiugaNum(n)) document.write(\"Yes\");else document.write(\"No\"); // This code is contributed by susmitakundugoaldanga </script>",
"e": 8546,
"s": 6971,
"text": null
},
{
"code": null,
"e": 8550,
"s": 8546,
"text": "Yes"
},
{
"code": null,
"e": 8568,
"s": 8552,
"text": "dewantipandeydp"
},
{
"code": null,
"e": 8586,
"s": 8568,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 8607,
"s": 8586,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 8629,
"s": 8607,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 8642,
"s": 8629,
"text": "ankita_saini"
},
{
"code": null,
"e": 8651,
"s": 8642,
"text": "sweetyty"
},
{
"code": null,
"e": 8658,
"s": 8651,
"text": "series"
},
{
"code": null,
"e": 8671,
"s": 8658,
"text": "Mathematical"
},
{
"code": null,
"e": 8684,
"s": 8671,
"text": "Mathematical"
},
{
"code": null,
"e": 8691,
"s": 8684,
"text": "series"
}
] |
Integer.numberOfLeadingZeros() Method in Java With Example | 13 Dec, 2021
The java.lang.Integer.numberOfLeadingZeros() is the method which returns the total number of zero(0) bits preceding the highest-order (ie.leftmost or most significant “1” bit)one-bit in the two’s complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. If the specified integer value has no one-bits in its two’s complement representation, in other words if it is equal to zero then it will returns 32.Syntax :
public static int numberOfLeadingZeros(int arg)
Parameter : This method accepts a single parameter arg which is the integer value.Return Value : This method returns the number of zero bits preceding the highest-order set-bit in the two’s complement binary representation of the specified int value, or 32 if the value is equal to zero.Explanation:
Consider any integer arg = 19
Binary Representation = 0001 0011
Highest bit(at 5) i.e.0001 0000
so result = 16-5 i.e. 11
Below programs illustrate the java.lang.Integer.numberOfLeadingZeros() method.Program 1: For a positive number.
java
// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { int a = 155; System.out.println("Integral Number = " + a); // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print("Number of Leading Zeros = "); System.out.println(Integer.numberOfLeadingZeros(a)); a = 10; System.out.println("Integral Number = " + a); // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print("Number of Leading Zeros = "); System.out.println(Integer.numberOfLeadingZeros(a)); }}
Integral Number = 155
Number of Leading Zeros = 24
Integral Number = 10
Number of Leading Zeros = 28
Program 2: For a negative number.
java
// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { int a = -15; System.out.println("Number = " + a); // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print("Number of Leading Zeros = "); System.out.println(Integer.numberOfLeadingZeros(a)); }}
Number = -15
Number of Leading Zeros = 0
Program 3: For a decimal value. Note:It returns an error message when a decimal value is passed as an argument.
java
// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print("Number of Leading Zeros = "); System.out.println(Integer.numberOfLeadingZeros(16.32)); }}
Output:
prog.java:11: error: incompatible types: possible lossy conversion from double to int
System.out.println(Integer.numberOfLeadingZeros(16.32));
^
Note: Some messages have been simplified; recompile with
-Xdiags:verbose to get full output
1 error
Program 4: For a string value is passed in argument. Note:It returns an error message when a string is passed as an argument.
java
// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { // returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print("Number of Leading Zeros = "); System.out.println(Integer.numberOfLeadingZeros("18")); }}
Output:
prog.java:11: error: incompatible types: String cannot be converted to int
System.out.println(Integer.numberOfLeadingZeros("18"));
^
Note: Some messages have been simplified; recompile with
-Xdiags:verbose to get full output
1 error
anikaseth98
Java-Functions
Java-Integer
Java-lang package
java-math
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
Abstraction in Java
HashSet in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Dec, 2021"
},
{
"code": null,
"e": 597,
"s": 28,
"text": "The java.lang.Integer.numberOfLeadingZeros() is the method which returns the total number of zero(0) bits preceding the highest-order (ie.leftmost or most significant “1” bit)one-bit in the two’s complement binary representation of the specified integer value or we can say that it is the function which converts int value to Binary then considers the highest one bit and return no. of zero bits preceding it. If the specified integer value has no one-bits in its two’s complement representation, in other words if it is equal to zero then it will returns 32.Syntax : "
},
{
"code": null,
"e": 645,
"s": 597,
"text": "public static int numberOfLeadingZeros(int arg)"
},
{
"code": null,
"e": 947,
"s": 645,
"text": "Parameter : This method accepts a single parameter arg which is the integer value.Return Value : This method returns the number of zero bits preceding the highest-order set-bit in the two’s complement binary representation of the specified int value, or 32 if the value is equal to zero.Explanation: "
},
{
"code": null,
"e": 977,
"s": 947,
"text": "Consider any integer arg = 19"
},
{
"code": null,
"e": 1011,
"s": 977,
"text": "Binary Representation = 0001 0011"
},
{
"code": null,
"e": 1043,
"s": 1011,
"text": "Highest bit(at 5) i.e.0001 0000"
},
{
"code": null,
"e": 1068,
"s": 1043,
"text": "so result = 16-5 i.e. 11"
},
{
"code": null,
"e": 1182,
"s": 1068,
"text": "Below programs illustrate the java.lang.Integer.numberOfLeadingZeros() method.Program 1: For a positive number. "
},
{
"code": null,
"e": 1187,
"s": 1182,
"text": "java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { int a = 155; System.out.println(\"Integral Number = \" + a); // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print(\"Number of Leading Zeros = \"); System.out.println(Integer.numberOfLeadingZeros(a)); a = 10; System.out.println(\"Integral Number = \" + a); // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print(\"Number of Leading Zeros = \"); System.out.println(Integer.numberOfLeadingZeros(a)); }}",
"e": 1933,
"s": 1187,
"text": null
},
{
"code": null,
"e": 2034,
"s": 1933,
"text": "Integral Number = 155\nNumber of Leading Zeros = 24\nIntegral Number = 10\nNumber of Leading Zeros = 28"
},
{
"code": null,
"e": 2071,
"s": 2036,
"text": "Program 2: For a negative number. "
},
{
"code": null,
"e": 2076,
"s": 2071,
"text": "java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { int a = -15; System.out.println(\"Number = \" + a); // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print(\"Number of Leading Zeros = \"); System.out.println(Integer.numberOfLeadingZeros(a)); }}",
"e": 2532,
"s": 2076,
"text": null
},
{
"code": null,
"e": 2573,
"s": 2532,
"text": "Number = -15\nNumber of Leading Zeros = 0"
},
{
"code": null,
"e": 2689,
"s": 2575,
"text": "Program 3: For a decimal value. Note:It returns an error message when a decimal value is passed as an argument. "
},
{
"code": null,
"e": 2694,
"s": 2689,
"text": "java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { // Returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print(\"Number of Leading Zeros = \"); System.out.println(Integer.numberOfLeadingZeros(16.32)); }}",
"e": 3089,
"s": 2694,
"text": null
},
{
"code": null,
"e": 3098,
"s": 3089,
"text": "Output: "
},
{
"code": null,
"e": 3408,
"s": 3098,
"text": "prog.java:11: error: incompatible types: possible lossy conversion from double to int\n System.out.println(Integer.numberOfLeadingZeros(16.32));\n ^\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n1 error"
},
{
"code": null,
"e": 3536,
"s": 3408,
"text": "Program 4: For a string value is passed in argument. Note:It returns an error message when a string is passed as an argument. "
},
{
"code": null,
"e": 3541,
"s": 3536,
"text": "java"
},
{
"code": "// Java program to illustrate the// java.lang.Integer.numberOfLeadingZeros()import java.lang.*; public class LeadingZeros { public static void main(String[] args) { // returns the number of zero bits preceding the highest-order // leftmost one-bit System.out.print(\"Number of Leading Zeros = \"); System.out.println(Integer.numberOfLeadingZeros(\"18\")); }}",
"e": 3935,
"s": 3541,
"text": null
},
{
"code": null,
"e": 3944,
"s": 3935,
"text": "Output: "
},
{
"code": null,
"e": 4243,
"s": 3944,
"text": "prog.java:11: error: incompatible types: String cannot be converted to int\n System.out.println(Integer.numberOfLeadingZeros(\"18\"));\n ^\nNote: Some messages have been simplified; recompile with \n-Xdiags:verbose to get full output\n1 error "
},
{
"code": null,
"e": 4255,
"s": 4243,
"text": "anikaseth98"
},
{
"code": null,
"e": 4270,
"s": 4255,
"text": "Java-Functions"
},
{
"code": null,
"e": 4283,
"s": 4270,
"text": "Java-Integer"
},
{
"code": null,
"e": 4301,
"s": 4283,
"text": "Java-lang package"
},
{
"code": null,
"e": 4311,
"s": 4301,
"text": "java-math"
},
{
"code": null,
"e": 4316,
"s": 4311,
"text": "Java"
},
{
"code": null,
"e": 4321,
"s": 4316,
"text": "Java"
},
{
"code": null,
"e": 4419,
"s": 4321,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4434,
"s": 4419,
"text": "Stream In Java"
},
{
"code": null,
"e": 4455,
"s": 4434,
"text": "Introduction to Java"
},
{
"code": null,
"e": 4476,
"s": 4455,
"text": "Constructors in Java"
},
{
"code": null,
"e": 4495,
"s": 4476,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 4512,
"s": 4495,
"text": "Generics in Java"
},
{
"code": null,
"e": 4542,
"s": 4512,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 4558,
"s": 4542,
"text": "Strings in Java"
},
{
"code": null,
"e": 4584,
"s": 4558,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4604,
"s": 4584,
"text": "Abstraction in Java"
}
] |
How to Convert Categorical Variable to Numeric in Pandas? | 01 Dec, 2021
In this article, we will learn how to convert a categorical variable into a Numeric by using pandas.
When we look at the categorical data, the first question that arises to anyone is how to handle those data, because machine learning is always good at dealing with numeric values. We could make machine learning models by using text data. So, to make predictive models we have to convert categorical data into numeric form.
Replacing is one of the methods to convert categorical terms into numeric. For example, We will take a dataset of people’s salaries based on their level of education. This is an ordinal type of categorical variable. We will convert their education levels into numeric terms.
Syntax:
replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)
Consider the given data:
Data
Python3
#import pandasimport pandas as pd # read csv filedf = pd.read_csv('data.csv') # replacing valuesdf['Education'].replace(['Under-Graduate', 'Diploma '], [0, 1], inplace=True)
Output:
In the above program, we have replaced “under-graduate” as 0 and “Diploma” as 1.
Replacing the values is not the most efficient way to convert them. Pandas provide a method called get_dummies which will return the dummy variable columns.
Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’, dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)
Step 1: Create dummies columns
get_dummies() method is called and the parameter name of the column is given. This method will return the dummy variable columns. In this case, we have 3 types of Categorical variables so, it returned three columns
Step 2: Concatenate
Syntax: pandas.concat(objs, axis=0, join=’outer’, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True
The next step is to concatenate the dummies columns into the data frame. In pandas, there is a concat() method, which you can call to join two data frames. You should supply it with the name of two data frames and the axis. This will give you the merged data frame.
Step 3: Drop columns
We have to drop the original ‘education’ column because we have the dummy variable column and we don’t need the text column. And we might also drop one of the dummy variable columns So that we could avoid the dummy variable trap which could mess up the model. After dropping the columns, the desired dataframe is obtained
We will implement this at code
Python3
#import pandasimport pandas as pd # read csvdf = pd.read_csv('salary.csv') # get the dummies and store it in a variabledummies = pd.get_dummies(df.Education) # Concatenate the dummies to original dataframemerged = pd.concat([df, dummies], axis='columns') # drop the valuesmerged.drop(['Education', 'Under-Graduate'], axis='columns') # print the dataframeprint(merged)
Output:
anikakapoor
Picked
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Iterate over a list in Python
Python Classes and Objects
Introduction To PYTHON | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Dec, 2021"
},
{
"code": null,
"e": 129,
"s": 28,
"text": "In this article, we will learn how to convert a categorical variable into a Numeric by using pandas."
},
{
"code": null,
"e": 452,
"s": 129,
"text": "When we look at the categorical data, the first question that arises to anyone is how to handle those data, because machine learning is always good at dealing with numeric values. We could make machine learning models by using text data. So, to make predictive models we have to convert categorical data into numeric form."
},
{
"code": null,
"e": 728,
"s": 452,
"text": "Replacing is one of the methods to convert categorical terms into numeric. For example, We will take a dataset of people’s salaries based on their level of education. This is an ordinal type of categorical variable. We will convert their education levels into numeric terms. "
},
{
"code": null,
"e": 736,
"s": 728,
"text": "Syntax:"
},
{
"code": null,
"e": 827,
"s": 736,
"text": "replace(to_replace=None, value=None, inplace=False, limit=None, regex=False, method=’pad’)"
},
{
"code": null,
"e": 852,
"s": 827,
"text": "Consider the given data:"
},
{
"code": null,
"e": 857,
"s": 852,
"text": "Data"
},
{
"code": null,
"e": 865,
"s": 857,
"text": "Python3"
},
{
"code": "#import pandasimport pandas as pd # read csv filedf = pd.read_csv('data.csv') # replacing valuesdf['Education'].replace(['Under-Graduate', 'Diploma '], [0, 1], inplace=True)",
"e": 1062,
"s": 865,
"text": null
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Output:"
},
{
"code": null,
"e": 1151,
"s": 1070,
"text": "In the above program, we have replaced “under-graduate” as 0 and “Diploma” as 1."
},
{
"code": null,
"e": 1308,
"s": 1151,
"text": "Replacing the values is not the most efficient way to convert them. Pandas provide a method called get_dummies which will return the dummy variable columns."
},
{
"code": null,
"e": 1444,
"s": 1308,
"text": "Syntax: pandas.get_dummies(data, prefix=None, prefix_sep=’_’, dummy_na=False, columns=None, sparse=False, drop_first=False, dtype=None)"
},
{
"code": null,
"e": 1475,
"s": 1444,
"text": "Step 1: Create dummies columns"
},
{
"code": null,
"e": 1690,
"s": 1475,
"text": "get_dummies() method is called and the parameter name of the column is given. This method will return the dummy variable columns. In this case, we have 3 types of Categorical variables so, it returned three columns"
},
{
"code": null,
"e": 1711,
"s": 1690,
"text": "Step 2: Concatenate "
},
{
"code": null,
"e": 1863,
"s": 1711,
"text": "Syntax: pandas.concat(objs, axis=0, join=’outer’, ignore_index=False, keys=None, levels=None, names=None, verify_integrity=False, sort=False, copy=True"
},
{
"code": null,
"e": 2130,
"s": 1863,
"text": "The next step is to concatenate the dummies columns into the data frame. In pandas, there is a concat() method, which you can call to join two data frames. You should supply it with the name of two data frames and the axis. This will give you the merged data frame."
},
{
"code": null,
"e": 2151,
"s": 2130,
"text": "Step 3: Drop columns"
},
{
"code": null,
"e": 2474,
"s": 2151,
"text": "We have to drop the original ‘education’ column because we have the dummy variable column and we don’t need the text column. And we might also drop one of the dummy variable columns So that we could avoid the dummy variable trap which could mess up the model. After dropping the columns, the desired dataframe is obtained"
},
{
"code": null,
"e": 2505,
"s": 2474,
"text": "We will implement this at code"
},
{
"code": null,
"e": 2513,
"s": 2505,
"text": "Python3"
},
{
"code": "#import pandasimport pandas as pd # read csvdf = pd.read_csv('salary.csv') # get the dummies and store it in a variabledummies = pd.get_dummies(df.Education) # Concatenate the dummies to original dataframemerged = pd.concat([df, dummies], axis='columns') # drop the valuesmerged.drop(['Education', 'Under-Graduate'], axis='columns') # print the dataframeprint(merged)",
"e": 2881,
"s": 2513,
"text": null
},
{
"code": null,
"e": 2889,
"s": 2881,
"text": "Output:"
},
{
"code": null,
"e": 2901,
"s": 2889,
"text": "anikakapoor"
},
{
"code": null,
"e": 2908,
"s": 2901,
"text": "Picked"
},
{
"code": null,
"e": 2922,
"s": 2908,
"text": "Python-pandas"
},
{
"code": null,
"e": 2929,
"s": 2922,
"text": "Python"
},
{
"code": null,
"e": 3027,
"s": 2929,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3045,
"s": 3027,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3087,
"s": 3045,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3109,
"s": 3087,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3144,
"s": 3109,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 3170,
"s": 3144,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3202,
"s": 3170,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3231,
"s": 3202,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 3261,
"s": 3231,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 3288,
"s": 3261,
"text": "Python Classes and Objects"
}
] |
SQL | ALTER (RENAME) | 22 Mar, 2021
Sometimes we may want to rename our table to give it a more relevant name. For this purpose we can use ALTER TABLE to rename the name of table.
*Syntax may vary in different databases. Syntax(Oracle,MySQL,MariaDB):
ALTER TABLE table_name
RENAME TO new_table_name;
Columns can be also be given new name with the use of ALTER TABLE.
Syntax(MySQL, Oracle):
ALTER TABLE table_name
RENAME COLUMN old_name TO new_name;
Syntax(MariaDB):
ALTER TABLE table_name
CHANGE COLUMN old_name TO new_name;
Sample Table:Student
QUERY:
Change the name of column NAME to FIRST_NAME in table Student.
ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;
OUTPUT:
Change the name of the table Student to Student_Details
ALTER TABLE Student RENAME TO Student_Details;
OUTPUT:Student_Details
This article is contributed by Shubham Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
guruvishnu_desireddy
tirathsharma098
SQL-Clauses-Operators
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Mar, 2021"
},
{
"code": null,
"e": 197,
"s": 53,
"text": "Sometimes we may want to rename our table to give it a more relevant name. For this purpose we can use ALTER TABLE to rename the name of table."
},
{
"code": null,
"e": 270,
"s": 197,
"text": "*Syntax may vary in different databases. Syntax(Oracle,MySQL,MariaDB): "
},
{
"code": null,
"e": 319,
"s": 270,
"text": "ALTER TABLE table_name\nRENAME TO new_table_name;"
},
{
"code": null,
"e": 386,
"s": 319,
"text": "Columns can be also be given new name with the use of ALTER TABLE."
},
{
"code": null,
"e": 409,
"s": 386,
"text": "Syntax(MySQL, Oracle):"
},
{
"code": null,
"e": 468,
"s": 409,
"text": "ALTER TABLE table_name\nRENAME COLUMN old_name TO new_name;"
},
{
"code": null,
"e": 485,
"s": 468,
"text": "Syntax(MariaDB):"
},
{
"code": null,
"e": 544,
"s": 485,
"text": "ALTER TABLE table_name\nCHANGE COLUMN old_name TO new_name;"
},
{
"code": null,
"e": 565,
"s": 544,
"text": "Sample Table:Student"
},
{
"code": null,
"e": 572,
"s": 565,
"text": "QUERY:"
},
{
"code": null,
"e": 635,
"s": 572,
"text": "Change the name of column NAME to FIRST_NAME in table Student."
},
{
"code": null,
"e": 689,
"s": 635,
"text": "ALTER TABLE Student RENAME COLUMN NAME TO FIRST_NAME;"
},
{
"code": null,
"e": 698,
"s": 689,
"text": "OUTPUT: "
},
{
"code": null,
"e": 756,
"s": 700,
"text": "Change the name of the table Student to Student_Details"
},
{
"code": null,
"e": 803,
"s": 756,
"text": "ALTER TABLE Student RENAME TO Student_Details;"
},
{
"code": null,
"e": 827,
"s": 803,
"text": "OUTPUT:Student_Details "
},
{
"code": null,
"e": 1133,
"s": 827,
"text": "This article is contributed by Shubham Chaudhary. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. "
},
{
"code": null,
"e": 1259,
"s": 1133,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1280,
"s": 1259,
"text": "guruvishnu_desireddy"
},
{
"code": null,
"e": 1296,
"s": 1280,
"text": "tirathsharma098"
},
{
"code": null,
"e": 1318,
"s": 1296,
"text": "SQL-Clauses-Operators"
},
{
"code": null,
"e": 1322,
"s": 1318,
"text": "SQL"
},
{
"code": null,
"e": 1326,
"s": 1322,
"text": "SQL"
}
] |
R – Charts and Graphs | 09 Dec, 2021
R language is mostly used for statistics and data analytics purposes to represent the data graphically in the software. To represent those data graphically, charts and graphs are used in R.
There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic plot, dot chart, coplot, histogram, pie chart, scatter graph, etc.
Bar Plot or Bar Chart
Pie Diagram or Pie Chart
Histogram
Scatter Plot
Box Plot
Bar plot or Bar Chart in R is used to represent the values in data vector as height of the bars. The data vector passed to the function is represented over y-axis of the graph. Bar chart can behave like histogram by using table() function instead of data vector.
Syntax: barplot(data, xlab, ylab)
where:
data is the data vector to be represented on y-axis
xlab is the label given to x-axis
ylab is the label given to y-axis
Note: To know about more optional parameters in barplot() function, use the below command in R console:
help("barplot")
Example:
R
# defining vectorx <- c(7, 15, 23, 12, 44, 56, 32) # output to be present as PNG filepng(file = "barplot.png") # plotting vectorbarplot(x, xlab = "GeeksforGeeks Audience", ylab = "Count", col = "white", col.axis = "darkgreen", col.lab = "darkgreen") # saving the filedev.off()
Output:
Pie chart is a circular chart divided into different segments according to the ratio of data provided. The total value of the pie is 100 and the segments tell the fraction of the whole pie. It is another method to represent statistical data in graphical form and pie() function is used to perform the same.
Syntax: pie(x, labels, col, main, radius)
where,
x is data vector
labels shows names given to slices
col fills the color in the slices as given parameter
main shows title name of the pie chart
radius indicates radius of the pie chart. It can be between -1 to +1
Note: To know about more optional parameters in pie() function, use the below command in the R console:
help("pie")
Example:
Assume, vector x indicates the number of articles present on the GeeksforGeeks portal in categories names(x)
R
# defining vector x with number of articlesx <- c(210, 450, 250, 100, 50, 90) # defining labels for each value in xnames(x) <- c("Algo", "DS", "Java", "C", "C++", "Python") # output to be present as PNG filepng(file = "piechart.png") # creating pie chartpie(x, labels = names(x), col = "white",main = "Articles on GeeksforGeeks", radius = -1,col.main = "darkgreen") # saving the filedev.off()
Output:
Pie chart in 3D can also be created in R by using following syntax but requires plotrix library.
Syntax: pie3D(x, labels, radius, main)
Note: To know about more optional parameters in pie3D() function, use below command in R console:
help("pie3D")
Example:
R
# importing library plotrix for pie3D()library(plotrix) # defining vector x with number of articlesx <- c(210, 450, 250, 100, 50, 90) # defining labels for each value in xnames(x) <- c("Algo", "DS", "Java", "C", "C++", "Python") # output to be present as PNG filepng(file = "piechart3d.png") # creating pie chartpie3D(x, labels = names(x), col = "white",main = "Articles on GeeksforGeeks",labelcol = "darkgreen", col.main = "darkgreen") # saving the filedev.off()
Output:
Histogram is a graphical representation used to create a graph with bars representing the frequency of grouped data in vector. Histogram is same as bar chart but only difference between them is histogram represents frequency of grouped data rather than data itself.
Syntax: hist(x, col, border, main, xlab, ylab)
where:
x is data vector
col specifies the color of the bars to be filled
border specifies the color of border of bars
main specifies the title name of histogram
xlab specifies the x-axis label
ylab specifies the y-axis label
Note: To know about more optional parameters in hist() function, use below command in R console:
help("hist")
Example:
R
# defining vectorx <- c(21, 23, 56, 90, 20, 7, 94, 12, 57, 76, 69, 45, 34, 32, 49, 55, 57) # output to be present as PNG filepng(file = "hist.png") # hist(x, main = "Histogram of Vector x", xlab = "Values", col.lab = "darkgreen", col.main = "darkgreen") # saving the filedev.off()
Output:
A Scatter plot is another type of graphical representation used to plot the points to show relationship between two data vectors. One of the data vectors is represented on x-axis and another on y-axis.
Syntax: plot(x, y, type, xlab, ylab, main)
Where,
x is the data vector represented on x-axis
y is the data vector represented on y-axis
type specifies the type of plot to be drawn. For example, “l” for lines, “p” for points, “s” for stair steps, etc.
xlab specifies the label for x-axis
ylab specifies the label for y-axis
main specifies the title name of the graph
Note: To know about more optional parameters in plot() function, use the below command in R console:
help("plot")
Example:
R
# taking input from dataset Orange already# present in Rorange <- Orange[, c('age', 'circumference')] # output to be present as PNG filepng(file = "plot.png") # plottingplot(x = orange$age, y = orange$circumference, xlab = "Age",ylab = "Circumference", main = "Age VS Circumference",col.lab = "darkgreen", col.main = "darkgreen",col.axis = "darkgreen") # saving the filedev.off()
Output:
If a scatter plot has to be drawn to show the relation between 2 or more vectors or to plot the scatter plot matrix between the vectors, then pairs() function is used to satisfy the criteria.
Syntax: pairs(~formula, data)
where,
~formula is the mathematical formula such as ~a+b+c
data is the dataset form where data is taken in formula
Note: To know about more optional parameters in pairs() function, use the below command in R console:
help("pairs")
Example :
R
# output to be present as PNG filepng(file = "plotmatrix.png") # plotting scatterplot matrix# using dataset Orangepairs(~age + circumference, data = Orange,col.axis = "darkgreen") # saving the filedev.off()
Output:
Box plot shows how the data is distributed in the data vector. It represents five values in the graph i.e., minimum, first quartile, second quartile(median), third quartile, the maximum value of the data vector.
Syntax: boxplot(x, xlab, ylab, notch)
where,
x specifies the data vector
xlab specifies the label for x-axis
ylab specifies the label for y-axis
notch, if TRUE then creates notch on both the sides of the box
Note: To know about more optional parameters in boxplot() function, use the below command in R console:
help("boxplot")
Example:
R
# defining vector with ages of employeesx <- c(42, 21, 22, 24, 25, 30, 29, 22, 23, 23, 24, 28, 32, 45, 39, 40) # output to be present as PNG filepng(file = "boxplot.png") # plottingboxplot(x, xlab = "Box Plot", ylab = "Age",col.axis = "darkgreen", col.lab = "darkgreen") # saving the filedev.off()
Output:
kumar_satyam
Picked
Programming Language
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Dec, 2021"
},
{
"code": null,
"e": 245,
"s": 54,
"text": "R language is mostly used for statistics and data analytics purposes to represent the data graphically in the software. To represent those data graphically, charts and graphs are used in R. "
},
{
"code": null,
"e": 407,
"s": 245,
"text": "There are hundreds of charts and graphs present in R. For example, bar plot, box plot, mosaic plot, dot chart, coplot, histogram, pie chart, scatter graph, etc. "
},
{
"code": null,
"e": 429,
"s": 407,
"text": "Bar Plot or Bar Chart"
},
{
"code": null,
"e": 454,
"s": 429,
"text": "Pie Diagram or Pie Chart"
},
{
"code": null,
"e": 464,
"s": 454,
"text": "Histogram"
},
{
"code": null,
"e": 477,
"s": 464,
"text": "Scatter Plot"
},
{
"code": null,
"e": 486,
"s": 477,
"text": "Box Plot"
},
{
"code": null,
"e": 750,
"s": 486,
"text": "Bar plot or Bar Chart in R is used to represent the values in data vector as height of the bars. The data vector passed to the function is represented over y-axis of the graph. Bar chart can behave like histogram by using table() function instead of data vector. "
},
{
"code": null,
"e": 784,
"s": 750,
"text": "Syntax: barplot(data, xlab, ylab)"
},
{
"code": null,
"e": 791,
"s": 784,
"text": "where:"
},
{
"code": null,
"e": 843,
"s": 791,
"text": "data is the data vector to be represented on y-axis"
},
{
"code": null,
"e": 877,
"s": 843,
"text": "xlab is the label given to x-axis"
},
{
"code": null,
"e": 911,
"s": 877,
"text": "ylab is the label given to y-axis"
},
{
"code": null,
"e": 1015,
"s": 911,
"text": "Note: To know about more optional parameters in barplot() function, use the below command in R console:"
},
{
"code": null,
"e": 1031,
"s": 1015,
"text": "help(\"barplot\")"
},
{
"code": null,
"e": 1041,
"s": 1031,
"text": "Example: "
},
{
"code": null,
"e": 1043,
"s": 1041,
"text": "R"
},
{
"code": "# defining vectorx <- c(7, 15, 23, 12, 44, 56, 32) # output to be present as PNG filepng(file = \"barplot.png\") # plotting vectorbarplot(x, xlab = \"GeeksforGeeks Audience\", ylab = \"Count\", col = \"white\", col.axis = \"darkgreen\", col.lab = \"darkgreen\") # saving the filedev.off()",
"e": 1341,
"s": 1043,
"text": null
},
{
"code": null,
"e": 1350,
"s": 1341,
"text": "Output: "
},
{
"code": null,
"e": 1658,
"s": 1350,
"text": "Pie chart is a circular chart divided into different segments according to the ratio of data provided. The total value of the pie is 100 and the segments tell the fraction of the whole pie. It is another method to represent statistical data in graphical form and pie() function is used to perform the same. "
},
{
"code": null,
"e": 1700,
"s": 1658,
"text": "Syntax: pie(x, labels, col, main, radius)"
},
{
"code": null,
"e": 1708,
"s": 1700,
"text": "where, "
},
{
"code": null,
"e": 1725,
"s": 1708,
"text": "x is data vector"
},
{
"code": null,
"e": 1760,
"s": 1725,
"text": "labels shows names given to slices"
},
{
"code": null,
"e": 1813,
"s": 1760,
"text": "col fills the color in the slices as given parameter"
},
{
"code": null,
"e": 1852,
"s": 1813,
"text": "main shows title name of the pie chart"
},
{
"code": null,
"e": 1921,
"s": 1852,
"text": "radius indicates radius of the pie chart. It can be between -1 to +1"
},
{
"code": null,
"e": 2026,
"s": 1921,
"text": "Note: To know about more optional parameters in pie() function, use the below command in the R console: "
},
{
"code": null,
"e": 2038,
"s": 2026,
"text": "help(\"pie\")"
},
{
"code": null,
"e": 2048,
"s": 2038,
"text": "Example: "
},
{
"code": null,
"e": 2158,
"s": 2048,
"text": "Assume, vector x indicates the number of articles present on the GeeksforGeeks portal in categories names(x) "
},
{
"code": null,
"e": 2160,
"s": 2158,
"text": "R"
},
{
"code": "# defining vector x with number of articlesx <- c(210, 450, 250, 100, 50, 90) # defining labels for each value in xnames(x) <- c(\"Algo\", \"DS\", \"Java\", \"C\", \"C++\", \"Python\") # output to be present as PNG filepng(file = \"piechart.png\") # creating pie chartpie(x, labels = names(x), col = \"white\",main = \"Articles on GeeksforGeeks\", radius = -1,col.main = \"darkgreen\") # saving the filedev.off()",
"e": 2553,
"s": 2160,
"text": null
},
{
"code": null,
"e": 2562,
"s": 2553,
"text": "Output: "
},
{
"code": null,
"e": 2660,
"s": 2562,
"text": "Pie chart in 3D can also be created in R by using following syntax but requires plotrix library. "
},
{
"code": null,
"e": 2699,
"s": 2660,
"text": "Syntax: pie3D(x, labels, radius, main)"
},
{
"code": null,
"e": 2798,
"s": 2699,
"text": "Note: To know about more optional parameters in pie3D() function, use below command in R console: "
},
{
"code": null,
"e": 2812,
"s": 2798,
"text": "help(\"pie3D\")"
},
{
"code": null,
"e": 2822,
"s": 2812,
"text": "Example: "
},
{
"code": null,
"e": 2824,
"s": 2822,
"text": "R"
},
{
"code": "# importing library plotrix for pie3D()library(plotrix) # defining vector x with number of articlesx <- c(210, 450, 250, 100, 50, 90) # defining labels for each value in xnames(x) <- c(\"Algo\", \"DS\", \"Java\", \"C\", \"C++\", \"Python\") # output to be present as PNG filepng(file = \"piechart3d.png\") # creating pie chartpie3D(x, labels = names(x), col = \"white\",main = \"Articles on GeeksforGeeks\",labelcol = \"darkgreen\", col.main = \"darkgreen\") # saving the filedev.off()",
"e": 3288,
"s": 2824,
"text": null
},
{
"code": null,
"e": 3297,
"s": 3288,
"text": "Output: "
},
{
"code": null,
"e": 3563,
"s": 3297,
"text": "Histogram is a graphical representation used to create a graph with bars representing the frequency of grouped data in vector. Histogram is same as bar chart but only difference between them is histogram represents frequency of grouped data rather than data itself."
},
{
"code": null,
"e": 3610,
"s": 3563,
"text": "Syntax: hist(x, col, border, main, xlab, ylab)"
},
{
"code": null,
"e": 3617,
"s": 3610,
"text": "where:"
},
{
"code": null,
"e": 3634,
"s": 3617,
"text": "x is data vector"
},
{
"code": null,
"e": 3683,
"s": 3634,
"text": "col specifies the color of the bars to be filled"
},
{
"code": null,
"e": 3728,
"s": 3683,
"text": "border specifies the color of border of bars"
},
{
"code": null,
"e": 3771,
"s": 3728,
"text": "main specifies the title name of histogram"
},
{
"code": null,
"e": 3803,
"s": 3771,
"text": "xlab specifies the x-axis label"
},
{
"code": null,
"e": 3835,
"s": 3803,
"text": "ylab specifies the y-axis label"
},
{
"code": null,
"e": 3933,
"s": 3835,
"text": "Note: To know about more optional parameters in hist() function, use below command in R console: "
},
{
"code": null,
"e": 3946,
"s": 3933,
"text": "help(\"hist\")"
},
{
"code": null,
"e": 3956,
"s": 3946,
"text": "Example: "
},
{
"code": null,
"e": 3958,
"s": 3956,
"text": "R"
},
{
"code": "# defining vectorx <- c(21, 23, 56, 90, 20, 7, 94, 12, 57, 76, 69, 45, 34, 32, 49, 55, 57) # output to be present as PNG filepng(file = \"hist.png\") # hist(x, main = \"Histogram of Vector x\", xlab = \"Values\", col.lab = \"darkgreen\", col.main = \"darkgreen\") # saving the filedev.off()",
"e": 4263,
"s": 3958,
"text": null
},
{
"code": null,
"e": 4272,
"s": 4263,
"text": "Output: "
},
{
"code": null,
"e": 4475,
"s": 4272,
"text": "A Scatter plot is another type of graphical representation used to plot the points to show relationship between two data vectors. One of the data vectors is represented on x-axis and another on y-axis. "
},
{
"code": null,
"e": 4518,
"s": 4475,
"text": "Syntax: plot(x, y, type, xlab, ylab, main)"
},
{
"code": null,
"e": 4526,
"s": 4518,
"text": "Where, "
},
{
"code": null,
"e": 4569,
"s": 4526,
"text": "x is the data vector represented on x-axis"
},
{
"code": null,
"e": 4612,
"s": 4569,
"text": "y is the data vector represented on y-axis"
},
{
"code": null,
"e": 4727,
"s": 4612,
"text": "type specifies the type of plot to be drawn. For example, “l” for lines, “p” for points, “s” for stair steps, etc."
},
{
"code": null,
"e": 4763,
"s": 4727,
"text": "xlab specifies the label for x-axis"
},
{
"code": null,
"e": 4799,
"s": 4763,
"text": "ylab specifies the label for y-axis"
},
{
"code": null,
"e": 4842,
"s": 4799,
"text": "main specifies the title name of the graph"
},
{
"code": null,
"e": 4944,
"s": 4842,
"text": "Note: To know about more optional parameters in plot() function, use the below command in R console: "
},
{
"code": null,
"e": 4957,
"s": 4944,
"text": "help(\"plot\")"
},
{
"code": null,
"e": 4967,
"s": 4957,
"text": "Example: "
},
{
"code": null,
"e": 4969,
"s": 4967,
"text": "R"
},
{
"code": "# taking input from dataset Orange already# present in Rorange <- Orange[, c('age', 'circumference')] # output to be present as PNG filepng(file = \"plot.png\") # plottingplot(x = orange$age, y = orange$circumference, xlab = \"Age\",ylab = \"Circumference\", main = \"Age VS Circumference\",col.lab = \"darkgreen\", col.main = \"darkgreen\",col.axis = \"darkgreen\") # saving the filedev.off()",
"e": 5349,
"s": 4969,
"text": null
},
{
"code": null,
"e": 5358,
"s": 5349,
"text": "Output: "
},
{
"code": null,
"e": 5551,
"s": 5358,
"text": "If a scatter plot has to be drawn to show the relation between 2 or more vectors or to plot the scatter plot matrix between the vectors, then pairs() function is used to satisfy the criteria. "
},
{
"code": null,
"e": 5581,
"s": 5551,
"text": "Syntax: pairs(~formula, data)"
},
{
"code": null,
"e": 5588,
"s": 5581,
"text": "where,"
},
{
"code": null,
"e": 5640,
"s": 5588,
"text": "~formula is the mathematical formula such as ~a+b+c"
},
{
"code": null,
"e": 5696,
"s": 5640,
"text": "data is the dataset form where data is taken in formula"
},
{
"code": null,
"e": 5799,
"s": 5696,
"text": "Note: To know about more optional parameters in pairs() function, use the below command in R console: "
},
{
"code": null,
"e": 5813,
"s": 5799,
"text": "help(\"pairs\")"
},
{
"code": null,
"e": 5824,
"s": 5813,
"text": "Example : "
},
{
"code": null,
"e": 5826,
"s": 5824,
"text": "R"
},
{
"code": "# output to be present as PNG filepng(file = \"plotmatrix.png\") # plotting scatterplot matrix# using dataset Orangepairs(~age + circumference, data = Orange,col.axis = \"darkgreen\") # saving the filedev.off()",
"e": 6033,
"s": 5826,
"text": null
},
{
"code": null,
"e": 6042,
"s": 6033,
"text": "Output: "
},
{
"code": null,
"e": 6254,
"s": 6042,
"text": "Box plot shows how the data is distributed in the data vector. It represents five values in the graph i.e., minimum, first quartile, second quartile(median), third quartile, the maximum value of the data vector."
},
{
"code": null,
"e": 6292,
"s": 6254,
"text": "Syntax: boxplot(x, xlab, ylab, notch)"
},
{
"code": null,
"e": 6300,
"s": 6292,
"text": "where, "
},
{
"code": null,
"e": 6328,
"s": 6300,
"text": "x specifies the data vector"
},
{
"code": null,
"e": 6364,
"s": 6328,
"text": "xlab specifies the label for x-axis"
},
{
"code": null,
"e": 6400,
"s": 6364,
"text": "ylab specifies the label for y-axis"
},
{
"code": null,
"e": 6463,
"s": 6400,
"text": "notch, if TRUE then creates notch on both the sides of the box"
},
{
"code": null,
"e": 6568,
"s": 6463,
"text": "Note: To know about more optional parameters in boxplot() function, use the below command in R console: "
},
{
"code": null,
"e": 6584,
"s": 6568,
"text": "help(\"boxplot\")"
},
{
"code": null,
"e": 6594,
"s": 6584,
"text": "Example: "
},
{
"code": null,
"e": 6596,
"s": 6594,
"text": "R"
},
{
"code": "# defining vector with ages of employeesx <- c(42, 21, 22, 24, 25, 30, 29, 22, 23, 23, 24, 28, 32, 45, 39, 40) # output to be present as PNG filepng(file = \"boxplot.png\") # plottingboxplot(x, xlab = \"Box Plot\", ylab = \"Age\",col.axis = \"darkgreen\", col.lab = \"darkgreen\") # saving the filedev.off()",
"e": 6897,
"s": 6596,
"text": null
},
{
"code": null,
"e": 6906,
"s": 6897,
"text": "Output: "
},
{
"code": null,
"e": 6919,
"s": 6906,
"text": "kumar_satyam"
},
{
"code": null,
"e": 6926,
"s": 6919,
"text": "Picked"
},
{
"code": null,
"e": 6947,
"s": 6926,
"text": "Programming Language"
},
{
"code": null,
"e": 6958,
"s": 6947,
"text": "R Language"
}
] |
How to install Doxygen on Ubuntu | Doxygen is the de facto regular tool for generating documentation from annotated C++ sources, however, it additionally supports different wellknown programming languages akin to C, objective-C, C#, Hypertext Preprocessor, Java, Python, IDL (Corba, Microsoft, and UNO/OpenOffice flavors), Fortran, VHDL and Tcl. This article explains about-“how to install Doxygen on Ubuntu”
To install Doxygen, use the following command –
$ sudo apt-get install doxygen
The sample output should be like this –
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following packages were automatically installed and are no longer required:
libterm-readkey-perl linux-headers-4.4.0-31 linux-headers-4.4.0-31-generic
linux-image-4.4.0-31-generic linux-image-extra-4.4.0-31-generic
linux-signed-image-4.4.0-31-generic
Use 'sudo apt autoremove' to remove them.
The following additional packages will be installed:
libclang1-3.6 libllvm3.6v5 libobjc-5-dev libobjc4
Suggested packages:
doxygen-latex doxygen-doc doxygen-gui graphviz
The following NEW packages will be installed:
doxygen libclang1-3.6 libllvm3.6v5 libobjc-5-dev libobjc4
0 upgraded, 5 newly installed, 0 to remove and 26 not upgraded.
Need to get 15.9 MB of archives.
After this operation, 64.0 MB of additional disk space will be used.
Do you want to continue? [Y/n] y
Get:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 libllvm3.6v5 amd64 1:3.6.2-3ubuntu2 [8,075 kB]
Get:2 http://in.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libobjc4 amd64 5.4.0-6ubuntu1~16.04.4 [111 kB]
Get:3 http://in.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libobjc-5-dev amd64 5.4.0-6ubuntu1~16.04.4 [380 kB]
Get:4 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 libclang1-3.6 amd64 1:3.6.2-3ubuntu2 [3,696 kB]
Get:5 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 doxygen amd64 1.8.11-1 [3,679 kB]
.........................................................................................
To get the more information about Doxygen, use the following command –
$ doxygen --help
The sample output should be like this-
Doxygen version 1.8.11
Copyright Dimitri van Heesch 1997-2015
You can use doxygen in a number of ways:
1) Use doxygen to generate a template configuration file:
doxygen [-s] -g [configName]
If - is used for configName doxygen will write to standard output.
2) Use doxygen to update an old configuration file:
doxygen [-s] -u [configName]
3) Use doxygen to generate documentation using an existing configuration file:
doxygen [configName]
If - is used for configName doxygen will read from standard input.
4) Use doxygen to generate a template file controlling the layout of the
generated documentation:
doxygen -l [layoutFileName.xml]
5) Use doxygen to generate a template style sheet file for RTF, HTML or Latex.
RTF: doxygen -w rtf styleSheetFile
HTML: doxygen -w html headerFile footerFile styleSheetFile [configFile]
LaTeX: doxygen -w latex headerFile footerFile styleSheetFile [configFile]
6) Use doxygen to generate a rtf extensions file
RTF: doxygen -e rtf extensionsFile
........................................................................
To generate documentation of source code, use the following code-
$ doxygen -g sample_text.conf
In the above command, it has generated a file called sample_text.conf which contains the following code as shown below –
# Doxyfile 1.8.11
# This file describes the settings to be used by the documentation system
# doxygen (www.doxygen.org) for a project.
#
# All text after a double hash (##) is considered a comment and is placed in
# front of the TAG it is preceding.
#
# All text after a single hash (#) is considered a comment and will be ignored.
# The format is:
# TAG = value [value, ...]
# For lists, items can also be appended using:
# TAG += value [value, ...]
# Values that contain spaces should be placed between quotes (\" \").
#---------------------------------------------------------------------------
# Project related configuration options
#---------------------------------------------------------------------------
..................................................................................
To generate the documentation, use the following command –
$ doxygen sample_text.conf
The sample output should be like this –
Searching for include files...
Searching for example files...
Searching for images...
Searching for dot files...
Searching for msc files...
Searching for dia files...
Searching for files to exclude
Searching INPUT for files to process...
Searching for files in directory /home/linux
warning: source /home/linux/.dbus is not a readable file or directory... skipping.
Reading and parsing tag files
Parsing files
Preprocessing /home/linux/abc.txt...
Parsing file /home/linux/abc.txt...
Preprocessing /home/linux/bbc.txt...
Parsing file /home/linux/bbc.txt...
Building group list...
Building directory list...
Building namespace list...
Building file list...
Building class list...
Associating documentation with classes...
Computing nesting relations for classes...
Building example list...
Searching for enumerations...
Searching for documented typedefs...
Searching for members imported via using declarations...
Searching for included using directives...
Searching for documented variables...
Building interface member list...
................................................................
To browse the HTML-formatted documentation, use the following command –
$ cd html
/html$ google-chrome index.html
The sample output should be like this –
After this article, you will be able to understand – How to install Doxygen on Ubuntu. In our next articles, we will come up with more Linux based tricks and tips. Keep reading! | [
{
"code": null,
"e": 1436,
"s": 1062,
"text": "Doxygen is the de facto regular tool for generating documentation from annotated C++ sources, however, it additionally supports different wellknown programming languages akin to C, objective-C, C#, Hypertext Preprocessor, Java, Python, IDL (Corba, Microsoft, and UNO/OpenOffice flavors), Fortran, VHDL and Tcl. This article explains about-“how to install Doxygen on Ubuntu”"
},
{
"code": null,
"e": 1484,
"s": 1436,
"text": "To install Doxygen, use the following command –"
},
{
"code": null,
"e": 1515,
"s": 1484,
"text": "$ sudo apt-get install doxygen"
},
{
"code": null,
"e": 1555,
"s": 1515,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 3066,
"s": 1555,
"text": "Reading package lists... Done\nBuilding dependency tree\nReading state information... Done\nThe following packages were automatically installed and are no longer required:\n libterm-readkey-perl linux-headers-4.4.0-31 linux-headers-4.4.0-31-generic\n linux-image-4.4.0-31-generic linux-image-extra-4.4.0-31-generic\n linux-signed-image-4.4.0-31-generic\nUse 'sudo apt autoremove' to remove them.\nThe following additional packages will be installed:\n libclang1-3.6 libllvm3.6v5 libobjc-5-dev libobjc4\nSuggested packages:\n doxygen-latex doxygen-doc doxygen-gui graphviz\nThe following NEW packages will be installed:\n doxygen libclang1-3.6 libllvm3.6v5 libobjc-5-dev libobjc4\n0 upgraded, 5 newly installed, 0 to remove and 26 not upgraded.\nNeed to get 15.9 MB of archives.\nAfter this operation, 64.0 MB of additional disk space will be used.\nDo you want to continue? [Y/n] y\nGet:1 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 libllvm3.6v5 amd64 1:3.6.2-3ubuntu2 [8,075 kB]\nGet:2 http://in.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libobjc4 amd64 5.4.0-6ubuntu1~16.04.4 [111 kB]\nGet:3 http://in.archive.ubuntu.com/ubuntu xenial-updates/main amd64 libobjc-5-dev amd64 5.4.0-6ubuntu1~16.04.4 [380 kB]\nGet:4 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 libclang1-3.6 amd64 1:3.6.2-3ubuntu2 [3,696 kB]\nGet:5 http://in.archive.ubuntu.com/ubuntu xenial/main amd64 doxygen amd64 1.8.11-1 [3,679 kB]\n........................................................................................."
},
{
"code": null,
"e": 3137,
"s": 3066,
"text": "To get the more information about Doxygen, use the following command –"
},
{
"code": null,
"e": 3154,
"s": 3137,
"text": "$ doxygen --help"
},
{
"code": null,
"e": 3193,
"s": 3154,
"text": "The sample output should be like this-"
},
{
"code": null,
"e": 4284,
"s": 3193,
"text": "Doxygen version 1.8.11\nCopyright Dimitri van Heesch 1997-2015\n\nYou can use doxygen in a number of ways:\n\n1) Use doxygen to generate a template configuration file:\n doxygen [-s] -g [configName]\n\n If - is used for configName doxygen will write to standard output.\n\n2) Use doxygen to update an old configuration file:\n doxygen [-s] -u [configName]\n\n3) Use doxygen to generate documentation using an existing configuration file:\n doxygen [configName]\n\n If - is used for configName doxygen will read from standard input.\n\n4) Use doxygen to generate a template file controlling the layout of the\ngenerated documentation:\n doxygen -l [layoutFileName.xml]\n\n5) Use doxygen to generate a template style sheet file for RTF, HTML or Latex.\n RTF: doxygen -w rtf styleSheetFile\n HTML: doxygen -w html headerFile footerFile styleSheetFile [configFile]\n LaTeX: doxygen -w latex headerFile footerFile styleSheetFile [configFile]\n\n6) Use doxygen to generate a rtf extensions file\n RTF: doxygen -e rtf extensionsFile\n........................................................................"
},
{
"code": null,
"e": 4350,
"s": 4284,
"text": "To generate documentation of source code, use the following code-"
},
{
"code": null,
"e": 4380,
"s": 4350,
"text": "$ doxygen -g sample_text.conf"
},
{
"code": null,
"e": 4501,
"s": 4380,
"text": "In the above command, it has generated a file called sample_text.conf which contains the following code as shown below –"
},
{
"code": null,
"e": 5302,
"s": 4501,
"text": "# Doxyfile 1.8.11\n\n# This file describes the settings to be used by the documentation system\n# doxygen (www.doxygen.org) for a project.\n#\n# All text after a double hash (##) is considered a comment and is placed in\n# front of the TAG it is preceding.\n#\n# All text after a single hash (#) is considered a comment and will be ignored.\n# The format is:\n# TAG = value [value, ...]\n# For lists, items can also be appended using:\n# TAG += value [value, ...]\n# Values that contain spaces should be placed between quotes (\\\" \\\").\n\n#---------------------------------------------------------------------------\n# Project related configuration options\n#---------------------------------------------------------------------------\n\n.................................................................................."
},
{
"code": null,
"e": 5361,
"s": 5302,
"text": "To generate the documentation, use the following command –"
},
{
"code": null,
"e": 5388,
"s": 5361,
"text": "$ doxygen sample_text.conf"
},
{
"code": null,
"e": 5428,
"s": 5388,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6520,
"s": 5428,
"text": "Searching for include files...\nSearching for example files...\nSearching for images...\nSearching for dot files...\nSearching for msc files...\nSearching for dia files...\nSearching for files to exclude\nSearching INPUT for files to process...\nSearching for files in directory /home/linux\nwarning: source /home/linux/.dbus is not a readable file or directory... skipping.\nReading and parsing tag files\nParsing files\nPreprocessing /home/linux/abc.txt...\nParsing file /home/linux/abc.txt...\nPreprocessing /home/linux/bbc.txt...\nParsing file /home/linux/bbc.txt...\nBuilding group list...\nBuilding directory list...\nBuilding namespace list...\nBuilding file list...\nBuilding class list...\nAssociating documentation with classes...\nComputing nesting relations for classes...\nBuilding example list...\nSearching for enumerations...\nSearching for documented typedefs...\nSearching for members imported via using declarations...\nSearching for included using directives...\nSearching for documented variables...\nBuilding interface member list...\n................................................................"
},
{
"code": null,
"e": 6592,
"s": 6520,
"text": "To browse the HTML-formatted documentation, use the following command –"
},
{
"code": null,
"e": 6634,
"s": 6592,
"text": "$ cd html\n/html$ google-chrome index.html"
},
{
"code": null,
"e": 6674,
"s": 6634,
"text": "The sample output should be like this –"
},
{
"code": null,
"e": 6852,
"s": 6674,
"text": "After this article, you will be able to understand – How to install Doxygen on Ubuntu. In our next articles, we will come up with more Linux based tricks and tips. Keep reading!"
}
] |
How to add two arrays into a new array in JavaScript? | Let’s say the following is our first array −
var firstArray=["John","David","Bob","Mike"];
Following is our second array −
var secondArray=["Chris","Adam","James","Carol"];
To add the above two arrays into a new array, use concat().
Following is the code −
var firstArray=["John","David","Bob","Mike"];
var secondArray=["Chris","Adam","James","Carol"];
var thirdArray=firstArray.concat(secondArray);
console.log("First Array value=");
console.log(firstArray);
console.log("Second Array value=");
console.log(secondArray);
console.log("Third Array value=");
console.log(thirdArray);
To run the above program, you need to use the following command −
node fileName.js.
Here, my file name is demo249.js.
This will produce the following output on console −
PS C:\Users\Amit\javascript-code> node demo249.js
First Array value=
[ 'John', 'David', 'Bob', 'Mike' ]
Second Array value=
[ 'Chris', 'Adam', 'James', 'Carol' ]
Third Array value=
[
'John', 'David',
'Bob', 'Mike',
'Chris', 'Adam',
'James', 'Carol'
] | [
{
"code": null,
"e": 1107,
"s": 1062,
"text": "Let’s say the following is our first array −"
},
{
"code": null,
"e": 1153,
"s": 1107,
"text": "var firstArray=[\"John\",\"David\",\"Bob\",\"Mike\"];"
},
{
"code": null,
"e": 1185,
"s": 1153,
"text": "Following is our second array −"
},
{
"code": null,
"e": 1235,
"s": 1185,
"text": "var secondArray=[\"Chris\",\"Adam\",\"James\",\"Carol\"];"
},
{
"code": null,
"e": 1295,
"s": 1235,
"text": "To add the above two arrays into a new array, use concat()."
},
{
"code": null,
"e": 1319,
"s": 1295,
"text": "Following is the code −"
},
{
"code": null,
"e": 1644,
"s": 1319,
"text": "var firstArray=[\"John\",\"David\",\"Bob\",\"Mike\"];\nvar secondArray=[\"Chris\",\"Adam\",\"James\",\"Carol\"];\nvar thirdArray=firstArray.concat(secondArray);\nconsole.log(\"First Array value=\");\nconsole.log(firstArray);\nconsole.log(\"Second Array value=\");\nconsole.log(secondArray);\nconsole.log(\"Third Array value=\");\nconsole.log(thirdArray);"
},
{
"code": null,
"e": 1710,
"s": 1644,
"text": "To run the above program, you need to use the following command −"
},
{
"code": null,
"e": 1728,
"s": 1710,
"text": "node fileName.js."
},
{
"code": null,
"e": 1762,
"s": 1728,
"text": "Here, my file name is demo249.js."
},
{
"code": null,
"e": 1814,
"s": 1762,
"text": "This will produce the following output on console −"
},
{
"code": null,
"e": 2080,
"s": 1814,
"text": "PS C:\\Users\\Amit\\javascript-code> node demo249.js\nFirst Array value=\n[ 'John', 'David', 'Bob', 'Mike' ]\nSecond Array value=\n[ 'Chris', 'Adam', 'James', 'Carol' ]\nThird Array value=\n[\n 'John', 'David',\n 'Bob', 'Mike',\n 'Chris', 'Adam',\n 'James', 'Carol'\n]"
}
] |
Log Transformation Base For Data Linearization Does Not Matter | by Jeremy Chow | Towards Data Science | Code for this demonstration can be found here:
Today a colleague asked me a simple question:
“How do you find the best logarithm base to linearly transform your data?”
This is actually a trick question, because there is no best log base to linearly transform your data — the fact that you are taking a log will linearize it no matter what the base of the log is.
My colleague was skeptical and I wanted to brush up on my algebra, so let’s dive into the math!
Let’s assume you have exponential data. This means your data is in some form similar to the following:
This means our data is non-linear. Linear data is arguably the best form of data we can model, because through linear regression we can directly quantify the effects of each feature on the target variable by looking at its coefficient. Linear regression is the best type of model for giving humans an intuitive and quantitative sense of how the model thinks our dependent variable is influenced by our independent variables versus, for example, the black boxes of deep neural nets.
Since we know the base here is e, we can linearize our data by taking the natural log of both sides (ignoring the constant C1):
Now if we plot ln(y) vs. x, we get a line. That’s pretty straightforward, but what happens if we didn’t know that the base of our power was e? We can try taking the log (base 10) of both sides:
but it doesn’t seem to look linear yet. However, what if we introduce the logarithm power rule?
But log(e) is a constant! therefore we have:
This means that our base 10 log is still directly proportional to x, just by a different scaling factor C, which is the log of the original base e in this case.
We can also visualize this with some python code!
import numpy as npimport matplotlib.pyplot as plt# Set up variables, x is 1-9 and y is e^xx = list(np.linspace(1,10,100))y= [np.exp(i) for i in x]# Plot the original variables - this is barebones plotting code, you # can find the more detailed plotting code on my github!plt.plot(x,y)# Plot log base 10 of yplt.plot(x,np.log10(y))# Plot log base e of yplt.plot(x,np.log(y))
The only thing that changed between the two logarithms was the y-scale because the slopes are slightly different! The important part is that both are still linearly proportional with x, and thus would have equal performance in a linear regression model.
In summary: If you have exponential data, you can do a log transformation of any base to linearize the data. If you have an intuition for the base from domain knowledge, then use the correct base — otherwise it doesn’t matter.
What if your data is in the slightly different form of x raised to the power of some unknown λ?
In this case, a Box-Cox transformation will help you find the ideal power to raise your data to in order to linearize it. I recommend using Sci-py’s implementation.
That’s all for this one, thanks for reading! | [
{
"code": null,
"e": 219,
"s": 172,
"text": "Code for this demonstration can be found here:"
},
{
"code": null,
"e": 265,
"s": 219,
"text": "Today a colleague asked me a simple question:"
},
{
"code": null,
"e": 340,
"s": 265,
"text": "“How do you find the best logarithm base to linearly transform your data?”"
},
{
"code": null,
"e": 535,
"s": 340,
"text": "This is actually a trick question, because there is no best log base to linearly transform your data — the fact that you are taking a log will linearize it no matter what the base of the log is."
},
{
"code": null,
"e": 631,
"s": 535,
"text": "My colleague was skeptical and I wanted to brush up on my algebra, so let’s dive into the math!"
},
{
"code": null,
"e": 734,
"s": 631,
"text": "Let’s assume you have exponential data. This means your data is in some form similar to the following:"
},
{
"code": null,
"e": 1216,
"s": 734,
"text": "This means our data is non-linear. Linear data is arguably the best form of data we can model, because through linear regression we can directly quantify the effects of each feature on the target variable by looking at its coefficient. Linear regression is the best type of model for giving humans an intuitive and quantitative sense of how the model thinks our dependent variable is influenced by our independent variables versus, for example, the black boxes of deep neural nets."
},
{
"code": null,
"e": 1344,
"s": 1216,
"text": "Since we know the base here is e, we can linearize our data by taking the natural log of both sides (ignoring the constant C1):"
},
{
"code": null,
"e": 1538,
"s": 1344,
"text": "Now if we plot ln(y) vs. x, we get a line. That’s pretty straightforward, but what happens if we didn’t know that the base of our power was e? We can try taking the log (base 10) of both sides:"
},
{
"code": null,
"e": 1634,
"s": 1538,
"text": "but it doesn’t seem to look linear yet. However, what if we introduce the logarithm power rule?"
},
{
"code": null,
"e": 1679,
"s": 1634,
"text": "But log(e) is a constant! therefore we have:"
},
{
"code": null,
"e": 1840,
"s": 1679,
"text": "This means that our base 10 log is still directly proportional to x, just by a different scaling factor C, which is the log of the original base e in this case."
},
{
"code": null,
"e": 1890,
"s": 1840,
"text": "We can also visualize this with some python code!"
},
{
"code": null,
"e": 2265,
"s": 1890,
"text": "import numpy as npimport matplotlib.pyplot as plt# Set up variables, x is 1-9 and y is e^xx = list(np.linspace(1,10,100))y= [np.exp(i) for i in x]# Plot the original variables - this is barebones plotting code, you # can find the more detailed plotting code on my github!plt.plot(x,y)# Plot log base 10 of yplt.plot(x,np.log10(y))# Plot log base e of yplt.plot(x,np.log(y))"
},
{
"code": null,
"e": 2519,
"s": 2265,
"text": "The only thing that changed between the two logarithms was the y-scale because the slopes are slightly different! The important part is that both are still linearly proportional with x, and thus would have equal performance in a linear regression model."
},
{
"code": null,
"e": 2746,
"s": 2519,
"text": "In summary: If you have exponential data, you can do a log transformation of any base to linearize the data. If you have an intuition for the base from domain knowledge, then use the correct base — otherwise it doesn’t matter."
},
{
"code": null,
"e": 2842,
"s": 2746,
"text": "What if your data is in the slightly different form of x raised to the power of some unknown λ?"
},
{
"code": null,
"e": 3007,
"s": 2842,
"text": "In this case, a Box-Cox transformation will help you find the ideal power to raise your data to in order to linearize it. I recommend using Sci-py’s implementation."
}
] |
Tryit Editor v3.7 | Padding & Spacing
Tryit: HTML table - space between cells | [
{
"code": null,
"e": 40,
"s": 22,
"text": "Padding & Spacing"
}
] |
Design File System in Python | Suppose we have to design a file system which provides these two functions −
createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist.
createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.
get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist.
The format of a path is one or more concatenated strings of the form − (forward slash) / followed by one or more lowercase English letters. For example, /programming and /programming/problems are valid paths while an empty string and / are not. Here we have to implement these two functions.
So as input, if we create a file-system, then create a path using [‘/a’, 1], then after using get(), with parameter [‘/a’], the output will be 1.
To solve this, we will follow these steps −
Define a map d
The createPath method will take path and value, this will act like −
p := list of components of path split by ‘/’
x := d
for i in range 1 to length of p – 1if p[i] is not present in x, then return falsex := x[p[i]][1]
if p[i] is not present in x, then return false
x := x[p[i]][1]
if last element of p is in x, then return false
x[last element of p] := a list with v and empty map
return true
The get() method is taking the path
x := d
p := list of components of path split by ‘/’
for i in range 1 to length of p – 1if p[i] is not present in x, then return -1x := x[p[i]][1]
if p[i] is not present in x, then return -1
x := x[p[i]][1]
if last element of p is in x, then return x[last element of p][0], otherwise return -1
Let us see the following implementation to get a better understanding −
Live Demo
class FileSystem(object):
def __init__(self):
self.d = {}
def create(self, p, v):
p = p.split("/")
x = self.d
for i in range(1,len(p)-1):
if p[i] not in x:
return False
x = x[p[i]][1]
if p[-1] in x:
return False
x[p[-1]] = [v,{}]
return True
def get(self, p):
x = self.d
p = p.split("/")
for i in range(1,len(p)-1):
if p[i] not in x:
return -1
x= x[p[i]][1]
if p[-1] in x:
return x[p[-1]][0]
else:
return -1
ob = FileSystem()
print(ob.create("/a", 1))
print(ob.get("/a"))
Initialize the object, then call createPath(“/a”, 1) and get(“/a”)
True
1 | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "Suppose we have to design a file system which provides these two functions −"
},
{
"code": null,
"e": 1422,
"s": 1139,
"text": "createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist.get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist."
},
{
"code": null,
"e": 1609,
"s": 1422,
"text": "createPath(path, value) − This creates a new path and associates a value to it if possible and returns True. It returns False if the path already exists or its parent path doesn't exist."
},
{
"code": null,
"e": 1706,
"s": 1609,
"text": "get(path) − This finds the value associated with a path or returns -1 if the path doesn't exist."
},
{
"code": null,
"e": 1998,
"s": 1706,
"text": "The format of a path is one or more concatenated strings of the form − (forward slash) / followed by one or more lowercase English letters. For example, /programming and /programming/problems are valid paths while an empty string and / are not. Here we have to implement these two functions."
},
{
"code": null,
"e": 2144,
"s": 1998,
"text": "So as input, if we create a file-system, then create a path using [‘/a’, 1], then after using get(), with parameter [‘/a’], the output will be 1."
},
{
"code": null,
"e": 2188,
"s": 2144,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 2203,
"s": 2188,
"text": "Define a map d"
},
{
"code": null,
"e": 2272,
"s": 2203,
"text": "The createPath method will take path and value, this will act like −"
},
{
"code": null,
"e": 2317,
"s": 2272,
"text": "p := list of components of path split by ‘/’"
},
{
"code": null,
"e": 2324,
"s": 2317,
"text": "x := d"
},
{
"code": null,
"e": 2421,
"s": 2324,
"text": "for i in range 1 to length of p – 1if p[i] is not present in x, then return falsex := x[p[i]][1]"
},
{
"code": null,
"e": 2468,
"s": 2421,
"text": "if p[i] is not present in x, then return false"
},
{
"code": null,
"e": 2484,
"s": 2468,
"text": "x := x[p[i]][1]"
},
{
"code": null,
"e": 2532,
"s": 2484,
"text": "if last element of p is in x, then return false"
},
{
"code": null,
"e": 2584,
"s": 2532,
"text": "x[last element of p] := a list with v and empty map"
},
{
"code": null,
"e": 2596,
"s": 2584,
"text": "return true"
},
{
"code": null,
"e": 2632,
"s": 2596,
"text": "The get() method is taking the path"
},
{
"code": null,
"e": 2639,
"s": 2632,
"text": "x := d"
},
{
"code": null,
"e": 2684,
"s": 2639,
"text": "p := list of components of path split by ‘/’"
},
{
"code": null,
"e": 2778,
"s": 2684,
"text": "for i in range 1 to length of p – 1if p[i] is not present in x, then return -1x := x[p[i]][1]"
},
{
"code": null,
"e": 2822,
"s": 2778,
"text": "if p[i] is not present in x, then return -1"
},
{
"code": null,
"e": 2838,
"s": 2822,
"text": "x := x[p[i]][1]"
},
{
"code": null,
"e": 2925,
"s": 2838,
"text": "if last element of p is in x, then return x[last element of p][0], otherwise return -1"
},
{
"code": null,
"e": 2997,
"s": 2925,
"text": "Let us see the following implementation to get a better understanding −"
},
{
"code": null,
"e": 3008,
"s": 2997,
"text": " Live Demo"
},
{
"code": null,
"e": 3648,
"s": 3008,
"text": "class FileSystem(object):\n def __init__(self):\n self.d = {}\n def create(self, p, v):\n p = p.split(\"/\")\n x = self.d\n for i in range(1,len(p)-1):\n if p[i] not in x:\n return False\n x = x[p[i]][1]\n if p[-1] in x:\n return False\n x[p[-1]] = [v,{}]\n return True\n def get(self, p):\n x = self.d\n p = p.split(\"/\")\n for i in range(1,len(p)-1):\n if p[i] not in x:\n return -1\n x= x[p[i]][1]\n if p[-1] in x:\n return x[p[-1]][0]\n else:\n return -1\nob = FileSystem()\nprint(ob.create(\"/a\", 1))\nprint(ob.get(\"/a\"))"
},
{
"code": null,
"e": 3715,
"s": 3648,
"text": "Initialize the object, then call createPath(“/a”, 1) and get(“/a”)"
},
{
"code": null,
"e": 3722,
"s": 3715,
"text": "True\n1"
}
] |
Replace first occurrence of a character in Java | To replace the first occurrence of a character in Java, use the replaceFirst() method.
Here is our string.
String str = "The Haunting of Hill House!";
Let us replace the first occurrence of character “H”
str.replaceFirst("(?:H)+", "B");
The following is the complete example.
Live Demo
public class Demo {
public static void main(String[] args) {
String str = "The Haunting of Hill House!";
System.out.println("String: "+str);
String res = str.replaceFirst("(?:H)+", "B");
System.out.println("String after replacing a character's first occurrence: "+res);
}
}
String: The Haunting of Hill House!
String after replacing a character's first occurance: The Baunting of Hill House! | [
{
"code": null,
"e": 1149,
"s": 1062,
"text": "To replace the first occurrence of a character in Java, use the replaceFirst() method."
},
{
"code": null,
"e": 1169,
"s": 1149,
"text": "Here is our string."
},
{
"code": null,
"e": 1213,
"s": 1169,
"text": "String str = \"The Haunting of Hill House!\";"
},
{
"code": null,
"e": 1266,
"s": 1213,
"text": "Let us replace the first occurrence of character “H”"
},
{
"code": null,
"e": 1299,
"s": 1266,
"text": "str.replaceFirst(\"(?:H)+\", \"B\");"
},
{
"code": null,
"e": 1338,
"s": 1299,
"text": "The following is the complete example."
},
{
"code": null,
"e": 1349,
"s": 1338,
"text": " Live Demo"
},
{
"code": null,
"e": 1659,
"s": 1349,
"text": "public class Demo {\n public static void main(String[] args) {\n String str = \"The Haunting of Hill House!\";\n System.out.println(\"String: \"+str);\n String res = str.replaceFirst(\"(?:H)+\", \"B\");\n System.out.println(\"String after replacing a character's first occurrence: \"+res);\n }\n}"
},
{
"code": null,
"e": 1777,
"s": 1659,
"text": "String: The Haunting of Hill House!\nString after replacing a character's first occurance: The Baunting of Hill House!"
}
] |
Gensim - Developing Word Embedding | The chapter will help us understand developing word embedding in Gensim.
Word embedding, approach to represent words & document, is a dense vector representation for text where words having the same meaning have a similar representation. Following are some characteristics of word embedding −
It is a class of technique which represents the individual words as real-valued vectors in a pre-defined vector space.
It is a class of technique which represents the individual words as real-valued vectors in a pre-defined vector space.
This technique is often lumped into the field of DL (deep learning) because every word is mapped to one vector and the vector values are learned in the same way a NN (Neural Networks) does.
This technique is often lumped into the field of DL (deep learning) because every word is mapped to one vector and the vector values are learned in the same way a NN (Neural Networks) does.
The key approach of word embedding technique is a dense distributed representation for every word.
The key approach of word embedding technique is a dense distributed representation for every word.
As discussed above, word embedding methods/algorithms learn a real-valued vector representation from a corpus of text. This learning process can either use with the NN model on task like document classification or is an unsupervised process such as document statistics. Here we are going to discuss two methods/algorithm that can be used to learn a word embedding from text −
Word2Vec, developed by Tomas Mikolov, et. al. at Google in 2013, is a statistical method for efficiently learning a word embedding from text corpus. It’s actually developed as a response to make NN based training of word embedding more efficient. It has become the de facto standard for word embedding.
Word embedding by Word2Vec involves analysis of the learned vectors as well as exploration of vector math on representation of words. Following are the two different learning methods which can be used as the part of Word2Vec method −
CBoW(Continuous Bag of Words) Model
Continuous Skip-Gram Model
GloVe(Global vectors for Word Representation), is an extension to the Word2Vec method. It was developed by Pennington et al. at Stanford. GloVe algorithm is a mix of both −
Global statistics of matrix factorization techniques like LSA (Latent Semantic Analysis)
Local context-based learning in Word2Vec.
If we talk about its working then instead of using a window to define local context, GloVe constructs an explicit word co-occurrence matrix using statistics across the whole text corpus.
Here, we will develop Word2Vec embedding by using Gensim. In order to work with a Word2Vec model, Gensim provides us Word2Vec class which can be imported from models.word2vec. For its implementation, word2vec requires a lot of text e.g. the entire Amazon review corpus. But here, we will apply this principle on small-in memory text.
First we need to import the Word2Vec class from gensim.models as follows −
from gensim.models import Word2Vec
Next, we need to define the training data. Rather than taking big text file, we are using some sentences to implement this principal.
sentences = [
['this', 'is', 'gensim', 'tutorial', 'for', 'free'],
['this', 'is', 'the', 'tutorials' 'point', 'website'],
['you', 'can', 'read', 'technical','tutorials', 'for','free'],
['we', 'are', 'implementing','word2vec'],
['learn', 'full', 'gensim', 'tutorial']
]
Once the training data is provided, we need to train the model. it can be done as follows −
model = Word2Vec(sentences, min_count=1)
We can summarise the model as follows −;
print(model)
We can summarise the vocabulary as follows −
words = list(model.wv.vocab)
print(words)
Next, let’s access the vector for one word. We are doing it for the word ‘tutorial’.
print(model['tutorial'])
Next, we need to save the model −
model.save('model.bin')
Next, we need to load the model −
new_model = Word2Vec.load('model.bin')
Finally, print the saved model as follows −
print(new_model)
from gensim.models import Word2Vec
sentences = [
['this', 'is', 'gensim', 'tutorial', 'for', 'free'],
['this', 'is', 'the', 'tutorials' 'point', 'website'],
['you', 'can', 'read', 'technical','tutorials', 'for','free'],
['we', 'are', 'implementing','word2vec'],
['learn', 'full', 'gensim', 'tutorial']
]
model = Word2Vec(sentences, min_count=1)
print(model)
words = list(model.wv.vocab)
print(words)
print(model['tutorial'])
model.save('model.bin')
new_model = Word2Vec.load('model.bin')
print(new_model)
Word2Vec(vocab=20, size=100, alpha=0.025)
[
'this', 'is', 'gensim', 'tutorial', 'for', 'free', 'the', 'tutorialspoint',
'website', 'you', 'can', 'read', 'technical', 'tutorials', 'we', 'are',
'implementing', 'word2vec', 'learn', 'full'
]
[
-2.5256255e-03 -4.5352755e-03 3.9024993e-03 -4.9509313e-03
-1.4255195e-03 -4.0217536e-03 4.9407515e-03 -3.5925603e-03
-1.1933431e-03 -4.6682903e-03 1.5440651e-03 -1.4101702e-03
3.5070938e-03 1.0914479e-03 2.3334436e-03 2.4452661e-03
-2.5336299e-04 -3.9676363e-03 -8.5054158e-04 1.6443320e-03
-4.9968651e-03 1.0974540e-03 -1.1123562e-03 1.5393364e-03
9.8941079e-04 -1.2656028e-03 -4.4471184e-03 1.8309267e-03
4.9302122e-03 -1.0032534e-03 4.6892050e-03 2.9563988e-03
1.8730218e-03 1.5343715e-03 -1.2685956e-03 8.3664013e-04
4.1721235e-03 1.9445885e-03 2.4097660e-03 3.7517555e-03
4.9687522e-03 -1.3598346e-03 7.1032363e-04 -3.6595813e-03
6.0000515e-04 3.0872561e-03 -3.2115565e-03 3.2270295e-03
-2.6354722e-03 -3.4988276e-04 1.8574356e-04 -3.5757164e-03
7.5391348e-04 -3.5205986e-03 -1.9795434e-03 -2.8321696e-03
4.7155009e-03 -4.3349937e-04 -1.5320212e-03 2.7013756e-03
-3.7055744e-03 -4.1658725e-03 4.8034848e-03 4.8594419e-03
3.7129463e-03 4.2385766e-03 2.4612297e-03 5.4920948e-04
-3.8912550e-03 -4.8226118e-03 -2.2763973e-04 4.5571579e-03
-3.4609400e-03 2.7903817e-03 -3.2709218e-03 -1.1036445e-03
2.1492650e-03 -3.0384419e-04 1.7709908e-03 1.8429896e-03
-3.4038599e-03 -2.4872608e-03 2.7693063e-03 -1.6352943e-03
1.9182395e-03 3.7772327e-03 2.2769428e-03 -4.4629495e-03
3.3151123e-03 4.6509290e-03 -4.8521687e-03 6.7615538e-04
3.1034781e-03 2.6369948e-05 4.1454583e-03 -3.6932561e-03
-1.8769916e-03 -2.1958587e-04 6.3395966e-04 -2.4969708e-03
]
Word2Vec(vocab=20, size=100, alpha=0.025)
We can also explore the word embedding with visualisation. It can be done by using a classical projection method (like PCA) to reduce the high-dimensional word vectors to 2-D plots. Once reduced, we can then plot them on graph.
First, we need to retrieve all the vectors from a trained model as follows −
Z = model[model.wv.vocab]
Next, we need to create a 2-D PCA model of word vectors by using PCA class as follows −
pca = PCA(n_components=2)
result = pca.fit_transform(Z)
Now, we can plot the resulting projection by using the matplotlib as follows −
Pyplot.scatter(result[:,0],result[:,1])
We can also annotate the points on the graph with the words itself. Plot the resulting projection by using the matplotlib as follows −
words = list(model.wv.vocab)
for i, word in enumerate(words):
pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))
from gensim.models import Word2Vec
from sklearn.decomposition import PCA
from matplotlib import pyplot
sentences = [
['this', 'is', 'gensim', 'tutorial', 'for', 'free'],
['this', 'is', 'the', 'tutorials' 'point', 'website'],
['you', 'can', 'read', 'technical','tutorials', 'for','free'],
['we', 'are', 'implementing','word2vec'],
['learn', 'full', 'gensim', 'tutorial']
]
model = Word2Vec(sentences, min_count=1)
X = model[model.wv.vocab]
pca = PCA(n_components=2)
result = pca.fit_transform(X)
pyplot.scatter(result[:, 0], result[:, 1])
words = list(model.wv.vocab)
for i, word in enumerate(words):
pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))
pyplot.show()
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2125,
"s": 2052,
"text": "The chapter will help us understand developing word embedding in Gensim."
},
{
"code": null,
"e": 2345,
"s": 2125,
"text": "Word embedding, approach to represent words & document, is a dense vector representation for text where words having the same meaning have a similar representation. Following are some characteristics of word embedding −"
},
{
"code": null,
"e": 2464,
"s": 2345,
"text": "It is a class of technique which represents the individual words as real-valued vectors in a pre-defined vector space."
},
{
"code": null,
"e": 2583,
"s": 2464,
"text": "It is a class of technique which represents the individual words as real-valued vectors in a pre-defined vector space."
},
{
"code": null,
"e": 2773,
"s": 2583,
"text": "This technique is often lumped into the field of DL (deep learning) because every word is mapped to one vector and the vector values are learned in the same way a NN (Neural Networks) does."
},
{
"code": null,
"e": 2963,
"s": 2773,
"text": "This technique is often lumped into the field of DL (deep learning) because every word is mapped to one vector and the vector values are learned in the same way a NN (Neural Networks) does."
},
{
"code": null,
"e": 3062,
"s": 2963,
"text": "The key approach of word embedding technique is a dense distributed representation for every word."
},
{
"code": null,
"e": 3161,
"s": 3062,
"text": "The key approach of word embedding technique is a dense distributed representation for every word."
},
{
"code": null,
"e": 3537,
"s": 3161,
"text": "As discussed above, word embedding methods/algorithms learn a real-valued vector representation from a corpus of text. This learning process can either use with the NN model on task like document classification or is an unsupervised process such as document statistics. Here we are going to discuss two methods/algorithm that can be used to learn a word embedding from text −"
},
{
"code": null,
"e": 3840,
"s": 3537,
"text": "Word2Vec, developed by Tomas Mikolov, et. al. at Google in 2013, is a statistical method for efficiently learning a word embedding from text corpus. It’s actually developed as a response to make NN based training of word embedding more efficient. It has become the de facto standard for word embedding."
},
{
"code": null,
"e": 4074,
"s": 3840,
"text": "Word embedding by Word2Vec involves analysis of the learned vectors as well as exploration of vector math on representation of words. Following are the two different learning methods which can be used as the part of Word2Vec method −"
},
{
"code": null,
"e": 4110,
"s": 4074,
"text": "CBoW(Continuous Bag of Words) Model"
},
{
"code": null,
"e": 4137,
"s": 4110,
"text": "Continuous Skip-Gram Model"
},
{
"code": null,
"e": 4310,
"s": 4137,
"text": "GloVe(Global vectors for Word Representation), is an extension to the Word2Vec method. It was developed by Pennington et al. at Stanford. GloVe algorithm is a mix of both −"
},
{
"code": null,
"e": 4399,
"s": 4310,
"text": "Global statistics of matrix factorization techniques like LSA (Latent Semantic Analysis)"
},
{
"code": null,
"e": 4441,
"s": 4399,
"text": "Local context-based learning in Word2Vec."
},
{
"code": null,
"e": 4628,
"s": 4441,
"text": "If we talk about its working then instead of using a window to define local context, GloVe constructs an explicit word co-occurrence matrix using statistics across the whole text corpus."
},
{
"code": null,
"e": 4962,
"s": 4628,
"text": "Here, we will develop Word2Vec embedding by using Gensim. In order to work with a Word2Vec model, Gensim provides us Word2Vec class which can be imported from models.word2vec. For its implementation, word2vec requires a lot of text e.g. the entire Amazon review corpus. But here, we will apply this principle on small-in memory text."
},
{
"code": null,
"e": 5037,
"s": 4962,
"text": "First we need to import the Word2Vec class from gensim.models as follows −"
},
{
"code": null,
"e": 5073,
"s": 5037,
"text": "from gensim.models import Word2Vec\n"
},
{
"code": null,
"e": 5207,
"s": 5073,
"text": "Next, we need to define the training data. Rather than taking big text file, we are using some sentences to implement this principal."
},
{
"code": null,
"e": 5492,
"s": 5207,
"text": "sentences = [\n ['this', 'is', 'gensim', 'tutorial', 'for', 'free'],\n ['this', 'is', 'the', 'tutorials' 'point', 'website'],\n ['you', 'can', 'read', 'technical','tutorials', 'for','free'],\n ['we', 'are', 'implementing','word2vec'],\n ['learn', 'full', 'gensim', 'tutorial']\n]\n"
},
{
"code": null,
"e": 5584,
"s": 5492,
"text": "Once the training data is provided, we need to train the model. it can be done as follows −"
},
{
"code": null,
"e": 5626,
"s": 5584,
"text": "model = Word2Vec(sentences, min_count=1)\n"
},
{
"code": null,
"e": 5667,
"s": 5626,
"text": "We can summarise the model as follows −;"
},
{
"code": null,
"e": 5681,
"s": 5667,
"text": "print(model)\n"
},
{
"code": null,
"e": 5726,
"s": 5681,
"text": "We can summarise the vocabulary as follows −"
},
{
"code": null,
"e": 5769,
"s": 5726,
"text": "words = list(model.wv.vocab)\nprint(words)\n"
},
{
"code": null,
"e": 5854,
"s": 5769,
"text": "Next, let’s access the vector for one word. We are doing it for the word ‘tutorial’."
},
{
"code": null,
"e": 5880,
"s": 5854,
"text": "print(model['tutorial'])\n"
},
{
"code": null,
"e": 5914,
"s": 5880,
"text": "Next, we need to save the model −"
},
{
"code": null,
"e": 5939,
"s": 5914,
"text": "model.save('model.bin')\n"
},
{
"code": null,
"e": 5973,
"s": 5939,
"text": "Next, we need to load the model −"
},
{
"code": null,
"e": 6013,
"s": 5973,
"text": "new_model = Word2Vec.load('model.bin')\n"
},
{
"code": null,
"e": 6057,
"s": 6013,
"text": "Finally, print the saved model as follows −"
},
{
"code": null,
"e": 6075,
"s": 6057,
"text": "print(new_model)\n"
},
{
"code": null,
"e": 6595,
"s": 6075,
"text": "from gensim.models import Word2Vec\nsentences = [\n ['this', 'is', 'gensim', 'tutorial', 'for', 'free'],\n ['this', 'is', 'the', 'tutorials' 'point', 'website'],\n ['you', 'can', 'read', 'technical','tutorials', 'for','free'],\n ['we', 'are', 'implementing','word2vec'],\n ['learn', 'full', 'gensim', 'tutorial']\n]\nmodel = Word2Vec(sentences, min_count=1)\nprint(model)\nwords = list(model.wv.vocab)\nprint(words)\nprint(model['tutorial'])\nmodel.save('model.bin')\nnew_model = Word2Vec.load('model.bin')\nprint(new_model)"
},
{
"code": null,
"e": 8413,
"s": 6595,
"text": "Word2Vec(vocab=20, size=100, alpha=0.025)\n[\n 'this', 'is', 'gensim', 'tutorial', 'for', 'free', 'the', 'tutorialspoint', \n 'website', 'you', 'can', 'read', 'technical', 'tutorials', 'we', 'are', \n 'implementing', 'word2vec', 'learn', 'full'\n]\n[\n -2.5256255e-03 -4.5352755e-03 3.9024993e-03 -4.9509313e-03\n -1.4255195e-03 -4.0217536e-03 4.9407515e-03 -3.5925603e-03\n -1.1933431e-03 -4.6682903e-03 1.5440651e-03 -1.4101702e-03\n 3.5070938e-03 1.0914479e-03 2.3334436e-03 2.4452661e-03\n -2.5336299e-04 -3.9676363e-03 -8.5054158e-04 1.6443320e-03\n -4.9968651e-03 1.0974540e-03 -1.1123562e-03 1.5393364e-03\n 9.8941079e-04 -1.2656028e-03 -4.4471184e-03 1.8309267e-03\n 4.9302122e-03 -1.0032534e-03 4.6892050e-03 2.9563988e-03\n 1.8730218e-03 1.5343715e-03 -1.2685956e-03 8.3664013e-04\n 4.1721235e-03 1.9445885e-03 2.4097660e-03 3.7517555e-03\n 4.9687522e-03 -1.3598346e-03 7.1032363e-04 -3.6595813e-03\n 6.0000515e-04 3.0872561e-03 -3.2115565e-03 3.2270295e-03\n -2.6354722e-03 -3.4988276e-04 1.8574356e-04 -3.5757164e-03\n 7.5391348e-04 -3.5205986e-03 -1.9795434e-03 -2.8321696e-03\n 4.7155009e-03 -4.3349937e-04 -1.5320212e-03 2.7013756e-03\n -3.7055744e-03 -4.1658725e-03 4.8034848e-03 4.8594419e-03\n 3.7129463e-03 4.2385766e-03 2.4612297e-03 5.4920948e-04\n -3.8912550e-03 -4.8226118e-03 -2.2763973e-04 4.5571579e-03\n -3.4609400e-03 2.7903817e-03 -3.2709218e-03 -1.1036445e-03\n 2.1492650e-03 -3.0384419e-04 1.7709908e-03 1.8429896e-03\n -3.4038599e-03 -2.4872608e-03 2.7693063e-03 -1.6352943e-03\n 1.9182395e-03 3.7772327e-03 2.2769428e-03 -4.4629495e-03\n 3.3151123e-03 4.6509290e-03 -4.8521687e-03 6.7615538e-04\n 3.1034781e-03 2.6369948e-05 4.1454583e-03 -3.6932561e-03\n -1.8769916e-03 -2.1958587e-04 6.3395966e-04 -2.4969708e-03\n]\nWord2Vec(vocab=20, size=100, alpha=0.025)\n"
},
{
"code": null,
"e": 8641,
"s": 8413,
"text": "We can also explore the word embedding with visualisation. It can be done by using a classical projection method (like PCA) to reduce the high-dimensional word vectors to 2-D plots. Once reduced, we can then plot them on graph."
},
{
"code": null,
"e": 8718,
"s": 8641,
"text": "First, we need to retrieve all the vectors from a trained model as follows −"
},
{
"code": null,
"e": 8745,
"s": 8718,
"text": "Z = model[model.wv.vocab]\n"
},
{
"code": null,
"e": 8833,
"s": 8745,
"text": "Next, we need to create a 2-D PCA model of word vectors by using PCA class as follows −"
},
{
"code": null,
"e": 8890,
"s": 8833,
"text": "pca = PCA(n_components=2)\nresult = pca.fit_transform(Z)\n"
},
{
"code": null,
"e": 8969,
"s": 8890,
"text": "Now, we can plot the resulting projection by using the matplotlib as follows −"
},
{
"code": null,
"e": 9010,
"s": 8969,
"text": "Pyplot.scatter(result[:,0],result[:,1])\n"
},
{
"code": null,
"e": 9145,
"s": 9010,
"text": "We can also annotate the points on the graph with the words itself. Plot the resulting projection by using the matplotlib as follows −"
},
{
"code": null,
"e": 9266,
"s": 9145,
"text": "words = list(model.wv.vocab)\nfor i, word in enumerate(words):\n pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))\n"
},
{
"code": null,
"e": 9946,
"s": 9266,
"text": "from gensim.models import Word2Vec\nfrom sklearn.decomposition import PCA\nfrom matplotlib import pyplot\nsentences = [\n ['this', 'is', 'gensim', 'tutorial', 'for', 'free'],\n\t['this', 'is', 'the', 'tutorials' 'point', 'website'],\n\t['you', 'can', 'read', 'technical','tutorials', 'for','free'],\n\t['we', 'are', 'implementing','word2vec'],\n\t['learn', 'full', 'gensim', 'tutorial']\n]\nmodel = Word2Vec(sentences, min_count=1)\nX = model[model.wv.vocab]\npca = PCA(n_components=2)\nresult = pca.fit_transform(X)\npyplot.scatter(result[:, 0], result[:, 1])\nwords = list(model.wv.vocab)\nfor i, word in enumerate(words):\n pyplot.annotate(word, xy=(result[i, 0], result[i, 1]))\npyplot.show()\n"
},
{
"code": null,
"e": 9953,
"s": 9946,
"text": " Print"
},
{
"code": null,
"e": 9964,
"s": 9953,
"text": " Add Notes"
}
] |
Python - Relational Databases | We can connect to relational databases for analysing data using the pandas library as well as another additional library for implementing database connectivity.
This package is named as sqlalchemy which provides full SQL language functionality to be used in python.
The installation is very straight forward using Anaconda which we have discussed in the chapter Data Science Environment. Assuming you have installed Anaconda as described in this chapter,
run the following command in the Anaconda Prompt Window to install the SQLAlchemy package.
conda install sqlalchemy
We will use Sqlite3 as our relational database as it is very light weight and easy to use. Though the SQLAlchemy library can connect to a variety of relational sources including MySql, Oracle and Postgresql and Mssql.
We first create a database engine and then connect to the database engine using the to_sql function of the SQLAlchemy library.
In the below example we create the relational table by using the to_sql function from a dataframe already created by reading a csv file.
Then we use the read_sql_query function from pandas to execute and capture the results from various SQL queries.
from sqlalchemy import create_engine
import pandas as pd
data = pd.read_csv('/path/input.csv')
# Create the db engine
engine = create_engine('sqlite:///:memory:')
# Store the dataframe as a table
data.to_sql('data_table', engine)
# Query 1 on the relational table
res1 = pd.read_sql_query('SELECT * FROM data_table', engine)
print('Result 1')
print(res1)
print('')
# Query 2 on the relational table
res2 = pd.read_sql_query('SELECT dept,sum(salary) FROM data_table group by dept', engine)
print('Result 2')
print(res2)
When we execute the above code, it produces the following result.
Result 1
index id name salary start_date dept
0 0 1 Rick 623.30 2012-01-01 IT
1 1 2 Dan 515.20 2013-09-23 Operations
2 2 3 Tusar 611.00 2014-11-15 IT
3 3 4 Ryan 729.00 2014-05-11 HR
4 4 5 Gary 843.25 2015-03-27 Finance
5 5 6 Rasmi 578.00 2013-05-21 IT
6 6 7 Pranab 632.80 2013-07-30 Operations
7 7 8 Guru 722.50 2014-06-17 Finance
Result 2
dept sum(salary)
0 Finance 1565.75
1 HR 729.00
2 IT 1812.30
3 Operations 1148.00
We can also insert data into relational tables using sql.execute function available in pandas. In the below code we previous csv file as input data set, store it in a relational table and then
insert another record using sql.execute.
from sqlalchemy import create_engine
from pandas.io import sql
import pandas as pd
data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')
# Store the Data in a relational table
data.to_sql('data_table', engine)
# Insert another row
sql.execute('INSERT INTO data_table VALUES(?,?,?,?,?,?)', engine, params=[('id',9,'Ruby',711.20,'2015-03-27','IT')])
# Read from the relational table
res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)
When we execute the above code, it produces the following result.
id dept name salary start_date
0 1 IT Rick 623.30 2012-01-01
1 2 Operations Dan 515.20 2013-09-23
2 3 IT Tusar 611.00 2014-11-15
3 4 HR Ryan 729.00 2014-05-11
4 5 Finance Gary 843.25 2015-03-27
5 6 IT Rasmi 578.00 2013-05-21
6 7 Operations Pranab 632.80 2013-07-30
7 8 Finance Guru 722.50 2014-06-17
8 9 IT Ruby 711.20 2015-03-27
We can also delete data into relational tables using sql.execute function available in pandas. The below code deletes a row based on the input condition given.
from sqlalchemy import create_engine
from pandas.io import sql
import pandas as pd
data = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')
engine = create_engine('sqlite:///:memory:')
data.to_sql('data_table', engine)
sql.execute('Delete from data_table where name = (?) ', engine, params=[('Gary')])
res = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)
print(res)
When we execute the above code, it produces the following result.
id dept name salary start_date
0 1 IT Rick 623.3 2012-01-01
1 2 Operations Dan 515.2 2013-09-23
2 3 IT Tusar 611.0 2014-11-15
3 4 HR Ryan 729.0 2014-05-11
4 6 IT Rasmi 578.0 2013-05-21
5 7 Operations Pranab 632.8 2013-07-30
6 8 Finance Guru 722.5 2014-06-17
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": 2795,
"s": 2529,
"text": "We can connect to relational databases for analysing data using the pandas library as well as another additional library for implementing database connectivity.\nThis package is named as sqlalchemy which provides full SQL language functionality to be used in python."
},
{
"code": null,
"e": 3075,
"s": 2795,
"text": "The installation is very straight forward using Anaconda which we have discussed in the chapter Data Science Environment. Assuming you have installed Anaconda as described in this chapter,\nrun the following command in the Anaconda Prompt Window to install the SQLAlchemy package."
},
{
"code": null,
"e": 3100,
"s": 3075,
"text": "conda install sqlalchemy"
},
{
"code": null,
"e": 3445,
"s": 3100,
"text": "We will use Sqlite3 as our relational database as it is very light weight and easy to use. Though the SQLAlchemy library can connect to a variety of relational sources including MySql, Oracle and Postgresql and Mssql.\nWe first create a database engine and then connect to the database engine using the to_sql function of the SQLAlchemy library."
},
{
"code": null,
"e": 3695,
"s": 3445,
"text": "In the below example we create the relational table by using the to_sql function from a dataframe already created by reading a csv file.\nThen we use the read_sql_query function from pandas to execute and capture the results from various SQL queries."
},
{
"code": null,
"e": 4219,
"s": 3695,
"text": "from sqlalchemy import create_engine\nimport pandas as pd\n\ndata = pd.read_csv('/path/input.csv')\n\n# Create the db engine\nengine = create_engine('sqlite:///:memory:')\n\n# Store the dataframe as a table\ndata.to_sql('data_table', engine)\n\n# Query 1 on the relational table\nres1 = pd.read_sql_query('SELECT * FROM data_table', engine)\nprint('Result 1')\nprint(res1)\nprint('')\n\n# Query 2 on the relational table\nres2 = pd.read_sql_query('SELECT dept,sum(salary) FROM data_table group by dept', engine)\nprint('Result 2')\nprint(res2)"
},
{
"code": null,
"e": 4285,
"s": 4219,
"text": "When we execute the above code, it produces the following result."
},
{
"code": null,
"e": 4917,
"s": 4285,
"text": "Result 1\n index id name salary start_date dept\n0 0 1 Rick 623.30 2012-01-01 IT\n1 1 2 Dan 515.20 2013-09-23 Operations\n2 2 3 Tusar 611.00 2014-11-15 IT\n3 3 4 Ryan 729.00 2014-05-11 HR\n4 4 5 Gary 843.25 2015-03-27 Finance\n5 5 6 Rasmi 578.00 2013-05-21 IT\n6 6 7 Pranab 632.80 2013-07-30 Operations\n7 7 8 Guru 722.50 2014-06-17 Finance\n\nResult 2\n dept sum(salary)\n0 Finance 1565.75\n1 HR 729.00\n2 IT 1812.30\n3 Operations 1148.00\n"
},
{
"code": null,
"e": 5151,
"s": 4917,
"text": "We can also insert data into relational tables using sql.execute function available in pandas. In the below code we previous csv file as input data set, store it in a relational table and then\ninsert another record using sql.execute."
},
{
"code": null,
"e": 5695,
"s": 5151,
"text": "from sqlalchemy import create_engine\nfrom pandas.io import sql\n\nimport pandas as pd\n\ndata = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')\nengine = create_engine('sqlite:///:memory:')\n\n# Store the Data in a relational table\ndata.to_sql('data_table', engine)\n\n# Insert another row\nsql.execute('INSERT INTO data_table VALUES(?,?,?,?,?,?)', engine, params=[('id',9,'Ruby',711.20,'2015-03-27','IT')])\n\n# Read from the relational table\nres = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)\nprint(res)"
},
{
"code": null,
"e": 5761,
"s": 5695,
"text": "When we execute the above code, it produces the following result."
},
{
"code": null,
"e": 6221,
"s": 5761,
"text": " id dept name salary start_date\n0 1 IT Rick 623.30 2012-01-01\n1 2 Operations Dan 515.20 2013-09-23\n2 3 IT Tusar 611.00 2014-11-15\n3 4 HR Ryan 729.00 2014-05-11\n4 5 Finance Gary 843.25 2015-03-27\n5 6 IT Rasmi 578.00 2013-05-21\n6 7 Operations Pranab 632.80 2013-07-30\n7 8 Finance Guru 722.50 2014-06-17\n8 9 IT Ruby 711.20 2015-03-27"
},
{
"code": null,
"e": 6381,
"s": 6221,
"text": "We can also delete data into relational tables using sql.execute function available in pandas. The below code deletes a row based on the input condition given."
},
{
"code": null,
"e": 6799,
"s": 6381,
"text": "from sqlalchemy import create_engine\nfrom pandas.io import sql\n\nimport pandas as pd\n\ndata = pd.read_csv('C:/Users/Rasmi/Documents/pydatasci/input.csv')\nengine = create_engine('sqlite:///:memory:')\ndata.to_sql('data_table', engine)\n\nsql.execute('Delete from data_table where name = (?) ', engine, params=[('Gary')])\n\nres = pd.read_sql_query('SELECT ID,Dept,Name,Salary,start_date FROM data_table', engine)\nprint(res)\n"
},
{
"code": null,
"e": 6865,
"s": 6799,
"text": "When we execute the above code, it produces the following result."
},
{
"code": null,
"e": 7233,
"s": 6865,
"text": " id dept name salary start_date\n0 1 IT Rick 623.3 2012-01-01\n1 2 Operations Dan 515.2 2013-09-23\n2 3 IT Tusar 611.0 2014-11-15\n3 4 HR Ryan 729.0 2014-05-11\n4 6 IT Rasmi 578.0 2013-05-21\n5 7 Operations Pranab 632.8 2013-07-30\n6 8 Finance Guru 722.5 2014-06-17"
},
{
"code": null,
"e": 7270,
"s": 7233,
"text": "\n 187 Lectures \n 17.5 hours \n"
},
{
"code": null,
"e": 7286,
"s": 7270,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 7319,
"s": 7286,
"text": "\n 55 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 7338,
"s": 7319,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 7373,
"s": 7338,
"text": "\n 136 Lectures \n 11 hours \n"
},
{
"code": null,
"e": 7395,
"s": 7373,
"text": " In28Minutes Official"
},
{
"code": null,
"e": 7429,
"s": 7395,
"text": "\n 75 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 7457,
"s": 7429,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 7492,
"s": 7457,
"text": "\n 70 Lectures \n 8.5 hours \n"
},
{
"code": null,
"e": 7506,
"s": 7492,
"text": " Lets Kode It"
},
{
"code": null,
"e": 7539,
"s": 7506,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7556,
"s": 7539,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 7563,
"s": 7556,
"text": " Print"
},
{
"code": null,
"e": 7574,
"s": 7563,
"text": " Add Notes"
}
] |
Hidden Bootstrap class | To hide a Bootstrap class, use the .hidden class.
You can try to run the following code to hide a class −
Live Demo
<!DOCTYPE html>
<html>
<head>
<title>Bootstrap Example</title>
<link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet">
<script src = "/scripts/jquery.min.js"></script>
<script src = "/bootstrap/js/bootstrap.min.js"></script>
</head>
<body>
<div class = "row" style = "padding: 91px 100px 19px 50px;">
<div class = "show" style = "left-margin:10px; width:300px; background-color:#ccc;">
This class is visible.
</div>
<div class = "hidden" style = "width:200px; background-color:#ccc;">
This is an example for hide class. This will be hidden.
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1112,
"s": 1062,
"text": "To hide a Bootstrap class, use the .hidden class."
},
{
"code": null,
"e": 1168,
"s": 1112,
"text": "You can try to run the following code to hide a class −"
},
{
"code": null,
"e": 1178,
"s": 1168,
"text": "Live Demo"
},
{
"code": null,
"e": 1869,
"s": 1178,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"row\" style = \"padding: 91px 100px 19px 50px;\">\n <div class = \"show\" style = \"left-margin:10px; width:300px; background-color:#ccc;\">\n This class is visible.\n </div>\n <div class = \"hidden\" style = \"width:200px; background-color:#ccc;\">\n This is an example for hide class. This will be hidden.\n </div>\n </div>\n </body>\n</html>"
}
] |
Laravel - Authentication | Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated.
Laravel uses the following command to create forms and the associated controllers to perform authentication −
php artisan make:auth
This command helps in creating authentication scaffolding successfully, as shown in the following screenshot −
The controller which is used for the authentication process is HomeController.
<?php
namespace App\Http\Controllers;
use App\Http\Requests;
use Illuminate\Http\Request;
class HomeController extends Controller{
/**
* Create a new controller instance.
*
* @return void
*/
public function __construct() {
$this->middleware('auth');
}
/**
* Show the application dashboard.
*
* @return \Illuminate\Http\Response
*/
public function index() {
return view('home');
}
}
As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below −
Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password.
Consider the following lines of code for LoginController which includes all the functions for authentication −
<?php
// Authentication mechanism
namespace App\Http\Controllers;
use Illuminate\Support\Facades\Auth;
class LoginController extends Controller{
/**
* Handling authentication request
*
* @return Response
*/
public function authenticate() {
if (Auth::attempt(['email' => $email, 'password' => $password])) {
// Authentication passed...
return redirect()->intended('dashboard');
}
}
}
13 Lectures
3 hours
Sebastian Sulinski
35 Lectures
3.5 hours
Antonio Papa
7 Lectures
1.5 hours
Sebastian Sulinski
42 Lectures
1 hours
Skillbakerystudios
165 Lectures
13 hours
Paul Carlo Tordecilla
116 Lectures
13 hours
Hafizullah Masoudi
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2760,
"s": 2472,
"text": "Authentication is the process of identifying the user credentials. In web applications, authentication is managed by sessions which take the input parameters such as email or username and password, for user identification. If these parameters match, the user is said to be authenticated."
},
{
"code": null,
"e": 2870,
"s": 2760,
"text": "Laravel uses the following command to create forms and the associated controllers to perform authentication −"
},
{
"code": null,
"e": 2893,
"s": 2870,
"text": "php artisan make:auth\n"
},
{
"code": null,
"e": 3004,
"s": 2893,
"text": "This command helps in creating authentication scaffolding successfully, as shown in the following screenshot −"
},
{
"code": null,
"e": 3083,
"s": 3004,
"text": "The controller which is used for the authentication process is HomeController."
},
{
"code": null,
"e": 3552,
"s": 3083,
"text": "<?php\n\nnamespace App\\Http\\Controllers;\n\nuse App\\Http\\Requests;\nuse Illuminate\\Http\\Request;\n\nclass HomeController extends Controller{\n /**\n * Create a new controller instance.\n *\n * @return void\n */\n \n public function __construct() {\n $this->middleware('auth');\n }\n \n /**\n * Show the application dashboard.\n *\n * @return \\Illuminate\\Http\\Response\n */\n \n public function index() {\n return view('home');\n }\n}"
},
{
"code": null,
"e": 3706,
"s": 3552,
"text": "As a result, the scaffold application generated creates the login page and the registration page for performing authentication. They are as shown below −"
},
{
"code": null,
"e": 3853,
"s": 3706,
"text": "Laravel uses the Auth façade which helps in manually authenticating the users. It includes the attempt method to verify their email and password."
},
{
"code": null,
"e": 3964,
"s": 3853,
"text": "Consider the following lines of code for LoginController which includes all the functions for authentication −"
},
{
"code": null,
"e": 4421,
"s": 3964,
"text": "<?php\n\n// Authentication mechanism\nnamespace App\\Http\\Controllers;\n\nuse Illuminate\\Support\\Facades\\Auth;\n\nclass LoginController extends Controller{\n /**\n * Handling authentication request\n *\n * @return Response\n */\n \n public function authenticate() {\n if (Auth::attempt(['email' => $email, 'password' => $password])) {\n \n // Authentication passed...\n return redirect()->intended('dashboard');\n }\n }\n}"
},
{
"code": null,
"e": 4454,
"s": 4421,
"text": "\n 13 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 4474,
"s": 4454,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 4509,
"s": 4474,
"text": "\n 35 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 4523,
"s": 4509,
"text": " Antonio Papa"
},
{
"code": null,
"e": 4557,
"s": 4523,
"text": "\n 7 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 4577,
"s": 4557,
"text": " Sebastian Sulinski"
},
{
"code": null,
"e": 4610,
"s": 4577,
"text": "\n 42 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 4630,
"s": 4610,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 4665,
"s": 4630,
"text": "\n 165 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4688,
"s": 4665,
"text": " Paul Carlo Tordecilla"
},
{
"code": null,
"e": 4723,
"s": 4688,
"text": "\n 116 Lectures \n 13 hours \n"
},
{
"code": null,
"e": 4743,
"s": 4723,
"text": " Hafizullah Masoudi"
},
{
"code": null,
"e": 4750,
"s": 4743,
"text": " Print"
},
{
"code": null,
"e": 4761,
"s": 4750,
"text": " Add Notes"
}
] |
Android - Drag and Drop | Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality −
Drag event class.
Drag event class.
Drag listeners.
Drag listeners.
Helper methods and classes.
Helper methods and classes.
There are basically four steps or states in the drag and drop process −
Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.
The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.
Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.
To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.
Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.
The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.
Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.
To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED.
Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object's appearance in response to the event or can react by highlighting its View.
The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.
Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object's appearance in response to the event or can react by highlighting its View.
The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View.
Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object's listener a drag event with action type ACTION_DROP.
Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object's listener a drag event with action type ACTION_DROP.
Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.
Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over.
The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process.
Following are all constants integers available as a part of DragEvent class.
ACTION_DRAG_STARTED
Signals the start of a drag and drop operation.
ACTION_DRAG_ENTERED
Signals to a View that the drag point has entered the bounding box of the View.
ACTION_DRAG_LOCATION
Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object's bounding box.
ACTION_DRAG_EXITED
Signals that the user has moved the drag shadow outside the bounding box of the View.
ACTION_DROP
Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View.
ACTION_DRAG_ENDED
Signals to a View that the drag and drop operation has concluded.
Following are few important and most frequently used methods available as a part of DragEvent class.
int getAction()
Inspect the action value of this event..
ClipData getClipData()
Returns the ClipData object sent to the system as part of the call to startDrag().
ClipDescription getClipDescription()
Returns the ClipDescription object contained in the ClipData.
boolean getResult()
Returns an indication of the result of the drag and drop operation.
float getX()
Gets the X coordinate of the drag point.
float getY()
Gets the Y coordinate of the drag point.
String toString()
Returns a string representation of this DragEvent object.
If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true.
The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android.
You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object.
Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that's the same size as the View argument passed to it, with the touch point centered in the drag shadow.
Following example shows the functionality of a simple Drag & Drop using View.setOnLongClickListener(), View.setOnTouchListener()and View.OnDragEventListener().
Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods.
package com.example.saira_000.myapplication;
import android.app.Activity;
import android.content.ClipData;
import android.content.ClipDescription;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.DragEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
public class MainActivity extends Activity {
ImageView img;
String msg;
private android.widget.RelativeLayout.LayoutParams layoutParams;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
img=(ImageView)findViewById(R.id.imageView);
img.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());
String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};
ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item);
View.DragShadowBuilder myShadow = new View.DragShadowBuilder(img);
v.startDrag(dragData,myShadow,null,0);
return true;
}
});
img.setOnDragListener(new View.OnDragListener() {
@Override
public boolean onDrag(View v, DragEvent event) {
switch(event.getAction()) {
case DragEvent.ACTION_DRAG_STARTED:
layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();
Log.d(msg, "Action is DragEvent.ACTION_DRAG_STARTED");
// Do nothing
break;
case DragEvent.ACTION_DRAG_ENTERED:
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENTERED");
int x_cord = (int) event.getX();
int y_cord = (int) event.getY();
break;
case DragEvent.ACTION_DRAG_EXITED :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_EXITED");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
layoutParams.leftMargin = x_cord;
layoutParams.topMargin = y_cord;
v.setLayoutParams(layoutParams);
break;
case DragEvent.ACTION_DRAG_LOCATION :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_LOCATION");
x_cord = (int) event.getX();
y_cord = (int) event.getY();
break;
case DragEvent.ACTION_DRAG_ENDED :
Log.d(msg, "Action is DragEvent.ACTION_DRAG_ENDED");
// Do nothing
break;
case DragEvent.ACTION_DROP:
Log.d(msg, "ACTION_DROP event");
// Do nothing
break;
default: break;
}
return true;
}
});
img.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
ClipData data = ClipData.newPlainText("", "");
View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(img);
img.startDrag(data, shadowBuilder, img, 0);
img.setVisibility(View.INVISIBLE);
return true;
} else {
return false;
}
}
});
}
}
Following will be the content of res/layout/activity_main.xml file −
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Drag and Drop Example"
android:id="@+id/textView"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:textSize="30dp" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials Point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_centerHorizontal="true"
android:textSize="30dp"
android:textColor="#ff14be3c" />>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_alignRight="@+id/textView2"
android:layout_alignEnd="@+id/textView2"
android:layout_alignLeft="@+id/textView2"
android:layout_alignStart="@+id/textView2" />
</RelativeLayout>
Following will be the content of res/values/strings.xml to define two new constants −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
</resources>
Following is the default content of AndroidManifest.xml −
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.saira_000.myapplication" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −
Now do long click on the displayed TutorialsPoint logo and you will see that logo image moves a little after 1 seconds long click from its place, its the time when you should start dragging the image. You can drag it around the screen and drop it at a new location.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3938,
"s": 3607,
"text": "Android drag/drop framework allows your users to move data from one View to another View in the current layout using a graphical drag and drop gesture. As of API 11 drag and drop of view onto other views or view groups is supported.The framework includes following three important components to support drag & drop functionality −"
},
{
"code": null,
"e": 3956,
"s": 3938,
"text": "Drag event class."
},
{
"code": null,
"e": 3974,
"s": 3956,
"text": "Drag event class."
},
{
"code": null,
"e": 3990,
"s": 3974,
"text": "Drag listeners."
},
{
"code": null,
"e": 4006,
"s": 3990,
"text": "Drag listeners."
},
{
"code": null,
"e": 4034,
"s": 4006,
"text": "Helper methods and classes."
},
{
"code": null,
"e": 4062,
"s": 4034,
"text": "Helper methods and classes."
},
{
"code": null,
"e": 4134,
"s": 4062,
"text": "There are basically four steps or states in the drag and drop process −"
},
{
"code": null,
"e": 5005,
"s": 4134,
"text": "Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow.\nThe system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device.\nNext, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout.\nTo continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED."
},
{
"code": null,
"e": 5298,
"s": 5005,
"text": "Started − This event occurs when you start dragging an item in a layout, your application calls startDrag() method to tell the system to start a drag. The arguments inside startDrag() method provide the data to be dragged, metadata for this data, and a callback for drawing the drag shadow."
},
{
"code": null,
"e": 5430,
"s": 5298,
"text": "The system first responds by calling back to your application to get a drag shadow. It then displays the drag shadow on the device."
},
{
"code": null,
"e": 5590,
"s": 5430,
"text": "Next, the system sends a drag event with action type ACTION_DRAG_STARTED to the registered drag event listeners for all the View objects in the current layout."
},
{
"code": null,
"e": 5876,
"s": 5590,
"text": "To continue to receive drag events, including a possible drop event, a drag event listener must return true, If the drag event listener returns false, then it will not receive drag events for the current operation until the system sends a drag event with action type ACTION_DRAG_ENDED."
},
{
"code": null,
"e": 6345,
"s": 5876,
"text": "Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object's appearance in response to the event or can react by highlighting its View.\nThe drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View."
},
{
"code": null,
"e": 6674,
"s": 6345,
"text": "Continuing − The user continues the drag. System sends ACTION_DRAG_ENTERED action followed by ACTION_DRAG_LOCATION action to the registered drag event listener for the View where dragging point enters. The listener may choose to alter its View object's appearance in response to the event or can react by highlighting its View."
},
{
"code": null,
"e": 6814,
"s": 6674,
"text": "The drag event listener receives a ACTION_DRAG_EXITED action after the user has moved the drag shadow outside the bounding box of the View."
},
{
"code": null,
"e": 6981,
"s": 6814,
"text": "Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object's listener a drag event with action type ACTION_DROP."
},
{
"code": null,
"e": 7148,
"s": 6981,
"text": "Dropped − The user releases the dragged item within the bounding box of a View. The system sends the View object's listener a drag event with action type ACTION_DROP."
},
{
"code": null,
"e": 7310,
"s": 7148,
"text": "Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over."
},
{
"code": null,
"e": 7472,
"s": 7310,
"text": "Ended − Just after the action type ACTION_DROP, the system sends out a drag event with action type ACTION_DRAG_ENDED to indicate that the drag operation is over."
},
{
"code": null,
"e": 7683,
"s": 7472,
"text": "The DragEvent represents an event that is sent out by the system at various times during a drag and drop operation. This class provides few Constants and important methods which we use during Drag/Drop process."
},
{
"code": null,
"e": 7760,
"s": 7683,
"text": "Following are all constants integers available as a part of DragEvent class."
},
{
"code": null,
"e": 7780,
"s": 7760,
"text": "ACTION_DRAG_STARTED"
},
{
"code": null,
"e": 7828,
"s": 7780,
"text": "Signals the start of a drag and drop operation."
},
{
"code": null,
"e": 7848,
"s": 7828,
"text": "ACTION_DRAG_ENTERED"
},
{
"code": null,
"e": 7928,
"s": 7848,
"text": "Signals to a View that the drag point has entered the bounding box of the View."
},
{
"code": null,
"e": 7949,
"s": 7928,
"text": "ACTION_DRAG_LOCATION"
},
{
"code": null,
"e": 8057,
"s": 7949,
"text": "Sent to a View after ACTION_DRAG_ENTERED if the drag shadow is still within the View object's bounding box."
},
{
"code": null,
"e": 8076,
"s": 8057,
"text": "ACTION_DRAG_EXITED"
},
{
"code": null,
"e": 8162,
"s": 8076,
"text": "Signals that the user has moved the drag shadow outside the bounding box of the View."
},
{
"code": null,
"e": 8174,
"s": 8162,
"text": "ACTION_DROP"
},
{
"code": null,
"e": 8295,
"s": 8174,
"text": "Signals to a View that the user has released the drag shadow, and the drag point is within the bounding box of the View."
},
{
"code": null,
"e": 8313,
"s": 8295,
"text": "ACTION_DRAG_ENDED"
},
{
"code": null,
"e": 8379,
"s": 8313,
"text": "Signals to a View that the drag and drop operation has concluded."
},
{
"code": null,
"e": 8480,
"s": 8379,
"text": "Following are few important and most frequently used methods available as a part of DragEvent class."
},
{
"code": null,
"e": 8496,
"s": 8480,
"text": "int getAction()"
},
{
"code": null,
"e": 8537,
"s": 8496,
"text": "Inspect the action value of this event.."
},
{
"code": null,
"e": 8560,
"s": 8537,
"text": "ClipData getClipData()"
},
{
"code": null,
"e": 8643,
"s": 8560,
"text": "Returns the ClipData object sent to the system as part of the call to startDrag()."
},
{
"code": null,
"e": 8680,
"s": 8643,
"text": "ClipDescription getClipDescription()"
},
{
"code": null,
"e": 8742,
"s": 8680,
"text": "Returns the ClipDescription object contained in the ClipData."
},
{
"code": null,
"e": 8762,
"s": 8742,
"text": "boolean getResult()"
},
{
"code": null,
"e": 8830,
"s": 8762,
"text": "Returns an indication of the result of the drag and drop operation."
},
{
"code": null,
"e": 8843,
"s": 8830,
"text": "float\tgetX()"
},
{
"code": null,
"e": 8884,
"s": 8843,
"text": "Gets the X coordinate of the drag point."
},
{
"code": null,
"e": 8897,
"s": 8884,
"text": "float getY()"
},
{
"code": null,
"e": 8938,
"s": 8897,
"text": "Gets the Y coordinate of the drag point."
},
{
"code": null,
"e": 8956,
"s": 8938,
"text": "String toString()"
},
{
"code": null,
"e": 9014,
"s": 8956,
"text": "Returns a string representation of this DragEvent object."
},
{
"code": null,
"e": 9468,
"s": 9014,
"text": "If you want any of your views within a Layout should respond Drag event then your view either implements View.OnDragListener or setup onDragEvent(DragEvent) callback method. When the system calls the method or listener, it passes to them a DragEvent object explained above. You can have both a listener and a callback method for View object. If this occurs, the system first calls the listener and then defined callback as long as listener returns true."
},
{
"code": null,
"e": 9675,
"s": 9468,
"text": "The combination of the onDragEvent(DragEvent) method and View.OnDragListener is analogous to the combination of the onTouchEvent() and View.OnTouchListener used with touch events in old versions of Android."
},
{
"code": null,
"e": 9989,
"s": 9675,
"text": "You start with creating a ClipData and ClipData.Item for the data being moved. As part of the ClipData object, supply metadata that is stored in a ClipDescription object within the ClipData. For a drag and drop operation that does not represent data movement, you may want to use null instead of an actual object."
},
{
"code": null,
"e": 10283,
"s": 9989,
"text": "Next either you can extend extend View.DragShadowBuilder to create a drag shadow for dragging the view or simply you can use View.DragShadowBuilder(View) to create a default drag shadow that's the same size as the View argument passed to it, with the touch point centered in the drag shadow."
},
{
"code": null,
"e": 10443,
"s": 10283,
"text": "Following example shows the functionality of a simple Drag & Drop using View.setOnLongClickListener(), View.setOnTouchListener()and View.OnDragEventListener()."
},
{
"code": null,
"e": 10591,
"s": 10443,
"text": "Following is the content of the modified main activity file src/MainActivity.java. This file can include each of the fundamental lifecycle methods."
},
{
"code": null,
"e": 14411,
"s": 10591,
"text": "package com.example.saira_000.myapplication;\n\nimport android.app.Activity;\n\nimport android.content.ClipData;\nimport android.content.ClipDescription;\n\nimport android.support.v7.app.ActionBarActivity;\nimport android.os.Bundle;\nimport android.util.Log;\n\nimport android.view.DragEvent;\nimport android.view.Menu;\nimport android.view.MenuItem;\nimport android.view.MotionEvent;\nimport android.view.View;\n\nimport android.widget.ImageView;\nimport android.widget.RelativeLayout;\n\n\npublic class MainActivity extends Activity {\n ImageView img;\n String msg;\n private android.widget.RelativeLayout.LayoutParams layoutParams;\n \n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n img=(ImageView)findViewById(R.id.imageView);\n \n img.setOnLongClickListener(new View.OnLongClickListener() {\n @Override\n public boolean onLongClick(View v) {\n ClipData.Item item = new ClipData.Item((CharSequence)v.getTag());\n String[] mimeTypes = {ClipDescription.MIMETYPE_TEXT_PLAIN};\n \n ClipData dragData = new ClipData(v.getTag().toString(),mimeTypes, item);\n View.DragShadowBuilder myShadow = new View.DragShadowBuilder(img);\n \n v.startDrag(dragData,myShadow,null,0);\n return true;\n }\n });\n \n img.setOnDragListener(new View.OnDragListener() {\n @Override\n public boolean onDrag(View v, DragEvent event) {\n switch(event.getAction()) {\n case DragEvent.ACTION_DRAG_STARTED:\n layoutParams = (RelativeLayout.LayoutParams)v.getLayoutParams();\n Log.d(msg, \"Action is DragEvent.ACTION_DRAG_STARTED\");\n \n // Do nothing\n break;\n \n case DragEvent.ACTION_DRAG_ENTERED:\n Log.d(msg, \"Action is DragEvent.ACTION_DRAG_ENTERED\");\n int x_cord = (int) event.getX();\n int y_cord = (int) event.getY();\n break;\n \n case DragEvent.ACTION_DRAG_EXITED :\n Log.d(msg, \"Action is DragEvent.ACTION_DRAG_EXITED\");\n x_cord = (int) event.getX();\n y_cord = (int) event.getY();\n layoutParams.leftMargin = x_cord;\n layoutParams.topMargin = y_cord;\n v.setLayoutParams(layoutParams);\n break;\n \n case DragEvent.ACTION_DRAG_LOCATION :\n Log.d(msg, \"Action is DragEvent.ACTION_DRAG_LOCATION\");\n x_cord = (int) event.getX();\n y_cord = (int) event.getY();\n break;\n \n case DragEvent.ACTION_DRAG_ENDED :\n Log.d(msg, \"Action is DragEvent.ACTION_DRAG_ENDED\");\n \n // Do nothing\n break;\n \n case DragEvent.ACTION_DROP:\n Log.d(msg, \"ACTION_DROP event\");\n \n // Do nothing\n break;\n default: break;\n }\n return true;\n }\n });\n \n img.setOnTouchListener(new View.OnTouchListener() {\n @Override\n public boolean onTouch(View v, MotionEvent event) {\n if (event.getAction() == MotionEvent.ACTION_DOWN) {\n ClipData data = ClipData.newPlainText(\"\", \"\");\n View.DragShadowBuilder shadowBuilder = new View.DragShadowBuilder(img);\n \n img.startDrag(data, shadowBuilder, img, 0);\n img.setVisibility(View.INVISIBLE);\n return true;\n } else {\n return false;\n }\n }\n });\n }\n}"
},
{
"code": null,
"e": 14480,
"s": 14411,
"text": "Following will be the content of res/layout/activity_main.xml file −"
},
{
"code": null,
"e": 16021,
"s": 14480,
"text": "<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 android:paddingLeft=\"@dimen/activity_horizontal_margin\"\n android:paddingRight=\"@dimen/activity_horizontal_margin\"\n android:paddingTop=\"@dimen/activity_vertical_margin\"\n android:paddingBottom=\"@dimen/activity_vertical_margin\" \n tools:context=\".MainActivity\">\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Drag and Drop Example\"\n android:id=\"@+id/textView\"\n android:layout_alignParentTop=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\" />\n \n <TextView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Tutorials Point\"\n android:id=\"@+id/textView2\"\n android:layout_below=\"@+id/textView\"\n android:layout_centerHorizontal=\"true\"\n android:textSize=\"30dp\"\n android:textColor=\"#ff14be3c\" />>\n \n <ImageView\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:id=\"@+id/imageView\"\n android:src=\"@drawable/abc\"\n android:layout_below=\"@+id/textView2\"\n android:layout_alignRight=\"@+id/textView2\"\n android:layout_alignEnd=\"@+id/textView2\"\n android:layout_alignLeft=\"@+id/textView2\"\n android:layout_alignStart=\"@+id/textView2\" />\n\n</RelativeLayout>"
},
{
"code": null,
"e": 16108,
"s": 16021,
"text": "Following will be the content of res/values/strings.xml to define two new constants −"
},
{
"code": null,
"e": 16223,
"s": 16108,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">My Application</string>\n</resources>"
},
{
"code": null,
"e": 16282,
"s": 16223,
"text": "Following is the default content of AndroidManifest.xml −"
},
{
"code": null,
"e": 16982,
"s": 16282,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.saira_000.myapplication\" >\n \n <application\n android:allowBackup=\"true\"\n android:icon=\"@drawable/ic_launcher\"\n android:label=\"@string/app_name\"\n android:theme=\"@style/AppTheme\" >\n \n <activity\n android:name=\".MainActivity\"\n android:label=\"@string/app_name\" >\n \n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n \n </activity>\n \n </application>\n</manifest>"
},
{
"code": null,
"e": 17374,
"s": 16982,
"text": "Let's try to run your My Application application. I assume you had created your AVD while doing environment setup. To run the app from Android Studio, open one of your project's activity files and click Run icon from the toolbar. Android studio installs the app on your AVD and starts it and if everything is fine with your setup and application, it will display following Emulator window −"
},
{
"code": null,
"e": 17640,
"s": 17374,
"text": "Now do long click on the displayed TutorialsPoint logo and you will see that logo image moves a little after 1 seconds long click from its place, its the time when you should start dragging the image. You can drag it around the screen and drop it at a new location."
},
{
"code": null,
"e": 17675,
"s": 17640,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 17687,
"s": 17675,
"text": " Aditya Dua"
},
{
"code": null,
"e": 17722,
"s": 17687,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 17736,
"s": 17722,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 17768,
"s": 17736,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17785,
"s": 17768,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 17820,
"s": 17785,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 17837,
"s": 17820,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 17872,
"s": 17837,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 17889,
"s": 17872,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 17922,
"s": 17889,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 17939,
"s": 17922,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 17946,
"s": 17939,
"text": " Print"
},
{
"code": null,
"e": 17957,
"s": 17946,
"text": " Add Notes"
}
] |
How to convert a Date object to LocalDate object in java? | To convert a Date object to LocalDate object in Java −
Convert the obtained date object to an Instant object using the toInstant() method.
Convert the obtained date object to an Instant object using the toInstant() method.
Instant instant = date.toInstant();
Create the ZonedDateTime object using the atZone() method of the Instant class.
Create the ZonedDateTime object using the atZone() method of the Instant class.
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method.
Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method.
LocalDate givenDate = zone.toLocalDate();
Following example accepts a name and Date of birth from the user in String formats and converts it to LocalDate object and prints it.
Live Demo
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.util.Date;
import java.util.Scanner;
public class DateToLocalDate {
public static void main(String args[]) throws ParseException {
//Reading name and date of birth from the user
Scanner sc = new Scanner(System.in);
System.out.println("Enter your name: ");
String name = sc.next();
System.out.println("Enter your date of birth (dd-MM-yyyy): ");
String dob = sc.next();
//Converting String to Date
SimpleDateFormat formatter = new SimpleDateFormat("dd-MM-yyyy");
Date date = formatter.parse(dob);
//Converting obtained Date object to LocalDate object
Instant instant = date.toInstant();
ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());
LocalDate localDate = zone.toLocalDate();
System.out.println("Local format of the given date of birth String: "+localDate);
}
}
Enter your name:
Krishna
Enter your date of birth (dd-MM-yyyy):
26-09-1989
Local format of the given date of birth String: 1989-09-26 | [
{
"code": null,
"e": 1117,
"s": 1062,
"text": "To convert a Date object to LocalDate object in Java −"
},
{
"code": null,
"e": 1201,
"s": 1117,
"text": "Convert the obtained date object to an Instant object using the toInstant() method."
},
{
"code": null,
"e": 1285,
"s": 1201,
"text": "Convert the obtained date object to an Instant object using the toInstant() method."
},
{
"code": null,
"e": 1321,
"s": 1285,
"text": "Instant instant = date.toInstant();"
},
{
"code": null,
"e": 1401,
"s": 1321,
"text": "Create the ZonedDateTime object using the atZone() method of the Instant class."
},
{
"code": null,
"e": 1481,
"s": 1401,
"text": "Create the ZonedDateTime object using the atZone() method of the Instant class."
},
{
"code": null,
"e": 1542,
"s": 1481,
"text": "ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());"
},
{
"code": null,
"e": 1640,
"s": 1542,
"text": "Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method."
},
{
"code": null,
"e": 1738,
"s": 1640,
"text": "Finally, convert the ZonedDateTime object to the LocalDate object using the toLocalDate() method."
},
{
"code": null,
"e": 1780,
"s": 1738,
"text": "LocalDate givenDate = zone.toLocalDate();"
},
{
"code": null,
"e": 1914,
"s": 1780,
"text": "Following example accepts a name and Date of birth from the user in String formats and converts it to LocalDate object and prints it."
},
{
"code": null,
"e": 1925,
"s": 1914,
"text": " Live Demo"
},
{
"code": null,
"e": 2980,
"s": 1925,
"text": "import java.text.ParseException;\nimport java.text.SimpleDateFormat;\nimport java.time.Instant;\nimport java.time.LocalDate;\nimport java.time.ZoneId;\nimport java.time.ZonedDateTime;\nimport java.util.Date;\nimport java.util.Scanner;\npublic class DateToLocalDate {\n public static void main(String args[]) throws ParseException {\n //Reading name and date of birth from the user\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter your name: \");\n String name = sc.next();\n System.out.println(\"Enter your date of birth (dd-MM-yyyy): \");\n String dob = sc.next();\n //Converting String to Date\n SimpleDateFormat formatter = new SimpleDateFormat(\"dd-MM-yyyy\");\n Date date = formatter.parse(dob);\n //Converting obtained Date object to LocalDate object\n Instant instant = date.toInstant();\n ZonedDateTime zone = instant.atZone(ZoneId.systemDefault());\n LocalDate localDate = zone.toLocalDate();\n System.out.println(\"Local format of the given date of birth String: \"+localDate);\n }\n}"
},
{
"code": null,
"e": 3114,
"s": 2980,
"text": "Enter your name:\nKrishna\nEnter your date of birth (dd-MM-yyyy):\n26-09-1989\nLocal format of the given date of birth String: 1989-09-26"
}
] |
8051 Program to Divide two 8 Bit numbers | Now we will see another arithmetic operation. The divide operation to divide two 8-bit numbers using this 8051 microcontroller. The register A and B will be used in this operation. No other registers can be used for division. The result of the division has two parts. The quotient part and the remainder part. Register A will hold Quotient, and register B will hold Remainder.
We are taking two number0EH and 03H at location 20H and 21H, After dividing the result will be stored at location 30H and 31H.
MOV R0, #20H;set source address 20H to R0
MOV R1, #30H;set destination address 30H to R1
MOV A, @R0;take the first operand from source to register A
INC R0; Point to the next location
MOV B, @R0; take the second operand from source to register B
DIV AB ; Divide A by B
MOV @R1, A; Store Quotient to 30H
INC R1; Increase R1 to point to the next location
MOV @R1, B; Store Remainder to 31H
HALT: SJMP HALT ;Stop the program
8051 provides DI VAB instruction. By using this instruction, the division can be done. In some other microprocessors like 8085, there was no DIV instruction. In that microprocessor, we need to use repetitive Subtraction operations to get the result of the division.
When the denominator is00H, the overflow flag OV will be 1. otherwise it is 0 for the division. | [
{
"code": null,
"e": 1439,
"s": 1062,
"text": "Now we will see another arithmetic operation. The divide operation to divide two 8-bit numbers using this 8051 microcontroller. The register A and B will be used in this operation. No other registers can be used for division. The result of the division has two parts. The quotient part and the remainder part. Register A will hold Quotient, and register B will hold Remainder."
},
{
"code": null,
"e": 1568,
"s": 1439,
"text": "We are taking two number0EH and 03H at location 20H and 21H, After dividing the result will be stored at location 30H and 31H. "
},
{
"code": null,
"e": 1995,
"s": 1568,
"text": "MOV R0, #20H;set source address 20H to R0\nMOV R1, #30H;set destination address 30H to R1\n\nMOV A, @R0;take the first operand from source to register A\nINC R0; Point to the next location\nMOV B, @R0; take the second operand from source to register B\n\nDIV AB ; Divide A by B\n\nMOV @R1, A; Store Quotient to 30H\nINC R1; Increase R1 to point to the next location\nMOV @R1, B; Store Remainder to 31H\nHALT: SJMP HALT ;Stop the program"
},
{
"code": null,
"e": 2262,
"s": 1995,
"text": "8051 provides DI VAB instruction. By using this instruction, the division can be done. In some other microprocessors like 8085, there was no DIV instruction. In that microprocessor, we need to use repetitive Subtraction operations to get the result of the division. "
},
{
"code": null,
"e": 2358,
"s": 2262,
"text": "When the denominator is00H, the overflow flag OV will be 1. otherwise it is 0 for the division."
}
] |
Basic calculator program using Python - GeeksforGeeks | 19 Apr, 2020
Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input.Approach :
User choose the desired operation. Options 1, 2, 3 and 4 are valid.
Two numbers are taken and an if...elif...else branching is used to execute a particular section.
Using functions add(), subtract(), multiply() and divide() evaluate respective operations.Example :Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 20
Enter second number : 13
20 + 13 = 33
# Python program for simple calculator # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def subtract(num1, num2): return num1 - num2 # Function to multiply two numbersdef multiply(num1, num2): return num1 * num2 # Function to divide two numbersdef divide(num1, num2): return num1 / num2 print("Please select operation -\n" \ "1. Add\n" \ "2. Subtract\n" \ "3. Multiply\n" \ "4. Divide\n") # Take input from the user select = int(input("Select operations form 1, 2, 3, 4 :")) number_1 = int(input("Enter first number: "))number_2 = int(input("Enter second number: ")) if select == 1: print(number_1, "+", number_2, "=", add(number_1, number_2)) elif select == 2: print(number_1, "-", number_2, "=", subtract(number_1, number_2)) elif select == 3: print(number_1, "*", number_2, "=", multiply(number_1, number_2)) elif select == 4: print(number_1, "/", number_2, "=", divide(number_1, number_2))else: print("Invalid input")Output :Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 15
Enter second number : 14
15 + 14 = 29
My Personal Notes
arrow_drop_upSave
Example :
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 20
Enter second number : 13
20 + 13 = 33
# Python program for simple calculator # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def subtract(num1, num2): return num1 - num2 # Function to multiply two numbersdef multiply(num1, num2): return num1 * num2 # Function to divide two numbersdef divide(num1, num2): return num1 / num2 print("Please select operation -\n" \ "1. Add\n" \ "2. Subtract\n" \ "3. Multiply\n" \ "4. Divide\n") # Take input from the user select = int(input("Select operations form 1, 2, 3, 4 :")) number_1 = int(input("Enter first number: "))number_2 = int(input("Enter second number: ")) if select == 1: print(number_1, "+", number_2, "=", add(number_1, number_2)) elif select == 2: print(number_1, "-", number_2, "=", subtract(number_1, number_2)) elif select == 3: print(number_1, "*", number_2, "=", multiply(number_1, number_2)) elif select == 4: print(number_1, "/", number_2, "=", divide(number_1, number_2))else: print("Invalid input")
Output :
Please select operation -
1. Add
2. Subtract
3. Multiply
4. Divide
Select operations form 1, 2, 3, 4 : 1
Enter first number : 15
Enter second number : 14
15 + 14 = 29
priyankakarande
vogelvikash1997
Python
School Programming
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python Dictionary
Arrays in C/C++
Inheritance in C++
Reverse a string in Java
Interfaces in Java | [
{
"code": null,
"e": 24348,
"s": 24320,
"text": "\n19 Apr, 2020"
},
{
"code": null,
"e": 24517,
"s": 24348,
"text": "Create a simple calculator which can perform basic arithmetic operations like addition, subtraction, multiplication or division depending upon the user input.Approach :"
},
{
"code": null,
"e": 24585,
"s": 24517,
"text": "User choose the desired operation. Options 1, 2, 3 and 4 are valid."
},
{
"code": null,
"e": 24682,
"s": 24585,
"text": "Two numbers are taken and an if...elif...else branching is used to execute a particular section."
},
{
"code": null,
"e": 26280,
"s": 24682,
"text": "Using functions add(), subtract(), multiply() and divide() evaluate respective operations.Example :Please select operation -\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\nSelect operations form 1, 2, 3, 4 : 1\nEnter first number : 20\nEnter second number : 13\n20 + 13 = 33\n# Python program for simple calculator # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def subtract(num1, num2): return num1 - num2 # Function to multiply two numbersdef multiply(num1, num2): return num1 * num2 # Function to divide two numbersdef divide(num1, num2): return num1 / num2 print(\"Please select operation -\\n\" \\ \"1. Add\\n\" \\ \"2. Subtract\\n\" \\ \"3. Multiply\\n\" \\ \"4. Divide\\n\") # Take input from the user select = int(input(\"Select operations form 1, 2, 3, 4 :\")) number_1 = int(input(\"Enter first number: \"))number_2 = int(input(\"Enter second number: \")) if select == 1: print(number_1, \"+\", number_2, \"=\", add(number_1, number_2)) elif select == 2: print(number_1, \"-\", number_2, \"=\", subtract(number_1, number_2)) elif select == 3: print(number_1, \"*\", number_2, \"=\", multiply(number_1, number_2)) elif select == 4: print(number_1, \"/\", number_2, \"=\", divide(number_1, number_2))else: print(\"Invalid input\")Output :Please select operation -\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\nSelect operations form 1, 2, 3, 4 : 1\nEnter first number : 15\nEnter second number : 14\n15 + 14 = 29\nMy Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 26290,
"s": 26280,
"text": "Example :"
},
{
"code": null,
"e": 26458,
"s": 26290,
"text": "Please select operation -\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\nSelect operations form 1, 2, 3, 4 : 1\nEnter first number : 20\nEnter second number : 13\n20 + 13 = 33\n"
},
{
"code": "# Python program for simple calculator # Function to add two numbers def add(num1, num2): return num1 + num2 # Function to subtract two numbers def subtract(num1, num2): return num1 - num2 # Function to multiply two numbersdef multiply(num1, num2): return num1 * num2 # Function to divide two numbersdef divide(num1, num2): return num1 / num2 print(\"Please select operation -\\n\" \\ \"1. Add\\n\" \\ \"2. Subtract\\n\" \\ \"3. Multiply\\n\" \\ \"4. Divide\\n\") # Take input from the user select = int(input(\"Select operations form 1, 2, 3, 4 :\")) number_1 = int(input(\"Enter first number: \"))number_2 = int(input(\"Enter second number: \")) if select == 1: print(number_1, \"+\", number_2, \"=\", add(number_1, number_2)) elif select == 2: print(number_1, \"-\", number_2, \"=\", subtract(number_1, number_2)) elif select == 3: print(number_1, \"*\", number_2, \"=\", multiply(number_1, number_2)) elif select == 4: print(number_1, \"/\", number_2, \"=\", divide(number_1, number_2))else: print(\"Invalid input\")",
"e": 27580,
"s": 26458,
"text": null
},
{
"code": null,
"e": 27589,
"s": 27580,
"text": "Output :"
},
{
"code": null,
"e": 27757,
"s": 27589,
"text": "Please select operation -\n1. Add\n2. Subtract\n3. Multiply\n4. Divide\nSelect operations form 1, 2, 3, 4 : 1\nEnter first number : 15\nEnter second number : 14\n15 + 14 = 29\n"
},
{
"code": null,
"e": 27773,
"s": 27757,
"text": "priyankakarande"
},
{
"code": null,
"e": 27789,
"s": 27773,
"text": "vogelvikash1997"
},
{
"code": null,
"e": 27796,
"s": 27789,
"text": "Python"
},
{
"code": null,
"e": 27815,
"s": 27796,
"text": "School Programming"
},
{
"code": null,
"e": 27913,
"s": 27815,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27931,
"s": 27913,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27963,
"s": 27931,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28005,
"s": 27963,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 28031,
"s": 28005,
"text": "Python String | replace()"
},
{
"code": null,
"e": 28068,
"s": 28031,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 28086,
"s": 28068,
"text": "Python Dictionary"
},
{
"code": null,
"e": 28102,
"s": 28086,
"text": "Arrays in C/C++"
},
{
"code": null,
"e": 28121,
"s": 28102,
"text": "Inheritance in C++"
},
{
"code": null,
"e": 28146,
"s": 28121,
"text": "Reverse a string in Java"
}
] |
TypeScript - Tuples | At times, there might be a need to store a collection of values of varied types. Arrays will not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve such a purpose.
It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions.
var tuple_name = [value1,value2,value3,...value n]
var mytuple = [10,"Hello"];
You can also declare an empty tuple in Typescript and choose to initialize it later.
var mytuple = [];
mytuple[0] = 120
mytuple[1] = 234
Tuple values are individually called items. Tuples are index based. This means that items in a tuple can be accessed using their corresponding numeric index. Tuple item’s index starts from zero and extends up to n-1(where n is the tuple’s size).
tuple_name[index]
var mytuple = [10,"Hello"]; //create a tuple
console.log(mytuple[0])
console.log(mytuple[1])
In the above example, a tuple, mytuple, is declared. The tuple contains values of numeric and string types respectively.
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
10
Hello
var tup = []
tup[0] = 12
tup[1] = 23
console.log(tup[0])
console.log(tup[1])
On compiling, it will generate the same code in JavaScript.
Its output is as follows −
12
23
Tuples in TypeScript supports various operations like pushing a new item, removing an item from the tuple, etc.
var mytuple = [10,"Hello","World","typeScript"];
console.log("Items before push "+mytuple.length) // returns the tuple size
mytuple.push(12) // append value to the tuple
console.log("Items after push "+mytuple.length)
console.log("Items before pop "+mytuple.length)
console.log(mytuple.pop()+" popped from the tuple") // removes and returns the last item
console.log("Items after pop "+mytuple.length)
The push() appends an item to the tuple
The push() appends an item to the tuple
The pop() removes and returns the last value in the tuple
The pop() removes and returns the last value in the tuple
On compiling, it will generate the same code in JavaScript.
The output of the above code is as follows −
Items before push 4
Items after push 5
Items before pop 5
12 popped from the tuple
Items after pop 4
Tuples are mutable which means you can update or change the values of tuple elements.
var mytuple = [10,"Hello","World","typeScript"]; //create a tuple
console.log("Tuple value at index 0 "+mytuple[0])
//update a tuple element
mytuple[0] = 121
console.log("Tuple value at index 0 changed to "+mytuple[0])
On compiling, it will generate the same code in JavaScript.
The output of the above code is as follows −
Tuple value at index 0 10
Tuple value at index 0 changed to 121
Destructuring refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of a tuple.
var a =[10,"hello"]
var [b,c] = a
console.log( b )
console.log( c )
On compiling, it will generate following JavaScript code.
//Generated by typescript 1.8.10
var a = [10, "hello"];
var b = a[0], c = a[1];
console.log(b);
console.log(c);
Its output is as follows −
10
hello
45 Lectures
4 hours
Antonio Papa
41 Lectures
7 hours
Haider Malik
60 Lectures
2.5 hours
Skillbakerystudios
77 Lectures
8 hours
Sean Bradley
77 Lectures
3.5 hours
TELCOMA Global
19 Lectures
3 hours
Christopher Frewin
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2248,
"s": 2048,
"text": "At times, there might be a need to store a collection of values of varied types. Arrays will not serve this purpose. TypeScript gives us a data type called tuple that helps to achieve such a purpose."
},
{
"code": null,
"e": 2428,
"s": 2248,
"text": "It represents a heterogeneous collection of values. In other words, tuples enable storing multiple fields of different types. Tuples can also be passed as parameters to functions."
},
{
"code": null,
"e": 2480,
"s": 2428,
"text": "var tuple_name = [value1,value2,value3,...value n]\n"
},
{
"code": null,
"e": 2509,
"s": 2480,
"text": "var mytuple = [10,\"Hello\"];\n"
},
{
"code": null,
"e": 2594,
"s": 2509,
"text": "You can also declare an empty tuple in Typescript and choose to initialize it later."
},
{
"code": null,
"e": 2649,
"s": 2594,
"text": "var mytuple = []; \nmytuple[0] = 120 \nmytuple[1] = 234\n"
},
{
"code": null,
"e": 2895,
"s": 2649,
"text": "Tuple values are individually called items. Tuples are index based. This means that items in a tuple can be accessed using their corresponding numeric index. Tuple item’s index starts from zero and extends up to n-1(where n is the tuple’s size)."
},
{
"code": null,
"e": 2914,
"s": 2895,
"text": "tuple_name[index]\n"
},
{
"code": null,
"e": 3011,
"s": 2914,
"text": "var mytuple = [10,\"Hello\"]; //create a tuple \nconsole.log(mytuple[0]) \nconsole.log(mytuple[1])\n"
},
{
"code": null,
"e": 3132,
"s": 3011,
"text": "In the above example, a tuple, mytuple, is declared. The tuple contains values of numeric and string types respectively."
},
{
"code": null,
"e": 3192,
"s": 3132,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 3219,
"s": 3192,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3230,
"s": 3219,
"text": "10 \nHello\n"
},
{
"code": null,
"e": 3313,
"s": 3230,
"text": "var tup = [] \ntup[0] = 12 \ntup[1] = 23 \n\nconsole.log(tup[0]) \nconsole.log(tup[1])\n"
},
{
"code": null,
"e": 3373,
"s": 3313,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 3400,
"s": 3373,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 3409,
"s": 3400,
"text": "12 \n23 \n"
},
{
"code": null,
"e": 3521,
"s": 3409,
"text": "Tuples in TypeScript supports various operations like pushing a new item, removing an item from the tuple, etc."
},
{
"code": null,
"e": 3971,
"s": 3521,
"text": "var mytuple = [10,\"Hello\",\"World\",\"typeScript\"]; \nconsole.log(\"Items before push \"+mytuple.length) // returns the tuple size \n\nmytuple.push(12) // append value to the tuple \nconsole.log(\"Items after push \"+mytuple.length) \nconsole.log(\"Items before pop \"+mytuple.length) \nconsole.log(mytuple.pop()+\" popped from the tuple\") // removes and returns the last item\n \nconsole.log(\"Items after pop \"+mytuple.length)\n"
},
{
"code": null,
"e": 4011,
"s": 3971,
"text": "The push() appends an item to the tuple"
},
{
"code": null,
"e": 4051,
"s": 4011,
"text": "The push() appends an item to the tuple"
},
{
"code": null,
"e": 4109,
"s": 4051,
"text": "The pop() removes and returns the last value in the tuple"
},
{
"code": null,
"e": 4167,
"s": 4109,
"text": "The pop() removes and returns the last value in the tuple"
},
{
"code": null,
"e": 4227,
"s": 4167,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 4272,
"s": 4227,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 4378,
"s": 4272,
"text": "Items before push 4 \nItems after push 5 \nItems before pop 5 \n12 popped from the tuple \nItems after pop 4\n"
},
{
"code": null,
"e": 4464,
"s": 4378,
"text": "Tuples are mutable which means you can update or change the values of tuple elements."
},
{
"code": null,
"e": 4696,
"s": 4464,
"text": "var mytuple = [10,\"Hello\",\"World\",\"typeScript\"]; //create a tuple \nconsole.log(\"Tuple value at index 0 \"+mytuple[0]) \n\n//update a tuple element \nmytuple[0] = 121 \nconsole.log(\"Tuple value at index 0 changed to \"+mytuple[0])\n"
},
{
"code": null,
"e": 4756,
"s": 4696,
"text": "On compiling, it will generate the same code in JavaScript."
},
{
"code": null,
"e": 4801,
"s": 4756,
"text": "The output of the above code is as follows −"
},
{
"code": null,
"e": 4867,
"s": 4801,
"text": "Tuple value at index 0 10 \nTuple value at index 0 changed to 121\n"
},
{
"code": null,
"e": 5002,
"s": 4867,
"text": "Destructuring refers to breaking up the structure of an entity. TypeScript supports destructuring when used in the context of a tuple."
},
{
"code": null,
"e": 5078,
"s": 5002,
"text": "var a =[10,\"hello\"] \nvar [b,c] = a \nconsole.log( b ) \nconsole.log( c ) \n"
},
{
"code": null,
"e": 5136,
"s": 5078,
"text": "On compiling, it will generate following JavaScript code."
},
{
"code": null,
"e": 5249,
"s": 5136,
"text": "//Generated by typescript 1.8.10\nvar a = [10, \"hello\"];\nvar b = a[0], c = a[1];\nconsole.log(b);\nconsole.log(c);\n"
},
{
"code": null,
"e": 5276,
"s": 5249,
"text": "Its output is as follows −"
},
{
"code": null,
"e": 5288,
"s": 5276,
"text": "10 \nhello \n"
},
{
"code": null,
"e": 5321,
"s": 5288,
"text": "\n 45 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 5335,
"s": 5321,
"text": " Antonio Papa"
},
{
"code": null,
"e": 5368,
"s": 5335,
"text": "\n 41 Lectures \n 7 hours \n"
},
{
"code": null,
"e": 5382,
"s": 5368,
"text": " Haider Malik"
},
{
"code": null,
"e": 5417,
"s": 5382,
"text": "\n 60 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 5437,
"s": 5417,
"text": " Skillbakerystudios"
},
{
"code": null,
"e": 5470,
"s": 5437,
"text": "\n 77 Lectures \n 8 hours \n"
},
{
"code": null,
"e": 5484,
"s": 5470,
"text": " Sean Bradley"
},
{
"code": null,
"e": 5519,
"s": 5484,
"text": "\n 77 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5535,
"s": 5519,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 5568,
"s": 5535,
"text": "\n 19 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 5588,
"s": 5568,
"text": " Christopher Frewin"
},
{
"code": null,
"e": 5595,
"s": 5588,
"text": " Print"
},
{
"code": null,
"e": 5606,
"s": 5595,
"text": " Add Notes"
}
] |
Matplotlib - Box Plot | A box plot which is also known as a whisker plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The whiskers go from each quartile to the minimum or maximum.
Let us create the data for the boxplots. We use the numpy.random.normal() function to create the fake data. It takes three arguments, mean and standard deviation of the normal distribution, and the number of values desired.
np.random.seed(10)
collectn_1 = np.random.normal(100, 10, 200)
collectn_2 = np.random.normal(80, 30, 200)
collectn_3 = np.random.normal(90, 20, 200)
collectn_4 = np.random.normal(70, 25, 200)
The list of arrays that we created above is the only required input for creating the boxplot. Using the data_to_plot line of code, we can create the boxplot with the following code −
fig = plt.figure()
# Create an axes instance
ax = fig.add_axes([0,0,1,1])
# Create the boxplot
bp = ax.boxplot(data_to_plot)
plt.show()
The above line of code will generate the following output −
63 Lectures
6 hours
Abhilash Nelson
11 Lectures
4 hours
DATAhill Solutions Srinivas Reddy
9 Lectures
2.5 hours
DATAhill Solutions Srinivas Reddy
32 Lectures
4 hours
Aipython
10 Lectures
2.5 hours
Akbar Khan
63 Lectures
6 hours
Anmol
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2868,
"s": 2516,
"text": "A box plot which is also known as a whisker plot displays a summary of a set of data containing the minimum, first quartile, median, third quartile, and maximum. In a box plot, we draw a box from the first quartile to the third quartile. A vertical line goes through the box at the median. The whiskers go from each quartile to the minimum or maximum."
},
{
"code": null,
"e": 3092,
"s": 2868,
"text": "Let us create the data for the boxplots. We use the numpy.random.normal() function to create the fake data. It takes three arguments, mean and standard deviation of the normal distribution, and the number of values desired."
},
{
"code": null,
"e": 3284,
"s": 3092,
"text": "np.random.seed(10)\ncollectn_1 = np.random.normal(100, 10, 200)\ncollectn_2 = np.random.normal(80, 30, 200)\ncollectn_3 = np.random.normal(90, 20, 200)\ncollectn_4 = np.random.normal(70, 25, 200)"
},
{
"code": null,
"e": 3467,
"s": 3284,
"text": "The list of arrays that we created above is the only required input for creating the boxplot. Using the data_to_plot line of code, we can create the boxplot with the following code −"
},
{
"code": null,
"e": 3603,
"s": 3467,
"text": "fig = plt.figure()\n# Create an axes instance\nax = fig.add_axes([0,0,1,1])\n# Create the boxplot\nbp = ax.boxplot(data_to_plot)\nplt.show()"
},
{
"code": null,
"e": 3663,
"s": 3603,
"text": "The above line of code will generate the following output −"
},
{
"code": null,
"e": 3696,
"s": 3663,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3713,
"s": 3696,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 3746,
"s": 3713,
"text": "\n 11 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3781,
"s": 3746,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3815,
"s": 3781,
"text": "\n 9 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3850,
"s": 3815,
"text": " DATAhill Solutions Srinivas Reddy"
},
{
"code": null,
"e": 3883,
"s": 3850,
"text": "\n 32 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3893,
"s": 3883,
"text": " Aipython"
},
{
"code": null,
"e": 3928,
"s": 3893,
"text": "\n 10 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3940,
"s": 3928,
"text": " Akbar Khan"
},
{
"code": null,
"e": 3973,
"s": 3940,
"text": "\n 63 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3980,
"s": 3973,
"text": " Anmol"
},
{
"code": null,
"e": 3987,
"s": 3980,
"text": " Print"
},
{
"code": null,
"e": 3998,
"s": 3987,
"text": " Add Notes"
}
] |
Java Program to get a character from a String | 11 Dec, 2018
Given a String str, the task is to get a specific character from that String at a specific index.
Examples:
Input: str = "Geeks", index = 2
Output: e
Input: str = "GeeksForGeeks", index = 5
Output: F
Below are various ways to do so:
Using String.charAt() method:Get the string and the indexGet the specific character using String.charAt(index) method.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.charAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}Output:Character from GeeksForGeeks at index 5 is F
Get the string and the indexGet the specific character using String.charAt(index) method.Return the specific character.
Get the string and the index
Get the specific character using String.charAt(index) method.
Return the specific character.
Below is the implementation of the above approach:
// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.charAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}
Character from GeeksForGeeks at index 5 is F
Using String.toCharArray() method:Get the string and the indexConvert the String into Character array using String.toCharArray() method.Get the specific character at the specific index of the character array.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.toCharArray()[index]; } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}Output:Character from GeeksForGeeks at index 5 is F
Get the string and the indexConvert the String into Character array using String.toCharArray() method.Get the specific character at the specific index of the character array.Return the specific character.
Get the string and the index
Convert the String into Character array using String.toCharArray() method.
Get the specific character at the specific index of the character array.
Return the specific character.
Below is the implementation of the above approach:
// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.toCharArray()[index]; } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}
Character from GeeksForGeeks at index 5 is F
Using Java 8 Streams:Get the string and the indexConvert String into IntStream using String.chars() method.Convert IntStream into Stream using IntStream.mapToObj() method.Convert Stream into Character[] using toArray() method.Get the element at the specific index from this character array.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str // Convert String into IntStream .chars() // Convert IntStream into Stream<Character> .mapToObj(ch -> (char)ch) // Convert Stream<Character> into Character[] // and get the element at the specific index .toArray(Character[] ::new)[index]; } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}Output:Character from GeeksForGeeks at index 5 is F
Get the string and the indexConvert String into IntStream using String.chars() method.Convert IntStream into Stream using IntStream.mapToObj() method.Convert Stream into Character[] using toArray() method.Get the element at the specific index from this character array.Return the specific character.
Get the string and the index
Convert String into IntStream using String.chars() method.
Convert IntStream into Stream using IntStream.mapToObj() method.
Convert Stream into Character[] using toArray() method.
Get the element at the specific index from this character array.
Return the specific character.
Below is the implementation of the above approach:
// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str // Convert String into IntStream .chars() // Convert IntStream into Stream<Character> .mapToObj(ch -> (char)ch) // Convert Stream<Character> into Character[] // and get the element at the specific index .toArray(Character[] ::new)[index]; } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}
Character from GeeksForGeeks at index 5 is F
Using String.codePointAt() method:Get the string and the indexGet the specific character ASCII value at the specific index using String.codePointAt() method.Convert this ASCII value into character using type casting.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return (char)str.codePointAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}Output:Character from GeeksForGeeks at index 5 is F
Get the string and the indexGet the specific character ASCII value at the specific index using String.codePointAt() method.Convert this ASCII value into character using type casting.Return the specific character.
Get the string and the index
Get the specific character ASCII value at the specific index using String.codePointAt() method.
Convert this ASCII value into character using type casting.
Return the specific character.
Below is the implementation of the above approach:
// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return (char)str.codePointAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}
Character from GeeksForGeeks at index 5 is F
Using String.getChars() method:Get the string and the indexCreate an empty char array of size 1Copy the element at specific index from String into the char[] using String.getChars() method.Get the specific character at the index 0 of the character array.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { // Create a character array of size 1 char[] singleCharArray = new char[1]; // Get the specific character from the String // into the char[] at index 0 str.getChars(index, index + 1, singleCharArray, 0); // Return the specific character // present at index 0 in char[] return singleCharArray[0]; } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}Output:Character from GeeksForGeeks at index 5 is F
Get the string and the indexCreate an empty char array of size 1Copy the element at specific index from String into the char[] using String.getChars() method.Get the specific character at the index 0 of the character array.Return the specific character.
Get the string and the index
Create an empty char array of size 1
Copy the element at specific index from String into the char[] using String.getChars() method.
Get the specific character at the index 0 of the character array.
Return the specific character.
Below is the implementation of the above approach:
// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { // Create a character array of size 1 char[] singleCharArray = new char[1]; // Get the specific character from the String // into the char[] at index 0 str.getChars(index, index + 1, singleCharArray, 0); // Return the specific character // present at index 0 in char[] return singleCharArray[0]; } // Driver code public static void main(String[] args) { // Get the String String str = "GeeksForGeeks"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println("Character from " + str + " at index " + index + " is " + ch); }}
Character from GeeksForGeeks at index 5 is F
Java - util package
Java-String-Programs
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Dec, 2018"
},
{
"code": null,
"e": 126,
"s": 28,
"text": "Given a String str, the task is to get a specific character from that String at a specific index."
},
{
"code": null,
"e": 136,
"s": 126,
"text": "Examples:"
},
{
"code": null,
"e": 230,
"s": 136,
"text": "Input: str = \"Geeks\", index = 2\nOutput: e\n\nInput: str = \"GeeksForGeeks\", index = 5\nOutput: F\n"
},
{
"code": null,
"e": 263,
"s": 230,
"text": "Below are various ways to do so:"
},
{
"code": null,
"e": 1183,
"s": 263,
"text": "Using String.charAt() method:Get the string and the indexGet the specific character using String.charAt(index) method.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.charAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}Output:Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 1303,
"s": 1183,
"text": "Get the string and the indexGet the specific character using String.charAt(index) method.Return the specific character."
},
{
"code": null,
"e": 1332,
"s": 1303,
"text": "Get the string and the index"
},
{
"code": null,
"e": 1394,
"s": 1332,
"text": "Get the specific character using String.charAt(index) method."
},
{
"code": null,
"e": 1425,
"s": 1394,
"text": "Return the specific character."
},
{
"code": null,
"e": 1476,
"s": 1425,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.charAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}",
"e": 2146,
"s": 1476,
"text": null
},
{
"code": null,
"e": 2192,
"s": 2146,
"text": "Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 3207,
"s": 2192,
"text": "Using String.toCharArray() method:Get the string and the indexConvert the String into Character array using String.toCharArray() method.Get the specific character at the specific index of the character array.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.toCharArray()[index]; } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}Output:Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 3412,
"s": 3207,
"text": "Get the string and the indexConvert the String into Character array using String.toCharArray() method.Get the specific character at the specific index of the character array.Return the specific character."
},
{
"code": null,
"e": 3441,
"s": 3412,
"text": "Get the string and the index"
},
{
"code": null,
"e": 3516,
"s": 3441,
"text": "Convert the String into Character array using String.toCharArray() method."
},
{
"code": null,
"e": 3589,
"s": 3516,
"text": "Get the specific character at the specific index of the character array."
},
{
"code": null,
"e": 3620,
"s": 3589,
"text": "Return the specific character."
},
{
"code": null,
"e": 3671,
"s": 3620,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str.toCharArray()[index]; } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}",
"e": 4346,
"s": 3671,
"text": null
},
{
"code": null,
"e": 4392,
"s": 4346,
"text": "Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 5787,
"s": 4392,
"text": "Using Java 8 Streams:Get the string and the indexConvert String into IntStream using String.chars() method.Convert IntStream into Stream using IntStream.mapToObj() method.Convert Stream into Character[] using toArray() method.Get the element at the specific index from this character array.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str // Convert String into IntStream .chars() // Convert IntStream into Stream<Character> .mapToObj(ch -> (char)ch) // Convert Stream<Character> into Character[] // and get the element at the specific index .toArray(Character[] ::new)[index]; } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}Output:Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 6087,
"s": 5787,
"text": "Get the string and the indexConvert String into IntStream using String.chars() method.Convert IntStream into Stream using IntStream.mapToObj() method.Convert Stream into Character[] using toArray() method.Get the element at the specific index from this character array.Return the specific character."
},
{
"code": null,
"e": 6116,
"s": 6087,
"text": "Get the string and the index"
},
{
"code": null,
"e": 6175,
"s": 6116,
"text": "Convert String into IntStream using String.chars() method."
},
{
"code": null,
"e": 6240,
"s": 6175,
"text": "Convert IntStream into Stream using IntStream.mapToObj() method."
},
{
"code": null,
"e": 6296,
"s": 6240,
"text": "Convert Stream into Character[] using toArray() method."
},
{
"code": null,
"e": 6361,
"s": 6296,
"text": "Get the element at the specific index from this character array."
},
{
"code": null,
"e": 6392,
"s": 6361,
"text": "Return the specific character."
},
{
"code": null,
"e": 6443,
"s": 6392,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return str // Convert String into IntStream .chars() // Convert IntStream into Stream<Character> .mapToObj(ch -> (char)ch) // Convert Stream<Character> into Character[] // and get the element at the specific index .toArray(Character[] ::new)[index]; } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}",
"e": 7416,
"s": 6443,
"text": null
},
{
"code": null,
"e": 7462,
"s": 7416,
"text": "Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 8489,
"s": 7462,
"text": "Using String.codePointAt() method:Get the string and the indexGet the specific character ASCII value at the specific index using String.codePointAt() method.Convert this ASCII value into character using type casting.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return (char)str.codePointAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}Output:Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 8702,
"s": 8489,
"text": "Get the string and the indexGet the specific character ASCII value at the specific index using String.codePointAt() method.Convert this ASCII value into character using type casting.Return the specific character."
},
{
"code": null,
"e": 8731,
"s": 8702,
"text": "Get the string and the index"
},
{
"code": null,
"e": 8827,
"s": 8731,
"text": "Get the specific character ASCII value at the specific index using String.codePointAt() method."
},
{
"code": null,
"e": 8887,
"s": 8827,
"text": "Convert this ASCII value into character using type casting."
},
{
"code": null,
"e": 8918,
"s": 8887,
"text": "Return the specific character."
},
{
"code": null,
"e": 8969,
"s": 8918,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { return (char)str.codePointAt(index); } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}",
"e": 9648,
"s": 8969,
"text": null
},
{
"code": null,
"e": 9694,
"s": 9648,
"text": "Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 11071,
"s": 9694,
"text": "Using String.getChars() method:Get the string and the indexCreate an empty char array of size 1Copy the element at specific index from String into the char[] using String.getChars() method.Get the specific character at the index 0 of the character array.Return the specific character.Below is the implementation of the above approach:// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { // Create a character array of size 1 char[] singleCharArray = new char[1]; // Get the specific character from the String // into the char[] at index 0 str.getChars(index, index + 1, singleCharArray, 0); // Return the specific character // present at index 0 in char[] return singleCharArray[0]; } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}Output:Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 11325,
"s": 11071,
"text": "Get the string and the indexCreate an empty char array of size 1Copy the element at specific index from String into the char[] using String.getChars() method.Get the specific character at the index 0 of the character array.Return the specific character."
},
{
"code": null,
"e": 11354,
"s": 11325,
"text": "Get the string and the index"
},
{
"code": null,
"e": 11391,
"s": 11354,
"text": "Create an empty char array of size 1"
},
{
"code": null,
"e": 11486,
"s": 11391,
"text": "Copy the element at specific index from String into the char[] using String.getChars() method."
},
{
"code": null,
"e": 11552,
"s": 11486,
"text": "Get the specific character at the index 0 of the character array."
},
{
"code": null,
"e": 11583,
"s": 11552,
"text": "Return the specific character."
},
{
"code": null,
"e": 11634,
"s": 11583,
"text": "Below is the implementation of the above approach:"
},
{
"code": "// Java program to get a specific character// from a given String at a specific index class GFG { // Function to get the specific character public static char getCharFromString(String str, int index) { // Create a character array of size 1 char[] singleCharArray = new char[1]; // Get the specific character from the String // into the char[] at index 0 str.getChars(index, index + 1, singleCharArray, 0); // Return the specific character // present at index 0 in char[] return singleCharArray[0]; } // Driver code public static void main(String[] args) { // Get the String String str = \"GeeksForGeeks\"; // Get the index int index = 5; // Get the specific character char ch = getCharFromString(str, index); System.out.println(\"Character from \" + str + \" at index \" + index + \" is \" + ch); }}",
"e": 12625,
"s": 11634,
"text": null
},
{
"code": null,
"e": 12671,
"s": 12625,
"text": "Character from GeeksForGeeks at index 5 is F\n"
},
{
"code": null,
"e": 12691,
"s": 12671,
"text": "Java - util package"
},
{
"code": null,
"e": 12712,
"s": 12691,
"text": "Java-String-Programs"
},
{
"code": null,
"e": 12725,
"s": 12712,
"text": "Java-Strings"
},
{
"code": null,
"e": 12730,
"s": 12725,
"text": "Java"
},
{
"code": null,
"e": 12743,
"s": 12730,
"text": "Java-Strings"
},
{
"code": null,
"e": 12748,
"s": 12743,
"text": "Java"
}
] |
jQuery | ajax() Method | 03 Aug, 2021
The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request.
Syntax:
$.ajax({name:value, name:value, ... })
Parameters: The list of possible values are given below:
type: It is used to specify the type of request.
url: It is used to specify the URL to send the request to.
username: It is used to specify a username to be used in an HTTP access authentication request.
xhr: It is used for creating the XMLHttpRequest object.
async: It’s default value is true. It indicates whether the request should be handled asynchronous or not.
beforeSend(xhr): It is a function which is to be run before the request is being sent.
dataType: The data type expected of the server response.
error(xhr, status, error): It is used to run if the request fails.
global: It’s default value is true. It is used to specify whether or not to trigger global AJAX event handles for the request.
ifModified: It’s default value is false. It is used to specify whether a request is only successful if the response has changed since the last request.
jsonp: A string overriding the callback function in a jsonp request.
jsonpCallback: It is used to specify a name for the callback function in a jsonp request.
cache: It’s default value is true. It indicates whether the browser should cache the requested pages.
complete(xhr, status): It is a function which is to be run when the request is being finished.
contentType: It’s default value is: “application/x-www-form-urlencoded” and it is used when data send to the server.
context: It is used to specify the “this” value for all AJAX related callback functions.
data: It is used to specify data to be sent to the server.
dataFilter(data, type): It is used to handle the raw response data of the XMLHttpRequest.
password: It is used to specify a password to be used in an HTTP access authentication request.
processData: It’s default value is true. It is used to specify whether or not data sent with the request should be transformed into a query string.
scriptCharset: It is used to specify the charset for the request.
success(result, status, xhr): It is to be run when the request succeeds.
timeout: It is the local timeout for the request. It measured in terms of milliseconds.
traditional: It is used to specify whether or not to use the traditional style of param serialization.
Example 1: This example use ajax() method to add the text content using ajax request.
<!DOCTYPE html><html> <head> <title> jQuery ajax() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("li:parent").css("background-color", "green"); }); </script></head> <body style="text-align:center;"> <h1 style="color:green"> GeeksForGeeks </h1> <h2> jQuery ajax() Method </h2> <h3 id="h11"></h3> <button>Click</button> <!-- Script to use ajax() method to add text content --> <script> $(document).ready(function() { $("button").click(function() { $.ajax({url: "geeks.txt", success: function(result) { $("#h11").html(result); }}); }); }); </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
Example 2: This example illustrates the ajax() method in jQuery.
<!DOCTYPE html><html> <head> <title> jQuery ajax() Method </title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script> <script> $(document).ready(function() { $("li:parent").css("background-color", "green"); }); </script></head> <body style="text-align:center;"> <h1 style="color:green"> GeeksForGeeks </h1> <h2>jQuery ajax() Method</h2> <h3 id="h11"></h3> <button>Click</button> <!-- Script to use ajax() method to add text content --> <script> $(document).ready(function(){ $("button").click(function(){ $.ajax({url: "geeks_exp.txt", async: false, success: function(result) { $("h11").html(result); }}); }); }); </script></body> </html>
Output:
Before Clicking the button:
After Clicking the button:
jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples.
jQuery-AJAX
Picked
JQuery
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 Aug, 2021"
},
{
"code": null,
"e": 147,
"s": 54,
"text": "The ajax() method in jQuery is used to perform an AJAX request or asynchronous HTTP request."
},
{
"code": null,
"e": 155,
"s": 147,
"text": "Syntax:"
},
{
"code": null,
"e": 194,
"s": 155,
"text": "$.ajax({name:value, name:value, ... })"
},
{
"code": null,
"e": 251,
"s": 194,
"text": "Parameters: The list of possible values are given below:"
},
{
"code": null,
"e": 300,
"s": 251,
"text": "type: It is used to specify the type of request."
},
{
"code": null,
"e": 359,
"s": 300,
"text": "url: It is used to specify the URL to send the request to."
},
{
"code": null,
"e": 455,
"s": 359,
"text": "username: It is used to specify a username to be used in an HTTP access authentication request."
},
{
"code": null,
"e": 511,
"s": 455,
"text": "xhr: It is used for creating the XMLHttpRequest object."
},
{
"code": null,
"e": 618,
"s": 511,
"text": "async: It’s default value is true. It indicates whether the request should be handled asynchronous or not."
},
{
"code": null,
"e": 705,
"s": 618,
"text": "beforeSend(xhr): It is a function which is to be run before the request is being sent."
},
{
"code": null,
"e": 762,
"s": 705,
"text": "dataType: The data type expected of the server response."
},
{
"code": null,
"e": 829,
"s": 762,
"text": "error(xhr, status, error): It is used to run if the request fails."
},
{
"code": null,
"e": 956,
"s": 829,
"text": "global: It’s default value is true. It is used to specify whether or not to trigger global AJAX event handles for the request."
},
{
"code": null,
"e": 1108,
"s": 956,
"text": "ifModified: It’s default value is false. It is used to specify whether a request is only successful if the response has changed since the last request."
},
{
"code": null,
"e": 1177,
"s": 1108,
"text": "jsonp: A string overriding the callback function in a jsonp request."
},
{
"code": null,
"e": 1267,
"s": 1177,
"text": "jsonpCallback: It is used to specify a name for the callback function in a jsonp request."
},
{
"code": null,
"e": 1369,
"s": 1267,
"text": "cache: It’s default value is true. It indicates whether the browser should cache the requested pages."
},
{
"code": null,
"e": 1464,
"s": 1369,
"text": "complete(xhr, status): It is a function which is to be run when the request is being finished."
},
{
"code": null,
"e": 1581,
"s": 1464,
"text": "contentType: It’s default value is: “application/x-www-form-urlencoded” and it is used when data send to the server."
},
{
"code": null,
"e": 1670,
"s": 1581,
"text": "context: It is used to specify the “this” value for all AJAX related callback functions."
},
{
"code": null,
"e": 1729,
"s": 1670,
"text": "data: It is used to specify data to be sent to the server."
},
{
"code": null,
"e": 1819,
"s": 1729,
"text": "dataFilter(data, type): It is used to handle the raw response data of the XMLHttpRequest."
},
{
"code": null,
"e": 1915,
"s": 1819,
"text": "password: It is used to specify a password to be used in an HTTP access authentication request."
},
{
"code": null,
"e": 2063,
"s": 1915,
"text": "processData: It’s default value is true. It is used to specify whether or not data sent with the request should be transformed into a query string."
},
{
"code": null,
"e": 2129,
"s": 2063,
"text": "scriptCharset: It is used to specify the charset for the request."
},
{
"code": null,
"e": 2202,
"s": 2129,
"text": "success(result, status, xhr): It is to be run when the request succeeds."
},
{
"code": null,
"e": 2290,
"s": 2202,
"text": "timeout: It is the local timeout for the request. It measured in terms of milliseconds."
},
{
"code": null,
"e": 2393,
"s": 2290,
"text": "traditional: It is used to specify whether or not to use the traditional style of param serialization."
},
{
"code": null,
"e": 2479,
"s": 2393,
"text": "Example 1: This example use ajax() method to add the text content using ajax request."
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery ajax() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"li:parent\").css(\"background-color\", \"green\"); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksForGeeks </h1> <h2> jQuery ajax() Method </h2> <h3 id=\"h11\"></h3> <button>Click</button> <!-- Script to use ajax() method to add text content --> <script> $(document).ready(function() { $(\"button\").click(function() { $.ajax({url: \"geeks.txt\", success: function(result) { $(\"#h11\").html(result); }}); }); }); </script></body> </html>",
"e": 3397,
"s": 2479,
"text": null
},
{
"code": null,
"e": 3405,
"s": 3397,
"text": "Output:"
},
{
"code": null,
"e": 3433,
"s": 3405,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 3460,
"s": 3433,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 3525,
"s": 3460,
"text": "Example 2: This example illustrates the ajax() method in jQuery."
},
{
"code": "<!DOCTYPE html><html> <head> <title> jQuery ajax() Method </title> <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"> </script> <script> $(document).ready(function() { $(\"li:parent\").css(\"background-color\", \"green\"); }); </script></head> <body style=\"text-align:center;\"> <h1 style=\"color:green\"> GeeksForGeeks </h1> <h2>jQuery ajax() Method</h2> <h3 id=\"h11\"></h3> <button>Click</button> <!-- Script to use ajax() method to add text content --> <script> $(document).ready(function(){ $(\"button\").click(function(){ $.ajax({url: \"geeks_exp.txt\", async: false, success: function(result) { $(\"h11\").html(result); }}); }); }); </script></body> </html>",
"e": 4450,
"s": 3525,
"text": null
},
{
"code": null,
"e": 4458,
"s": 4450,
"text": "Output:"
},
{
"code": null,
"e": 4486,
"s": 4458,
"text": "Before Clicking the button:"
},
{
"code": null,
"e": 4513,
"s": 4486,
"text": "After Clicking the button:"
},
{
"code": null,
"e": 4781,
"s": 4513,
"text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples."
},
{
"code": null,
"e": 4793,
"s": 4781,
"text": "jQuery-AJAX"
},
{
"code": null,
"e": 4800,
"s": 4793,
"text": "Picked"
},
{
"code": null,
"e": 4807,
"s": 4800,
"text": "JQuery"
},
{
"code": null,
"e": 4824,
"s": 4807,
"text": "Web Technologies"
}
] |
PHP | Introduction | 17 Jun, 2022
The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. It is open-source which means it is free to download and use. It is very simple to learn and use. The files have the extension “.php”.
Rasmus Lerdorf inspired the first version of PHP and participated in the later versions. It is an interpreted language and it does not require a compiler.
PHP code is executed in the server.
It can be integrated with many databases such as Oracle, Microsoft SQL Server, MySQL, PostgreSQL, Sybase, and Informix.
It is powerful to hold a content management system like WordPress and can be used to control user access.
It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others.
Websites like www.facebook.com and www.yahoo.com are also built on PHP.
One of the main reasons behind this is that PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file.
The thing that differentiates PHP from the client-side language like HTML is, that PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. PHP codes are first executed on the server and then the result is returned to the browser.
The only information that the client or browser knows is the result returned after executing the PHP script on the server and not the actual PHP codes present in the PHP file. Also, PHP files can support other client-side scripting languages like CSS and JavaScript.
Other characteristics of PHP are as follows.
Simple and fast
Efficient
Secured
Flexible
Cross-platform, it works with major operating systems like Windows, Linux, and macOS.
Open Source
Powerful Library Support
Database Connectivity
Syntax:
<?php
PHP code goes here
?>
Example:
HTML
<html> <head> <title>PHP Example</title> </head> <body> <?php echo "Hello, World! This is PHP code";?> </body> </html>
Output:
Hello, World! This is PHP code
Why should we use PHP?
PHP can actually do anything related to server-side scripting or more popularly known as the backend of a website. For example, PHP can receive data from forms, generate dynamic page content, can work with databases, create sessions, send and receive cookies, send emails, etc. There are also many hash functions available in PHP to encrypt users’ data which makes PHP secure and reliable to be used as a server-side scripting language. So these are some of PHP’s abilities that make it suitable to be used as a server-side scripting language. You will get to know more of these abilities in further tutorials. Even if the above abilities do not convince you of PHP, there are some more features of PHP. PHP can run on all major operating systems like Windows, Linux, Unix, Mac OS X, etc. Almost all of the major servers available today like Apache supports PHP. PHP allows using a wide range of databases. And the most important factor is that it is free to use and download and anyone can download PHP from its official source: www.php.net. Please refer to setting up the development environment and basic syntax of PHP in further articles.
What’s new in PHP 7.0:
PHP 7 is faster than the previous versions.
PHP 7 supports new operators.
PHP 7 supports better Error Handling functionalities.
PHP 7 supports stricter declarations for types in function parameters.References:
https://en.wikipedia.org/wiki/PHP
http://php.net/manual/en/introduction.php
Disadvantages of PHP:
PHP is not secure as it is open source.Not good to create desktop applications.Not suitable for large Web Applications- Php code is hard to maintain since it is not very modular.Modification Problem – PHP does not allow the change in the core behavior of the web applications.
PHP is not secure as it is open source.
Not good to create desktop applications.
Not suitable for large Web Applications- Php code is hard to maintain since it is not very modular.
Modification Problem – PHP does not allow the change in the core behavior of the web applications.
geetanjali16
luizashaikh1
PHP-basics
PHP
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n17 Jun, 2022"
},
{
"code": null,
"e": 331,
"s": 52,
"text": "The term PHP is an acronym for PHP: Hypertext Preprocessor. PHP is a server-side scripting language designed specifically for web development. It is open-source which means it is free to download and use. It is very simple to learn and use. The files have the extension “.php”. "
},
{
"code": null,
"e": 487,
"s": 331,
"text": "Rasmus Lerdorf inspired the first version of PHP and participated in the later versions. It is an interpreted language and it does not require a compiler. "
},
{
"code": null,
"e": 523,
"s": 487,
"text": "PHP code is executed in the server."
},
{
"code": null,
"e": 643,
"s": 523,
"text": "It can be integrated with many databases such as Oracle, Microsoft SQL Server, MySQL, PostgreSQL, Sybase, and Informix."
},
{
"code": null,
"e": 749,
"s": 643,
"text": "It is powerful to hold a content management system like WordPress and can be used to control user access."
},
{
"code": null,
"e": 829,
"s": 749,
"text": "It supports main protocols like HTTP Basic, HTTP Digest, IMAP, FTP, and others."
},
{
"code": null,
"e": 901,
"s": 829,
"text": "Websites like www.facebook.com and www.yahoo.com are also built on PHP."
},
{
"code": null,
"e": 1036,
"s": 901,
"text": "One of the main reasons behind this is that PHP can be easily embedded in HTML files and HTML codes can also be written in a PHP file."
},
{
"code": null,
"e": 1304,
"s": 1036,
"text": "The thing that differentiates PHP from the client-side language like HTML is, that PHP codes are executed on the server whereas HTML codes are directly rendered on the browser. PHP codes are first executed on the server and then the result is returned to the browser."
},
{
"code": null,
"e": 1571,
"s": 1304,
"text": "The only information that the client or browser knows is the result returned after executing the PHP script on the server and not the actual PHP codes present in the PHP file. Also, PHP files can support other client-side scripting languages like CSS and JavaScript."
},
{
"code": null,
"e": 1616,
"s": 1571,
"text": "Other characteristics of PHP are as follows."
},
{
"code": null,
"e": 1632,
"s": 1616,
"text": "Simple and fast"
},
{
"code": null,
"e": 1642,
"s": 1632,
"text": "Efficient"
},
{
"code": null,
"e": 1650,
"s": 1642,
"text": "Secured"
},
{
"code": null,
"e": 1659,
"s": 1650,
"text": "Flexible"
},
{
"code": null,
"e": 1745,
"s": 1659,
"text": "Cross-platform, it works with major operating systems like Windows, Linux, and macOS."
},
{
"code": null,
"e": 1757,
"s": 1745,
"text": "Open Source"
},
{
"code": null,
"e": 1782,
"s": 1757,
"text": "Powerful Library Support"
},
{
"code": null,
"e": 1804,
"s": 1782,
"text": "Database Connectivity"
},
{
"code": null,
"e": 1812,
"s": 1804,
"text": "Syntax:"
},
{
"code": null,
"e": 1844,
"s": 1812,
"text": "<?php \n PHP code goes here \n?>"
},
{
"code": null,
"e": 1853,
"s": 1844,
"text": "Example:"
},
{
"code": null,
"e": 1858,
"s": 1853,
"text": "HTML"
},
{
"code": "<html> <head> <title>PHP Example</title> </head> <body> <?php echo \"Hello, World! This is PHP code\";?> </body> </html>",
"e": 2003,
"s": 1858,
"text": null
},
{
"code": null,
"e": 2011,
"s": 2003,
"text": "Output:"
},
{
"code": null,
"e": 2042,
"s": 2011,
"text": "Hello, World! This is PHP code"
},
{
"code": null,
"e": 2065,
"s": 2042,
"text": "Why should we use PHP?"
},
{
"code": null,
"e": 3209,
"s": 2065,
"text": "PHP can actually do anything related to server-side scripting or more popularly known as the backend of a website. For example, PHP can receive data from forms, generate dynamic page content, can work with databases, create sessions, send and receive cookies, send emails, etc. There are also many hash functions available in PHP to encrypt users’ data which makes PHP secure and reliable to be used as a server-side scripting language. So these are some of PHP’s abilities that make it suitable to be used as a server-side scripting language. You will get to know more of these abilities in further tutorials. Even if the above abilities do not convince you of PHP, there are some more features of PHP. PHP can run on all major operating systems like Windows, Linux, Unix, Mac OS X, etc. Almost all of the major servers available today like Apache supports PHP. PHP allows using a wide range of databases. And the most important factor is that it is free to use and download and anyone can download PHP from its official source: www.php.net. Please refer to setting up the development environment and basic syntax of PHP in further articles. "
},
{
"code": null,
"e": 3232,
"s": 3209,
"text": "What’s new in PHP 7.0:"
},
{
"code": null,
"e": 3276,
"s": 3232,
"text": "PHP 7 is faster than the previous versions."
},
{
"code": null,
"e": 3306,
"s": 3276,
"text": "PHP 7 supports new operators."
},
{
"code": null,
"e": 3360,
"s": 3306,
"text": "PHP 7 supports better Error Handling functionalities."
},
{
"code": null,
"e": 3442,
"s": 3360,
"text": "PHP 7 supports stricter declarations for types in function parameters.References:"
},
{
"code": null,
"e": 3476,
"s": 3442,
"text": "https://en.wikipedia.org/wiki/PHP"
},
{
"code": null,
"e": 3518,
"s": 3476,
"text": "http://php.net/manual/en/introduction.php"
},
{
"code": null,
"e": 3540,
"s": 3518,
"text": "Disadvantages of PHP:"
},
{
"code": null,
"e": 3817,
"s": 3540,
"text": "PHP is not secure as it is open source.Not good to create desktop applications.Not suitable for large Web Applications- Php code is hard to maintain since it is not very modular.Modification Problem – PHP does not allow the change in the core behavior of the web applications."
},
{
"code": null,
"e": 3857,
"s": 3817,
"text": "PHP is not secure as it is open source."
},
{
"code": null,
"e": 3898,
"s": 3857,
"text": "Not good to create desktop applications."
},
{
"code": null,
"e": 3998,
"s": 3898,
"text": "Not suitable for large Web Applications- Php code is hard to maintain since it is not very modular."
},
{
"code": null,
"e": 4097,
"s": 3998,
"text": "Modification Problem – PHP does not allow the change in the core behavior of the web applications."
},
{
"code": null,
"e": 4110,
"s": 4097,
"text": "geetanjali16"
},
{
"code": null,
"e": 4123,
"s": 4110,
"text": "luizashaikh1"
},
{
"code": null,
"e": 4134,
"s": 4123,
"text": "PHP-basics"
},
{
"code": null,
"e": 4138,
"s": 4134,
"text": "PHP"
},
{
"code": null,
"e": 4165,
"s": 4138,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 4169,
"s": 4165,
"text": "PHP"
}
] |
Delete a Linked List node at a given position | 28 Jun, 2022
Given a singly linked list and a position, delete a linked list node at the given position.
Example:
Input: position = 1, Linked List = 8->2->3->1->7
Output: Linked List = 8->3->1->7
Input: position = 0, Linked List = 8->2->3->1->7
Output: Linked List = 2->3->1->7
If the node to be deleted is the root, simply delete it. To delete a middle node, we must have a pointer to the node previous to the node to be deleted. So if positions are not zero, we run a loop position-1 times and get a pointer to the previous node.
Below is the implementation of the above idea.
C++
C
Java
Python3
C#
Javascript
// A complete working C++ program to delete// a node in a linked list at a given position#include <iostream>using namespace std; // A linked list nodeclass Node {public: int data; Node* next;}; // Given a reference (pointer to pointer) to// the head of a list and an int inserts a// new node on the front of the list.void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Given a reference (pointer to pointer) to// the head of a list and a position, deletes// the node at the given positionvoid deleteNode(Node** head_ref, int position){ // If linked list is empty if (*head_ref == NULL) return; // Store head node Node* temp = *head_ref; // If head needs to be removed if (position == 0) { // Change head *head_ref = temp->next; // Free old head free(temp); return; } // Find previous node of the node to be deleted for (int i = 0; temp != NULL && i < position - 1; i++) temp = temp->next; // If position is more than number of nodes if (temp == NULL || temp->next == NULL) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node* next = temp->next->next; // Unlink the node from linked list free(temp->next); // Free memory // Unlink the deleted node from list temp->next = next;} // This function prints contents of linked// list starting from the given nodevoid printList(Node* node){ while (node != NULL) { cout << node->data << " "; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); push(&head, 8); cout << "Created Linked List: "; printList(head); deleteNode(&head, 4); cout << "\nLinked List after Deletion at position 4: "; printList(head); return 0;} // This code is contributed by premsai2030
// Simple C code to delete node at particular position #include<stdio.h>#include<stdlib.h> void insert(int );void display_List();void delete(int ); struct node // Structure declaration{ int data; struct node *next; // Self referral pointer}*head=NULL,*tail=NULL; // Initial value of Head and Tail pointer is NULL void delete(int pos){ struct node *temp = head; // Creating a temporary variable pointing to head int i; if(pos==0) { printf("\nElement deleted is : %d\n",temp->data); head=head->next; // Advancing the head pointer temp->next=NULL; free(temp); // Node is deleted } else { for(i=0;i<pos-1;i++) { temp=temp->next; } // Now temp pointer points to the previous node of the node to be deleted struct node *del =temp->next; // del pointer points to the node to be deleted temp->next=temp->next->next; printf("\nElement deleted is : %d\n",del->data); del->next=NULL; free(del); // Node is deleted } printf("\nUpdated Linked List is : \n"); display_List(); return ;} void insert(int value){ struct node *newnode; // Creating a new node newnode = (struct node *)malloc(sizeof(struct node)); // Allocating dynamic memory newnode->data = value; // Assigning value to newnode newnode->next = NULL; if(head==NULL) // Checking if List is empty { head = newnode; tail = newnode; } else // If not empty then... { tail->next=newnode; tail=newnode; // Updating the tail node with each insertion } return ;} void display_List(){ struct node *temp; // Creating a temporary pointer to the structure temp=head; // temp points to head; while(temp!=NULL) { if(temp->next==NULL) { printf(" %d->NULL",temp->data); } else { printf(" %d->",temp->data); } temp=temp->next; // Traversing the List till end } printf("\n"); return ;}// --Driver Code--int main(){ insert(10); insert(20); insert(30); insert(40); insert(50); insert(60); printf("\n--Created Linked List--\n"); display_List(); printf("\nLinked List after deletion at position 0"); delete(0); // List indexing starts from 0 printf("\nLinked List after deletion at position 2"); delete(2); return 0;}// This code is contributed by Sanjeeban Mukhopadhyay.
// A complete working Java program to delete a node in a// linked list at a given positionclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Given a reference (pointer to pointer) to the head of a list and a position, deletes the node at the given position */ void deleteNode(int position) { // If linked list is empty if (head == null) return; // Store head node Node temp = head; // If head needs to be removed if (position == 0) { head = temp.next; // Change head return; } // Find previous node of the node to be deleted for (int i = 0; temp != null && i < position - 1; i++) temp = temp.next; // If position is more than number of nodes if (temp == null || temp.next == null) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node next = temp.next.next; temp.next = next; // Unlink the deleted node from list } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data + " "); tnode = tnode.next; } } /* Driver program to test above functions. Ideally this function should be in a separate user class. It is kept here to keep code compact */ public static void main(String[] args) { /* Start with the empty list */ LinkedList llist = new LinkedList(); llist.push(7); llist.push(1); llist.push(3); llist.push(2); llist.push(8); System.out.println("\nCreated Linked list is: "); llist.printList(); llist.deleteNode(4); // Delete node at position 4 System.out.println( "\nLinked List after Deletion at position 4: "); llist.printList(); }}
# Python program to delete a node in a linked list# at a given position # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Constructor to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Given a reference to the head of a list # and a position, delete the node at a given position #This delete function code is contributed by Arabin Islam def deleteNode(self, position): if self.head is None: return if position == 0: self.head = self.head.next return self.head index = 0 current = self.head prev = self.head temp = self.head while current is not None: if index == position: temp = current.next break prev = current current = current.next index += 1 prev.next = temp return prev # Utility function to print the LinkedList def printList(self): temp = self.head while(temp): print (" %d " % (temp.data),end=" ") temp = temp.next # Driver program to test above functionllist = LinkedList()llist.push(7)llist.push(1)llist.push(3)llist.push(2)llist.push(8) print ("Created Linked List: ")llist.printList()llist.deleteNode(4)print ("\nLinked List after Deletion at position 4: ")llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)
// A complete working C# program to delete// a node in a linked list at a given positionusing System; class GFG { // Head of list Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Inserts a new Node at front of the list. public void Push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Given a reference (pointer to pointer) // to the head of a list and a position, // deletes the node at the given position void deleteNode(int position) { // If linked list is empty if (head == null) return; // Store head node Node temp = head; // If head needs to be removed if (position == 0) { // Change head head = temp.next; return; } // Find previous node of the node to be deleted for (int i = 0; temp != null && i < position - 1; i++) temp = temp.next; // If position is more than number of nodes if (temp == null || temp.next == null) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node next = temp.next.next; // Unlink the deleted node from list temp.next = next; } // This function prints contents of // linked list starting from the // given node public void printList() { Node tnode = head; while (tnode != null) { Console.Write(tnode.data + " "); tnode = tnode.next; } } // Driver code public static void Main(String[] args) { // Start with the empty list GFG llist = new GFG(); llist.Push(7); llist.Push(1); llist.Push(3); llist.Push(2); llist.Push(8); Console.WriteLine("\nCreated Linked list is: "); llist.printList(); // Delete node at position 4 llist.deleteNode(4); Console.WriteLine("\nLinked List after " + "Deletion at position 4: "); llist.printList(); }} // This code is contributed by Rajput-Ji
<script> // A complete working javascript program to// delete a node in a linked list at a// given position // head of listvar head; /* Linked list Node */class Node{ constructor(val) { this.data = val; this.next = null; }} /* Inserts a new Node at front of the list. */function push(new_data){ /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} /* * Given a reference (pointer to pointer) to the * head of a list and a position, * deletes the node at the given position */function deleteNode(position){ // If linked list is empty if (head == null) return; // Store head node var temp = head; // If head needs to be removed if (position == 0) { // Change head head = temp.next; return; } // Find previous node of the node to be deleted for(i = 0; temp != null && i < position - 1; i++) temp = temp.next; // If position is more than number of nodes if (temp == null || temp.next == null) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted var next = temp.next.next; // Unlink the deleted node from list temp.next = next;} /** This function prints contents of linked* list starting from the given node*/function printList(){ var tnode = head; while (tnode != null) { document.write(tnode.data + " "); tnode = tnode.next; }} /** Driver program to test above functions.* Ideally this function should be in a* separate user class. It is kept here* to keep code compact*/ /* Start with the empty list */push(7);push(1);push(3);push(2);push(8); document.write("Created Linked list is: <br/>");printList(); // Delete node at position 4deleteNode(4); document.write("<br/>Linked List after " + "Deletion at position 4: <br/>");printList(); // This code is contributed by todaysgaurav </script>
Created Linked List: 8 2 3 1 7
Linked List after Deletion at position 4: 8 2 3 1
Complexity Analysis :
Best Case : O(1) if given position is 1
Average & Worst Case : O(N) if position given is size-1 then need to traverse till position not found.
Space Complexity : O(1) no extra any space is required
kanishk_bharadwaj
Akanksha_Rai
Rajput-Ji
premsai2030
todaysgaurav
simranarora5sos
arabintappware
amartyaghoshgfg
sanjeeban5644
simmytarika5
devendrasalunke
hardikkoriintern
Samsung
Linked List
Samsung
Linked List
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Jun, 2022"
},
{
"code": null,
"e": 144,
"s": 52,
"text": "Given a singly linked list and a position, delete a linked list node at the given position."
},
{
"code": null,
"e": 155,
"s": 144,
"text": "Example: "
},
{
"code": null,
"e": 321,
"s": 155,
"text": "Input: position = 1, Linked List = 8->2->3->1->7\nOutput: Linked List = 8->3->1->7\n\nInput: position = 0, Linked List = 8->2->3->1->7\nOutput: Linked List = 2->3->1->7"
},
{
"code": null,
"e": 575,
"s": 321,
"text": "If the node to be deleted is the root, simply delete it. To delete a middle node, we must have a pointer to the node previous to the node to be deleted. So if positions are not zero, we run a loop position-1 times and get a pointer to the previous node."
},
{
"code": null,
"e": 622,
"s": 575,
"text": "Below is the implementation of the above idea."
},
{
"code": null,
"e": 626,
"s": 622,
"text": "C++"
},
{
"code": null,
"e": 628,
"s": 626,
"text": "C"
},
{
"code": null,
"e": 633,
"s": 628,
"text": "Java"
},
{
"code": null,
"e": 641,
"s": 633,
"text": "Python3"
},
{
"code": null,
"e": 644,
"s": 641,
"text": "C#"
},
{
"code": null,
"e": 655,
"s": 644,
"text": "Javascript"
},
{
"code": "// A complete working C++ program to delete// a node in a linked list at a given position#include <iostream>using namespace std; // A linked list nodeclass Node {public: int data; Node* next;}; // Given a reference (pointer to pointer) to// the head of a list and an int inserts a// new node on the front of the list.void push(Node** head_ref, int new_data){ Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); (*head_ref) = new_node;} // Given a reference (pointer to pointer) to// the head of a list and a position, deletes// the node at the given positionvoid deleteNode(Node** head_ref, int position){ // If linked list is empty if (*head_ref == NULL) return; // Store head node Node* temp = *head_ref; // If head needs to be removed if (position == 0) { // Change head *head_ref = temp->next; // Free old head free(temp); return; } // Find previous node of the node to be deleted for (int i = 0; temp != NULL && i < position - 1; i++) temp = temp->next; // If position is more than number of nodes if (temp == NULL || temp->next == NULL) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node* next = temp->next->next; // Unlink the node from linked list free(temp->next); // Free memory // Unlink the deleted node from list temp->next = next;} // This function prints contents of linked// list starting from the given nodevoid printList(Node* node){ while (node != NULL) { cout << node->data << \" \"; node = node->next; }} // Driver codeint main(){ // Start with the empty list Node* head = NULL; push(&head, 7); push(&head, 1); push(&head, 3); push(&head, 2); push(&head, 8); cout << \"Created Linked List: \"; printList(head); deleteNode(&head, 4); cout << \"\\nLinked List after Deletion at position 4: \"; printList(head); return 0;} // This code is contributed by premsai2030",
"e": 2724,
"s": 655,
"text": null
},
{
"code": "// Simple C code to delete node at particular position #include<stdio.h>#include<stdlib.h> void insert(int );void display_List();void delete(int ); struct node // Structure declaration{ int data; struct node *next; // Self referral pointer}*head=NULL,*tail=NULL; // Initial value of Head and Tail pointer is NULL void delete(int pos){ struct node *temp = head; // Creating a temporary variable pointing to head int i; if(pos==0) { printf(\"\\nElement deleted is : %d\\n\",temp->data); head=head->next; // Advancing the head pointer temp->next=NULL; free(temp); // Node is deleted } else { for(i=0;i<pos-1;i++) { temp=temp->next; } // Now temp pointer points to the previous node of the node to be deleted struct node *del =temp->next; // del pointer points to the node to be deleted temp->next=temp->next->next; printf(\"\\nElement deleted is : %d\\n\",del->data); del->next=NULL; free(del); // Node is deleted } printf(\"\\nUpdated Linked List is : \\n\"); display_List(); return ;} void insert(int value){ struct node *newnode; // Creating a new node newnode = (struct node *)malloc(sizeof(struct node)); // Allocating dynamic memory newnode->data = value; // Assigning value to newnode newnode->next = NULL; if(head==NULL) // Checking if List is empty { head = newnode; tail = newnode; } else // If not empty then... { tail->next=newnode; tail=newnode; // Updating the tail node with each insertion } return ;} void display_List(){ struct node *temp; // Creating a temporary pointer to the structure temp=head; // temp points to head; while(temp!=NULL) { if(temp->next==NULL) { printf(\" %d->NULL\",temp->data); } else { printf(\" %d->\",temp->data); } temp=temp->next; // Traversing the List till end } printf(\"\\n\"); return ;}// --Driver Code--int main(){ insert(10); insert(20); insert(30); insert(40); insert(50); insert(60); printf(\"\\n--Created Linked List--\\n\"); display_List(); printf(\"\\nLinked List after deletion at position 0\"); delete(0); // List indexing starts from 0 printf(\"\\nLinked List after deletion at position 2\"); delete(2); return 0;}// This code is contributed by Sanjeeban Mukhopadhyay.",
"e": 5351,
"s": 2724,
"text": null
},
{
"code": "// A complete working Java program to delete a node in a// linked list at a given positionclass LinkedList { Node head; // head of list /* Linked list Node*/ class Node { int data; Node next; Node(int d) { data = d; next = null; } } /* Inserts a new Node at front of the list. */ public void push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } /* Given a reference (pointer to pointer) to the head of a list and a position, deletes the node at the given position */ void deleteNode(int position) { // If linked list is empty if (head == null) return; // Store head node Node temp = head; // If head needs to be removed if (position == 0) { head = temp.next; // Change head return; } // Find previous node of the node to be deleted for (int i = 0; temp != null && i < position - 1; i++) temp = temp.next; // If position is more than number of nodes if (temp == null || temp.next == null) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node next = temp.next.next; temp.next = next; // Unlink the deleted node from list } /* This function prints contents of linked list starting from the given node */ public void printList() { Node tnode = head; while (tnode != null) { System.out.print(tnode.data + \" \"); tnode = tnode.next; } } /* Driver program to test above functions. Ideally this function should be in a separate user class. It is kept here to keep code compact */ public static void main(String[] args) { /* Start with the empty list */ LinkedList llist = new LinkedList(); llist.push(7); llist.push(1); llist.push(3); llist.push(2); llist.push(8); System.out.println(\"\\nCreated Linked list is: \"); llist.printList(); llist.deleteNode(4); // Delete node at position 4 System.out.println( \"\\nLinked List after Deletion at position 4: \"); llist.printList(); }}",
"e": 7900,
"s": 5351,
"text": null
},
{
"code": "# Python program to delete a node in a linked list# at a given position # Node class class Node: # Constructor to initialize the node object def __init__(self, data): self.data = data self.next = None class LinkedList: # Constructor to initialize head def __init__(self): self.head = None # Function to insert a new node at the beginning def push(self, new_data): new_node = Node(new_data) new_node.next = self.head self.head = new_node # Given a reference to the head of a list # and a position, delete the node at a given position #This delete function code is contributed by Arabin Islam def deleteNode(self, position): if self.head is None: return if position == 0: self.head = self.head.next return self.head index = 0 current = self.head prev = self.head temp = self.head while current is not None: if index == position: temp = current.next break prev = current current = current.next index += 1 prev.next = temp return prev # Utility function to print the LinkedList def printList(self): temp = self.head while(temp): print (\" %d \" % (temp.data),end=\" \") temp = temp.next # Driver program to test above functionllist = LinkedList()llist.push(7)llist.push(1)llist.push(3)llist.push(2)llist.push(8) print (\"Created Linked List: \")llist.printList()llist.deleteNode(4)print (\"\\nLinked List after Deletion at position 4: \")llist.printList() # This code is contributed by Nikhil Kumar Singh(nickzuck_007)",
"e": 9599,
"s": 7900,
"text": null
},
{
"code": "// A complete working C# program to delete// a node in a linked list at a given positionusing System; class GFG { // Head of list Node head; // Linked list Node public class Node { public int data; public Node next; public Node(int d) { data = d; next = null; } } // Inserts a new Node at front of the list. public void Push(int new_data) { /* 1 & 2: Allocate the Node & Put in the data*/ Node new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node; } // Given a reference (pointer to pointer) // to the head of a list and a position, // deletes the node at the given position void deleteNode(int position) { // If linked list is empty if (head == null) return; // Store head node Node temp = head; // If head needs to be removed if (position == 0) { // Change head head = temp.next; return; } // Find previous node of the node to be deleted for (int i = 0; temp != null && i < position - 1; i++) temp = temp.next; // If position is more than number of nodes if (temp == null || temp.next == null) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted Node next = temp.next.next; // Unlink the deleted node from list temp.next = next; } // This function prints contents of // linked list starting from the // given node public void printList() { Node tnode = head; while (tnode != null) { Console.Write(tnode.data + \" \"); tnode = tnode.next; } } // Driver code public static void Main(String[] args) { // Start with the empty list GFG llist = new GFG(); llist.Push(7); llist.Push(1); llist.Push(3); llist.Push(2); llist.Push(8); Console.WriteLine(\"\\nCreated Linked list is: \"); llist.printList(); // Delete node at position 4 llist.deleteNode(4); Console.WriteLine(\"\\nLinked List after \" + \"Deletion at position 4: \"); llist.printList(); }} // This code is contributed by Rajput-Ji",
"e": 12091,
"s": 9599,
"text": null
},
{
"code": "<script> // A complete working javascript program to// delete a node in a linked list at a// given position // head of listvar head; /* Linked list Node */class Node{ constructor(val) { this.data = val; this.next = null; }} /* Inserts a new Node at front of the list. */function push(new_data){ /* * 1 & 2: Allocate the Node & Put in the data */ var new_node = new Node(new_data); /* 3. Make next of new Node as head */ new_node.next = head; /* 4. Move the head to point to new Node */ head = new_node;} /* * Given a reference (pointer to pointer) to the * head of a list and a position, * deletes the node at the given position */function deleteNode(position){ // If linked list is empty if (head == null) return; // Store head node var temp = head; // If head needs to be removed if (position == 0) { // Change head head = temp.next; return; } // Find previous node of the node to be deleted for(i = 0; temp != null && i < position - 1; i++) temp = temp.next; // If position is more than number of nodes if (temp == null || temp.next == null) return; // Node temp->next is the node to be deleted // Store pointer to the next of node to be deleted var next = temp.next.next; // Unlink the deleted node from list temp.next = next;} /** This function prints contents of linked* list starting from the given node*/function printList(){ var tnode = head; while (tnode != null) { document.write(tnode.data + \" \"); tnode = tnode.next; }} /** Driver program to test above functions.* Ideally this function should be in a* separate user class. It is kept here* to keep code compact*/ /* Start with the empty list */push(7);push(1);push(3);push(2);push(8); document.write(\"Created Linked list is: <br/>\");printList(); // Delete node at position 4deleteNode(4); document.write(\"<br/>Linked List after \" + \"Deletion at position 4: <br/>\");printList(); // This code is contributed by todaysgaurav </script>",
"e": 14216,
"s": 12091,
"text": null
},
{
"code": null,
"e": 14299,
"s": 14216,
"text": "Created Linked List: 8 2 3 1 7 \nLinked List after Deletion at position 4: 8 2 3 1 "
},
{
"code": null,
"e": 14322,
"s": 14299,
"text": "Complexity Analysis : "
},
{
"code": null,
"e": 14363,
"s": 14322,
"text": "Best Case : O(1) if given position is 1 "
},
{
"code": null,
"e": 14468,
"s": 14363,
"text": "Average & Worst Case : O(N) if position given is size-1 then need to traverse till position not found."
},
{
"code": null,
"e": 14523,
"s": 14468,
"text": "Space Complexity : O(1) no extra any space is required"
},
{
"code": null,
"e": 14541,
"s": 14523,
"text": "kanishk_bharadwaj"
},
{
"code": null,
"e": 14554,
"s": 14541,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 14564,
"s": 14554,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 14576,
"s": 14564,
"text": "premsai2030"
},
{
"code": null,
"e": 14589,
"s": 14576,
"text": "todaysgaurav"
},
{
"code": null,
"e": 14605,
"s": 14589,
"text": "simranarora5sos"
},
{
"code": null,
"e": 14620,
"s": 14605,
"text": "arabintappware"
},
{
"code": null,
"e": 14636,
"s": 14620,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 14650,
"s": 14636,
"text": "sanjeeban5644"
},
{
"code": null,
"e": 14663,
"s": 14650,
"text": "simmytarika5"
},
{
"code": null,
"e": 14679,
"s": 14663,
"text": "devendrasalunke"
},
{
"code": null,
"e": 14696,
"s": 14679,
"text": "hardikkoriintern"
},
{
"code": null,
"e": 14704,
"s": 14696,
"text": "Samsung"
},
{
"code": null,
"e": 14716,
"s": 14704,
"text": "Linked List"
},
{
"code": null,
"e": 14724,
"s": 14716,
"text": "Samsung"
},
{
"code": null,
"e": 14736,
"s": 14724,
"text": "Linked List"
}
] |
How to find an element using the attribute “name” in Selenium? | We can find an element using the attribute name with Selenium webdriver using the locators - name, css, or xpath. To identify the element with css, the expression should be tagname[name='value'] and the method to be used is By.cssSelector.
To identify the element with xpath, the expression should be //tagname[@name='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator name, we have to use the By.name method.
Let us look at the html code of an element with name attribute −
WebElement e = driver. findElement(By.name("q"));
WebElement m = driver. findElement(By.xpath("//input[@name = 'q']"));
WebElement n =
driver. findElement(By.cssSelector("input[name='q']"));
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import java.util.concurrent.TimeUnit;
public class LocatorName{
public static void main(String[] args) {
System.setProperty("webdriver.gecko.driver",
"C:\\Users\\ghs6kor\\Desktop\\Java\\geckodriver.exe");
WebDriver driver = new FirefoxDriver();
//implicit wait
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
//URL launch
driver.get("https://www.google.com/");
// identify element with name
WebElement k = driver.findElement(By.name("q"));
k.sendKeys("Selenium");
//identify element with css
WebElement p = driver.
findElement(By.cssSelector("input[name='q']"));
String st = p.getAttribute("value");
System.out.println("Attribute value: " + st);
//identify element with xpath
WebElement o = driver.
findElement(By.xpath("//input[@name='q']"));
o.clear();
driver.quit();
}
} | [
{
"code": null,
"e": 1302,
"s": 1062,
"text": "We can find an element using the attribute name with Selenium webdriver using the locators - name, css, or xpath. To identify the element with css, the expression should be tagname[name='value'] and the method to be used is By.cssSelector."
},
{
"code": null,
"e": 1521,
"s": 1302,
"text": "To identify the element with xpath, the expression should be //tagname[@name='value']. Then, we have to use the method By.xpath to locate it. To locate an element with a locator name, we have to use the By.name method."
},
{
"code": null,
"e": 1586,
"s": 1521,
"text": "Let us look at the html code of an element with name attribute −"
},
{
"code": null,
"e": 1777,
"s": 1586,
"text": "WebElement e = driver. findElement(By.name(\"q\"));\nWebElement m = driver. findElement(By.xpath(\"//input[@name = 'q']\"));\nWebElement n =\ndriver. findElement(By.cssSelector(\"input[name='q']\"));"
},
{
"code": null,
"e": 2846,
"s": 1777,
"text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.firefox.FirefoxDriver;\nimport java.util.concurrent.TimeUnit;\npublic class LocatorName{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.gecko.driver\",\n\"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\geckodriver.exe\");\n WebDriver driver = new FirefoxDriver();\n //implicit wait\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n //URL launch\n driver.get(\"https://www.google.com/\");\n // identify element with name\n WebElement k = driver.findElement(By.name(\"q\"));\n k.sendKeys(\"Selenium\");\n //identify element with css\n WebElement p = driver.\n findElement(By.cssSelector(\"input[name='q']\"));\n String st = p.getAttribute(\"value\");\n System.out.println(\"Attribute value: \" + st);\n //identify element with xpath\n WebElement o = driver.\n findElement(By.xpath(\"//input[@name='q']\"));\n\n o.clear();\n driver.quit();\n }\n}"
}
] |
Java String isEmpty() method with example - GeeksforGeeks | 04 Dec, 2018
Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of String class is included in java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0.Examples:
Input String1 : Hello_Gfg
Input String2 :
Output for String1 : false
Output for String2 : true
Syntax:
public boolean isEmpty()
Returns : true if the length of the string is 0.
// Java program to demonstrate working of // isEmpty() methodclass Gfg { public static void main(String args[]) { // non-empty string String str1 = "Hello_Gfg"; // empty string String str2 = ""; // prints false System.out.println(str1.isEmpty()); // prints true System.out.println(str2.isEmpty()); }}
Output:
false
true
Java-Functions
Java-lang package
Java-Strings
Java
Java-Strings
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Initialize an ArrayList in Java
Overriding in Java
Multidimensional Arrays in Java
LinkedList in Java
PriorityQueue in Java
How to iterate any Map in Java
ArrayList in Java
Queue Interface In Java
Stack Class in Java
Object Oriented Programming (OOPs) Concept in Java | [
{
"code": null,
"e": 24666,
"s": 24638,
"text": "\n04 Dec, 2018"
},
{
"code": null,
"e": 25006,
"s": 24666,
"text": "Java.lang.String.isEmpty() String method checks whether a String is empty or not. This method returns true if the given string is empty, else it returns false. The isEmpty() method of String class is included in java string since JDK 1.6. In other words, you can say that this method returns true if the length of the string is 0.Examples:"
},
{
"code": null,
"e": 25102,
"s": 25006,
"text": "Input String1 : Hello_Gfg\nInput String2 :\nOutput for String1 : false\nOutput for String2 : true\n"
},
{
"code": null,
"e": 25110,
"s": 25102,
"text": "Syntax:"
},
{
"code": null,
"e": 25184,
"s": 25110,
"text": "public boolean isEmpty()\nReturns : true if the length of the string is 0."
},
{
"code": "// Java program to demonstrate working of // isEmpty() methodclass Gfg { public static void main(String args[]) { // non-empty string String str1 = \"Hello_Gfg\"; // empty string String str2 = \"\"; // prints false System.out.println(str1.isEmpty()); // prints true System.out.println(str2.isEmpty()); }}",
"e": 25556,
"s": 25184,
"text": null
},
{
"code": null,
"e": 25564,
"s": 25556,
"text": "Output:"
},
{
"code": null,
"e": 25576,
"s": 25564,
"text": "false\ntrue\n"
},
{
"code": null,
"e": 25591,
"s": 25576,
"text": "Java-Functions"
},
{
"code": null,
"e": 25609,
"s": 25591,
"text": "Java-lang package"
},
{
"code": null,
"e": 25622,
"s": 25609,
"text": "Java-Strings"
},
{
"code": null,
"e": 25627,
"s": 25622,
"text": "Java"
},
{
"code": null,
"e": 25640,
"s": 25627,
"text": "Java-Strings"
},
{
"code": null,
"e": 25645,
"s": 25640,
"text": "Java"
},
{
"code": null,
"e": 25743,
"s": 25645,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25752,
"s": 25743,
"text": "Comments"
},
{
"code": null,
"e": 25765,
"s": 25752,
"text": "Old Comments"
},
{
"code": null,
"e": 25797,
"s": 25765,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 25816,
"s": 25797,
"text": "Overriding in Java"
},
{
"code": null,
"e": 25848,
"s": 25816,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 25867,
"s": 25848,
"text": "LinkedList in Java"
},
{
"code": null,
"e": 25889,
"s": 25867,
"text": "PriorityQueue in Java"
},
{
"code": null,
"e": 25920,
"s": 25889,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 25938,
"s": 25920,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 25962,
"s": 25938,
"text": "Queue Interface In Java"
},
{
"code": null,
"e": 25982,
"s": 25962,
"text": "Stack Class in Java"
}
] |
Java String split() method example. | The split(String regex, int limit) method of the String class. splits the current string around matches of the given regular expression.
The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string.
If the expression does not match any part of the input then the resulting array has just one element, namely this string.
Live Demo
import java.lang.*;
public class StringDemo {
public static void main(String[] args) {
String str = "a d, m, i.n";
String delimiters = "\\s+|,\\s*|\\.\\s*";
//analysing the string
String[] tokensVal = str.split(delimiters);
//prints the count of tokens
System.out.println("Count of tokens = " + tokensVal.length);
for(String token : tokensVal) {
System.out.print(token);
}
//analysing the string with limit as 3
tokensVal = str.split(delimiters, 3);
//prints the count of tokens
System.out.println("\nCount of tokens = " + tokensVal.length);
for(String token : tokensVal) {
System.out.print(token);
}
}
}
Count of tokens = 5
admin
Count of tokens = 3
adm, i.n | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "The split(String regex, int limit) method of the String class. splits the current string around matches of the given regular expression."
},
{
"code": null,
"e": 1389,
"s": 1199,
"text": "The array returned by this method contains each substring of this string that is terminated by another substring that matches the given expression or is terminated by the end of the string."
},
{
"code": null,
"e": 1511,
"s": 1389,
"text": "If the expression does not match any part of the input then the resulting array has just one element, namely this string."
},
{
"code": null,
"e": 1521,
"s": 1511,
"text": "Live Demo"
},
{
"code": null,
"e": 2238,
"s": 1521,
"text": "import java.lang.*;\npublic class StringDemo {\n public static void main(String[] args) {\n String str = \"a d, m, i.n\";\n String delimiters = \"\\\\s+|,\\\\s*|\\\\.\\\\s*\";\n\n //analysing the string\n String[] tokensVal = str.split(delimiters);\n\n //prints the count of tokens\n System.out.println(\"Count of tokens = \" + tokensVal.length);\n\n for(String token : tokensVal) {\n System.out.print(token);\n }\n //analysing the string with limit as 3\n tokensVal = str.split(delimiters, 3);\n\n //prints the count of tokens\n System.out.println(\"\\nCount of tokens = \" + tokensVal.length);\n for(String token : tokensVal) {\n System.out.print(token);\n }\n }\n}"
},
{
"code": null,
"e": 2293,
"s": 2238,
"text": "Count of tokens = 5\nadmin\nCount of tokens = 3\nadm, i.n"
}
] |
java.util.zip.ZipInputStream.read() Method Example | The java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method reads from the current ZIP entry into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned.
Following is the declaration for java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method.
public int read(byte[] buf, int off, int len)
throws IOException
buf − the buffer into which the data is read.
buf − the buffer into which the data is read.
off − the start offset in the destination array b.
off − the start offset in the destination array b.
len − the maximum number of bytes read.
len − the maximum number of bytes read.
the actual number of bytes read, or -1 if the end of the stream is reached.
NullPointerException − If buf is null.
NullPointerException − If buf is null.
IndexOutOfBoundsException − If off is negative, len is negative, or len is greater than buf.length - off.
IndexOutOfBoundsException − If off is negative, len is negative, or len is greater than buf.length - off.
ZipException − if a ZIP file error has occurred.
ZipException − if a ZIP file error has occurred.
IOException − if an I/O error has occurred.
IOException − if an I/O error has occurred.
Create a file Hello.txt in D:> test > directory with the following content.
This is an example.
The following example shows the usage of java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method.
package com.tutorialspoint;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.zip.Adler32;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipInputStreamDemo {
private static String SOURCE_FILE = "D:\\test\\Hello.txt";
private static String TARGET_FILE = "D:\\test\\Hello.zip";
public static void main(String[] args) {
try {
createZipFile();
readZipFile();
} catch(IOException ioe) {
System.out.println("IOException : " + ioe);
}
}
private static void createZipFile() throws IOException{
FileOutputStream fout = new FileOutputStream(TARGET_FILE);
CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());
ZipOutputStream zout = new ZipOutputStream(checksum);
FileInputStream fin = new FileInputStream(SOURCE_FILE);
ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);
zout.putNextEntry(zipEntry);
int length;
byte[] buffer = new byte[1024];
while((length = fin.read(buffer)) > 0) {
zout.write(buffer, 0, length);
}
zout.closeEntry();
fin.close();
zout.close();
}
private static void readZipFile() throws IOException{
ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE));
ZipEntry entry;
while((entry = zin.getNextEntry())!=null){
System.out.printf("File: %s Modified on %TD %n",
entry.getName(), new Date(entry.getTime()));
extractFile(entry, zin);
System.out.printf("Zip file %s extracted successfully.", SOURCE_FILE);
zin.closeEntry();
}
zin.close();
}
private static void extractFile(final ZipEntry entry, ZipInputStream is)
throws IOException {
FileOutputStream fos = null;
try {
fos = new FileOutputStream(entry.getName());
final byte[] buf = new byte[1024];
int read = 0;
int length;
while ((length = is.read(buf, 0, buf.length)) >= 0) {
fos.write(buf, 0, length);
}
} catch (IOException ioex) {
fos.close();
}
}
}
Let us compile and run the above program, this will produce the following result −
File: D:\test\Hello.txt Modified on 05/22/17
Zip file D:\test\Hello.txt extracted successfully.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2441,
"s": 2192,
"text": "The java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method reads from the current ZIP entry into an array of bytes. If len is not zero, the method blocks until some input is available; otherwise, no bytes are read and 0 is returned."
},
{
"code": null,
"e": 2546,
"s": 2441,
"text": "Following is the declaration for java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method."
},
{
"code": null,
"e": 2615,
"s": 2546,
"text": "public int read(byte[] buf, int off, int len)\n throws IOException\n"
},
{
"code": null,
"e": 2661,
"s": 2615,
"text": "buf − the buffer into which the data is read."
},
{
"code": null,
"e": 2707,
"s": 2661,
"text": "buf − the buffer into which the data is read."
},
{
"code": null,
"e": 2758,
"s": 2707,
"text": "off − the start offset in the destination array b."
},
{
"code": null,
"e": 2809,
"s": 2758,
"text": "off − the start offset in the destination array b."
},
{
"code": null,
"e": 2849,
"s": 2809,
"text": "len − the maximum number of bytes read."
},
{
"code": null,
"e": 2889,
"s": 2849,
"text": "len − the maximum number of bytes read."
},
{
"code": null,
"e": 2965,
"s": 2889,
"text": "the actual number of bytes read, or -1 if the end of the stream is reached."
},
{
"code": null,
"e": 3005,
"s": 2965,
"text": "NullPointerException − If buf is null."
},
{
"code": null,
"e": 3045,
"s": 3005,
"text": "NullPointerException − If buf is null."
},
{
"code": null,
"e": 3152,
"s": 3045,
"text": "IndexOutOfBoundsException − If off is negative, len is negative, or len is greater than buf.length - off."
},
{
"code": null,
"e": 3259,
"s": 3152,
"text": "IndexOutOfBoundsException − If off is negative, len is negative, or len is greater than buf.length - off."
},
{
"code": null,
"e": 3309,
"s": 3259,
"text": "ZipException − if a ZIP file error has occurred."
},
{
"code": null,
"e": 3359,
"s": 3309,
"text": "ZipException − if a ZIP file error has occurred."
},
{
"code": null,
"e": 3404,
"s": 3359,
"text": "IOException − if an I/O error has occurred."
},
{
"code": null,
"e": 3449,
"s": 3404,
"text": "IOException − if an I/O error has occurred."
},
{
"code": null,
"e": 3526,
"s": 3449,
"text": "Create a file Hello.txt in D:> test > directory with the following content."
},
{
"code": null,
"e": 3547,
"s": 3526,
"text": "This is an example.\n"
},
{
"code": null,
"e": 3660,
"s": 3547,
"text": "The following example shows the usage of java.util.zip.ZipInputStream.read(byte[] buf, int off, int len) method."
},
{
"code": null,
"e": 5978,
"s": 3660,
"text": "package com.tutorialspoint;\n\nimport java.io.FileInputStream;\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.Date;\nimport java.util.zip.Adler32;\nimport java.util.zip.CheckedOutputStream;\nimport java.util.zip.ZipEntry;\nimport java.util.zip.ZipInputStream;\nimport java.util.zip.ZipOutputStream;\n\npublic class ZipInputStreamDemo {\n private static String SOURCE_FILE = \"D:\\\\test\\\\Hello.txt\";\n private static String TARGET_FILE = \"D:\\\\test\\\\Hello.zip\";\n\n public static void main(String[] args) {\n try {\n createZipFile();\n readZipFile();\n } catch(IOException ioe) {\n System.out.println(\"IOException : \" + ioe);\n }\n }\n\n private static void createZipFile() throws IOException{\n FileOutputStream fout = new FileOutputStream(TARGET_FILE);\n CheckedOutputStream checksum = new CheckedOutputStream(fout, new Adler32());\n ZipOutputStream zout = new ZipOutputStream(checksum);\n\n FileInputStream fin = new FileInputStream(SOURCE_FILE);\n ZipEntry zipEntry = new ZipEntry(SOURCE_FILE);\n zout.putNextEntry(zipEntry);\n int length;\n byte[] buffer = new byte[1024];\n while((length = fin.read(buffer)) > 0) {\n zout.write(buffer, 0, length);\n }\n\n zout.closeEntry();\n fin.close();\n zout.close();\n }\n\n private static void readZipFile() throws IOException{\n ZipInputStream zin = new ZipInputStream(new FileInputStream(TARGET_FILE)); \n\n ZipEntry entry;\n while((entry = zin.getNextEntry())!=null){\n System.out.printf(\"File: %s Modified on %TD %n\", \n entry.getName(), new Date(entry.getTime()));\n extractFile(entry, zin); \n System.out.printf(\"Zip file %s extracted successfully.\", SOURCE_FILE);\n zin.closeEntry();\n }\n zin.close();\n }\n\n private static void extractFile(final ZipEntry entry, ZipInputStream is) \n throws IOException {\n FileOutputStream fos = null; \n try { \n fos = new FileOutputStream(entry.getName()); \n final byte[] buf = new byte[1024]; \n int read = 0; \n int length; \n while ((length = is.read(buf, 0, buf.length)) >= 0) { \n fos.write(buf, 0, length); \n } \n } catch (IOException ioex) { \n fos.close(); \n } \n }\n}"
},
{
"code": null,
"e": 6061,
"s": 5978,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 6159,
"s": 6061,
"text": "File: D:\\test\\Hello.txt Modified on 05/22/17 \nZip file D:\\test\\Hello.txt extracted successfully.\n"
},
{
"code": null,
"e": 6166,
"s": 6159,
"text": " Print"
},
{
"code": null,
"e": 6177,
"s": 6166,
"text": " Add Notes"
}
] |
Maximum water that can be stored between two buildings - GeeksforGeeks | 11 Feb, 2022
Given an integer array which represents the heights of N buildings, the task is to delete N-2 buildings such that the water that can be trapped between the remaining two building is maximum. Please note that the total water trapped between two buildings is gap between them (number of buildings removed) multiplied by height of the smaller building.
Examples:
Input: arr[] = {1, 3, 4} Output: 1 We have to calculate the maximum water that can be stored between any 2 buildings. Water between the buildings of height 1 and height 3 = 0. Water between the buildings of height 1 and height 4 = 1. Water between the buildings of height 3 and height 4 = 0. Hence maximum of all the cases is 1.
Input: arr[] = {2, 1, 3, 4, 6, 5} Output: 8 We remove the middle 4 buildings and get the total water stored as 2 * 4 = 8
Naive approach: Check for all possible pairs and the pair which can hold maximum water will be the answer. Water stored between two buildings of height h1 and h2 would be equal to:
minimum(h1, h2)*(distance between the buildings-1)
Our task is to maximize this value for every pair.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Return the maximum water that can be storedint maxWater(int height[], int n){ int maximum = 0; // Check all possible pairs of buildings for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int current = (min(height[i], height[j]) * (j - i - 1)); // Maximum so far maximum = max(maximum, current); } } return maximum;} // Driver codeint main(){ int height[] = { 2, 1, 3, 4, 6, 5 }; int n = sizeof(height) / sizeof(height[0]); cout << maxWater(height, n); return 0;} // This code is contributed by ihritik
// Java implementation of the above approachclass GFG { // Return the maximum water that can be stored static int maxWater(int height[], int n) { int max = 0; // Check all possible pairs of buildings for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int current = (Math.min(height[i], height[j]) * (j - i - 1)); // Maximum so far max = Math.max(max, current); } } return max; } // Driver code public static void main(String[] args) { int height[] = { 2, 1, 3, 4, 6, 5 }; int n = height.length; System.out.print(maxWater(height, n)); }}
# Python3 implementation of the above approach # Return the maximum water# that can be storeddef maxWater(height, n) : maximum = 0; # Check all possible pairs of buildings for i in range(n - 1) : for j in range(i + 1, n) : current = min(height[i], height[j]) * (j - i - 1); # Maximum so far maximum = max(maximum, current); return maximum; # Driver codeif __name__ == "__main__" : height = [ 2, 1, 3, 4, 6, 5 ]; n = len(height); print(maxWater(height, n)); # This code is contributed by AnkitRai01
// C# implementation of the above approachusing System; class GFG { // Return the maximum water that can be stored static int maxWater(int[] height, int n) { int max = 0; // Check all possible pairs of buildings for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int current = (Math.Min(height[i], height[j]) * (j - i - 1)); // Maximum so far max = Math.Max(max, current); } } return max; } // Driver code static public void Main() { int[] height = { 2, 1, 3, 4, 6, 5 }; int n = height.Length; Console.WriteLine(maxWater(height, n)); }} // This code is contributed by @tushil.
<script> // Javascript implementation of the above approach // Return the maximum water that can be storedfunction maxWater( height, n){ let maximum = 0; // Check all possible pairs of buildings for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let current = (Math.min(height[i], height[j]) * (j - i - 1)); // Maximum so far maximum = Math.max(maximum, current); } } return maximum;} // Driver program let height = [ 2, 1, 3, 4, 6, 5 ]; let n = height.length; document.write(maxWater(height, n)); </script>
8
Time Complexity: O(N*N)
Efficient approach:
Sort the array according to increasing height without affecting the original indices i.e. make pairs of (element, index).
Then for every element, assume it is the building with the minimum height among the two buildings required then the height of the required water will be equal to the height of the chosen building and the width will be equal to the index difference between the chosen building and the building to be found.
In order to choose the other building which maximizes the water, the other building has to be as far as possible and must be greater in height as compared to the currently chosen building.
Now, the problem gets reduced to finding the minimum and maximum indices on the right for every building in the sorted array.
Below is the implementation of the above approach:
C++
Java
// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; bool compareTo(pair<int, int> p1, pair<int, int> p2){ return p1.second < p2.second;} // Return the maximum water that// can be storedint maxWater(int height[], int n){ // Make pairs with indices pair<int, int> pairs[n]; for(int i = 0; i < n; i++) pairs[i] = make_pair(i, height[i]); // Sort array based on heights sort(pairs, pairs + n, compareTo); // To store the min and max index so far // from the right int minIndSoFar = pairs[n - 1].first; int maxIndSoFar = pairs[n - 1].first; int maxi = 0; for(int i = n - 2; i >= 0; i--) { // Current building paired with // the building greater in height // and on the extreme left int left = 0; if (minIndSoFar < pairs[i].first) { left = (pairs[i].second * (pairs[i].first - minIndSoFar - 1)); } // Current building paired with // the building greater in height // and on the extreme right int right = 0; if (maxIndSoFar > pairs[i].first) { right = (pairs[i].second * (maxIndSoFar - pairs[i].first - 1)); } // Maximum so far maxi = max(left, max(right, maxi)); // Update the maximum and minimum so far minIndSoFar = min(minIndSoFar, pairs[i].first); maxIndSoFar = max(maxIndSoFar, pairs[i].first); } return maxi;} // Driver codeint main( ){ int height[] = { 2, 1, 3, 4, 6, 5 }; int n = sizeof(height) / sizeof(height[0]); cout << maxWater(height, n);} // This code is contributed by manupathria
// Java implementation of the above approachimport java.util.Arrays; // Class to store the pairsclass Pair implements Comparable<Pair> { int ind, val; Pair(int ind, int val) { this.ind = ind; this.val = val; } @Override public int compareTo(Pair o) { if (this.val > o.val) return 1; return -1; }} class GFG { // Return the maximum water that can be stored static int maxWater(int height[], int n) { // Make pairs with indices Pair pairs[] = new Pair[n]; for (int i = 0; i < n; i++) pairs[i] = new Pair(i, height[i]); // Sort array based on heights Arrays.sort(pairs); // To store the min and max index so far // from the right int minIndSoFar = pairs[n - 1].ind; int maxIndSoFar = pairs[n - 1].ind; int max = 0; for (int i = n - 2; i >= 0; i--) { // Current building paired with the building // greater in height and on the extreme left int left = 0; if (minIndSoFar < pairs[i].ind) { left = (pairs[i].val * (pairs[i].ind - minIndSoFar - 1)); } // Current building paired with the building // greater in height and on the extreme right int right = 0; if (maxIndSoFar > pairs[i].ind) { right = (pairs[i].val * (maxIndSoFar - pairs[i].ind - 1)); } // Maximum so far max = Math.max(left, Math.max(right, max)); // Update the maximum and minimum so far minIndSoFar = Math.min(minIndSoFar, pairs[i].ind); maxIndSoFar = Math.max(maxIndSoFar, pairs[i].ind); } return max; } // Driver code public static void main(String[] args) { int height[] = { 2, 1, 3, 4, 6, 5 }; int n = height.length; System.out.print(maxWater(height, n)); }}
8
Time Complexity : O(N*log(N))
Two pointer approach: Take two pointers i and j pointing to the first and the last building respectively and calculate the water that can be stored between these two buildings. Now increment i if height[i] < height[j] else decrement j. This is because the water that can be trapped is dependent on the height of the small building and moving from the greater height building will just reduce the amount of water instead of maximizing it. In the end, print the maximum amount of water calculated so far.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Return the maximum water that can be storedint maxWater(int height[], int n){ // To store the maximum water so far int maximum = 0; // Both the pointers are pointing at the first // and the last buildings respectively int i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { maximum = max(maximum, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { maximum = max(maximum, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { maximum = max(maximum, (j - i - 1) * height[i]); i++; j--; } } return maximum;} // Driver codeint main(){ int height[] = { 2, 1, 3, 4, 6, 5 }; int n = sizeof(height)/sizeof(height[0]); cout<<(maxWater(height, n));} // This code is contributed by CrazyPro
// Java implementation of the approachimport java.util.Arrays; class GFG { // Return the maximum water that can be stored static int maxWater(int height[], int n) { // To store the maximum water so far int max = 0; // Both the pointers are pointing at the first // and the last buildings respectively int i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { max = Math.max(max, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { max = Math.max(max, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { max = Math.max(max, (j - i - 1) * height[i]); i++; j--; } } return max; } // Driver code public static void main(String[] args) { int height[] = { 2, 1, 3, 4, 6, 5 }; int n = height.length; System.out.print(maxWater(height, n)); }}
# Python3 implementation of the approach # Return the maximum water that can be storeddef maxWater(height, n): # To store the maximum water so far maximum = 0; # Both the pointers are pointing at the first # and the last buildings respectively i = 0 j = n - 1 # While the water can be stored between # the currently chosen buildings while (i < j): # Update maximum water so far and increment i if (height[i] < height[j]): maximum = max(maximum, (j - i - 1) * height[i]); i += 1; # Update maximum water so far and decrement j elif (height[j] < height[i]): maximum = max(maximum, (j - i - 1) * height[j]); j -= 1; # Any of the pointers can be updated (or both) else: maximum = max(maximum, (j - i - 1) * height[i]); i += 1; j -= 1; return maximum; # Driver codeheight = [2, 1, 3, 4, 6, 5] n = len(height) print (maxWater(height, n)); # This code is contributed by CrazyPro
// C# implementation of the approachusing System; class GFG{ // Return the maximum water that can be stored static int maxWater(int []height, int n) { // To store the maximum water so far int max = 0; // Both the pointers are pointing at the first // and the last buildings respectively int i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { max = Math.Max(max, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { max = Math.Max(max, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { max = Math.Max(max, (j - i - 1) * height[i]); i++; j--; } } return max; } // Driver code static public void Main () { int []height = { 2, 1, 3, 4, 6, 5 }; int n = height.Length; Console.Write(maxWater(height, n)); }} // This code is contributed by jit_t
<script> // Javascript implementation of the approach // Return the maximum water that can be storedfunction maxWater(height, n){ // To store the maximum water so far var maximum = 0; // Both the pointers are pointing at the first // and the last buildings respectively var i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { maximum = Math.max(maximum, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { maximum = Math.max(maximum, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { maximum = Math.max(maximum, (j - i - 1) * height[i]); i++; j--; } } return maximum;} // Driver codevar height = [ 2, 1, 3, 4, 6, 5 ];var n = height.length;document.write(maxWater(height, n)) </script>
8
Time Complexity: O(N)
jit_t
ankthon
ihritik
gp6
CrazyPro
manupathria
saisatwik2226
jana_sayantan
rutvik_56
simmytarika5
Constructive Algorithms
Arrays
Sorting
Arrays
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Program to find sum of elements in a given array
Building Heap from Array
Window Sliding Technique
1's and 2's complement of a Binary Number
Reversal algorithm for array rotation | [
{
"code": null,
"e": 24429,
"s": 24401,
"text": "\n11 Feb, 2022"
},
{
"code": null,
"e": 24779,
"s": 24429,
"text": "Given an integer array which represents the heights of N buildings, the task is to delete N-2 buildings such that the water that can be trapped between the remaining two building is maximum. Please note that the total water trapped between two buildings is gap between them (number of buildings removed) multiplied by height of the smaller building."
},
{
"code": null,
"e": 24790,
"s": 24779,
"text": "Examples: "
},
{
"code": null,
"e": 25119,
"s": 24790,
"text": "Input: arr[] = {1, 3, 4} Output: 1 We have to calculate the maximum water that can be stored between any 2 buildings. Water between the buildings of height 1 and height 3 = 0. Water between the buildings of height 1 and height 4 = 1. Water between the buildings of height 3 and height 4 = 0. Hence maximum of all the cases is 1."
},
{
"code": null,
"e": 25242,
"s": 25119,
"text": "Input: arr[] = {2, 1, 3, 4, 6, 5} Output: 8 We remove the middle 4 buildings and get the total water stored as 2 * 4 = 8 "
},
{
"code": null,
"e": 25424,
"s": 25242,
"text": "Naive approach: Check for all possible pairs and the pair which can hold maximum water will be the answer. Water stored between two buildings of height h1 and h2 would be equal to: "
},
{
"code": null,
"e": 25475,
"s": 25424,
"text": "minimum(h1, h2)*(distance between the buildings-1)"
},
{
"code": null,
"e": 25526,
"s": 25475,
"text": "Our task is to maximize this value for every pair."
},
{
"code": null,
"e": 25578,
"s": 25526,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 25582,
"s": 25578,
"text": "C++"
},
{
"code": null,
"e": 25587,
"s": 25582,
"text": "Java"
},
{
"code": null,
"e": 25595,
"s": 25587,
"text": "Python3"
},
{
"code": null,
"e": 25598,
"s": 25595,
"text": "C#"
},
{
"code": null,
"e": 25609,
"s": 25598,
"text": "Javascript"
},
{
"code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Return the maximum water that can be storedint maxWater(int height[], int n){ int maximum = 0; // Check all possible pairs of buildings for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int current = (min(height[i], height[j]) * (j - i - 1)); // Maximum so far maximum = max(maximum, current); } } return maximum;} // Driver codeint main(){ int height[] = { 2, 1, 3, 4, 6, 5 }; int n = sizeof(height) / sizeof(height[0]); cout << maxWater(height, n); return 0;} // This code is contributed by ihritik",
"e": 26351,
"s": 25609,
"text": null
},
{
"code": "// Java implementation of the above approachclass GFG { // Return the maximum water that can be stored static int maxWater(int height[], int n) { int max = 0; // Check all possible pairs of buildings for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int current = (Math.min(height[i], height[j]) * (j - i - 1)); // Maximum so far max = Math.max(max, current); } } return max; } // Driver code public static void main(String[] args) { int height[] = { 2, 1, 3, 4, 6, 5 }; int n = height.length; System.out.print(maxWater(height, n)); }}",
"e": 27125,
"s": 26351,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Return the maximum water# that can be storeddef maxWater(height, n) : maximum = 0; # Check all possible pairs of buildings for i in range(n - 1) : for j in range(i + 1, n) : current = min(height[i], height[j]) * (j - i - 1); # Maximum so far maximum = max(maximum, current); return maximum; # Driver codeif __name__ == \"__main__\" : height = [ 2, 1, 3, 4, 6, 5 ]; n = len(height); print(maxWater(height, n)); # This code is contributed by AnkitRai01",
"e": 27733,
"s": 27125,
"text": null
},
{
"code": "// C# implementation of the above approachusing System; class GFG { // Return the maximum water that can be stored static int maxWater(int[] height, int n) { int max = 0; // Check all possible pairs of buildings for (int i = 0; i < n - 1; i++) { for (int j = i + 1; j < n; j++) { int current = (Math.Min(height[i], height[j]) * (j - i - 1)); // Maximum so far max = Math.Max(max, current); } } return max; } // Driver code static public void Main() { int[] height = { 2, 1, 3, 4, 6, 5 }; int n = height.Length; Console.WriteLine(maxWater(height, n)); }} // This code is contributed by @tushil.",
"e": 28547,
"s": 27733,
"text": null
},
{
"code": "<script> // Javascript implementation of the above approach // Return the maximum water that can be storedfunction maxWater( height, n){ let maximum = 0; // Check all possible pairs of buildings for (let i = 0; i < n - 1; i++) { for (let j = i + 1; j < n; j++) { let current = (Math.min(height[i], height[j]) * (j - i - 1)); // Maximum so far maximum = Math.max(maximum, current); } } return maximum;} // Driver program let height = [ 2, 1, 3, 4, 6, 5 ]; let n = height.length; document.write(maxWater(height, n)); </script>",
"e": 29224,
"s": 28547,
"text": null
},
{
"code": null,
"e": 29226,
"s": 29224,
"text": "8"
},
{
"code": null,
"e": 29252,
"s": 29228,
"text": "Time Complexity: O(N*N)"
},
{
"code": null,
"e": 29273,
"s": 29252,
"text": "Efficient approach: "
},
{
"code": null,
"e": 29395,
"s": 29273,
"text": "Sort the array according to increasing height without affecting the original indices i.e. make pairs of (element, index)."
},
{
"code": null,
"e": 29701,
"s": 29395,
"text": "Then for every element, assume it is the building with the minimum height among the two buildings required then the height of the required water will be equal to the height of the chosen building and the width will be equal to the index difference between the chosen building and the building to be found."
},
{
"code": null,
"e": 29890,
"s": 29701,
"text": "In order to choose the other building which maximizes the water, the other building has to be as far as possible and must be greater in height as compared to the currently chosen building."
},
{
"code": null,
"e": 30016,
"s": 29890,
"text": "Now, the problem gets reduced to finding the minimum and maximum indices on the right for every building in the sorted array."
},
{
"code": null,
"e": 30069,
"s": 30016,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 30073,
"s": 30069,
"text": "C++"
},
{
"code": null,
"e": 30078,
"s": 30073,
"text": "Java"
},
{
"code": "// C++ implementation of the above approach#include<bits/stdc++.h>using namespace std; bool compareTo(pair<int, int> p1, pair<int, int> p2){ return p1.second < p2.second;} // Return the maximum water that// can be storedint maxWater(int height[], int n){ // Make pairs with indices pair<int, int> pairs[n]; for(int i = 0; i < n; i++) pairs[i] = make_pair(i, height[i]); // Sort array based on heights sort(pairs, pairs + n, compareTo); // To store the min and max index so far // from the right int minIndSoFar = pairs[n - 1].first; int maxIndSoFar = pairs[n - 1].first; int maxi = 0; for(int i = n - 2; i >= 0; i--) { // Current building paired with // the building greater in height // and on the extreme left int left = 0; if (minIndSoFar < pairs[i].first) { left = (pairs[i].second * (pairs[i].first - minIndSoFar - 1)); } // Current building paired with // the building greater in height // and on the extreme right int right = 0; if (maxIndSoFar > pairs[i].first) { right = (pairs[i].second * (maxIndSoFar - pairs[i].first - 1)); } // Maximum so far maxi = max(left, max(right, maxi)); // Update the maximum and minimum so far minIndSoFar = min(minIndSoFar, pairs[i].first); maxIndSoFar = max(maxIndSoFar, pairs[i].first); } return maxi;} // Driver codeint main( ){ int height[] = { 2, 1, 3, 4, 6, 5 }; int n = sizeof(height) / sizeof(height[0]); cout << maxWater(height, n);} // This code is contributed by manupathria",
"e": 31917,
"s": 30078,
"text": null
},
{
"code": "// Java implementation of the above approachimport java.util.Arrays; // Class to store the pairsclass Pair implements Comparable<Pair> { int ind, val; Pair(int ind, int val) { this.ind = ind; this.val = val; } @Override public int compareTo(Pair o) { if (this.val > o.val) return 1; return -1; }} class GFG { // Return the maximum water that can be stored static int maxWater(int height[], int n) { // Make pairs with indices Pair pairs[] = new Pair[n]; for (int i = 0; i < n; i++) pairs[i] = new Pair(i, height[i]); // Sort array based on heights Arrays.sort(pairs); // To store the min and max index so far // from the right int minIndSoFar = pairs[n - 1].ind; int maxIndSoFar = pairs[n - 1].ind; int max = 0; for (int i = n - 2; i >= 0; i--) { // Current building paired with the building // greater in height and on the extreme left int left = 0; if (minIndSoFar < pairs[i].ind) { left = (pairs[i].val * (pairs[i].ind - minIndSoFar - 1)); } // Current building paired with the building // greater in height and on the extreme right int right = 0; if (maxIndSoFar > pairs[i].ind) { right = (pairs[i].val * (maxIndSoFar - pairs[i].ind - 1)); } // Maximum so far max = Math.max(left, Math.max(right, max)); // Update the maximum and minimum so far minIndSoFar = Math.min(minIndSoFar, pairs[i].ind); maxIndSoFar = Math.max(maxIndSoFar, pairs[i].ind); } return max; } // Driver code public static void main(String[] args) { int height[] = { 2, 1, 3, 4, 6, 5 }; int n = height.length; System.out.print(maxWater(height, n)); }}",
"e": 33928,
"s": 31917,
"text": null
},
{
"code": null,
"e": 33930,
"s": 33928,
"text": "8"
},
{
"code": null,
"e": 33962,
"s": 33932,
"text": "Time Complexity : O(N*log(N))"
},
{
"code": null,
"e": 34465,
"s": 33962,
"text": "Two pointer approach: Take two pointers i and j pointing to the first and the last building respectively and calculate the water that can be stored between these two buildings. Now increment i if height[i] < height[j] else decrement j. This is because the water that can be trapped is dependent on the height of the small building and moving from the greater height building will just reduce the amount of water instead of maximizing it. In the end, print the maximum amount of water calculated so far."
},
{
"code": null,
"e": 34518,
"s": 34465,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 34522,
"s": 34518,
"text": "C++"
},
{
"code": null,
"e": 34527,
"s": 34522,
"text": "Java"
},
{
"code": null,
"e": 34535,
"s": 34527,
"text": "Python3"
},
{
"code": null,
"e": 34538,
"s": 34535,
"text": "C#"
},
{
"code": null,
"e": 34549,
"s": 34538,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>using namespace std; // Return the maximum water that can be storedint maxWater(int height[], int n){ // To store the maximum water so far int maximum = 0; // Both the pointers are pointing at the first // and the last buildings respectively int i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { maximum = max(maximum, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { maximum = max(maximum, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { maximum = max(maximum, (j - i - 1) * height[i]); i++; j--; } } return maximum;} // Driver codeint main(){ int height[] = { 2, 1, 3, 4, 6, 5 }; int n = sizeof(height)/sizeof(height[0]); cout<<(maxWater(height, n));} // This code is contributed by CrazyPro",
"e": 35757,
"s": 34549,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.Arrays; class GFG { // Return the maximum water that can be stored static int maxWater(int height[], int n) { // To store the maximum water so far int max = 0; // Both the pointers are pointing at the first // and the last buildings respectively int i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { max = Math.max(max, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { max = Math.max(max, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { max = Math.max(max, (j - i - 1) * height[i]); i++; j--; } } return max; } // Driver code public static void main(String[] args) { int height[] = { 2, 1, 3, 4, 6, 5 }; int n = height.length; System.out.print(maxWater(height, n)); }}",
"e": 37050,
"s": 35757,
"text": null
},
{
"code": "# Python3 implementation of the approach # Return the maximum water that can be storeddef maxWater(height, n): # To store the maximum water so far maximum = 0; # Both the pointers are pointing at the first # and the last buildings respectively i = 0 j = n - 1 # While the water can be stored between # the currently chosen buildings while (i < j): # Update maximum water so far and increment i if (height[i] < height[j]): maximum = max(maximum, (j - i - 1) * height[i]); i += 1; # Update maximum water so far and decrement j elif (height[j] < height[i]): maximum = max(maximum, (j - i - 1) * height[j]); j -= 1; # Any of the pointers can be updated (or both) else: maximum = max(maximum, (j - i - 1) * height[i]); i += 1; j -= 1; return maximum; # Driver codeheight = [2, 1, 3, 4, 6, 5] n = len(height) print (maxWater(height, n)); # This code is contributed by CrazyPro",
"e": 38113,
"s": 37050,
"text": null
},
{
"code": "// C# implementation of the approachusing System; class GFG{ // Return the maximum water that can be stored static int maxWater(int []height, int n) { // To store the maximum water so far int max = 0; // Both the pointers are pointing at the first // and the last buildings respectively int i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { max = Math.Max(max, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { max = Math.Max(max, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { max = Math.Max(max, (j - i - 1) * height[i]); i++; j--; } } return max; } // Driver code static public void Main () { int []height = { 2, 1, 3, 4, 6, 5 }; int n = height.Length; Console.Write(maxWater(height, n)); }} // This code is contributed by jit_t",
"e": 39467,
"s": 38113,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Return the maximum water that can be storedfunction maxWater(height, n){ // To store the maximum water so far var maximum = 0; // Both the pointers are pointing at the first // and the last buildings respectively var i = 0, j = n - 1; // While the water can be stored between // the currently chosen buildings while (i < j) { // Update maximum water so far and increment i if (height[i] < height[j]) { maximum = Math.max(maximum, (j - i - 1) * height[i]); i++; } // Update maximum water so far and decrement j else if (height[j] < height[i]) { maximum = Math.max(maximum, (j - i - 1) * height[j]); j--; } // Any of the pointers can be updated (or both) else { maximum = Math.max(maximum, (j - i - 1) * height[i]); i++; j--; } } return maximum;} // Driver codevar height = [ 2, 1, 3, 4, 6, 5 ];var n = height.length;document.write(maxWater(height, n)) </script>",
"e": 40589,
"s": 39467,
"text": null
},
{
"code": null,
"e": 40591,
"s": 40589,
"text": "8"
},
{
"code": null,
"e": 40615,
"s": 40593,
"text": "Time Complexity: O(N)"
},
{
"code": null,
"e": 40621,
"s": 40615,
"text": "jit_t"
},
{
"code": null,
"e": 40629,
"s": 40621,
"text": "ankthon"
},
{
"code": null,
"e": 40637,
"s": 40629,
"text": "ihritik"
},
{
"code": null,
"e": 40641,
"s": 40637,
"text": "gp6"
},
{
"code": null,
"e": 40650,
"s": 40641,
"text": "CrazyPro"
},
{
"code": null,
"e": 40662,
"s": 40650,
"text": "manupathria"
},
{
"code": null,
"e": 40676,
"s": 40662,
"text": "saisatwik2226"
},
{
"code": null,
"e": 40690,
"s": 40676,
"text": "jana_sayantan"
},
{
"code": null,
"e": 40700,
"s": 40690,
"text": "rutvik_56"
},
{
"code": null,
"e": 40713,
"s": 40700,
"text": "simmytarika5"
},
{
"code": null,
"e": 40737,
"s": 40713,
"text": "Constructive Algorithms"
},
{
"code": null,
"e": 40744,
"s": 40737,
"text": "Arrays"
},
{
"code": null,
"e": 40752,
"s": 40744,
"text": "Sorting"
},
{
"code": null,
"e": 40759,
"s": 40752,
"text": "Arrays"
},
{
"code": null,
"e": 40767,
"s": 40759,
"text": "Sorting"
},
{
"code": null,
"e": 40865,
"s": 40767,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40874,
"s": 40865,
"text": "Comments"
},
{
"code": null,
"e": 40887,
"s": 40874,
"text": "Old Comments"
},
{
"code": null,
"e": 40936,
"s": 40887,
"text": "Program to find sum of elements in a given array"
},
{
"code": null,
"e": 40961,
"s": 40936,
"text": "Building Heap from Array"
},
{
"code": null,
"e": 40986,
"s": 40961,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 41028,
"s": 40986,
"text": "1's and 2's complement of a Binary Number"
}
] |
What is strncpy() Function in C language? | The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where, the length of src is less than that of n, the remainder of dest will be padded with null bytes.
An array of characters is called a string.
Following is the declaration for an array −
char stringname [size];
For example − char string[50]; string of length 50 characters
Using single character constant −
char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\0’}
Using string constants −
char string[10] = "Hello":;
Accessing − There is a control string "%s" used for accessing the string till it encounters ‘\0’.
This function is used for copying ‘n’ characters of source string into destination string.
This function is used for copying ‘n’ characters of source string into destination string.
The length of the destination string is greater than or equal to the source string.
The length of the destination string is greater than or equal to the source string.
The syntax is as follows −
strncpy (Destination string, Source String, n);
Following is the C program for strncpy() function −
#include<string.h>
main ( ){
char a[50], b[50];
printf ("enter a string");
gets (a);
strncpy (b,a,3);
b[3] = '\0';
printf ("copied string = %s",b);
getch ( );
}
When the above program is executed, it produces the following result −
Enter a string : Hello
Copied string = Hel
It is also used for extracting substrings.
The following example shows the usage of strncpy() function.
char result[10], s1[15] = "Jan 10 2010";
strncpy (result, &s1[4], 2);
result[2] = ‘\0’
When the above program is executed, it produces the following result −
Result = 10
Let’s see another example on strncpy.
Given below is a C program to copy n number of characters from source string to destination string using strncpy library function −
#include<stdio.h>
#include<string.h>
void main(){
//Declaring source and destination strings//
char source[45],destination[50];
char destination1[10],destination2[10],destination3[10],destination4[10];
//Reading source string and destination string from user//
printf("Enter the source string :");
gets(source);
//Extracting the new destination string using strncpy//
strncpy(destination1,source,2);
printf("The first destination value is : ");
destination1[2]='\0';//Garbage value is being printed in the o/p because always assign null value before printing O/p//
puts(destination1);
strncpy(destination2,&source[8],1);
printf("The second destination value is : ");
destination2[1]='\0';
puts(destination2);
strncpy(destination3,&source[12],1);
printf("The third destination value is : ");
destination3[1]='\0';
puts(destination3);
//Concatenate all the above results//
strcat(destination1,destination2);
strcat(destination1,destination3);
printf("The modified destination string :");
printf("%s3",destination1);//Is there a logical way to concatenate numbers to the destination string?//
}
When the above program is executed, it produces the following result −
Enter the source string :Tutorials Point
The first destination value is : Tu
The second destination value is : s
The third destination value is : i
The modified destination string :Tusi3 | [
{
"code": null,
"e": 1321,
"s": 1062,
"text": "The C library function char *strncpy(char *dest, const char *src, size_t n) copies up to n characters from the string pointed to, by src to dest. In a case where, the length of src is less than that of n, the remainder of dest will be padded with null bytes."
},
{
"code": null,
"e": 1364,
"s": 1321,
"text": "An array of characters is called a string."
},
{
"code": null,
"e": 1408,
"s": 1364,
"text": "Following is the declaration for an array −"
},
{
"code": null,
"e": 1432,
"s": 1408,
"text": "char stringname [size];"
},
{
"code": null,
"e": 1494,
"s": 1432,
"text": "For example − char string[50]; string of length 50 characters"
},
{
"code": null,
"e": 1528,
"s": 1494,
"text": "Using single character constant −"
},
{
"code": null,
"e": 1579,
"s": 1528,
"text": "char string[10] = { ‘H’, ‘e’, ‘l’, ‘l’, ‘o’ ,‘\\0’}"
},
{
"code": null,
"e": 1604,
"s": 1579,
"text": "Using string constants −"
},
{
"code": null,
"e": 1632,
"s": 1604,
"text": "char string[10] = \"Hello\":;"
},
{
"code": null,
"e": 1730,
"s": 1632,
"text": "Accessing − There is a control string \"%s\" used for accessing the string till it encounters ‘\\0’."
},
{
"code": null,
"e": 1821,
"s": 1730,
"text": "This function is used for copying ‘n’ characters of source string into destination string."
},
{
"code": null,
"e": 1912,
"s": 1821,
"text": "This function is used for copying ‘n’ characters of source string into destination string."
},
{
"code": null,
"e": 1996,
"s": 1912,
"text": "The length of the destination string is greater than or equal to the source string."
},
{
"code": null,
"e": 2080,
"s": 1996,
"text": "The length of the destination string is greater than or equal to the source string."
},
{
"code": null,
"e": 2107,
"s": 2080,
"text": "The syntax is as follows −"
},
{
"code": null,
"e": 2155,
"s": 2107,
"text": "strncpy (Destination string, Source String, n);"
},
{
"code": null,
"e": 2207,
"s": 2155,
"text": "Following is the C program for strncpy() function −"
},
{
"code": null,
"e": 2389,
"s": 2207,
"text": "#include<string.h>\nmain ( ){\n char a[50], b[50];\n printf (\"enter a string\");\n gets (a);\n strncpy (b,a,3);\n b[3] = '\\0';\n printf (\"copied string = %s\",b);\n getch ( );\n}"
},
{
"code": null,
"e": 2460,
"s": 2389,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2503,
"s": 2460,
"text": "Enter a string : Hello\nCopied string = Hel"
},
{
"code": null,
"e": 2546,
"s": 2503,
"text": "It is also used for extracting substrings."
},
{
"code": null,
"e": 2607,
"s": 2546,
"text": "The following example shows the usage of strncpy() function."
},
{
"code": null,
"e": 2694,
"s": 2607,
"text": "char result[10], s1[15] = \"Jan 10 2010\";\nstrncpy (result, &s1[4], 2);\nresult[2] = ‘\\0’"
},
{
"code": null,
"e": 2765,
"s": 2694,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 2777,
"s": 2765,
"text": "Result = 10"
},
{
"code": null,
"e": 2815,
"s": 2777,
"text": "Let’s see another example on strncpy."
},
{
"code": null,
"e": 2947,
"s": 2815,
"text": "Given below is a C program to copy n number of characters from source string to destination string using strncpy library function −"
},
{
"code": null,
"e": 4111,
"s": 2947,
"text": "#include<stdio.h>\n#include<string.h>\nvoid main(){\n //Declaring source and destination strings//\n char source[45],destination[50];\n char destination1[10],destination2[10],destination3[10],destination4[10];\n //Reading source string and destination string from user//\n printf(\"Enter the source string :\");\n gets(source);\n //Extracting the new destination string using strncpy//\n strncpy(destination1,source,2);\n printf(\"The first destination value is : \");\n destination1[2]='\\0';//Garbage value is being printed in the o/p because always assign null value before printing O/p//\n puts(destination1);\n strncpy(destination2,&source[8],1);\n printf(\"The second destination value is : \");\n destination2[1]='\\0';\n puts(destination2);\n strncpy(destination3,&source[12],1);\n printf(\"The third destination value is : \");\n destination3[1]='\\0';\n puts(destination3);\n //Concatenate all the above results//\n strcat(destination1,destination2);\n strcat(destination1,destination3);\n printf(\"The modified destination string :\");\n printf(\"%s3\",destination1);//Is there a logical way to concatenate numbers to the destination string?//\n}"
},
{
"code": null,
"e": 4182,
"s": 4111,
"text": "When the above program is executed, it produces the following result −"
},
{
"code": null,
"e": 4369,
"s": 4182,
"text": "Enter the source string :Tutorials Point\nThe first destination value is : Tu\nThe second destination value is : s\nThe third destination value is : i\nThe modified destination string :Tusi3"
}
] |
C - Array of pointers | Before we understand the concept of arrays of pointers, let us consider the following example, which uses an array of 3 integers −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i;
for (i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, var[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −
int *ptr[MAX];
It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int value. The following example uses three integers, which are stored in an array of pointers, as follows −
#include <stdio.h>
const int MAX = 3;
int main () {
int var[] = {10, 100, 200};
int i, *ptr[MAX];
for ( i = 0; i < MAX; i++) {
ptr[i] = &var[i]; /* assign the address of integer. */
}
for ( i = 0; i < MAX; i++) {
printf("Value of var[%d] = %d\n", i, *ptr[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of var[0] = 10
Value of var[1] = 100
Value of var[2] = 200
You can also use an array of pointers to character to store a list of strings as follows −
#include <stdio.h>
const int MAX = 4;
int main () {
char *names[] = {
"Zara Ali",
"Hina Ali",
"Nuha Ali",
"Sara Ali"
};
int i = 0;
for ( i = 0; i < MAX; i++) {
printf("Value of names[%d] = %s\n", i, names[i] );
}
return 0;
}
When the above code is compiled and executed, it produces the following result −
Value of names[0] = Zara Ali
Value of names[1] = Hina Ali
Value of names[2] = Nuha Ali
Value of names[3] = Sara Ali
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2215,
"s": 2084,
"text": "Before we understand the concept of arrays of pointers, let us consider the following example, which uses an array of 3 integers −"
},
{
"code": null,
"e": 2424,
"s": 2215,
"text": "#include <stdio.h>\n \nconst int MAX = 3;\n \nint main () {\n\n int var[] = {10, 100, 200};\n int i;\n \n for (i = 0; i < MAX; i++) {\n printf(\"Value of var[%d] = %d\\n\", i, var[i] );\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 2505,
"s": 2424,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 2571,
"s": 2505,
"text": "Value of var[0] = 10\nValue of var[1] = 100\nValue of var[2] = 200\n"
},
{
"code": null,
"e": 2777,
"s": 2571,
"text": "There may be a situation when we want to maintain an array, which can store pointers to an int or char or any other data type available. Following is the declaration of an array of pointers to an integer −"
},
{
"code": null,
"e": 2793,
"s": 2777,
"text": "int *ptr[MAX];\n"
},
{
"code": null,
"e": 3004,
"s": 2793,
"text": "It declares ptr as an array of MAX integer pointers. Thus, each element in ptr, holds a pointer to an int value. The following example uses three integers, which are stored in an array of pointers, as follows −"
},
{
"code": null,
"e": 3328,
"s": 3004,
"text": "#include <stdio.h>\n \nconst int MAX = 3;\n \nint main () {\n\n int var[] = {10, 100, 200};\n int i, *ptr[MAX];\n \n for ( i = 0; i < MAX; i++) {\n ptr[i] = &var[i]; /* assign the address of integer. */\n }\n \n for ( i = 0; i < MAX; i++) {\n printf(\"Value of var[%d] = %d\\n\", i, *ptr[i] );\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3409,
"s": 3328,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3475,
"s": 3409,
"text": "Value of var[0] = 10\nValue of var[1] = 100\nValue of var[2] = 200\n"
},
{
"code": null,
"e": 3566,
"s": 3475,
"text": "You can also use an array of pointers to character to store a list of strings as follows −"
},
{
"code": null,
"e": 3853,
"s": 3566,
"text": "#include <stdio.h>\n \nconst int MAX = 4;\n \nint main () {\n\n char *names[] = {\n \"Zara Ali\",\n \"Hina Ali\",\n \"Nuha Ali\",\n \"Sara Ali\"\n };\n \n int i = 0;\n\n for ( i = 0; i < MAX; i++) {\n printf(\"Value of names[%d] = %s\\n\", i, names[i] );\n }\n \n return 0;\n}"
},
{
"code": null,
"e": 3934,
"s": 3853,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 4051,
"s": 3934,
"text": "Value of names[0] = Zara Ali\nValue of names[1] = Hina Ali\nValue of names[2] = Nuha Ali\nValue of names[3] = Sara Ali\n"
},
{
"code": null,
"e": 4058,
"s": 4051,
"text": " Print"
},
{
"code": null,
"e": 4069,
"s": 4058,
"text": " Add Notes"
}
] |
Preprocessing BIG Data In Julia With Lathe | by Emmett Boudreau | Towards Data Science | When it comes to the wonderful and vast world of machine-learning, there are many popular options that many Data Scientists choose to work worth. Truthfully, in my personal outlook on the Data Science ecosystem right now, I think that many aspects of the field are outdated while others are charging forward at the speed of light. In a way this makes sense, because an exploding industry like this has not had the time to properly mature to its size, and thus we ultimately face some issues.
One significant issue that Data Science is facing is that of programming languages. To many entry-level developers, Data Science can be rather hard to enter as a result. Because there are so many options, and avid, sometimes blatantly religious, followers of certain languages who will likely construe certain opinions on why X or Y is better than the other. If you happen to be in that boat, I actually have an article that could answer this question, because the language you choose will very likely make a significant impact on the type of work you ultimately end up doing. You can check that article out here if you desire:
towardsdatascience.com
I digress... Ultimately I think that while it is very unclear and cannot be known what language will become the new Data Science poster-child, if the language even changes, I think that the problems with languages are often brought to light with Data Science work. Let us all recall that back in 2015, most Data Science job listings were for Java. That being said, Python has only been dominating the field for about 7 years now, meaning that the language has only recently started to target this audience. Many will debate that Python is the perfect language for Data Science, but truthfully there cannot be a perfect language for anything as there is always some sort of flaw.
source
While Python has the ultimate Data Science ecosystem, it is also an interpreted language, and is more akin to something like JavaScript than something like Scala or C++. This of course slows things down, and while most packages are written in C, and can actually run very quickly thanks to optimization and good code, they still are not without their problems. The problem with Python is that if you want to work with more complex, multi-dimensional, big-data, then you are simply going to run into a lot of unexpected problems. Needless to say, trying to squeeze every last drop of performance out of your computer because of the programming language you use is not a perfect experience.
Python also has an after-thought of parallel computing, meaning it was not necessarily designed with parallel computing in mind. Parallel computing is becoming more and more important and more and more widely-used every single day. The fact that Python can sometimes have trouble with it is certainly a hindrance to the language, especially when compounded with everything else.
Of course, Julia is not perfect either, as Julia has many flaws as well. While I think that its paradigm is incredibly great to write in and there is nowhere else that I would rather write my code, I also can see some issues with the language. Of course, the language is still relatively new, so this is definitely sensible. And the fact that it only recently climbed in popularity means that the ecosystem is still very immature. With an immature ecosystem, it is doubtful that much Julia will be adopted by the industry, primarily because they do not want to pay people to write packages that are already written in another language.
All of this out of the way, I really think that there is no perfect language at this time. I think Python is great, and I think Julia is great, but I think they both have flaws that detract from their greatness. That being said, I also think that Julia shows a lot of promise for the future, even if that future is being a side-kick to Python. Today I wanted to demonstrate the potential of this language, with a matured eco-system, and some more work on the core itself, I really think that Julia could do a lot of very exciting things in the Data Science domain, which of course makes me excited.
Notebook
Lathe is a machine-learning package for Julia that has been in broadly active development since 2019. One problem with Julia is that there is a big gap inside of the ecosystem for general-purpose machine-learning. Many of the packages target linear modeling, data processing, statistics, or deep-learning individually without consistent direction or types. This is problematic because we have all of these independently created tools that depend on each-other, yet somehow do not work together — which is just silly as Julia was made to easily be extendable using sub-typing. If you would like to learn more about this package, you may visit
lathe.ai
or the Github page,
github.com
I remember when I originally started in Julia in 2018, and for the life of me could not find a good way to train-test-split my data. I ended up having to write a function to do it, and I would use that same function each time I needed to train-test-split something. Lathe aims to set up some level of consistency, although it is object-oriented, the tools are made to be extended. If we think of Python, SkLearn set a standard for predicting with models that has been followed by other packages since.
Today I wanted to work with some huge data-sets, and truly put Lathe through its paces in order to both demonstrate how to actually use the module to some extent, and also demonstrate how capable the module actually is. To get started, let us generate an absolute TON of random data. I would like to do both a categorical and a continuous option with both encoders and scalers put into a pipeline. First lets import our dependencies:
using DataFramesusing Lathe.preprocess: TrainTestSplitusing Lathe.preprocess: StandardScaler, OrdinalEncoder, OneHotEncoderusing Lathe.models: LinearRegression, RandomForestClassifier, Router
For the continuous data, I pretty much just used randn() to generate some random numbers. As for number of observations, I chose 5,000,000. Millions of observations are essentially impossible to work with in most of the industry standard tools, even from a 1-dimensional perspective. I do not imagine Python would even create this array, though I could be wrong. I generated this data using the randn() function:
x = randn(5000000)y = randn(5000000)
Now categorical data is a bit more tricky, as Julia really does not have a random choice function like Python. You can draw samples iteratively, that is about it. I wrote this neat little function, making use of Lathe’s ordinal encoder object in order to create a lookup dictionary, reverse it, and then index it with integers in a given range:
function randchoice(opts::Array{String}, count = 5)mapping = OrdinalEncoder(opts).lookupinverse_dct = Dict([pair[2] => pair[1] for pair in Set(mapping)])[inverse_dct[Int64(rand(1:length(opts)))] for i in 1:count]end
Next I created some categorical options in the form of strings. I created 3,000,000 of these, because I thought I would challenge the model and put the CUDA implementation of this model to the test at the same time.
opts = ["A", "B", "C"]caty = randchoice(opts, 3000000)catx = randchoice(opts, 3000000)
Finally, let us condense our data into two dataframes:
df = DataFrame(:X => x, :Y => y)catdf = DataFrame(:CATX => catx, :caty => caty)
And we will be splitting each dataframe, I timed these using the time macro, and from here on out everything Lathe will have some time screenshots below it!
@time train, test = TrainTestSplit(df)
Then I made a trainX and trainy array:
tr = :Xte = :YtrainX = Array(train[!, tr])trainy = Array(train[!, te])testX = Array(test[!, tr])testy = Array(test[!, te])
Next, let’s create a standard scaler to scale our incoming X:
@time scaler = StandardScaler(trainX)
Then we will use its predict() function in order to get some data to train with:
@time scaled_tX = scaler.predict(trainX)
Finally, let us fit this to a basic linear regression model:
@time model = LinearRegression(scaled_tX, trainy)
Now I will make a pipeline with our scaler and model using the addition operator:
pipe = scaler + model@time yhat = pipe.predict(testX)
For our categorical model, I did the same exact splitting process as before:
@time train, test = TrainTestSplit(catdf)
Then got that data into 1-dimensional arrays:
tr = :CATXte = :catyctrainX = Array(train[!, tr])ctrainy = Array(train[!, te])ctestX = Array(test[!, tr])ctesty = Array(test[!, te])
After that, I fit an ordinal incoder:
@time encoder = OrdinalEncoder(ctrainX)
And once again used the predict() function to predict:
@time tx_enc = encoder.predict(ctrainX)
Finally, I finished off by fitting a Random Forest Classifier:
@time model = RandomForestClassifier(tx_enc, ctrainy, # cuda = true # < uncomment for cuda!)
Next, let us use the addition operator again to create another pipe for categorical input:
catpipe = encoder + model@time catpipe.predict(ctesty)
I think it is clear that Lathe is powerful and speedy for preprocessing data for most machine-learning scenarios. I think that being able to go through this big data so easily with these preprocessing tools definitely gives Lathe a significant amount of promise to stay in the industry, along with Julia. This could be the case, even if the systems were used only to feed Python-written machine-learning models. Of all of these tests, the only one that ever went over 10 seconds in compilation time was the random forest classifier, which I think still has a pretty radical time for dealing with this much data.
I tried to compare these times with CUDA times, but it would appear as though my CUDA is not working, which ruins the fun! If you happen to have a graphics card and CUDA, you can feel free to try it out in the notebook and let me know how it goes, that would mean the world to me! Thank you for reading, and I hope this article went to show just how powerful the Julia language can potentially be with the right steam behind it! | [
{
"code": null,
"e": 664,
"s": 172,
"text": "When it comes to the wonderful and vast world of machine-learning, there are many popular options that many Data Scientists choose to work worth. Truthfully, in my personal outlook on the Data Science ecosystem right now, I think that many aspects of the field are outdated while others are charging forward at the speed of light. In a way this makes sense, because an exploding industry like this has not had the time to properly mature to its size, and thus we ultimately face some issues."
},
{
"code": null,
"e": 1292,
"s": 664,
"text": "One significant issue that Data Science is facing is that of programming languages. To many entry-level developers, Data Science can be rather hard to enter as a result. Because there are so many options, and avid, sometimes blatantly religious, followers of certain languages who will likely construe certain opinions on why X or Y is better than the other. If you happen to be in that boat, I actually have an article that could answer this question, because the language you choose will very likely make a significant impact on the type of work you ultimately end up doing. You can check that article out here if you desire:"
},
{
"code": null,
"e": 1315,
"s": 1292,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 1994,
"s": 1315,
"text": "I digress... Ultimately I think that while it is very unclear and cannot be known what language will become the new Data Science poster-child, if the language even changes, I think that the problems with languages are often brought to light with Data Science work. Let us all recall that back in 2015, most Data Science job listings were for Java. That being said, Python has only been dominating the field for about 7 years now, meaning that the language has only recently started to target this audience. Many will debate that Python is the perfect language for Data Science, but truthfully there cannot be a perfect language for anything as there is always some sort of flaw."
},
{
"code": null,
"e": 2001,
"s": 1994,
"text": "source"
},
{
"code": null,
"e": 2690,
"s": 2001,
"text": "While Python has the ultimate Data Science ecosystem, it is also an interpreted language, and is more akin to something like JavaScript than something like Scala or C++. This of course slows things down, and while most packages are written in C, and can actually run very quickly thanks to optimization and good code, they still are not without their problems. The problem with Python is that if you want to work with more complex, multi-dimensional, big-data, then you are simply going to run into a lot of unexpected problems. Needless to say, trying to squeeze every last drop of performance out of your computer because of the programming language you use is not a perfect experience."
},
{
"code": null,
"e": 3069,
"s": 2690,
"text": "Python also has an after-thought of parallel computing, meaning it was not necessarily designed with parallel computing in mind. Parallel computing is becoming more and more important and more and more widely-used every single day. The fact that Python can sometimes have trouble with it is certainly a hindrance to the language, especially when compounded with everything else."
},
{
"code": null,
"e": 3705,
"s": 3069,
"text": "Of course, Julia is not perfect either, as Julia has many flaws as well. While I think that its paradigm is incredibly great to write in and there is nowhere else that I would rather write my code, I also can see some issues with the language. Of course, the language is still relatively new, so this is definitely sensible. And the fact that it only recently climbed in popularity means that the ecosystem is still very immature. With an immature ecosystem, it is doubtful that much Julia will be adopted by the industry, primarily because they do not want to pay people to write packages that are already written in another language."
},
{
"code": null,
"e": 4304,
"s": 3705,
"text": "All of this out of the way, I really think that there is no perfect language at this time. I think Python is great, and I think Julia is great, but I think they both have flaws that detract from their greatness. That being said, I also think that Julia shows a lot of promise for the future, even if that future is being a side-kick to Python. Today I wanted to demonstrate the potential of this language, with a matured eco-system, and some more work on the core itself, I really think that Julia could do a lot of very exciting things in the Data Science domain, which of course makes me excited."
},
{
"code": null,
"e": 4313,
"s": 4304,
"text": "Notebook"
},
{
"code": null,
"e": 4955,
"s": 4313,
"text": "Lathe is a machine-learning package for Julia that has been in broadly active development since 2019. One problem with Julia is that there is a big gap inside of the ecosystem for general-purpose machine-learning. Many of the packages target linear modeling, data processing, statistics, or deep-learning individually without consistent direction or types. This is problematic because we have all of these independently created tools that depend on each-other, yet somehow do not work together — which is just silly as Julia was made to easily be extendable using sub-typing. If you would like to learn more about this package, you may visit"
},
{
"code": null,
"e": 4964,
"s": 4955,
"text": "lathe.ai"
},
{
"code": null,
"e": 4984,
"s": 4964,
"text": "or the Github page,"
},
{
"code": null,
"e": 4995,
"s": 4984,
"text": "github.com"
},
{
"code": null,
"e": 5497,
"s": 4995,
"text": "I remember when I originally started in Julia in 2018, and for the life of me could not find a good way to train-test-split my data. I ended up having to write a function to do it, and I would use that same function each time I needed to train-test-split something. Lathe aims to set up some level of consistency, although it is object-oriented, the tools are made to be extended. If we think of Python, SkLearn set a standard for predicting with models that has been followed by other packages since."
},
{
"code": null,
"e": 5931,
"s": 5497,
"text": "Today I wanted to work with some huge data-sets, and truly put Lathe through its paces in order to both demonstrate how to actually use the module to some extent, and also demonstrate how capable the module actually is. To get started, let us generate an absolute TON of random data. I would like to do both a categorical and a continuous option with both encoders and scalers put into a pipeline. First lets import our dependencies:"
},
{
"code": null,
"e": 6123,
"s": 5931,
"text": "using DataFramesusing Lathe.preprocess: TrainTestSplitusing Lathe.preprocess: StandardScaler, OrdinalEncoder, OneHotEncoderusing Lathe.models: LinearRegression, RandomForestClassifier, Router"
},
{
"code": null,
"e": 6536,
"s": 6123,
"text": "For the continuous data, I pretty much just used randn() to generate some random numbers. As for number of observations, I chose 5,000,000. Millions of observations are essentially impossible to work with in most of the industry standard tools, even from a 1-dimensional perspective. I do not imagine Python would even create this array, though I could be wrong. I generated this data using the randn() function:"
},
{
"code": null,
"e": 6573,
"s": 6536,
"text": "x = randn(5000000)y = randn(5000000)"
},
{
"code": null,
"e": 6918,
"s": 6573,
"text": "Now categorical data is a bit more tricky, as Julia really does not have a random choice function like Python. You can draw samples iteratively, that is about it. I wrote this neat little function, making use of Lathe’s ordinal encoder object in order to create a lookup dictionary, reverse it, and then index it with integers in a given range:"
},
{
"code": null,
"e": 7134,
"s": 6918,
"text": "function randchoice(opts::Array{String}, count = 5)mapping = OrdinalEncoder(opts).lookupinverse_dct = Dict([pair[2] => pair[1] for pair in Set(mapping)])[inverse_dct[Int64(rand(1:length(opts)))] for i in 1:count]end"
},
{
"code": null,
"e": 7350,
"s": 7134,
"text": "Next I created some categorical options in the form of strings. I created 3,000,000 of these, because I thought I would challenge the model and put the CUDA implementation of this model to the test at the same time."
},
{
"code": null,
"e": 7437,
"s": 7350,
"text": "opts = [\"A\", \"B\", \"C\"]caty = randchoice(opts, 3000000)catx = randchoice(opts, 3000000)"
},
{
"code": null,
"e": 7492,
"s": 7437,
"text": "Finally, let us condense our data into two dataframes:"
},
{
"code": null,
"e": 7572,
"s": 7492,
"text": "df = DataFrame(:X => x, :Y => y)catdf = DataFrame(:CATX => catx, :caty => caty)"
},
{
"code": null,
"e": 7729,
"s": 7572,
"text": "And we will be splitting each dataframe, I timed these using the time macro, and from here on out everything Lathe will have some time screenshots below it!"
},
{
"code": null,
"e": 7768,
"s": 7729,
"text": "@time train, test = TrainTestSplit(df)"
},
{
"code": null,
"e": 7807,
"s": 7768,
"text": "Then I made a trainX and trainy array:"
},
{
"code": null,
"e": 7930,
"s": 7807,
"text": "tr = :Xte = :YtrainX = Array(train[!, tr])trainy = Array(train[!, te])testX = Array(test[!, tr])testy = Array(test[!, te])"
},
{
"code": null,
"e": 7992,
"s": 7930,
"text": "Next, let’s create a standard scaler to scale our incoming X:"
},
{
"code": null,
"e": 8030,
"s": 7992,
"text": "@time scaler = StandardScaler(trainX)"
},
{
"code": null,
"e": 8111,
"s": 8030,
"text": "Then we will use its predict() function in order to get some data to train with:"
},
{
"code": null,
"e": 8152,
"s": 8111,
"text": "@time scaled_tX = scaler.predict(trainX)"
},
{
"code": null,
"e": 8213,
"s": 8152,
"text": "Finally, let us fit this to a basic linear regression model:"
},
{
"code": null,
"e": 8263,
"s": 8213,
"text": "@time model = LinearRegression(scaled_tX, trainy)"
},
{
"code": null,
"e": 8345,
"s": 8263,
"text": "Now I will make a pipeline with our scaler and model using the addition operator:"
},
{
"code": null,
"e": 8399,
"s": 8345,
"text": "pipe = scaler + model@time yhat = pipe.predict(testX)"
},
{
"code": null,
"e": 8476,
"s": 8399,
"text": "For our categorical model, I did the same exact splitting process as before:"
},
{
"code": null,
"e": 8518,
"s": 8476,
"text": "@time train, test = TrainTestSplit(catdf)"
},
{
"code": null,
"e": 8564,
"s": 8518,
"text": "Then got that data into 1-dimensional arrays:"
},
{
"code": null,
"e": 8697,
"s": 8564,
"text": "tr = :CATXte = :catyctrainX = Array(train[!, tr])ctrainy = Array(train[!, te])ctestX = Array(test[!, tr])ctesty = Array(test[!, te])"
},
{
"code": null,
"e": 8735,
"s": 8697,
"text": "After that, I fit an ordinal incoder:"
},
{
"code": null,
"e": 8775,
"s": 8735,
"text": "@time encoder = OrdinalEncoder(ctrainX)"
},
{
"code": null,
"e": 8830,
"s": 8775,
"text": "And once again used the predict() function to predict:"
},
{
"code": null,
"e": 8870,
"s": 8830,
"text": "@time tx_enc = encoder.predict(ctrainX)"
},
{
"code": null,
"e": 8933,
"s": 8870,
"text": "Finally, I finished off by fitting a Random Forest Classifier:"
},
{
"code": null,
"e": 9026,
"s": 8933,
"text": "@time model = RandomForestClassifier(tx_enc, ctrainy, # cuda = true # < uncomment for cuda!)"
},
{
"code": null,
"e": 9117,
"s": 9026,
"text": "Next, let us use the addition operator again to create another pipe for categorical input:"
},
{
"code": null,
"e": 9172,
"s": 9117,
"text": "catpipe = encoder + model@time catpipe.predict(ctesty)"
},
{
"code": null,
"e": 9784,
"s": 9172,
"text": "I think it is clear that Lathe is powerful and speedy for preprocessing data for most machine-learning scenarios. I think that being able to go through this big data so easily with these preprocessing tools definitely gives Lathe a significant amount of promise to stay in the industry, along with Julia. This could be the case, even if the systems were used only to feed Python-written machine-learning models. Of all of these tests, the only one that ever went over 10 seconds in compilation time was the random forest classifier, which I think still has a pretty radical time for dealing with this much data."
}
] |
Next.js - CLI | NEXT.JS provides a CLI to start, build and export application. It can be invoked using npx which comes npm 5.2 onwards.
To get list of CLI commands and help on them, type the following command.
npx next -h
Usage
$ next <command>
Available commands
build, start, export, dev, telemetry
Options
--version, -v Version number
--help, -h Displays this message
For more information run a command with the --help flag
$ next build --help
Type the following command.
npx next build
info - Loaded env from D:\Node\nextjs\.env.local
Creating an optimized production build
Compiled successfully.
Automatically optimizing pages
Page Size First Load JS
+ ? / 2.25 kB 60.3 kB
+ /_app 288 B 58.1 kB
+ /404 3.25 kB 61.3 kB
+ ? /api/user
+ ? /posts/[id] 312 B 61.6 kB
+ + /posts/one
+ + /posts/two
+ ? /posts/env 2.71 kB 60.8 kB
+ ? /posts/first 374 B 61.7 kB
+ First Load JS shared by all 58.1 kB
+ static/pages/_app.js 288 B
+ chunks/ab55cb957ceed242a750c37a082143fb9d2f0cdf.a1a019.js 10.5 kB
+ chunks/framework.c6faae.js 40 kB
+ runtime/main.60464f.js 6.54 kB
+ runtime/webpack.c21266.js 746 B
+ css/9706b5b8ed8e82c0fba0.css 175 B
? (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps)
(Static) automatically rendered as static HTML (uses no initial props)
? (SSG) automatically generated as static HTML + JSON (uses getStaticProps)
Type the following command.
npx next dev
ready - started server on http://localhost:3000
info - Loaded env from D:\Node\nextjs\.env.local
event - compiled successfully
Type the following command.
npx next start
info - Loaded env from \Node\nextjs\.env.local
ready - started server on http://localhost:3000
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2227,
"s": 2107,
"text": "NEXT.JS provides a CLI to start, build and export application. It can be invoked using npx which comes npm 5.2 onwards."
},
{
"code": null,
"e": 2301,
"s": 2227,
"text": "To get list of CLI commands and help on them, type the following command."
},
{
"code": null,
"e": 2590,
"s": 2301,
"text": "npx next -h\n Usage\n $ next <command>\n\n Available commands\n build, start, export, dev, telemetry\n\n Options\n --version, -v Version number\n --help, -h Displays this message\n\n For more information run a command with the --help flag\n $ next build --help"
},
{
"code": null,
"e": 2618,
"s": 2590,
"text": "Type the following command."
},
{
"code": null,
"e": 4171,
"s": 2618,
"text": "npx next build\ninfo - Loaded env from D:\\Node\\nextjs\\.env.local\nCreating an optimized production build\n\nCompiled successfully.\n\nAutomatically optimizing pages\n\nPage Size First Load JS\n+ ? / 2.25 kB 60.3 kB\n+ /_app 288 B 58.1 kB\n+ /404 3.25 kB 61.3 kB\n+ ? /api/user\n+ ? /posts/[id] 312 B 61.6 kB\n+ + /posts/one\n+ + /posts/two\n+ ? /posts/env 2.71 kB 60.8 kB\n+ ? /posts/first 374 B 61.7 kB\n+ First Load JS shared by all 58.1 kB\n + static/pages/_app.js 288 B\n + chunks/ab55cb957ceed242a750c37a082143fb9d2f0cdf.a1a019.js 10.5 kB\n + chunks/framework.c6faae.js 40 kB\n + runtime/main.60464f.js 6.54 kB\n + runtime/webpack.c21266.js 746 B\n + css/9706b5b8ed8e82c0fba0.css 175 B\n\n? (Server) server-side renders at runtime (uses getInitialProps or getServerSideProps)\n (Static) automatically rendered as static HTML (uses no initial props)\n? (SSG) automatically generated as static HTML + JSON (uses getStaticProps)"
},
{
"code": null,
"e": 4199,
"s": 4171,
"text": "Type the following command."
},
{
"code": null,
"e": 4342,
"s": 4199,
"text": "npx next dev\n\nready - started server on http://localhost:3000\ninfo - Loaded env from D:\\Node\\nextjs\\.env.local\nevent - compiled successfully\n"
},
{
"code": null,
"e": 4370,
"s": 4342,
"text": "Type the following command."
},
{
"code": null,
"e": 4483,
"s": 4370,
"text": "npx next start\n\ninfo - Loaded env from \\Node\\nextjs\\.env.local\nready - started server on http://localhost:3000\n"
},
{
"code": null,
"e": 4490,
"s": 4483,
"text": " Print"
},
{
"code": null,
"e": 4501,
"s": 4490,
"text": " Add Notes"
}
] |
How we can translate Python dictionary into C++? | A python dictionary is a Hashmap. You can use the map data structure in C++ to mimic the behavior of a python dict. You can use map in C++ as follows:
#include <iostream>
#include <map>
using namespace std;
int main(void) {
/* Initializer_list constructor */
map<char, int> m1 = {
{'a', 1},
{'b', 2},
{'c', 3},
{'d', 4},
{'e', 5}
};
cout << "Map contains following elements" << endl;
for (auto it = m1.begin(); it != m1.end(); ++it)
cout << it->first << " = " << it->second << endl;
return 0;
}
This will give the output
The map contains following elements
a = 1
b = 2
c = 3
d = 4
e = 5
Note that this map is equivalent to the python dict:
m1 = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5
} | [
{
"code": null,
"e": 1213,
"s": 1062,
"text": "A python dictionary is a Hashmap. You can use the map data structure in C++ to mimic the behavior of a python dict. You can use map in C++ as follows:"
},
{
"code": null,
"e": 1608,
"s": 1213,
"text": "#include <iostream>\n#include <map>\nusing namespace std;\nint main(void) {\n /* Initializer_list constructor */\n map<char, int> m1 = {\n {'a', 1},\n {'b', 2},\n {'c', 3},\n {'d', 4},\n {'e', 5}\n };\n cout << \"Map contains following elements\" << endl;\n for (auto it = m1.begin(); it != m1.end(); ++it)\n cout << it->first << \" = \" << it->second << endl;\n return 0;\n}"
},
{
"code": null,
"e": 1634,
"s": 1608,
"text": "This will give the output"
},
{
"code": null,
"e": 1700,
"s": 1634,
"text": "The map contains following elements\na = 1\nb = 2\nc = 3\nd = 4\ne = 5"
},
{
"code": null,
"e": 1753,
"s": 1700,
"text": "Note that this map is equivalent to the python dict:"
},
{
"code": null,
"e": 1816,
"s": 1753,
"text": "m1 = {\n 'a': 1,\n 'b': 2,\n 'c': 3,\n 'd': 4,\n 'e': 5\n}"
}
] |
How can I clear text of a textbox using Python Selenium WebDriver? | We can clear text of a textbox with Selenium webdriver in Python using the clear method. First of all, we have to identify the text box with the help of any of the locators like id, css, name, class, xpath, css, or class.
Then we have to enter text into it with the help of the send_keys method. Finally, to clear it we have to use the clear method. We can verify if the text has been cleared with the help of the get_attribute method.
l = driver.find_element_by_id('txt')
l.clear()
Let us try to clear the text from the below edit box.
from selenium import webdriver
#set chromodriver.exe path
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
#implicit wait
driver.implicitly_wait(0.5)
#maximize browser
driver.maximize_window()
#launch URL
driver.get("https://www.tutorialspoint.com/tutor_connect/index.php")
#identify element
l = driver.find_element_by_id("txtSearchText")
l.send_keys("Selenium")
#get value entered
s= l.get_attribute("value")
print("Value after entering text: ")
print(s)
#clear text
l.clear()
t= l.get_attribute("value")
print("Value after clearing text: ")
print(t)
#close browser
driver.close() | [
{
"code": null,
"e": 1284,
"s": 1062,
"text": "We can clear text of a textbox with Selenium webdriver in Python using the clear method. First of all, we have to identify the text box with the help of any of the locators like id, css, name, class, xpath, css, or class."
},
{
"code": null,
"e": 1498,
"s": 1284,
"text": "Then we have to enter text into it with the help of the send_keys method. Finally, to clear it we have to use the clear method. We can verify if the text has been cleared with the help of the get_attribute method."
},
{
"code": null,
"e": 1545,
"s": 1498,
"text": "l = driver.find_element_by_id('txt')\nl.clear()"
},
{
"code": null,
"e": 1599,
"s": 1545,
"text": "Let us try to clear the text from the below edit box."
},
{
"code": null,
"e": 2198,
"s": 1599,
"text": "from selenium import webdriver\n#set chromodriver.exe path\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n#implicit wait\ndriver.implicitly_wait(0.5)\n#maximize browser\ndriver.maximize_window()\n#launch URL\ndriver.get(\"https://www.tutorialspoint.com/tutor_connect/index.php\")\n#identify element\nl = driver.find_element_by_id(\"txtSearchText\")\nl.send_keys(\"Selenium\")\n#get value entered\ns= l.get_attribute(\"value\")\nprint(\"Value after entering text: \")\nprint(s)\n#clear text\nl.clear()\nt= l.get_attribute(\"value\")\nprint(\"Value after clearing text: \")\nprint(t)\n#close browser\ndriver.close()"
}
] |
Bloom Filters - Introduction and Implementation - GeeksforGeeks | 21 Apr, 2022
Suppose you are creating an account on Geekbook, you want to enter a cool username, you entered it and got a message, “Username is already taken”. You added your birth date along username, still no luck. Now you have added your university roll number also, still got “Username is already taken”. It’s really frustrating, isn’t it? But have you ever thought about how quickly Geekbook checks availability of username by searching millions of username registered with it. There are many ways to do this job –
Linear search : Bad idea!
Binary Search : Store all username alphabetically and compare entered username with middle one in list, If it matched, then username is taken otherwise figure out, whether entered username will come before or after middle one and if it will come after, neglect all the usernames before middle one(inclusive). Now search after middle one and repeat this process until you got a match or search end with no match. This technique is better and promising but still it requires multiple steps. But, there must be something better!!
Bloom Filter is a data structure that can do this job.For understanding bloom filters, you must know what is hashing. A hash function takes input and outputs a unique identifier of fixed length which is used for identification of input.
What is Bloom Filter?
A Bloom filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. For example, checking availability of username is set membership problem, where the set is the list of all registered username. The price we pay for efficiency is that it is probabilistic in nature that means, there might be some False Positive results. False positive means, it might tell that given username is already taken but actually it’s not.Interesting Properties of Bloom Filters
Unlike a standard hash table, a Bloom filter of a fixed size can represent a set with an arbitrarily large number of elements.
Adding an element never fails. However, the false positive rate increases steadily as elements are added until all bits in the filter are set to 1, at which point all queries yield a positive result.
Bloom filters never generate false negative result, i.e., telling you that a username doesn’t exist when it actually exists.
Deleting elements from filter is not possible because, if we delete a single element by clearing bits at indices generated by k hash functions, it might cause deletion of few other elements. Example – if we delete “geeks” (in given example below) by clearing bit at 1, 4 and 7, we might end up deleting “nerd” also Because bit at index 4 becomes 0 and bloom filter claims that “nerd” is not present.
Working of Bloom Filter
A empty bloom filter is a bit array of m bits, all set to zero, like this –
We need k number of hash functions to calculate the hashes for a given input. When we want to add an item in the filter, the bits at k indices h1(x), h2(x), ... hk(x) are set, where indices are calculated using hash functions. Example – Suppose we want to enter “geeks” in the filter, we are using 3 hash functions and a bit array of length 10, all set to 0 initially. First we’ll calculate the hashes as follows:
h1(“geeks”) % 10 = 1
h2(“geeks”) % 10 = 4
h3(“geeks”) % 10 = 7
Note: These outputs are random for explanation only. Now we will set the bits at indices 1, 4 and 7 to 1
Again we want to enter “nerd”, similarly, we’ll calculate hashes
h1(“nerd”) % 10 = 3
h2(“nerd”) % 10 = 5
h3(“nerd”) % 10 = 4
Set the bits at indices 3, 5 and 4 to 1
Now if we want to check “geeks” is present in filter or not. We’ll do the same process but this time in reverse order. We calculate respective hashes using h1, h2 and h3 and check if all these indices are set to 1 in the bit array. If all the bits are set then we can say that “geeks” is probably present. If any of the bit at these indices are 0 then “geeks” is definitely not present.
False Positive in Bloom Filters
The question is why we said “probably present”, why this uncertainty. Let’s understand this with an example. Suppose we want to check whether “cat” is present or not. We’ll calculate hashes using h1, h2 and h3
h1(“cat”) % 10 = 1
h2(“cat”) % 10 = 3
h3(“cat”) % 10 = 7
If we check the bit array, bits at these indices are set to 1 but we know that “cat” was never added to the filter. Bit at index 1 and 7 was set when we added “geeks” and bit 3 was set we added “nerd”.
So, because bits at calculated indices are already set by some other item, bloom filter erroneously claims that “cat” is present and generating a false positive result. Depending on the application, it could be huge downside or relatively okay.We can control the probability of getting a false positive by controlling the size of the Bloom filter. More space means fewer false positives. If we want to decrease probability of false positive result, we have to use more number of hash functions and larger bit array. This would add latency in addition to the item and checking membership. Operations that a Bloom Filter supports
insert(x) : To insert an element in the Bloom Filter.
lookup(x) : to check whether an element is already present in Bloom Filter with a positive false probability.
NOTE : We cannot delete an element in Bloom Filter.Probability of False positivity: Let m be the size of bit array, k be the number of hash functions and n be the number of expected elements to be inserted in the filter, then the probability of false positive p can be calculated as:
Size of Bit Array: If expected number of elements n is known and desired false positive probability is p then the size of bit array m can be calculated as :
Optimum number of hash functions: The number of hash functions k must be a positive integer. If m is size of bit array and n is number of elements to be inserted, then k can be calculated as :
Space Efficiency
If we want to store large list of items in a set for purpose of set membership, we can store it in hashmap, tries or simple array or linked list. All these methods require storing item itself, which is not very memory efficient. For example, if we want to store “geeks” in hashmap we have to store actual string “ geeks” as a key value pair {some_key : ”geeks”}. Bloom filters do not store the data item at all. As we have seen they use bit array which allow hash collision. Without hash collision, it would not be compact.
Choice of Hash Function
The hash function used in bloom filters should be independent and uniformly distributed. They should be fast as possible. Fast simple non cryptographic hashes which are independent enough include murmur, FNV series of hash functions and Jenkins hashes. Generating hash is major operation in bloom filters. Cryptographic hash functions provide stability and guarantee but are expensive in calculation. With increase in number of hash functions k, bloom filter become slow. All though non-cryptographic hash functions do not provide guarantee but provide major performance improvement.
Basic implementation of Bloom Filter class in Python3. Save it as bloomfilter.py
Python
# Python 3 program to build Bloom Filter# Install mmh3 and bitarray 3rd party module first# pip install mmh3# pip install bitarrayimport mathimport mmh3from bitarray import bitarray class BloomFilter(object): ''' Class for Bloom filter, using murmur3 hash function ''' def __init__(self, items_count, fp_prob): ''' items_count : int Number of items expected to be stored in bloom filter fp_prob : float False Positive probability in decimal ''' # False possible probability in decimal self.fp_prob = fp_prob # Size of bit array to use self.size = self.get_size(items_count, fp_prob) # number of hash functions to use self.hash_count = self.get_hash_count(self.size, items_count) # Bit array of given size self.bit_array = bitarray(self.size) # initialize all bits as 0 self.bit_array.setall(0) def add(self, item): ''' Add an item in the filter ''' digests = [] for i in range(self.hash_count): # create digest for given item. # i work as seed to mmh3.hash() function # With different seed, digest created is different digest = mmh3.hash(item, i) % self.size digests.append(digest) # set the bit True in bit_array self.bit_array[digest] = True def check(self, item): ''' Check for existence of an item in filter ''' for i in range(self.hash_count): digest = mmh3.hash(item, i) % self.size if self.bit_array[digest] == False: # if any of bit is False then,its not present # in filter # else there is probability that it exist return False return True @classmethod def get_size(self, n, p): ''' Return the size of bit array(m) to used using following formula m = -(n * lg(p)) / (lg(2)^2) n : int number of items expected to be stored in filter p : float False Positive probability in decimal ''' m = -(n * math.log(p))/(math.log(2)**2) return int(m) @classmethod def get_hash_count(self, m, n): ''' Return the hash function(k) to be used using following formula k = (m/n) * lg(2) m : int size of bit array n : int number of items expected to be stored in filter ''' k = (m/n) * math.log(2) return int(k)
Lets test the bloom filter. Save this file as bloom_test.py
Python
from bloomfilter import BloomFilterfrom random import shuffle n = 20 #no of items to addp = 0.05 #false positive probability bloomf = BloomFilter(n,p)print("Size of bit array:{}".format(bloomf.size))print("False positive Probability:{}".format(bloomf.fp_prob))print("Number of hash functions:{}".format(bloomf.hash_count)) # words to be addedword_present = ['abound','abounds','abundance','abundant','accessible', 'bloom','blossom','bolster','bonny','bonus','bonuses', 'coherent','cohesive','colorful','comely','comfort', 'gems','generosity','generous','generously','genial'] # word not addedword_absent = ['bluff','cheater','hate','war','humanity', 'racism','hurt','nuke','gloomy','facebook', 'geeksforgeeks','twitter'] for item in word_present: bloomf.add(item) shuffle(word_present)shuffle(word_absent) test_words = word_present[:10] + word_absentshuffle(test_words)for word in test_words: if bloomf.check(word): if word in word_absent: print("'{}' is a false positive!".format(word)) else: print("'{}' is probably present!".format(word)) else: print("'{}' is definitely not present!".format(word))
Output
Size of bit array:124
False positive Probability:0.05
Number of hash functions:4
'war' is definitely not present!
'gloomy' is definitely not present!
'humanity' is definitely not present!
'abundant' is probably present!
'bloom' is probably present!
'coherent' is probably present!
'cohesive' is probably present!
'bluff' is definitely not present!
'bolster' is probably present!
'hate' is definitely not present!
'racism' is definitely not present!
'bonus' is probably present!
'abounds' is probably present!
'genial' is probably present!
'geeksforgeeks' is definitely not present!
'nuke' is definitely not present!
'hurt' is definitely not present!
'twitter' is a false positive!
'cheater' is definitely not present!
'generosity' is probably present!
'facebook' is definitely not present!
'abundance' is probably present!
Here is the implementation of a sample Bloom Filters with 4 sample hash functions ( k = 4) and the size of bit array is 100.
C++
#include <bits/stdc++.h>#define ll long longusing namespace std; // hash 1int h1(string s, int arrSize){ ll int hash = 0; for (int i = 0; i < s.size(); i++) { hash = (hash + ((int)s[i])); hash = hash % arrSize; } return hash;} // hash 2int h2(string s, int arrSize){ ll int hash = 1; for (int i = 0; i < s.size(); i++) { hash = hash + pow(19, i) * s[i]; hash = hash % arrSize; } return hash % arrSize;} // hash 3int h3(string s, int arrSize){ ll int hash = 7; for (int i = 0; i < s.size(); i++) { hash = (hash * 31 + s[i]) % arrSize; } return hash % arrSize;} // hash 4int h4(string s, int arrSize){ ll int hash = 3; int p = 7; for (int i = 0; i < s.size(); i++) { hash += hash * 7 + s[0] * pow(p, i); hash = hash % arrSize; } return hash;} // lookup operationbool lookup(bool* bitarray, int arrSize, string s){ int a = h1(s, arrSize); int b = h2(s, arrSize); int c = h3(s, arrSize); int d = h4(s, arrSize); if (bitarray[a] && bitarray[b] && bitarray && bitarray[d]) return true; else return false;} // insert operationvoid insert(bool* bitarray, int arrSize, string s){ // check if the element in already present or not if (lookup(bitarray, arrSize, s)) cout << s << " is Probably already present" << endl; else { int a = h1(s, arrSize); int b = h2(s, arrSize); int c = h3(s, arrSize); int d = h4(s, arrSize); bitarray[a] = true; bitarray[b] = true; bitarray = true; bitarray[d] = true; cout << s << " inserted" << endl; }} // Driver Codeint main(){ bool bitarray[100] = { false }; int arrSize = 100; string sarray[33] = { "abound", "abounds", "abundance", "abundant", "accessible", "bloom", "blossom", "bolster", "bonny", "bonus", "bonuses", "coherent", "cohesive", "colorful", "comely", "comfort", "gems", "generosity", "generous", "generously", "genial", "bluff", "cheater", "hate", "war", "humanity", "racism", "hurt", "nuke", "gloomy", "facebook", "geeksforgeeks", "twitter" }; for (int i = 0; i < 33; i++) { insert(bitarray, arrSize, sarray[i]); } return 0;}
abound inserted
abounds inserted
abundance inserted
abundant inserted
accessible inserted
bloom inserted
blossom inserted
bolster inserted
bonny inserted
bonus inserted
bonuses inserted
coherent inserted
cohesive inserted
colorful inserted
comely inserted
comfort inserted
gems inserted
generosity inserted
generous inserted
generously inserted
genial inserted
bluff is Probably already present
cheater inserted
hate inserted
war is Probably already present
humanity inserted
racism inserted
hurt inserted
nuke is Probably already present
gloomy is Probably already present
facebook inserted
geeksforgeeks inserted
twitter inserted
Applications of Bloom filters
Medium uses bloom filters for recommending post to users by filtering post which have been seen by user.
Quora implemented a shared bloom filter in the feed backend to filter out stories that people have seen before.
The Google Chrome web browser used to use a Bloom filter to identify malicious URLs
Google BigTable, Apache HBase and Apache Cassandra, and Postgresql use Bloom filters to reduce the disk lookups for non-existent rows or columns
References
https://en.wikipedia.org/wiki/Bloom_filter
https://blog.medium.com/what-are-bloom-filters-1ec2a50c68ff
https://www.quora.com/What-are-the-best-applications-of-Bloom-filters
This article is contributed by Atul Kumar and improved by Manoj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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.
manoj_26
sweetyty
punamsingh628700
adnanirshad158
simmytarika5
simranarora5sos
GBlog
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GET and POST requests using Python
Types of Software Testing
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to Start Learning DSA?
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": 24592,
"s": 24564,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 25101,
"s": 24592,
"text": "Suppose you are creating an account on Geekbook, you want to enter a cool username, you entered it and got a message, “Username is already taken”. You added your birth date along username, still no luck. Now you have added your university roll number also, still got “Username is already taken”. It’s really frustrating, isn’t it? But have you ever thought about how quickly Geekbook checks availability of username by searching millions of username registered with it. There are many ways to do this job – "
},
{
"code": null,
"e": 25127,
"s": 25101,
"text": "Linear search : Bad idea!"
},
{
"code": null,
"e": 25654,
"s": 25127,
"text": "Binary Search : Store all username alphabetically and compare entered username with middle one in list, If it matched, then username is taken otherwise figure out, whether entered username will come before or after middle one and if it will come after, neglect all the usernames before middle one(inclusive). Now search after middle one and repeat this process until you got a match or search end with no match. This technique is better and promising but still it requires multiple steps. But, there must be something better!!"
},
{
"code": null,
"e": 25892,
"s": 25654,
"text": "Bloom Filter is a data structure that can do this job.For understanding bloom filters, you must know what is hashing. A hash function takes input and outputs a unique identifier of fixed length which is used for identification of input. "
},
{
"code": null,
"e": 25914,
"s": 25892,
"text": "What is Bloom Filter?"
},
{
"code": null,
"e": 26432,
"s": 25914,
"text": "A Bloom filter is a space-efficient probabilistic data structure that is used to test whether an element is a member of a set. For example, checking availability of username is set membership problem, where the set is the list of all registered username. The price we pay for efficiency is that it is probabilistic in nature that means, there might be some False Positive results. False positive means, it might tell that given username is already taken but actually it’s not.Interesting Properties of Bloom Filters "
},
{
"code": null,
"e": 26559,
"s": 26432,
"text": "Unlike a standard hash table, a Bloom filter of a fixed size can represent a set with an arbitrarily large number of elements."
},
{
"code": null,
"e": 26759,
"s": 26559,
"text": "Adding an element never fails. However, the false positive rate increases steadily as elements are added until all bits in the filter are set to 1, at which point all queries yield a positive result."
},
{
"code": null,
"e": 26884,
"s": 26759,
"text": "Bloom filters never generate false negative result, i.e., telling you that a username doesn’t exist when it actually exists."
},
{
"code": null,
"e": 27285,
"s": 26884,
"text": "Deleting elements from filter is not possible because, if we delete a single element by clearing bits at indices generated by k hash functions, it might cause deletion of few other elements. Example – if we delete “geeks” (in given example below) by clearing bit at 1, 4 and 7, we might end up deleting “nerd” also Because bit at index 4 becomes 0 and bloom filter claims that “nerd” is not present. "
},
{
"code": null,
"e": 27309,
"s": 27285,
"text": "Working of Bloom Filter"
},
{
"code": null,
"e": 27387,
"s": 27309,
"text": "A empty bloom filter is a bit array of m bits, all set to zero, like this – "
},
{
"code": null,
"e": 27803,
"s": 27387,
"text": "We need k number of hash functions to calculate the hashes for a given input. When we want to add an item in the filter, the bits at k indices h1(x), h2(x), ... hk(x) are set, where indices are calculated using hash functions. Example – Suppose we want to enter “geeks” in the filter, we are using 3 hash functions and a bit array of length 10, all set to 0 initially. First we’ll calculate the hashes as follows: "
},
{
"code": null,
"e": 27866,
"s": 27803,
"text": "h1(“geeks”) % 10 = 1\nh2(“geeks”) % 10 = 4\nh3(“geeks”) % 10 = 7"
},
{
"code": null,
"e": 27973,
"s": 27866,
"text": "Note: These outputs are random for explanation only. Now we will set the bits at indices 1, 4 and 7 to 1 "
},
{
"code": null,
"e": 28039,
"s": 27973,
"text": "Again we want to enter “nerd”, similarly, we’ll calculate hashes "
},
{
"code": null,
"e": 28099,
"s": 28039,
"text": "h1(“nerd”) % 10 = 3\nh2(“nerd”) % 10 = 5\nh3(“nerd”) % 10 = 4"
},
{
"code": null,
"e": 28141,
"s": 28099,
"text": "Set the bits at indices 3, 5 and 4 to 1 "
},
{
"code": null,
"e": 28530,
"s": 28141,
"text": "Now if we want to check “geeks” is present in filter or not. We’ll do the same process but this time in reverse order. We calculate respective hashes using h1, h2 and h3 and check if all these indices are set to 1 in the bit array. If all the bits are set then we can say that “geeks” is probably present. If any of the bit at these indices are 0 then “geeks” is definitely not present. "
},
{
"code": null,
"e": 28562,
"s": 28530,
"text": "False Positive in Bloom Filters"
},
{
"code": null,
"e": 28774,
"s": 28562,
"text": "The question is why we said “probably present”, why this uncertainty. Let’s understand this with an example. Suppose we want to check whether “cat” is present or not. We’ll calculate hashes using h1, h2 and h3 "
},
{
"code": null,
"e": 28831,
"s": 28774,
"text": "h1(“cat”) % 10 = 1\nh2(“cat”) % 10 = 3\nh3(“cat”) % 10 = 7"
},
{
"code": null,
"e": 29035,
"s": 28831,
"text": "If we check the bit array, bits at these indices are set to 1 but we know that “cat” was never added to the filter. Bit at index 1 and 7 was set when we added “geeks” and bit 3 was set we added “nerd”. "
},
{
"code": null,
"e": 29665,
"s": 29035,
"text": "So, because bits at calculated indices are already set by some other item, bloom filter erroneously claims that “cat” is present and generating a false positive result. Depending on the application, it could be huge downside or relatively okay.We can control the probability of getting a false positive by controlling the size of the Bloom filter. More space means fewer false positives. If we want to decrease probability of false positive result, we have to use more number of hash functions and larger bit array. This would add latency in addition to the item and checking membership. Operations that a Bloom Filter supports "
},
{
"code": null,
"e": 29719,
"s": 29665,
"text": "insert(x) : To insert an element in the Bloom Filter."
},
{
"code": null,
"e": 29829,
"s": 29719,
"text": "lookup(x) : to check whether an element is already present in Bloom Filter with a positive false probability."
},
{
"code": null,
"e": 30113,
"s": 29829,
"text": "NOTE : We cannot delete an element in Bloom Filter.Probability of False positivity: Let m be the size of bit array, k be the number of hash functions and n be the number of expected elements to be inserted in the filter, then the probability of false positive p can be calculated as:"
},
{
"code": null,
"e": 30273,
"s": 30115,
"text": "Size of Bit Array: If expected number of elements n is known and desired false positive probability is p then the size of bit array m can be calculated as : "
},
{
"code": null,
"e": 30469,
"s": 30275,
"text": "Optimum number of hash functions: The number of hash functions k must be a positive integer. If m is size of bit array and n is number of elements to be inserted, then k can be calculated as : "
},
{
"code": null,
"e": 30486,
"s": 30469,
"text": "Space Efficiency"
},
{
"code": null,
"e": 31012,
"s": 30486,
"text": "If we want to store large list of items in a set for purpose of set membership, we can store it in hashmap, tries or simple array or linked list. All these methods require storing item itself, which is not very memory efficient. For example, if we want to store “geeks” in hashmap we have to store actual string “ geeks” as a key value pair {some_key : ”geeks”}. Bloom filters do not store the data item at all. As we have seen they use bit array which allow hash collision. Without hash collision, it would not be compact. "
},
{
"code": null,
"e": 31036,
"s": 31012,
"text": "Choice of Hash Function"
},
{
"code": null,
"e": 31620,
"s": 31036,
"text": "The hash function used in bloom filters should be independent and uniformly distributed. They should be fast as possible. Fast simple non cryptographic hashes which are independent enough include murmur, FNV series of hash functions and Jenkins hashes. Generating hash is major operation in bloom filters. Cryptographic hash functions provide stability and guarantee but are expensive in calculation. With increase in number of hash functions k, bloom filter become slow. All though non-cryptographic hash functions do not provide guarantee but provide major performance improvement."
},
{
"code": null,
"e": 31702,
"s": 31620,
"text": "Basic implementation of Bloom Filter class in Python3. Save it as bloomfilter.py "
},
{
"code": null,
"e": 31709,
"s": 31702,
"text": "Python"
},
{
"code": "# Python 3 program to build Bloom Filter# Install mmh3 and bitarray 3rd party module first# pip install mmh3# pip install bitarrayimport mathimport mmh3from bitarray import bitarray class BloomFilter(object): ''' Class for Bloom filter, using murmur3 hash function ''' def __init__(self, items_count, fp_prob): ''' items_count : int Number of items expected to be stored in bloom filter fp_prob : float False Positive probability in decimal ''' # False possible probability in decimal self.fp_prob = fp_prob # Size of bit array to use self.size = self.get_size(items_count, fp_prob) # number of hash functions to use self.hash_count = self.get_hash_count(self.size, items_count) # Bit array of given size self.bit_array = bitarray(self.size) # initialize all bits as 0 self.bit_array.setall(0) def add(self, item): ''' Add an item in the filter ''' digests = [] for i in range(self.hash_count): # create digest for given item. # i work as seed to mmh3.hash() function # With different seed, digest created is different digest = mmh3.hash(item, i) % self.size digests.append(digest) # set the bit True in bit_array self.bit_array[digest] = True def check(self, item): ''' Check for existence of an item in filter ''' for i in range(self.hash_count): digest = mmh3.hash(item, i) % self.size if self.bit_array[digest] == False: # if any of bit is False then,its not present # in filter # else there is probability that it exist return False return True @classmethod def get_size(self, n, p): ''' Return the size of bit array(m) to used using following formula m = -(n * lg(p)) / (lg(2)^2) n : int number of items expected to be stored in filter p : float False Positive probability in decimal ''' m = -(n * math.log(p))/(math.log(2)**2) return int(m) @classmethod def get_hash_count(self, m, n): ''' Return the hash function(k) to be used using following formula k = (m/n) * lg(2) m : int size of bit array n : int number of items expected to be stored in filter ''' k = (m/n) * math.log(2) return int(k)",
"e": 34275,
"s": 31709,
"text": null
},
{
"code": null,
"e": 34335,
"s": 34275,
"text": "Lets test the bloom filter. Save this file as bloom_test.py"
},
{
"code": null,
"e": 34342,
"s": 34335,
"text": "Python"
},
{
"code": "from bloomfilter import BloomFilterfrom random import shuffle n = 20 #no of items to addp = 0.05 #false positive probability bloomf = BloomFilter(n,p)print(\"Size of bit array:{}\".format(bloomf.size))print(\"False positive Probability:{}\".format(bloomf.fp_prob))print(\"Number of hash functions:{}\".format(bloomf.hash_count)) # words to be addedword_present = ['abound','abounds','abundance','abundant','accessible', 'bloom','blossom','bolster','bonny','bonus','bonuses', 'coherent','cohesive','colorful','comely','comfort', 'gems','generosity','generous','generously','genial'] # word not addedword_absent = ['bluff','cheater','hate','war','humanity', 'racism','hurt','nuke','gloomy','facebook', 'geeksforgeeks','twitter'] for item in word_present: bloomf.add(item) shuffle(word_present)shuffle(word_absent) test_words = word_present[:10] + word_absentshuffle(test_words)for word in test_words: if bloomf.check(word): if word in word_absent: print(\"'{}' is a false positive!\".format(word)) else: print(\"'{}' is probably present!\".format(word)) else: print(\"'{}' is definitely not present!\".format(word))",
"e": 35569,
"s": 34342,
"text": null
},
{
"code": null,
"e": 35577,
"s": 35569,
"text": "Output "
},
{
"code": null,
"e": 36400,
"s": 35577,
"text": "Size of bit array:124\nFalse positive Probability:0.05\nNumber of hash functions:4\n'war' is definitely not present!\n'gloomy' is definitely not present!\n'humanity' is definitely not present!\n'abundant' is probably present!\n'bloom' is probably present!\n'coherent' is probably present!\n'cohesive' is probably present!\n'bluff' is definitely not present!\n'bolster' is probably present!\n'hate' is definitely not present!\n'racism' is definitely not present!\n'bonus' is probably present!\n'abounds' is probably present!\n'genial' is probably present!\n'geeksforgeeks' is definitely not present!\n'nuke' is definitely not present!\n'hurt' is definitely not present!\n'twitter' is a false positive!\n'cheater' is definitely not present!\n'generosity' is probably present!\n'facebook' is definitely not present!\n'abundance' is probably present!"
},
{
"code": null,
"e": 36525,
"s": 36400,
"text": "Here is the implementation of a sample Bloom Filters with 4 sample hash functions ( k = 4) and the size of bit array is 100."
},
{
"code": null,
"e": 36529,
"s": 36525,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h>#define ll long longusing namespace std; // hash 1int h1(string s, int arrSize){ ll int hash = 0; for (int i = 0; i < s.size(); i++) { hash = (hash + ((int)s[i])); hash = hash % arrSize; } return hash;} // hash 2int h2(string s, int arrSize){ ll int hash = 1; for (int i = 0; i < s.size(); i++) { hash = hash + pow(19, i) * s[i]; hash = hash % arrSize; } return hash % arrSize;} // hash 3int h3(string s, int arrSize){ ll int hash = 7; for (int i = 0; i < s.size(); i++) { hash = (hash * 31 + s[i]) % arrSize; } return hash % arrSize;} // hash 4int h4(string s, int arrSize){ ll int hash = 3; int p = 7; for (int i = 0; i < s.size(); i++) { hash += hash * 7 + s[0] * pow(p, i); hash = hash % arrSize; } return hash;} // lookup operationbool lookup(bool* bitarray, int arrSize, string s){ int a = h1(s, arrSize); int b = h2(s, arrSize); int c = h3(s, arrSize); int d = h4(s, arrSize); if (bitarray[a] && bitarray[b] && bitarray && bitarray[d]) return true; else return false;} // insert operationvoid insert(bool* bitarray, int arrSize, string s){ // check if the element in already present or not if (lookup(bitarray, arrSize, s)) cout << s << \" is Probably already present\" << endl; else { int a = h1(s, arrSize); int b = h2(s, arrSize); int c = h3(s, arrSize); int d = h4(s, arrSize); bitarray[a] = true; bitarray[b] = true; bitarray = true; bitarray[d] = true; cout << s << \" inserted\" << endl; }} // Driver Codeint main(){ bool bitarray[100] = { false }; int arrSize = 100; string sarray[33] = { \"abound\", \"abounds\", \"abundance\", \"abundant\", \"accessible\", \"bloom\", \"blossom\", \"bolster\", \"bonny\", \"bonus\", \"bonuses\", \"coherent\", \"cohesive\", \"colorful\", \"comely\", \"comfort\", \"gems\", \"generosity\", \"generous\", \"generously\", \"genial\", \"bluff\", \"cheater\", \"hate\", \"war\", \"humanity\", \"racism\", \"hurt\", \"nuke\", \"gloomy\", \"facebook\", \"geeksforgeeks\", \"twitter\" }; for (int i = 0; i < 33; i++) { insert(bitarray, arrSize, sarray[i]); } return 0;}",
"e": 38951,
"s": 36529,
"text": null
},
{
"code": null,
"e": 39584,
"s": 38951,
"text": "abound inserted\nabounds inserted\nabundance inserted\nabundant inserted\naccessible inserted\nbloom inserted\nblossom inserted\nbolster inserted\nbonny inserted\nbonus inserted\nbonuses inserted\ncoherent inserted\ncohesive inserted\ncolorful inserted\ncomely inserted\ncomfort inserted\ngems inserted\ngenerosity inserted\ngenerous inserted\ngenerously inserted\ngenial inserted\nbluff is Probably already present\ncheater inserted\nhate inserted\nwar is Probably already present\nhumanity inserted\nracism inserted\nhurt inserted\nnuke is Probably already present\ngloomy is Probably already present\nfacebook inserted\ngeeksforgeeks inserted\ntwitter inserted\n"
},
{
"code": null,
"e": 39615,
"s": 39584,
"text": "Applications of Bloom filters "
},
{
"code": null,
"e": 39720,
"s": 39615,
"text": "Medium uses bloom filters for recommending post to users by filtering post which have been seen by user."
},
{
"code": null,
"e": 39832,
"s": 39720,
"text": "Quora implemented a shared bloom filter in the feed backend to filter out stories that people have seen before."
},
{
"code": null,
"e": 39916,
"s": 39832,
"text": "The Google Chrome web browser used to use a Bloom filter to identify malicious URLs"
},
{
"code": null,
"e": 40061,
"s": 39916,
"text": "Google BigTable, Apache HBase and Apache Cassandra, and Postgresql use Bloom filters to reduce the disk lookups for non-existent rows or columns"
},
{
"code": null,
"e": 40073,
"s": 40061,
"text": "References "
},
{
"code": null,
"e": 40116,
"s": 40073,
"text": "https://en.wikipedia.org/wiki/Bloom_filter"
},
{
"code": null,
"e": 40176,
"s": 40116,
"text": "https://blog.medium.com/what-are-bloom-filters-1ec2a50c68ff"
},
{
"code": null,
"e": 40246,
"s": 40176,
"text": "https://www.quora.com/What-are-the-best-applications-of-Bloom-filters"
},
{
"code": null,
"e": 40693,
"s": 40246,
"text": "This article is contributed by Atul Kumar and improved by Manoj Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 40702,
"s": 40693,
"text": "manoj_26"
},
{
"code": null,
"e": 40711,
"s": 40702,
"text": "sweetyty"
},
{
"code": null,
"e": 40728,
"s": 40711,
"text": "punamsingh628700"
},
{
"code": null,
"e": 40743,
"s": 40728,
"text": "adnanirshad158"
},
{
"code": null,
"e": 40756,
"s": 40743,
"text": "simmytarika5"
},
{
"code": null,
"e": 40772,
"s": 40756,
"text": "simranarora5sos"
},
{
"code": null,
"e": 40778,
"s": 40772,
"text": "GBlog"
},
{
"code": null,
"e": 40785,
"s": 40778,
"text": "Python"
},
{
"code": null,
"e": 40804,
"s": 40785,
"text": "Technical Scripter"
},
{
"code": null,
"e": 40902,
"s": 40804,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 40927,
"s": 40902,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 40962,
"s": 40927,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 40988,
"s": 40962,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 41050,
"s": 40988,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 41077,
"s": 41050,
"text": "How to Start Learning DSA?"
},
{
"code": null,
"e": 41105,
"s": 41077,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 41155,
"s": 41105,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 41177,
"s": 41155,
"text": "Python map() function"
}
] |
How to Avoid the “divide by Zero” Error in SQL? - GeeksforGeeks | 25 Oct, 2021
In this article, we will look at how to avoid the “divide by zero” error in SQL. If we divide any number by zero, it leads to infinity, and we get an error message. We can avoid this error message using the following three methods:
Using NULLIF() function
Using CASE statement
Using SET ARITHABORT OFF
We will be creating a database first to perform SQL operations.
Query:
CREATE DATABASE Test;
Output:
Commands completed successfully show the database “Test” is created.
For all the methods we need to declare two variables that will store the values of the numerator and denominator.
DECLARE @Num1 INT;
DECLARE @Num2 INT;
After declaring the variable we have to set the values. Set the second variable value as zero.
SET @Num1=12;
SET @Num2=0;
Method 1: Using NULLIF() function
If both arguments are equal, it returns NULL. If both arguments are not equal, it returns the value of the first argument.
Syntax:
NULLIF(exp1, exp2);
Now we are using the NULLIF() function in the denominator with the second argument value zero.
SELECT @Num1/NULLIF(@Num2,0) AS Division;
In the SQL server, if we divide any number with a NULL value its output will be NULL.
If the first argument is zero, it means if the Num2 value is zero, then NULLIF() function returns the NULL value.
If the first argument is not zero, then NULLIF() function returns the value of that argument. And the division takes place as regular.
Here is the complete query.
Query:
DECLARE @Num1 INT;
DECLARE @Num2 INT;
SET @Num1=12;
SET @Num2=0;
SELECT @Num1/NULLIF(@Num2,0) AS Division;
Output:
Method 2: Using the CASE statement
The SQL CASE statement is used to check the condition and return a value. It checks the conditions until it is true and if no conditions are true it returns the value in the else part.
We have to check the value of the denominator i.e the value of the Num2 variable. If it is zero then return NULL otherwise return the regular division.
SELECT CASE
WHEN @Num2=0
THEN NULL
ELSE @Num1/@Num2
END AS Division;
Here is the complete query:
Query:
DECLARE @Num1 INT;
DECLARE @Num2 INT;
SET @Num1=12;
SET @Num2=0;
SELECT CASE
WHEN @Num2=0
THEN NULL
ELSE @Num1/@Num2
END AS Division;
Output:
Method 3: SET ARITHABORT OFF
To control the behavior of queries, we can use SET methods. By default, ARITHABORT is set as ON. It terminates the query and returns an error message. If we set it OFF it will terminate and returns a NULL value.
Like ARITHBORT, we have to set ANSI_WARNINGS OFF to avoid the error message.
SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
Here is the complete query:
Query:
SET ARITHABORT OFF;
SET ANSI_WARNINGS OFF;
DECLARE @Num1 INT;
DECLARE @Num2 INT;
SET @Num1=12;
SET @Num2=0;
Select @num1/@Num2;
Output:
Picked
SQL-Server
SQL
SQL
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Update Multiple Columns in Single Update Statement in SQL?
What is Temporary Table in SQL?
SQL using Python
SQL Query for Matching Multiple Values in the Same Column
SQL Query to Insert Multiple Rows
SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter
SQL Query to Convert VARCHAR to INT
SQL | Subquery
SQL - SELECT from Multiple Tables with MS SQL Server
Window functions in SQL | [
{
"code": null,
"e": 24188,
"s": 24160,
"text": "\n25 Oct, 2021"
},
{
"code": null,
"e": 24420,
"s": 24188,
"text": "In this article, we will look at how to avoid the “divide by zero” error in SQL. If we divide any number by zero, it leads to infinity, and we get an error message. We can avoid this error message using the following three methods:"
},
{
"code": null,
"e": 24444,
"s": 24420,
"text": "Using NULLIF() function"
},
{
"code": null,
"e": 24465,
"s": 24444,
"text": "Using CASE statement"
},
{
"code": null,
"e": 24490,
"s": 24465,
"text": "Using SET ARITHABORT OFF"
},
{
"code": null,
"e": 24554,
"s": 24490,
"text": "We will be creating a database first to perform SQL operations."
},
{
"code": null,
"e": 24561,
"s": 24554,
"text": "Query:"
},
{
"code": null,
"e": 24583,
"s": 24561,
"text": "CREATE DATABASE Test;"
},
{
"code": null,
"e": 24591,
"s": 24583,
"text": "Output:"
},
{
"code": null,
"e": 24660,
"s": 24591,
"text": "Commands completed successfully show the database “Test” is created."
},
{
"code": null,
"e": 24774,
"s": 24660,
"text": "For all the methods we need to declare two variables that will store the values of the numerator and denominator."
},
{
"code": null,
"e": 24812,
"s": 24774,
"text": "DECLARE @Num1 INT;\nDECLARE @Num2 INT;"
},
{
"code": null,
"e": 24907,
"s": 24812,
"text": "After declaring the variable we have to set the values. Set the second variable value as zero."
},
{
"code": null,
"e": 24934,
"s": 24907,
"text": "SET @Num1=12;\nSET @Num2=0;"
},
{
"code": null,
"e": 24968,
"s": 24934,
"text": "Method 1: Using NULLIF() function"
},
{
"code": null,
"e": 25091,
"s": 24968,
"text": "If both arguments are equal, it returns NULL. If both arguments are not equal, it returns the value of the first argument."
},
{
"code": null,
"e": 25099,
"s": 25091,
"text": "Syntax:"
},
{
"code": null,
"e": 25119,
"s": 25099,
"text": "NULLIF(exp1, exp2);"
},
{
"code": null,
"e": 25215,
"s": 25119,
"text": "Now we are using the NULLIF() function in the denominator with the second argument value zero. "
},
{
"code": null,
"e": 25257,
"s": 25215,
"text": "SELECT @Num1/NULLIF(@Num2,0) AS Division;"
},
{
"code": null,
"e": 25343,
"s": 25257,
"text": "In the SQL server, if we divide any number with a NULL value its output will be NULL."
},
{
"code": null,
"e": 25457,
"s": 25343,
"text": "If the first argument is zero, it means if the Num2 value is zero, then NULLIF() function returns the NULL value."
},
{
"code": null,
"e": 25592,
"s": 25457,
"text": "If the first argument is not zero, then NULLIF() function returns the value of that argument. And the division takes place as regular."
},
{
"code": null,
"e": 25620,
"s": 25592,
"text": "Here is the complete query."
},
{
"code": null,
"e": 25627,
"s": 25620,
"text": "Query:"
},
{
"code": null,
"e": 25734,
"s": 25627,
"text": "DECLARE @Num1 INT;\nDECLARE @Num2 INT;\nSET @Num1=12;\nSET @Num2=0;\nSELECT @Num1/NULLIF(@Num2,0) AS Division;"
},
{
"code": null,
"e": 25742,
"s": 25734,
"text": "Output:"
},
{
"code": null,
"e": 25777,
"s": 25742,
"text": "Method 2: Using the CASE statement"
},
{
"code": null,
"e": 25962,
"s": 25777,
"text": "The SQL CASE statement is used to check the condition and return a value. It checks the conditions until it is true and if no conditions are true it returns the value in the else part."
},
{
"code": null,
"e": 26114,
"s": 25962,
"text": "We have to check the value of the denominator i.e the value of the Num2 variable. If it is zero then return NULL otherwise return the regular division."
},
{
"code": null,
"e": 26183,
"s": 26114,
"text": "SELECT CASE\nWHEN @Num2=0\nTHEN NULL\nELSE @Num1/@Num2\nEND AS Division;"
},
{
"code": null,
"e": 26211,
"s": 26183,
"text": "Here is the complete query:"
},
{
"code": null,
"e": 26218,
"s": 26211,
"text": "Query:"
},
{
"code": null,
"e": 26364,
"s": 26218,
"text": "DECLARE @Num1 INT;\nDECLARE @Num2 INT;\nSET @Num1=12;\nSET @Num2=0;\nSELECT CASE\n WHEN @Num2=0\n THEN NULL\n ELSE @Num1/@Num2\nEND AS Division;"
},
{
"code": null,
"e": 26372,
"s": 26364,
"text": "Output:"
},
{
"code": null,
"e": 26401,
"s": 26372,
"text": "Method 3: SET ARITHABORT OFF"
},
{
"code": null,
"e": 26613,
"s": 26401,
"text": "To control the behavior of queries, we can use SET methods. By default, ARITHABORT is set as ON. It terminates the query and returns an error message. If we set it OFF it will terminate and returns a NULL value."
},
{
"code": null,
"e": 26690,
"s": 26613,
"text": "Like ARITHBORT, we have to set ANSI_WARNINGS OFF to avoid the error message."
},
{
"code": null,
"e": 26733,
"s": 26690,
"text": "SET ARITHABORT OFF;\nSET ANSI_WARNINGS OFF;"
},
{
"code": null,
"e": 26761,
"s": 26733,
"text": "Here is the complete query:"
},
{
"code": null,
"e": 26768,
"s": 26761,
"text": "Query:"
},
{
"code": null,
"e": 26896,
"s": 26768,
"text": "SET ARITHABORT OFF;\nSET ANSI_WARNINGS OFF;\nDECLARE @Num1 INT;\nDECLARE @Num2 INT;\nSET @Num1=12;\nSET @Num2=0;\nSelect @num1/@Num2;"
},
{
"code": null,
"e": 26904,
"s": 26896,
"text": "Output:"
},
{
"code": null,
"e": 26911,
"s": 26904,
"text": "Picked"
},
{
"code": null,
"e": 26922,
"s": 26911,
"text": "SQL-Server"
},
{
"code": null,
"e": 26926,
"s": 26922,
"text": "SQL"
},
{
"code": null,
"e": 26930,
"s": 26926,
"text": "SQL"
},
{
"code": null,
"e": 27028,
"s": 26930,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27037,
"s": 27028,
"text": "Comments"
},
{
"code": null,
"e": 27050,
"s": 27037,
"text": "Old Comments"
},
{
"code": null,
"e": 27116,
"s": 27050,
"text": "How to Update Multiple Columns in Single Update Statement in SQL?"
},
{
"code": null,
"e": 27148,
"s": 27116,
"text": "What is Temporary Table in SQL?"
},
{
"code": null,
"e": 27165,
"s": 27148,
"text": "SQL using Python"
},
{
"code": null,
"e": 27223,
"s": 27165,
"text": "SQL Query for Matching Multiple Values in the Same Column"
},
{
"code": null,
"e": 27257,
"s": 27223,
"text": "SQL Query to Insert Multiple Rows"
},
{
"code": null,
"e": 27335,
"s": 27257,
"text": "SQL Query to Find the Name of a Person Whose Name Starts with Specific Letter"
},
{
"code": null,
"e": 27371,
"s": 27335,
"text": "SQL Query to Convert VARCHAR to INT"
},
{
"code": null,
"e": 27386,
"s": 27371,
"text": "SQL | Subquery"
},
{
"code": null,
"e": 27439,
"s": 27386,
"text": "SQL - SELECT from Multiple Tables with MS SQL Server"
}
] |
Consecutive Numbers Sum in C++ | Suppose we have a positive integer N, we have to find how many different ways can we write it as a sum of consecutive positive integers?
So, if the input is like 10, then the output will be 3, this is because we can represent 10 as 5 + 5 and 7 + 3, so there are two different ways.
To solve this, we will follow these steps −
ret := 1
ret := 1
for initialize i := 2, (increase i by 1), do −sum := (i * (i + 1)) / 2if sum > N, then −Come out from the looprem := N - sumret := ret + (1 when rem mod i is 0, otherwise 0)
for initialize i := 2, (increase i by 1), do −
sum := (i * (i + 1)) / 2
sum := (i * (i + 1)) / 2
if sum > N, then −Come out from the loop
if sum > N, then −
Come out from the loop
Come out from the loop
rem := N - sum
rem := N - sum
ret := ret + (1 when rem mod i is 0, otherwise 0)
ret := ret + (1 when rem mod i is 0, otherwise 0)
return ret
return ret
Let us see the following implementation to get better understanding −
Live Demo
#include <bits/stdc++.h>
using namespace std;
class Solution {
public:
int consecutiveNumbersSum(int N) {
int ret = 1;
for(int i = 2; ; i++){
int sum = (i * (i + 1)) / 2;
if(sum > N) break;
int rem = N - sum; ret += (rem % i == 0);
}
return ret;
}
}; main(){
Solution ob;cout << (ob.consecutiveNumbersSum(10));
}
10
2 | [
{
"code": null,
"e": 1199,
"s": 1062,
"text": "Suppose we have a positive integer N, we have to find how many different ways can we write it as a sum of consecutive positive integers?"
},
{
"code": null,
"e": 1344,
"s": 1199,
"text": "So, if the input is like 10, then the output will be 3, this is because we can represent 10 as 5 + 5 and 7 + 3, so there are two different ways."
},
{
"code": null,
"e": 1388,
"s": 1344,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1397,
"s": 1388,
"text": "ret := 1"
},
{
"code": null,
"e": 1406,
"s": 1397,
"text": "ret := 1"
},
{
"code": null,
"e": 1580,
"s": 1406,
"text": "for initialize i := 2, (increase i by 1), do −sum := (i * (i + 1)) / 2if sum > N, then −Come out from the looprem := N - sumret := ret + (1 when rem mod i is 0, otherwise 0)"
},
{
"code": null,
"e": 1627,
"s": 1580,
"text": "for initialize i := 2, (increase i by 1), do −"
},
{
"code": null,
"e": 1652,
"s": 1627,
"text": "sum := (i * (i + 1)) / 2"
},
{
"code": null,
"e": 1677,
"s": 1652,
"text": "sum := (i * (i + 1)) / 2"
},
{
"code": null,
"e": 1718,
"s": 1677,
"text": "if sum > N, then −Come out from the loop"
},
{
"code": null,
"e": 1737,
"s": 1718,
"text": "if sum > N, then −"
},
{
"code": null,
"e": 1760,
"s": 1737,
"text": "Come out from the loop"
},
{
"code": null,
"e": 1783,
"s": 1760,
"text": "Come out from the loop"
},
{
"code": null,
"e": 1798,
"s": 1783,
"text": "rem := N - sum"
},
{
"code": null,
"e": 1813,
"s": 1798,
"text": "rem := N - sum"
},
{
"code": null,
"e": 1863,
"s": 1813,
"text": "ret := ret + (1 when rem mod i is 0, otherwise 0)"
},
{
"code": null,
"e": 1913,
"s": 1863,
"text": "ret := ret + (1 when rem mod i is 0, otherwise 0)"
},
{
"code": null,
"e": 1924,
"s": 1913,
"text": "return ret"
},
{
"code": null,
"e": 1935,
"s": 1924,
"text": "return ret"
},
{
"code": null,
"e": 2005,
"s": 1935,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2016,
"s": 2005,
"text": " Live Demo"
},
{
"code": null,
"e": 2392,
"s": 2016,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nclass Solution {\n public:\n int consecutiveNumbersSum(int N) {\n int ret = 1;\n for(int i = 2; ; i++){\n int sum = (i * (i + 1)) / 2;\n if(sum > N) break;\n int rem = N - sum; ret += (rem % i == 0);\n }\n return ret;\n }\n}; main(){\n Solution ob;cout << (ob.consecutiveNumbersSum(10));\n}"
},
{
"code": null,
"e": 2395,
"s": 2392,
"text": "10"
},
{
"code": null,
"e": 2397,
"s": 2395,
"text": "2"
}
] |
Apache Spark with Scala - Resilient Distributed Dataset - GeeksforGeeks | 02 Sep, 2021
In the modern world, we are dealing with huge datasets every day. Data is growing even faster than processing speeds. To perform computations on such large data is often achieved by using distributed systems. A distributed system consists of clusters (nodes/networked computers) that run processes in parallel and communicate with each other if needed.
Apache Spark is a unified analytics engine for large-scale data processing. It provides high-level APIs in Java, Scala, Python, and R, and an optimized engine that supports general execution graphs. This rich set of functionalities and libraries supported higher-level tools like Spark SQL for SQL and structured data processing, MLlib for machine learning, GraphX for graph processing, and Structured Streaming for incremental computation and stream processing. In this article, we will be learning Apache spark (version 2.x) using Scala.
Some basic concepts :
RDD(Resilient Distributed Dataset) – It is an immutable distributed collection of objects. In the case of RDD, the dataset is the main part and It is divided into logical partitions.SparkSession –The entry point to programming Spark with the Dataset and DataFrame API.
RDD(Resilient Distributed Dataset) – It is an immutable distributed collection of objects. In the case of RDD, the dataset is the main part and It is divided into logical partitions.
SparkSession –The entry point to programming Spark with the Dataset and DataFrame API.
We will be using Scala IDE only for demonstration purposes. A dedicated spark compiler is required to run the below code. Follow the link to run the below code.
Let’s create our first data frame in spark.
Scala
// Importing SparkSessionimport org.apache.spark.sql.SparkSession // Creating SparkSession objectval sparkSession = SparkSession.builder() .appName("My First Spark Application") .master("local").getOrCreate() // Loading sparkContextval sparkContext = sparkSession.sparkContext // Creating an RDDval intArray = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // parallelize method creates partitions, which additionally// takes integer argument to specifies the number of partitions.// Here we are using 3 partitions. val intRDD = sparkContext.parallelize(intArray, 3) // Printing number of partitionsprintln(s"Number of partitions in intRDD : ${intRDD.partitions.size}") // Printing first element of RDDprintln(s"First element in intRDD : ${intRDD.first}") // Creating string from RDD// take(n) function is used to fetch n elements from// RDD and returns an Array.// Then we will convert the Array to string using// mkString function in scala.val strFromRDD = intRDD.take(intRDD.count.toInt).mkString(", ")println(s"String from intRDD : ${strFromRDD}") // Printing contents of RDD// collect function is used to retrieve all the data in an RDD.println("Printing intRDD: ")intRDD.collect().foreach(println)
Output :
Number of partitions in intRDD : 3
First element in intRDD : 1
String from intRDD : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
Printing intRDD:
1
2
3
4
5
6
7
8
9
10
sooda367
Hadoop
Scala
Hadoop
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Create Table in Hive?
Hadoop - Schedulers and Types of Schedulers
Hive - Alter Table
Difference Between Hadoop 2.x vs Hadoop 3.x
Hadoop - File Blocks and Replication Factor
For Loop in Scala
Scala | flatMap Method
Scala | map() method
Scala List filter() method with example
String concatenation in Scala | [
{
"code": null,
"e": 24346,
"s": 24318,
"text": "\n02 Sep, 2021"
},
{
"code": null,
"e": 24699,
"s": 24346,
"text": "In the modern world, we are dealing with huge datasets every day. Data is growing even faster than processing speeds. To perform computations on such large data is often achieved by using distributed systems. A distributed system consists of clusters (nodes/networked computers) that run processes in parallel and communicate with each other if needed."
},
{
"code": null,
"e": 25239,
"s": 24699,
"text": "Apache Spark is a unified analytics engine for large-scale data processing. It provides high-level APIs in Java, Scala, Python, and R, and an optimized engine that supports general execution graphs. This rich set of functionalities and libraries supported higher-level tools like Spark SQL for SQL and structured data processing, MLlib for machine learning, GraphX for graph processing, and Structured Streaming for incremental computation and stream processing. In this article, we will be learning Apache spark (version 2.x) using Scala."
},
{
"code": null,
"e": 25262,
"s": 25239,
"text": "Some basic concepts : "
},
{
"code": null,
"e": 25531,
"s": 25262,
"text": "RDD(Resilient Distributed Dataset) – It is an immutable distributed collection of objects. In the case of RDD, the dataset is the main part and It is divided into logical partitions.SparkSession –The entry point to programming Spark with the Dataset and DataFrame API."
},
{
"code": null,
"e": 25714,
"s": 25531,
"text": "RDD(Resilient Distributed Dataset) – It is an immutable distributed collection of objects. In the case of RDD, the dataset is the main part and It is divided into logical partitions."
},
{
"code": null,
"e": 25801,
"s": 25714,
"text": "SparkSession –The entry point to programming Spark with the Dataset and DataFrame API."
},
{
"code": null,
"e": 25962,
"s": 25801,
"text": "We will be using Scala IDE only for demonstration purposes. A dedicated spark compiler is required to run the below code. Follow the link to run the below code."
},
{
"code": null,
"e": 26006,
"s": 25962,
"text": "Let’s create our first data frame in spark."
},
{
"code": null,
"e": 26012,
"s": 26006,
"text": "Scala"
},
{
"code": "// Importing SparkSessionimport org.apache.spark.sql.SparkSession // Creating SparkSession objectval sparkSession = SparkSession.builder() .appName(\"My First Spark Application\") .master(\"local\").getOrCreate() // Loading sparkContextval sparkContext = sparkSession.sparkContext // Creating an RDDval intArray = Array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) // parallelize method creates partitions, which additionally// takes integer argument to specifies the number of partitions.// Here we are using 3 partitions. val intRDD = sparkContext.parallelize(intArray, 3) // Printing number of partitionsprintln(s\"Number of partitions in intRDD : ${intRDD.partitions.size}\") // Printing first element of RDDprintln(s\"First element in intRDD : ${intRDD.first}\") // Creating string from RDD// take(n) function is used to fetch n elements from// RDD and returns an Array.// Then we will convert the Array to string using// mkString function in scala.val strFromRDD = intRDD.take(intRDD.count.toInt).mkString(\", \")println(s\"String from intRDD : ${strFromRDD}\") // Printing contents of RDD// collect function is used to retrieve all the data in an RDD.println(\"Printing intRDD: \")intRDD.collect().foreach(println)",
"e": 27242,
"s": 26012,
"text": null
},
{
"code": null,
"e": 27253,
"s": 27242,
"text": "Output : "
},
{
"code": null,
"e": 27406,
"s": 27253,
"text": "Number of partitions in intRDD : 3\nFirst element in intRDD : 1\nString from intRDD : 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\nPrinting intRDD: \n1\n2\n3\n4\n5\n6\n7\n8\n9\n10"
},
{
"code": null,
"e": 27419,
"s": 27410,
"text": "sooda367"
},
{
"code": null,
"e": 27426,
"s": 27419,
"text": "Hadoop"
},
{
"code": null,
"e": 27432,
"s": 27426,
"text": "Scala"
},
{
"code": null,
"e": 27439,
"s": 27432,
"text": "Hadoop"
},
{
"code": null,
"e": 27537,
"s": 27439,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27546,
"s": 27537,
"text": "Comments"
},
{
"code": null,
"e": 27559,
"s": 27546,
"text": "Old Comments"
},
{
"code": null,
"e": 27588,
"s": 27559,
"text": "How to Create Table in Hive?"
},
{
"code": null,
"e": 27632,
"s": 27588,
"text": "Hadoop - Schedulers and Types of Schedulers"
},
{
"code": null,
"e": 27651,
"s": 27632,
"text": "Hive - Alter Table"
},
{
"code": null,
"e": 27695,
"s": 27651,
"text": "Difference Between Hadoop 2.x vs Hadoop 3.x"
},
{
"code": null,
"e": 27739,
"s": 27695,
"text": "Hadoop - File Blocks and Replication Factor"
},
{
"code": null,
"e": 27757,
"s": 27739,
"text": "For Loop in Scala"
},
{
"code": null,
"e": 27780,
"s": 27757,
"text": "Scala | flatMap Method"
},
{
"code": null,
"e": 27801,
"s": 27780,
"text": "Scala | map() method"
},
{
"code": null,
"e": 27841,
"s": 27801,
"text": "Scala List filter() method with example"
}
] |
Beautiful Soup - Quick Guide | In today’s world, we have tons of unstructured data/information (mostly web data) available freely. Sometimes the freely available data is easy to read and sometimes not. No matter how your data is available, web scraping is very useful tool to transform unstructured data into structured data that is easier to read & analyze. In other words, one way to collect, organize and analyze this enormous amount of data is through web scraping. So let us first understand what is web-scraping.
Scraping is simply a process of extracting (from various means), copying and screening of data.
When we do scraping or extracting data or feeds from the web (like from web-pages or websites), it is termed as web-scraping.
So, web scraping which is also known as web data extraction or web harvesting is the extraction of data from web. In short, web scraping provides a way to the developers to collect and analyze data from the internet.
Web-scraping provides one of the great tools to automate most of the things a human does while browsing. Web-scraping is used in an enterprise in a variety of ways −
Smart analyst (like researcher or journalist) uses web scrapper instead of manually collecting and cleaning data from the websites.
Currently there are couple of services which use web scrappers to collect data from numerous online sites and use it to compare products popularity and prices.
There are numerous SEO tools such as Ahrefs, Seobility, SEMrush, etc., which are used for competitive analysis and for pulling data from your client’s websites.
There are some big IT companies whose business solely depends on web scraping.
The data gathered through web scraping can be used by marketers to analyze different niches and competitors or by the sales specialist for selling content marketing or social media promotion services.
Python is one of the most popular languages for web scraping as it can handle most of the web crawling related tasks very easily.
Below are some of the points on why to choose python for web scraping:
As most of the developers agree that python is very easy to code. We don’t have to use any curly braces “{ }” or semi-colons “;” anywhere, which makes it more readable and easy-to-use while developing web scrapers.
Python provides huge set of libraries for different requirements, so it is appropriate for web scraping as well as for data visualization, machine learning, etc.
Python is a very readable programming language as python syntax are easy to understand. Python is very expressive and code indentation helps the users to differentiate different blocks or scoopes in the code.
Python is a dynamically-typed language, which means the data assigned to a variable tells, what type of variable it is. It saves lot of time and makes work faster.
Python community is huge which helps you wherever you stuck while writing code.
The Beautiful Soup is a python library which is named after a Lewis Carroll poem of the same name in “Alice’s Adventures in the Wonderland”. Beautiful Soup is a python package and as the name suggests, parses the unwanted data and helps to organize and format the messy web data by fixing bad HTML and present to us in an easily-traversible XML structures.
In short, Beautiful Soup is a python package which allows us to pull data out of HTML and XML documents.
As BeautifulSoup is not a standard python library, we need to install it first. We are going to install the BeautifulSoup 4 library (also known as BS4), which is the latest one.
To isolate our working environment so as not to disturb the existing setup, let us first create a virtual environment.
A virtual environment allows us to create an isolated working copy of python for a specific project without affecting the outside setup.
Best way to install any python package machine is using pip, however, if pip is not installed already (you can check it using – “pip –version” in your command or shell prompt), you can install by giving below command −
$sudo apt-get install python-pip
To install pip in windows, do the following −
Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer.
Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer.
Open the command prompt and navigate to the folder containing get-pip.py file.
Open the command prompt and navigate to the folder containing get-pip.py file.
Run the following command −
Run the following command −
>python get-pip.py
That’s it, pip is now installed in your windows machine.
You can verify your pip installed by running below command −
>pip --version
pip 19.2.3 from c:\users\yadur\appdata\local\programs\python\python37\lib\site-packages\pip (python 3.7)
Run the below command in your command prompt −
>pip install virtualenv
After running, you will see the below screenshot −
Below command will create a virtual environment (“myEnv”) in your current directory −
>virtualenv myEnv
To activate your virtual environment, run the following command −
>myEnv\Scripts\activate
In the above screenshot, you can see we have “myEnv” as prefix which tells us that we are under virtual environment “myEnv”.
To come out of virtual environment, run deactivate.
(myEnv) C:\Users\yadur>deactivate
C:\Users\yadur>
As our virtual environment is ready, now let us install beautifulsoup.
As BeautifulSoup is not a standard library, we need to install it. We are going to use the BeautifulSoup 4 package (known as bs4).
To install bs4 on Debian or Ubuntu linux using system package manager, run the below command −
$sudo apt-get install python-bs4 (for python 2.x)
$sudo apt-get install python3-bs4 (for python 3.x)
You can install bs4 using easy_install or pip (in case you find problem in installing using system packager).
$easy_install beautifulsoup4
$pip install beautifulsoup4
(You may need to use easy_install3 or pip3 respectively if you’re using python3)
To install beautifulsoup4 in windows is very simple, especially if you have pip already installed.
>pip install beautifulsoup4
So now beautifulsoup4 is installed in our machine. Let us talk about some problems encountered after installation.
On windows machine you might encounter, wrong version being installed error mainly through −
error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3.
error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3.
error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2.
error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2.
Best way to get out of above two situations is to re-install the BeautifulSoup again, completely removing existing installation.
If you get the SyntaxError “Invalid syntax” on the line ROOT_TAG_NAME = u’[document]’, then you need to convert the python 2 code to python 3, just by either installing the package −
$ python3 setup.py install
or by manually running python’s 2 to 3 conversion script on the bs4 directory −
$ 2to3-3.2 -w bs4
By default, Beautiful Soup supports the HTML parser included in Python’s standard library, however it also supports many external third party python parsers like lxml parser or html5lib parser.
To install lxml or html5lib parser, use the command −
$apt-get install python-lxml
$apt-get insall python-html5lib
$pip install lxml
$pip install html5lib
Generally, users use lxml for speed and it is recommended to use lxml or html5lib parser if you are using older version of python 2 (before 2.7.3 version) or python 3 (before 3.2.2) as python’s built-in HTML parser is not very good in handling older version.
It is time to test our Beautiful Soup package in one of the html pages (taking web page – https://www.tutorialspoint.com/index.htm, you can choose any-other web page you want) and extract some information from it.
In the below code, we are trying to extract the title from the webpage −
from bs4 import BeautifulSoup
import requests
url = "https://www.tutorialspoint.com/index.htm"
req = requests.get(url)
soup = BeautifulSoup(req.text, "html.parser")
print(soup.title)
<title>H2O, Colab, Theano, Flutter, KNime, Mean.js, Weka, Solidity, Org.Json, AWS QuickSight, JSON.Simple, Jackson Annotations, Passay, Boon, MuleSoft, Nagios, Matplotlib, Java NIO, PyTorch, SLF4J, Parallax Scrolling, Java Cryptography</title>
One common task is to extract all the URLs within a webpage. For that we just need to add the below line of code −
for link in soup.find_all('a'):
print(link.get('href'))
https://www.tutorialspoint.com/index.htm
https://www.tutorialspoint.com/about/about_careers.htm
https://www.tutorialspoint.com/questions/index.php
https://www.tutorialspoint.com/online_dev_tools.htm
https://www.tutorialspoint.com/codingground.htm
https://www.tutorialspoint.com/current_affairs.htm
https://www.tutorialspoint.com/upsc_ias_exams.htm
https://www.tutorialspoint.com/tutor_connect/index.php
https://www.tutorialspoint.com/whiteboard.htm
https://www.tutorialspoint.com/netmeeting.php
https://www.tutorialspoint.com/index.htm
https://www.tutorialspoint.com/tutorialslibrary.htm
https://www.tutorialspoint.com/videotutorials/index.php
https://store.tutorialspoint.com
https://www.tutorialspoint.com/gate_exams_tutorials.htm
https://www.tutorialspoint.com/html_online_training/index.asp
https://www.tutorialspoint.com/css_online_training/index.asp
https://www.tutorialspoint.com/3d_animation_online_training/index.asp
https://www.tutorialspoint.com/swift_4_online_training/index.asp
https://www.tutorialspoint.com/blockchain_online_training/index.asp
https://www.tutorialspoint.com/reactjs_online_training/index.asp
https://www.tutorix.com
https://www.tutorialspoint.com/videotutorials/top-courses.php
https://www.tutorialspoint.com/the_full_stack_web_development/index.asp
....
....
https://www.tutorialspoint.com/online_dev_tools.htm
https://www.tutorialspoint.com/free_web_graphics.htm
https://www.tutorialspoint.com/online_file_conversion.htm
https://www.tutorialspoint.com/netmeeting.php
https://www.tutorialspoint.com/free_online_whiteboard.htm
http://www.tutorialspoint.com
https://www.facebook.com/tutorialspointindia
https://plus.google.com/u/0/+tutorialspoint
http://www.twitter.com/tutorialspoint
http://www.linkedin.com/company/tutorialspoint
https://www.youtube.com/channel/UCVLbzhxVTiTLiVKeGV7WEBg
https://www.tutorialspoint.com/index.htm
/about/about_privacy.htm#cookies
/about/faq.htm
/about/about_helping.htm
/about/contact_us.htm
Similarly, we can extract useful information using beautifulsoup4.
Now let us understand more about “soup” in above example.
In the previous code example, we parse the document through beautiful constructor using a string method. Another way is to pass the document through open filehandle.
from bs4 import BeautifulSoup
with open("example.html") as fp:
soup = BeautifulSoup(fp)
soup = BeautifulSoup("<html>data</html>")
First the document is converted to Unicode, and HTML entities are converted to Unicode characters:</p>
import bs4
html = '''<b>tutorialspoint</b>, <i>&web scraping &data science;</i>'''
soup = bs4.BeautifulSoup(html, 'lxml')
print(soup)
<html><body><b>tutorialspoint</b>, <i>&web scraping &data science;</i></body></html>
BeautifulSoup then parses the data using HTML parser or you explicitly tell it to parse using an XML parser.
Before we look into different components of a HTML page, let us first understand the HTML tree structure.
The root element in the document tree is the html, which can have parents, children and siblings and this determines by its position in the tree structure. To move among HTML elements, attributes and text, you have to move among nodes in your tree structure.
Let us suppose the webpage is as shown below −
Which translates to an html document as follows −
<html><head><title>TutorialsPoint</title></head><h1>Tutorialspoint Online Library</h1><p<<b>It's all Free</b></p></body></html>
Which simply means, for above html document, we have a html tree structure as follows −
When we passed a html document or string to a beautifulsoup constructor, beautifulsoup basically converts a complex html page into different python objects. Below we are going to discuss four major kinds of objects:
Tag
Tag
NavigableString
NavigableString
BeautifulSoup
BeautifulSoup
Comments
Comments
A HTML tag is used to define various types of content. A tag object in BeautifulSoup corresponds to an HTML or XML tag in the actual page or document.
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('<b class="boldest">TutorialsPoint</b>')
>>> tag = soup.html
>>> type(tag)
<class 'bs4.element.Tag'>
Tags contain lot of attributes and methods and two important features of a tag are its name and attributes.
Every tag contains a name and can be accessed through ‘.name’ as suffix. tag.name will return the type of tag it is.
>>> tag.name
'html'
However, if we change the tag name, same will be reflected in the HTML markup generated by the BeautifulSoup.
>>> tag.name = "Strong"
>>> tag
<Strong><body><b class="boldest">TutorialsPoint</b></body></Strong>
>>> tag.name
'Strong'
A tag object can have any number of attributes. The tag <b class=”boldest”> has an attribute ‘class’ whose value is “boldest”. Anything that is NOT tag, is basically an attribute and must contain a value. You can access the attributes either through accessing the keys (like accessing “class” in above example) or directly accessing through “.attrs”
>>> tutorialsP = BeautifulSoup("<div class='tutorialsP'></div>",'lxml')
>>> tag2 = tutorialsP.div
>>> tag2['class']
['tutorialsP']
We can do all kind of modifications to our tag’s attributes (add/remove/modify).
>>> tag2['class'] = 'Online-Learning'
>>> tag2['style'] = '2007'
>>>
>>> tag2
<div class="Online-Learning" style="2007"></div>
>>> del tag2['style']
>>> tag2
<div class="Online-Learning"></div>
>>> del tag['class']
>>> tag
<b SecondAttribute="2">TutorialsPoint</b>
>>>
>>> del tag['SecondAttribute']
>>> tag
</b>
>>> tag2['class']
'Online-Learning'
>>> tag2['style']
KeyError: 'style'
Some of the HTML5 attributes can have multiple values. Most commonly used is the class-attribute which can have multiple CSS-values. Others include ‘rel’, ‘rev’, ‘headers’, ‘accesskey’ and ‘accept-charset’. The multi-valued attributes in beautiful soup are shown as list.
>>> from bs4 import BeautifulSoup
>>>
>>> css_soup = BeautifulSoup('<p class="body"></p>')
>>> css_soup.p['class']
['body']
>>>
>>> css_soup = BeautifulSoup('<p class="body bold"></p>')
>>> css_soup.p['class']
['body', 'bold']
However, if any attribute contains more than one value but it is not multi-valued attributes by any-version of HTML standard, beautiful soup will leave the attribute alone −
>>> id_soup = BeautifulSoup('<p id="body bold"></p>')
>>> id_soup.p['id']
'body bold'
>>> type(id_soup.p['id'])
<class 'str'>
You can consolidate multiple attribute values if you turn a tag to a string.
>>> rel_soup = BeautifulSoup("<p> tutorialspoint Main <a rel='Index'> Page</a></p>")
>>> rel_soup.a['rel']
['Index']
>>> rel_soup.a['rel'] = ['Index', ' Online Library, Its all Free']
>>> print(rel_soup.p)
<p> tutorialspoint Main <a rel="Index Online Library, Its all Free"> Page</a></p>
By using ‘get_attribute_list’, you get a value that is always a list, string, irrespective of whether it is a multi-valued or not.
id_soup.p.get_attribute_list(‘id’)
However, if you parse the document as ‘xml’, there are no multi-valued attributes −
>>> xml_soup = BeautifulSoup('<p class="body bold"></p>', 'xml')
>>> xml_soup.p['class']
'body bold'
The navigablestring object is used to represent the contents of a tag. To access the contents, use “.string” with tag.
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("<h2 id='message'>Hello, Tutorialspoint!</h2>")
>>>
>>> soup.string
'Hello, Tutorialspoint!'
>>> type(soup.string)
>
You can replace the string with another string but you can’t edit the existing string.
>>> soup = BeautifulSoup("<h2 id='message'>Hello, Tutorialspoint!</h2>")
>>> soup.string.replace_with("Online Learning!")
'Hello, Tutorialspoint!'
>>> soup.string
'Online Learning!'
>>> soup
<html><body><h2 id="message">Online Learning!</h2></body></html>
BeautifulSoup is the object created when we try to scrape a web resource. So, it is the complete document which we are trying to scrape. Most of the time, it is treated tag object.
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup("<h2 id='message'>Hello, Tutorialspoint!</h2>")
>>> type(soup)
<class 'bs4.BeautifulSoup'>
>>> soup.name
'[document]'
The comment object illustrates the comment part of the web document. It is just a special type of NavigableString.
>>> soup = BeautifulSoup('<p><!-- Everything inside it is COMMENTS --></p>')
>>> comment = soup.p.string
>>> type(comment)
<class 'bs4.element.Comment'>
>>> type(comment)
<class 'bs4.element.Comment'>
>>> print(soup.p.prettify())
<p>
<!-- Everything inside it is COMMENTS -->
</p>
The navigablestring objects are used to represent text within tags, rather than the tags themselves.
In this chapter, we shall discuss about Navigating by Tags.
Below is our html document −
>>> html_doc = """
<html><head><title>Tutorials Point</title></head>
<body>
<p class="title"><b>The Biggest Online Tutorials Library, It's all Free</b></p>
<p class="prog">Top 5 most used Programming Languages are:
<a href="https://www.tutorialspoint.com/java/java_overview.htm" class="prog" id="link1">Java</a>,
<a href="https://www.tutorialspoint.com/cprogramming/index.htm" class="prog" id="link2">C</a>,
<a href="https://www.tutorialspoint.com/python/index.htm" class="prog" id="link3">Python</a>,
<a href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" class="prog" id="link4">JavaScript</a> and
<a href="https://www.tutorialspoint.com/ruby/index.htm" class="prog" id="link5">C</a>;
as per online survey.</p>
<p class="prog">Programming Languages</p>
"""
>>>
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup(html_doc, 'html.parser')
>>>
Based on the above document, we will try to move from one part of document to another.
One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children.
Easiest way to search a parse tree is to search the tag by its name. If you want the <head> tag, use soup.head −
>>> soup.head
<head>&t;title>Tutorials Point</title></head>
>>> soup.title
<title>Tutorials Point</title>
To get specific tag (like first <b> tag) in the <body> tag.
>>> soup.body.b
<b>The Biggest Online Tutorials Library, It's all Free</b>
Using a tag name as an attribute will give you only the first tag by that name −
>>> soup.a
<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>
To get all the tag’s attribute, you can use find_all() method −
>>> soup.find_all("a")
[<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>, <a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>, <a class="prog" href="https://www.tutorialspoint.com/python/index.htm" id="link3">Python</a>, <a class="prog" href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" id="link4">JavaScript</a>, <a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>]>>> soup.find_all("a")
[<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>, <a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>, <a class="prog" href="https://www.tutorialspoint.com/python/index.htm" id="link3">Python</a>, <a class="prog" href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" id="link4">JavaScript</a>, <a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>]
We can search tag’s children in a list by its .contents −
>>> head_tag = soup.head
>>> head_tag
<head><title>Tutorials Point</title></head>
>>> Htag = soup.head
>>> Htag
<head><title>Tutorials Point</title></head>
>>>
>>> Htag.contents
[<title>Tutorials Point</title>
>>>
>>> Ttag = head_tag.contents[0]
>>> Ttag
<title>Tutorials Point</title>
>>> Ttag.contents
['Tutorials Point']
The BeautifulSoup object itself has children. In this case, the <html> tag is the child of the BeautifulSoup object −
>>> len(soup.contents)
2
>>> soup.contents[1].name
'html'
A string does not have .contents, because it can’t contain anything −
>>> text = Ttag.contents[0]
>>> text.contents
self.__class__.__name__, attr))
AttributeError: 'NavigableString' object has no attribute 'contents'
Instead of getting them as a list, use .children generator to access tag’s children −
>>> for child in Ttag.children:
print(child)
Tutorials Point
The .descendants attribute allows you to iterate over all of a tag’s children, recursively −
its direct children and the children of its direct children and so on −
>>> for child in Htag.descendants:
print(child)
<title>Tutorials Point</title>
Tutorials Point
The <head> tag has only one child, but it has two descendants: the <title> tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −
>>> len(list(soup.children))
2
>>> len(list(soup.descendants))
33
If the tag has only one child, and that child is a NavigableString, the child is made available as .string −
>>> Ttag.string
'Tutorials Point'
If a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −
>>> Htag.contents
[<title>Tutorials Point</title>]
>>>
>>> Htag.string
'Tutorials Point'
However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −
>>> print(soup.html.string)
None
If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −
>>> for string in soup.strings:
print(repr(string))
'\n'
'Tutorials Point'
'\n'
'\n'
"The Biggest Online Tutorials Library, It's all Free"
'\n'
'Top 5 most used Programming Languages are: \n'
'Java'
',\n'
'C'
',\n'
'Python'
',\n'
'JavaScript'
' and\n'
'C'
';\n \nas per online survey.'
'\n'
'Programming Languages'
'\n'
To remove extra whitespace, use .stripped_strings generator −
>>> for string in soup.stripped_strings:
print(repr(string))
'Tutorials Point'
"The Biggest Online Tutorials Library, It's all Free"
'Top 5 most used Programming Languages are:'
'Java'
','
'C'
','
'Python'
','
'JavaScript'
'and'
'C'
';\n \nas per online survey.'
'Programming Languages'
In a “family tree” analogy, every tag and every string has a parent: the tag that contain it:
To access the element’s parent element, use .parent attribute.
>>> Ttag = soup.title
>>> Ttag
<title>Tutorials Point</title>
>>> Ttag.parent
<head>title>Tutorials Point</title></head>
In our html_doc, the title string itself has a parent: the <title> tag that contain it−
>>> Ttag.string.parent
<title>Tutorials Point</title>
The parent of a top-level tag like <html> is the Beautifulsoup object itself −
>>> htmltag = soup.html
>>> type(htmltag.parent)
<class 'bs4.BeautifulSoup'>
The .parent of a Beautifulsoup object is defined as None −
>>> print(soup.parent)
None
To iterate over all the parents elements, use .parents attribute.
>>> link = soup.a
>>> link
<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>
>>>
>>> for parent in link.parents:
if parent is None:
print(parent)
else:
print(parent.name)
p
body
html
[document]
Below is one simple document −
>>> sibling_soup = BeautifulSoup("<a><b>TutorialsPoint</b><c><strong>The Biggest Online Tutorials Library, It's all Free</strong></b></a>")
>>> print(sibling_soup.prettify())
<html>
<body>
<a>
<b>
TutorialsPoint
</b>
<c>
<strong>
The Biggest Online Tutorials Library, It's all Free
</strong>
</c>
</a>
</body>
</html>
In the above doc, <b> and <c> tag is at the same level and they are both children of the same tag. Both <b> and <c> tag are siblings.
Use .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:
>>> sibling_soup.b.next_sibling
<c><strong>The Biggest Online Tutorials Library, It's all Free</strong></c>
>>>
>>> sibling_soup.c.previous_sibling
<b>TutorialsPoint</b>
The <b> tag has a .next_sibling but no .previous_sibling, as there is nothing before the <b> tag on the same level of the tree, same case is with <c> tag.
>>> print(sibling_soup.b.previous_sibling)
None
>>> print(sibling_soup.c.next_sibling)
None
The two strings are not siblings, as they don’t have the same parent.
>>> sibling_soup.b.string
'TutorialsPoint'
>>>
>>> print(sibling_soup.b.string.next_sibling)
None
To iterate over a tag’s siblings use .next_siblings and .previous_siblings.
>>> for sibling in soup.a.next_siblings:
print(repr(sibling))
',\n'
<a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>
',\n'
>a class="prog" href="https://www.tutorialspoint.com/python/index.htm" id="link3">Python</a>
',\n'
<a class="prog" href="https://www.tutorialspoint.com/javascript/javascript_overview.htm" id="link4">JavaScript</a>
' and\n'
<a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm"
id="link5">C</a>
';\n \nas per online survey.'
>>> for sibling in soup.find(id="link3").previous_siblings:
print(repr(sibling))
',\n'
<a class="prog" href="https://www.tutorialspoint.com/cprogramming/index.htm" id="link2">C</a>
',\n'
<a class="prog" href="https://www.tutorialspoint.com/java/java_overview.htm" id="link1">Java</a>
'Top 5 most used Programming Languages are: \n'
Now let us get back to first two lines in our previous “html_doc” example −
&t;html><head><title>Tutorials Point</title></head>
<body>
<h4 class="tagLine"><b>The Biggest Online Tutorials Library, It's all Free</b></h4>
An HTML parser takes above string of characters and turns it into a series of events like “open an <html> tag”, “open an <head> tag”, “open the <title> tag”, “add a string”, “close the </title> tag”, “close the </head> tag”, “open a <h4> tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document.
The .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.
Below is the final <a> tag in our “html_doc” example document.
>>> last_a_tag = soup.find("a", id="link5")
>>> last_a_tag
<a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>
>>> last_a_tag.next_sibling
';\n \nas per online survey.'
However the .next_element of that <a> tag, the thing that was parsed immediately after the <a> tag, is not the rest of that sentence: it is the word “C”:
>>> last_a_tag.next_element
'C'
Above behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an <a> tag, then the letter “C”, then the closing </a> tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the <a> tag, but the letter “C” was encountered first.
The .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one.
>>> last_a_tag.previous_element
' and\n'
>>>
>>> last_a_tag.previous_element.next_element
<a class="prog" href="https://www.tutorialspoint.com/ruby/index.htm" id="link5">C</a>
We use these iterators to move forward and backward to an element.
>>> for element in last_a_tag.next_e lements:
print(repr(element))
'C'
';\n \nas per online survey.'
'\n'
<p class="prog">Programming Languages</p>
'Programming Languages'
'\n'
There are many Beautifulsoup methods, which allows us to search a parse tree. The two most common and used methods are find() and find_all().
Before talking about find() and find_all(), let us see some examples of different filters you can pass into these methods.
We have different filters which we can pass into these methods and understanding of these filters is crucial as these filters used again and again, throughout the search API. We can use these filters based on tag’s name, on its attributes, on the text of a string, or mixed of these.
One of the simplest types of filter is a string. Passing a string to the search method and Beautifulsoup will perform a match against that exact string.
Below code will find all the <p> tags in the document −
>>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>')
>>> markup.find_all('p')
[<p>Top Three</p>, <p></p>, <p><b>Java, Python, Cplusplus</b></p>]
You can find all tags starting with a given string/tag. Before that we need to import the re module to use regular expression.
>>> import re
>>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>')
>>>
>>> markup.find_all(re.compile('^p'))
[<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>]
You can pass multiple tags to find by providing a list. Below code finds all the <b> and <pre> tags −
>>> markup.find_all(['pre', 'b'])
[<pre>Programming Languages are:</pre>, <b>Java, Python, Cplusplus</b>]
True will return all tags that it can find, but no strings on their own −
>>> markup.find_all(True)
[<html><body><p>Top Three</p><p></p><pre>Programming Languages are:</pre>
<p><b>Java, Python, Cplusplus</b> </p> </body></html>,
<body><p>Top Three</p><p></p><pre> Programming Languages are:</pre><p><b>Java, Python, Cplusplus</b></p>
</body>,
<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>, <b>Java, Python, Cplusplus</b>]
To return only the tags from the above soup −
>>> for tag in markup.find_all(True):
(tag.name)
'html'
'body'
'p'
'p'
'pre'
'p'
'b'
You can use find_all to extract all the occurrences of a particular tag from the page response as −
find_all(name, attrs, recursive, string, limit, **kwargs)
Let us extract some interesting data from IMDB-“Top rated movies” of all time.
>>> url="https://www.imdb.com/chart/top/?ref_=nv_mv_250"
>>> content = requests.get(url)
>>> soup = BeautifulSoup(content.text, 'html.parser')
#Extract title Page
>>> print(soup.find('title'))
<title>IMDb Top 250 - IMDb</title>
#Extracting main heading
>>> for heading in soup.find_all('h1'):
print(heading.text)
Top Rated Movies
#Extracting sub-heading
>>> for heading in soup.find_all('h3'):
print(heading.text)
IMDb Charts
You Have Seen
IMDb Charts
Top India Charts
Top Rated Movies by Genre
Recently Viewed
From above, we can see find_all will give us all the items matching the search criteria we define. All the filters we can use with find_all() can be used with find() and other searching methods too like find_parents() or find_siblings().
We have seen above, find_all() is used to scan the entire document to find all the contents but something, the requirement is to find only one result. If you know that the document contains only one <body> tag, it is waste of time to search the entire document. One way is to call find_all() with limit=1 every time or else we can use find() method to do the same −
find(name, attrs, recursive, string, **kwargs)
So below two different methods gives the same output −
>>> soup.find_all('title',limit=1)
[<title>IMDb Top 250 - IMDb</title>]
>>>
>>> soup.find('title')
<title>IMDb Top 250 - IMDb</title>
In the above outputs, we can see the find_all() method returns a list containing single item whereas find() method returns single result.
Another difference between find() and find_all() method is −
>>> soup.find_all('h2')
[]
>>>
>>> soup.find('h2')
If soup.find_all() method can’t find anything, it returns empty list whereas find() returns None.
Unlike the find_all() and find() methods which traverse the tree, looking at tag’s descendents, find_parents() and find_parents methods() do the opposite, they traverse the tree upwards and look at a tag’s (or a string’s) parents.
find_parents(name, attrs, string, limit, **kwargs)
find_parent(name, attrs, string, **kwargs)
>>> a_string = soup.find(string="The Godfather")
>>> a_string
'The Godfather'
>>> a_string.find_parents('a')
[<a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a>]
>>> a_string.find_parent('a')
<a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a>
>>> a_string.find_parent('tr')
<tr>
<td class="posterColumn">
<span data-value="2" name="rk"></span>
<span data-value="9.149038526210072" name="ir"></span>
<span data-value="6.93792E10" name="us"></span>
<span data-value="1485540" name="nv"></span>
<span data-value="-1.850961473789928" name="ur"></span>
<a href="/title/tt0068646/"> <img alt="The Godfather" height="67" src="https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_UY67_CR1,0,45,67_AL_.jpg" width="45"/>
</a> </td>
<td class="titleColumn">
2.
<a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a>
<span class="secondaryInfo">(1972)</span>
</td>
<td class="ratingColumn imdbRating">
<strong title="9.1 based on 1,485,540 user ratings">9.1</strong>
</td>
<td class="ratingColumn">
<div class="seen-widget seen-widget-tt0068646 pending" data-titleid="tt0068646">
<div class="boundary">
<div class="popover">
<span class="delete"> </span><ol><li>1<li>2<li>3<li>4<li>5<li>6<li>7<li>8<li>9<li>10</li>0</li></li></li></li&td;</li></li></li></li></li></ol> </div>
</div>
<div class="inline">
<div class="pending"></div>
<div class="unseeable">NOT YET RELEASED</div>
<div class="unseen"> </div>
<div class="rating"></div>
<div class="seen">Seen</div>
</div>
</div>
</td>
<td class="watchlistColumn">
<div class="wlb_ribbon" data-recordmetrics="true" data-tconst="tt0068646"></div>
</td>
</tr>
>>>
>>> a_string.find_parents('td')
[<td class="titleColumn">
2.
<a href="/title/tt0068646/" title="Francis Ford Coppola (dir.), Marlon Brando, Al Pacino">The Godfather</a>
<span class="secondaryInfo">(1972)</span>
</td>]
There are eight other similar methods −
find_next_siblings(name, attrs, string, limit, **kwargs)
find_next_sibling(name, attrs, string, **kwargs)
find_previous_siblings(name, attrs, string, limit, **kwargs)
find_previous_sibling(name, attrs, string, **kwargs)
find_all_next(name, attrs, string, limit, **kwargs)
find_next(name, attrs, string, **kwargs)
find_all_previous(name, attrs, string, limit, **kwargs)
find_previous(name, attrs, string, **kwargs)
Where,
find_next_siblings() and find_next_sibling() methods will iterate over all the siblings of the element that come after the current one.
find_previous_siblings() and find_previous_sibling() methods will iterate over all the siblings that come before the current element.
find_all_next() and find_next() methods will iterate over all the tags and strings that come after the current element.
find_all_previous and find_previous() methods will iterate over all the tags and strings that come before the current element.
The BeautifulSoup library to support the most commonly-used CSS selectors. You can search for elements using CSS selectors with the help of the select() method.
Here are some examples −
>>> soup.select('title')
[<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>]
>>>
>>> soup.select("p:nth-of-type(1)")
[<p>The Top Rated Movie list only includes theatrical features.</p>, <p> class="imdb-footer__copyright _2-iNNCFskmr4l2OFN2DRsf">© 1990-2019 by IMDb.com, Inc.</p>]
>>> len(soup.select("p:nth-of-type(1)"))
2
>>> len(soup.select("a"))
609
>>> len(soup.select("p"))
2
>>> soup.select("html head title")
[<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>]
>>> soup.select("head > title")
[<title>IMDb Top 250 - IMDb</title>]
#print HTML code of the tenth li elemnet
>>> soup.select("li:nth-of-type(10)")
[<li class="subnav_item_main">
<a href="/search/title?genres=film_noir&sort=user_rating,desc&title_type=feature&num_votes=25000,">Film-Noir
</a> </li>]
One of the important aspects of BeautifulSoup is search the parse tree and it allows you to make changes to the web document according to your requirement. We can make changes to tag’s properties using its attributes, such as the .name, .string or .append() method. It allows you to add new tags and strings to an existing tag with the help of the .new_string() and .new_tag() methods. There are other methods too, such as .insert(), .insert_before() or .insert_after() to make various modification to your HTML or XML document.
Once you have created the soup, it is easy to make modification like renaming the tag, make modification to its attributes, add new attributes and delete attributes.
>>> soup = BeautifulSoup('<b class="bolder">Very Bold</b>')
>>> tag = soup.b
Modification and adding new attributes are as follows −
>>> tag.name = 'Blockquote'
>>> tag['class'] = 'Bolder'
>>> tag['id'] = 1.1
>>> tag
<Blockquote class="Bolder" id="1.1">Very Bold</Blockquote>
Deleting attributes are as follows −
>>> del tag['class']
>>> tag
<Blockquote id="1.1">Very Bold</Blockquote>
>>> del tag['id']
>>> tag
<Blockquote>Very Bold</Blockquote>
You can easily modify the tag’s .string attribute −
>>> markup = '<a href="https://www.tutorialspoint.com/index.htm">Must for every <i>Learner>/i<</a>'
>>> Bsoup = BeautifulSoup(markup)
>>> tag = Bsoup.a
>>> tag.string = "My Favourite spot."
>>> tag
<a href="https://www.tutorialspoint.com/index.htm">My Favourite spot.</a>
From above, we can see if the tag contains any other tag, they and all their contents will be replaced by new data.
Adding new data/contents to an existing tag is by using tag.append() method. It is very much similar to append() method in Python list.
>>> markup = '<a href="https://www.tutorialspoint.com/index.htm">Must for every <i>Learner</i></a>'
>>> Bsoup = BeautifulSoup(markup)
>>> Bsoup.a.append(" Really Liked it")
>>> Bsoup
<html><body><a href="https://www.tutorialspoint.com/index.htm">Must for every <i>Learner</i> Really Liked it</a></body></html>
>>> Bsoup.a.contents
['Must for every ', <i>Learner</i>, ' Really Liked it']
In case you want to add a string to a document, this can be done easily by using the append() or by NavigableString() constructor −
>>> soup = BeautifulSoup("<b></b>")
>>> tag = soup.b
>>> tag.append("Start")
>>>
>>> new_string = NavigableString(" Your")
>>> tag.append(new_string)
>>> tag
<b>Start Your</b>
>>> tag.contents
['Start', ' Your']
Note: If you find any name Error while accessing the NavigableString() function, as follows−
NameError: name 'NavigableString' is not defined
Just import the NavigableString directory from bs4 package −
>>> from bs4 import NavigableString
We can resolve the above error.
You can add comments to your existing tag’s or can add some other subclass of NavigableString, just call the constructor.
>>> from bs4 import Comment
>>> adding_comment = Comment("Always Learn something Good!")
>>> tag.append(adding_comment)
>>> tag
<b>Start Your<!--Always Learn something Good!--></b>
>>> tag.contents
['Start', ' Your', 'Always Learn something Good!']
Adding a whole new tag (not appending to an existing tag) can be done using the Beautifulsoup inbuilt method, BeautifulSoup.new_tag() −
>>> soup = BeautifulSoup("<b></b>")
>>> Otag = soup.b
>>>
>>> Newtag = soup.new_tag("a", href="https://www.tutorialspoint.com")
>>> Otag.append(Newtag)
>>> Otag
<b><a href="https://www.tutorialspoint.com"></a></b>
Only the first argument, the tag name, is required.
Similar to .insert() method on python list, tag.insert() will insert new element however, unlike tag.append(), new element doesn’t necessarily go at the end of its parent’s contents. New element can be added at any position.
>>> markup = '<a href="https://www.djangoproject.com/community/">Django Official website <i>Huge Community base</i></a>'
>>> soup = BeautifulSoup(markup)
>>> tag = soup.a
>>>
>>> tag.insert(1, "Love this framework ")
>>> tag
<a href="https://www.djangoproject.com/community/">Django Official website Love this framework <i>Huge Community base</i></a>
>>> tag.contents
['Django Official website ', 'Love this framework ', <i>Huge Community base</i
>]
>>>
To insert some tag or string just before something in the parse tree, we use insert_before() −
>>> soup = BeautifulSoup("Brave")
>>> tag = soup.new_tag("i")
>>> tag.string = "Be"
>>>
>>> soup.b.string.insert_before(tag)
>>> soup.b
<b><i>Be</i>Brave</b>
Similarly to insert some tag or string just after something in the parse tree, use insert_after().
>>> soup.b.i.insert_after(soup.new_string(" Always "))
>>> soup.b
<b><i>Be</i> Always Brave</b>
>>> soup.b.contents
[<i>Be</i>, ' Always ', 'Brave']
To remove the contents of a tag, use tag.clear() −
>>> markup = '<a href="https://www.tutorialspoint.com/index.htm">For <i>technical & Non-technical&lr;/i> Contents</a>'
>>> soup = BeautifulSoup(markup)
>>> tag = soup.a
>>> tag
<a href="https://www.tutorialspoint.com/index.htm">For <i>technical & Non-technical</i> Contents</a>
>>>
>>> tag.clear()
>>> tag
<a href="https://www.tutorialspoint.com/index.htm"></a>
To remove a tag or strings from the tree, use PageElement.extract().
>>> markup = '<a href="https://www.tutorialspoint.com/index.htm">For <i&gr;technical & Non-technical</i> Contents</a>'
>>> soup = BeautifulSoup(markup)
>>> a_tag = soup.a
>>>
>>> i_tag = soup.i.extract()
>>>
>>> a_tag
<a href="https://www.tutorialspoint.com/index.htm">For Contents</a>
>>>
>>> i_tag
<i>technical & Non-technical</i>
>>>
>>> print(i_tag.parent)
None
The tag.decompose() removes a tag from the tree and deletes all its contents.
>>> markup = '<a href="https://www.tutorialspoint.com/index.htm">For <i>technical & Non-technical</i> Contents</a>'
>>> soup = BeautifulSoup(markup)
>>> a_tag = soup.a
>>> a_tag
<a href="https://www.tutorialspoint.com/index.htm">For <i>technical & Non-technical</i> Contents</a>
>>>
>>> soup.i.decompose()
>>> a_tag
<a href="https://www.tutorialspoint.com/index.htm">For Contents</a>
>>>
As the name suggests, pageElement.replace_with() function will replace the old tag or string with the new tag or string in the tree −
>>> markup = '<a href="https://www.tutorialspoint.com/index.htm">Complete Python <i>Material</i></a>'
>>> soup = BeautifulSoup(markup)
>>> a_tag = soup.a
>>>
>>> new_tag = soup.new_tag("Official_site")
>>> new_tag.string = "https://www.python.org/"
>>> a_tag.i.replace_with(new_tag)
<i>Material</i>
>>>
>>> a_tag
<a href="https://www.tutorialspoint.com/index.htm">Complete Python <Official_site>https://www.python.org/</Official_site></a>
In the above output, you have noticed that replace_with() returns the tag or string that was replaced (like “Material” in our case), so you can examine it or add it back to another part of the tree.
The pageElement.wrap() enclosed an element in the tag you specify and returns a new wrapper −
>>> soup = BeautifulSoup("<p>tutorialspoint.com</p>")
>>> soup.p.string.wrap(soup.new_tag("b"))
<b>tutorialspoint.com</b>
>>>
>>> soup.p.wrap(soup.new_tag("Div"))
<Div><p><b>tutorialspoint.com</b></p></Div>
The tag.unwrap() is just opposite to wrap() and replaces a tag with whatever inside that tag.
>>> soup = BeautifulSoup('<a href="https://www.tutorialspoint.com/">I liked <i>tutorialspoint</i></a>')
>>> a_tag = soup.a
>>>
>>> a_tag.i.unwrap()
<i></i>
>>> a_tag
<a href="https://www.tutorialspoint.com/">I liked tutorialspoint</a>
From above, you have noticed that like replace_with(), unwrap() returns the tag that was replaced.
Below is one more example of unwrap() to understand it better −
>>> soup = BeautifulSoup("<p>I <strong>AM</strong> a <i>text</i>.</p>")
>>> soup.i.unwrap()
<i></i>
>>> soup
<html><body><p>I <strong>AM</strong> a text.</p></body></html>
unwrap() is good for striping out markup.
All HTML or XML documents are written in some specific encoding like ASCII or UTF-8. However, when you load that HTML/XML document into BeautifulSoup, it has been converted to Unicode.
>>> markup = "<p>I will display £</p>"
>>> Bsoup = BeautifulSoup(markup)
>>> Bsoup.p
<p>I will display £</p>
>>> Bsoup.p.string
'I will display £'
Above behavior is because BeautifulSoup internally uses the sub-library called Unicode, Dammit to detect a document’s encoding and then convert it into Unicode.
However, not all the time, the Unicode, Dammit guesses correctly. As the document is searched byte-by-byte to guess the encoding, it takes lot of time. You can save some time and avoid mistakes, if you already know the encoding by passing it to the BeautifulSoup constructor as from_encoding.
Below is one example where the BeautifulSoup misidentifies, an ISO-8859-8 document as ISO-8859-7 −
>>> markup = b"<h1>\xed\xe5\xec\xf9</h1>"
>>> soup = BeautifulSoup(markup)
>>> soup.h1
<h1>νεμω</h1>
>>> soup.original_encoding
'ISO-8859-7'
>>>
To resolve above issue, pass it to BeautifulSoup using from_encoding −
>>> soup = BeautifulSoup(markup, from_encoding="iso-8859-8")
>>> soup.h1
<h1>ולש </h1>
>>> soup.original_encoding
'iso-8859-8'
>>>
Another new feature added from BeautifulSoup 4.4.0 is, exclude_encoding. It can be used, when you don’t know the correct encoding but sure that Unicode, Dammit is showing wrong result.
>>> soup = BeautifulSoup(markup, exclude_encodings=["ISO-8859-7"])
The output from a BeautifulSoup is UTF-8 document, irrespective of the entered document to BeautifulSoup. Below a document, where the polish characters are there in ISO-8859-2 format.
html_markup = """
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<HTML>
<HEAD>
<META HTTP-EQUIV="content-type" CONTENT="text/html; charset=iso-8859-2">
</HEAD>
<BODY>
ą ć ę ł ń ó ś ź ż Ą Ć Ę Ł Ń Ó Ś Ź Ż
</BODY>
</HTML>
"""
>>> soup = BeautifulSoup(html_markup)
>>> print(soup.prettify())
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="content-type"/>
</head>
<body>
ą ć ę ł ń ó ś ź ż Ą Ć Ę Ł Ń Ó Ś Ź Ż
</body>
</html>
In the above example, if you notice, the <meta> tag has been rewritten to reflect the generated document from BeautifulSoup is now in UTF-8 format.
If you don’t want the generated output in UTF-8, you can assign the desired encoding in prettify().
>>> print(soup.prettify("latin-1"))
b'<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">\n<html>\n <head>\n <meta content="text/html; charset=latin-1" http-equiv="content-type"/>\n </head>\n <body>\n ą ć ę ł ń \xf3 ś ź ż Ą Ć Ę Ł Ń \xd3 Ś Ź Ż\n </body>\n</html>\n'
In the above example, we have encoded the complete document, however you can encode, any particular element in the soup as if they were a python string −
>>> soup.p.encode("latin-1")
b'<p>0My first paragraph.</p>'
>>> soup.h1.encode("latin-1")
b'<h1>My First Heading</h1>'
Any characters that can’t be represented in your chosen encoding will be converted into numeric XML entity references. Below is one such example −
>>> markup = u"<b>\N{SNOWMAN}</b>"
>>> snowman_soup = BeautifulSoup(markup)
>>> tag = snowman_soup.b
>>> print(tag.encode("utf-8"))
b'<b>\xe2\x98\x83</b>'
If you try to encode the above in “latin-1” or “ascii”, it will generate “☃”, indicating there is no representation for that.
>>> print (tag.encode("latin-1"))
b'<b>☃</b>'
>>> print (tag.encode("ascii"))
b'<b>☃</b>'
Unicode, Dammit is used mainly when the incoming document is in unknown format (mainly foreign language) and we want to encode in some known format (Unicode) and also we don’t need Beautifulsoup to do all this.
The starting point of any BeautifulSoup project, is the BeautifulSoup object. A BeautifulSoup object represents the input HTML/XML document used for its creation.
We can either pass a string or a file-like object for Beautiful Soup, where files (objects) are either locally stored in our machine or a web page.
The most common BeautifulSoup Objects are −
Tag
NavigableString
BeautifulSoup
Comment
As per the beautiful soup, two navigable string or tag objects are equal if they represent the same HTML/XML markup.
Now let us see the below example, where the two <b> tags are treated as equal, even though they live in different parts of the object tree, because they both look like “<b>Java</b>”.
>>> markup = "<p>Learn Python and <b>Java</b> and advanced <b>Java</b>! from Tutorialspoint</p>"
>>> soup = BeautifulSoup(markup, "html.parser")
>>> first_b, second_b = soup.find_all('b')
>>> print(first_b == second_b)
True
>>> print(first_b.previous_element == second_b.previous_element)
False
However, to check if the two variables refer to the same objects, you can use the following−
>>> print(first_b is second_b)
False
To create a copy of any tag or NavigableString, use copy.copy() function, just like below −
>>> import copy
>>> p_copy = copy.copy(soup.p)
>>> print(p_copy)
<p>Learn Python and <b>Java</b> and advanced <b>Java</b>! from Tutorialspoint</p>
>>>
Although the two copies (original and copied one) contain the same markup however, the two do not represent the same object −
>>> print(soup.p == p_copy)
True
>>>
>>> print(soup.p is p_copy)
False
>>>
The only real difference is that the copy is completely detached from the original Beautiful Soup object tree, just as if extract() had been called on it.
>>> print(p_copy.parent)
None
Above behavior is due to two different tag objects which cannot occupy the same space at the same time.
There are multiple situations where you want to extract specific types of information (only <a> tags) using Beautifulsoup4. The SoupStrainer class in Beautifulsoup allows you to parse only specific part of an incoming document.
One way is to create a SoupStrainer and pass it on to the Beautifulsoup4 constructor as the parse_only argument.
A SoupStrainer tells BeautifulSoup what parts extract, and the parse tree consists of only these elements. If you narrow down your required information to a specific portion of the HTML, this will speed up your search result.
product = SoupStrainer('div',{'id': 'products_list'})
soup = BeautifulSoup(html,parse_only=product)
Above lines of code will parse only the titles from a product site, which might be inside a tag field.
Similarly, like above we can use other soupStrainer objects, to parse specific information from an HTML tag. Below are some of the examples −
from bs4 import BeautifulSoup, SoupStrainer
#Only "a" tags
only_a_tags = SoupStrainer("a")
#Will parse only the below mentioned "ids".
parse_only = SoupStrainer(id=["first", "third", "my_unique_id"])
soup = BeautifulSoup(my_document, "html.parser", parse_only=parse_only)
#parse only where string length is less than 10
def is_short_string(string):
return len(string) < 10
only_short_strings =SoupStrainer(string=is_short_string)
There are two main kinds of errors that need to be handled in BeautifulSoup. These two errors are not from your script but from the structure of the snippet because the BeautifulSoup API throws an error.
The two main errors are as follows −
It is caused when the dot notation doesn’t find a sibling tag to the current HTML tag. For example, you may have encountered this error, because of missing “anchor tag”, cost-key will throw an error as it traverses and requires an anchor tag.
This error occurs if the required HTML tag attribute is missing. For example, if we don’t have data-pid attribute in a snippet, the pid key will throw key-error.
To avoid the above two listed errors when parsing a result, that result will be bypassed to make sure that a malformed snippet isn’t inserted into the databases −
except(AttributeError, KeyError) as er:
pass
Whenever we find any difficulty in understanding what BeautifulSoup does to our document or HTML, simply pass it to the diagnose() function. On passing document file to the diagnose() function, we can show how list of different parser handles the document.
Below is one example to demonstrate the use of diagnose() function −
from bs4.diagnose import diagnose
with open("20 Books.html",encoding="utf8") as fp:
data = fp.read()
diagnose(data)
There are two main types of parsing errors. You might get an exception like HTMLParseError, when you feed your document to BeautifulSoup. You may also get an unexpected result, where the BeautifulSoup parse tree looks a lot different from the expected result from the parse document.
None of the parsing error is caused due to BeautifulSoup. It is because of external parser we use (html5lib, lxml) since BeautifulSoup doesn’t contain any parser code. One way to resolve above parsing error is to use another parser.
from HTMLParser import HTMLParser
try:
from HTMLParser import HTMLParseError
except ImportError, e:
# From python 3.5, HTMLParseError is removed. Since it can never be
# thrown in 3.5, we can just define our own class as a placeholder.
class HTMLParseError(Exception):
pass
Python built-in HTML parser causes two most common parse errors, HTMLParser.HTMLParserError: malformed start tag and HTMLParser.HTMLParserError: bad end tag and to resolve this, is to use another parser mainly: lxml or html5lib.
Another common type of unexpected behavior is that you can’t find a tag that you know is in the document. However, when you run the find_all() returns [] or find() returns None.
This may be due to python built-in HTML parser sometimes skips tags it doesn’t understand.
By default, BeautifulSoup package parses the documents as HTML, however, it is very easy-to-use and handle ill-formed XML in a very elegant manner using beautifulsoup4.
To parse the document as XML, you need to have lxml parser and you just need to pass the “xml” as the second argument to the Beautifulsoup constructor −
soup = BeautifulSoup(markup, "lxml-xml")
or
soup = BeautifulSoup(markup, "xml")
One common XML parsing error is −
AttributeError: 'NoneType' object has no attribute 'attrib'
This might happen in case, some element is missing or not defined while using find() or findall() function.
Given below are some of the other parsing errors we are going to discuss in this section −
Apart from the above mentioned parsing errors, you may encounter other parsing issues such as environmental issues where your script might work in one operating system but not in another operating system or may work in one virtual environment but not in another virtual environment or may not work outside the virtual environment. All these issues may be because the two environments have different parser libraries available.
It is recommended to know or check your default parser in your current working environment. You can check the current default parser available for the current working environment or else pass explicitly the required parser library as second arguments to the BeautifulSoup constructor.
As the HTML tags and attributes are case-insensitive, all three HTML parsers convert tag and attribute names to lowercase. However, if you want to preserve mixed-case or uppercase tags and attributes, then it is better to parse the document as XML.
Let us look into below code segment −
soup = BeautifulSoup(response, "html.parser")
print (soup)
UnicodeEncodeError: 'charmap' codec can't encode character '\u011f'
Above problem may be because of two main situations. You might be trying to print out a unicode character that your console doesn’t know how to display. Second, you are trying to write to a file and you pass in a Unicode character that’s not supported by your default encoding.
One way to resolve above problem is to encode the response text/character before making the soup to get the desired result, as follows −
responseTxt = response.text.encode('UTF-8')
It is caused by accessing tag[‘attr’] when the tag in question doesn’t define the attr attribute. Most common errors are: “KeyError: ‘href’” and “KeyError: ‘class’”. Use tag.get(‘attr’) if you are not sure attr is defined.
for item in soup.fetch('a'):
try:
if (item['href'].startswith('/') or "tutorialspoint" in item['href']):
(...)
except KeyError:
pass # or some other fallback action
You may encounter AttributeError as follows −
AttributeError: 'list' object has no attribute 'find_all'
The above error mainly occurs because you expected find_all() return a single tag or string. However, soup.find_all returns a python list of elements.
All you need to do is to iterate through the list and catch data from those elements.
38 Lectures
3.5 hours
Chandramouli Jayendran
22 Lectures
1 hours
TELCOMA Global
6 Lectures
1 hours
AlexanderSchlee
6 Lectures
1 hours
AlexanderSchlee
6 Lectures
1 hours
AlexanderSchlee
22 Lectures
4 hours
AlexanderSchlee
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2473,
"s": 1985,
"text": "In today’s world, we have tons of unstructured data/information (mostly web data) available freely. Sometimes the freely available data is easy to read and sometimes not. No matter how your data is available, web scraping is very useful tool to transform unstructured data into structured data that is easier to read & analyze. In other words, one way to collect, organize and analyze this enormous amount of data is through web scraping. So let us first understand what is web-scraping."
},
{
"code": null,
"e": 2569,
"s": 2473,
"text": "Scraping is simply a process of extracting (from various means), copying and screening of data."
},
{
"code": null,
"e": 2695,
"s": 2569,
"text": "When we do scraping or extracting data or feeds from the web (like from web-pages or websites), it is termed as web-scraping."
},
{
"code": null,
"e": 2912,
"s": 2695,
"text": "So, web scraping which is also known as web data extraction or web harvesting is the extraction of data from web. In short, web scraping provides a way to the developers to collect and analyze data from the internet."
},
{
"code": null,
"e": 3078,
"s": 2912,
"text": "Web-scraping provides one of the great tools to automate most of the things a human does while browsing. Web-scraping is used in an enterprise in a variety of ways −"
},
{
"code": null,
"e": 3210,
"s": 3078,
"text": "Smart analyst (like researcher or journalist) uses web scrapper instead of manually collecting and cleaning data from the websites."
},
{
"code": null,
"e": 3370,
"s": 3210,
"text": "Currently there are couple of services which use web scrappers to collect data from numerous online sites and use it to compare products popularity and prices."
},
{
"code": null,
"e": 3531,
"s": 3370,
"text": "There are numerous SEO tools such as Ahrefs, Seobility, SEMrush, etc., which are used for competitive analysis and for pulling data from your client’s websites."
},
{
"code": null,
"e": 3610,
"s": 3531,
"text": "There are some big IT companies whose business solely depends on web scraping."
},
{
"code": null,
"e": 3811,
"s": 3610,
"text": "The data gathered through web scraping can be used by marketers to analyze different niches and competitors or by the sales specialist for selling content marketing or social media promotion services."
},
{
"code": null,
"e": 3941,
"s": 3811,
"text": "Python is one of the most popular languages for web scraping as it can handle most of the web crawling related tasks very easily."
},
{
"code": null,
"e": 4012,
"s": 3941,
"text": "Below are some of the points on why to choose python for web scraping:"
},
{
"code": null,
"e": 4227,
"s": 4012,
"text": "As most of the developers agree that python is very easy to code. We don’t have to use any curly braces “{ }” or semi-colons “;” anywhere, which makes it more readable and easy-to-use while developing web scrapers."
},
{
"code": null,
"e": 4389,
"s": 4227,
"text": "Python provides huge set of libraries for different requirements, so it is appropriate for web scraping as well as for data visualization, machine learning, etc."
},
{
"code": null,
"e": 4598,
"s": 4389,
"text": "Python is a very readable programming language as python syntax are easy to understand. Python is very expressive and code indentation helps the users to differentiate different blocks or scoopes in the code."
},
{
"code": null,
"e": 4762,
"s": 4598,
"text": "Python is a dynamically-typed language, which means the data assigned to a variable tells, what type of variable it is. It saves lot of time and makes work faster."
},
{
"code": null,
"e": 4842,
"s": 4762,
"text": "Python community is huge which helps you wherever you stuck while writing code."
},
{
"code": null,
"e": 5199,
"s": 4842,
"text": "The Beautiful Soup is a python library which is named after a Lewis Carroll poem of the same name in “Alice’s Adventures in the Wonderland”. Beautiful Soup is a python package and as the name suggests, parses the unwanted data and helps to organize and format the messy web data by fixing bad HTML and present to us in an easily-traversible XML structures."
},
{
"code": null,
"e": 5304,
"s": 5199,
"text": "In short, Beautiful Soup is a python package which allows us to pull data out of HTML and XML documents."
},
{
"code": null,
"e": 5482,
"s": 5304,
"text": "As BeautifulSoup is not a standard python library, we need to install it first. We are going to install the BeautifulSoup 4 library (also known as BS4), which is the latest one."
},
{
"code": null,
"e": 5601,
"s": 5482,
"text": "To isolate our working environment so as not to disturb the existing setup, let us first create a virtual environment."
},
{
"code": null,
"e": 5738,
"s": 5601,
"text": "A virtual environment allows us to create an isolated working copy of python for a specific project without affecting the outside setup."
},
{
"code": null,
"e": 5957,
"s": 5738,
"text": "Best way to install any python package machine is using pip, however, if pip is not installed already (you can check it using – “pip –version” in your command or shell prompt), you can install by giving below command −"
},
{
"code": null,
"e": 5991,
"s": 5957,
"text": "$sudo apt-get install python-pip\n"
},
{
"code": null,
"e": 6037,
"s": 5991,
"text": "To install pip in windows, do the following −"
},
{
"code": null,
"e": 6140,
"s": 6037,
"text": "Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer."
},
{
"code": null,
"e": 6243,
"s": 6140,
"text": "Download the get-pip.py from https://bootstrap.pypa.io/get-pip.py or from the github to your computer."
},
{
"code": null,
"e": 6322,
"s": 6243,
"text": "Open the command prompt and navigate to the folder containing get-pip.py file."
},
{
"code": null,
"e": 6401,
"s": 6322,
"text": "Open the command prompt and navigate to the folder containing get-pip.py file."
},
{
"code": null,
"e": 6429,
"s": 6401,
"text": "Run the following command −"
},
{
"code": null,
"e": 6457,
"s": 6429,
"text": "Run the following command −"
},
{
"code": null,
"e": 6477,
"s": 6457,
"text": ">python get-pip.py\n"
},
{
"code": null,
"e": 6534,
"s": 6477,
"text": "That’s it, pip is now installed in your windows machine."
},
{
"code": null,
"e": 6595,
"s": 6534,
"text": "You can verify your pip installed by running below command −"
},
{
"code": null,
"e": 6715,
"s": 6595,
"text": ">pip --version\npip 19.2.3 from c:\\users\\yadur\\appdata\\local\\programs\\python\\python37\\lib\\site-packages\\pip (python 3.7)"
},
{
"code": null,
"e": 6762,
"s": 6715,
"text": "Run the below command in your command prompt −"
},
{
"code": null,
"e": 6787,
"s": 6762,
"text": ">pip install virtualenv\n"
},
{
"code": null,
"e": 6838,
"s": 6787,
"text": "After running, you will see the below screenshot −"
},
{
"code": null,
"e": 6924,
"s": 6838,
"text": "Below command will create a virtual environment (“myEnv”) in your current directory −"
},
{
"code": null,
"e": 6943,
"s": 6924,
"text": ">virtualenv myEnv\n"
},
{
"code": null,
"e": 7009,
"s": 6943,
"text": "To activate your virtual environment, run the following command −"
},
{
"code": null,
"e": 7034,
"s": 7009,
"text": ">myEnv\\Scripts\\activate\n"
},
{
"code": null,
"e": 7159,
"s": 7034,
"text": "In the above screenshot, you can see we have “myEnv” as prefix which tells us that we are under virtual environment “myEnv”."
},
{
"code": null,
"e": 7211,
"s": 7159,
"text": "To come out of virtual environment, run deactivate."
},
{
"code": null,
"e": 7261,
"s": 7211,
"text": "(myEnv) C:\\Users\\yadur>deactivate\nC:\\Users\\yadur>"
},
{
"code": null,
"e": 7332,
"s": 7261,
"text": "As our virtual environment is ready, now let us install beautifulsoup."
},
{
"code": null,
"e": 7463,
"s": 7332,
"text": "As BeautifulSoup is not a standard library, we need to install it. We are going to use the BeautifulSoup 4 package (known as bs4)."
},
{
"code": null,
"e": 7558,
"s": 7463,
"text": "To install bs4 on Debian or Ubuntu linux using system package manager, run the below command −"
},
{
"code": null,
"e": 7659,
"s": 7558,
"text": "$sudo apt-get install python-bs4 (for python 2.x)\n$sudo apt-get install python3-bs4 (for python 3.x)"
},
{
"code": null,
"e": 7769,
"s": 7659,
"text": "You can install bs4 using easy_install or pip (in case you find problem in installing using system packager)."
},
{
"code": null,
"e": 7826,
"s": 7769,
"text": "$easy_install beautifulsoup4\n$pip install beautifulsoup4"
},
{
"code": null,
"e": 7907,
"s": 7826,
"text": "(You may need to use easy_install3 or pip3 respectively if you’re using python3)"
},
{
"code": null,
"e": 8006,
"s": 7907,
"text": "To install beautifulsoup4 in windows is very simple, especially if you have pip already installed."
},
{
"code": null,
"e": 8035,
"s": 8006,
"text": ">pip install beautifulsoup4\n"
},
{
"code": null,
"e": 8150,
"s": 8035,
"text": "So now beautifulsoup4 is installed in our machine. Let us talk about some problems encountered after installation."
},
{
"code": null,
"e": 8243,
"s": 8150,
"text": "On windows machine you might encounter, wrong version being installed error mainly through −"
},
{
"code": null,
"e": 8362,
"s": 8243,
"text": "error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3."
},
{
"code": null,
"e": 8481,
"s": 8362,
"text": "error: ImportError “No module named HTMLParser”, then you must be running python 2 version of the code under Python 3."
},
{
"code": null,
"e": 8607,
"s": 8481,
"text": "error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2."
},
{
"code": null,
"e": 8733,
"s": 8607,
"text": "error: ImportError “No module named html.parser” error, then you must be running Python 3 version of the code under Python 2."
},
{
"code": null,
"e": 8862,
"s": 8733,
"text": "Best way to get out of above two situations is to re-install the BeautifulSoup again, completely removing existing installation."
},
{
"code": null,
"e": 9045,
"s": 8862,
"text": "If you get the SyntaxError “Invalid syntax” on the line ROOT_TAG_NAME = u’[document]’, then you need to convert the python 2 code to python 3, just by either installing the package −"
},
{
"code": null,
"e": 9073,
"s": 9045,
"text": "$ python3 setup.py install\n"
},
{
"code": null,
"e": 9153,
"s": 9073,
"text": "or by manually running python’s 2 to 3 conversion script on the bs4 directory −"
},
{
"code": null,
"e": 9172,
"s": 9153,
"text": "$ 2to3-3.2 -w bs4\n"
},
{
"code": null,
"e": 9366,
"s": 9172,
"text": "By default, Beautiful Soup supports the HTML parser included in Python’s standard library, however it also supports many external third party python parsers like lxml parser or html5lib parser."
},
{
"code": null,
"e": 9420,
"s": 9366,
"text": "To install lxml or html5lib parser, use the command −"
},
{
"code": null,
"e": 9481,
"s": 9420,
"text": "$apt-get install python-lxml\n$apt-get insall python-html5lib"
},
{
"code": null,
"e": 9521,
"s": 9481,
"text": "$pip install lxml\n$pip install html5lib"
},
{
"code": null,
"e": 9780,
"s": 9521,
"text": "Generally, users use lxml for speed and it is recommended to use lxml or html5lib parser if you are using older version of python 2 (before 2.7.3 version) or python 3 (before 3.2.2) as python’s built-in HTML parser is not very good in handling older version."
},
{
"code": null,
"e": 9994,
"s": 9780,
"text": "It is time to test our Beautiful Soup package in one of the html pages (taking web page – https://www.tutorialspoint.com/index.htm, you can choose any-other web page you want) and extract some information from it."
},
{
"code": null,
"e": 10067,
"s": 9994,
"text": "In the below code, we are trying to extract the title from the webpage −"
},
{
"code": null,
"e": 10250,
"s": 10067,
"text": "from bs4 import BeautifulSoup\nimport requests\nurl = \"https://www.tutorialspoint.com/index.htm\"\nreq = requests.get(url)\nsoup = BeautifulSoup(req.text, \"html.parser\")\nprint(soup.title)"
},
{
"code": null,
"e": 10495,
"s": 10250,
"text": "<title>H2O, Colab, Theano, Flutter, KNime, Mean.js, Weka, Solidity, Org.Json, AWS QuickSight, JSON.Simple, Jackson Annotations, Passay, Boon, MuleSoft, Nagios, Matplotlib, Java NIO, PyTorch, SLF4J, Parallax Scrolling, Java Cryptography</title>\n"
},
{
"code": null,
"e": 10610,
"s": 10495,
"text": "One common task is to extract all the URLs within a webpage. For that we just need to add the below line of code −"
},
{
"code": null,
"e": 10666,
"s": 10610,
"text": "for link in soup.find_all('a'):\nprint(link.get('href'))"
},
{
"code": null,
"e": 12623,
"s": 10666,
"text": "https://www.tutorialspoint.com/index.htm\nhttps://www.tutorialspoint.com/about/about_careers.htm\nhttps://www.tutorialspoint.com/questions/index.php\nhttps://www.tutorialspoint.com/online_dev_tools.htm\nhttps://www.tutorialspoint.com/codingground.htm\nhttps://www.tutorialspoint.com/current_affairs.htm\nhttps://www.tutorialspoint.com/upsc_ias_exams.htm\nhttps://www.tutorialspoint.com/tutor_connect/index.php\nhttps://www.tutorialspoint.com/whiteboard.htm\nhttps://www.tutorialspoint.com/netmeeting.php\nhttps://www.tutorialspoint.com/index.htm\nhttps://www.tutorialspoint.com/tutorialslibrary.htm\nhttps://www.tutorialspoint.com/videotutorials/index.php\nhttps://store.tutorialspoint.com\nhttps://www.tutorialspoint.com/gate_exams_tutorials.htm\nhttps://www.tutorialspoint.com/html_online_training/index.asp\nhttps://www.tutorialspoint.com/css_online_training/index.asp\nhttps://www.tutorialspoint.com/3d_animation_online_training/index.asp\nhttps://www.tutorialspoint.com/swift_4_online_training/index.asp\nhttps://www.tutorialspoint.com/blockchain_online_training/index.asp\nhttps://www.tutorialspoint.com/reactjs_online_training/index.asp\nhttps://www.tutorix.com\nhttps://www.tutorialspoint.com/videotutorials/top-courses.php\nhttps://www.tutorialspoint.com/the_full_stack_web_development/index.asp\n....\n....\nhttps://www.tutorialspoint.com/online_dev_tools.htm\nhttps://www.tutorialspoint.com/free_web_graphics.htm\nhttps://www.tutorialspoint.com/online_file_conversion.htm\nhttps://www.tutorialspoint.com/netmeeting.php\nhttps://www.tutorialspoint.com/free_online_whiteboard.htm\nhttp://www.tutorialspoint.com\nhttps://www.facebook.com/tutorialspointindia\nhttps://plus.google.com/u/0/+tutorialspoint\nhttp://www.twitter.com/tutorialspoint\nhttp://www.linkedin.com/company/tutorialspoint\nhttps://www.youtube.com/channel/UCVLbzhxVTiTLiVKeGV7WEBg\nhttps://www.tutorialspoint.com/index.htm\n/about/about_privacy.htm#cookies\n/about/faq.htm\n/about/about_helping.htm\n/about/contact_us.htm\n"
},
{
"code": null,
"e": 12690,
"s": 12623,
"text": "Similarly, we can extract useful information using beautifulsoup4."
},
{
"code": null,
"e": 12748,
"s": 12690,
"text": "Now let us understand more about “soup” in above example."
},
{
"code": null,
"e": 12914,
"s": 12748,
"text": "In the previous code example, we parse the document through beautiful constructor using a string method. Another way is to pass the document through open filehandle."
},
{
"code": null,
"e": 13047,
"s": 12914,
"text": "from bs4 import BeautifulSoup\nwith open(\"example.html\") as fp:\n soup = BeautifulSoup(fp)\nsoup = BeautifulSoup(\"<html>data</html>\")"
},
{
"code": null,
"e": 13151,
"s": 13047,
"text": "First the document is converted to Unicode, and HTML entities are converted to Unicode characters:</p>\n"
},
{
"code": null,
"e": 13285,
"s": 13151,
"text": "import bs4\nhtml = '''<b>tutorialspoint</b>, <i>&web scraping &data science;</i>'''\nsoup = bs4.BeautifulSoup(html, 'lxml')\nprint(soup)"
},
{
"code": null,
"e": 13371,
"s": 13285,
"text": "<html><body><b>tutorialspoint</b>, <i>&web scraping &data science;</i></body></html>\n"
},
{
"code": null,
"e": 13480,
"s": 13371,
"text": "BeautifulSoup then parses the data using HTML parser or you explicitly tell it to parse using an XML parser."
},
{
"code": null,
"e": 13586,
"s": 13480,
"text": "Before we look into different components of a HTML page, let us first understand the HTML tree structure."
},
{
"code": null,
"e": 13845,
"s": 13586,
"text": "The root element in the document tree is the html, which can have parents, children and siblings and this determines by its position in the tree structure. To move among HTML elements, attributes and text, you have to move among nodes in your tree structure."
},
{
"code": null,
"e": 13892,
"s": 13845,
"text": "Let us suppose the webpage is as shown below −"
},
{
"code": null,
"e": 13942,
"s": 13892,
"text": "Which translates to an html document as follows −"
},
{
"code": null,
"e": 14070,
"s": 13942,
"text": "<html><head><title>TutorialsPoint</title></head><h1>Tutorialspoint Online Library</h1><p<<b>It's all Free</b></p></body></html>"
},
{
"code": null,
"e": 14158,
"s": 14070,
"text": "Which simply means, for above html document, we have a html tree structure as follows −"
},
{
"code": null,
"e": 14374,
"s": 14158,
"text": "When we passed a html document or string to a beautifulsoup constructor, beautifulsoup basically converts a complex html page into different python objects. Below we are going to discuss four major kinds of objects:"
},
{
"code": null,
"e": 14378,
"s": 14374,
"text": "Tag"
},
{
"code": null,
"e": 14382,
"s": 14378,
"text": "Tag"
},
{
"code": null,
"e": 14398,
"s": 14382,
"text": "NavigableString"
},
{
"code": null,
"e": 14414,
"s": 14398,
"text": "NavigableString"
},
{
"code": null,
"e": 14428,
"s": 14414,
"text": "BeautifulSoup"
},
{
"code": null,
"e": 14442,
"s": 14428,
"text": "BeautifulSoup"
},
{
"code": null,
"e": 14451,
"s": 14442,
"text": "Comments"
},
{
"code": null,
"e": 14460,
"s": 14451,
"text": "Comments"
},
{
"code": null,
"e": 14611,
"s": 14460,
"text": "A HTML tag is used to define various types of content. A tag object in BeautifulSoup corresponds to an HTML or XML tag in the actual page or document."
},
{
"code": null,
"e": 14771,
"s": 14611,
"text": ">>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup('<b class=\"boldest\">TutorialsPoint</b>')\n>>> tag = soup.html\n>>> type(tag)\n<class 'bs4.element.Tag'>"
},
{
"code": null,
"e": 14879,
"s": 14771,
"text": "Tags contain lot of attributes and methods and two important features of a tag are its name and attributes."
},
{
"code": null,
"e": 14996,
"s": 14879,
"text": "Every tag contains a name and can be accessed through ‘.name’ as suffix. tag.name will return the type of tag it is."
},
{
"code": null,
"e": 15017,
"s": 14996,
"text": ">>> tag.name\n'html'\n"
},
{
"code": null,
"e": 15127,
"s": 15017,
"text": "However, if we change the tag name, same will be reflected in the HTML markup generated by the BeautifulSoup."
},
{
"code": null,
"e": 15249,
"s": 15127,
"text": ">>> tag.name = \"Strong\"\n>>> tag\n<Strong><body><b class=\"boldest\">TutorialsPoint</b></body></Strong>\n>>> tag.name\n'Strong'"
},
{
"code": null,
"e": 15599,
"s": 15249,
"text": "A tag object can have any number of attributes. The tag <b class=”boldest”> has an attribute ‘class’ whose value is “boldest”. Anything that is NOT tag, is basically an attribute and must contain a value. You can access the attributes either through accessing the keys (like accessing “class” in above example) or directly accessing through “.attrs”"
},
{
"code": null,
"e": 15730,
"s": 15599,
"text": ">>> tutorialsP = BeautifulSoup(\"<div class='tutorialsP'></div>\",'lxml')\n>>> tag2 = tutorialsP.div\n>>> tag2['class']\n['tutorialsP']"
},
{
"code": null,
"e": 15811,
"s": 15730,
"text": "We can do all kind of modifications to our tag’s attributes (add/remove/modify)."
},
{
"code": null,
"e": 16196,
"s": 15811,
"text": ">>> tag2['class'] = 'Online-Learning'\n>>> tag2['style'] = '2007'\n>>>\n>>> tag2\n<div class=\"Online-Learning\" style=\"2007\"></div>\n>>> del tag2['style']\n>>> tag2\n<div class=\"Online-Learning\"></div>\n>>> del tag['class']\n>>> tag\n<b SecondAttribute=\"2\">TutorialsPoint</b>\n>>>\n>>> del tag['SecondAttribute']\n>>> tag\n</b>\n>>> tag2['class']\n'Online-Learning'\n>>> tag2['style']\nKeyError: 'style'"
},
{
"code": null,
"e": 16468,
"s": 16196,
"text": "Some of the HTML5 attributes can have multiple values. Most commonly used is the class-attribute which can have multiple CSS-values. Others include ‘rel’, ‘rev’, ‘headers’, ‘accesskey’ and ‘accept-charset’. The multi-valued attributes in beautiful soup are shown as list."
},
{
"code": null,
"e": 16695,
"s": 16468,
"text": ">>> from bs4 import BeautifulSoup\n>>>\n>>> css_soup = BeautifulSoup('<p class=\"body\"></p>')\n>>> css_soup.p['class']\n['body']\n>>>\n>>> css_soup = BeautifulSoup('<p class=\"body bold\"></p>')\n>>> css_soup.p['class']\n['body', 'bold']"
},
{
"code": null,
"e": 16869,
"s": 16695,
"text": "However, if any attribute contains more than one value but it is not multi-valued attributes by any-version of HTML standard, beautiful soup will leave the attribute alone −"
},
{
"code": null,
"e": 16995,
"s": 16869,
"text": ">>> id_soup = BeautifulSoup('<p id=\"body bold\"></p>')\n>>> id_soup.p['id']\n'body bold'\n>>> type(id_soup.p['id'])\n<class 'str'>"
},
{
"code": null,
"e": 17072,
"s": 16995,
"text": "You can consolidate multiple attribute values if you turn a tag to a string."
},
{
"code": null,
"e": 17360,
"s": 17072,
"text": ">>> rel_soup = BeautifulSoup(\"<p> tutorialspoint Main <a rel='Index'> Page</a></p>\")\n>>> rel_soup.a['rel']\n['Index']\n>>> rel_soup.a['rel'] = ['Index', ' Online Library, Its all Free']\n>>> print(rel_soup.p)\n<p> tutorialspoint Main <a rel=\"Index Online Library, Its all Free\"> Page</a></p>"
},
{
"code": null,
"e": 17491,
"s": 17360,
"text": "By using ‘get_attribute_list’, you get a value that is always a list, string, irrespective of whether it is a multi-valued or not."
},
{
"code": null,
"e": 17527,
"s": 17491,
"text": "id_soup.p.get_attribute_list(‘id’)\n"
},
{
"code": null,
"e": 17611,
"s": 17527,
"text": "However, if you parse the document as ‘xml’, there are no multi-valued attributes −"
},
{
"code": null,
"e": 17712,
"s": 17611,
"text": ">>> xml_soup = BeautifulSoup('<p class=\"body bold\"></p>', 'xml')\n>>> xml_soup.p['class']\n'body bold'"
},
{
"code": null,
"e": 17831,
"s": 17712,
"text": "The navigablestring object is used to represent the contents of a tag. To access the contents, use “.string” with tag."
},
{
"code": null,
"e": 18007,
"s": 17831,
"text": ">>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup(\"<h2 id='message'>Hello, Tutorialspoint!</h2>\")\n>>>\n>>> soup.string\n'Hello, Tutorialspoint!'\n>>> type(soup.string)\n>"
},
{
"code": null,
"e": 18094,
"s": 18007,
"text": "You can replace the string with another string but you can’t edit the existing string."
},
{
"code": null,
"e": 18350,
"s": 18094,
"text": ">>> soup = BeautifulSoup(\"<h2 id='message'>Hello, Tutorialspoint!</h2>\")\n>>> soup.string.replace_with(\"Online Learning!\")\n'Hello, Tutorialspoint!'\n>>> soup.string\n'Online Learning!'\n>>> soup\n<html><body><h2 id=\"message\">Online Learning!</h2></body></html>"
},
{
"code": null,
"e": 18531,
"s": 18350,
"text": "BeautifulSoup is the object created when we try to scrape a web resource. So, it is the complete document which we are trying to scrape. Most of the time, it is treated tag object."
},
{
"code": null,
"e": 18708,
"s": 18531,
"text": ">>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup(\"<h2 id='message'>Hello, Tutorialspoint!</h2>\")\n>>> type(soup)\n<class 'bs4.BeautifulSoup'>\n>>> soup.name\n'[document]'"
},
{
"code": null,
"e": 18823,
"s": 18708,
"text": "The comment object illustrates the comment part of the web document. It is just a special type of NavigableString."
},
{
"code": null,
"e": 19104,
"s": 18823,
"text": ">>> soup = BeautifulSoup('<p><!-- Everything inside it is COMMENTS --></p>')\n>>> comment = soup.p.string\n>>> type(comment)\n<class 'bs4.element.Comment'>\n>>> type(comment)\n<class 'bs4.element.Comment'>\n>>> print(soup.p.prettify())\n<p>\n<!-- Everything inside it is COMMENTS -->\n</p>"
},
{
"code": null,
"e": 19205,
"s": 19104,
"text": "The navigablestring objects are used to represent text within tags, rather than the tags themselves."
},
{
"code": null,
"e": 19265,
"s": 19205,
"text": "In this chapter, we shall discuss about Navigating by Tags."
},
{
"code": null,
"e": 19294,
"s": 19265,
"text": "Below is our html document −"
},
{
"code": null,
"e": 20166,
"s": 19294,
"text": ">>> html_doc = \"\"\"\n<html><head><title>Tutorials Point</title></head>\n<body>\n<p class=\"title\"><b>The Biggest Online Tutorials Library, It's all Free</b></p>\n<p class=\"prog\">Top 5 most used Programming Languages are:\n<a href=\"https://www.tutorialspoint.com/java/java_overview.htm\" class=\"prog\" id=\"link1\">Java</a>,\n<a href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" class=\"prog\" id=\"link2\">C</a>,\n<a href=\"https://www.tutorialspoint.com/python/index.htm\" class=\"prog\" id=\"link3\">Python</a>,\n<a href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" class=\"prog\" id=\"link4\">JavaScript</a> and\n<a href=\"https://www.tutorialspoint.com/ruby/index.htm\" class=\"prog\" id=\"link5\">C</a>;\nas per online survey.</p>\n<p class=\"prog\">Programming Languages</p>\n\"\"\"\n>>>\n>>> from bs4 import BeautifulSoup\n>>> soup = BeautifulSoup(html_doc, 'html.parser')\n>>>"
},
{
"code": null,
"e": 20253,
"s": 20166,
"text": "Based on the above document, we will try to move from one part of document to another."
},
{
"code": null,
"e": 20473,
"s": 20253,
"text": "One of the important pieces of element in any piece of HTML document are tags, which may contain other tags/strings (tag’s children). Beautiful Soup provides different ways to navigate and iterate over’s tag’s children."
},
{
"code": null,
"e": 20586,
"s": 20473,
"text": "Easiest way to search a parse tree is to search the tag by its name. If you want the <head> tag, use soup.head −"
},
{
"code": null,
"e": 20692,
"s": 20586,
"text": ">>> soup.head\n<head>&t;title>Tutorials Point</title></head>\n>>> soup.title\n<title>Tutorials Point</title>"
},
{
"code": null,
"e": 20752,
"s": 20692,
"text": "To get specific tag (like first <b> tag) in the <body> tag."
},
{
"code": null,
"e": 20827,
"s": 20752,
"text": ">>> soup.body.b\n<b>The Biggest Online Tutorials Library, It's all Free</b>"
},
{
"code": null,
"e": 20908,
"s": 20827,
"text": "Using a tag name as an attribute will give you only the first tag by that name −"
},
{
"code": null,
"e": 21017,
"s": 20908,
"text": ">>> soup.a\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>\n"
},
{
"code": null,
"e": 21081,
"s": 21017,
"text": "To get all the tag’s attribute, you can use find_all() method −"
},
{
"code": null,
"e": 22108,
"s": 21081,
"text": ">>> soup.find_all(\"a\")\n[<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" id=\"link4\">JavaScript</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>]>>> soup.find_all(\"a\")\n[<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" id=\"link4\">JavaScript</a>, <a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>]"
},
{
"code": null,
"e": 22166,
"s": 22108,
"text": "We can search tag’s children in a list by its .contents −"
},
{
"code": null,
"e": 22490,
"s": 22166,
"text": ">>> head_tag = soup.head\n>>> head_tag\n<head><title>Tutorials Point</title></head>\n>>> Htag = soup.head\n>>> Htag\n<head><title>Tutorials Point</title></head>\n>>>\n>>> Htag.contents\n[<title>Tutorials Point</title>\n>>>\n>>> Ttag = head_tag.contents[0]\n>>> Ttag\n<title>Tutorials Point</title>\n>>> Ttag.contents\n['Tutorials Point']"
},
{
"code": null,
"e": 22608,
"s": 22490,
"text": "The BeautifulSoup object itself has children. In this case, the <html> tag is the child of the BeautifulSoup object −"
},
{
"code": null,
"e": 22666,
"s": 22608,
"text": ">>> len(soup.contents)\n2\n>>> soup.contents[1].name\n'html'"
},
{
"code": null,
"e": 22736,
"s": 22666,
"text": "A string does not have .contents, because it can’t contain anything −"
},
{
"code": null,
"e": 22883,
"s": 22736,
"text": ">>> text = Ttag.contents[0]\n>>> text.contents\nself.__class__.__name__, attr))\nAttributeError: 'NavigableString' object has no attribute 'contents'"
},
{
"code": null,
"e": 22969,
"s": 22883,
"text": "Instead of getting them as a list, use .children generator to access tag’s children −"
},
{
"code": null,
"e": 23031,
"s": 22969,
"text": ">>> for child in Ttag.children:\nprint(child)\nTutorials Point\n"
},
{
"code": null,
"e": 23124,
"s": 23031,
"text": "The .descendants attribute allows you to iterate over all of a tag’s children, recursively −"
},
{
"code": null,
"e": 23196,
"s": 23124,
"text": "its direct children and the children of its direct children and so on −"
},
{
"code": null,
"e": 23292,
"s": 23196,
"text": ">>> for child in Htag.descendants:\nprint(child)\n<title>Tutorials Point</title>\nTutorials Point\n"
},
{
"code": null,
"e": 23509,
"s": 23292,
"text": "The <head> tag has only one child, but it has two descendants: the <title> tag and the <title> tag’s child. The beautifulsoup object has only one direct child (the <html> tag), but it has a whole lot of descendants −"
},
{
"code": null,
"e": 23576,
"s": 23509,
"text": ">>> len(list(soup.children))\n2\n>>> len(list(soup.descendants))\n33\n"
},
{
"code": null,
"e": 23685,
"s": 23576,
"text": "If the tag has only one child, and that child is a NavigableString, the child is made available as .string −"
},
{
"code": null,
"e": 23720,
"s": 23685,
"text": ">>> Ttag.string\n'Tutorials Point'\n"
},
{
"code": null,
"e": 23860,
"s": 23720,
"text": "If a tag’s only child is another tag, and that tag has a .string, then the parent tag is considered to have the same .string as its child −"
},
{
"code": null,
"e": 23949,
"s": 23860,
"text": ">>> Htag.contents\n[<title>Tutorials Point</title>]\n>>>\n>>> Htag.string\n'Tutorials Point'"
},
{
"code": null,
"e": 24079,
"s": 23949,
"text": "However, if a tag contains more than one thing, then it’s not clear what .string should refer to, so .string is defined to None −"
},
{
"code": null,
"e": 24113,
"s": 24079,
"text": ">>> print(soup.html.string)\nNone\n"
},
{
"code": null,
"e": 24227,
"s": 24113,
"text": "If there’s more than one thing inside a tag, you can still look at just the strings. Use the .strings generator −"
},
{
"code": null,
"e": 24547,
"s": 24227,
"text": ">>> for string in soup.strings:\nprint(repr(string))\n'\\n'\n'Tutorials Point'\n'\\n'\n'\\n'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'\\n'\n'Top 5 most used Programming Languages are: \\n'\n'Java'\n',\\n'\n'C'\n',\\n'\n'Python'\n',\\n'\n'JavaScript'\n' and\\n'\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n'Programming Languages'\n'\\n'"
},
{
"code": null,
"e": 24609,
"s": 24547,
"text": "To remove extra whitespace, use .stripped_strings generator −"
},
{
"code": null,
"e": 24896,
"s": 24609,
"text": ">>> for string in soup.stripped_strings:\nprint(repr(string))\n'Tutorials Point'\n\"The Biggest Online Tutorials Library, It's all Free\"\n'Top 5 most used Programming Languages are:'\n'Java'\n','\n'C'\n','\n'Python'\n','\n'JavaScript'\n'and'\n'C'\n';\\n \\nas per online survey.'\n'Programming Languages'"
},
{
"code": null,
"e": 24990,
"s": 24896,
"text": "In a “family tree” analogy, every tag and every string has a parent: the tag that contain it:"
},
{
"code": null,
"e": 25053,
"s": 24990,
"text": "To access the element’s parent element, use .parent attribute."
},
{
"code": null,
"e": 25174,
"s": 25053,
"text": ">>> Ttag = soup.title\n>>> Ttag\n<title>Tutorials Point</title>\n>>> Ttag.parent\n<head>title>Tutorials Point</title></head>"
},
{
"code": null,
"e": 25262,
"s": 25174,
"text": "In our html_doc, the title string itself has a parent: the <title> tag that contain it−"
},
{
"code": null,
"e": 25317,
"s": 25262,
"text": ">>> Ttag.string.parent\n<title>Tutorials Point</title>\n"
},
{
"code": null,
"e": 25396,
"s": 25317,
"text": "The parent of a top-level tag like <html> is the Beautifulsoup object itself −"
},
{
"code": null,
"e": 25474,
"s": 25396,
"text": ">>> htmltag = soup.html\n>>> type(htmltag.parent)\n<class 'bs4.BeautifulSoup'>\n"
},
{
"code": null,
"e": 25533,
"s": 25474,
"text": "The .parent of a Beautifulsoup object is defined as None −"
},
{
"code": null,
"e": 25562,
"s": 25533,
"text": ">>> print(soup.parent)\nNone\n"
},
{
"code": null,
"e": 25628,
"s": 25562,
"text": "To iterate over all the parents elements, use .parents attribute."
},
{
"code": null,
"e": 25869,
"s": 25628,
"text": ">>> link = soup.a\n>>> link\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>\n>>>\n>>> for parent in link.parents:\nif parent is None:\nprint(parent)\nelse:\nprint(parent.name)\np\nbody\nhtml\n[document]"
},
{
"code": null,
"e": 25900,
"s": 25869,
"text": "Below is one simple document −"
},
{
"code": null,
"e": 26287,
"s": 25900,
"text": ">>> sibling_soup = BeautifulSoup(\"<a><b>TutorialsPoint</b><c><strong>The Biggest Online Tutorials Library, It's all Free</strong></b></a>\")\n>>> print(sibling_soup.prettify())\n<html>\n<body>\n <a>\n <b>\n TutorialsPoint\n </b>\n <c>\n <strong>\n The Biggest Online Tutorials Library, It's all Free\n </strong>\n </c>\n </a>\n</body>\n</html>"
},
{
"code": null,
"e": 26421,
"s": 26287,
"text": "In the above doc, <b> and <c> tag is at the same level and they are both children of the same tag. Both <b> and <c> tag are siblings."
},
{
"code": null,
"e": 26541,
"s": 26421,
"text": "Use .next_sibling and .previous_sibling to navigate between page elements that are on the same level of the parse tree:"
},
{
"code": null,
"e": 26711,
"s": 26541,
"text": ">>> sibling_soup.b.next_sibling\n<c><strong>The Biggest Online Tutorials Library, It's all Free</strong></c>\n>>>\n>>> sibling_soup.c.previous_sibling\n<b>TutorialsPoint</b>"
},
{
"code": null,
"e": 26866,
"s": 26711,
"text": "The <b> tag has a .next_sibling but no .previous_sibling, as there is nothing before the <b> tag on the same level of the tree, same case is with <c> tag."
},
{
"code": null,
"e": 26959,
"s": 26866,
"text": ">>> print(sibling_soup.b.previous_sibling)\nNone\n>>> print(sibling_soup.c.next_sibling)\nNone\n"
},
{
"code": null,
"e": 27029,
"s": 26959,
"text": "The two strings are not siblings, as they don’t have the same parent."
},
{
"code": null,
"e": 27127,
"s": 27029,
"text": ">>> sibling_soup.b.string\n'TutorialsPoint'\n>>>\n>>> print(sibling_soup.b.string.next_sibling)\nNone"
},
{
"code": null,
"e": 27203,
"s": 27127,
"text": "To iterate over a tag’s siblings use .next_siblings and .previous_siblings."
},
{
"code": null,
"e": 28042,
"s": 27203,
"text": ">>> for sibling in soup.a.next_siblings:\nprint(repr(sibling))\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>\n',\\n'\n>a class=\"prog\" href=\"https://www.tutorialspoint.com/python/index.htm\" id=\"link3\">Python</a>\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/javascript/javascript_overview.htm\" id=\"link4\">JavaScript</a>\n' and\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\"\nid=\"link5\">C</a>\n';\\n \\nas per online survey.'\n>>> for sibling in soup.find(id=\"link3\").previous_siblings:\nprint(repr(sibling))\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/cprogramming/index.htm\" id=\"link2\">C</a>\n',\\n'\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/java/java_overview.htm\" id=\"link1\">Java</a>\n'Top 5 most used Programming Languages are: \\n'"
},
{
"code": null,
"e": 28118,
"s": 28042,
"text": "Now let us get back to first two lines in our previous “html_doc” example −"
},
{
"code": null,
"e": 28261,
"s": 28118,
"text": "&t;html><head><title>Tutorials Point</title></head>\n<body>\n<h4 class=\"tagLine\"><b>The Biggest Online Tutorials Library, It's all Free</b></h4>"
},
{
"code": null,
"e": 28605,
"s": 28261,
"text": "An HTML parser takes above string of characters and turns it into a series of events like “open an <html> tag”, “open an <head> tag”, “open the <title> tag”, “add a string”, “close the </title> tag”, “close the </head> tag”, “open a <h4> tag” and so on. BeautifulSoup offers different methods to reconstructs the initial parse of the document."
},
{
"code": null,
"e": 28847,
"s": 28605,
"text": "The .next_element attribute of a tag or string points to whatever was parsed immediately afterwards. Sometimes it looks similar to .next_sibling, however it is not same entirely.\nBelow is the final <a> tag in our “html_doc” example document."
},
{
"code": null,
"e": 29050,
"s": 28847,
"text": ">>> last_a_tag = soup.find(\"a\", id=\"link5\")\n>>> last_a_tag\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>\n>>> last_a_tag.next_sibling\n';\\n \\nas per online survey.'"
},
{
"code": null,
"e": 29204,
"s": 29050,
"text": "However the .next_element of that <a> tag, the thing that was parsed immediately after the <a> tag, is not the rest of that sentence: it is the word “C”:"
},
{
"code": null,
"e": 29237,
"s": 29204,
"text": ">>> last_a_tag.next_element\n'C'\n"
},
{
"code": null,
"e": 29555,
"s": 29237,
"text": "Above behavior is because in the original markup, the letter “C” appeared before that semicolon. The parser encountered an <a> tag, then the letter “C”, then the closing </a> tag, then the semicolon and rest of the sentence. The semicolon is on the same level as the <a> tag, but the letter “C” was encountered first."
},
{
"code": null,
"e": 29697,
"s": 29555,
"text": "The .previous_element attribute is the exact opposite of .next_element. It points to whatever element was parsed immediately before this one."
},
{
"code": null,
"e": 29873,
"s": 29697,
"text": ">>> last_a_tag.previous_element\n' and\\n'\n>>>\n>>> last_a_tag.previous_element.next_element\n<a class=\"prog\" href=\"https://www.tutorialspoint.com/ruby/index.htm\" id=\"link5\">C</a>"
},
{
"code": null,
"e": 29940,
"s": 29873,
"text": "We use these iterators to move forward and backward to an element."
},
{
"code": null,
"e": 30118,
"s": 29940,
"text": ">>> for element in last_a_tag.next_e lements:\nprint(repr(element))\n'C'\n';\\n \\nas per online survey.'\n'\\n'\n<p class=\"prog\">Programming Languages</p>\n'Programming Languages'\n'\\n'\n"
},
{
"code": null,
"e": 30260,
"s": 30118,
"text": "There are many Beautifulsoup methods, which allows us to search a parse tree. The two most common and used methods are find() and find_all()."
},
{
"code": null,
"e": 30383,
"s": 30260,
"text": "Before talking about find() and find_all(), let us see some examples of different filters you can pass into these methods."
},
{
"code": null,
"e": 30667,
"s": 30383,
"text": "We have different filters which we can pass into these methods and understanding of these filters is crucial as these filters used again and again, throughout the search API. We can use these filters based on tag’s name, on its attributes, on the text of a string, or mixed of these."
},
{
"code": null,
"e": 30820,
"s": 30667,
"text": "One of the simplest types of filter is a string. Passing a string to the search method and Beautifulsoup will perform a match against that exact string."
},
{
"code": null,
"e": 30876,
"s": 30820,
"text": "Below code will find all the <p> tags in the document −"
},
{
"code": null,
"e": 31096,
"s": 30876,
"text": ">>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>')\n>>> markup.find_all('p')\n[<p>Top Three</p>, <p></p>, <p><b>Java, Python, Cplusplus</b></p>]"
},
{
"code": null,
"e": 31223,
"s": 31096,
"text": "You can find all tags starting with a given string/tag. Before that we need to import the re module to use regular expression."
},
{
"code": null,
"e": 31513,
"s": 31223,
"text": ">>> import re\n>>> markup = BeautifulSoup('<p>Top Three</p><p><pre>Programming Languages are:</pre></p><p><b>Java, Python, Cplusplus</b></p>')\n>>>\n>>> markup.find_all(re.compile('^p'))\n[<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>]"
},
{
"code": null,
"e": 31615,
"s": 31513,
"text": "You can pass multiple tags to find by providing a list. Below code finds all the <b> and <pre> tags −"
},
{
"code": null,
"e": 31722,
"s": 31615,
"text": ">>> markup.find_all(['pre', 'b'])\n[<pre>Programming Languages are:</pre>, <b>Java, Python, Cplusplus</b>]\n"
},
{
"code": null,
"e": 31796,
"s": 31722,
"text": "True will return all tags that it can find, but no strings on their own −"
},
{
"code": null,
"e": 32204,
"s": 31796,
"text": ">>> markup.find_all(True)\n[<html><body><p>Top Three</p><p></p><pre>Programming Languages are:</pre>\n<p><b>Java, Python, Cplusplus</b> </p> </body></html>, \n<body><p>Top Three</p><p></p><pre> Programming Languages are:</pre><p><b>Java, Python, Cplusplus</b></p>\n</body>, \n<p>Top Three</p>, <p></p>, <pre>Programming Languages are:</pre>, <p><b>Java, Python, Cplusplus</b></p>, <b>Java, Python, Cplusplus</b>]"
},
{
"code": null,
"e": 32250,
"s": 32204,
"text": "To return only the tags from the above soup −"
},
{
"code": null,
"e": 32336,
"s": 32250,
"text": ">>> for tag in markup.find_all(True):\n(tag.name)\n'html'\n'body'\n'p'\n'p'\n'pre'\n'p'\n'b'\n"
},
{
"code": null,
"e": 32436,
"s": 32336,
"text": "You can use find_all to extract all the occurrences of a particular tag from the page response as −"
},
{
"code": null,
"e": 32495,
"s": 32436,
"text": "find_all(name, attrs, recursive, string, limit, **kwargs)\n"
},
{
"code": null,
"e": 32574,
"s": 32495,
"text": "Let us extract some interesting data from IMDB-“Top rated movies” of all time."
},
{
"code": null,
"e": 33103,
"s": 32574,
"text": ">>> url=\"https://www.imdb.com/chart/top/?ref_=nv_mv_250\"\n>>> content = requests.get(url)\n>>> soup = BeautifulSoup(content.text, 'html.parser')\n#Extract title Page\n>>> print(soup.find('title'))\n<title>IMDb Top 250 - IMDb</title>\n\n#Extracting main heading\n>>> for heading in soup.find_all('h1'):\n print(heading.text)\nTop Rated Movies\n\n#Extracting sub-heading\n>>> for heading in soup.find_all('h3'):\n print(heading.text)\n \nIMDb Charts\nYou Have Seen\n IMDb Charts\n Top India Charts\nTop Rated Movies by Genre\nRecently Viewed"
},
{
"code": null,
"e": 33341,
"s": 33103,
"text": "From above, we can see find_all will give us all the items matching the search criteria we define. All the filters we can use with find_all() can be used with find() and other searching methods too like find_parents() or find_siblings()."
},
{
"code": null,
"e": 33707,
"s": 33341,
"text": "We have seen above, find_all() is used to scan the entire document to find all the contents but something, the requirement is to find only one result. If you know that the document contains only one <body> tag, it is waste of time to search the entire document. One way is to call find_all() with limit=1 every time or else we can use find() method to do the same −"
},
{
"code": null,
"e": 33755,
"s": 33707,
"text": "find(name, attrs, recursive, string, **kwargs)\n"
},
{
"code": null,
"e": 33810,
"s": 33755,
"text": "So below two different methods gives the same output −"
},
{
"code": null,
"e": 33944,
"s": 33810,
"text": ">>> soup.find_all('title',limit=1)\n[<title>IMDb Top 250 - IMDb</title>]\n>>>\n>>> soup.find('title')\n<title>IMDb Top 250 - IMDb</title>"
},
{
"code": null,
"e": 34082,
"s": 33944,
"text": "In the above outputs, we can see the find_all() method returns a list containing single item whereas find() method returns single result."
},
{
"code": null,
"e": 34143,
"s": 34082,
"text": "Another difference between find() and find_all() method is −"
},
{
"code": null,
"e": 34195,
"s": 34143,
"text": ">>> soup.find_all('h2')\n[]\n>>>\n>>> soup.find('h2')\n"
},
{
"code": null,
"e": 34293,
"s": 34195,
"text": "If soup.find_all() method can’t find anything, it returns empty list whereas find() returns None."
},
{
"code": null,
"e": 34524,
"s": 34293,
"text": "Unlike the find_all() and find() methods which traverse the tree, looking at tag’s descendents, find_parents() and find_parents methods() do the opposite, they traverse the tree upwards and look at a tag’s (or a string’s) parents."
},
{
"code": null,
"e": 36670,
"s": 34524,
"text": "find_parents(name, attrs, string, limit, **kwargs)\nfind_parent(name, attrs, string, **kwargs)\n\n>>> a_string = soup.find(string=\"The Godfather\")\n>>> a_string\n'The Godfather'\n>>> a_string.find_parents('a')\n[<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>]\n>>> a_string.find_parent('a')\n<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>\n>>> a_string.find_parent('tr')\n<tr>\n\n<td class=\"posterColumn\">\n<span data-value=\"2\" name=\"rk\"></span>\n<span data-value=\"9.149038526210072\" name=\"ir\"></span>\n<span data-value=\"6.93792E10\" name=\"us\"></span>\n<span data-value=\"1485540\" name=\"nv\"></span>\n<span data-value=\"-1.850961473789928\" name=\"ur\"></span>\n<a href=\"/title/tt0068646/\"> <img alt=\"The Godfather\" height=\"67\" src=\"https://m.media-amazon.com/images/M/MV5BM2MyNjYxNmUtYTAwNi00MTYxLWJmNWYtYzZlODY3ZTk3OTFlXkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_UY67_CR1,0,45,67_AL_.jpg\" width=\"45\"/>\n</a> </td>\n<td class=\"titleColumn\">\n2.\n<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>\n<span class=\"secondaryInfo\">(1972)</span>\n</td>\n<td class=\"ratingColumn imdbRating\">\n<strong title=\"9.1 based on 1,485,540 user ratings\">9.1</strong>\n</td>\n<td class=\"ratingColumn\">\n<div class=\"seen-widget seen-widget-tt0068646 pending\" data-titleid=\"tt0068646\">\n<div class=\"boundary\">\n<div class=\"popover\">\n<span class=\"delete\"> </span><ol><li>1<li>2<li>3<li>4<li>5<li>6<li>7<li>8<li>9<li>10</li>0</li></li></li></li&td;</li></li></li></li></li></ol> </div>\n</div>\n<div class=\"inline\">\n<div class=\"pending\"></div>\n<div class=\"unseeable\">NOT YET RELEASED</div>\n<div class=\"unseen\"> </div>\n<div class=\"rating\"></div>\n<div class=\"seen\">Seen</div>\n</div>\n</div>\n</td>\n<td class=\"watchlistColumn\">\n\n<div class=\"wlb_ribbon\" data-recordmetrics=\"true\" data-tconst=\"tt0068646\"></div>\n</td>\n</tr>\n>>>\n>>> a_string.find_parents('td')\n[<td class=\"titleColumn\">\n2.\n<a href=\"/title/tt0068646/\" title=\"Francis Ford Coppola (dir.), Marlon Brando, Al Pacino\">The Godfather</a>\n<span class=\"secondaryInfo\">(1972)</span>\n</td>]"
},
{
"code": null,
"e": 36710,
"s": 36670,
"text": "There are eight other similar methods −"
},
{
"code": null,
"e": 37127,
"s": 36710,
"text": "find_next_siblings(name, attrs, string, limit, **kwargs)\nfind_next_sibling(name, attrs, string, **kwargs)\n\nfind_previous_siblings(name, attrs, string, limit, **kwargs)\nfind_previous_sibling(name, attrs, string, **kwargs)\n\nfind_all_next(name, attrs, string, limit, **kwargs)\nfind_next(name, attrs, string, **kwargs)\n\nfind_all_previous(name, attrs, string, limit, **kwargs)\nfind_previous(name, attrs, string, **kwargs)"
},
{
"code": null,
"e": 37134,
"s": 37127,
"text": "Where,"
},
{
"code": null,
"e": 37270,
"s": 37134,
"text": "find_next_siblings() and find_next_sibling() methods will iterate over all the siblings of the element that come after the current one."
},
{
"code": null,
"e": 37404,
"s": 37270,
"text": "find_previous_siblings() and find_previous_sibling() methods will iterate over all the siblings that come before the current element."
},
{
"code": null,
"e": 37524,
"s": 37404,
"text": "find_all_next() and find_next() methods will iterate over all the tags and strings that come after the current element."
},
{
"code": null,
"e": 37651,
"s": 37524,
"text": "find_all_previous and find_previous() methods will iterate over all the tags and strings that come before the current element."
},
{
"code": null,
"e": 37812,
"s": 37651,
"text": "The BeautifulSoup library to support the most commonly-used CSS selectors. You can search for elements using CSS selectors with the help of the select() method."
},
{
"code": null,
"e": 37837,
"s": 37812,
"text": "Here are some examples −"
},
{
"code": null,
"e": 38653,
"s": 37837,
"text": ">>> soup.select('title')\n[<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>]\n>>>\n>>> soup.select(\"p:nth-of-type(1)\")\n[<p>The Top Rated Movie list only includes theatrical features.</p>, <p> class=\"imdb-footer__copyright _2-iNNCFskmr4l2OFN2DRsf\">© 1990-2019 by IMDb.com, Inc.</p>]\n>>> len(soup.select(\"p:nth-of-type(1)\"))\n2\n>>> len(soup.select(\"a\"))\n609\n>>> len(soup.select(\"p\"))\n2\n\n>>> soup.select(\"html head title\")\n[<title>IMDb Top 250 - IMDb</title>, <title>IMDb Top Rated Movies</title>]\n>>> soup.select(\"head > title\")\n[<title>IMDb Top 250 - IMDb</title>]\n\n#print HTML code of the tenth li elemnet\n>>> soup.select(\"li:nth-of-type(10)\")\n[<li class=\"subnav_item_main\">\n<a href=\"/search/title?genres=film_noir&sort=user_rating,desc&title_type=feature&num_votes=25000,\">Film-Noir\n</a> </li>]"
},
{
"code": null,
"e": 39182,
"s": 38653,
"text": "One of the important aspects of BeautifulSoup is search the parse tree and it allows you to make changes to the web document according to your requirement. We can make changes to tag’s properties using its attributes, such as the .name, .string or .append() method. It allows you to add new tags and strings to an existing tag with the help of the .new_string() and .new_tag() methods. There are other methods too, such as .insert(), .insert_before() or .insert_after() to make various modification to your HTML or XML document."
},
{
"code": null,
"e": 39348,
"s": 39182,
"text": "Once you have created the soup, it is easy to make modification like renaming the tag, make modification to its attributes, add new attributes and delete attributes."
},
{
"code": null,
"e": 39426,
"s": 39348,
"text": ">>> soup = BeautifulSoup('<b class=\"bolder\">Very Bold</b>')\n>>> tag = soup.b\n"
},
{
"code": null,
"e": 39482,
"s": 39426,
"text": "Modification and adding new attributes are as follows −"
},
{
"code": null,
"e": 39625,
"s": 39482,
"text": ">>> tag.name = 'Blockquote'\n>>> tag['class'] = 'Bolder'\n>>> tag['id'] = 1.1\n>>> tag\n<Blockquote class=\"Bolder\" id=\"1.1\">Very Bold</Blockquote>"
},
{
"code": null,
"e": 39662,
"s": 39625,
"text": "Deleting attributes are as follows −"
},
{
"code": null,
"e": 39796,
"s": 39662,
"text": ">>> del tag['class']\n>>> tag\n<Blockquote id=\"1.1\">Very Bold</Blockquote>\n>>> del tag['id']\n>>> tag\n<Blockquote>Very Bold</Blockquote>"
},
{
"code": null,
"e": 39848,
"s": 39796,
"text": "You can easily modify the tag’s .string attribute −"
},
{
"code": null,
"e": 40121,
"s": 39848,
"text": ">>> markup = '<a href=\"https://www.tutorialspoint.com/index.htm\">Must for every <i>Learner>/i<</a>'\n>>> Bsoup = BeautifulSoup(markup)\n>>> tag = Bsoup.a\n>>> tag.string = \"My Favourite spot.\"\n>>> tag\n<a href=\"https://www.tutorialspoint.com/index.htm\">My Favourite spot.</a>\n"
},
{
"code": null,
"e": 40237,
"s": 40121,
"text": "From above, we can see if the tag contains any other tag, they and all their contents will be replaced by new data."
},
{
"code": null,
"e": 40373,
"s": 40237,
"text": "Adding new data/contents to an existing tag is by using tag.append() method. It is very much similar to append() method in Python list."
},
{
"code": null,
"e": 40760,
"s": 40373,
"text": ">>> markup = '<a href=\"https://www.tutorialspoint.com/index.htm\">Must for every <i>Learner</i></a>'\n>>> Bsoup = BeautifulSoup(markup)\n>>> Bsoup.a.append(\" Really Liked it\")\n>>> Bsoup\n<html><body><a href=\"https://www.tutorialspoint.com/index.htm\">Must for every <i>Learner</i> Really Liked it</a></body></html>\n>>> Bsoup.a.contents\n['Must for every ', <i>Learner</i>, ' Really Liked it']"
},
{
"code": null,
"e": 40892,
"s": 40760,
"text": "In case you want to add a string to a document, this can be done easily by using the append() or by NavigableString() constructor −"
},
{
"code": null,
"e": 41104,
"s": 40892,
"text": ">>> soup = BeautifulSoup(\"<b></b>\")\n>>> tag = soup.b\n>>> tag.append(\"Start\")\n>>>\n>>> new_string = NavigableString(\" Your\")\n>>> tag.append(new_string)\n>>> tag\n<b>Start Your</b>\n>>> tag.contents\n['Start', ' Your']"
},
{
"code": null,
"e": 41197,
"s": 41104,
"text": "Note: If you find any name Error while accessing the NavigableString() function, as follows−"
},
{
"code": null,
"e": 41246,
"s": 41197,
"text": "NameError: name 'NavigableString' is not defined"
},
{
"code": null,
"e": 41307,
"s": 41246,
"text": "Just import the NavigableString directory from bs4 package −"
},
{
"code": null,
"e": 41344,
"s": 41307,
"text": ">>> from bs4 import NavigableString\n"
},
{
"code": null,
"e": 41376,
"s": 41344,
"text": "We can resolve the above error."
},
{
"code": null,
"e": 41498,
"s": 41376,
"text": "You can add comments to your existing tag’s or can add some other subclass of NavigableString, just call the constructor."
},
{
"code": null,
"e": 41747,
"s": 41498,
"text": ">>> from bs4 import Comment\n>>> adding_comment = Comment(\"Always Learn something Good!\")\n>>> tag.append(adding_comment)\n>>> tag\n<b>Start Your<!--Always Learn something Good!--></b>\n>>> tag.contents\n['Start', ' Your', 'Always Learn something Good!']"
},
{
"code": null,
"e": 41883,
"s": 41747,
"text": "Adding a whole new tag (not appending to an existing tag) can be done using the Beautifulsoup inbuilt method, BeautifulSoup.new_tag() −"
},
{
"code": null,
"e": 42097,
"s": 41883,
"text": ">>> soup = BeautifulSoup(\"<b></b>\")\n>>> Otag = soup.b\n>>>\n>>> Newtag = soup.new_tag(\"a\", href=\"https://www.tutorialspoint.com\")\n>>> Otag.append(Newtag)\n>>> Otag\n<b><a href=\"https://www.tutorialspoint.com\"></a></b>"
},
{
"code": null,
"e": 42149,
"s": 42097,
"text": "Only the first argument, the tag name, is required."
},
{
"code": null,
"e": 42374,
"s": 42149,
"text": "Similar to .insert() method on python list, tag.insert() will insert new element however, unlike tag.append(), new element doesn’t necessarily go at the end of its parent’s contents. New element can be added at any position."
},
{
"code": null,
"e": 42828,
"s": 42374,
"text": ">>> markup = '<a href=\"https://www.djangoproject.com/community/\">Django Official website <i>Huge Community base</i></a>'\n>>> soup = BeautifulSoup(markup)\n>>> tag = soup.a\n>>>\n>>> tag.insert(1, \"Love this framework \")\n>>> tag\n<a href=\"https://www.djangoproject.com/community/\">Django Official website Love this framework <i>Huge Community base</i></a>\n>>> tag.contents\n['Django Official website ', 'Love this framework ', <i>Huge Community base</i\n>]\n>>>"
},
{
"code": null,
"e": 42923,
"s": 42828,
"text": "To insert some tag or string just before something in the parse tree, we use insert_before() −"
},
{
"code": null,
"e": 43081,
"s": 42923,
"text": ">>> soup = BeautifulSoup(\"Brave\")\n>>> tag = soup.new_tag(\"i\")\n>>> tag.string = \"Be\"\n>>>\n>>> soup.b.string.insert_before(tag)\n>>> soup.b\n<b><i>Be</i>Brave</b>"
},
{
"code": null,
"e": 43180,
"s": 43081,
"text": "Similarly to insert some tag or string just after something in the parse tree, use insert_after()."
},
{
"code": null,
"e": 43329,
"s": 43180,
"text": ">>> soup.b.i.insert_after(soup.new_string(\" Always \"))\n>>> soup.b\n<b><i>Be</i> Always Brave</b>\n>>> soup.b.contents\n[<i>Be</i>, ' Always ', 'Brave']"
},
{
"code": null,
"e": 43380,
"s": 43329,
"text": "To remove the contents of a tag, use tag.clear() −"
},
{
"code": null,
"e": 43742,
"s": 43380,
"text": ">>> markup = '<a href=\"https://www.tutorialspoint.com/index.htm\">For <i>technical & Non-technical&lr;/i> Contents</a>'\n>>> soup = BeautifulSoup(markup)\n>>> tag = soup.a\n>>> tag\n<a href=\"https://www.tutorialspoint.com/index.htm\">For <i>technical & Non-technical</i> Contents</a>\n>>>\n>>> tag.clear()\n>>> tag\n<a href=\"https://www.tutorialspoint.com/index.htm\"></a>"
},
{
"code": null,
"e": 43811,
"s": 43742,
"text": "To remove a tag or strings from the tree, use PageElement.extract()."
},
{
"code": null,
"e": 44177,
"s": 43811,
"text": ">>> markup = '<a href=\"https://www.tutorialspoint.com/index.htm\">For <i&gr;technical & Non-technical</i> Contents</a>'\n>>> soup = BeautifulSoup(markup)\n>>> a_tag = soup.a\n>>>\n>>> i_tag = soup.i.extract()\n>>>\n>>> a_tag\n<a href=\"https://www.tutorialspoint.com/index.htm\">For Contents</a>\n>>>\n>>> i_tag\n<i>technical & Non-technical</i>\n>>>\n>>> print(i_tag.parent)\nNone"
},
{
"code": null,
"e": 44255,
"s": 44177,
"text": "The tag.decompose() removes a tag from the tree and deletes all its contents."
},
{
"code": null,
"e": 44643,
"s": 44255,
"text": ">>> markup = '<a href=\"https://www.tutorialspoint.com/index.htm\">For <i>technical & Non-technical</i> Contents</a>'\n>>> soup = BeautifulSoup(markup)\n>>> a_tag = soup.a\n>>> a_tag\n<a href=\"https://www.tutorialspoint.com/index.htm\">For <i>technical & Non-technical</i> Contents</a>\n>>>\n>>> soup.i.decompose()\n>>> a_tag\n<a href=\"https://www.tutorialspoint.com/index.htm\">For Contents</a>\n>>>"
},
{
"code": null,
"e": 44777,
"s": 44643,
"text": "As the name suggests, pageElement.replace_with() function will replace the old tag or string with the new tag or string in the tree −"
},
{
"code": null,
"e": 45216,
"s": 44777,
"text": ">>> markup = '<a href=\"https://www.tutorialspoint.com/index.htm\">Complete Python <i>Material</i></a>'\n>>> soup = BeautifulSoup(markup)\n>>> a_tag = soup.a\n>>>\n>>> new_tag = soup.new_tag(\"Official_site\")\n>>> new_tag.string = \"https://www.python.org/\"\n>>> a_tag.i.replace_with(new_tag)\n<i>Material</i>\n>>>\n>>> a_tag\n<a href=\"https://www.tutorialspoint.com/index.htm\">Complete Python <Official_site>https://www.python.org/</Official_site></a>"
},
{
"code": null,
"e": 45415,
"s": 45216,
"text": "In the above output, you have noticed that replace_with() returns the tag or string that was replaced (like “Material” in our case), so you can examine it or add it back to another part of the tree."
},
{
"code": null,
"e": 45509,
"s": 45415,
"text": "The pageElement.wrap() enclosed an element in the tag you specify and returns a new wrapper −"
},
{
"code": null,
"e": 45716,
"s": 45509,
"text": ">>> soup = BeautifulSoup(\"<p>tutorialspoint.com</p>\")\n>>> soup.p.string.wrap(soup.new_tag(\"b\"))\n<b>tutorialspoint.com</b>\n>>>\n>>> soup.p.wrap(soup.new_tag(\"Div\"))\n<Div><p><b>tutorialspoint.com</b></p></Div>"
},
{
"code": null,
"e": 45810,
"s": 45716,
"text": "The tag.unwrap() is just opposite to wrap() and replaces a tag with whatever inside that tag."
},
{
"code": null,
"e": 46045,
"s": 45810,
"text": ">>> soup = BeautifulSoup('<a href=\"https://www.tutorialspoint.com/\">I liked <i>tutorialspoint</i></a>')\n>>> a_tag = soup.a\n>>>\n>>> a_tag.i.unwrap()\n<i></i>\n>>> a_tag\n<a href=\"https://www.tutorialspoint.com/\">I liked tutorialspoint</a>"
},
{
"code": null,
"e": 46144,
"s": 46045,
"text": "From above, you have noticed that like replace_with(), unwrap() returns the tag that was replaced."
},
{
"code": null,
"e": 46208,
"s": 46144,
"text": "Below is one more example of unwrap() to understand it better −"
},
{
"code": null,
"e": 46380,
"s": 46208,
"text": ">>> soup = BeautifulSoup(\"<p>I <strong>AM</strong> a <i>text</i>.</p>\")\n>>> soup.i.unwrap()\n<i></i>\n>>> soup\n<html><body><p>I <strong>AM</strong> a text.</p></body></html>"
},
{
"code": null,
"e": 46422,
"s": 46380,
"text": "unwrap() is good for striping out markup."
},
{
"code": null,
"e": 46607,
"s": 46422,
"text": "All HTML or XML documents are written in some specific encoding like ASCII or UTF-8. However, when you load that HTML/XML document into BeautifulSoup, it has been converted to Unicode."
},
{
"code": null,
"e": 46754,
"s": 46607,
"text": ">>> markup = \"<p>I will display £</p>\"\n>>> Bsoup = BeautifulSoup(markup)\n>>> Bsoup.p\n<p>I will display £</p>\n>>> Bsoup.p.string\n'I will display £'"
},
{
"code": null,
"e": 46915,
"s": 46754,
"text": "Above behavior is because BeautifulSoup internally uses the sub-library called Unicode, Dammit to detect a document’s encoding and then convert it into Unicode."
},
{
"code": null,
"e": 47208,
"s": 46915,
"text": "However, not all the time, the Unicode, Dammit guesses correctly. As the document is searched byte-by-byte to guess the encoding, it takes lot of time. You can save some time and avoid mistakes, if you already know the encoding by passing it to the BeautifulSoup constructor as from_encoding."
},
{
"code": null,
"e": 47307,
"s": 47208,
"text": "Below is one example where the BeautifulSoup misidentifies, an ISO-8859-8 document as ISO-8859-7 −"
},
{
"code": null,
"e": 47452,
"s": 47307,
"text": ">>> markup = b\"<h1>\\xed\\xe5\\xec\\xf9</h1>\"\n>>> soup = BeautifulSoup(markup)\n>>> soup.h1\n<h1>νεμω</h1>\n>>> soup.original_encoding\n'ISO-8859-7'\n>>>"
},
{
"code": null,
"e": 47523,
"s": 47452,
"text": "To resolve above issue, pass it to BeautifulSoup using from_encoding −"
},
{
"code": null,
"e": 47654,
"s": 47523,
"text": ">>> soup = BeautifulSoup(markup, from_encoding=\"iso-8859-8\")\n>>> soup.h1\n<h1>ולש </h1>\n>>> soup.original_encoding\n'iso-8859-8'\n>>>"
},
{
"code": null,
"e": 47839,
"s": 47654,
"text": "Another new feature added from BeautifulSoup 4.4.0 is, exclude_encoding. It can be used, when you don’t know the correct encoding but sure that Unicode, Dammit is showing wrong result."
},
{
"code": null,
"e": 47907,
"s": 47839,
"text": ">>> soup = BeautifulSoup(markup, exclude_encodings=[\"ISO-8859-7\"])\n"
},
{
"code": null,
"e": 48091,
"s": 47907,
"text": "The output from a BeautifulSoup is UTF-8 document, irrespective of the entered document to BeautifulSoup. Below a document, where the polish characters are there in ISO-8859-2 format."
},
{
"code": null,
"e": 48668,
"s": 48091,
"text": "html_markup = \"\"\"\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<HTML>\n<HEAD>\n<META HTTP-EQUIV=\"content-type\" CONTENT=\"text/html; charset=iso-8859-2\">\n</HEAD>\n<BODY>\ną ć ę ł ń ó ś ź ż Ą Ć Ę Ł Ń Ó Ś Ź Ż\n</BODY>\n</HTML>\n\"\"\"\n\n\n>>> soup = BeautifulSoup(html_markup)\n>>> print(soup.prettify())\n<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\n<html>\n <head>\n <meta content=\"text/html; charset=utf-8\" http-equiv=\"content-type\"/>\n </head>\n <body>\n ą ć ę ł ń ó ś ź ż Ą Ć Ę Ł Ń Ó Ś Ź Ż\n </body>\n</html>"
},
{
"code": null,
"e": 48816,
"s": 48668,
"text": "In the above example, if you notice, the <meta> tag has been rewritten to reflect the generated document from BeautifulSoup is now in UTF-8 format."
},
{
"code": null,
"e": 48916,
"s": 48816,
"text": "If you don’t want the generated output in UTF-8, you can assign the desired encoding in prettify()."
},
{
"code": null,
"e": 49207,
"s": 48916,
"text": ">>> print(soup.prettify(\"latin-1\"))\nb'<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">\\n<html>\\n <head>\\n <meta content=\"text/html; charset=latin-1\" http-equiv=\"content-type\"/>\\n </head>\\n <body>\\n ą ć ę ł ń \\xf3 ś ź ż Ą Ć Ę Ł Ń \\xd3 Ś Ź Ż\\n </body>\\n</html>\\n'"
},
{
"code": null,
"e": 49361,
"s": 49207,
"text": "In the above example, we have encoded the complete document, however you can encode, any particular element in the soup as if they were a python string −"
},
{
"code": null,
"e": 49480,
"s": 49361,
"text": ">>> soup.p.encode(\"latin-1\")\nb'<p>0My first paragraph.</p>'\n>>> soup.h1.encode(\"latin-1\")\nb'<h1>My First Heading</h1>'"
},
{
"code": null,
"e": 49627,
"s": 49480,
"text": "Any characters that can’t be represented in your chosen encoding will be converted into numeric XML entity references. Below is one such example −"
},
{
"code": null,
"e": 49782,
"s": 49627,
"text": ">>> markup = u\"<b>\\N{SNOWMAN}</b>\"\n>>> snowman_soup = BeautifulSoup(markup)\n>>> tag = snowman_soup.b\n>>> print(tag.encode(\"utf-8\"))\nb'<b>\\xe2\\x98\\x83</b>'"
},
{
"code": null,
"e": 49908,
"s": 49782,
"text": "If you try to encode the above in “latin-1” or “ascii”, it will generate “☃”, indicating there is no representation for that."
},
{
"code": null,
"e": 49998,
"s": 49908,
"text": ">>> print (tag.encode(\"latin-1\"))\nb'<b>☃</b>'\n>>> print (tag.encode(\"ascii\"))\nb'<b>☃</b>'"
},
{
"code": null,
"e": 50209,
"s": 49998,
"text": "Unicode, Dammit is used mainly when the incoming document is in unknown format (mainly foreign language) and we want to encode in some known format (Unicode) and also we don’t need Beautifulsoup to do all this."
},
{
"code": null,
"e": 50372,
"s": 50209,
"text": "The starting point of any BeautifulSoup project, is the BeautifulSoup object. A BeautifulSoup object represents the input HTML/XML document used for its creation."
},
{
"code": null,
"e": 50520,
"s": 50372,
"text": "We can either pass a string or a file-like object for Beautiful Soup, where files (objects) are either locally stored in our machine or a web page."
},
{
"code": null,
"e": 50564,
"s": 50520,
"text": "The most common BeautifulSoup Objects are −"
},
{
"code": null,
"e": 50568,
"s": 50564,
"text": "Tag"
},
{
"code": null,
"e": 50584,
"s": 50568,
"text": "NavigableString"
},
{
"code": null,
"e": 50598,
"s": 50584,
"text": "BeautifulSoup"
},
{
"code": null,
"e": 50606,
"s": 50598,
"text": "Comment"
},
{
"code": null,
"e": 50723,
"s": 50606,
"text": "As per the beautiful soup, two navigable string or tag objects are equal if they represent the same HTML/XML markup."
},
{
"code": null,
"e": 50906,
"s": 50723,
"text": "Now let us see the below example, where the two <b> tags are treated as equal, even though they live in different parts of the object tree, because they both look like “<b>Java</b>”."
},
{
"code": null,
"e": 51201,
"s": 50906,
"text": ">>> markup = \"<p>Learn Python and <b>Java</b> and advanced <b>Java</b>! from Tutorialspoint</p>\"\n>>> soup = BeautifulSoup(markup, \"html.parser\")\n>>> first_b, second_b = soup.find_all('b')\n>>> print(first_b == second_b)\nTrue\n>>> print(first_b.previous_element == second_b.previous_element)\nFalse"
},
{
"code": null,
"e": 51294,
"s": 51201,
"text": "However, to check if the two variables refer to the same objects, you can use the following−"
},
{
"code": null,
"e": 51332,
"s": 51294,
"text": ">>> print(first_b is second_b)\nFalse\n"
},
{
"code": null,
"e": 51424,
"s": 51332,
"text": "To create a copy of any tag or NavigableString, use copy.copy() function, just like below −"
},
{
"code": null,
"e": 51575,
"s": 51424,
"text": ">>> import copy\n>>> p_copy = copy.copy(soup.p)\n>>> print(p_copy)\n<p>Learn Python and <b>Java</b> and advanced <b>Java</b>! from Tutorialspoint</p>\n>>>"
},
{
"code": null,
"e": 51701,
"s": 51575,
"text": "Although the two copies (original and copied one) contain the same markup however, the two do not represent the same object −"
},
{
"code": null,
"e": 51777,
"s": 51701,
"text": ">>> print(soup.p == p_copy)\nTrue\n>>>\n>>> print(soup.p is p_copy)\nFalse\n>>>\n"
},
{
"code": null,
"e": 51932,
"s": 51777,
"text": "The only real difference is that the copy is completely detached from the original Beautiful Soup object tree, just as if extract() had been called on it."
},
{
"code": null,
"e": 51963,
"s": 51932,
"text": ">>> print(p_copy.parent)\nNone\n"
},
{
"code": null,
"e": 52067,
"s": 51963,
"text": "Above behavior is due to two different tag objects which cannot occupy the same space at the same time."
},
{
"code": null,
"e": 52295,
"s": 52067,
"text": "There are multiple situations where you want to extract specific types of information (only <a> tags) using Beautifulsoup4. The SoupStrainer class in Beautifulsoup allows you to parse only specific part of an incoming document."
},
{
"code": null,
"e": 52408,
"s": 52295,
"text": "One way is to create a SoupStrainer and pass it on to the Beautifulsoup4 constructor as the parse_only argument."
},
{
"code": null,
"e": 52634,
"s": 52408,
"text": "A SoupStrainer tells BeautifulSoup what parts extract, and the parse tree consists of only these elements. If you narrow down your required information to a specific portion of the HTML, this will speed up your search result."
},
{
"code": null,
"e": 52735,
"s": 52634,
"text": "product = SoupStrainer('div',{'id': 'products_list'})\nsoup = BeautifulSoup(html,parse_only=product)\n"
},
{
"code": null,
"e": 52838,
"s": 52735,
"text": "Above lines of code will parse only the titles from a product site, which might be inside a tag field."
},
{
"code": null,
"e": 52980,
"s": 52838,
"text": "Similarly, like above we can use other soupStrainer objects, to parse specific information from an HTML tag. Below are some of the examples −"
},
{
"code": null,
"e": 53420,
"s": 52980,
"text": "from bs4 import BeautifulSoup, SoupStrainer\n\n#Only \"a\" tags\nonly_a_tags = SoupStrainer(\"a\")\n\n#Will parse only the below mentioned \"ids\".\nparse_only = SoupStrainer(id=[\"first\", \"third\", \"my_unique_id\"])\nsoup = BeautifulSoup(my_document, \"html.parser\", parse_only=parse_only)\n\n#parse only where string length is less than 10\ndef is_short_string(string):\n return len(string) < 10\n \nonly_short_strings =SoupStrainer(string=is_short_string)"
},
{
"code": null,
"e": 53624,
"s": 53420,
"text": "There are two main kinds of errors that need to be handled in BeautifulSoup. These two errors are not from your script but from the structure of the snippet because the BeautifulSoup API throws an error."
},
{
"code": null,
"e": 53661,
"s": 53624,
"text": "The two main errors are as follows −"
},
{
"code": null,
"e": 53904,
"s": 53661,
"text": "It is caused when the dot notation doesn’t find a sibling tag to the current HTML tag. For example, you may have encountered this error, because of missing “anchor tag”, cost-key will throw an error as it traverses and requires an anchor tag."
},
{
"code": null,
"e": 54066,
"s": 53904,
"text": "This error occurs if the required HTML tag attribute is missing. For example, if we don’t have data-pid attribute in a snippet, the pid key will throw key-error."
},
{
"code": null,
"e": 54229,
"s": 54066,
"text": "To avoid the above two listed errors when parsing a result, that result will be bypassed to make sure that a malformed snippet isn’t inserted into the databases −"
},
{
"code": null,
"e": 54275,
"s": 54229,
"text": "except(AttributeError, KeyError) as er:\npass\n"
},
{
"code": null,
"e": 54532,
"s": 54275,
"text": "Whenever we find any difficulty in understanding what BeautifulSoup does to our document or HTML, simply pass it to the diagnose() function. On passing document file to the diagnose() function, we can show how list of different parser handles the document."
},
{
"code": null,
"e": 54601,
"s": 54532,
"text": "Below is one example to demonstrate the use of diagnose() function −"
},
{
"code": null,
"e": 54725,
"s": 54601,
"text": "from bs4.diagnose import diagnose\n\nwith open(\"20 Books.html\",encoding=\"utf8\") as fp:\n data = fp.read()\n \ndiagnose(data)"
},
{
"code": null,
"e": 55009,
"s": 54725,
"text": "There are two main types of parsing errors. You might get an exception like HTMLParseError, when you feed your document to BeautifulSoup. You may also get an unexpected result, where the BeautifulSoup parse tree looks a lot different from the expected result from the parse document."
},
{
"code": null,
"e": 55242,
"s": 55009,
"text": "None of the parsing error is caused due to BeautifulSoup. It is because of external parser we use (html5lib, lxml) since BeautifulSoup doesn’t contain any parser code. One way to resolve above parsing error is to use another parser."
},
{
"code": null,
"e": 55535,
"s": 55242,
"text": "from HTMLParser import HTMLParser\n\ntry:\n from HTMLParser import HTMLParseError\nexcept ImportError, e:\n # From python 3.5, HTMLParseError is removed. Since it can never be\n # thrown in 3.5, we can just define our own class as a placeholder.\n class HTMLParseError(Exception):\n pass"
},
{
"code": null,
"e": 55764,
"s": 55535,
"text": "Python built-in HTML parser causes two most common parse errors, HTMLParser.HTMLParserError: malformed start tag and HTMLParser.HTMLParserError: bad end tag and to resolve this, is to use another parser mainly: lxml or html5lib."
},
{
"code": null,
"e": 55942,
"s": 55764,
"text": "Another common type of unexpected behavior is that you can’t find a tag that you know is in the document. However, when you run the find_all() returns [] or find() returns None."
},
{
"code": null,
"e": 56033,
"s": 55942,
"text": "This may be due to python built-in HTML parser sometimes skips tags it doesn’t understand."
},
{
"code": null,
"e": 56202,
"s": 56033,
"text": "By default, BeautifulSoup package parses the documents as HTML, however, it is very easy-to-use and handle ill-formed XML in a very elegant manner using beautifulsoup4."
},
{
"code": null,
"e": 56355,
"s": 56202,
"text": "To parse the document as XML, you need to have lxml parser and you just need to pass the “xml” as the second argument to the Beautifulsoup constructor −"
},
{
"code": null,
"e": 56397,
"s": 56355,
"text": "soup = BeautifulSoup(markup, \"lxml-xml\")\n"
},
{
"code": null,
"e": 56400,
"s": 56397,
"text": "or"
},
{
"code": null,
"e": 56437,
"s": 56400,
"text": "soup = BeautifulSoup(markup, \"xml\")\n"
},
{
"code": null,
"e": 56471,
"s": 56437,
"text": "One common XML parsing error is −"
},
{
"code": null,
"e": 56532,
"s": 56471,
"text": "AttributeError: 'NoneType' object has no attribute 'attrib'\n"
},
{
"code": null,
"e": 56640,
"s": 56532,
"text": "This might happen in case, some element is missing or not defined while using find() or findall() function."
},
{
"code": null,
"e": 56731,
"s": 56640,
"text": "Given below are some of the other parsing errors we are going to discuss in this section −"
},
{
"code": null,
"e": 57158,
"s": 56731,
"text": "Apart from the above mentioned parsing errors, you may encounter other parsing issues such as environmental issues where your script might work in one operating system but not in another operating system or may work in one virtual environment but not in another virtual environment or may not work outside the virtual environment. All these issues may be because the two environments have different parser libraries available."
},
{
"code": null,
"e": 57443,
"s": 57158,
"text": "It is recommended to know or check your default parser in your current working environment. You can check the current default parser available for the current working environment or else pass explicitly the required parser library as second arguments to the BeautifulSoup constructor."
},
{
"code": null,
"e": 57692,
"s": 57443,
"text": "As the HTML tags and attributes are case-insensitive, all three HTML parsers convert tag and attribute names to lowercase. However, if you want to preserve mixed-case or uppercase tags and attributes, then it is better to parse the document as XML."
},
{
"code": null,
"e": 57730,
"s": 57692,
"text": "Let us look into below code segment −"
},
{
"code": null,
"e": 57793,
"s": 57730,
"text": "soup = BeautifulSoup(response, \"html.parser\")\n print (soup)\n"
},
{
"code": null,
"e": 57862,
"s": 57793,
"text": "UnicodeEncodeError: 'charmap' codec can't encode character '\\u011f'\n"
},
{
"code": null,
"e": 58140,
"s": 57862,
"text": "Above problem may be because of two main situations. You might be trying to print out a unicode character that your console doesn’t know how to display. Second, you are trying to write to a file and you pass in a Unicode character that’s not supported by your default encoding."
},
{
"code": null,
"e": 58277,
"s": 58140,
"text": "One way to resolve above problem is to encode the response text/character before making the soup to get the desired result, as follows −"
},
{
"code": null,
"e": 58322,
"s": 58277,
"text": "responseTxt = response.text.encode('UTF-8')\n"
},
{
"code": null,
"e": 58545,
"s": 58322,
"text": "It is caused by accessing tag[‘attr’] when the tag in question doesn’t define the attr attribute. Most common errors are: “KeyError: ‘href’” and “KeyError: ‘class’”. Use tag.get(‘attr’) if you are not sure attr is defined."
},
{
"code": null,
"e": 58734,
"s": 58545,
"text": "for item in soup.fetch('a'):\n try:\n if (item['href'].startswith('/') or \"tutorialspoint\" in item['href']):\n (...)\n except KeyError:\n pass # or some other fallback action"
},
{
"code": null,
"e": 58780,
"s": 58734,
"text": "You may encounter AttributeError as follows −"
},
{
"code": null,
"e": 58839,
"s": 58780,
"text": "AttributeError: 'list' object has no attribute 'find_all'\n"
},
{
"code": null,
"e": 58990,
"s": 58839,
"text": "The above error mainly occurs because you expected find_all() return a single tag or string. However, soup.find_all returns a python list of elements."
},
{
"code": null,
"e": 59076,
"s": 58990,
"text": "All you need to do is to iterate through the list and catch data from those elements."
},
{
"code": null,
"e": 59111,
"s": 59076,
"text": "\n 38 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 59135,
"s": 59111,
"text": " Chandramouli Jayendran"
},
{
"code": null,
"e": 59168,
"s": 59135,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 59184,
"s": 59168,
"text": " TELCOMA Global"
},
{
"code": null,
"e": 59216,
"s": 59184,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 59233,
"s": 59216,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 59265,
"s": 59233,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 59282,
"s": 59265,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 59314,
"s": 59282,
"text": "\n 6 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 59331,
"s": 59314,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 59364,
"s": 59331,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 59381,
"s": 59364,
"text": " AlexanderSchlee"
},
{
"code": null,
"e": 59388,
"s": 59381,
"text": " Print"
},
{
"code": null,
"e": 59399,
"s": 59388,
"text": " Add Notes"
}
] |
Latent Dirichlet Allocation For Topic Modelling Explained: Algorithm And Python Scikit-Learn Implementation | by Marius Borcan | Towards Data Science | Latent Dirichlet Allocation algorithm for topic modelling and Python Scikit-Learn Implementation.
Latent Dirichlet Allocation is a form of unsupervised Machine Learning that is usually used for topic modelling in Natural Language Processing tasks. It is a very popular model for these type of tasks and the algorithm behind it is quite easy to understand and use. Also, the Scikit-Learn library has a very good implementation for the algorithm, so in this article, we are going to focus on topic modelling using Latent Dirichlet Allocation.
What is Topic Modelling
What is Unsupervised Machine Learning
Latent Dirichlet Allocation applications
Latent Dirichlet Allocation algorithm
Building a Latent Dirichlet Allocation dataset
Latent Dirichlet Allocation implementation using Scikit-Learn
Topic Modelling is an unsupervised Machine Learning task where we try to discover “abstract topics” that can describe a collection of documents. This means we have a collection of texts and we try to find patterns of words and phrases that can help us cluster the documents and group them by “topics”.
I put topics into quotes and I call them abstract topics because these are not obvious topics and we don’t need them to be. We work on the assumption that similar documents will have similar patterns of words and phrases.
For example, let’s say we have a collection of 100 texts. We go through each text and discover that ten of them contain words like “machine learning”, “training”, “supervised”, “unsupervised”, “dataset” and so on. We may not know what these words mean and we really don’t care.
We only see a pattern here, that 10% of our articles contain these words and we conclude that they should be included in the same topic. We can’t actually name the topic and again, this is not needed. We are able to cluster these 10 articles into the same topic. And when we get a new text which we have never seen before, we look into it, we find it contains some of these words, then we’ll be able to say “hey, this goes into the same category with the other 10 articles!”
Unsupervised Machine Learning is a type of Machine Learning model where we try to infer data patterns without any prior knowledge and without knowing a priori if we are right and wrong. With this type of models, we try to find patterns in the data and then we can use them to cluster, classify or describe our data.
Latent Dirichlet Allocation is a type of Unsupervised Machine Learning. We don’t know the topics of documents before we begin, we can only specify how many topics we want to find. At the end of the parsing, we can look into the results and figure out if they are helpful or not.
Latent Dirichlet Allocation is mostly used in topic modelling. Now we can think about why would we need topic modelling.
With topic modelling, we can cluster a collection of documents so that more similar documents are grouped together and less similar documents are put into different categories. This can be used to analyse and understand a dataset.
We can also automatically organise our documents based on this algorithm and then, when a new document appears into a dataset, we can automatically put it in the correct category.
Moreover, this can be used to improve text search and text similarities features in applications that deal with text documents.
Latent Dirichlet Allocation algorithm works with a few simple steps. The only preprocessing we need to do is the one we do in almost all text processing tasks: removing the stopwords (words that, with a high probability, are found in most of the documents and don’t bring any value) from all of our documents.
Establish a number of n topics that will be identified by the LDA algorithm. How can we find the perfect number of topics? Well, it’s not very easy and it’s usually a trial and error process: we try different values for n until we are satisfied with the results. Or, maybe we are lucky and we have other information about the dataset that allows us to establish the perfect number of topics.Assign every word in every document to a temporary topic. This temporary topic will be random at first, but will be updated in the next step.For this step, we will go through every document and then every word in that document and compute 2 values
Establish a number of n topics that will be identified by the LDA algorithm. How can we find the perfect number of topics? Well, it’s not very easy and it’s usually a trial and error process: we try different values for n until we are satisfied with the results. Or, maybe we are lucky and we have other information about the dataset that allows us to establish the perfect number of topics.
Assign every word in every document to a temporary topic. This temporary topic will be random at first, but will be updated in the next step.
For this step, we will go through every document and then every word in that document and compute 2 values
the probability that this document belongs to a certain topic; this is based on how many words(except the current word) from this document belong to the topic of the current word
the proportion of documents that are assigned to the topic of the current word because of the current word.
We will run through step 3 a certain number of times(established before beginning to run the algorithm). In the end, we will look at each document, find the topic that is most prevalent based on its words and assign that document to that topic.
Sometimes, when I learn about a new concept, I like to build my own small dataset that I can use to learn faster. I prefer this for 2 reasons:
no time wasted on cleaning up the data. I know that this is a very important skill for a Machine Learning Engineer or a Data Scientist, but this topic is not the focus here. If I want to learn about an algorithm, I’ll build my own small, clean dataset that will allow me to play with it.
faster trial and error process: building a dataset of my own will allow me to make it big enough to offer results, but small enough to run fast.
For the LDA Algorithm, I’m going to get the summary section of 6 Wikipedia pages(2 about cities, 2 about technology, 2 about books) and use them as documents to be clustered by the LDA algorithm. Then I’ll offer a 7th summary from another page and observe it’s placed in the correct category.
For the purpose of extracting the text from Wikipedia, I’ll use the wikipedia python package.
pip3 install wikipedia
And I'm going to use a small class to download the summary.
import wikipediaclass TextFetcher: def __init__(self, title): self.title = title page = wikipedia.page(title) self.text = page.summary def getText(self): return self.text
Then I can use this class to extract the data. As I've mentioned earlier, the only preprocessing that needs to be done is removing the stopwords. For that, I'll use the nltk package.
def preprocessor(text): nltk.download('stopwords') tokens = word_tokenize(text) return (" ").join([word for word in tokens if word not in stopwords.words()])if __name__ == "__main__": textFetcher = TextFetcher("London") text1 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("Natural Language Processing") text2 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("The Great Gatsby") text3 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("Machine Learning") text4 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("Berlin") text5 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher("For Whom the Bell Tolls") text6 = preprocessor(textFetcher.getText()) docs = [text1, text2, text3, text4, text5, text6]
And since we have our dataset ready, we can move on to the algorithm implementation.
The scikit-learn package has an excellent implementation of the LDA Algorithm. We are going to use this for today’s purpose.
pip3 install scikit-learn
The first step is to convert our words into numbers. Although we are working with words, many text processing tasks are done with numbers, because they are easier to understand for computers.
The CountVectorizer class from the scikit-learn package can convert a word in a vector of real numbers. So let’s do that with our dataset.
countVectorizer = CountVectorizer(stop_words='english') termFrequency = countVectorizer.fit_transform(docs) featureNames = countVectorizer.get_feature_names()
Now let’s apply the Latent Dirichlet Allocation algorithm on our word vectors and let’s print out our results. For each topic, we’ll print the first 10 words.
lda = LatentDirichletAllocation(n_components=3) lda.fit(termFrequency) for idx, topic in enumerate(lda.components_): print ("Topic ", idx, " ".join(featureNames[i] for i in topic.argsort()[:-10 - 1:-1]))
And the result looks like this:
Topic 0 berlin city capital german learning machine natural germany world dataTopic 1 novel fitzgerald gatsby great american published war book following consideredTopic 2 london city largest world europe populous area college westminster square
As we’ve discussed earlier, this info might not tell you much, but it’s enough for us to correctly classify a new text about Paris(after we again vectorize this text).
text7 = preprocessor(TextFetcher("Paris").getText()) print (lda.transform(countVectorizer.transform([text7])))
And the result is this:
[[0.17424998 0.10191793 0.72383209]]
Those 3 are probabilities that our text belongs to one of the 3 topics we’ve generated from the LDA algorithm. We can see that the highest probability(72%) tells us that this text should also belong to the 3rd topic, so in the same topic that talks about cities. We can see that this is a very good result obtained from a very small dataset.
In this article, we’ve discussed a general overview of the Latent Dirichlet Allocation algorithm. We’ve then built a small dataset of our own and tested the algorithm. I am very satisfied with this result and I hope you are too.
This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind.
Thank you so much for reading this! Interested in more stories like this? Follow me on Twitter at @b_dmarius and I’ll post there every new article. | [
{
"code": null,
"e": 270,
"s": 172,
"text": "Latent Dirichlet Allocation algorithm for topic modelling and Python Scikit-Learn Implementation."
},
{
"code": null,
"e": 713,
"s": 270,
"text": "Latent Dirichlet Allocation is a form of unsupervised Machine Learning that is usually used for topic modelling in Natural Language Processing tasks. It is a very popular model for these type of tasks and the algorithm behind it is quite easy to understand and use. Also, the Scikit-Learn library has a very good implementation for the algorithm, so in this article, we are going to focus on topic modelling using Latent Dirichlet Allocation."
},
{
"code": null,
"e": 737,
"s": 713,
"text": "What is Topic Modelling"
},
{
"code": null,
"e": 775,
"s": 737,
"text": "What is Unsupervised Machine Learning"
},
{
"code": null,
"e": 816,
"s": 775,
"text": "Latent Dirichlet Allocation applications"
},
{
"code": null,
"e": 854,
"s": 816,
"text": "Latent Dirichlet Allocation algorithm"
},
{
"code": null,
"e": 901,
"s": 854,
"text": "Building a Latent Dirichlet Allocation dataset"
},
{
"code": null,
"e": 963,
"s": 901,
"text": "Latent Dirichlet Allocation implementation using Scikit-Learn"
},
{
"code": null,
"e": 1265,
"s": 963,
"text": "Topic Modelling is an unsupervised Machine Learning task where we try to discover “abstract topics” that can describe a collection of documents. This means we have a collection of texts and we try to find patterns of words and phrases that can help us cluster the documents and group them by “topics”."
},
{
"code": null,
"e": 1487,
"s": 1265,
"text": "I put topics into quotes and I call them abstract topics because these are not obvious topics and we don’t need them to be. We work on the assumption that similar documents will have similar patterns of words and phrases."
},
{
"code": null,
"e": 1765,
"s": 1487,
"text": "For example, let’s say we have a collection of 100 texts. We go through each text and discover that ten of them contain words like “machine learning”, “training”, “supervised”, “unsupervised”, “dataset” and so on. We may not know what these words mean and we really don’t care."
},
{
"code": null,
"e": 2240,
"s": 1765,
"text": "We only see a pattern here, that 10% of our articles contain these words and we conclude that they should be included in the same topic. We can’t actually name the topic and again, this is not needed. We are able to cluster these 10 articles into the same topic. And when we get a new text which we have never seen before, we look into it, we find it contains some of these words, then we’ll be able to say “hey, this goes into the same category with the other 10 articles!”"
},
{
"code": null,
"e": 2556,
"s": 2240,
"text": "Unsupervised Machine Learning is a type of Machine Learning model where we try to infer data patterns without any prior knowledge and without knowing a priori if we are right and wrong. With this type of models, we try to find patterns in the data and then we can use them to cluster, classify or describe our data."
},
{
"code": null,
"e": 2835,
"s": 2556,
"text": "Latent Dirichlet Allocation is a type of Unsupervised Machine Learning. We don’t know the topics of documents before we begin, we can only specify how many topics we want to find. At the end of the parsing, we can look into the results and figure out if they are helpful or not."
},
{
"code": null,
"e": 2956,
"s": 2835,
"text": "Latent Dirichlet Allocation is mostly used in topic modelling. Now we can think about why would we need topic modelling."
},
{
"code": null,
"e": 3187,
"s": 2956,
"text": "With topic modelling, we can cluster a collection of documents so that more similar documents are grouped together and less similar documents are put into different categories. This can be used to analyse and understand a dataset."
},
{
"code": null,
"e": 3367,
"s": 3187,
"text": "We can also automatically organise our documents based on this algorithm and then, when a new document appears into a dataset, we can automatically put it in the correct category."
},
{
"code": null,
"e": 3495,
"s": 3367,
"text": "Moreover, this can be used to improve text search and text similarities features in applications that deal with text documents."
},
{
"code": null,
"e": 3805,
"s": 3495,
"text": "Latent Dirichlet Allocation algorithm works with a few simple steps. The only preprocessing we need to do is the one we do in almost all text processing tasks: removing the stopwords (words that, with a high probability, are found in most of the documents and don’t bring any value) from all of our documents."
},
{
"code": null,
"e": 4444,
"s": 3805,
"text": "Establish a number of n topics that will be identified by the LDA algorithm. How can we find the perfect number of topics? Well, it’s not very easy and it’s usually a trial and error process: we try different values for n until we are satisfied with the results. Or, maybe we are lucky and we have other information about the dataset that allows us to establish the perfect number of topics.Assign every word in every document to a temporary topic. This temporary topic will be random at first, but will be updated in the next step.For this step, we will go through every document and then every word in that document and compute 2 values"
},
{
"code": null,
"e": 4836,
"s": 4444,
"text": "Establish a number of n topics that will be identified by the LDA algorithm. How can we find the perfect number of topics? Well, it’s not very easy and it’s usually a trial and error process: we try different values for n until we are satisfied with the results. Or, maybe we are lucky and we have other information about the dataset that allows us to establish the perfect number of topics."
},
{
"code": null,
"e": 4978,
"s": 4836,
"text": "Assign every word in every document to a temporary topic. This temporary topic will be random at first, but will be updated in the next step."
},
{
"code": null,
"e": 5085,
"s": 4978,
"text": "For this step, we will go through every document and then every word in that document and compute 2 values"
},
{
"code": null,
"e": 5264,
"s": 5085,
"text": "the probability that this document belongs to a certain topic; this is based on how many words(except the current word) from this document belong to the topic of the current word"
},
{
"code": null,
"e": 5372,
"s": 5264,
"text": "the proportion of documents that are assigned to the topic of the current word because of the current word."
},
{
"code": null,
"e": 5617,
"s": 5372,
"text": "We will run through step 3 a certain number of times(established before beginning to run the algorithm). In the end, we will look at each document, find the topic that is most prevalent based on its words and assign that document to that topic."
},
{
"code": null,
"e": 5760,
"s": 5617,
"text": "Sometimes, when I learn about a new concept, I like to build my own small dataset that I can use to learn faster. I prefer this for 2 reasons:"
},
{
"code": null,
"e": 6048,
"s": 5760,
"text": "no time wasted on cleaning up the data. I know that this is a very important skill for a Machine Learning Engineer or a Data Scientist, but this topic is not the focus here. If I want to learn about an algorithm, I’ll build my own small, clean dataset that will allow me to play with it."
},
{
"code": null,
"e": 6193,
"s": 6048,
"text": "faster trial and error process: building a dataset of my own will allow me to make it big enough to offer results, but small enough to run fast."
},
{
"code": null,
"e": 6486,
"s": 6193,
"text": "For the LDA Algorithm, I’m going to get the summary section of 6 Wikipedia pages(2 about cities, 2 about technology, 2 about books) and use them as documents to be clustered by the LDA algorithm. Then I’ll offer a 7th summary from another page and observe it’s placed in the correct category."
},
{
"code": null,
"e": 6580,
"s": 6486,
"text": "For the purpose of extracting the text from Wikipedia, I’ll use the wikipedia python package."
},
{
"code": null,
"e": 6603,
"s": 6580,
"text": "pip3 install wikipedia"
},
{
"code": null,
"e": 6663,
"s": 6603,
"text": "And I'm going to use a small class to download the summary."
},
{
"code": null,
"e": 6868,
"s": 6663,
"text": "import wikipediaclass TextFetcher: def __init__(self, title): self.title = title page = wikipedia.page(title) self.text = page.summary def getText(self): return self.text"
},
{
"code": null,
"e": 7051,
"s": 6868,
"text": "Then I can use this class to extract the data. As I've mentioned earlier, the only preprocessing that needs to be done is removing the stopwords. For that, I'll use the nltk package."
},
{
"code": null,
"e": 7871,
"s": 7051,
"text": "def preprocessor(text): nltk.download('stopwords') tokens = word_tokenize(text) return (\" \").join([word for word in tokens if word not in stopwords.words()])if __name__ == \"__main__\": textFetcher = TextFetcher(\"London\") text1 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher(\"Natural Language Processing\") text2 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher(\"The Great Gatsby\") text3 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher(\"Machine Learning\") text4 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher(\"Berlin\") text5 = preprocessor(textFetcher.getText()) textFetcher = TextFetcher(\"For Whom the Bell Tolls\") text6 = preprocessor(textFetcher.getText()) docs = [text1, text2, text3, text4, text5, text6]"
},
{
"code": null,
"e": 7956,
"s": 7871,
"text": "And since we have our dataset ready, we can move on to the algorithm implementation."
},
{
"code": null,
"e": 8081,
"s": 7956,
"text": "The scikit-learn package has an excellent implementation of the LDA Algorithm. We are going to use this for today’s purpose."
},
{
"code": null,
"e": 8107,
"s": 8081,
"text": "pip3 install scikit-learn"
},
{
"code": null,
"e": 8299,
"s": 8107,
"text": "The first step is to convert our words into numbers. Although we are working with words, many text processing tasks are done with numbers, because they are easier to understand for computers."
},
{
"code": null,
"e": 8438,
"s": 8299,
"text": "The CountVectorizer class from the scikit-learn package can convert a word in a vector of real numbers. So let’s do that with our dataset."
},
{
"code": null,
"e": 8603,
"s": 8438,
"text": "countVectorizer = CountVectorizer(stop_words='english') termFrequency = countVectorizer.fit_transform(docs) featureNames = countVectorizer.get_feature_names()"
},
{
"code": null,
"e": 8762,
"s": 8603,
"text": "Now let’s apply the Latent Dirichlet Allocation algorithm on our word vectors and let’s print out our results. For each topic, we’ll print the first 10 words."
},
{
"code": null,
"e": 8979,
"s": 8762,
"text": "lda = LatentDirichletAllocation(n_components=3) lda.fit(termFrequency) for idx, topic in enumerate(lda.components_): print (\"Topic \", idx, \" \".join(featureNames[i] for i in topic.argsort()[:-10 - 1:-1]))"
},
{
"code": null,
"e": 9011,
"s": 8979,
"text": "And the result looks like this:"
},
{
"code": null,
"e": 9260,
"s": 9011,
"text": "Topic 0 berlin city capital german learning machine natural germany world dataTopic 1 novel fitzgerald gatsby great american published war book following consideredTopic 2 london city largest world europe populous area college westminster square"
},
{
"code": null,
"e": 9428,
"s": 9260,
"text": "As we’ve discussed earlier, this info might not tell you much, but it’s enough for us to correctly classify a new text about Paris(after we again vectorize this text)."
},
{
"code": null,
"e": 9542,
"s": 9428,
"text": "text7 = preprocessor(TextFetcher(\"Paris\").getText()) print (lda.transform(countVectorizer.transform([text7])))"
},
{
"code": null,
"e": 9566,
"s": 9542,
"text": "And the result is this:"
},
{
"code": null,
"e": 9603,
"s": 9566,
"text": "[[0.17424998 0.10191793 0.72383209]]"
},
{
"code": null,
"e": 9945,
"s": 9603,
"text": "Those 3 are probabilities that our text belongs to one of the 3 topics we’ve generated from the LDA algorithm. We can see that the highest probability(72%) tells us that this text should also belong to the 3rd topic, so in the same topic that talks about cities. We can see that this is a very good result obtained from a very small dataset."
},
{
"code": null,
"e": 10174,
"s": 9945,
"text": "In this article, we’ve discussed a general overview of the Latent Dirichlet Allocation algorithm. We’ve then built a small dataset of our own and tested the algorithm. I am very satisfied with this result and I hope you are too."
},
{
"code": null,
"e": 10321,
"s": 10174,
"text": "This article was originally published on the Programmer Backpack Blog. Make sure to visit this blog if you want to read more stories of this kind."
}
] |
SMOTE using Python. Achieving class balance with few lines... | by Dr. Saptarsi Goswami | Towards Data Science | Class Imbalance is a quite frequently occurring problem manifested in fraud detection, intrusion detection, Suspicious activity detection to name a few. In the context of binary classification, the less frequently occurring class is called the minority class, and the more frequently occurring class is called the majority class. You can check out our video on the same topic here.
What’s the issue with this?
Most machine learning models actually get overwhelmed by the majority class, as it expects the classes to be somewhat balanced. It’s like asking a student to learn both algebra and trigonometry equally well but giving him only 5 solved problems of trigonometry to learn from compared to a 1000 solved problem in algebra. The patterns of the minority class get buried. This literally becomes the problem of finding a neeedle from the haystack.
The evaluation also goes for a toss, we are more concerned with the minority class recall rather than anything else.
False-positive is kind of ‘ok’ but ‘False Negative is unacceptable. The fraud class is taken as the positive class.
The objective of this article is the implementation, for the theoretical understanding you can refer to the detailed working of SMOTE here.
Of course, the best thing is to have more data, but that’s too ideal. Among the sampling-based and sampling-based strategies, SMOTE comes under the generate synthetic sample strategy.
Step 1: Creating a sample dataset
from sklearn.datasets import make_classificationX, y = make_classification(n_classes=2, class_sep=0.5,weights=[0.05, 0.95], n_informative=2, n_redundant=0, flip_y=0,n_features=2, n_clusters_per_class=1, n_samples=1000, random_state=10)
make_classification is a pretty handy function to create some experimental data for you. The important parameter over here is weights which ensure 95% are from one class and 5% from the other class.
It can be understood the red class is the majority class and the blue class is the minority class.
Step 2: Create train, test dataset, fit and evaluate the model
The main issue over here we have a very poor recall rate for the minority class when the original imbalanced data is used for training the model.
Step 3: Create a dataset with Synthetic samples
from imblearn.over_sampling import SMOTEsm = SMOTE(random_state=42)X_res, y_res = sm.fit_resample(X_train, y_train)
We can create a balanced dataset with just above three lines of code
Step 4: Fit and evaluate the model on the modified dataset
We can see directly, the recall has improved from .21 to .84. Such is the power and beauty of the three lines code.
SMOTE works by selecting pair of minority class observations and then creating a synthetic point that lies on the line connecting these two. It is pretty liberal about selecting the minority points and may end up picking up minority points that are outliers.
ADASYN, BorderLine SMOTE, KMeansSMOTE, SVMSMOTE are some of the strategies to select better minority points.
EndNote:
Class Imbalance is a quite common problem and if not handled can have a telling impact on the model performance. The model performance is especially critical for the minority class.
In this article, we have outlined how with few lines of code, can work like a miracle. | [
{
"code": null,
"e": 554,
"s": 172,
"text": "Class Imbalance is a quite frequently occurring problem manifested in fraud detection, intrusion detection, Suspicious activity detection to name a few. In the context of binary classification, the less frequently occurring class is called the minority class, and the more frequently occurring class is called the majority class. You can check out our video on the same topic here."
},
{
"code": null,
"e": 582,
"s": 554,
"text": "What’s the issue with this?"
},
{
"code": null,
"e": 1025,
"s": 582,
"text": "Most machine learning models actually get overwhelmed by the majority class, as it expects the classes to be somewhat balanced. It’s like asking a student to learn both algebra and trigonometry equally well but giving him only 5 solved problems of trigonometry to learn from compared to a 1000 solved problem in algebra. The patterns of the minority class get buried. This literally becomes the problem of finding a neeedle from the haystack."
},
{
"code": null,
"e": 1142,
"s": 1025,
"text": "The evaluation also goes for a toss, we are more concerned with the minority class recall rather than anything else."
},
{
"code": null,
"e": 1258,
"s": 1142,
"text": "False-positive is kind of ‘ok’ but ‘False Negative is unacceptable. The fraud class is taken as the positive class."
},
{
"code": null,
"e": 1398,
"s": 1258,
"text": "The objective of this article is the implementation, for the theoretical understanding you can refer to the detailed working of SMOTE here."
},
{
"code": null,
"e": 1582,
"s": 1398,
"text": "Of course, the best thing is to have more data, but that’s too ideal. Among the sampling-based and sampling-based strategies, SMOTE comes under the generate synthetic sample strategy."
},
{
"code": null,
"e": 1616,
"s": 1582,
"text": "Step 1: Creating a sample dataset"
},
{
"code": null,
"e": 1852,
"s": 1616,
"text": "from sklearn.datasets import make_classificationX, y = make_classification(n_classes=2, class_sep=0.5,weights=[0.05, 0.95], n_informative=2, n_redundant=0, flip_y=0,n_features=2, n_clusters_per_class=1, n_samples=1000, random_state=10)"
},
{
"code": null,
"e": 2051,
"s": 1852,
"text": "make_classification is a pretty handy function to create some experimental data for you. The important parameter over here is weights which ensure 95% are from one class and 5% from the other class."
},
{
"code": null,
"e": 2150,
"s": 2051,
"text": "It can be understood the red class is the majority class and the blue class is the minority class."
},
{
"code": null,
"e": 2213,
"s": 2150,
"text": "Step 2: Create train, test dataset, fit and evaluate the model"
},
{
"code": null,
"e": 2359,
"s": 2213,
"text": "The main issue over here we have a very poor recall rate for the minority class when the original imbalanced data is used for training the model."
},
{
"code": null,
"e": 2407,
"s": 2359,
"text": "Step 3: Create a dataset with Synthetic samples"
},
{
"code": null,
"e": 2523,
"s": 2407,
"text": "from imblearn.over_sampling import SMOTEsm = SMOTE(random_state=42)X_res, y_res = sm.fit_resample(X_train, y_train)"
},
{
"code": null,
"e": 2592,
"s": 2523,
"text": "We can create a balanced dataset with just above three lines of code"
},
{
"code": null,
"e": 2651,
"s": 2592,
"text": "Step 4: Fit and evaluate the model on the modified dataset"
},
{
"code": null,
"e": 2767,
"s": 2651,
"text": "We can see directly, the recall has improved from .21 to .84. Such is the power and beauty of the three lines code."
},
{
"code": null,
"e": 3026,
"s": 2767,
"text": "SMOTE works by selecting pair of minority class observations and then creating a synthetic point that lies on the line connecting these two. It is pretty liberal about selecting the minority points and may end up picking up minority points that are outliers."
},
{
"code": null,
"e": 3135,
"s": 3026,
"text": "ADASYN, BorderLine SMOTE, KMeansSMOTE, SVMSMOTE are some of the strategies to select better minority points."
},
{
"code": null,
"e": 3144,
"s": 3135,
"text": "EndNote:"
},
{
"code": null,
"e": 3326,
"s": 3144,
"text": "Class Imbalance is a quite common problem and if not handled can have a telling impact on the model performance. The model performance is especially critical for the minority class."
}
] |
Image segmentation using fastai. Learn how to color code every pixel of... | by Dipam Vasani | Towards Data Science | Image segmentation is an application of computer vision wherein we color-code every pixel in an image. Each pixel then represents a particular object in that image. If you look at the images above, every street is coded in violet, every building is orange, every tree is green and so on. Why do we do this and how is it different from object detection?
Image segmentation is usually used when we care about edges and regions, when we want to separate important objects from the background. We want to know the specifics of an object and conduct further analysis on it from there on. Think about it in terms of a self driving car. A self driving car will not only want to identify a street, but also know it’s edges or curves in order to make the correct turn.
Image segmentation has a lot of significance in the field of medicine. Parts that need to be studied are color coded and viewed in scans taken from different angles. They are then used for things like automatic measurement of organs, cell counting, or simulations based on the extracted boundary information.
We treat image segmentation as a classification problem, where for every pixel in the image, we try to predict what it is. Is it a bicycle, road line, sidewalk, or a building? In this way we produce a color coded image where every object has the same color.
As usual we start by importing the fastai libraries.
Let’s first take a look at one of the images.
Next, we take a look at what the image looks like after segmentation. Since the values in the labelled image are integers, we cannot use the same functions to open it. Instead, we use open_mask with show to display the image.
Notice the function get_y_fn inside open_mask . In every segmentation problem, we are given 2 sets of images, original ones and labelled ones. We need to match the labelled images with the normal ones. We do this using the filenames. Let’s take a look at the filenames of some of the images.
We see that the filenames of the normal images and the labelled images are the same except, the corresponding labelled image has an _P towards the end. Hence we write a function which for every image, identifies its corresponding labelled counterpart.
We also have a file called codes.txt that tells us what object the integers in our labelled image correspond to. Let’s open the data for our labelled image.
Now let’s check the codes file for the meaning of these integers.
The labelled data had a lot of 26s in it. Counting from index 0 in our codes file we see that the object referred by the integer 26 is a tree.
Now that we’ve understood our data, we can move on to creating a data bunch and training our model.
We will not use the whole dataset, and we will also keep the batch size relatively small since classifying every pixel in every image is a resource intensive task.
As usual we create our data bunch. Reading the above code:
Create the data bunch from a folder
Split the data into training and testing based on filenames mentioned in valid.txt
Find the labelled images using the function get_y_fn and use the codes as classes to be predicted.
Apply transforms on the image (note the tfm_y = True here. This means that whatever transform we apply on our dependent images should also be applied on our target image. (Example: If we flip an image horizontally, we should also flip the corresponding labelled image))
For training, we will use a CNN architecture called U-Net since they are good at recreating images.
Before explaining what a U-Net is, notice the metrics used in the above code. What’s acc_camvid ?
The accuracy in an image segmentation problem is the same as that in any classification problem.
Accuracy = no. of correctly classified pixels / total no. of pixels
However in this case, some pixels are labelled as Void (this label also exists in codes.txt) and shouldn’t be considered when calculating the accuracy. Hence we make a new function for accuracy where we avoid those labels.
The way a CNN works is it breaks down an image into smaller and smaller parts until is has just one thing to predict (left part of the U-Net architecture shown below). A U-Net then takes this and makes it bigger and bigger again and it does this for every stage of the CNN. However, constructing an image from a small vector is a difficult job. Hence we have connections from the original convolution layers to our deconvolution network.
As always we find the learning rate and train our model. Even with half the data set, we get a pretty good accuracy of 92%.
Checking some of the results.
The ground truths are the actual targets and the predictions are what our model labelled.
We can now train on the full data set.
That will be it for this article. In this article we saw how to color code every pixel of an image using a U-net. U-nets are gaining popularity because they’ve performed better than GANs on applications like generating high resolution images from blurry images. Hence it will be really useful to know what they are and how to use them.
The full notebook can be found here.
If you want to learn more about deep learning check out my series of articles on the same: | [
{
"code": null,
"e": 525,
"s": 172,
"text": "Image segmentation is an application of computer vision wherein we color-code every pixel in an image. Each pixel then represents a particular object in that image. If you look at the images above, every street is coded in violet, every building is orange, every tree is green and so on. Why do we do this and how is it different from object detection?"
},
{
"code": null,
"e": 932,
"s": 525,
"text": "Image segmentation is usually used when we care about edges and regions, when we want to separate important objects from the background. We want to know the specifics of an object and conduct further analysis on it from there on. Think about it in terms of a self driving car. A self driving car will not only want to identify a street, but also know it’s edges or curves in order to make the correct turn."
},
{
"code": null,
"e": 1241,
"s": 932,
"text": "Image segmentation has a lot of significance in the field of medicine. Parts that need to be studied are color coded and viewed in scans taken from different angles. They are then used for things like automatic measurement of organs, cell counting, or simulations based on the extracted boundary information."
},
{
"code": null,
"e": 1499,
"s": 1241,
"text": "We treat image segmentation as a classification problem, where for every pixel in the image, we try to predict what it is. Is it a bicycle, road line, sidewalk, or a building? In this way we produce a color coded image where every object has the same color."
},
{
"code": null,
"e": 1552,
"s": 1499,
"text": "As usual we start by importing the fastai libraries."
},
{
"code": null,
"e": 1598,
"s": 1552,
"text": "Let’s first take a look at one of the images."
},
{
"code": null,
"e": 1824,
"s": 1598,
"text": "Next, we take a look at what the image looks like after segmentation. Since the values in the labelled image are integers, we cannot use the same functions to open it. Instead, we use open_mask with show to display the image."
},
{
"code": null,
"e": 2116,
"s": 1824,
"text": "Notice the function get_y_fn inside open_mask . In every segmentation problem, we are given 2 sets of images, original ones and labelled ones. We need to match the labelled images with the normal ones. We do this using the filenames. Let’s take a look at the filenames of some of the images."
},
{
"code": null,
"e": 2368,
"s": 2116,
"text": "We see that the filenames of the normal images and the labelled images are the same except, the corresponding labelled image has an _P towards the end. Hence we write a function which for every image, identifies its corresponding labelled counterpart."
},
{
"code": null,
"e": 2525,
"s": 2368,
"text": "We also have a file called codes.txt that tells us what object the integers in our labelled image correspond to. Let’s open the data for our labelled image."
},
{
"code": null,
"e": 2591,
"s": 2525,
"text": "Now let’s check the codes file for the meaning of these integers."
},
{
"code": null,
"e": 2734,
"s": 2591,
"text": "The labelled data had a lot of 26s in it. Counting from index 0 in our codes file we see that the object referred by the integer 26 is a tree."
},
{
"code": null,
"e": 2834,
"s": 2734,
"text": "Now that we’ve understood our data, we can move on to creating a data bunch and training our model."
},
{
"code": null,
"e": 2998,
"s": 2834,
"text": "We will not use the whole dataset, and we will also keep the batch size relatively small since classifying every pixel in every image is a resource intensive task."
},
{
"code": null,
"e": 3057,
"s": 2998,
"text": "As usual we create our data bunch. Reading the above code:"
},
{
"code": null,
"e": 3093,
"s": 3057,
"text": "Create the data bunch from a folder"
},
{
"code": null,
"e": 3176,
"s": 3093,
"text": "Split the data into training and testing based on filenames mentioned in valid.txt"
},
{
"code": null,
"e": 3275,
"s": 3176,
"text": "Find the labelled images using the function get_y_fn and use the codes as classes to be predicted."
},
{
"code": null,
"e": 3545,
"s": 3275,
"text": "Apply transforms on the image (note the tfm_y = True here. This means that whatever transform we apply on our dependent images should also be applied on our target image. (Example: If we flip an image horizontally, we should also flip the corresponding labelled image))"
},
{
"code": null,
"e": 3645,
"s": 3545,
"text": "For training, we will use a CNN architecture called U-Net since they are good at recreating images."
},
{
"code": null,
"e": 3743,
"s": 3645,
"text": "Before explaining what a U-Net is, notice the metrics used in the above code. What’s acc_camvid ?"
},
{
"code": null,
"e": 3840,
"s": 3743,
"text": "The accuracy in an image segmentation problem is the same as that in any classification problem."
},
{
"code": null,
"e": 3908,
"s": 3840,
"text": "Accuracy = no. of correctly classified pixels / total no. of pixels"
},
{
"code": null,
"e": 4131,
"s": 3908,
"text": "However in this case, some pixels are labelled as Void (this label also exists in codes.txt) and shouldn’t be considered when calculating the accuracy. Hence we make a new function for accuracy where we avoid those labels."
},
{
"code": null,
"e": 4569,
"s": 4131,
"text": "The way a CNN works is it breaks down an image into smaller and smaller parts until is has just one thing to predict (left part of the U-Net architecture shown below). A U-Net then takes this and makes it bigger and bigger again and it does this for every stage of the CNN. However, constructing an image from a small vector is a difficult job. Hence we have connections from the original convolution layers to our deconvolution network."
},
{
"code": null,
"e": 4693,
"s": 4569,
"text": "As always we find the learning rate and train our model. Even with half the data set, we get a pretty good accuracy of 92%."
},
{
"code": null,
"e": 4723,
"s": 4693,
"text": "Checking some of the results."
},
{
"code": null,
"e": 4813,
"s": 4723,
"text": "The ground truths are the actual targets and the predictions are what our model labelled."
},
{
"code": null,
"e": 4852,
"s": 4813,
"text": "We can now train on the full data set."
},
{
"code": null,
"e": 5188,
"s": 4852,
"text": "That will be it for this article. In this article we saw how to color code every pixel of an image using a U-net. U-nets are gaining popularity because they’ve performed better than GANs on applications like generating high resolution images from blurry images. Hence it will be really useful to know what they are and how to use them."
},
{
"code": null,
"e": 5225,
"s": 5188,
"text": "The full notebook can be found here."
}
] |
MariaDB - PHP Syntax | MariaDB partners well with a wide variety of programming languages and frameworks such as PHP, C#, JavaScript, Ruby on Rails, Django, and more. PHP remains the most popular of all available languages due to its simplicity and historical footprint. This guide will focus on PHP partnered with MariaDB.
PHP provides a selection of functions for working with the MySQL database. These functions perform tasks like accessing it or performing operations, and they are fully compatible with MariaDB. Simply call these functions as you would call any other PHP function.
The PHP functions you will use for MariaDB conform to the following format −
mysql_function(value,value,...);
The second part of the function specifies its action. Two of the functions used in this guide are as follows −
mysqli_connect($connect);
mysqli_query($connect,"SQL statement");
The following example demonstrates the general syntax of a PHP call to a MariaDB function −
<html>
<head>
<title>PHP and MariaDB</title>
</head>
<body>
<?php
$retval = mysql_function(value, [value,...]);
if( !$retval ) {
die ( "Error: Error message here" );
}
// MariaDB or PHP Statements
?>
</body>
</html>
In the next section, we will examine essential MariaDB tasks, using PHP functions.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2663,
"s": 2362,
"text": "MariaDB partners well with a wide variety of programming languages and frameworks such as PHP, C#, JavaScript, Ruby on Rails, Django, and more. PHP remains the most popular of all available languages due to its simplicity and historical footprint. This guide will focus on PHP partnered with MariaDB."
},
{
"code": null,
"e": 2926,
"s": 2663,
"text": "PHP provides a selection of functions for working with the MySQL database. These functions perform tasks like accessing it or performing operations, and they are fully compatible with MariaDB. Simply call these functions as you would call any other PHP function."
},
{
"code": null,
"e": 3003,
"s": 2926,
"text": "The PHP functions you will use for MariaDB conform to the following format −"
},
{
"code": null,
"e": 3037,
"s": 3003,
"text": "mysql_function(value,value,...);\n"
},
{
"code": null,
"e": 3148,
"s": 3037,
"text": "The second part of the function specifies its action. Two of the functions used in this guide are as follows −"
},
{
"code": null,
"e": 3215,
"s": 3148,
"text": "mysqli_connect($connect);\nmysqli_query($connect,\"SQL statement\");\n"
},
{
"code": null,
"e": 3307,
"s": 3215,
"text": "The following example demonstrates the general syntax of a PHP call to a MariaDB function −"
},
{
"code": null,
"e": 3609,
"s": 3307,
"text": "<html>\n <head>\n <title>PHP and MariaDB</title>\n </head>\n\n <body>\n <?php\n $retval = mysql_function(value, [value,...]);\n \n if( !$retval ) {\n die ( \"Error: Error message here\" );\n }\n // MariaDB or PHP Statements\n ?>\n </body>\n</html>"
},
{
"code": null,
"e": 3692,
"s": 3609,
"text": "In the next section, we will examine essential MariaDB tasks, using PHP functions."
},
{
"code": null,
"e": 3699,
"s": 3692,
"text": " Print"
},
{
"code": null,
"e": 3710,
"s": 3699,
"text": " Add Notes"
}
] |
C Program for Basic Euclidean algorithms? | Here we will see the Euclidean algorithm to find the GCD of two numbers. The GCD (Greatest Common Divisor) can easily be found using Euclidean algorithm. There are two different approach. One is iterative, another one is recursive. Here we are going to use the recursive Euclidean algorithm.
begin
if a is 0, then
return b
end if
return gcd(b mod a, a)
end
Live Demo
#include<iostream>
using namespace std;
int euclideanAlgorithm(int a, int b) {
if (a == 0)
return b;
return euclideanAlgorithm(b%a, a);
}
main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "GCD " << euclideanAlgorithm(a, b);
}
Enter two numbers: 12 16
GCD 4 | [
{
"code": null,
"e": 1354,
"s": 1062,
"text": "Here we will see the Euclidean algorithm to find the GCD of two numbers. The GCD (Greatest Common Divisor) can easily be found using Euclidean algorithm. There are two different approach. One is iterative, another one is recursive. Here we are going to use the recursive Euclidean algorithm."
},
{
"code": null,
"e": 1434,
"s": 1354,
"text": "begin\n if a is 0, then\n return b\n end if\n return gcd(b mod a, a)\nend"
},
{
"code": null,
"e": 1445,
"s": 1434,
"text": " Live Demo"
},
{
"code": null,
"e": 1718,
"s": 1445,
"text": "#include<iostream>\nusing namespace std;\nint euclideanAlgorithm(int a, int b) {\n if (a == 0)\n return b;\n return euclideanAlgorithm(b%a, a);\n}\nmain() {\n int a, b;\n cout << \"Enter two numbers: \";\n cin >> a >> b;\n cout << \"GCD \" << euclideanAlgorithm(a, b);\n}"
},
{
"code": null,
"e": 1749,
"s": 1718,
"text": "Enter two numbers: 12 16\nGCD 4"
}
] |
Running Jupyter on a remote Docker container using SSH | by Lucas Rodés-Guirao | Towards Data Science | In my research I work with Machine Learning/Deep Learning algorithms, which I mostly develop using Python. As such, I find it useful to test different frameworks (such as Keras, PyTorch, Tensorflow...). This lead me to using Docker, and in particular ufoym/deepo image as it provides a very complete environment.
I use a remote machine with GPUs, where I have Docker installed. When programming and testing some code snippets, I find it really helpful to use Jupyter. I had previously used Jupyter locally... but question here was how could I remotely use Jupyter running on a another machine. And on top of that, what if I was using a Docker container on my remote machine?
In this tutorial I will try to share my experience in how I solved this puzzle and made it possible to locally use the Jupyter web-app running the code in a remote machine.
Let me first illustrate my working environment set up.
I use my regular laptop as the host machine.I connect to the server of my department (remote) via ssh.I then connect to a specific machine within the server which has GPUs.Finally I start the docker container in that machine.
I use my regular laptop as the host machine.
I connect to the server of my department (remote) via ssh.
I then connect to a specific machine within the server which has GPUs.
Finally I start the docker container in that machine.
In my particular case, the machine I work on is the one labeled as GPU in the above picture, which happens to be only accessible from another machine within the server. Hence the double ssh... But in your case you might be able to connect directly to your GPU machine from the outer world.
It sounds like messy, but bear with me, you just need to organise it once and for all.
Make sure to have docker installed in your remote machine. If you are unfamiliar with Docker, please check some of the resources available (I found this and this to be helpful). If you are aiming for a GPU-support environment, check next.
If your remote machine has GPUs you might want to exploit this fact. Make sure you have the NVIDIA driver installed. You also need to install nvidia-docker. Note that by installing nvidia-docker we automatically install the last stable release of docker-ce, hence you don’t need to explicitly install docker before.
Jupyter Notebook runs on a certain port on the machine. Hence, the basic idea would be to make that port reachable from your host machine. Luckily, ssh provides the -L option to specify port forwarding.
$ ssh -L <host port>:localhost:<remote port> user@remote
In my case I use port 9999 in both ends, namely <host port> = <remote port> = 9999.
Here the approach is exactly the same as before.
$ ssh -L <remote port>:localhost:<GPU port> user@GPU
Again, I use <host port> = <remote port> = 9999.
This step is slightly different. First, you need to create a docker container using some docker image of your preference. In my case, as aforementioned, I am using ufoym/deepo. Since I want GPU-support, I will use nvidia-docker to create the container.
$ nvidia-docker run -it \-p <GPU port>:<container port> \--name <container name> \ufoym/deepo bash
Note the option -p , which tells the docker container to do port forwarding. This way, we can get access to apps running in the docker on a certain port from the outside world. Here, I also use <host port> = <remote port> = 9999.
By the way, an extremely useful option when creating a container is -v, which allows you to access machine files from within the docker container.
Well, once all the tunneling is set up, we can start our jupyter app. We will use 0.0.0.0 ip and the same port we used when creating the docker container instance. Also, in my case, I use the option --allow-root , as I am root in my container and Jupyter won’t run unless I use this option.
$ jupyter notebook --ip 0.0.0.0 --port <container port> --allow-root
Oh, and if you prefer the new cool jupyter lab, just use the following command instead.
$ jupyter lab --ip 0.0.0.0 --port <container port> --allow-root
Now, on my host, I simply go to localhost:9999 and voila, there you go.
If you have a similar working environment, I would recommend to enable more ports for remote access. You can simply add those to your ssh command using -L <local port>:localhost:<remote port> . This way, if you ever happen to run other services on some ports in your docker machine you can easily access them remotely.
As you add more options to your ssh command, it increases it size. An option is to define a host under ~/.ssh/config file. In my case I added a user <name>:
Host <name> Hostname <remote IP> Port <remote port for SSH (typically 22)> IdentityFile <path to rsa key> LocalForward 9999 127.0.0.1:9999
A good way to test out if your tunneling is working, is to use http.server from python. This way you can check for every stage if the ports were correctly forwarded. Use the following command to run a simple http server on a particular port.
$ python -m http.server <remote port>
Note that this works for python3, for python2 versions use python -m SimpleHTTPServer <remote port> instead.
If you get any other difficulties, please leave it in the comments and I’ll be glad to help you! | [
{
"code": null,
"e": 485,
"s": 172,
"text": "In my research I work with Machine Learning/Deep Learning algorithms, which I mostly develop using Python. As such, I find it useful to test different frameworks (such as Keras, PyTorch, Tensorflow...). This lead me to using Docker, and in particular ufoym/deepo image as it provides a very complete environment."
},
{
"code": null,
"e": 847,
"s": 485,
"text": "I use a remote machine with GPUs, where I have Docker installed. When programming and testing some code snippets, I find it really helpful to use Jupyter. I had previously used Jupyter locally... but question here was how could I remotely use Jupyter running on a another machine. And on top of that, what if I was using a Docker container on my remote machine?"
},
{
"code": null,
"e": 1020,
"s": 847,
"text": "In this tutorial I will try to share my experience in how I solved this puzzle and made it possible to locally use the Jupyter web-app running the code in a remote machine."
},
{
"code": null,
"e": 1075,
"s": 1020,
"text": "Let me first illustrate my working environment set up."
},
{
"code": null,
"e": 1301,
"s": 1075,
"text": "I use my regular laptop as the host machine.I connect to the server of my department (remote) via ssh.I then connect to a specific machine within the server which has GPUs.Finally I start the docker container in that machine."
},
{
"code": null,
"e": 1346,
"s": 1301,
"text": "I use my regular laptop as the host machine."
},
{
"code": null,
"e": 1405,
"s": 1346,
"text": "I connect to the server of my department (remote) via ssh."
},
{
"code": null,
"e": 1476,
"s": 1405,
"text": "I then connect to a specific machine within the server which has GPUs."
},
{
"code": null,
"e": 1530,
"s": 1476,
"text": "Finally I start the docker container in that machine."
},
{
"code": null,
"e": 1820,
"s": 1530,
"text": "In my particular case, the machine I work on is the one labeled as GPU in the above picture, which happens to be only accessible from another machine within the server. Hence the double ssh... But in your case you might be able to connect directly to your GPU machine from the outer world."
},
{
"code": null,
"e": 1907,
"s": 1820,
"text": "It sounds like messy, but bear with me, you just need to organise it once and for all."
},
{
"code": null,
"e": 2146,
"s": 1907,
"text": "Make sure to have docker installed in your remote machine. If you are unfamiliar with Docker, please check some of the resources available (I found this and this to be helpful). If you are aiming for a GPU-support environment, check next."
},
{
"code": null,
"e": 2462,
"s": 2146,
"text": "If your remote machine has GPUs you might want to exploit this fact. Make sure you have the NVIDIA driver installed. You also need to install nvidia-docker. Note that by installing nvidia-docker we automatically install the last stable release of docker-ce, hence you don’t need to explicitly install docker before."
},
{
"code": null,
"e": 2665,
"s": 2462,
"text": "Jupyter Notebook runs on a certain port on the machine. Hence, the basic idea would be to make that port reachable from your host machine. Luckily, ssh provides the -L option to specify port forwarding."
},
{
"code": null,
"e": 2722,
"s": 2665,
"text": "$ ssh -L <host port>:localhost:<remote port> user@remote"
},
{
"code": null,
"e": 2806,
"s": 2722,
"text": "In my case I use port 9999 in both ends, namely <host port> = <remote port> = 9999."
},
{
"code": null,
"e": 2855,
"s": 2806,
"text": "Here the approach is exactly the same as before."
},
{
"code": null,
"e": 2908,
"s": 2855,
"text": "$ ssh -L <remote port>:localhost:<GPU port> user@GPU"
},
{
"code": null,
"e": 2957,
"s": 2908,
"text": "Again, I use <host port> = <remote port> = 9999."
},
{
"code": null,
"e": 3210,
"s": 2957,
"text": "This step is slightly different. First, you need to create a docker container using some docker image of your preference. In my case, as aforementioned, I am using ufoym/deepo. Since I want GPU-support, I will use nvidia-docker to create the container."
},
{
"code": null,
"e": 3310,
"s": 3210,
"text": "$ nvidia-docker run -it \\-p <GPU port>:<container port> \\--name <container name> \\ufoym/deepo bash"
},
{
"code": null,
"e": 3540,
"s": 3310,
"text": "Note the option -p , which tells the docker container to do port forwarding. This way, we can get access to apps running in the docker on a certain port from the outside world. Here, I also use <host port> = <remote port> = 9999."
},
{
"code": null,
"e": 3687,
"s": 3540,
"text": "By the way, an extremely useful option when creating a container is -v, which allows you to access machine files from within the docker container."
},
{
"code": null,
"e": 3978,
"s": 3687,
"text": "Well, once all the tunneling is set up, we can start our jupyter app. We will use 0.0.0.0 ip and the same port we used when creating the docker container instance. Also, in my case, I use the option --allow-root , as I am root in my container and Jupyter won’t run unless I use this option."
},
{
"code": null,
"e": 4047,
"s": 3978,
"text": "$ jupyter notebook --ip 0.0.0.0 --port <container port> --allow-root"
},
{
"code": null,
"e": 4135,
"s": 4047,
"text": "Oh, and if you prefer the new cool jupyter lab, just use the following command instead."
},
{
"code": null,
"e": 4199,
"s": 4135,
"text": "$ jupyter lab --ip 0.0.0.0 --port <container port> --allow-root"
},
{
"code": null,
"e": 4271,
"s": 4199,
"text": "Now, on my host, I simply go to localhost:9999 and voila, there you go."
},
{
"code": null,
"e": 4590,
"s": 4271,
"text": "If you have a similar working environment, I would recommend to enable more ports for remote access. You can simply add those to your ssh command using -L <local port>:localhost:<remote port> . This way, if you ever happen to run other services on some ports in your docker machine you can easily access them remotely."
},
{
"code": null,
"e": 4747,
"s": 4590,
"text": "As you add more options to your ssh command, it increases it size. An option is to define a host under ~/.ssh/config file. In my case I added a user <name>:"
},
{
"code": null,
"e": 4890,
"s": 4747,
"text": "Host <name> Hostname <remote IP> Port <remote port for SSH (typically 22)> IdentityFile <path to rsa key> LocalForward 9999 127.0.0.1:9999"
},
{
"code": null,
"e": 5132,
"s": 4890,
"text": "A good way to test out if your tunneling is working, is to use http.server from python. This way you can check for every stage if the ports were correctly forwarded. Use the following command to run a simple http server on a particular port."
},
{
"code": null,
"e": 5170,
"s": 5132,
"text": "$ python -m http.server <remote port>"
},
{
"code": null,
"e": 5279,
"s": 5170,
"text": "Note that this works for python3, for python2 versions use python -m SimpleHTTPServer <remote port> instead."
}
] |
Find duplicate rows in a binary matrix | Practice | GeeksforGeeks | Given a boolean matrix of size RxC where each cell contains either 0 or 1, find the row numbers of row (0-based) which already exists or are repeated.
Example 1:
Input:
R = 2, C = 2
matrix[][] = {{1, 0},
{1, 0}}
Output:
1
Explanation:
Row 1 is duplicate of Row 0.
Example 2:
Input:
R = 4, C = 3
matrix[][] = {{ 1, 0, 0},
{ 1, 0, 0},
{ 1, 0, 0},
{ 0, 0, 0}}
Output:
1 2
Explanation:
Row 1 and Row 2 are duplicates of Row 0.
Your Task:
You dont need to read input or print anything. Complete the function repeatedRows() that takes the matrix as input parameter and returns a list of row numbers which are duplicate rows.
Expected Time Complexity: O(R * C)
Expected Auxiliary Space: O(R*C)
Constraints:
1 ≤ R ≤ 1000
1 ≤ C ≤ 20
0 ≤ matrix[i][j] ≤ 1
0
prajjwalfire5 days ago
BIT Masking for each row and Map
vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N)
{
unordered_map<int,int> ma;
vector<int> kim;
for(int r=0;r<M;r++)
{
int num=0;
for(int c=0;c<N;c++)
{
if(matrix[r][c])
{
num=num|(1<<c);
}
}
if(ma.count(num))
kim.push_back(r);
else
ma[num]++;
}
return kim;
}
0
shuklaps11192 weeks ago
//1.3/6.28 java solution.......
class Solution
{
public static ArrayList<Integer> repeatedRows(int matrix[][], int m, int n)
{
//code here
HashSet<String> s = new HashSet<>();
ArrayList<Integer> al = new ArrayList<>();
for(int i=0;i<m;i++){
String str = "";
for(int j=0;j<n;j++)
str += matrix[i][j];
if(s.contains(str))
al.add(i);
else
s.add(str);
}
return al;
}
}
0
shilpfizzy4 weeks ago
class Solution{ public:vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N) { set<int> st; int deci; vector<int> res; for(int i=0; i<M; i++){ deci = 0; for(int j=0; j<N; j++){ deci += (matrix[i][j] * pow(2,j)); } if(st.find(deci) != st.end()){ res.push_back(i); } else{ st.insert(deci); } } return res;} };
0
shibombhowmik12091 month ago
struct Node{
Node *links[2];
bool flag=false;
bool containsKey(int x){
return (links[x]!=NULL);
}
void put(int x,Node *node){
links[x]=node;
}
Node *get(int x){
return links[x];
}
void setEnd(){
flag=true;
}
bool getEnd(){
return flag;
}
};
class Trie{
private:Node *root;
public:
Trie(){
root=new Node();
}
void insert(vector<int> v){
Node *node=root;
for(int i=0;i<v.size();i++){
if(!node->containsKey(v[i])){
node->put(v[i],new Node());
}
node=node->get(v[i]);
}
node->setEnd();
}
bool ispresent(vector<int> v){
Node *node=root;
for(int i=0;i<v.size();i++){
if(node->containsKey(v[i])){
node=node->get(v[i]);
}
else{
return false;
}
}
return node->getEnd();
}
};
class Solution
{
public:
vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N)
{
// Your code here
Trie *obj=new Trie();
vector<int> res;
for(int i=0;i<M;i++){
vector<int> v;
for(int j=0;j<N;j++){
v.emplace_back(matrix[i][j]);
}
if(obj->ispresent(v)){
res.emplace_back(i);
}
obj->insert(v);
}
return res;
}
};
+1
vt28522412 months ago
Easy Java solution using HashSet
public static ArrayList<Integer> repeatedRows(int matrix[][], int m, int n) { HashSet<String> set=new HashSet<>(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0; i<m; i++){ String str=""; for(int j=0; j<n; j++){ str+=matrix[i][j]; } if(set.contains(str)){ list.add(i); } else{ set.add(str); } } return list; }
0
kumaarsahab4322 months ago
//Using HashMap
vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N)
{
map<vector<int>, int> m ;
vector<int> ans;
for(int i=0 ; i<M ; i++)
{
vector<int> x=matrix[i] ;
if(m[x]>0) ans.push_back(i) ;
m[x]++ ;
}
return ans ;
}
+1
himanshujain4572 months ago
Simple Java Solution Using Trie:
class Solution{ static class TrieNode{ int wordend=0; TrieNode child[]=new TrieNode[2]; TrieNode() { for(int i=0;i<2;i++) { child[i]=null; } } } static TrieNode root=new TrieNode(); static void BuildTrie(int matrix[][], int m, int n) { for(int i=0;i<m;i++) { TrieNode temp=root; for(int j=0;j<n;j++) { if(temp.child[matrix[i][j]]==null) { temp.child[matrix[i][j]]=new TrieNode(); } temp=temp.child[matrix[i][j]]; } temp.wordend=1; } } public static ArrayList<Integer> repeatedRows(int matrix[][], int m, int n) { ArrayList<Integer>res=new ArrayList<Integer>(); BuildTrie(matrix,m,n); for(int i=0;i<m;i++) { TrieNode temp=root; for(int j=0;j<n;j++) { temp=temp.child[matrix[i][j]]; } if(temp.wordend==1) { temp.wordend=0; } else { res.add(i); } } return res; }}
+1
abisheksrinivasan3 months ago
Simple Python soln:
def repeatedRows(self, a, m ,n):
strings, res = set(), []
for r in range(m):
s=''
for c in range(n):
s+=str(a[r][c])
if s in strings:
res.append(r)
else:
strings.add(s)
return res
0
paurushbatish3 months ago
Easy question →
vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N)
{
// Your code here
map<vector<int>, vector<int>>m;
vector<int>ans;
for(int i = 0;i<M;i++){
vector<int>x = matrix[i];
if(m[x].size()!=0){
ans.push_back(i);
}
m[x].push_back(i);
}
return ans;
}
0
abhishekpundir5263 months ago
string s = ""; set<string>st; vector<int>ans; for(int i = 0;i < matrix.size();i++){ s = ""; for(int j = 0;j < matrix[i].size();j++){ s = s + to_string(matrix[i][j]); } if(st.find(s) != st.end()){ ans.push_back(i); } else{ st.insert(s); } } return ans;
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as the final solution code.
You can view the solutions submitted by other users from the submission tab. | [
{
"code": null,
"e": 389,
"s": 238,
"text": "Given a boolean matrix of size RxC where each cell contains either 0 or 1, find the row numbers of row (0-based) which already exists or are repeated."
},
{
"code": null,
"e": 400,
"s": 389,
"text": "Example 1:"
},
{
"code": null,
"e": 517,
"s": 400,
"text": "Input:\nR = 2, C = 2\nmatrix[][] = {{1, 0},\n {1, 0}}\nOutput: \n1\nExplanation:\nRow 1 is duplicate of Row 0."
},
{
"code": null,
"e": 529,
"s": 517,
"text": "\nExample 2:"
},
{
"code": null,
"e": 722,
"s": 529,
"text": "Input:\nR = 4, C = 3\nmatrix[][] = {{ 1, 0, 0},\n { 1, 0, 0},\n { 1, 0, 0},\n { 0, 0, 0}}\nOutput: \n1 2 \nExplanation:\nRow 1 and Row 2 are duplicates of Row 0. "
},
{
"code": null,
"e": 921,
"s": 722,
"text": "\nYour Task:\nYou dont need to read input or print anything. Complete the function repeatedRows() that takes the matrix as input parameter and returns a list of row numbers which are duplicate rows.\n "
},
{
"code": null,
"e": 992,
"s": 921,
"text": "Expected Time Complexity: O(R * C)\nExpected Auxiliary Space: O(R*C) \n "
},
{
"code": null,
"e": 1050,
"s": 992,
"text": "Constraints:\n1 ≤ R ≤ 1000\n1 ≤ C ≤ 20\n0 ≤ matrix[i][j] ≤ 1"
},
{
"code": null,
"e": 1052,
"s": 1050,
"text": "0"
},
{
"code": null,
"e": 1075,
"s": 1052,
"text": "prajjwalfire5 days ago"
},
{
"code": null,
"e": 1108,
"s": 1075,
"text": "BIT Masking for each row and Map"
},
{
"code": null,
"e": 1559,
"s": 1108,
"text": "vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N) \n{ \n unordered_map<int,int> ma;\n vector<int> kim;\n for(int r=0;r<M;r++)\n {\n int num=0;\n \n for(int c=0;c<N;c++)\n {\n if(matrix[r][c])\n {\n num=num|(1<<c);\n }\n }\n \n if(ma.count(num))\n kim.push_back(r);\n else\n ma[num]++;\n }\n \n return kim;\n} "
},
{
"code": null,
"e": 1561,
"s": 1559,
"text": "0"
},
{
"code": null,
"e": 1585,
"s": 1561,
"text": "shuklaps11192 weeks ago"
},
{
"code": null,
"e": 2155,
"s": 1585,
"text": "//1.3/6.28 java solution.......\n\nclass Solution\n{\n public static ArrayList<Integer> repeatedRows(int matrix[][], int m, int n)\n {\n //code here\n HashSet<String> s = new HashSet<>();\n ArrayList<Integer> al = new ArrayList<>();\n for(int i=0;i<m;i++){\n String str = \"\";\n for(int j=0;j<n;j++)\n str += matrix[i][j];\n \n \n if(s.contains(str))\n al.add(i);\n else\n s.add(str);\n \n }\n \n return al;\n }\n}"
},
{
"code": null,
"e": 2157,
"s": 2155,
"text": "0"
},
{
"code": null,
"e": 2179,
"s": 2157,
"text": "shilpfizzy4 weeks ago"
},
{
"code": null,
"e": 2616,
"s": 2179,
"text": "class Solution{ public:vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N) { set<int> st; int deci; vector<int> res; for(int i=0; i<M; i++){ deci = 0; for(int j=0; j<N; j++){ deci += (matrix[i][j] * pow(2,j)); } if(st.find(deci) != st.end()){ res.push_back(i); } else{ st.insert(deci); } } return res;} };"
},
{
"code": null,
"e": 2618,
"s": 2616,
"text": "0"
},
{
"code": null,
"e": 2647,
"s": 2618,
"text": "shibombhowmik12091 month ago"
},
{
"code": null,
"e": 4389,
"s": 2647,
"text": "struct Node{\n Node *links[2];\n bool flag=false;\n \n bool containsKey(int x){\n return (links[x]!=NULL);\n }\n \n void put(int x,Node *node){\n links[x]=node;\n }\n \n Node *get(int x){\n return links[x];\n }\n \n void setEnd(){\n flag=true;\n }\n \n bool getEnd(){\n return flag;\n }\n};\n\nclass Trie{\n private:Node *root;\n public:\n Trie(){\n root=new Node();\n }\n \n void insert(vector<int> v){\n Node *node=root;\n for(int i=0;i<v.size();i++){\n if(!node->containsKey(v[i])){\n node->put(v[i],new Node());\n }\n \n node=node->get(v[i]);\n }\n \n node->setEnd();\n }\n \n bool ispresent(vector<int> v){\n Node *node=root;\n for(int i=0;i<v.size();i++){\n if(node->containsKey(v[i])){\n node=node->get(v[i]); \n }\n else{\n return false;\n }\n }\n \n return node->getEnd();\n }\n};\n\nclass Solution\n{ \npublic:\nvector<int> repeatedRows(vector<vector<int>> matrix, int M, int N) \n{ \n // Your code here\n Trie *obj=new Trie();\n vector<int> res;\n \n for(int i=0;i<M;i++){\n vector<int> v;\n for(int j=0;j<N;j++){\n v.emplace_back(matrix[i][j]);\n }\n \n if(obj->ispresent(v)){\n res.emplace_back(i);\n }\n obj->insert(v);\n }\n \n return res;\n} \n};"
},
{
"code": null,
"e": 4392,
"s": 4389,
"text": "+1"
},
{
"code": null,
"e": 4414,
"s": 4392,
"text": "vt28522412 months ago"
},
{
"code": null,
"e": 4447,
"s": 4414,
"text": "Easy Java solution using HashSet"
},
{
"code": null,
"e": 4919,
"s": 4447,
"text": "public static ArrayList<Integer> repeatedRows(int matrix[][], int m, int n) { HashSet<String> set=new HashSet<>(); ArrayList<Integer> list=new ArrayList<>(); for(int i=0; i<m; i++){ String str=\"\"; for(int j=0; j<n; j++){ str+=matrix[i][j]; } if(set.contains(str)){ list.add(i); } else{ set.add(str); } } return list; }"
},
{
"code": null,
"e": 4921,
"s": 4919,
"text": "0"
},
{
"code": null,
"e": 4948,
"s": 4921,
"text": "kumaarsahab4322 months ago"
},
{
"code": null,
"e": 5281,
"s": 4948,
"text": "//Using HashMap\nvector<int> repeatedRows(vector<vector<int>> matrix, int M, int N) \n { \n map<vector<int>, int> m ;\n vector<int> ans; \n for(int i=0 ; i<M ; i++)\n {\n vector<int> x=matrix[i] ;\n if(m[x]>0) ans.push_back(i) ;\n m[x]++ ;\n }\n return ans ; \n }"
},
{
"code": null,
"e": 5284,
"s": 5281,
"text": "+1"
},
{
"code": null,
"e": 5312,
"s": 5284,
"text": "himanshujain4572 months ago"
},
{
"code": null,
"e": 5346,
"s": 5312,
"text": "Simple Java Solution Using Trie:"
},
{
"code": null,
"e": 6551,
"s": 5346,
"text": "class Solution{ static class TrieNode{ int wordend=0; TrieNode child[]=new TrieNode[2]; TrieNode() { for(int i=0;i<2;i++) { child[i]=null; } } } static TrieNode root=new TrieNode(); static void BuildTrie(int matrix[][], int m, int n) { for(int i=0;i<m;i++) { TrieNode temp=root; for(int j=0;j<n;j++) { if(temp.child[matrix[i][j]]==null) { temp.child[matrix[i][j]]=new TrieNode(); } temp=temp.child[matrix[i][j]]; } temp.wordend=1; } } public static ArrayList<Integer> repeatedRows(int matrix[][], int m, int n) { ArrayList<Integer>res=new ArrayList<Integer>(); BuildTrie(matrix,m,n); for(int i=0;i<m;i++) { TrieNode temp=root; for(int j=0;j<n;j++) { temp=temp.child[matrix[i][j]]; } if(temp.wordend==1) { temp.wordend=0; } else { res.add(i); } } return res; }}"
},
{
"code": null,
"e": 6554,
"s": 6551,
"text": "+1"
},
{
"code": null,
"e": 6584,
"s": 6554,
"text": "abisheksrinivasan3 months ago"
},
{
"code": null,
"e": 6604,
"s": 6584,
"text": "Simple Python soln:"
},
{
"code": null,
"e": 6904,
"s": 6604,
"text": "def repeatedRows(self, a, m ,n):\n strings, res = set(), []\n for r in range(m):\n s=''\n for c in range(n):\n s+=str(a[r][c])\n if s in strings:\n res.append(r)\n else:\n strings.add(s)\n return res"
},
{
"code": null,
"e": 6906,
"s": 6904,
"text": "0"
},
{
"code": null,
"e": 6932,
"s": 6906,
"text": "paurushbatish3 months ago"
},
{
"code": null,
"e": 6949,
"s": 6932,
"text": "Easy question →"
},
{
"code": null,
"e": 7290,
"s": 6949,
"text": "vector<int> repeatedRows(vector<vector<int>> matrix, int M, int N) \n{ \n // Your code here\n map<vector<int>, vector<int>>m;\n vector<int>ans;\n for(int i = 0;i<M;i++){\n vector<int>x = matrix[i];\n if(m[x].size()!=0){\n ans.push_back(i);\n }\n m[x].push_back(i);\n \n }\n \n return ans;\n}"
},
{
"code": null,
"e": 7292,
"s": 7290,
"text": "0"
},
{
"code": null,
"e": 7322,
"s": 7292,
"text": "abhishekpundir5263 months ago"
},
{
"code": null,
"e": 7667,
"s": 7322,
"text": " string s = \"\"; set<string>st; vector<int>ans; for(int i = 0;i < matrix.size();i++){ s = \"\"; for(int j = 0;j < matrix[i].size();j++){ s = s + to_string(matrix[i][j]); } if(st.find(s) != st.end()){ ans.push_back(i); } else{ st.insert(s); } } return ans; "
},
{
"code": null,
"e": 7813,
"s": 7667,
"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": 7849,
"s": 7813,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7859,
"s": 7849,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7869,
"s": 7859,
"text": "\nContest\n"
},
{
"code": null,
"e": 7932,
"s": 7869,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 8080,
"s": 7932,
"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": 8288,
"s": 8080,
"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": 8394,
"s": 8288,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
How to replace missing values with linear interpolation method in an R vector? | The linear interpolation is a method of fitting a curve using linear polynomials and it helps us to create a new data points but these points lie within the range of the original values for which the linear interpolation is done. Sometimes these values may go a little far from the original values but not too far. In R, if we have some missing values then na.approx function of zoo package can be used to replace the NA with linear interpolation method.
Loading zoo package:
Live Demo
> library(zoo)
> x1<-sample(c(NA,2,5),10,replace=TRUE)
> x1
[1] 2 2 2 5 2 2 5 NA 2 5
Replacing NA with linear interpolation:
> na.approx(x1)
[1] 2.0 2.0 2.0 5.0 2.0 2.0 5.0 3.5 2.0 5.0
Live Demo
> x2<-sample(c(NA,1:4),150,replace=TRUE)
> x2
[1] 2 NA NA 2 1 1 NA 2 4 NA 1 2 1 4 3 3 1 3 1 4 4 2 3 1 3
[26] 1 4 2 4 2 1 2 1 3 NA 2 NA 3 1 2 3 3 3 2 4 4 3 3 4 3
[51] 1 4 3 1 4 NA NA NA 2 NA 3 4 NA 2 3 3 1 4 2 4 NA NA 4 3 2
[76] 3 NA 3 NA 4 3 2 3 NA 3 1 1 3 2 NA 1 3 3 NA 3 NA 2 NA 4 1
[101] NA 2 2 4 3 NA 4 NA 2 2 NA 3 2 NA NA 3 NA 3 1 NA 1 NA 1 NA 1
[126] 2 1 3 4 1 4 2 3 NA 3 NA NA 4 NA 2 NA 4 2 3 NA 1 2 1 3 4
> na.approx(x2)
[1] 2.000000 2.000000 2.000000 2.000000 1.000000 1.000000 1.500000 2.000000
[9] 4.000000 2.500000 1.000000 2.000000 1.000000 4.000000 3.000000 3.000000
[17] 1.000000 3.000000 1.000000 4.000000 4.000000 2.000000 3.000000 1.000000
[25] 3.000000 1.000000 4.000000 2.000000 4.000000 2.000000 1.000000 2.000000
[33] 1.000000 3.000000 2.500000 2.000000 2.500000 3.000000 1.000000 2.000000
[41] 3.000000 3.000000 3.000000 2.000000 4.000000 4.000000 3.000000 3.000000
[49] 4.000000 3.000000 1.000000 4.000000 3.000000 1.000000 4.000000 3.500000
[57] 3.000000 2.500000 2.000000 2.500000 3.000000 4.000000 3.000000 2.000000
[65] 3.000000 3.000000 1.000000 4.000000 2.000000 4.000000 4.000000 4.000000
[73] 4.000000 3.000000 2.000000 3.000000 3.000000 3.000000 3.500000 4.000000
[81] 3.000000 2.000000 3.000000 3.000000 3.000000 1.000000 1.000000 3.000000
[89] 2.000000 1.500000 1.000000 3.000000 3.000000 3.000000 3.000000 2.500000
[97] 2.000000 3.000000 4.000000 1.000000 1.500000 2.000000 2.000000 4.000000
[105] 3.000000 3.500000 4.000000 3.000000 2.000000 2.000000 2.500000 3.000000
[113] 2.000000 2.333333 2.666667 3.000000 3.000000 3.000000 1.000000 1.000000
[121] 1.000000 1.000000 1.000000 1.000000 1.000000 2.000000 1.000000 3.000000
[129] 4.000000 1.000000 4.000000 2.000000 3.000000 3.000000 3.000000 3.333333
[137] 3.666667 4.000000 3.000000 2.000000 3.000000 4.000000 2.000000 3.000000
[145] 2.000000 1.000000 2.000000 1.000000 3.000000 4.000000
Live Demo
> x3<-sample(c(NA,rnorm(5)),80,replace=TRUE)
> x3
[1] -0.7419539 -0.7419539 -0.7419539 -0.7419539 NA -0.2225833
[7] -0.7240064 0.8134500 -0.2225833 -0.2225833 0.8134500 -0.7419539
[13] -0.7240064 -0.7419539 -0.7240064 -0.7419539 -0.7240064 0.7383318
[19] NA -0.7240064 0.7383318 0.7383318 NA 0.8134500
[25] -0.2225833 -0.7419539 -0.2225833 0.8134500 0.8134500 NA
[31] -0.2225833 -0.2225833 -0.7240064 -0.2225833 0.7383318 NA
[37] NA -0.7419539 -0.7240064 -0.7240064 -0.7419539 0.7383318
[43] 0.8134500 -0.7240064 0.7383318 0.8134500 0.7383318 0.8134500
[49] 0.7383318 -0.7240064 -0.2225833 -0.7240064 -0.7240064 -0.7240064
[55] 0.7383318 0.7383318 NA -0.2225833 -0.7419539 -0.7419539
[61] 0.8134500 -0.2225833 -0.2225833 0.7383318 -0.2225833 0.8134500
[67] -0.2225833 0.7383318 -0.7240064 0.7383318 NA -0.2225833
[73] 0.7383318 -0.7419539 0.8134500 -0.2225833 NA -0.7240064
[79] -0.2225833 -0.2225833
> na.approx(x3)
[1] -0.741953856 -0.741953856 -0.741953856 -0.741953856 -0.482268589
[6] -0.222583323 -0.724006386 0.813450002 -0.222583323 -0.222583323
[11] 0.813450002 -0.741953856 -0.724006386 -0.741953856 -0.724006386
[16] -0.741953856 -0.724006386 0.738331799 0.007162706 -0.724006386
[21] 0.738331799 0.738331799 0.775890900 0.813450002 -0.222583323
[26] -0.741953856 -0.222583323 0.813450002 0.813450002 0.295433340
[31] -0.222583323 -0.222583323 -0.724006386 -0.222583323 0.738331799
[36] 0.244903247 -0.248525304 -0.741953856 -0.724006386 -0.724006386
[41] -0.741953856 0.738331799 0.813450002 -0.724006386 0.738331799
[46] 0.813450002 0.738331799 0.813450002 0.738331799 -0.724006386
[51] -0.222583323 -0.724006386 -0.724006386 -0.724006386 0.738331799
[56] 0.738331799 0.257874238 -0.222583323 -0.741953856 -0.741953856
[61] 0.813450002 -0.222583323 -0.222583323 0.738331799 -0.222583323
[66] 0.813450002 -0.222583323 0.738331799 -0.724006386 0.738331799
[71] 0.257874238 -0.222583323 0.738331799 -0.741953856 0.813450002
[76] -0.222583323 -0.473294855 -0.724006386 -0.222583323 -0.222583323
Live Demo
> x4<-sample(c(NA,rpois(20,2)),100,replace=TRUE)
> x4
[1] 3 3 0 2 NA 2 2 2 1 NA 0 1 3 3 3 3 1 1 3 3 1 2 1 1 2
[26] 3 5 5 0 2 1 1 3 2 1 3 2 NA 3 3 0 0 3 3 6 2 3 3 2 3
[51] 3 2 0 NA 2 NA 3 5 NA 0 3 1 5 2 1 NA 3 3 3 2 2 6 5 2 1
[76] 2 1 5 2 3 NA 0 0 2 2 2 0 5 2 3 6 0 3 3 3 3 2 2 3 1
> na.approx(x4)
[1] 3.0 3.0 0.0 2.0 2.0 2.0 2.0 2.0 1.0 0.5 0.0 1.0 3.0 3.0 3.0 3.0 1.0 1.0
[19] 3.0 3.0 1.0 2.0 1.0 1.0 2.0 3.0 5.0 5.0 0.0 2.0 1.0 1.0 3.0 2.0 1.0 3.0
[37] 2.0 2.5 3.0 3.0 0.0 0.0 3.0 3.0 6.0 2.0 3.0 3.0 2.0 3.0 3.0 2.0 0.0 1.0
[55] 2.0 2.5 3.0 5.0 2.5 0.0 3.0 1.0 5.0 2.0 1.0 2.0 3.0 3.0 3.0 2.0 2.0 6.0
[73] 5.0 2.0 1.0 2.0 1.0 5.0 2.0 3.0 1.5 0.0 0.0 2.0 2.0 2.0 0.0 5.0 2.0 3.0
[91] 6.0 0.0 3.0 3.0 3.0 3.0 2.0 2.0 3.0 1.0
Live Demo
> x5<-sample(c(NA,rpois(5,3)),100,replace=TRUE)
> x5
[1] 3 1 3 6 5 3 5 NA 5 5 3 1 3 1 3 NA 3 5 6 NA 3 3 5 5 3
[26] 5 NA 3 3 3 5 5 NA 5 6 3 1 3 1 3 3 5 NA 5 6 1 3 6 5 5
[51] 1 5 NA 5 NA 1 5 3 1 6 NA 5 1 5 NA NA 6 6 5 1 5 5 NA 3 5
[76] 5 5 5 1 5 NA NA 1 6 5 5 5 5 5 1 5 NA 1 NA 3 NA 3 6 5 1
> na.approx(x5)
[1] 3.000000 1.000000 3.000000 6.000000 5.000000 3.000000 5.000000 5.000000
[9] 5.000000 5.000000 3.000000 1.000000 3.000000 1.000000 3.000000 3.000000
[17] 3.000000 5.000000 6.000000 4.500000 3.000000 3.000000 5.000000 5.000000
[25] 3.000000 5.000000 4.000000 3.000000 3.000000 3.000000 5.000000 5.000000
[33] 5.000000 5.000000 6.000000 3.000000 1.000000 3.000000 1.000000 3.000000
[41] 3.000000 5.000000 5.000000 5.000000 6.000000 1.000000 3.000000 6.000000
[49] 5.000000 5.000000 1.000000 5.000000 5.000000 5.000000 3.000000 1.000000
[57] 5.000000 3.000000 1.000000 6.000000 5.500000 5.000000 1.000000 5.000000
[65] 5.333333 5.666667 6.000000 6.000000 5.000000 1.000000 5.000000 5.000000
[73] 4.000000 3.000000 5.000000 5.000000 5.000000 5.000000 1.000000 5.000000
[81] 3.666667 2.333333 1.000000 6.000000 5.000000 5.000000 5.000000 5.000000
[89] 5.000000 1.000000 5.000000 3.000000 1.000000 2.000000 3.000000 3.000000
[97] 3.000000 6.000000 5.000000 1.000000 | [
{
"code": null,
"e": 1517,
"s": 1062,
"text": "The linear interpolation is a method of fitting a curve using linear polynomials and it helps us to create a new data points but these points lie within the range of the original values for which the linear interpolation is done. Sometimes these values may go a little far from the original values but not too far. In R, if we have some missing values then na.approx function of zoo package can be used to replace the NA with linear interpolation method."
},
{
"code": null,
"e": 1538,
"s": 1517,
"text": "Loading zoo package:"
},
{
"code": null,
"e": 1548,
"s": 1538,
"text": "Live Demo"
},
{
"code": null,
"e": 1608,
"s": 1548,
"text": "> library(zoo)\n> x1<-sample(c(NA,2,5),10,replace=TRUE)\n> x1"
},
{
"code": null,
"e": 1633,
"s": 1608,
"text": "[1] 2 2 2 5 2 2 5 NA 2 5"
},
{
"code": null,
"e": 1673,
"s": 1633,
"text": "Replacing NA with linear interpolation:"
},
{
"code": null,
"e": 1689,
"s": 1673,
"text": "> na.approx(x1)"
},
{
"code": null,
"e": 1734,
"s": 1689,
"text": "[1] 2.0 2.0 2.0 5.0 2.0 2.0 5.0 3.5 2.0 5.0\n"
},
{
"code": null,
"e": 1744,
"s": 1734,
"text": "Live Demo"
},
{
"code": null,
"e": 1790,
"s": 1744,
"text": "> x2<-sample(c(NA,1:4),150,replace=TRUE)\n> x2"
},
{
"code": null,
"e": 2157,
"s": 1790,
"text": "[1] 2 NA NA 2 1 1 NA 2 4 NA 1 2 1 4 3 3 1 3 1 4 4 2 3 1 3\n[26] 1 4 2 4 2 1 2 1 3 NA 2 NA 3 1 2 3 3 3 2 4 4 3 3 4 3\n[51] 1 4 3 1 4 NA NA NA 2 NA 3 4 NA 2 3 3 1 4 2 4 NA NA 4 3 2\n[76] 3 NA 3 NA 4 3 2 3 NA 3 1 1 3 2 NA 1 3 3 NA 3 NA 2 NA 4 1\n[101] NA 2 2 4 3 NA 4 NA 2 2 NA 3 2 NA NA 3 NA 3 1 NA 1 NA 1 NA 1\n[126] 2 1 3 4 1 4 2 3 NA 3 NA NA 4 NA 2 NA 4 2 3 NA 1 2 1 3 4"
},
{
"code": null,
"e": 2173,
"s": 2157,
"text": "> na.approx(x2)"
},
{
"code": null,
"e": 3624,
"s": 2173,
"text": " [1] 2.000000 2.000000 2.000000 2.000000 1.000000 1.000000 1.500000 2.000000\n [9] 4.000000 2.500000 1.000000 2.000000 1.000000 4.000000 3.000000 3.000000\n[17] 1.000000 3.000000 1.000000 4.000000 4.000000 2.000000 3.000000 1.000000\n[25] 3.000000 1.000000 4.000000 2.000000 4.000000 2.000000 1.000000 2.000000\n[33] 1.000000 3.000000 2.500000 2.000000 2.500000 3.000000 1.000000 2.000000\n[41] 3.000000 3.000000 3.000000 2.000000 4.000000 4.000000 3.000000 3.000000\n[49] 4.000000 3.000000 1.000000 4.000000 3.000000 1.000000 4.000000 3.500000\n[57] 3.000000 2.500000 2.000000 2.500000 3.000000 4.000000 3.000000 2.000000\n[65] 3.000000 3.000000 1.000000 4.000000 2.000000 4.000000 4.000000 4.000000\n[73] 4.000000 3.000000 2.000000 3.000000 3.000000 3.000000 3.500000 4.000000\n[81] 3.000000 2.000000 3.000000 3.000000 3.000000 1.000000 1.000000 3.000000\n[89] 2.000000 1.500000 1.000000 3.000000 3.000000 3.000000 3.000000 2.500000\n[97] 2.000000 3.000000 4.000000 1.000000 1.500000 2.000000 2.000000 4.000000\n[105] 3.000000 3.500000 4.000000 3.000000 2.000000 2.000000 2.500000 3.000000\n[113] 2.000000 2.333333 2.666667 3.000000 3.000000 3.000000 1.000000 1.000000\n[121] 1.000000 1.000000 1.000000 1.000000 1.000000 2.000000 1.000000 3.000000\n[129] 4.000000 1.000000 4.000000 2.000000 3.000000 3.000000 3.000000 3.333333\n[137] 3.666667 4.000000 3.000000 2.000000 3.000000 4.000000 2.000000 3.000000\n[145] 2.000000 1.000000 2.000000 1.000000 3.000000 4.000000"
},
{
"code": null,
"e": 3634,
"s": 3624,
"text": "Live Demo"
},
{
"code": null,
"e": 3684,
"s": 3634,
"text": "> x3<-sample(c(NA,rnorm(5)),80,replace=TRUE)\n> x3"
},
{
"code": null,
"e": 4535,
"s": 3684,
"text": "[1] -0.7419539 -0.7419539 -0.7419539 -0.7419539 NA -0.2225833\n[7] -0.7240064 0.8134500 -0.2225833 -0.2225833 0.8134500 -0.7419539\n[13] -0.7240064 -0.7419539 -0.7240064 -0.7419539 -0.7240064 0.7383318\n[19] NA -0.7240064 0.7383318 0.7383318 NA 0.8134500\n[25] -0.2225833 -0.7419539 -0.2225833 0.8134500 0.8134500 NA\n[31] -0.2225833 -0.2225833 -0.7240064 -0.2225833 0.7383318 NA\n[37] NA -0.7419539 -0.7240064 -0.7240064 -0.7419539 0.7383318\n[43] 0.8134500 -0.7240064 0.7383318 0.8134500 0.7383318 0.8134500\n[49] 0.7383318 -0.7240064 -0.2225833 -0.7240064 -0.7240064 -0.7240064\n[55] 0.7383318 0.7383318 NA -0.2225833 -0.7419539 -0.7419539\n[61] 0.8134500 -0.2225833 -0.2225833 0.7383318 -0.2225833 0.8134500\n[67] -0.2225833 0.7383318 -0.7240064 0.7383318 NA -0.2225833\n[73] 0.7383318 -0.7419539 0.8134500 -0.2225833 NA -0.7240064\n[79] -0.2225833 -0.2225833"
},
{
"code": null,
"e": 4551,
"s": 4535,
"text": "> na.approx(x3)"
},
{
"code": null,
"e": 5638,
"s": 4551,
"text": "[1] -0.741953856 -0.741953856 -0.741953856 -0.741953856 -0.482268589\n[6] -0.222583323 -0.724006386 0.813450002 -0.222583323 -0.222583323\n[11] 0.813450002 -0.741953856 -0.724006386 -0.741953856 -0.724006386\n[16] -0.741953856 -0.724006386 0.738331799 0.007162706 -0.724006386\n[21] 0.738331799 0.738331799 0.775890900 0.813450002 -0.222583323\n[26] -0.741953856 -0.222583323 0.813450002 0.813450002 0.295433340\n[31] -0.222583323 -0.222583323 -0.724006386 -0.222583323 0.738331799\n[36] 0.244903247 -0.248525304 -0.741953856 -0.724006386 -0.724006386\n[41] -0.741953856 0.738331799 0.813450002 -0.724006386 0.738331799\n[46] 0.813450002 0.738331799 0.813450002 0.738331799 -0.724006386\n[51] -0.222583323 -0.724006386 -0.724006386 -0.724006386 0.738331799\n[56] 0.738331799 0.257874238 -0.222583323 -0.741953856 -0.741953856\n[61] 0.813450002 -0.222583323 -0.222583323 0.738331799 -0.222583323\n[66] 0.813450002 -0.222583323 0.738331799 -0.724006386 0.738331799\n[71] 0.257874238 -0.222583323 0.738331799 -0.741953856 0.813450002\n[76] -0.222583323 -0.473294855 -0.724006386 -0.222583323 -0.222583323"
},
{
"code": null,
"e": 5648,
"s": 5638,
"text": "Live Demo"
},
{
"code": null,
"e": 5702,
"s": 5648,
"text": "> x4<-sample(c(NA,rpois(20,2)),100,replace=TRUE)\n> x4"
},
{
"code": null,
"e": 5929,
"s": 5702,
"text": "[1] 3 3 0 2 NA 2 2 2 1 NA 0 1 3 3 3 3 1 1 3 3 1 2 1 1 2\n[26] 3 5 5 0 2 1 1 3 2 1 3 2 NA 3 3 0 0 3 3 6 2 3 3 2 3\n[51] 3 2 0 NA 2 NA 3 5 NA 0 3 1 5 2 1 NA 3 3 3 2 2 6 5 2 1\n[76] 2 1 5 2 3 NA 0 0 2 2 2 0 5 2 3 6 0 3 3 3 3 2 2 3 1"
},
{
"code": null,
"e": 5945,
"s": 5929,
"text": "> na.approx(x4)"
},
{
"code": null,
"e": 6374,
"s": 5945,
"text": "[1] 3.0 3.0 0.0 2.0 2.0 2.0 2.0 2.0 1.0 0.5 0.0 1.0 3.0 3.0 3.0 3.0 1.0 1.0\n[19] 3.0 3.0 1.0 2.0 1.0 1.0 2.0 3.0 5.0 5.0 0.0 2.0 1.0 1.0 3.0 2.0 1.0 3.0\n[37] 2.0 2.5 3.0 3.0 0.0 0.0 3.0 3.0 6.0 2.0 3.0 3.0 2.0 3.0 3.0 2.0 0.0 1.0\n[55] 2.0 2.5 3.0 5.0 2.5 0.0 3.0 1.0 5.0 2.0 1.0 2.0 3.0 3.0 3.0 2.0 2.0 6.0\n[73] 5.0 2.0 1.0 2.0 1.0 5.0 2.0 3.0 1.5 0.0 0.0 2.0 2.0 2.0 0.0 5.0 2.0 3.0\n[91] 6.0 0.0 3.0 3.0 3.0 3.0 2.0 2.0 3.0 1.0"
},
{
"code": null,
"e": 6384,
"s": 6374,
"text": "Live Demo"
},
{
"code": null,
"e": 6437,
"s": 6384,
"text": "> x5<-sample(c(NA,rpois(5,3)),100,replace=TRUE)\n> x5"
},
{
"code": null,
"e": 6673,
"s": 6437,
"text": "[1] 3 1 3 6 5 3 5 NA 5 5 3 1 3 1 3 NA 3 5 6 NA 3 3 5 5 3\n[26] 5 NA 3 3 3 5 5 NA 5 6 3 1 3 1 3 3 5 NA 5 6 1 3 6 5 5\n[51] 1 5 NA 5 NA 1 5 3 1 6 NA 5 1 5 NA NA 6 6 5 1 5 5 NA 3 5\n[76] 5 5 5 1 5 NA NA 1 6 5 5 5 5 5 1 5 NA 1 NA 3 NA 3 6 5 1"
},
{
"code": null,
"e": 6689,
"s": 6673,
"text": "> na.approx(x5)"
},
{
"code": null,
"e": 7654,
"s": 6689,
"text": " [1] 3.000000 1.000000 3.000000 6.000000 5.000000 3.000000 5.000000 5.000000\n [9] 5.000000 5.000000 3.000000 1.000000 3.000000 1.000000 3.000000 3.000000\n[17] 3.000000 5.000000 6.000000 4.500000 3.000000 3.000000 5.000000 5.000000\n[25] 3.000000 5.000000 4.000000 3.000000 3.000000 3.000000 5.000000 5.000000\n[33] 5.000000 5.000000 6.000000 3.000000 1.000000 3.000000 1.000000 3.000000\n[41] 3.000000 5.000000 5.000000 5.000000 6.000000 1.000000 3.000000 6.000000\n[49] 5.000000 5.000000 1.000000 5.000000 5.000000 5.000000 3.000000 1.000000\n[57] 5.000000 3.000000 1.000000 6.000000 5.500000 5.000000 1.000000 5.000000\n[65] 5.333333 5.666667 6.000000 6.000000 5.000000 1.000000 5.000000 5.000000\n[73] 4.000000 3.000000 5.000000 5.000000 5.000000 5.000000 1.000000 5.000000\n[81] 3.666667 2.333333 1.000000 6.000000 5.000000 5.000000 5.000000 5.000000\n[89] 5.000000 1.000000 5.000000 3.000000 1.000000 2.000000 3.000000 3.000000\n[97] 3.000000 6.000000 5.000000 1.000000"
}
] |
Using HTML ISMAP | To use an image with ismap attribute, you simply put your image inside a hyper link and use ismap attribute which makes it special image and when the user clicks some place within the image, the browser passes the coordinates of the mouse pointer along with the URL specified in the <a> tag to the web server. The server uses the mouse-pointer coordinates to determine which document to deliver back to the browser.
When ismap is used, the href attribute of the containing <a> tag must contain the URL of a server application like a cgi or PHP script etc. to process the incoming request based on the passed coordinates.
The coordinates of the mouse position are screen pixels counted from the upper-left corner of the image, beginning with (0,0). The coordinates, preceded by a question mark, are added to the end of the URL.
For example, if a user clicks 50 pixels over and 30 pixels down from the upper-left corner of the following image:
Click following link
Which has been generated by the following code snippet −
<!DOCTYPE html>
<html>
<head>
<title>ISMAP Hyperlink Example</title>
</head>
<body>
<p>Click following link</p>
<a href = "/cgi-bin/ismap.cgi" target="_self">
<img ismap src="/images/logo.png" alt="Tutorials Point" border="0"/>
</a>
</body>
</html>
Then the browser sends the following search parameters to the web server −
/cgi-bin/ismap.cgi?20,30
Now these passed coordinates can be processed by one of the following two ways −
Using a CGI (or PHP file if you are not using CGI file)
Using a map file
Following is the perl code for ismap.cgi script which is being used in the above example −
#!/usr/bin/perl
local ($buffer, $x, $y);
# Read in text
$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;
if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}
# Split information into name/value pairs
($x, $y) = split(/,/, $buffer);
print "Content-type:text/html\r\n\r\n";
print "<html>";
print "<head>";
print "<title>ISMAP</title>";
print "</head>";
print "<body>";
print "<h2>Passed Parameters are : X = $x, Y = $y </h2>";
print "</body>";
print "</html>";
1;
Because you are able to parse passed coordinates, you can put a list of if conditions to check passed coordinates and send appropriate linked document back to the browser.
A map file can be used to store the location of HTML files that you want the reader to be taken to when the area between the identified coordinates is "clicked."
You keep default file at the first location and other files are put corresponding to various coordinates as shown below in ismap.map file.
default http://www.tutorialspoint.com
rect http://www.tutorialspoint.com/html 5,5 64,141
rect http://www.tutorialspoint.com/css 91,5 127,196
circle http://www.tutorialspoint.com/javscript 154,150,59
This way you can assign different links to different part of the image and when those coordinates are clicked, you can open linked document. So let's rewrite above example using ismap.map file:
<!DOCTYPE html>
<html>
<head>
<title>ISMAP Hyperlink Example</title>
</head>
<body>
<p>Click following link</p>
<a href = "/html/ismap.map" target="_self">
<img ismap src = "/images/logo.png" alt="Tutorials Point" border="0"/>
</a>
</body>
</html>
Before trying above example, you need to make sure that your webserver has required configuration to support image map file.
The actual value of coords is totally dependent on the shape in question. Here is a summary, to be followed by detailed examples. You can use any available tool like Adobe Photoshop or MS Paint to detect various coordinates available on the image to be used for ISMAP.
A lines beginning with # are comments. Every other non-blank line consists of the following −
x1 and y1 are the coordinates of the upper left corner of the rectangle; x2 and y2 are the coordinates of the lower right corner.
xc and yc are the coordinates of the center of the circle, and radius is the circle's radius. A circle centered at 200,50 with a radius of 25 would have the attribute coords="200,50,25"
The various x-y pairs define vertices (points) of the polygon, with a "line" being drawn from one point to the next point. A diamond-shaped polygon with its top point at 20,20 and 40 pixels across at its widest points would have the attribute coords="20,20,40,40,20,60,0,40".
All coordinates are relative to the upper-left corner of the image (0,0). Each shape has a related URL.You can use any image software to know the coordinates of different positions.
19 Lectures
2 hours
Anadi Sharma
16 Lectures
1.5 hours
Anadi Sharma
18 Lectures
1.5 hours
Frahaan Hussain
57 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
54 Lectures
6 hours
DigiFisk (Programming Is Fun)
45 Lectures
5.5 hours
DigiFisk (Programming Is Fun)
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2790,
"s": 2374,
"text": "To use an image with ismap attribute, you simply put your image inside a hyper link and use ismap attribute which makes it special image and when the user clicks some place within the image, the browser passes the coordinates of the mouse pointer along with the URL specified in the <a> tag to the web server. The server uses the mouse-pointer coordinates to determine which document to deliver back to the browser."
},
{
"code": null,
"e": 2995,
"s": 2790,
"text": "When ismap is used, the href attribute of the containing <a> tag must contain the URL of a server application like a cgi or PHP script etc. to process the incoming request based on the passed coordinates."
},
{
"code": null,
"e": 3201,
"s": 2995,
"text": "The coordinates of the mouse position are screen pixels counted from the upper-left corner of the image, beginning with (0,0). The coordinates, preceded by a question mark, are added to the end of the URL."
},
{
"code": null,
"e": 3316,
"s": 3201,
"text": "For example, if a user clicks 50 pixels over and 30 pixels down from the upper-left corner of the following image:"
},
{
"code": null,
"e": 3337,
"s": 3316,
"text": "Click following link"
},
{
"code": null,
"e": 3394,
"s": 3337,
"text": "Which has been generated by the following code snippet −"
},
{
"code": null,
"e": 3690,
"s": 3394,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>ISMAP Hyperlink Example</title>\n </head>\n <body>\n <p>Click following link</p>\n <a href = \"/cgi-bin/ismap.cgi\" target=\"_self\"> \n <img ismap src=\"/images/logo.png\" alt=\"Tutorials Point\" border=\"0\"/> \n </a>\n </body>\n</html>"
},
{
"code": null,
"e": 3765,
"s": 3690,
"text": "Then the browser sends the following search parameters to the web server −"
},
{
"code": null,
"e": 3791,
"s": 3765,
"text": "/cgi-bin/ismap.cgi?20,30\n"
},
{
"code": null,
"e": 3872,
"s": 3791,
"text": "Now these passed coordinates can be processed by one of the following two ways −"
},
{
"code": null,
"e": 3928,
"s": 3872,
"text": "Using a CGI (or PHP file if you are not using CGI file)"
},
{
"code": null,
"e": 3945,
"s": 3928,
"text": "Using a map file"
},
{
"code": null,
"e": 4036,
"s": 3945,
"text": "Following is the perl code for ismap.cgi script which is being used in the above example −"
},
{
"code": null,
"e": 4515,
"s": 4036,
"text": "#!/usr/bin/perl\n\nlocal ($buffer, $x, $y);\n# Read in text\n$ENV{'REQUEST_METHOD'} =~ tr/a-z/A-Z/;\nif ($ENV{'REQUEST_METHOD'} eq \"GET\") {\n $buffer = $ENV{'QUERY_STRING'};\n}\n\n# Split information into name/value pairs\n($x, $y) = split(/,/, $buffer);\n\nprint \"Content-type:text/html\\r\\n\\r\\n\";\nprint \"<html>\";\nprint \"<head>\";\nprint \"<title>ISMAP</title>\";\nprint \"</head>\";\nprint \"<body>\";\nprint \"<h2>Passed Parameters are : X = $x, Y = $y </h2>\";\nprint \"</body>\";\nprint \"</html>\";\n\n1;"
},
{
"code": null,
"e": 4687,
"s": 4515,
"text": "Because you are able to parse passed coordinates, you can put a list of if conditions to check passed coordinates and send appropriate linked document back to the browser."
},
{
"code": null,
"e": 4849,
"s": 4687,
"text": "A map file can be used to store the location of HTML files that you want the reader to be taken to when the area between the identified coordinates is \"clicked.\""
},
{
"code": null,
"e": 4988,
"s": 4849,
"text": "You keep default file at the first location and other files are put corresponding to various coordinates as shown below in ismap.map file."
},
{
"code": null,
"e": 5197,
"s": 4988,
"text": "default http://www.tutorialspoint.com\nrect http://www.tutorialspoint.com/html 5,5 64,141\nrect http://www.tutorialspoint.com/css 91,5 127,196\ncircle http://www.tutorialspoint.com/javscript 154,150,59\n"
},
{
"code": null,
"e": 5391,
"s": 5197,
"text": "This way you can assign different links to different part of the image and when those coordinates are clicked, you can open linked document. So let's rewrite above example using ismap.map file:"
},
{
"code": null,
"e": 5686,
"s": 5391,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>ISMAP Hyperlink Example</title>\n </head>\n <body>\n <p>Click following link</p>\n <a href = \"/html/ismap.map\" target=\"_self\"> \n <img ismap src = \"/images/logo.png\" alt=\"Tutorials Point\" border=\"0\"/> \n </a>\n </body>\n</html>"
},
{
"code": null,
"e": 5811,
"s": 5686,
"text": "Before trying above example, you need to make sure that your webserver has required configuration to support image map file."
},
{
"code": null,
"e": 6080,
"s": 5811,
"text": "The actual value of coords is totally dependent on the shape in question. Here is a summary, to be followed by detailed examples. You can use any available tool like Adobe Photoshop or MS Paint to detect various coordinates available on the image to be used for ISMAP."
},
{
"code": null,
"e": 6174,
"s": 6080,
"text": "A lines beginning with # are comments. Every other non-blank line consists of the following −"
},
{
"code": null,
"e": 6304,
"s": 6174,
"text": "x1 and y1 are the coordinates of the upper left corner of the rectangle; x2 and y2 are the coordinates of the lower right corner."
},
{
"code": null,
"e": 6491,
"s": 6304,
"text": "xc and yc are the coordinates of the center of the circle, and radius is the circle's radius. A circle centered at 200,50 with a radius of 25 would have the attribute coords=\"200,50,25\""
},
{
"code": null,
"e": 6768,
"s": 6491,
"text": "The various x-y pairs define vertices (points) of the polygon, with a \"line\" being drawn from one point to the next point. A diamond-shaped polygon with its top point at 20,20 and 40 pixels across at its widest points would have the attribute coords=\"20,20,40,40,20,60,0,40\"."
},
{
"code": null,
"e": 6950,
"s": 6768,
"text": "All coordinates are relative to the upper-left corner of the image (0,0). Each shape has a related URL.You can use any image software to know the coordinates of different positions."
},
{
"code": null,
"e": 6983,
"s": 6950,
"text": "\n 19 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6997,
"s": 6983,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7032,
"s": 6997,
"text": "\n 16 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7046,
"s": 7032,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 7081,
"s": 7046,
"text": "\n 18 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 7098,
"s": 7081,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 7133,
"s": 7098,
"text": "\n 57 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7164,
"s": 7133,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7197,
"s": 7164,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 7228,
"s": 7197,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7263,
"s": 7228,
"text": "\n 45 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 7294,
"s": 7263,
"text": " DigiFisk (Programming Is Fun)"
},
{
"code": null,
"e": 7301,
"s": 7294,
"text": " Print"
},
{
"code": null,
"e": 7312,
"s": 7301,
"text": " Add Notes"
}
] |
Stack using two queues | Practice | GeeksforGeeks | Implement a Stack using two queues q1 and q2.
Example 1:
Input:
push(2)
push(3)
pop()
push(4)
pop()
Output: 3 4
Explanation:
push(2) the stack will be {2}
push(3) the stack will be {2 3}
pop() poped element will be 3 the
stack will be {2}
push(4) the stack will be {2 4}
pop() poped element will be 4
Example 2:
Input:
push(2)
pop()
pop()
push(3)
Output: 2 -1
Your Task:
Since this is a function problem, you don't need to take inputs. You are required to complete the two methods push() which takes an integer 'x' as input denoting the element to be pushed into the stack and pop() which returns the integer poped out from the stack(-1 if the stack is empty).
Expected Time Complexity: O(1) for push() and O(N) for pop() (or vice-versa).
Expected Auxiliary Space: O(1) for both push() and pop().
Constraints:
1 <= Number of queries <= 100
1 <= values of the stack <= 100
-1
smitasinghthakur1891 week ago
void QueueStack :: push(int x)
{
q1.push(x);
}
//Function to pop an element from stack using two queues.
int QueueStack :: pop()
{
if(q1.empty()) return -1;
while(q1.size()>1)
{
q2.push(q1.front());
q1.pop();
}
int x=q1.front();
q1.pop();
while(!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
return x;
}
0
shaikhmohammedammar1 week ago
//Function to push an element into stack using two queues.
void QueueStack :: push(int x){
// if both are empty, then it's the first element, start with q1
if(q1.empty() && q2.empty()) q1.push(x);
// if q2 or q1 is not empty, then it's in the process, push in it.
else if(q1.empty() && !q2.empty()) q2.push(x);
else q1.push(x);
}
int QueueStack :: pop()
{
// IF Q1 is not empty, then it's in process, empty it in Q2, return the last element.
if(!q1.empty()){
while(q1.size() != 1){
q2.push(q1.front());
q1.pop();
}
int x = q1.front(); q1.pop();
return x;
}
// else if Q2 is not empty, empty it in Q1, return the last element.
else if(!q2.empty()){
while(q2.size() != 1){
q1.push(q2.front());
q2.pop();
}
int x = q2.front(); q2.pop();
return x;
}
// else both are empty, return nothing, ie.-1.
return -1;
}
0
hharshit81182 weeks ago
void QueueStack :: push(int x){ if(q1.empty() && q2.empty()){ q1.push(x); } else if(q1.empty() && !q2.empty()){ q2.push(x); } else{ q1.push(x); }}
int QueueStack :: pop(){ if(q1.empty() == false){ while(q1.size() != 1){ q2.push(q1.front()); q1.pop(); } int x = q1.front(); q1.pop(); return x; } else if(q2.empty() == false){ while(q2.size() != 1){ q1.push(q2.front()); q2.pop(); } int x = q2.front(); q2.pop(); return x; } else{ return -1; }}
0
ankitap99322 weeks ago
//Function to push an element into stack using two queues.void QueueStack :: push(int x){ //step-1 push into q2 //step-2 push remaining elements of q1 into q2 //step-3 swap q1 and q2 q2.push(x); while(q1.size()!=0){ q2.push(q1.front()); q1.pop(); } swap(q1,q2); //push using one queue only approach //step-1 push into q1 //step-2 rotate q1 elements from front to q1.size()-1 elements // q1.push(x); // int rotate=q1.size()-1; // while(rotate--){ // q1.push(q1.front()); // q1.pop(); // }}
//Function to pop an element from stack using two queues. int QueueStack :: pop(){ int ans; if(q1.empty()){ ans=-1; } else{ ans=q1.front(); q1.pop(); } return ans; }
+1
swastikp17111 month ago
class Queues
{
Queue<Integer> q1 = new LinkedList<Integer>();
Queue<Integer> q2 = new LinkedList<Integer>();
//Function to push an element into stack using two queues.
void push(int a)
{
while(!q1.isEmpty()){
q2.offer(q1.poll());
}
q1.offer(a);
while(!q2.isEmpty()){
q1.offer(q2.poll());
}
}
//Function to pop an element from stack using two queues.
int pop()
{
if(q1.isEmpty()) return -1;
return q1.poll();
}
}
+1
mashhadihossain1 month ago
SIMPLE JAVA SOLUTION (0.4/1.7 SEC)
class Queues{ Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); //Function to push an element into stack using two queues. void push(int a) { if(q1.isEmpty()) { q1.add(a); } else { while(!q1.isEmpty()) { q2.add(q1.remove()); } q1.add(a); while(!q2.isEmpty()) { q1.add(q2.remove()); } } } //Function to pop an element from stack using two queues. int pop() { int x=-1; if(!q1.isEmpty()) { x=q1.remove(); } return x; }}
0
mohankumar9875mk1 month ago
JS code:(partial)
class QueueStack{ constructor(){ this.q1 = new Queue(); this.q2 = new Queue(); } push(x){ this.q2.push(x); while(this.q2.length===x){ this.q1.push(this.q2.pop()); } (this.q1),(this.q2)=(this.q1),(this.q2) } pop(){ return(this.q1.pop()) }}
0
sunboykenneth1 month ago
class StackWithQueues {private: queue<int> q1; queue<int> q2;
public: void push(int data) { queue<int> *targetQ = NULL; if (!q1.empty()) { targetQ = &q1; } else { targetQ = &q2; } targetQ->push(data); } int pop() { queue<int> *targetQ = NULL, *newQ = NULL; if (!q1.empty()) { targetQ = &q1; newQ = &q2; } else if (!q2.empty()) { targetQ = &q2; newQ = &q1; } else { return 0; } int size = targetQ->size(); size--; while(size > 0) { newQ->push(targetQ->front()); targetQ->pop(); size--; } int data = targetQ->front(); targetQ->pop(); return data; } };
+1
amanasati11 month ago
Implementing stack using 2 queue push operationStep 1- insert into Q1Step 2- push remaining elements of Q2 into Q1Step 3- Swap Q1 and Q2
pop operationpop from Q2 as all the element in Q2
Below is easy pythonic approach
def push(x):
# global declaration
global queue_1
global queue_2
# code here
queue_1.append(x)
while queue_2:
queue_1.append(queue_2.pop(0))
queue_1,queue_2=queue_2,queue_1
#Function to pop an element from stack using two queues.
def pop():
# global declaration
global queue_1
global queue_2
# code here
if not queue_2:
return -1
return queue_2.pop(0)
+1
detroix072 months ago
void QueueStack :: push(int x){ while(q1.size()!=0) { q2.push(q1.front()); q1.pop(); } q1.push(x); while(q2.size()!=0) { q1.push(q2.front()); q2.pop(); } }
//Function to pop an element from stack using two queues.
int QueueStack :: pop(){ if(q1.size()==0) return -1; int Ele = q1.front(); q1.pop(); return Ele;}
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": 284,
"s": 238,
"text": "Implement a Stack using two queues q1 and q2."
},
{
"code": null,
"e": 295,
"s": 284,
"text": "Example 1:"
},
{
"code": null,
"e": 555,
"s": 295,
"text": "Input:\npush(2)\npush(3)\npop()\npush(4)\npop()\nOutput: 3 4\nExplanation:\npush(2) the stack will be {2}\npush(3) the stack will be {2 3}\npop() poped element will be 3 the \n stack will be {2}\npush(4) the stack will be {2 4}\npop() poped element will be 4 \n"
},
{
"code": null,
"e": 566,
"s": 555,
"text": "Example 2:"
},
{
"code": null,
"e": 614,
"s": 566,
"text": "Input:\npush(2)\npop()\npop()\npush(3)\nOutput: 2 -1"
},
{
"code": null,
"e": 625,
"s": 614,
"text": "Your Task:"
},
{
"code": null,
"e": 915,
"s": 625,
"text": "Since this is a function problem, you don't need to take inputs. You are required to complete the two methods push() which takes an integer 'x' as input denoting the element to be pushed into the stack and pop() which returns the integer poped out from the stack(-1 if the stack is empty)."
},
{
"code": null,
"e": 1051,
"s": 915,
"text": "Expected Time Complexity: O(1) for push() and O(N) for pop() (or vice-versa).\nExpected Auxiliary Space: O(1) for both push() and pop()."
},
{
"code": null,
"e": 1126,
"s": 1051,
"text": "Constraints:\n1 <= Number of queries <= 100\n1 <= values of the stack <= 100"
},
{
"code": null,
"e": 1129,
"s": 1126,
"text": "-1"
},
{
"code": null,
"e": 1159,
"s": 1129,
"text": "smitasinghthakur1891 week ago"
},
{
"code": null,
"e": 1551,
"s": 1159,
"text": "void QueueStack :: push(int x)\n{\n q1.push(x); \n}\n\n//Function to pop an element from stack using two queues. \nint QueueStack :: pop()\n{\n if(q1.empty()) return -1;\n while(q1.size()>1)\n {\n q2.push(q1.front());\n q1.pop();\n }\n int x=q1.front();\n q1.pop();\n while(!q2.empty())\n {\n q1.push(q2.front());\n q2.pop();\n }\n return x; \n}"
},
{
"code": null,
"e": 1553,
"s": 1551,
"text": "0"
},
{
"code": null,
"e": 1583,
"s": 1553,
"text": "shaikhmohammedammar1 week ago"
},
{
"code": null,
"e": 2611,
"s": 1583,
"text": "\n//Function to push an element into stack using two queues.\nvoid QueueStack :: push(int x){\n // if both are empty, then it's the first element, start with q1\n if(q1.empty() && q2.empty()) q1.push(x);\n// if q2 or q1 is not empty, then it's in the process, push in it.\n else if(q1.empty() && !q2.empty()) q2.push(x);\n else q1.push(x);\n}\n\nint QueueStack :: pop()\n{\n // IF Q1 is not empty, then it's in process, empty it in Q2, return the last element.\n if(!q1.empty()){\n while(q1.size() != 1){\n q2.push(q1.front());\n q1.pop();\n }\n int x = q1.front(); q1.pop();\n return x;\n }\n // else if Q2 is not empty, empty it in Q1, return the last element.\n else if(!q2.empty()){\n while(q2.size() != 1){\n q1.push(q2.front());\n q2.pop();\n }\n int x = q2.front(); q2.pop();\n return x;\n }\n // else both are empty, return nothing, ie.-1.\n return -1;\n \n}"
},
{
"code": null,
"e": 2613,
"s": 2611,
"text": "0"
},
{
"code": null,
"e": 2637,
"s": 2613,
"text": "hharshit81182 weeks ago"
},
{
"code": null,
"e": 2814,
"s": 2637,
"text": "void QueueStack :: push(int x){ if(q1.empty() && q2.empty()){ q1.push(x); } else if(q1.empty() && !q2.empty()){ q2.push(x); } else{ q1.push(x); }}"
},
{
"code": null,
"e": 3298,
"s": 2814,
"text": "int QueueStack :: pop(){ if(q1.empty() == false){ while(q1.size() != 1){ q2.push(q1.front()); q1.pop(); } int x = q1.front(); q1.pop(); return x; } else if(q2.empty() == false){ while(q2.size() != 1){ q1.push(q2.front()); q2.pop(); } int x = q2.front(); q2.pop(); return x; } else{ return -1; }}"
},
{
"code": null,
"e": 3300,
"s": 3298,
"text": "0"
},
{
"code": null,
"e": 3323,
"s": 3300,
"text": "ankitap99322 weeks ago"
},
{
"code": null,
"e": 3892,
"s": 3323,
"text": "//Function to push an element into stack using two queues.void QueueStack :: push(int x){ //step-1 push into q2 //step-2 push remaining elements of q1 into q2 //step-3 swap q1 and q2 q2.push(x); while(q1.size()!=0){ q2.push(q1.front()); q1.pop(); } swap(q1,q2); //push using one queue only approach //step-1 push into q1 //step-2 rotate q1 elements from front to q1.size()-1 elements // q1.push(x); // int rotate=q1.size()-1; // while(rotate--){ // q1.push(q1.front()); // q1.pop(); // }}"
},
{
"code": null,
"e": 4087,
"s": 3892,
"text": "//Function to pop an element from stack using two queues. int QueueStack :: pop(){ int ans; if(q1.empty()){ ans=-1; } else{ ans=q1.front(); q1.pop(); } return ans; }"
},
{
"code": null,
"e": 4090,
"s": 4087,
"text": "+1"
},
{
"code": null,
"e": 4114,
"s": 4090,
"text": "swastikp17111 month ago"
},
{
"code": null,
"e": 4632,
"s": 4114,
"text": "class Queues\n{\n Queue<Integer> q1 = new LinkedList<Integer>();\n Queue<Integer> q2 = new LinkedList<Integer>();\n \n //Function to push an element into stack using two queues.\n void push(int a)\n {\n\t while(!q1.isEmpty()){\n\t q2.offer(q1.poll());\n\t }\n\t q1.offer(a);\n\t while(!q2.isEmpty()){\n\t q1.offer(q2.poll());\n\t }\n }\n \n //Function to pop an element from stack using two queues. \n int pop()\n {\n\t if(q1.isEmpty()) return -1;\n\t return q1.poll();\n }\n\t\n}"
},
{
"code": null,
"e": 4635,
"s": 4632,
"text": "+1"
},
{
"code": null,
"e": 4662,
"s": 4635,
"text": "mashhadihossain1 month ago"
},
{
"code": null,
"e": 4697,
"s": 4662,
"text": "SIMPLE JAVA SOLUTION (0.4/1.7 SEC)"
},
{
"code": null,
"e": 5305,
"s": 4697,
"text": "class Queues{ Queue<Integer> q1 = new LinkedList<Integer>(); Queue<Integer> q2 = new LinkedList<Integer>(); //Function to push an element into stack using two queues. void push(int a) { if(q1.isEmpty()) { q1.add(a); } else { while(!q1.isEmpty()) { q2.add(q1.remove()); } q1.add(a); while(!q2.isEmpty()) { q1.add(q2.remove()); } } } //Function to pop an element from stack using two queues. int pop() { int x=-1; if(!q1.isEmpty()) { x=q1.remove(); } return x; }}"
},
{
"code": null,
"e": 5307,
"s": 5305,
"text": "0"
},
{
"code": null,
"e": 5335,
"s": 5307,
"text": "mohankumar9875mk1 month ago"
},
{
"code": null,
"e": 5353,
"s": 5335,
"text": "JS code:(partial)"
},
{
"code": null,
"e": 5668,
"s": 5355,
"text": "class QueueStack{ constructor(){ this.q1 = new Queue(); this.q2 = new Queue(); } push(x){ this.q2.push(x); while(this.q2.length===x){ this.q1.push(this.q2.pop()); } (this.q1),(this.q2)=(this.q1),(this.q2) } pop(){ return(this.q1.pop()) }}"
},
{
"code": null,
"e": 5670,
"s": 5668,
"text": "0"
},
{
"code": null,
"e": 5695,
"s": 5670,
"text": "sunboykenneth1 month ago"
},
{
"code": null,
"e": 5761,
"s": 5695,
"text": "class StackWithQueues {private: queue<int> q1; queue<int> q2;"
},
{
"code": null,
"e": 6492,
"s": 5761,
"text": "public: void push(int data) { queue<int> *targetQ = NULL; if (!q1.empty()) { targetQ = &q1; } else { targetQ = &q2; } targetQ->push(data); } int pop() { queue<int> *targetQ = NULL, *newQ = NULL; if (!q1.empty()) { targetQ = &q1; newQ = &q2; } else if (!q2.empty()) { targetQ = &q2; newQ = &q1; } else { return 0; } int size = targetQ->size(); size--; while(size > 0) { newQ->push(targetQ->front()); targetQ->pop(); size--; } int data = targetQ->front(); targetQ->pop(); return data; } };"
},
{
"code": null,
"e": 6495,
"s": 6492,
"text": "+1"
},
{
"code": null,
"e": 6517,
"s": 6495,
"text": "amanasati11 month ago"
},
{
"code": null,
"e": 6654,
"s": 6517,
"text": "Implementing stack using 2 queue push operationStep 1- insert into Q1Step 2- push remaining elements of Q2 into Q1Step 3- Swap Q1 and Q2"
},
{
"code": null,
"e": 6706,
"s": 6656,
"text": "pop operationpop from Q2 as all the element in Q2"
},
{
"code": null,
"e": 6740,
"s": 6708,
"text": "Below is easy pythonic approach"
},
{
"code": null,
"e": 7192,
"s": 6742,
"text": "def push(x):\n \n # global declaration\n global queue_1\n global queue_2\n \n # code here\n queue_1.append(x)\n while queue_2:\n queue_1.append(queue_2.pop(0))\n queue_1,queue_2=queue_2,queue_1\n\n\n#Function to pop an element from stack using two queues. \ndef pop():\n \n # global declaration\n global queue_1\n global queue_2\n # code here\n if not queue_2:\n return -1\n \n return queue_2.pop(0)"
},
{
"code": null,
"e": 7195,
"s": 7192,
"text": "+1"
},
{
"code": null,
"e": 7217,
"s": 7195,
"text": "detroix072 months ago"
},
{
"code": null,
"e": 7398,
"s": 7217,
"text": "void QueueStack :: push(int x){ while(q1.size()!=0) { q2.push(q1.front()); q1.pop(); } q1.push(x); while(q2.size()!=0) { q1.push(q2.front()); q2.pop(); } }"
},
{
"code": null,
"e": 7458,
"s": 7400,
"text": "//Function to pop an element from stack using two queues."
},
{
"code": null,
"e": 7569,
"s": 7458,
"text": " int QueueStack :: pop(){ if(q1.size()==0) return -1; int Ele = q1.front(); q1.pop(); return Ele;} "
},
{
"code": null,
"e": 7715,
"s": 7569,
"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": 7751,
"s": 7715,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 7761,
"s": 7751,
"text": "\nProblem\n"
},
{
"code": null,
"e": 7771,
"s": 7761,
"text": "\nContest\n"
},
{
"code": null,
"e": 7834,
"s": 7771,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 7982,
"s": 7834,
"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": 8190,
"s": 7982,
"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": 8296,
"s": 8190,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Swift - Continue Statement | The continue statement in Swift 4 tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop.
For a for loop, the continue statement causes the conditional test and increments the portions of the loop to execute. For while and do...while loops, the continue statement causes the program control to pass to the conditional tests.
The syntax for a continue statement in Swift 4 is as follows −
continue
var index = 10
repeat {
index = index + 1
if( index == 15 ){
continue
}
print( "Value of index is \(index)")
} while index < 20
When the above code is compiled and executed, it produces the following result −
Value of index is 11
Value of index is 12
Value of index is 13
Value of index is 14
Value of index is 16
Value of index is 17
Value of index is 18
Value of index is 19
Value of index is 20
38 Lectures
1 hours
Ashish Sharma
13 Lectures
2 hours
Three Millennials
7 Lectures
1 hours
Three Millennials
22 Lectures
1 hours
Frahaan Hussain
12 Lectures
39 mins
Devasena Rajendran
40 Lectures
2.5 hours
Grant Klimaytys
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2398,
"s": 2253,
"text": "The continue statement in Swift 4 tells a loop to stop what it is doing and start again at the beginning of the next iteration through the loop."
},
{
"code": null,
"e": 2633,
"s": 2398,
"text": "For a for loop, the continue statement causes the conditional test and increments the portions of the loop to execute. For while and do...while loops, the continue statement causes the program control to pass to the conditional tests."
},
{
"code": null,
"e": 2696,
"s": 2633,
"text": "The syntax for a continue statement in Swift 4 is as follows −"
},
{
"code": null,
"e": 2706,
"s": 2696,
"text": "continue\n"
},
{
"code": null,
"e": 2853,
"s": 2706,
"text": "var index = 10\n\nrepeat {\n index = index + 1\n if( index == 15 ){\n continue\n }\n print( \"Value of index is \\(index)\")\n} while index < 20"
},
{
"code": null,
"e": 2934,
"s": 2853,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3124,
"s": 2934,
"text": "Value of index is 11\nValue of index is 12\nValue of index is 13\nValue of index is 14\nValue of index is 16\nValue of index is 17\nValue of index is 18\nValue of index is 19\nValue of index is 20\n"
},
{
"code": null,
"e": 3157,
"s": 3124,
"text": "\n 38 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3172,
"s": 3157,
"text": " Ashish Sharma"
},
{
"code": null,
"e": 3205,
"s": 3172,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3224,
"s": 3205,
"text": " Three Millennials"
},
{
"code": null,
"e": 3256,
"s": 3224,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3275,
"s": 3256,
"text": " Three Millennials"
},
{
"code": null,
"e": 3308,
"s": 3275,
"text": "\n 22 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 3325,
"s": 3308,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3357,
"s": 3325,
"text": "\n 12 Lectures \n 39 mins\n"
},
{
"code": null,
"e": 3377,
"s": 3357,
"text": " Devasena Rajendran"
},
{
"code": null,
"e": 3412,
"s": 3377,
"text": "\n 40 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3429,
"s": 3412,
"text": " Grant Klimaytys"
},
{
"code": null,
"e": 3436,
"s": 3429,
"text": " Print"
},
{
"code": null,
"e": 3447,
"s": 3436,
"text": " Add Notes"
}
] |
How to append an element in an array in JavaScript? - GeeksforGeeks | 06 Mar, 2019
There are several methods for adding new elements to a JavaScript array.
push(): The push() method will add an element to the end of an array, while its twin function, the pop() method, will remove an element from the end of the array. If you need to add an element or multiple elements to the end of an array, the push() method will almost always be your simplest and quickest option.Syntax:array.push(item1, item2, ..., itemX)Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to the end of the array.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> var Geeks = ["Geeks1", "Geeks2", "Geeks3", "Geeks4"]; document.getElementById("geeks").innerHTML = Geeks; function GFG() { Geeks.push("Geeks5", "Geeks6"); document.getElementById("geeks").innerHTML = Geeks; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:
Syntax:
array.push(item1, item2, ..., itemX)
Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to the end of the array.
Example:
<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> var Geeks = ["Geeks1", "Geeks2", "Geeks3", "Geeks4"]; document.getElementById("geeks").innerHTML = Geeks; function GFG() { Geeks.push("Geeks5", "Geeks6"); document.getElementById("geeks").innerHTML = Geeks; } </script> </center></body></html>
Output:
Before Click on the Button:
After Click on the Button:
unshift(): The unshift() method will add an element to the beginning of an array, while its twin function, shift(), will remove one element from the beginning of the array.Syntax:array.unshift(item1, item2, ..., itemX)Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to add to the beginning of the array.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> var Geeks = ["Geeks1", "Geeks2", "Geeks3", "Geeks4"]; document.getElementById("geeks").innerHTML = Geeks; function GFG() { Geeks.unshift("Geeks5", "Geeks6"); document.getElementById("geeks").innerHTML = Geeks; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:
array.unshift(item1, item2, ..., itemX)
Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to add to the beginning of the array.
Example:
<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> var Geeks = ["Geeks1", "Geeks2", "Geeks3", "Geeks4"]; document.getElementById("geeks").innerHTML = Geeks; function GFG() { Geeks.unshift("Geeks5", "Geeks6"); document.getElementById("geeks").innerHTML = Geeks; } </script> </center></body></html>
Output:
Before Click on the Button:
After Click on the Button:
splice(): The splice() method modifies the content of an array by removing existing elements and/or adding new elements.Syntax:array.splice(index, howmany, item1, ....., itemX)Parameter:index: This is required parameter. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the arrayhowmany: This is Optional parameter. The number of items to be removed. If set to 0, no items will be removed.item1, item2, ..., itemX: These are Optional parameters. The new item(s) to be added to the array.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> var Geeks = ["Geeks1", "Geeks2", "Geeks3", "Geeks4"]; document.getElementById("geeks").innerHTML = Geeks; function GFG() { Geeks.splice(2, 1, "Geeks5", "Geeks6"); document.getElementById("geeks").innerHTML = Geeks; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:
Syntax:
array.splice(index, howmany, item1, ....., itemX)
Parameter:
index: This is required parameter. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array
howmany: This is Optional parameter. The number of items to be removed. If set to 0, no items will be removed.
item1, item2, ..., itemX: These are Optional parameters. The new item(s) to be added to the array.
Example:
<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> var Geeks = ["Geeks1", "Geeks2", "Geeks3", "Geeks4"]; document.getElementById("geeks").innerHTML = Geeks; function GFG() { Geeks.splice(2, 1, "Geeks5", "Geeks6"); document.getElementById("geeks").innerHTML = Geeks; } </script> </center></body></html>
Output:
Before Click on the Button:
After Click on the Button:
concat(): The concat() method returns a new combined array comprised of the array on which it is called, joined with the array (or arrays) from its argument.This method is used to join two or more arrays and this method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.Syntax:array1.concat(array2, array3, ..., arrayX)Parameter:array2, array3, ..., arrayX: These are required parameters. The arrays to be joined.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> function GFG() { var g1 = ["Geeks1", "Geeks2"]; var g2 = ["Geeks3", "Geeks4"]; var g3 = ["GeeksForGeeks"]; var g4 = g1.concat(g2, g3); document.getElementById("geeks").innerHTML = g4; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:
Syntax:
array1.concat(array2, array3, ..., arrayX)
Parameter:
array2, array3, ..., arrayX: These are required parameters. The arrays to be joined.
Example:
<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick="GFG()">Click</button> <p id="geeks"></p> <script> function GFG() { var g1 = ["Geeks1", "Geeks2"]; var g2 = ["Geeks3", "Geeks4"]; var g3 = ["GeeksForGeeks"]; var g4 = g1.concat(g2, g3); document.getElementById("geeks").innerHTML = g4; } </script> </center></body></html>
Output:
Before Click on the Button:
After Click on the Button:
javascript-array
Picked
Web-Programs
JavaScript
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Node.js | fs.writeFileSync() Method
Remove elements from a JavaScript Array
Set the value of an input field in JavaScript
How to read a local text file using JavaScript?
How to Use the JavaScript Fetch API to Get Data?
Form validation using HTML and JavaScript | [
{
"code": null,
"e": 24604,
"s": 24576,
"text": "\n06 Mar, 2019"
},
{
"code": null,
"e": 24677,
"s": 24604,
"text": "There are several methods for adding new elements to a JavaScript array."
},
{
"code": null,
"e": 25665,
"s": 24677,
"text": "push(): The push() method will add an element to the end of an array, while its twin function, the pop() method, will remove an element from the end of the array. If you need to add an element or multiple elements to the end of an array, the push() method will almost always be your simplest and quickest option.Syntax:array.push(item1, item2, ..., itemX)Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to the end of the array.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> var Geeks = [\"Geeks1\", \"Geeks2\", \"Geeks3\", \"Geeks4\"]; document.getElementById(\"geeks\").innerHTML = Geeks; function GFG() { Geeks.push(\"Geeks5\", \"Geeks6\"); document.getElementById(\"geeks\").innerHTML = Geeks; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:"
},
{
"code": null,
"e": 25673,
"s": 25665,
"text": "Syntax:"
},
{
"code": null,
"e": 25710,
"s": 25673,
"text": "array.push(item1, item2, ..., itemX)"
},
{
"code": null,
"e": 25815,
"s": 25710,
"text": "Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to the end of the array."
},
{
"code": null,
"e": 25824,
"s": 25815,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> var Geeks = [\"Geeks1\", \"Geeks2\", \"Geeks3\", \"Geeks4\"]; document.getElementById(\"geeks\").innerHTML = Geeks; function GFG() { Geeks.push(\"Geeks5\", \"Geeks6\"); document.getElementById(\"geeks\").innerHTML = Geeks; } </script> </center></body></html>",
"e": 26285,
"s": 25824,
"text": null
},
{
"code": null,
"e": 26293,
"s": 26285,
"text": "Output:"
},
{
"code": null,
"e": 26321,
"s": 26293,
"text": "Before Click on the Button:"
},
{
"code": null,
"e": 26348,
"s": 26321,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 27215,
"s": 26348,
"text": "unshift(): The unshift() method will add an element to the beginning of an array, while its twin function, shift(), will remove one element from the beginning of the array.Syntax:array.unshift(item1, item2, ..., itemX)Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to add to the beginning of the array.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> var Geeks = [\"Geeks1\", \"Geeks2\", \"Geeks3\", \"Geeks4\"]; document.getElementById(\"geeks\").innerHTML = Geeks; function GFG() { Geeks.unshift(\"Geeks5\", \"Geeks6\"); document.getElementById(\"geeks\").innerHTML = Geeks; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:"
},
{
"code": null,
"e": 27255,
"s": 27215,
"text": "array.unshift(item1, item2, ..., itemX)"
},
{
"code": null,
"e": 27373,
"s": 27255,
"text": "Parameter: item1, item2, ..., itemX: These are required parameters. The item(s) to add to the beginning of the array."
},
{
"code": null,
"e": 27382,
"s": 27373,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> var Geeks = [\"Geeks1\", \"Geeks2\", \"Geeks3\", \"Geeks4\"]; document.getElementById(\"geeks\").innerHTML = Geeks; function GFG() { Geeks.unshift(\"Geeks5\", \"Geeks6\"); document.getElementById(\"geeks\").innerHTML = Geeks; } </script> </center></body></html>",
"e": 27846,
"s": 27382,
"text": null
},
{
"code": null,
"e": 27854,
"s": 27846,
"text": "Output:"
},
{
"code": null,
"e": 27882,
"s": 27854,
"text": "Before Click on the Button:"
},
{
"code": null,
"e": 27909,
"s": 27882,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 29008,
"s": 27909,
"text": "splice(): The splice() method modifies the content of an array by removing existing elements and/or adding new elements.Syntax:array.splice(index, howmany, item1, ....., itemX)Parameter:index: This is required parameter. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the arrayhowmany: This is Optional parameter. The number of items to be removed. If set to 0, no items will be removed.item1, item2, ..., itemX: These are Optional parameters. The new item(s) to be added to the array.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> var Geeks = [\"Geeks1\", \"Geeks2\", \"Geeks3\", \"Geeks4\"]; document.getElementById(\"geeks\").innerHTML = Geeks; function GFG() { Geeks.splice(2, 1, \"Geeks5\", \"Geeks6\"); document.getElementById(\"geeks\").innerHTML = Geeks; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:"
},
{
"code": null,
"e": 29016,
"s": 29008,
"text": "Syntax:"
},
{
"code": null,
"e": 29066,
"s": 29016,
"text": "array.splice(index, howmany, item1, ....., itemX)"
},
{
"code": null,
"e": 29077,
"s": 29066,
"text": "Parameter:"
},
{
"code": null,
"e": 29246,
"s": 29077,
"text": "index: This is required parameter. An integer that specifies at what position to add/remove items, Use negative values to specify the position from the end of the array"
},
{
"code": null,
"e": 29357,
"s": 29246,
"text": "howmany: This is Optional parameter. The number of items to be removed. If set to 0, no items will be removed."
},
{
"code": null,
"e": 29456,
"s": 29357,
"text": "item1, item2, ..., itemX: These are Optional parameters. The new item(s) to be added to the array."
},
{
"code": null,
"e": 29465,
"s": 29456,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> var Geeks = [\"Geeks1\", \"Geeks2\", \"Geeks3\", \"Geeks4\"]; document.getElementById(\"geeks\").innerHTML = Geeks; function GFG() { Geeks.splice(2, 1, \"Geeks5\", \"Geeks6\"); document.getElementById(\"geeks\").innerHTML = Geeks; } </script> </center></body></html>",
"e": 29934,
"s": 29465,
"text": null
},
{
"code": null,
"e": 29942,
"s": 29934,
"text": "Output:"
},
{
"code": null,
"e": 29970,
"s": 29942,
"text": "Before Click on the Button:"
},
{
"code": null,
"e": 29997,
"s": 29970,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 30985,
"s": 29997,
"text": "concat(): The concat() method returns a new combined array comprised of the array on which it is called, joined with the array (or arrays) from its argument.This method is used to join two or more arrays and this method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.Syntax:array1.concat(array2, array3, ..., arrayX)Parameter:array2, array3, ..., arrayX: These are required parameters. The arrays to be joined.Example:<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> function GFG() { var g1 = [\"Geeks1\", \"Geeks2\"]; var g2 = [\"Geeks3\", \"Geeks4\"]; var g3 = [\"GeeksForGeeks\"]; var g4 = g1.concat(g2, g3); document.getElementById(\"geeks\").innerHTML = g4; } </script> </center></body></html>Output:Before Click on the Button:After Click on the Button:"
},
{
"code": null,
"e": 30993,
"s": 30985,
"text": "Syntax:"
},
{
"code": null,
"e": 31036,
"s": 30993,
"text": "array1.concat(array2, array3, ..., arrayX)"
},
{
"code": null,
"e": 31047,
"s": 31036,
"text": "Parameter:"
},
{
"code": null,
"e": 31132,
"s": 31047,
"text": "array2, array3, ..., arrayX: These are required parameters. The arrays to be joined."
},
{
"code": null,
"e": 31141,
"s": 31132,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html><body> <center> <h1>GeeksForGeeks</h1> <button onclick=\"GFG()\">Click</button> <p id=\"geeks\"></p> <script> function GFG() { var g1 = [\"Geeks1\", \"Geeks2\"]; var g2 = [\"Geeks3\", \"Geeks4\"]; var g3 = [\"GeeksForGeeks\"]; var g4 = g1.concat(g2, g3); document.getElementById(\"geeks\").innerHTML = g4; } </script> </center></body></html>",
"e": 31593,
"s": 31141,
"text": null
},
{
"code": null,
"e": 31601,
"s": 31593,
"text": "Output:"
},
{
"code": null,
"e": 31629,
"s": 31601,
"text": "Before Click on the Button:"
},
{
"code": null,
"e": 31656,
"s": 31629,
"text": "After Click on the Button:"
},
{
"code": null,
"e": 31673,
"s": 31656,
"text": "javascript-array"
},
{
"code": null,
"e": 31680,
"s": 31673,
"text": "Picked"
},
{
"code": null,
"e": 31693,
"s": 31680,
"text": "Web-Programs"
},
{
"code": null,
"e": 31704,
"s": 31693,
"text": "JavaScript"
},
{
"code": null,
"e": 31802,
"s": 31704,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31847,
"s": 31802,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 31908,
"s": 31847,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 31980,
"s": 31908,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 32021,
"s": 31980,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 32057,
"s": 32021,
"text": "Node.js | fs.writeFileSync() Method"
},
{
"code": null,
"e": 32097,
"s": 32057,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32143,
"s": 32097,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 32191,
"s": 32143,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 32240,
"s": 32191,
"text": "How to Use the JavaScript Fetch API to Get Data?"
}
] |
Check if all rows of a matrix are circular rotations of each other in Python | Suppose, we are provided with a matrix of the size n*n, containing integer numbers. We have to find out if all the rows of that matrix are circular rotations of its previous row. In case of first row, it should be a circular rotation of the n-th row.
So, if the input is like
then the output will be True.
To solve this, we will follow these steps −
concat := blank string
for i in range 0 to number of rows, doconcat := concat concatenate "-" concatenate matrix[0,i]
concat := concat concatenate "-" concatenate matrix[0,i]
concat := concat concatenate concat
for i in range 1 to size of matrix, docurr_row := blank stringfor j in range 0 to number of columns, docurr_row := curr_row concatenate "-" concatenate matrix[i,j]if curr_row is present in string concat, thenreturn True
curr_row := blank string
for j in range 0 to number of columns, docurr_row := curr_row concatenate "-" concatenate matrix[i,j]
curr_row := curr_row concatenate "-" concatenate matrix[i,j]
if curr_row is present in string concat, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
Live Demo
def solve(matrix) :
concat = ""
for i in range(len(matrix)) :
concat = concat + "-" + str(matrix[0][i])
concat = concat + concat
for i in range(1, len(matrix)) :
curr_row = ""
for j in range(len(matrix[0])) :
curr_row = curr_row + "-" + str(matrix[i][j])
if (concat.find(curr_row)) :
return True
return False
matrix = [['B', 'A', 'D', 'C'],
['C', 'B', 'A', 'D'],
['D', 'C', 'B', 'A'],
['A', 'D', 'C', 'B']]
print(solve(matrix))
[['B', 'A', 'D', 'C'],
['C', 'B', 'A', 'D'],
['D', 'C', 'B', 'A'],
['A', 'D', 'C', 'B']]
True | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "Suppose, we are provided with a matrix of the size n*n, containing integer numbers. We have to find out if all the rows of that matrix are circular rotations of its previous row. In case of first row, it should be a circular rotation of the n-th row."
},
{
"code": null,
"e": 1338,
"s": 1313,
"text": "So, if the input is like"
},
{
"code": null,
"e": 1368,
"s": 1338,
"text": "then the output will be True."
},
{
"code": null,
"e": 1412,
"s": 1368,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1435,
"s": 1412,
"text": "concat := blank string"
},
{
"code": null,
"e": 1530,
"s": 1435,
"text": "for i in range 0 to number of rows, doconcat := concat concatenate \"-\" concatenate matrix[0,i]"
},
{
"code": null,
"e": 1587,
"s": 1530,
"text": "concat := concat concatenate \"-\" concatenate matrix[0,i]"
},
{
"code": null,
"e": 1623,
"s": 1587,
"text": "concat := concat concatenate concat"
},
{
"code": null,
"e": 1843,
"s": 1623,
"text": "for i in range 1 to size of matrix, docurr_row := blank stringfor j in range 0 to number of columns, docurr_row := curr_row concatenate \"-\" concatenate matrix[i,j]if curr_row is present in string concat, thenreturn True"
},
{
"code": null,
"e": 1868,
"s": 1843,
"text": "curr_row := blank string"
},
{
"code": null,
"e": 1970,
"s": 1868,
"text": "for j in range 0 to number of columns, docurr_row := curr_row concatenate \"-\" concatenate matrix[i,j]"
},
{
"code": null,
"e": 2031,
"s": 1970,
"text": "curr_row := curr_row concatenate \"-\" concatenate matrix[i,j]"
},
{
"code": null,
"e": 2088,
"s": 2031,
"text": "if curr_row is present in string concat, thenreturn True"
},
{
"code": null,
"e": 2100,
"s": 2088,
"text": "return True"
},
{
"code": null,
"e": 2113,
"s": 2100,
"text": "return False"
},
{
"code": null,
"e": 2183,
"s": 2113,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 2194,
"s": 2183,
"text": " Live Demo"
},
{
"code": null,
"e": 2706,
"s": 2194,
"text": "def solve(matrix) :\n concat = \"\"\n for i in range(len(matrix)) :\n concat = concat + \"-\" + str(matrix[0][i])\n concat = concat + concat\n for i in range(1, len(matrix)) :\n curr_row = \"\"\n for j in range(len(matrix[0])) :\n curr_row = curr_row + \"-\" + str(matrix[i][j])\n if (concat.find(curr_row)) :\n return True\n return False\nmatrix = [['B', 'A', 'D', 'C'],\n ['C', 'B', 'A', 'D'],\n ['D', 'C', 'B', 'A'],\n ['A', 'D', 'C', 'B']]\nprint(solve(matrix))"
},
{
"code": null,
"e": 2795,
"s": 2706,
"text": "[['B', 'A', 'D', 'C'],\n['C', 'B', 'A', 'D'],\n['D', 'C', 'B', 'A'],\n['A', 'D', 'C', 'B']]"
},
{
"code": null,
"e": 2800,
"s": 2795,
"text": "True"
}
] |
Rebuilding indexes in MongoDB? | To rebuild indexes, use reIndex(). Let us first create an index. Following is the query −
> db.demo42.createIndex({"StudentFirstName":1});
This will produce the following output −
{
"createdCollectionAutomatically" : true,
"numIndexesBefore" : 1,
"numIndexesAfter" : 2,
"ok" : 1
}
Following is the query to rebuild index in MongoDB −
> db.demo42.reIndex({"StudentFirstName":1});
This will produce the following output −
{
"nIndexesWas" : 2,
"nIndexes" : 2,
"indexes" : [
{
"v" : 2,
"key" : {
"_id" : 1
},
"name" : "_id_",
"ns" : "web.demo42"
},
{
"v" : 2,
"key" : {
"StudentFirstName" : 1
},
"name" : "StudentFirstName_1",
"ns" : "web.demo42"
}
],
"ok" : 1
} | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To rebuild indexes, use reIndex(). Let us first create an index. Following is the query −"
},
{
"code": null,
"e": 1201,
"s": 1152,
"text": "> db.demo42.createIndex({\"StudentFirstName\":1});"
},
{
"code": null,
"e": 1242,
"s": 1201,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1355,
"s": 1242,
"text": "{\n \"createdCollectionAutomatically\" : true,\n \"numIndexesBefore\" : 1,\n \"numIndexesAfter\" : 2,\n \"ok\" : 1\n}"
},
{
"code": null,
"e": 1408,
"s": 1355,
"text": "Following is the query to rebuild index in MongoDB −"
},
{
"code": null,
"e": 1453,
"s": 1408,
"text": "> db.demo42.reIndex({\"StudentFirstName\":1});"
},
{
"code": null,
"e": 1494,
"s": 1453,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 1885,
"s": 1494,
"text": "{\n \"nIndexesWas\" : 2,\n \"nIndexes\" : 2,\n \"indexes\" : [\n {\n \"v\" : 2,\n \"key\" : {\n \"_id\" : 1\n },\n \"name\" : \"_id_\",\n \"ns\" : \"web.demo42\"\n },\n {\n \"v\" : 2,\n \"key\" : {\n \"StudentFirstName\" : 1\n },\n \"name\" : \"StudentFirstName_1\",\n \"ns\" : \"web.demo42\"\n }\n ],\n \"ok\" : 1\n}"
}
] |
Largest area rectangular sub-matrix with equal number of 1's and 0's - GeeksforGeeks | 26 Sep, 2017
Given a binary matrix. The problem is to find the largest area rectangular sub-matrix with equal number of 1’s and 0’s.
Examples:
Input : mat[][] = { {0, 0, 1, 1},
{0, 1, 1, 0},
{1, 1, 1, 0},
{1, 0, 0, 1} }
Output : 8 sq. units
(Top, left): (0, 0)
(Bottom, right): (3, 1)
Input : mat[][] = { {0, 0, 1, 1},
{0, 1, 1, 1} }
Output : 6 sq. units
The naive solution for this problem is to check every possible rectangle in given 2D array by counting the total number of 1’s and 0’s in that rectangle. This solution requires 4 nested loops and time complexity of this solution would be O(n^4).
An efficient solution is based on Largest rectangular sub-matrix whose sum is 0 which reduces the time complexity to O(n^3). First of all consider every ‘0’ in the matrix as ‘-1’. Now, the idea is to reduce the problem to 1-D array. We fix the left and right columns one by one and find the largest sub-array with 0 sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have sum zero) for every fixed left and right column pair. To find the top and bottom row numbers, calculate sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i. If we find largest subarray with 0 sum in temp[], we can get the index positions of rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s and 0’s). With this process we can find the largest area rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s and 0’s). We can use Hashing technique to find maximum length sub-array with sum equal to 0 in 1-D array in O(n) time.
// C++ implementation to find largest area rectangular// submatrix with equal number of 1's and 0's#include <bits/stdc++.h> using namespace std; #define MAX_ROW 10#define MAX_COL 10 // This function basically finds largest 0// sum subarray in arr[0..n-1]. If 0 sum// does't exist, then it returns false. Else// it returns true and sets starting and// ending indexes as start and end.bool subArrWithSumZero(int arr[], int &start, int &end, int n){ // to store cumulative sum int sum[n]; // Initialize all elements of sum[] to 0 memset(sum, 0, sizeof(sum)); // map to store the indexes of sum unordered_map<int, int> um; // build up the cumulative sum[] array sum[0] = arr[0]; for (int i=1; i<n; i++) sum[i] = sum[i-1] + arr[i]; // to store the maximum length subarray // with sum equal to 0 int maxLen = 0; // traverse to the sum[] array for (int i=0; i<n; i++) { // if true, then there is a subarray // with sum equal to 0 from the // beginning up to index 'i' if (sum[i] == 0) { // update the required variables start = 0; end = i; maxLen = (i+1); } // else if true, then sum[i] has not // seen before in 'um' else if (um.find(sum[i]) == um.end()) um[sum[i]] = i; // sum[i] has been seen before in the // unordered_map 'um' else { // if previous subarray length is smaller // than the current subarray length, then // update the required variables if (maxLen < (i-um[sum[i]])) { maxLen = (i-um[sum[i]]); start = um[sum[i]] + 1; end = i; } } } // if true, then there is no // subarray with sum equal to 0 if (maxLen == 0) return false; // else return true return true; } // function to find largest area rectangular// submatrix with equal number of 1's and 0'svoid maxAreaRectWithSumZero(int mat[MAX_ROW][MAX_COL], int row, int col){ // to store intermediate values int temp[row], startRow, endRow; // to store the final outputs int finalLeft, finalRight, finalTop, finalBottom; finalLeft = finalRight = finalTop = finalBottom = -1; int maxArea = 0; // Set the left column for (int left = 0; left < col; left++) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left column // set by outer loop for (int right = left; right < col; right++) { // Calculate sum between current left // and right for every row 'i' // consider value '1' as '1' and // value '0' as '-1' for (int i=0; i<row; i++) temp[i] += mat[i][right] ? 1 : -1; // Find largest subarray with 0 sum in // temp[]. The subArrWithSumZero() function // also sets values of finalTop, finalBottom, // finalLeft and finalRight if there exists // a subarray with sum 0 in temp if (subArrWithSumZero(temp, startRow, endRow, row)) { int area = (right - left + 1) * (endRow - startRow + 1); // Compare current 'area' with previous area // and accodingly update final values if (maxArea < area) { finalTop = startRow; finalBottom = endRow; finalLeft = left; finalRight = right; maxArea = area; } } } } // if true then there is no rectangular submatrix // with equal number of 1's and 0's if (maxArea == 0) cout << "No such rectangular submatrix exists:"; // displaying the top left and bottom right boundaries // with the area of the rectangular submatrix else { cout << "(Top, Left): " << "(" << finalTop << ", " << finalLeft << ")" << endl; cout << "(Bottom, Right): " << "(" << finalBottom << ", " << finalRight << ")" << endl; cout << "Area: " << maxArea << " sq.units"; }} // Driver program to test aboveint main(){ int mat[MAX_ROW][MAX_COL] = { {0, 0, 1, 1}, {0, 1, 1, 0}, {1, 1, 1, 0}, {1, 0, 0, 1} }; int row = 4, col = 4; maxAreaRectWithSumZero(mat, row, col); return 0; }
Output:
(Top, Left): (0, 0)
(Bottom, Right): (3, 1)
Area: 8 sq.units
Time Complexity: O(n3)Auxiliary Space: O(n)
This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Dynamic Programming
Matrix
Dynamic Programming
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16
Subset Sum Problem | DP-25
Coin Change | DP-7
Matrix Chain Multiplication | DP-8
Matrix Chain Multiplication | DP-8
Program to find largest element in an array
Print a given matrix in spiral form
Sudoku | Backtracking-7
Rat in a Maze | Backtracking-2 | [
{
"code": null,
"e": 24935,
"s": 24907,
"text": "\n26 Sep, 2017"
},
{
"code": null,
"e": 25055,
"s": 24935,
"text": "Given a binary matrix. The problem is to find the largest area rectangular sub-matrix with equal number of 1’s and 0’s."
},
{
"code": null,
"e": 25065,
"s": 25055,
"text": "Examples:"
},
{
"code": null,
"e": 25371,
"s": 25065,
"text": "Input : mat[][] = { {0, 0, 1, 1},\n {0, 1, 1, 0},\n {1, 1, 1, 0},\n {1, 0, 0, 1} }\nOutput : 8 sq. units\n(Top, left): (0, 0)\n(Bottom, right): (3, 1)\n\nInput : mat[][] = { {0, 0, 1, 1},\n {0, 1, 1, 1} } \nOutput : 6 sq. units\n"
},
{
"code": null,
"e": 25617,
"s": 25371,
"text": "The naive solution for this problem is to check every possible rectangle in given 2D array by counting the total number of 1’s and 0’s in that rectangle. This solution requires 4 nested loops and time complexity of this solution would be O(n^4)."
},
{
"code": null,
"e": 26723,
"s": 25617,
"text": "An efficient solution is based on Largest rectangular sub-matrix whose sum is 0 which reduces the time complexity to O(n^3). First of all consider every ‘0’ in the matrix as ‘-1’. Now, the idea is to reduce the problem to 1-D array. We fix the left and right columns one by one and find the largest sub-array with 0 sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have sum zero) for every fixed left and right column pair. To find the top and bottom row numbers, calculate sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i. If we find largest subarray with 0 sum in temp[], we can get the index positions of rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s and 0’s). With this process we can find the largest area rectangular sub-matrix with sum equal to 0 (i.e. having equal number of 1’s and 0’s). We can use Hashing technique to find maximum length sub-array with sum equal to 0 in 1-D array in O(n) time."
},
{
"code": "// C++ implementation to find largest area rectangular// submatrix with equal number of 1's and 0's#include <bits/stdc++.h> using namespace std; #define MAX_ROW 10#define MAX_COL 10 // This function basically finds largest 0// sum subarray in arr[0..n-1]. If 0 sum// does't exist, then it returns false. Else// it returns true and sets starting and// ending indexes as start and end.bool subArrWithSumZero(int arr[], int &start, int &end, int n){ // to store cumulative sum int sum[n]; // Initialize all elements of sum[] to 0 memset(sum, 0, sizeof(sum)); // map to store the indexes of sum unordered_map<int, int> um; // build up the cumulative sum[] array sum[0] = arr[0]; for (int i=1; i<n; i++) sum[i] = sum[i-1] + arr[i]; // to store the maximum length subarray // with sum equal to 0 int maxLen = 0; // traverse to the sum[] array for (int i=0; i<n; i++) { // if true, then there is a subarray // with sum equal to 0 from the // beginning up to index 'i' if (sum[i] == 0) { // update the required variables start = 0; end = i; maxLen = (i+1); } // else if true, then sum[i] has not // seen before in 'um' else if (um.find(sum[i]) == um.end()) um[sum[i]] = i; // sum[i] has been seen before in the // unordered_map 'um' else { // if previous subarray length is smaller // than the current subarray length, then // update the required variables if (maxLen < (i-um[sum[i]])) { maxLen = (i-um[sum[i]]); start = um[sum[i]] + 1; end = i; } } } // if true, then there is no // subarray with sum equal to 0 if (maxLen == 0) return false; // else return true return true; } // function to find largest area rectangular// submatrix with equal number of 1's and 0'svoid maxAreaRectWithSumZero(int mat[MAX_ROW][MAX_COL], int row, int col){ // to store intermediate values int temp[row], startRow, endRow; // to store the final outputs int finalLeft, finalRight, finalTop, finalBottom; finalLeft = finalRight = finalTop = finalBottom = -1; int maxArea = 0; // Set the left column for (int left = 0; left < col; left++) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left column // set by outer loop for (int right = left; right < col; right++) { // Calculate sum between current left // and right for every row 'i' // consider value '1' as '1' and // value '0' as '-1' for (int i=0; i<row; i++) temp[i] += mat[i][right] ? 1 : -1; // Find largest subarray with 0 sum in // temp[]. The subArrWithSumZero() function // also sets values of finalTop, finalBottom, // finalLeft and finalRight if there exists // a subarray with sum 0 in temp if (subArrWithSumZero(temp, startRow, endRow, row)) { int area = (right - left + 1) * (endRow - startRow + 1); // Compare current 'area' with previous area // and accodingly update final values if (maxArea < area) { finalTop = startRow; finalBottom = endRow; finalLeft = left; finalRight = right; maxArea = area; } } } } // if true then there is no rectangular submatrix // with equal number of 1's and 0's if (maxArea == 0) cout << \"No such rectangular submatrix exists:\"; // displaying the top left and bottom right boundaries // with the area of the rectangular submatrix else { cout << \"(Top, Left): \" << \"(\" << finalTop << \", \" << finalLeft << \")\" << endl; cout << \"(Bottom, Right): \" << \"(\" << finalBottom << \", \" << finalRight << \")\" << endl; cout << \"Area: \" << maxArea << \" sq.units\"; }} // Driver program to test aboveint main(){ int mat[MAX_ROW][MAX_COL] = { {0, 0, 1, 1}, {0, 1, 1, 0}, {1, 1, 1, 0}, {1, 0, 0, 1} }; int row = 4, col = 4; maxAreaRectWithSumZero(mat, row, col); return 0; } ",
"e": 31663,
"s": 26723,
"text": null
},
{
"code": null,
"e": 31671,
"s": 31663,
"text": "Output:"
},
{
"code": null,
"e": 31733,
"s": 31671,
"text": "(Top, Left): (0, 0)\n(Bottom, Right): (3, 1)\nArea: 8 sq.units\n"
},
{
"code": null,
"e": 31777,
"s": 31733,
"text": "Time Complexity: O(n3)Auxiliary Space: O(n)"
},
{
"code": null,
"e": 32078,
"s": 31777,
"text": "This article is contributed by Ayush Jauhari. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 32203,
"s": 32078,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 32223,
"s": 32203,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32230,
"s": 32223,
"text": "Matrix"
},
{
"code": null,
"e": 32250,
"s": 32230,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 32257,
"s": 32250,
"text": "Matrix"
},
{
"code": null,
"e": 32355,
"s": 32257,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32364,
"s": 32355,
"text": "Comments"
},
{
"code": null,
"e": 32377,
"s": 32364,
"text": "Old Comments"
},
{
"code": null,
"e": 32408,
"s": 32377,
"text": "Bellman–Ford Algorithm | DP-23"
},
{
"code": null,
"e": 32441,
"s": 32408,
"text": "Floyd Warshall Algorithm | DP-16"
},
{
"code": null,
"e": 32468,
"s": 32441,
"text": "Subset Sum Problem | DP-25"
},
{
"code": null,
"e": 32487,
"s": 32468,
"text": "Coin Change | DP-7"
},
{
"code": null,
"e": 32522,
"s": 32487,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 32557,
"s": 32522,
"text": "Matrix Chain Multiplication | DP-8"
},
{
"code": null,
"e": 32601,
"s": 32557,
"text": "Program to find largest element in an array"
},
{
"code": null,
"e": 32637,
"s": 32601,
"text": "Print a given matrix in spiral form"
},
{
"code": null,
"e": 32661,
"s": 32637,
"text": "Sudoku | Backtracking-7"
}
] |
FTP protocol client in Python | The all important The FTP class in ftplib module implements the client side of the FTP protocol.
To establish connection with a FTP server, obtain FTP object.
The FTP class supports following methods −
Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification.
Return the welcome message sent by the server in reply to the initial connection.
login(user='anonymous', passwd='', acct='')
Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to 'anonymous'. If user is 'anonymous', the default passwd is 'anonymous@'.
Abort a file transfer that is in progress.
Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: 'RETR filename'.
Store a file in binary transfer mode. cmd should be an appropriate STOR command: "STOR filename". fp is a file object (opened in binary mode) which is read until EOF using its read() method
Produce a directory listing as returned by the LIST command, printing it to standard output.
Remove the file named filename from the server.
Set the current directory on the server.
Create a new directory on the server.
Return the pathname of the current directory on the server.
Remove the directory named dirname on the server.
Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations.
Send a QUIT command to the server and close the connection.
Following example establishes anonymous connection with a server, downloads a file to local folder and uploads a local file.
from ftplib import FTP
import os
def downloadFile():
filename = 'README.MIRRORS'
localfile = open(filename, 'wb')
ftp.retrbinary('RETR ' + filename, localfile.write, 1024)
ftp.quit()
localfile.close()
def uploadFile():
filename = '/home/malhar/file.txt'
ftp.storbinary('STOR '+filename, open(filename, 'rb'))
ftp.quit()
with FTP("ftp1.at.proftpd.org") as ftp:
ftp.login()
ftp.getwelcome()
ftp.dir()
downloadFile()
uploadFile() | [
{
"code": null,
"e": 1159,
"s": 1062,
"text": "The all important The FTP class in ftplib module implements the client side of the FTP protocol."
},
{
"code": null,
"e": 1221,
"s": 1159,
"text": "To establish connection with a FTP server, obtain FTP object."
},
{
"code": null,
"e": 1264,
"s": 1221,
"text": "The FTP class supports following methods −"
},
{
"code": null,
"e": 1379,
"s": 1264,
"text": "Connect to the given host and port. The default port number is 21, as specified by the FTP protocol specification."
},
{
"code": null,
"e": 1461,
"s": 1379,
"text": "Return the welcome message sent by the server in reply to the initial connection."
},
{
"code": null,
"e": 1505,
"s": 1461,
"text": "login(user='anonymous', passwd='', acct='')"
},
{
"code": null,
"e": 1721,
"s": 1505,
"text": "Log in as the given user. The passwd and acct parameters are optional and default to the empty string. If no user is specified, it defaults to 'anonymous'. If user is 'anonymous', the default passwd is 'anonymous@'."
},
{
"code": null,
"e": 1764,
"s": 1721,
"text": "Abort a file transfer that is in progress."
},
{
"code": null,
"e": 1865,
"s": 1764,
"text": "Retrieve a file in binary transfer mode. cmd should be an appropriate RETR command: 'RETR filename'."
},
{
"code": null,
"e": 2055,
"s": 1865,
"text": "Store a file in binary transfer mode. cmd should be an appropriate STOR command: \"STOR filename\". fp is a file object (opened in binary mode) which is read until EOF using its read() method"
},
{
"code": null,
"e": 2148,
"s": 2055,
"text": "Produce a directory listing as returned by the LIST command, printing it to standard output."
},
{
"code": null,
"e": 2196,
"s": 2148,
"text": "Remove the file named filename from the server."
},
{
"code": null,
"e": 2237,
"s": 2196,
"text": "Set the current directory on the server."
},
{
"code": null,
"e": 2275,
"s": 2237,
"text": "Create a new directory on the server."
},
{
"code": null,
"e": 2335,
"s": 2275,
"text": "Return the pathname of the current directory on the server."
},
{
"code": null,
"e": 2385,
"s": 2335,
"text": "Remove the directory named dirname on the server."
},
{
"code": null,
"e": 2636,
"s": 2385,
"text": "Request the size of the file named filename on the server. On success, the size of the file is returned as an integer, otherwise None is returned. Note that the SIZE command is not standardized, but is supported by many common server implementations."
},
{
"code": null,
"e": 2696,
"s": 2636,
"text": "Send a QUIT command to the server and close the connection."
},
{
"code": null,
"e": 2821,
"s": 2696,
"text": "Following example establishes anonymous connection with a server, downloads a file to local folder and uploads a local file."
},
{
"code": null,
"e": 3287,
"s": 2821,
"text": "from ftplib import FTP\nimport os\ndef downloadFile():\n filename = 'README.MIRRORS'\n localfile = open(filename, 'wb')\n ftp.retrbinary('RETR ' + filename, localfile.write, 1024)\n ftp.quit()\n localfile.close()\ndef uploadFile():\n filename = '/home/malhar/file.txt'\n ftp.storbinary('STOR '+filename, open(filename, 'rb'))\n ftp.quit()\nwith FTP(\"ftp1.at.proftpd.org\") as ftp:\n ftp.login()\n ftp.getwelcome()\n ftp.dir()\n downloadFile()\n uploadFile()"
}
] |
Cassandra - Update Data | UPDATE is the command used to update data in a table. The following keywords are used while updating data in a table −
Where − This clause is used to select the row to be updated.
Where − This clause is used to select the row to be updated.
Set − Set the value using this keyword.
Set − Set the value using this keyword.
Must − Includes all the columns composing the primary key.
Must − Includes all the columns composing the primary key.
While updating rows, if a given row is unavailable, then UPDATE creates a fresh row. Given below is the syntax of UPDATE command −
UPDATE <tablename>
SET <column name> = <new value>
<column name> = <value>....
WHERE <condition>
Assume there is a table named emp. This table stores the details of employees of a certain company, and it has the following details −
Let us now update emp_city of robin to Delhi, and his salary to 50000. Given below is the query to perform the required updates.
cqlsh:tutorialspoint> UPDATE emp SET emp_city='Delhi',emp_sal=50000
WHERE emp_id=2;
Use SELECT statement to verify whether the data has been updated or not. If you verify the emp table using SELECT statement, it will produce the following output.
cqlsh:tutorialspoint> select * from emp;
emp_id | emp_city | emp_name | emp_phone | emp_sal
--------+-----------+----------+------------+---------
1 | Hyderabad | ram | 9848022338 | 50000
2 | Delhi | robin | 9848022339 | 50000
3 | Chennai | rahman | 9848022330 | 45000
(3 rows)
Here you can observe the table data has got updated.
You can update data in a table using the execute() method of Session class. Follow the steps given below to update data in a table using Java API.
Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below.
//Creating Cluster.Builder object
Cluster.Builder builder1 = Cluster.builder();
Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder.
//Adding contact point to the Cluster.Builder object
Cluster.Builder builder2 = build.addContactPoint("127.0.0.1");
Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. Use the following code to create the cluster object.
//Building a cluster
Cluster cluster = builder.build();
You can build the cluster object using a single line of code as shown below.
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Create an instance of Session object using the connect() method of Cluster class as shown below.
Session session = cluster.connect( );
This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below.
Session session = cluster.connect(“ Your keyspace name”);
Here we are using the KeySpace named tp. Therefore, create the session object as shown below.
Session session = cluster.connect(“tp”);
You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh.
In the following example, we are updating the emp table. You have to store the query in a string variable and pass it to the execute() method as shown below:
String query = “ UPDATE emp SET emp_city='Delhi',emp_sal=50000
WHERE emp_id = 2;” ;
Given below is the complete program to update data in a table using Java API.
import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;
public class Update_Data {
public static void main(String args[]){
//query
String query = " UPDATE emp SET emp_city='Delhi',emp_sal=50000"
//Creating Cluster object
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
//Creating Session object
Session session = cluster.connect("tp");
//Executing the query
session.execute(query);
System.out.println("Data updated");
}
}
Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below.
$javac Update_Data.java
$java Update_Data
Under normal conditions, it should produce the following output −
Data updated
27 Lectures
2 hours
Navdeep Kaur
34 Lectures
1.5 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2406,
"s": 2287,
"text": "UPDATE is the command used to update data in a table. The following keywords are used while updating data in a table −"
},
{
"code": null,
"e": 2467,
"s": 2406,
"text": "Where − This clause is used to select the row to be updated."
},
{
"code": null,
"e": 2528,
"s": 2467,
"text": "Where − This clause is used to select the row to be updated."
},
{
"code": null,
"e": 2568,
"s": 2528,
"text": "Set − Set the value using this keyword."
},
{
"code": null,
"e": 2608,
"s": 2568,
"text": "Set − Set the value using this keyword."
},
{
"code": null,
"e": 2667,
"s": 2608,
"text": "Must − Includes all the columns composing the primary key."
},
{
"code": null,
"e": 2726,
"s": 2667,
"text": "Must − Includes all the columns composing the primary key."
},
{
"code": null,
"e": 2857,
"s": 2726,
"text": "While updating rows, if a given row is unavailable, then UPDATE creates a fresh row. Given below is the syntax of UPDATE command −"
},
{
"code": null,
"e": 2955,
"s": 2857,
"text": "UPDATE <tablename>\nSET <column name> = <new value>\n<column name> = <value>....\nWHERE <condition>\n"
},
{
"code": null,
"e": 3090,
"s": 2955,
"text": "Assume there is a table named emp. This table stores the details of employees of a certain company, and it has the following details −"
},
{
"code": null,
"e": 3219,
"s": 3090,
"text": "Let us now update emp_city of robin to Delhi, and his salary to 50000. Given below is the query to perform the required updates."
},
{
"code": null,
"e": 3307,
"s": 3219,
"text": "cqlsh:tutorialspoint> UPDATE emp SET emp_city='Delhi',emp_sal=50000\n WHERE emp_id=2;\n"
},
{
"code": null,
"e": 3470,
"s": 3307,
"text": "Use SELECT statement to verify whether the data has been updated or not. If you verify the emp table using SELECT statement, it will produce the following output."
},
{
"code": null,
"e": 3794,
"s": 3470,
"text": "cqlsh:tutorialspoint> select * from emp;\n\n emp_id | emp_city | emp_name | emp_phone | emp_sal\n--------+-----------+----------+------------+---------\n 1 | Hyderabad | ram | 9848022338 | 50000\n 2 | Delhi | robin | 9848022339 | 50000\n 3 | Chennai | rahman | 9848022330 | 45000\n \n(3 rows)\n"
},
{
"code": null,
"e": 3847,
"s": 3794,
"text": "Here you can observe the table data has got updated."
},
{
"code": null,
"e": 3994,
"s": 3847,
"text": "You can update data in a table using the execute() method of Session class. Follow the steps given below to update data in a table using Java API."
},
{
"code": null,
"e": 4090,
"s": 3994,
"text": "Create an instance of Cluster.builder class of com.datastax.driver.core package as shown below."
},
{
"code": null,
"e": 4171,
"s": 4090,
"text": "//Creating Cluster.Builder object\nCluster.Builder builder1 = Cluster.builder();\n"
},
{
"code": null,
"e": 4315,
"s": 4171,
"text": "Add a contact point (IP address of the node) using the addContactPoint() method of Cluster.Builder object. This method returns Cluster.Builder."
},
{
"code": null,
"e": 4432,
"s": 4315,
"text": "//Adding contact point to the Cluster.Builder object\nCluster.Builder builder2 = build.addContactPoint(\"127.0.0.1\");\n"
},
{
"code": null,
"e": 4613,
"s": 4432,
"text": "Using the new builder object, create a cluster object. To do so, you have a method called build() in the Cluster.Builder class. Use the following code to create the cluster object."
},
{
"code": null,
"e": 4670,
"s": 4613,
"text": "//Building a cluster\nCluster cluster = builder.build();\n"
},
{
"code": null,
"e": 4747,
"s": 4670,
"text": "You can build the cluster object using a single line of code as shown below."
},
{
"code": null,
"e": 4822,
"s": 4747,
"text": "Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n"
},
{
"code": null,
"e": 4919,
"s": 4822,
"text": "Create an instance of Session object using the connect() method of Cluster class as shown below."
},
{
"code": null,
"e": 4958,
"s": 4919,
"text": "Session session = cluster.connect( );\n"
},
{
"code": null,
"e": 5161,
"s": 4958,
"text": "This method creates a new session and initializes it. If you already have a keyspace, then you can set it to the existing one by passing the KeySpace name in string format to this method as shown below."
},
{
"code": null,
"e": 5220,
"s": 5161,
"text": "Session session = cluster.connect(“ Your keyspace name”);\n"
},
{
"code": null,
"e": 5314,
"s": 5220,
"text": "Here we are using the KeySpace named tp. Therefore, create the session object as shown below."
},
{
"code": null,
"e": 5356,
"s": 5314,
"text": "Session session = cluster.connect(“tp”);\n"
},
{
"code": null,
"e": 5605,
"s": 5356,
"text": "You can execute CQL queries using the execute() method of Session class. Pass the query either in string format or as a Statement class object to the execute() method. Whatever you pass to this method in string format will be executed on the cqlsh."
},
{
"code": null,
"e": 5763,
"s": 5605,
"text": "In the following example, we are updating the emp table. You have to store the query in a string variable and pass it to the execute() method as shown below:"
},
{
"code": null,
"e": 5848,
"s": 5763,
"text": "String query = “ UPDATE emp SET emp_city='Delhi',emp_sal=50000\nWHERE emp_id = 2;” ;\n"
},
{
"code": null,
"e": 5926,
"s": 5848,
"text": "Given below is the complete program to update data in a table using Java API."
},
{
"code": null,
"e": 6504,
"s": 5926,
"text": "import com.datastax.driver.core.Cluster;\nimport com.datastax.driver.core.Session;\n\npublic class Update_Data {\n \n public static void main(String args[]){\n \n //query\n String query = \" UPDATE emp SET emp_city='Delhi',emp_sal=50000\"\n \n //Creating Cluster object\n Cluster cluster = Cluster.builder().addContactPoint(\"127.0.0.1\").build();\n \n //Creating Session object\n Session session = cluster.connect(\"tp\");\n \n //Executing the query\n session.execute(query);\n\n System.out.println(\"Data updated\");\n }\n }"
},
{
"code": null,
"e": 6656,
"s": 6504,
"text": "Save the above program with the class name followed by .java, browse to the location where it is saved. Compile and execute the program as shown below."
},
{
"code": null,
"e": 6699,
"s": 6656,
"text": "$javac Update_Data.java\n$java Update_Data\n"
},
{
"code": null,
"e": 6765,
"s": 6699,
"text": "Under normal conditions, it should produce the following output −"
},
{
"code": null,
"e": 6779,
"s": 6765,
"text": "Data updated\n"
},
{
"code": null,
"e": 6812,
"s": 6779,
"text": "\n 27 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 6826,
"s": 6812,
"text": " Navdeep Kaur"
},
{
"code": null,
"e": 6861,
"s": 6826,
"text": "\n 34 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 6879,
"s": 6861,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 6886,
"s": 6879,
"text": " Print"
},
{
"code": null,
"e": 6897,
"s": 6886,
"text": " Add Notes"
}
] |
Introduction to Convolutional Neural Networks (CNN) with TensorFlow | by Marco Peixeiro | Towards Data Science | Recent advances in deep learning have made computer vision applications leap forward: from unlocking our mobile phone with our face, to safer self-driving cars.
Convolutional neural networks (CNN) are the architecture behind computer vision applications. In this post, you will learn about the foundations of CNNs and computer vision such as the convolution operation, padding, strided convolutions and pooling layers. Then, we will use TensorFlow to build a CNN for image recognition.
For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel.
The convolution operation is the building block of a convolutional neural network as the name suggests it.
Now, in the field of computer vision, an image can be expressed as a matrix of RGB values. This concept was actually introduced in an earlier post.
To complete the convolution operation, we need an image and a filter.
Therefore, let’s consider the 6x6 matrix below as a part of an image:
And the filter will be the following matrix:
Then, the convolution involves superimposing the filter onto the image matrix, adding the product of the values from the filter and and the values from the image matrix, which will generate a 4x4 convoluted layer.
This is very hard to put in words, but here is a nice animation that explains the convolution:
Performing this on the image matrix above and using the filter defined above, you should get the following resulting matrix:
How do you interpret the output layer?
Well, considering that each value is indicative of color, or how dark a pixel is (positive value means light, negative value means dark), then you can interpret the output layer as:
Therefore, it seems that this particular filter is responsible to detect vertical edges in images!
This is a natural question, as you might realize that there is an infinite number of possible filters you can apply to an image.
It turns out that the exact values in your filter matrix can be trainable parameters based on the model’s objective. Therefore, you can either choose a filter that has worked for your specific application, or you can use backpropagation to determine the best values for your filter that will yield the best outcome.
Previously, we have seen that a 3x3 filter convoluted with a 6x6 image, will result in 4x4 matrix. This is because there are 4x4 possible positions for the filter to fit in a 6x6 image.
Therefore, after each convolution step, the image shrinks, meaning that only a finite number of convolution can be performed until the image cannot be shrunken anymore. Furthermore, pixels situated in the corner of the image are only used once, and this results in loss of information for the neural network.
In order to solve both problems stated above, padding is used. Padding consists in adding a border around the input image as shown below:
As you can see, the added border is usually filled with zeros. Now, the corner pixel of the image will be used many times to calculate the output, effectively preventing loss of information. Also, it allows us to keep the input matrix shape in the output.
Considering our 6x6 input image, if we add a padding of 1, we get a 8x8 matrix. Applying a 3x3 filter, this will result in a 6x6 output.
A simple equation can help us figure out the shape of the output:
To reiterate, we have:
6x6 input
padding of 1
3x3 filter
Thus, the output shape will be: 6+2(1)-3+1 = 6. Therefore, the output will be a 6x6 matrix, just like the input image!
Padding is not always required. However, when padding is used, it is usually for the output to have the same size as the input image. This yields two types of convolutions.
When no padding is applied, this is called a “valid convolution”. Otherwise, it is termed “same convolution”. To determine the padding size required to keep the dimensions of the input image, simply equate the formula above to n. After solving for p, you should get:
You might have noticed that f should be odd in order for the padding to be a whole number. Hence, it is a convention in the field of computer visions to have odd filters.
Previously, we have seen a convolution with a stride of 1. This means that the filter was moving horizontally and vertically by 1 pixel.
A strided convolution is when the stride is greater than 1. In the animation below, the stride is 2:
Now, taking into account the stride, the formula to calculate the shape of the output matrix is:
As a convention, if the formula above does not yield a whole number, then we round down to the nearest integer.
Pooling layers are another way to reduce the size of the image interpretation in order to speed up computation, and it makes the detected features more robust.
Pooling is best explained with an image. Below is an example of max pooling:
As you can see, we chose a 2x2 filter with a stride of 2. This is equivalent to dividing the input into 4 identical squares, we then take the maximum value of each square, and use it in the output.
Average pooling can also be performed, but it less popular than max pooling.
You can think of pooling as a way to prevent overfitting, since we are removing some features from the input image.
We now have a strong foundational knowledge of convolutional neural networks. However, why do deep learning practitioners use them?
Unlike fully connected layers, convolutional layers have a much smaller set of parameters to learn. This is due to:
parameter sharing
sparsity of connection
Parameter sharing refers to the fact that one feature detector, such as vertical edges detector, will be useful in many parts of the image. Then, the sparsity of connections refers to the fact that only a few features are related to a certain output value.
Considering the above example of max pooling, the top left value for the output depends solely on the top left 2x2 square from the input image.
Therefore, we can train on smaller datasets and greatly reduce the number of parameters to learn, making CNNs a great tool for computer vision tasks.
Enough with the theory, let’s code a CNN for hand signs recognition. We revisit a previous project to see if a CNN will perform better.
As always, the full notebook is available here.
After importing the required libraries and assets, we load the data and preprocess the images:
Then, we create placeholders for the features and the target:
We then initialize our parameters using Xavier initialization:
Now, we define the forward propagation step, which is really the architecture of our CNN. We will use a simply 3-layer network with 2 convolutional layers and a final fully-connected layer:
Finally, we define a function that will compute the cost:
Now, we combine all the functions above into a single CNN network. We will use mini-batch gradient descent for training:
Great! Now, we can run our model and see how it performs:
_, _, parameters = model(X_train, Y_train, X_test, Y_test)
In my case, I trained the CNN on a laptop using only CPU, and I got a pretty bad result. If you train the CNN on a desktop with a better CPU and GPU, you will surely get better results than I did.
Congratulations! You now have a very good knowledge about CNNs and the field of computer vision. Although there is much more to learn, the more advanced techniques use the concepts introduced here as building blocks.
In the next post, I will introduce residual networks with Keras! | [
{
"code": null,
"e": 332,
"s": 171,
"text": "Recent advances in deep learning have made computer vision applications leap forward: from unlocking our mobile phone with our face, to safer self-driving cars."
},
{
"code": null,
"e": 657,
"s": 332,
"text": "Convolutional neural networks (CNN) are the architecture behind computer vision applications. In this post, you will learn about the foundations of CNNs and computer vision such as the convolution operation, padding, strided convolutions and pooling layers. Then, we will use TensorFlow to build a CNN for image recognition."
},
{
"code": null,
"e": 780,
"s": 657,
"text": "For hands-on video tutorials on machine learning, deep learning, and artificial intelligence, checkout my YouTube channel."
},
{
"code": null,
"e": 887,
"s": 780,
"text": "The convolution operation is the building block of a convolutional neural network as the name suggests it."
},
{
"code": null,
"e": 1035,
"s": 887,
"text": "Now, in the field of computer vision, an image can be expressed as a matrix of RGB values. This concept was actually introduced in an earlier post."
},
{
"code": null,
"e": 1105,
"s": 1035,
"text": "To complete the convolution operation, we need an image and a filter."
},
{
"code": null,
"e": 1175,
"s": 1105,
"text": "Therefore, let’s consider the 6x6 matrix below as a part of an image:"
},
{
"code": null,
"e": 1220,
"s": 1175,
"text": "And the filter will be the following matrix:"
},
{
"code": null,
"e": 1434,
"s": 1220,
"text": "Then, the convolution involves superimposing the filter onto the image matrix, adding the product of the values from the filter and and the values from the image matrix, which will generate a 4x4 convoluted layer."
},
{
"code": null,
"e": 1529,
"s": 1434,
"text": "This is very hard to put in words, but here is a nice animation that explains the convolution:"
},
{
"code": null,
"e": 1654,
"s": 1529,
"text": "Performing this on the image matrix above and using the filter defined above, you should get the following resulting matrix:"
},
{
"code": null,
"e": 1693,
"s": 1654,
"text": "How do you interpret the output layer?"
},
{
"code": null,
"e": 1875,
"s": 1693,
"text": "Well, considering that each value is indicative of color, or how dark a pixel is (positive value means light, negative value means dark), then you can interpret the output layer as:"
},
{
"code": null,
"e": 1974,
"s": 1875,
"text": "Therefore, it seems that this particular filter is responsible to detect vertical edges in images!"
},
{
"code": null,
"e": 2103,
"s": 1974,
"text": "This is a natural question, as you might realize that there is an infinite number of possible filters you can apply to an image."
},
{
"code": null,
"e": 2419,
"s": 2103,
"text": "It turns out that the exact values in your filter matrix can be trainable parameters based on the model’s objective. Therefore, you can either choose a filter that has worked for your specific application, or you can use backpropagation to determine the best values for your filter that will yield the best outcome."
},
{
"code": null,
"e": 2605,
"s": 2419,
"text": "Previously, we have seen that a 3x3 filter convoluted with a 6x6 image, will result in 4x4 matrix. This is because there are 4x4 possible positions for the filter to fit in a 6x6 image."
},
{
"code": null,
"e": 2914,
"s": 2605,
"text": "Therefore, after each convolution step, the image shrinks, meaning that only a finite number of convolution can be performed until the image cannot be shrunken anymore. Furthermore, pixels situated in the corner of the image are only used once, and this results in loss of information for the neural network."
},
{
"code": null,
"e": 3052,
"s": 2914,
"text": "In order to solve both problems stated above, padding is used. Padding consists in adding a border around the input image as shown below:"
},
{
"code": null,
"e": 3308,
"s": 3052,
"text": "As you can see, the added border is usually filled with zeros. Now, the corner pixel of the image will be used many times to calculate the output, effectively preventing loss of information. Also, it allows us to keep the input matrix shape in the output."
},
{
"code": null,
"e": 3445,
"s": 3308,
"text": "Considering our 6x6 input image, if we add a padding of 1, we get a 8x8 matrix. Applying a 3x3 filter, this will result in a 6x6 output."
},
{
"code": null,
"e": 3511,
"s": 3445,
"text": "A simple equation can help us figure out the shape of the output:"
},
{
"code": null,
"e": 3534,
"s": 3511,
"text": "To reiterate, we have:"
},
{
"code": null,
"e": 3544,
"s": 3534,
"text": "6x6 input"
},
{
"code": null,
"e": 3557,
"s": 3544,
"text": "padding of 1"
},
{
"code": null,
"e": 3568,
"s": 3557,
"text": "3x3 filter"
},
{
"code": null,
"e": 3687,
"s": 3568,
"text": "Thus, the output shape will be: 6+2(1)-3+1 = 6. Therefore, the output will be a 6x6 matrix, just like the input image!"
},
{
"code": null,
"e": 3860,
"s": 3687,
"text": "Padding is not always required. However, when padding is used, it is usually for the output to have the same size as the input image. This yields two types of convolutions."
},
{
"code": null,
"e": 4127,
"s": 3860,
"text": "When no padding is applied, this is called a “valid convolution”. Otherwise, it is termed “same convolution”. To determine the padding size required to keep the dimensions of the input image, simply equate the formula above to n. After solving for p, you should get:"
},
{
"code": null,
"e": 4298,
"s": 4127,
"text": "You might have noticed that f should be odd in order for the padding to be a whole number. Hence, it is a convention in the field of computer visions to have odd filters."
},
{
"code": null,
"e": 4435,
"s": 4298,
"text": "Previously, we have seen a convolution with a stride of 1. This means that the filter was moving horizontally and vertically by 1 pixel."
},
{
"code": null,
"e": 4536,
"s": 4435,
"text": "A strided convolution is when the stride is greater than 1. In the animation below, the stride is 2:"
},
{
"code": null,
"e": 4633,
"s": 4536,
"text": "Now, taking into account the stride, the formula to calculate the shape of the output matrix is:"
},
{
"code": null,
"e": 4745,
"s": 4633,
"text": "As a convention, if the formula above does not yield a whole number, then we round down to the nearest integer."
},
{
"code": null,
"e": 4905,
"s": 4745,
"text": "Pooling layers are another way to reduce the size of the image interpretation in order to speed up computation, and it makes the detected features more robust."
},
{
"code": null,
"e": 4982,
"s": 4905,
"text": "Pooling is best explained with an image. Below is an example of max pooling:"
},
{
"code": null,
"e": 5180,
"s": 4982,
"text": "As you can see, we chose a 2x2 filter with a stride of 2. This is equivalent to dividing the input into 4 identical squares, we then take the maximum value of each square, and use it in the output."
},
{
"code": null,
"e": 5257,
"s": 5180,
"text": "Average pooling can also be performed, but it less popular than max pooling."
},
{
"code": null,
"e": 5373,
"s": 5257,
"text": "You can think of pooling as a way to prevent overfitting, since we are removing some features from the input image."
},
{
"code": null,
"e": 5505,
"s": 5373,
"text": "We now have a strong foundational knowledge of convolutional neural networks. However, why do deep learning practitioners use them?"
},
{
"code": null,
"e": 5621,
"s": 5505,
"text": "Unlike fully connected layers, convolutional layers have a much smaller set of parameters to learn. This is due to:"
},
{
"code": null,
"e": 5639,
"s": 5621,
"text": "parameter sharing"
},
{
"code": null,
"e": 5662,
"s": 5639,
"text": "sparsity of connection"
},
{
"code": null,
"e": 5919,
"s": 5662,
"text": "Parameter sharing refers to the fact that one feature detector, such as vertical edges detector, will be useful in many parts of the image. Then, the sparsity of connections refers to the fact that only a few features are related to a certain output value."
},
{
"code": null,
"e": 6063,
"s": 5919,
"text": "Considering the above example of max pooling, the top left value for the output depends solely on the top left 2x2 square from the input image."
},
{
"code": null,
"e": 6213,
"s": 6063,
"text": "Therefore, we can train on smaller datasets and greatly reduce the number of parameters to learn, making CNNs a great tool for computer vision tasks."
},
{
"code": null,
"e": 6349,
"s": 6213,
"text": "Enough with the theory, let’s code a CNN for hand signs recognition. We revisit a previous project to see if a CNN will perform better."
},
{
"code": null,
"e": 6397,
"s": 6349,
"text": "As always, the full notebook is available here."
},
{
"code": null,
"e": 6492,
"s": 6397,
"text": "After importing the required libraries and assets, we load the data and preprocess the images:"
},
{
"code": null,
"e": 6554,
"s": 6492,
"text": "Then, we create placeholders for the features and the target:"
},
{
"code": null,
"e": 6617,
"s": 6554,
"text": "We then initialize our parameters using Xavier initialization:"
},
{
"code": null,
"e": 6807,
"s": 6617,
"text": "Now, we define the forward propagation step, which is really the architecture of our CNN. We will use a simply 3-layer network with 2 convolutional layers and a final fully-connected layer:"
},
{
"code": null,
"e": 6865,
"s": 6807,
"text": "Finally, we define a function that will compute the cost:"
},
{
"code": null,
"e": 6986,
"s": 6865,
"text": "Now, we combine all the functions above into a single CNN network. We will use mini-batch gradient descent for training:"
},
{
"code": null,
"e": 7044,
"s": 6986,
"text": "Great! Now, we can run our model and see how it performs:"
},
{
"code": null,
"e": 7103,
"s": 7044,
"text": "_, _, parameters = model(X_train, Y_train, X_test, Y_test)"
},
{
"code": null,
"e": 7300,
"s": 7103,
"text": "In my case, I trained the CNN on a laptop using only CPU, and I got a pretty bad result. If you train the CNN on a desktop with a better CPU and GPU, you will surely get better results than I did."
},
{
"code": null,
"e": 7517,
"s": 7300,
"text": "Congratulations! You now have a very good knowledge about CNNs and the field of computer vision. Although there is much more to learn, the more advanced techniques use the concepts introduced here as building blocks."
}
] |
C++ Program for Recursive Bubble Sort? | In this section we will see another approach of famous bubble sort technique. We have used bubble sort in iterative manner. But here we will see recursive approach of the bubble sort. The recursive bubble sort algorithm is look like this.
begin
if n = 1, return
for i in range 1 to n-2, do
if arr[i] > arr[i+1], then
exchange arr[i] and arr[i+1]
end if
done
bubbleRec(arr, n-1)
end
Live Demo
#include<iostream>
using namespace std;
void recBubble(int arr[], int n){
if (n == 1)
return;
for (int i=0; i<n-1; i++) //for each pass p
if (arr[i] > arr[i+1]) //if the current element is greater than next one
swap(arr[i], arr[i+1]); //swap elements
recBubble(arr, n-1);
}
main() {
int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};
int n = sizeof(data)/sizeof(data[0]);
cout << "Sorted Sequence ";
recBubble(data, n);
for(int i = 0; i <n;i++){
cout << data[i] << " ";
}
}
Sorted Sequence 13 20 32 35 40 54 74 98 98 154 | [
{
"code": null,
"e": 1301,
"s": 1062,
"text": "In this section we will see another approach of famous bubble sort technique. We have used bubble sort in iterative manner. But here we will see recursive approach of the bubble sort. The recursive bubble sort algorithm is look like this."
},
{
"code": null,
"e": 1477,
"s": 1301,
"text": "begin\n if n = 1, return\n for i in range 1 to n-2, do\n if arr[i] > arr[i+1], then\n exchange arr[i] and arr[i+1]\n end if\n done\n bubbleRec(arr, n-1)\nend"
},
{
"code": null,
"e": 1488,
"s": 1477,
"text": " Live Demo"
},
{
"code": null,
"e": 2015,
"s": 1488,
"text": "#include<iostream>\nusing namespace std;\nvoid recBubble(int arr[], int n){\n if (n == 1)\n return;\n for (int i=0; i<n-1; i++) //for each pass p\n if (arr[i] > arr[i+1]) //if the current element is greater than next one\n swap(arr[i], arr[i+1]); //swap elements\n recBubble(arr, n-1);\n}\nmain() {\n int data[] = {54, 74, 98, 154, 98, 32, 20, 13, 35, 40};\n int n = sizeof(data)/sizeof(data[0]);\n cout << \"Sorted Sequence \";\n recBubble(data, n);\n for(int i = 0; i <n;i++){\n cout << data[i] << \" \";\n }\n}"
},
{
"code": null,
"e": 2062,
"s": 2015,
"text": "Sorted Sequence 13 20 32 35 40 54 74 98 98 154"
}
] |
Explaining DBSCAN Clustering. Using DBSCAN to identify employee... | by Kamil Mysiak | Towards Data Science | Density-based spatial clustering of applications with noise (DBSCAN) is an unsupervised clustering ML algorithm. Unsupervised in the sense that it does not use pre-labeled targets to cluster the data points. Clustering in the sense that it attempts to group similar data points into artificial groups or clusters. It is an alternative to popular clustering algorithms such as KMeans and hierarchical clustering.
In our example, we will be examining a human resources dataset consisting of 15,000 individual employees. The dataset contains employee job characteristics such as job satisfaction, performance score, workload, years of tenure, accidents, number of promotions.
In my previous article, we examined the KMeans clustering algorithm which I strongly suggest you read (LINK). You will be able to orient yourself to how KMeans clusters the data.
KMeans is especially vulnerable to outliers. As the algorithm iterates through centroids, outliers have a significant impact on the way the centroids moves before reaching stability and convergence. Furthermore, KMeans has problems accurately clustering data where the clusters are of different sizes and densities. K-Means can only apply spherical clusters and its accuracy will suffer if the data is not spherical. Last but not least, KMeans requires us to first select the number of clusters we wish to find. Below is an example of how KMeans and DBSCAN would individually cluster the same dataset.
On the other hand, DBSCAN does not require us to specify the number of clusters, avoids outliers, and works quite well with arbitrarily shaped and sized clusters. It does not have centroids, the clusters are formed by a process of linking neighbor points together.
First, let’s define Epsilon and Minimum Points, two required parameters when applying the DBSCAN algorithm, and some additional terminology.
Epsilon (ɛ): Max radius of the neighborhood. Data points will be valid neighbors if their mutual distance is less than or equal to the specified epsilon. In other words, it is the distance that DBSCAN uses to determine if two points are similar and belong together. A larger epsilon will produce broader clusters (encompassing more data points) and a smaller epsilon will build smaller clusters. In general, we prefer smaller values because we only want a small fraction of data points within the epsilon distance from each other. Too small and you’ll begin to split valid clusters into smaller and smaller clusters. Too big and you’ll aggregate valid clusters into 2–3 massive clusters with little business insights.Minimum Points (minPts): The minimum number of data points within the radius of a neighborhood (ie. epsilon) for the neighborhood to be considered a cluster. Keep in mind that the initial point is included in the minPts. A low minPts help the algorithm build more clusters with more noise or outliers. A higher minPts will ensure more robust clusters but if it’s too large smaller clusters will be incorporated into larger clusters.
Epsilon (ɛ): Max radius of the neighborhood. Data points will be valid neighbors if their mutual distance is less than or equal to the specified epsilon. In other words, it is the distance that DBSCAN uses to determine if two points are similar and belong together. A larger epsilon will produce broader clusters (encompassing more data points) and a smaller epsilon will build smaller clusters. In general, we prefer smaller values because we only want a small fraction of data points within the epsilon distance from each other. Too small and you’ll begin to split valid clusters into smaller and smaller clusters. Too big and you’ll aggregate valid clusters into 2–3 massive clusters with little business insights.
Minimum Points (minPts): The minimum number of data points within the radius of a neighborhood (ie. epsilon) for the neighborhood to be considered a cluster. Keep in mind that the initial point is included in the minPts. A low minPts help the algorithm build more clusters with more noise or outliers. A higher minPts will ensure more robust clusters but if it’s too large smaller clusters will be incorporated into larger clusters.
If “minimum points” = 4, any 4 or more points within the epsilon distance away from each other will be considered a cluster.
Core Points: Core data points have at least minPts number of data points within their epsilon distance.
I had always believed DBSCAN needed a third parameter named “core_min” which would determine the minimum number of core points before a cluster of neighborhood points can be considered a valid cluster.
Border Points: Border data points are on the outskirts as they are in the neighborhood (ie. w/in epsilon distance of core point) but have less than the required minPts.
Outlier Points: These points are not part of a neighborhood (ie. more than epsilon distance) and are not border points. These are points located in low-density areas.
First, a random point is selected which has at least minPts within its epsilon radius. Then each point that is within the neighborhood of the core point is evaluated to determine if it has the minPts nearby within the epsilon distance (minPts includes the point itself). If the point does meet the minPts criteria it becomes another core point and the cluster expands. If a point does not meet the minPts criteria it becomes a border point. As the process continues a chain begins to develop as core point “a” is a neighbor of “b” which is a neighbor or “c” and so on. The cluster is complete as it becomes surrounded by border points because there are no more points within the epsilon distance. A new random point is selected and the process repeats to identify the next cluster.
One method used to estimate the optimal epsilon value is to use nearest neighbor distances. If you recall, nearest neighbors is a supervised ML clustering algorithm which clusters new data points based on their distance from other “known” data points. We train a KNN model on labeled training data to determine which data points belong to which cluster. Then when we apply the model to new data, the algorithm determines which cluster the new data point belongs to based on the distance to trained clusters. We do have to determine the “k” parameter a-priori which specifies how many closest or nearest neighboring points the model will consider before assigning the new data point to a cluster.
To determine the best epsilon value, we calculate the average distance between each point and its closest/nearest neighbors. We then plot a k-distance and choose the epsilon value at the “elbow” of the graph. On the y-axis, we plot the average distances and the x-axis all the data points in your dataset.
if epsilon is chosen much too small, a large part of the data will not be clustered, whereas a high epsilon value clusters will merge and the majority of data points will be in the same cluster. In general, small values of epsilon are preferable, and as a rule of thumb, only a small fraction of points should be within this distance of each other.
Typically, we should set minPts to be greater or equal to the number of dimensionality of our dataset. That said, we often see folks multiplying the number of features X 2 to determine their minPts value.
Much like the “Elbow Method” used to determine the optimal epsilon value the minPts heuristic isn’t correct 100% of the time.
Silhouette Method: This technique measures the separability between clusters. First, an average distance is found between each point and all other points in a cluster. Then it measures the distance between each point and each point in other clusters. We subtract the two average measures and divide by whichever average is larger.
We ultimately want a high (ie. closest to 1) score which would indicate that there is a small intra-cluster average distance (tight clusters) and a large inter-cluster average distance (clusters well separated).
Visual Cluster Interpretation: Once you have obtained your clusters it is very important to interpret each cluster. This is typically done by merging the original dataset with the clusters and visualizing each cluster. The more clear and distinct each cluster is the better. We will review this process below.
Does not require us to pre-determine the number of clusters like KMeans
Handles outliers like a champ
Can separate high density data into small clusters
Can cluster non-linear relationships (finds arbitrary shapes)
Struggles to identify clusters within data of varying density
Can suffer with high dimensional data
Very sensitive to epsilon and minimum points parameters
import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport plotly.offline as pyopyo.init_notebook_mode()import plotly.graph_objs as gofrom plotly import toolsfrom plotly.subplots import make_subplotsimport plotly.offline as pyimport plotly.express as pxfrom sklearn.cluster import DBSCANfrom sklearn.neighbors import NearestNeighborsfrom sklearn.metrics import silhouette_scorefrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAplt.style.use('fivethirtyeight')from warnings import filterwarningsfilterwarnings('ignore')with open('HR_data.csv') as f: df = pd.read_csv(f, usecols=['satisfaction_level', 'last_evaluation', 'number_project', 'average_montly_hours', 'time_spend_company', 'Work_accident', 'promotion_last_5years'])f.close()
Since the features in our dataset are not on the same scale we need to standardize the entire dataset. In other words, each feature in our dataset has unique magnitudes and range for their data. A one-point increase in Satisfaction_level does not equal a one-point increase in Last_evaluation and vice versa. Since DBSCAN utilizes the distance (Euclidean) between points to determine similarity, unscaled data creates a problem. If one feature has higher variability in its data the distance calculation will be more affected by that feature. By scaling our features we align all the features to a mean of zero and a standard deviation of one.
scaler = StandardScaler()scaler.fit(df)X_scale = scaler.transform(df)df_scale = pd.DataFrame(X_scale, columns=df.columns)df_scale.head()
Some algorithms such as KMeans find it difficult to accurately construct clusters if the dataset has too many features (ie. high dimensionality). High dimensionality does not necessarily mean hundreds or even thousands of features. Even 10 features can create accuracy issues.
The theory behind feature or dimensionality reduction is to convert the original feature set into fewer artificially derived features which still maintain most of the information encompassed in the original features.
One of the most prevalent feature reduction techniques is Principal Component Analysis or PCA. PCA reduces the original dataset into a specified number of features which PCA calls principal components. We have to select the number of principal components we wish to see. We discuss feature reduction in my article on KMeans clustering and I strongly advise you to take a look (LINK).
First, we need to determine the appropriate number of principal components. It would seem that 3 principal components account for roughly 75% of the variance.
pca = PCA(n_components=7)pca.fit(df_scale)variance = pca.explained_variance_ratio_ var=np.cumsum(np.round(variance, 3)*100)plt.figure(figsize=(12,6))plt.ylabel('% Variance Explained')plt.xlabel('# of Features')plt.title('PCA Analysis')plt.ylim(0,100.5)plt.plot(var)
Now that we know the number of principal components needed to maintain a specific percentage of variance let’s apply a 3-component PCA to our original dataset. Notice that the first principal component accounts for 26% of the variance from the original dataset. We will utilize the “pca_df” data frame for the remainder of this article.
pca = PCA(n_components=3)pca.fit(df_scale)pca_scale = pca.transform(df_scale)pca_df = pd.DataFrame(pca_scale, columns=['pc1', 'pc2', 'pc3'])print(pca.explained_variance_ratio_)
Plotting our data in a 3D space we can see some potential problems for DBSCAN. If you recall one of the main cons for DBSCAN is its inability to accurately cluster data of varying density and from the plot below we can see two separate clusters of very different density. Upon applying the DBSCAN algorithm we might be able to find clusters in the lower cluster of data points but many of the data points in the upper cluster might be classified as outliers/noise. This is of course all dependent on our selection of epsilon and minimum point values.
Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))trace = go.Scatter3d(x=pca_df.iloc[:,0], y=pca_df.iloc[:,1], z=pca_df.iloc[:,2], mode='markers',marker=dict(colorscale='Greys', opacity=0.3, size = 10, ))layout = go.Layout(margin=dict(l=0,r=0),scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.show()
Approach #1
Before we apply the clustering algorithm we have to determine the appropriate epsilon level using the “Elbow Method” we discussed above. It would seem the optimal epsilon value is around 0.2. Finally, since we have 3 principal components to our data we’ll set our minimum points criteria to 6.
plt.figure(figsize=(10,5))nn = NearestNeighbors(n_neighbors=5).fit(pca_df)distances, idx = nn.kneighbors(pca_df)distances = np.sort(distances, axis=0)distances = distances[:,1]plt.plot(distances)plt.show()
Setting the epsilon to 0.2 and min_samples to 6 has resulted in 53 clusters, a Silhouette score of -0.521, and over 1500 data points which are considered outliers/noise. There may be some research areas where 53 clusters might be considered informative but we have a dataset of 15,000 employees. From a business perspective, we need a manageable number of clusters (ie 3–5) which can be used to better understand the workplace. Also, a silhouette score of -0.521 would indicate data points are incorrectly clustered.
Looking at the 3D plot below we can see one cluster encompassing the majority of the data points. There is a smaller but significant cluster which emerged but that leaves 52 remaining clusters of much smaller size. From a business perspective these clusters are not very informative as most employees belong to just two clusters. The organization would want to see a few large clusters in order to be certain of their validity but also be able to engage in some organization initiatives against the clustered employees (ie. increased training, compensation changes, etc.).
db = DBSCAN(eps=0.2, min_samples=6).fit(pca_df)labels = db.labels_# Number of clusters in labels, ignoring noise if present.n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)print('Estimated number of clusters: %d' % n_clusters_)print('Estimated number of noise points: %d' % n_noise_)print("Silhouette Coefficient: %0.3f" % metrics.silhouette_score(pca_df, labels))
Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))labels = db.labels_trace = go.Scatter3d(x=pca_df.iloc[:,0], y=pca_df.iloc[:,1], z=pca_df.iloc[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'gray',width = 5)))layout = go.Layout(scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.update_layout(title='DBSCAN clusters (53) Derived from PCA', font=dict(size=12,))fig.show()
Approach #2
Instead of using the “Elbow Method” and the minimum value heuristic let’s take an iterative approach to fine-tuning our DBSCAN model. We are going to iterate through a range of epsilon and minimum point values as we apply the DBSCAN algorithm to our data.
In our example, we are going to iterative through epsilon values ranging from 0.5 to 1.5 at 0.1 intervals and minimum point values ranging from 2–7. The for-loop will run the DBSCAN algorithm using the set of values and produce the number of clusters and silhouette score for each iteration. Keep in mind you will need to adjust your parameters according to your data. You might run this code on one set of parameters and find that the best silhouette score produced is 0.30. You might want to increase the epsilon value in order to encompass more points into a cluster.
pca_eps_values = np.arange(0.2,1.5,0.1) pca_min_samples = np.arange(2,5) pca_dbscan_params = list(product(pca_eps_values, pca_min_samples))pca_no_of_clusters = []pca_sil_score = []pca_epsvalues = []pca_min_samp = []for p in pca_dbscan_params: pca_dbscan_cluster = DBSCAN(eps=p[0], min_samples=p[1]).fit(pca_df) pca_epsvalues.append(p[0]) pca_min_samp.append(p[1])pca_no_of_clusters.append(len(np.unique(pca_dbscan_cluster.labels_))) pca_sil_score.append(silhouette_score(pca_df, pca_dbscan_cluster.labels_))pca_eps_min = list(zip(pca_no_of_clusters, pca_sil_score, pca_epsvalues, pca_min_samp))pca_eps_min_df = pd.DataFrame(pca_eps_min, columns=['no_of_clusters', 'silhouette_score', 'epsilon_values', 'minimum_points'])pca_ep_min_df
We can see that iterating through our epsilon and minimum values we had obtained a wide range of number of clusters and silhouette scores. Epsilon scores between 0.9 and 1.1 began to produce a manageable number of clusters. Increasing epsilon to 1.2 and above creates too few clusters to make much business sense. Furthermore, some of those clusters may be just noise (ie. -1) which we’ll get to in a bit.
It is also important to understand that increasing epsilon decreases the number of clusters but each cluster will also begin to encompass more outlier/noise data points. There is a certain level of diminishing returns.
For the sake of simplicity let’s choose 7 clusters and examine what the cluster distribution looks like. (epsilon: 1.0 & minPts: 4).
It is also important to point out a frequent error you will surely encounter running this string of code. Sometimes when you have set your parameters (ie. eps_values and min_samples) too broad the for-loop will eventually come to a combination of eps_values and min_samples which only produces one cluster. However, the Silhouette_score function requires at least two clusters to be defined. You will need to restrict your parameters to avoid this issue.
In our example above, if we had set our epsilon parameter range from 0.2 to 2.5 that would most likely result in one cluster and ultimately elicit the error.
You might be asking yourself “weren’t we supposed to obtain 7 clusters?”. The answer is “Yes” and if we look at the unique labels/clusters we see 7 labels for each data point. Per Sklearn documentation, a label of “-1” equates to a “noisy” data point it hasn’t been clustered into any of the 6 high-density clusters. We naturally don’t want to consider any labels of “-1” as a cluster, therefore, they are removed from the calculation.
db = DBSCAN(eps=1.0, min_samples=4).fit(pca_df)labels = db.labels_# Number of clusters in labels, ignoring noise if present.n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)print('Estimated number of clusters: %d' % n_clusters_)print('Estimated number of noise points: %d' % n_noise_)print("Silhouette Coefficient: %0.3f" % silhouette_score(pca_df, labels))
set(labels)
Looking at the 3D plot of the six DBSCAN derived clusters it seems the less dense cluster towards the top of the plot did not pose much of a problem for DBSCAN despite it being less dense. If you recall, DBSCAN has a difficult time properly clustering data of various density. The distance between the top cluster and the much larger bottom cluster was most likely larger than our epsilon value of 1.0.
That said, the dataset contains additional high-density clusters but our epsilon and minimum values are too large. The bottom cluster contains at least two high-density clusters, however, due to the strong density of the bottom cluster lowering the epsilon and minimum point values would simply create many smaller clusters. Once again this is the major downside of DBSCAN. I always believed DBSCAN needed a 3rd parameter, “min_core”, which would determine the minimum number of core points before a cluster can be considered a valid cluster.
Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))# model.labels_ is nothing but the predicted clusters i.e y_clusterslabels = db.labels_trace = go.Scatter3d(x=pca_df.iloc[:,0], y=pca_df.iloc[:,1], z=pca_df.iloc[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'gray',width = 5)))layout = go.Layout(scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.update_layout(title="'DBSCAN Clusters (6) Derived from PCA'", font=dict(size=12,))fig.show()
Before we get ahead of ourselves let’s quickly get a count of the number of employees in each cluster. Well it seems cluster 0 contains most of the data points which isn’t very informative. In fact, if we had ran the algorithm using epsilon values of 0.5 and minimum points of 5 which would have produced 63 clusters, cluster 0 still would have contained 99% of the employee population.
np.unique(labels, return_counts=True)
DBSCAN, a density clustering algorithm which is often used on non-linear or non-spherical datasets. Epsilon and Minimum Points are two required parameters. Epsilon is the radius within nearby data points that need to be in to be considered ‘similar’ enough to begin a cluster. Finally, Minimum Points is the minimum number of data points that need to be inside the radius (ie. epsilon) before they can be considered a cluster.
In our example, we attempted to cluster a dataset of 15,000 employees based on their job characteristics. We first standardized the dataset to scale the features. Next, we applied PCA in order to reduce the number of dimensions/features to 3 principal components. Using the “Elbow Method” we estimated an epsilon value of 0.2 and a minimum point value of 6. Using these parameters we were able to obtain 53 clusters, 1,500 outliers, and a silhouette score of -0.52. Needless to say, the results were not very promising.
Next, we attempted an iterative approach to fine-tuning the epsilon and minimum points parameters. We had decided upon an epsilon value of 1.0 and a minimum points value of 4. The algorithm returned 6 valid clusters (one -1 cluster), only 7 outliers, and a respectable silhouette score of 0.46. However, upon plotting the derived clusters it was discovered the first cluster contained 99% of the employees. Once again from a business perspective, we would want our clusters to be more equally distributed to provide us with good insights about our employees.
It would seem DBSCAN is not the optimal clustering algorithm for this particular dataset.
This same dataset was clustered using KMeans and produced much more equal and defined clusters (LINK). | [
{
"code": null,
"e": 584,
"s": 172,
"text": "Density-based spatial clustering of applications with noise (DBSCAN) is an unsupervised clustering ML algorithm. Unsupervised in the sense that it does not use pre-labeled targets to cluster the data points. Clustering in the sense that it attempts to group similar data points into artificial groups or clusters. It is an alternative to popular clustering algorithms such as KMeans and hierarchical clustering."
},
{
"code": null,
"e": 845,
"s": 584,
"text": "In our example, we will be examining a human resources dataset consisting of 15,000 individual employees. The dataset contains employee job characteristics such as job satisfaction, performance score, workload, years of tenure, accidents, number of promotions."
},
{
"code": null,
"e": 1024,
"s": 845,
"text": "In my previous article, we examined the KMeans clustering algorithm which I strongly suggest you read (LINK). You will be able to orient yourself to how KMeans clusters the data."
},
{
"code": null,
"e": 1626,
"s": 1024,
"text": "KMeans is especially vulnerable to outliers. As the algorithm iterates through centroids, outliers have a significant impact on the way the centroids moves before reaching stability and convergence. Furthermore, KMeans has problems accurately clustering data where the clusters are of different sizes and densities. K-Means can only apply spherical clusters and its accuracy will suffer if the data is not spherical. Last but not least, KMeans requires us to first select the number of clusters we wish to find. Below is an example of how KMeans and DBSCAN would individually cluster the same dataset."
},
{
"code": null,
"e": 1891,
"s": 1626,
"text": "On the other hand, DBSCAN does not require us to specify the number of clusters, avoids outliers, and works quite well with arbitrarily shaped and sized clusters. It does not have centroids, the clusters are formed by a process of linking neighbor points together."
},
{
"code": null,
"e": 2032,
"s": 1891,
"text": "First, let’s define Epsilon and Minimum Points, two required parameters when applying the DBSCAN algorithm, and some additional terminology."
},
{
"code": null,
"e": 3182,
"s": 2032,
"text": "Epsilon (ɛ): Max radius of the neighborhood. Data points will be valid neighbors if their mutual distance is less than or equal to the specified epsilon. In other words, it is the distance that DBSCAN uses to determine if two points are similar and belong together. A larger epsilon will produce broader clusters (encompassing more data points) and a smaller epsilon will build smaller clusters. In general, we prefer smaller values because we only want a small fraction of data points within the epsilon distance from each other. Too small and you’ll begin to split valid clusters into smaller and smaller clusters. Too big and you’ll aggregate valid clusters into 2–3 massive clusters with little business insights.Minimum Points (minPts): The minimum number of data points within the radius of a neighborhood (ie. epsilon) for the neighborhood to be considered a cluster. Keep in mind that the initial point is included in the minPts. A low minPts help the algorithm build more clusters with more noise or outliers. A higher minPts will ensure more robust clusters but if it’s too large smaller clusters will be incorporated into larger clusters."
},
{
"code": null,
"e": 3900,
"s": 3182,
"text": "Epsilon (ɛ): Max radius of the neighborhood. Data points will be valid neighbors if their mutual distance is less than or equal to the specified epsilon. In other words, it is the distance that DBSCAN uses to determine if two points are similar and belong together. A larger epsilon will produce broader clusters (encompassing more data points) and a smaller epsilon will build smaller clusters. In general, we prefer smaller values because we only want a small fraction of data points within the epsilon distance from each other. Too small and you’ll begin to split valid clusters into smaller and smaller clusters. Too big and you’ll aggregate valid clusters into 2–3 massive clusters with little business insights."
},
{
"code": null,
"e": 4333,
"s": 3900,
"text": "Minimum Points (minPts): The minimum number of data points within the radius of a neighborhood (ie. epsilon) for the neighborhood to be considered a cluster. Keep in mind that the initial point is included in the minPts. A low minPts help the algorithm build more clusters with more noise or outliers. A higher minPts will ensure more robust clusters but if it’s too large smaller clusters will be incorporated into larger clusters."
},
{
"code": null,
"e": 4458,
"s": 4333,
"text": "If “minimum points” = 4, any 4 or more points within the epsilon distance away from each other will be considered a cluster."
},
{
"code": null,
"e": 4562,
"s": 4458,
"text": "Core Points: Core data points have at least minPts number of data points within their epsilon distance."
},
{
"code": null,
"e": 4764,
"s": 4562,
"text": "I had always believed DBSCAN needed a third parameter named “core_min” which would determine the minimum number of core points before a cluster of neighborhood points can be considered a valid cluster."
},
{
"code": null,
"e": 4933,
"s": 4764,
"text": "Border Points: Border data points are on the outskirts as they are in the neighborhood (ie. w/in epsilon distance of core point) but have less than the required minPts."
},
{
"code": null,
"e": 5100,
"s": 4933,
"text": "Outlier Points: These points are not part of a neighborhood (ie. more than epsilon distance) and are not border points. These are points located in low-density areas."
},
{
"code": null,
"e": 5882,
"s": 5100,
"text": "First, a random point is selected which has at least minPts within its epsilon radius. Then each point that is within the neighborhood of the core point is evaluated to determine if it has the minPts nearby within the epsilon distance (minPts includes the point itself). If the point does meet the minPts criteria it becomes another core point and the cluster expands. If a point does not meet the minPts criteria it becomes a border point. As the process continues a chain begins to develop as core point “a” is a neighbor of “b” which is a neighbor or “c” and so on. The cluster is complete as it becomes surrounded by border points because there are no more points within the epsilon distance. A new random point is selected and the process repeats to identify the next cluster."
},
{
"code": null,
"e": 6578,
"s": 5882,
"text": "One method used to estimate the optimal epsilon value is to use nearest neighbor distances. If you recall, nearest neighbors is a supervised ML clustering algorithm which clusters new data points based on their distance from other “known” data points. We train a KNN model on labeled training data to determine which data points belong to which cluster. Then when we apply the model to new data, the algorithm determines which cluster the new data point belongs to based on the distance to trained clusters. We do have to determine the “k” parameter a-priori which specifies how many closest or nearest neighboring points the model will consider before assigning the new data point to a cluster."
},
{
"code": null,
"e": 6884,
"s": 6578,
"text": "To determine the best epsilon value, we calculate the average distance between each point and its closest/nearest neighbors. We then plot a k-distance and choose the epsilon value at the “elbow” of the graph. On the y-axis, we plot the average distances and the x-axis all the data points in your dataset."
},
{
"code": null,
"e": 7233,
"s": 6884,
"text": "if epsilon is chosen much too small, a large part of the data will not be clustered, whereas a high epsilon value clusters will merge and the majority of data points will be in the same cluster. In general, small values of epsilon are preferable, and as a rule of thumb, only a small fraction of points should be within this distance of each other."
},
{
"code": null,
"e": 7438,
"s": 7233,
"text": "Typically, we should set minPts to be greater or equal to the number of dimensionality of our dataset. That said, we often see folks multiplying the number of features X 2 to determine their minPts value."
},
{
"code": null,
"e": 7564,
"s": 7438,
"text": "Much like the “Elbow Method” used to determine the optimal epsilon value the minPts heuristic isn’t correct 100% of the time."
},
{
"code": null,
"e": 7895,
"s": 7564,
"text": "Silhouette Method: This technique measures the separability between clusters. First, an average distance is found between each point and all other points in a cluster. Then it measures the distance between each point and each point in other clusters. We subtract the two average measures and divide by whichever average is larger."
},
{
"code": null,
"e": 8107,
"s": 7895,
"text": "We ultimately want a high (ie. closest to 1) score which would indicate that there is a small intra-cluster average distance (tight clusters) and a large inter-cluster average distance (clusters well separated)."
},
{
"code": null,
"e": 8417,
"s": 8107,
"text": "Visual Cluster Interpretation: Once you have obtained your clusters it is very important to interpret each cluster. This is typically done by merging the original dataset with the clusters and visualizing each cluster. The more clear and distinct each cluster is the better. We will review this process below."
},
{
"code": null,
"e": 8489,
"s": 8417,
"text": "Does not require us to pre-determine the number of clusters like KMeans"
},
{
"code": null,
"e": 8519,
"s": 8489,
"text": "Handles outliers like a champ"
},
{
"code": null,
"e": 8570,
"s": 8519,
"text": "Can separate high density data into small clusters"
},
{
"code": null,
"e": 8632,
"s": 8570,
"text": "Can cluster non-linear relationships (finds arbitrary shapes)"
},
{
"code": null,
"e": 8694,
"s": 8632,
"text": "Struggles to identify clusters within data of varying density"
},
{
"code": null,
"e": 8732,
"s": 8694,
"text": "Can suffer with high dimensional data"
},
{
"code": null,
"e": 8788,
"s": 8732,
"text": "Very sensitive to epsilon and minimum points parameters"
},
{
"code": null,
"e": 9611,
"s": 8788,
"text": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport seaborn as snsimport plotly.offline as pyopyo.init_notebook_mode()import plotly.graph_objs as gofrom plotly import toolsfrom plotly.subplots import make_subplotsimport plotly.offline as pyimport plotly.express as pxfrom sklearn.cluster import DBSCANfrom sklearn.neighbors import NearestNeighborsfrom sklearn.metrics import silhouette_scorefrom sklearn.preprocessing import StandardScalerfrom sklearn.decomposition import PCAplt.style.use('fivethirtyeight')from warnings import filterwarningsfilterwarnings('ignore')with open('HR_data.csv') as f: df = pd.read_csv(f, usecols=['satisfaction_level', 'last_evaluation', 'number_project', 'average_montly_hours', 'time_spend_company', 'Work_accident', 'promotion_last_5years'])f.close()"
},
{
"code": null,
"e": 10255,
"s": 9611,
"text": "Since the features in our dataset are not on the same scale we need to standardize the entire dataset. In other words, each feature in our dataset has unique magnitudes and range for their data. A one-point increase in Satisfaction_level does not equal a one-point increase in Last_evaluation and vice versa. Since DBSCAN utilizes the distance (Euclidean) between points to determine similarity, unscaled data creates a problem. If one feature has higher variability in its data the distance calculation will be more affected by that feature. By scaling our features we align all the features to a mean of zero and a standard deviation of one."
},
{
"code": null,
"e": 10392,
"s": 10255,
"text": "scaler = StandardScaler()scaler.fit(df)X_scale = scaler.transform(df)df_scale = pd.DataFrame(X_scale, columns=df.columns)df_scale.head()"
},
{
"code": null,
"e": 10669,
"s": 10392,
"text": "Some algorithms such as KMeans find it difficult to accurately construct clusters if the dataset has too many features (ie. high dimensionality). High dimensionality does not necessarily mean hundreds or even thousands of features. Even 10 features can create accuracy issues."
},
{
"code": null,
"e": 10886,
"s": 10669,
"text": "The theory behind feature or dimensionality reduction is to convert the original feature set into fewer artificially derived features which still maintain most of the information encompassed in the original features."
},
{
"code": null,
"e": 11270,
"s": 10886,
"text": "One of the most prevalent feature reduction techniques is Principal Component Analysis or PCA. PCA reduces the original dataset into a specified number of features which PCA calls principal components. We have to select the number of principal components we wish to see. We discuss feature reduction in my article on KMeans clustering and I strongly advise you to take a look (LINK)."
},
{
"code": null,
"e": 11429,
"s": 11270,
"text": "First, we need to determine the appropriate number of principal components. It would seem that 3 principal components account for roughly 75% of the variance."
},
{
"code": null,
"e": 11695,
"s": 11429,
"text": "pca = PCA(n_components=7)pca.fit(df_scale)variance = pca.explained_variance_ratio_ var=np.cumsum(np.round(variance, 3)*100)plt.figure(figsize=(12,6))plt.ylabel('% Variance Explained')plt.xlabel('# of Features')plt.title('PCA Analysis')plt.ylim(0,100.5)plt.plot(var)"
},
{
"code": null,
"e": 12032,
"s": 11695,
"text": "Now that we know the number of principal components needed to maintain a specific percentage of variance let’s apply a 3-component PCA to our original dataset. Notice that the first principal component accounts for 26% of the variance from the original dataset. We will utilize the “pca_df” data frame for the remainder of this article."
},
{
"code": null,
"e": 12209,
"s": 12032,
"text": "pca = PCA(n_components=3)pca.fit(df_scale)pca_scale = pca.transform(df_scale)pca_df = pd.DataFrame(pca_scale, columns=['pc1', 'pc2', 'pc3'])print(pca.explained_variance_ratio_)"
},
{
"code": null,
"e": 12760,
"s": 12209,
"text": "Plotting our data in a 3D space we can see some potential problems for DBSCAN. If you recall one of the main cons for DBSCAN is its inability to accurately cluster data of varying density and from the plot below we can see two separate clusters of very different density. Upon applying the DBSCAN algorithm we might be able to find clusters in the lower cluster of data points but many of the data points in the upper cluster might be classified as outliers/noise. This is of course all dependent on our selection of epsilon and minimum point values."
},
{
"code": null,
"e": 13166,
"s": 12760,
"text": "Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))trace = go.Scatter3d(x=pca_df.iloc[:,0], y=pca_df.iloc[:,1], z=pca_df.iloc[:,2], mode='markers',marker=dict(colorscale='Greys', opacity=0.3, size = 10, ))layout = go.Layout(margin=dict(l=0,r=0),scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.show()"
},
{
"code": null,
"e": 13178,
"s": 13166,
"text": "Approach #1"
},
{
"code": null,
"e": 13472,
"s": 13178,
"text": "Before we apply the clustering algorithm we have to determine the appropriate epsilon level using the “Elbow Method” we discussed above. It would seem the optimal epsilon value is around 0.2. Finally, since we have 3 principal components to our data we’ll set our minimum points criteria to 6."
},
{
"code": null,
"e": 13678,
"s": 13472,
"text": "plt.figure(figsize=(10,5))nn = NearestNeighbors(n_neighbors=5).fit(pca_df)distances, idx = nn.kneighbors(pca_df)distances = np.sort(distances, axis=0)distances = distances[:,1]plt.plot(distances)plt.show()"
},
{
"code": null,
"e": 14195,
"s": 13678,
"text": "Setting the epsilon to 0.2 and min_samples to 6 has resulted in 53 clusters, a Silhouette score of -0.521, and over 1500 data points which are considered outliers/noise. There may be some research areas where 53 clusters might be considered informative but we have a dataset of 15,000 employees. From a business perspective, we need a manageable number of clusters (ie 3–5) which can be used to better understand the workplace. Also, a silhouette score of -0.521 would indicate data points are incorrectly clustered."
},
{
"code": null,
"e": 14768,
"s": 14195,
"text": "Looking at the 3D plot below we can see one cluster encompassing the majority of the data points. There is a smaller but significant cluster which emerged but that leaves 52 remaining clusters of much smaller size. From a business perspective these clusters are not very informative as most employees belong to just two clusters. The organization would want to see a few large clusters in order to be certain of their validity but also be able to engage in some organization initiatives against the clustered employees (ie. increased training, compensation changes, etc.)."
},
{
"code": null,
"e": 15177,
"s": 14768,
"text": "db = DBSCAN(eps=0.2, min_samples=6).fit(pca_df)labels = db.labels_# Number of clusters in labels, ignoring noise if present.n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)print('Estimated number of clusters: %d' % n_clusters_)print('Estimated number of noise points: %d' % n_noise_)print(\"Silhouette Coefficient: %0.3f\" % metrics.silhouette_score(pca_df, labels))"
},
{
"code": null,
"e": 15708,
"s": 15177,
"text": "Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))labels = db.labels_trace = go.Scatter3d(x=pca_df.iloc[:,0], y=pca_df.iloc[:,1], z=pca_df.iloc[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'gray',width = 5)))layout = go.Layout(scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.update_layout(title='DBSCAN clusters (53) Derived from PCA', font=dict(size=12,))fig.show()"
},
{
"code": null,
"e": 15720,
"s": 15708,
"text": "Approach #2"
},
{
"code": null,
"e": 15976,
"s": 15720,
"text": "Instead of using the “Elbow Method” and the minimum value heuristic let’s take an iterative approach to fine-tuning our DBSCAN model. We are going to iterate through a range of epsilon and minimum point values as we apply the DBSCAN algorithm to our data."
},
{
"code": null,
"e": 16547,
"s": 15976,
"text": "In our example, we are going to iterative through epsilon values ranging from 0.5 to 1.5 at 0.1 intervals and minimum point values ranging from 2–7. The for-loop will run the DBSCAN algorithm using the set of values and produce the number of clusters and silhouette score for each iteration. Keep in mind you will need to adjust your parameters according to your data. You might run this code on one set of parameters and find that the best silhouette score produced is 0.30. You might want to increase the epsilon value in order to encompass more points into a cluster."
},
{
"code": null,
"e": 17293,
"s": 16547,
"text": "pca_eps_values = np.arange(0.2,1.5,0.1) pca_min_samples = np.arange(2,5) pca_dbscan_params = list(product(pca_eps_values, pca_min_samples))pca_no_of_clusters = []pca_sil_score = []pca_epsvalues = []pca_min_samp = []for p in pca_dbscan_params: pca_dbscan_cluster = DBSCAN(eps=p[0], min_samples=p[1]).fit(pca_df) pca_epsvalues.append(p[0]) pca_min_samp.append(p[1])pca_no_of_clusters.append(len(np.unique(pca_dbscan_cluster.labels_))) pca_sil_score.append(silhouette_score(pca_df, pca_dbscan_cluster.labels_))pca_eps_min = list(zip(pca_no_of_clusters, pca_sil_score, pca_epsvalues, pca_min_samp))pca_eps_min_df = pd.DataFrame(pca_eps_min, columns=['no_of_clusters', 'silhouette_score', 'epsilon_values', 'minimum_points'])pca_ep_min_df"
},
{
"code": null,
"e": 17699,
"s": 17293,
"text": "We can see that iterating through our epsilon and minimum values we had obtained a wide range of number of clusters and silhouette scores. Epsilon scores between 0.9 and 1.1 began to produce a manageable number of clusters. Increasing epsilon to 1.2 and above creates too few clusters to make much business sense. Furthermore, some of those clusters may be just noise (ie. -1) which we’ll get to in a bit."
},
{
"code": null,
"e": 17918,
"s": 17699,
"text": "It is also important to understand that increasing epsilon decreases the number of clusters but each cluster will also begin to encompass more outlier/noise data points. There is a certain level of diminishing returns."
},
{
"code": null,
"e": 18051,
"s": 17918,
"text": "For the sake of simplicity let’s choose 7 clusters and examine what the cluster distribution looks like. (epsilon: 1.0 & minPts: 4)."
},
{
"code": null,
"e": 18506,
"s": 18051,
"text": "It is also important to point out a frequent error you will surely encounter running this string of code. Sometimes when you have set your parameters (ie. eps_values and min_samples) too broad the for-loop will eventually come to a combination of eps_values and min_samples which only produces one cluster. However, the Silhouette_score function requires at least two clusters to be defined. You will need to restrict your parameters to avoid this issue."
},
{
"code": null,
"e": 18664,
"s": 18506,
"text": "In our example above, if we had set our epsilon parameter range from 0.2 to 2.5 that would most likely result in one cluster and ultimately elicit the error."
},
{
"code": null,
"e": 19100,
"s": 18664,
"text": "You might be asking yourself “weren’t we supposed to obtain 7 clusters?”. The answer is “Yes” and if we look at the unique labels/clusters we see 7 labels for each data point. Per Sklearn documentation, a label of “-1” equates to a “noisy” data point it hasn’t been clustered into any of the 6 high-density clusters. We naturally don’t want to consider any labels of “-1” as a cluster, therefore, they are removed from the calculation."
},
{
"code": null,
"e": 19501,
"s": 19100,
"text": "db = DBSCAN(eps=1.0, min_samples=4).fit(pca_df)labels = db.labels_# Number of clusters in labels, ignoring noise if present.n_clusters_ = len(set(labels)) - (1 if -1 in labels else 0)n_noise_ = list(labels).count(-1)print('Estimated number of clusters: %d' % n_clusters_)print('Estimated number of noise points: %d' % n_noise_)print(\"Silhouette Coefficient: %0.3f\" % silhouette_score(pca_df, labels))"
},
{
"code": null,
"e": 19513,
"s": 19501,
"text": "set(labels)"
},
{
"code": null,
"e": 19916,
"s": 19513,
"text": "Looking at the 3D plot of the six DBSCAN derived clusters it seems the less dense cluster towards the top of the plot did not pose much of a problem for DBSCAN despite it being less dense. If you recall, DBSCAN has a difficult time properly clustering data of various density. The distance between the top cluster and the much larger bottom cluster was most likely larger than our epsilon value of 1.0."
},
{
"code": null,
"e": 20459,
"s": 19916,
"text": "That said, the dataset contains additional high-density clusters but our epsilon and minimum values are too large. The bottom cluster contains at least two high-density clusters, however, due to the strong density of the bottom cluster lowering the epsilon and minimum point values would simply create many smaller clusters. Once again this is the major downside of DBSCAN. I always believed DBSCAN needed a 3rd parameter, “min_core”, which would determine the minimum number of core points before a cluster can be considered a valid cluster."
},
{
"code": null,
"e": 21059,
"s": 20459,
"text": "Scene = dict(xaxis = dict(title = 'PC1'),yaxis = dict(title = 'PC2'),zaxis = dict(title = 'PC3'))# model.labels_ is nothing but the predicted clusters i.e y_clusterslabels = db.labels_trace = go.Scatter3d(x=pca_df.iloc[:,0], y=pca_df.iloc[:,1], z=pca_df.iloc[:,2], mode='markers',marker=dict(color = labels, colorscale='Viridis', size = 10, line = dict(color = 'gray',width = 5)))layout = go.Layout(scene = Scene, height = 1000,width = 1000)data = [trace]fig = go.Figure(data = data, layout = layout)fig.update_layout(title=\"'DBSCAN Clusters (6) Derived from PCA'\", font=dict(size=12,))fig.show()"
},
{
"code": null,
"e": 21446,
"s": 21059,
"text": "Before we get ahead of ourselves let’s quickly get a count of the number of employees in each cluster. Well it seems cluster 0 contains most of the data points which isn’t very informative. In fact, if we had ran the algorithm using epsilon values of 0.5 and minimum points of 5 which would have produced 63 clusters, cluster 0 still would have contained 99% of the employee population."
},
{
"code": null,
"e": 21484,
"s": 21446,
"text": "np.unique(labels, return_counts=True)"
},
{
"code": null,
"e": 21911,
"s": 21484,
"text": "DBSCAN, a density clustering algorithm which is often used on non-linear or non-spherical datasets. Epsilon and Minimum Points are two required parameters. Epsilon is the radius within nearby data points that need to be in to be considered ‘similar’ enough to begin a cluster. Finally, Minimum Points is the minimum number of data points that need to be inside the radius (ie. epsilon) before they can be considered a cluster."
},
{
"code": null,
"e": 22431,
"s": 21911,
"text": "In our example, we attempted to cluster a dataset of 15,000 employees based on their job characteristics. We first standardized the dataset to scale the features. Next, we applied PCA in order to reduce the number of dimensions/features to 3 principal components. Using the “Elbow Method” we estimated an epsilon value of 0.2 and a minimum point value of 6. Using these parameters we were able to obtain 53 clusters, 1,500 outliers, and a silhouette score of -0.52. Needless to say, the results were not very promising."
},
{
"code": null,
"e": 22990,
"s": 22431,
"text": "Next, we attempted an iterative approach to fine-tuning the epsilon and minimum points parameters. We had decided upon an epsilon value of 1.0 and a minimum points value of 4. The algorithm returned 6 valid clusters (one -1 cluster), only 7 outliers, and a respectable silhouette score of 0.46. However, upon plotting the derived clusters it was discovered the first cluster contained 99% of the employees. Once again from a business perspective, we would want our clusters to be more equally distributed to provide us with good insights about our employees."
},
{
"code": null,
"e": 23080,
"s": 22990,
"text": "It would seem DBSCAN is not the optimal clustering algorithm for this particular dataset."
}
] |
Set upper_bound() function in C++ STL | In this article we are going to discuss the set::upper_bound() in C++ STL, their syntax, working and their return values.
Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.
upper_bound() is an inbuilt function in C++ STL which is declared in <set> header file. upper_bound() returns an iterator to the upper bound of the value whose upper bound we wish to find. The function returns iterator pointing to the immediate next element of the value whose upper bound we wish to find.
name_of_set.upper_bound(const type_t& value);
This function accepts a parameter, i.e. The value whose upper bound is to be found.
This function returns an iterator pointing to the immediate next element which is greater than the value
Input: set<int> myset = {1, 2, 3, 4, 5};
Myset.upper_bound(3);
Output: Upper bound = 4
Live Demo
#include <bits/stdc++.h>
using namespace std;
int main(){
set<int> Set;
Set.insert(9);
Set.insert(7);
Set.insert(5);
Set.insert(3);
Set.insert(1);
cout<<"Elements are : ";
for (auto i = Set.begin(); i!= Set.end(); i++)
cout << *i << " ";
auto i = Set.upper_bound(5);
cout <<"\nupper bound of 5 in the set is: ";
cout << (*i) << endl;
i = Set.upper_bound(1);
cout<<"upper bound of 1 in the set is: ";
cout << (*i) << endl;
return 0;
}
If we run the above code it will generate the following output −
upper bound of 5 in the set is: 7
upper bound of 1 in the set is: 3
Live Demo
#include <iostream>
#include <set>
int main (){
std::set<int> Set;
std::set<int>::iterator one, end;
for (int i=1; i<10; i++)
Set.insert(i*10);
one = Set.lower_bound (20);
end = Set.upper_bound (40);
Set.erase(one , end); // 10 20 70 80 90
std::cout<<"Elements are: ";
for (std::set<int>::iterator i = Set.begin(); i!=Set.end(); ++i)
std::cout << ' ' << *i;
std::cout << '\n';
return 0;
}
If we run the above code it will generate the following output −
Elements are : 10 50 60 70 80 90 | [
{
"code": null,
"e": 1184,
"s": 1062,
"text": "In this article we are going to discuss the set::upper_bound() in C++ STL, their syntax, working and their return values."
},
{
"code": null,
"e": 1517,
"s": 1184,
"text": "Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees."
},
{
"code": null,
"e": 1823,
"s": 1517,
"text": "upper_bound() is an inbuilt function in C++ STL which is declared in <set> header file. upper_bound() returns an iterator to the upper bound of the value whose upper bound we wish to find. The function returns iterator pointing to the immediate next element of the value whose upper bound we wish to find."
},
{
"code": null,
"e": 1869,
"s": 1823,
"text": "name_of_set.upper_bound(const type_t& value);"
},
{
"code": null,
"e": 1953,
"s": 1869,
"text": "This function accepts a parameter, i.e. The value whose upper bound is to be found."
},
{
"code": null,
"e": 2058,
"s": 1953,
"text": "This function returns an iterator pointing to the immediate next element which is greater than the value"
},
{
"code": null,
"e": 2148,
"s": 2058,
"text": "Input: set<int> myset = {1, 2, 3, 4, 5};\n Myset.upper_bound(3);\nOutput: Upper bound = 4"
},
{
"code": null,
"e": 2159,
"s": 2148,
"text": " Live Demo"
},
{
"code": null,
"e": 2644,
"s": 2159,
"text": "#include <bits/stdc++.h>\nusing namespace std;\nint main(){\n set<int> Set;\n Set.insert(9);\n Set.insert(7);\n Set.insert(5);\n Set.insert(3);\n Set.insert(1);\n cout<<\"Elements are : \";\n for (auto i = Set.begin(); i!= Set.end(); i++)\n cout << *i << \" \";\n auto i = Set.upper_bound(5);\n cout <<\"\\nupper bound of 5 in the set is: \";\n cout << (*i) << endl;\n i = Set.upper_bound(1);\n cout<<\"upper bound of 1 in the set is: \";\n cout << (*i) << endl;\n return 0;\n}"
},
{
"code": null,
"e": 2709,
"s": 2644,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 2777,
"s": 2709,
"text": "upper bound of 5 in the set is: 7\nupper bound of 1 in the set is: 3"
},
{
"code": null,
"e": 2788,
"s": 2777,
"text": " Live Demo"
},
{
"code": null,
"e": 3216,
"s": 2788,
"text": "#include <iostream>\n#include <set>\nint main (){\n std::set<int> Set;\n std::set<int>::iterator one, end;\n for (int i=1; i<10; i++)\n Set.insert(i*10);\n one = Set.lower_bound (20);\n end = Set.upper_bound (40);\n Set.erase(one , end); // 10 20 70 80 90\n std::cout<<\"Elements are: \";\n for (std::set<int>::iterator i = Set.begin(); i!=Set.end(); ++i)\n std::cout << ' ' << *i;\n std::cout << '\\n';\n return 0;\n}"
},
{
"code": null,
"e": 3281,
"s": 3216,
"text": "If we run the above code it will generate the following output −"
},
{
"code": null,
"e": 3314,
"s": 3281,
"text": "Elements are : 10 50 60 70 80 90"
}
] |
How to create a Binomial distribution graph using Plotly, Python | by Usama Bin Tariq | Towards Data Science | Sometimes, Python graphs are necessary elements of your argument or the data case you are trying to build. This tutorial is about creating a binomial or normal distribution graph. We would start by declaring an array of numbers that are binomially distributed. We can do this by simply importing binom from scipy.stats.
from scipy.stats import binomn = 1024size = 1000prob = 0.1y = binom.rvs(n, prob, size=size)
This chunk of code generating a thousand numbers with 1024 turns with 0.1 as the probability of success. Once done with this, next we want to count the frequency of numbers in the array. We can do this by making this a data frame and create frequency bins using logic below.
import numpy as npimport pandas as pd# Creating X array for numbers between the maximum and minimum values of y and making it a dataframex = np.arange(y.min(), y.max())xx = pd.DataFrame(x)# Making y a dataframe and generating an empty array yyd = pd.DataFrame(y, columns = ['Data'])yy = []# Calculating frequency of all numbers between maxiumum and minimum valuesfor k in range(len(x)): yy.append(d[d['Data'] == x[k]].count()[0])# Making frequency data frame and concatenating it with the xx freq = pd.DataFrame(yy, columns=['Frequency'])data = pd.concat([xx, freq], axis=1)data.columns = ['Score', 'Frequency']
Now we have the score and frequency bins. We can use this data to generate a binomial graph using plotly.graph.
import plotly.graph_objects as gofig = go.Figure( # Loading the data into the figur data=[go.Scatter(x=data['Score'], y=data['Frequency'], mode="lines", line=dict(width=2, color="blue"))], # Setting the layout of the graph layout=go.Layout( xaxis=dict(range=[y.min(), y.max()], autorange=False), yaxis=dict(range=[data['Frequency'].min(), data['Frequency'].max()], autorange=False), title="Binomial Curve", updatemenus=[dict( type="buttons", buttons=[dict(label="Play", method="animate", args=[None])])] ))fig.show()
The following graph is generated using the code above.
As we can see, the curve demonstrates a basic binomial behavior with a lot of noise, random hovering above and below the expected paths. But it can be easily turned into a complete binomial graph by repeating this procedure a lot of times and averaging out the results. In my case, I performed the above-mentioned step 1500 times. Please check out the code below:
n = 1024size = 1000prob = p / 10x = np.arange(70, 135)yy = []tt = []# Repeating the step 1500 times, rest code is same as abovefor a in range(1500): y = binom.rvs(n, prob, size=size) d = pd.DataFrame(y, columns = ['Data']) for k in range(len(x)): yy.append(d[d['Data'] == x[k]].count()[0]) tt.append(yy) yy = [] y = []kk = pd.DataFrame(tt).Ty = kk.mean(axis=1)N = len(y)
The above code generates a new array “y”, which has averaged frequencies of all the scores in the data. We can generate a new data frame and see the data using the code below:
data = pd.DataFrame([x,y]).Tdata.columns = ['Score', 'Frequency']data.head()
plotting this data again using the plotly code, we get a good looking binomial graph.
With the above graph in our hand, we can play with the data a little more, like we can animate the gradient of the graph, or its derivative at every point using plotly as well.
Derivative at any point can be calculated numerically using the formula shown below.
We can implement this formula using pandas to calculate the value of gradient at all relevant points.
# Declaring an empty arrayderi = []# Setting first derivative to zerofir = 0deri.append(fir)# Calculating the derivative all points other than first and last pointsfor a in range(1,64): diff = (data['Frequency'][a+1] - data['Frequency'][a-1])/2 deri.append(diff)# Setting last derivative to zeroend = 0deri.append(end)der = pd.DataFrame(deri, columns = ['Derivatives'])data = pd.concat([data, der], axis = 1)
Please note that we have deliberately kept zero as a value of the first and last points in the data. This is done since the derivative formula requires preceding and proceeding values. The preceding value is missing for the first value and the proceeding value is missing for the last value. Henceforth both are kept to zero for convenience.
Now that we have derivatives, we need to calculate the starting and ending coordinates of the gradient line we need to animate on plotly.
sx = []sy = []ex = []ey = []Gap = 3.5for b in range(0,65): #Computing Start Coordinates ssx =data['Score'][b] - Gap sx.append(ssx) ssy = data['Frequency'][b] - Gap * data['Derivatives'][b] sy.append(ssy) #Computing End Coordinates eex = data['Score'][b] + Gap ex.append(eex) eey = data['Frequency'][b] + Gap * data['Derivatives'][b] ey.append(eey)cord = pd.DataFrame([sx, sy, ex, ey]).Tcord.columns = ['XStart', 'YStart', 'XEnd', 'YEnd']
Now that we are done, we can visualize the resulting animations.
Further, If we want to mark regions onto this figure and add text to that, we can easily do this using the snippet below.
fig.add_trace(go.Scatter(x=[70,85,85,70], y=[0,0,50,50], fill='toself', mode='lines', line_color='#FF5A5F', opacity = 0.3))fig.add_trace(go.Scatter(x=[85,102,102,85], y=[0,0,50,50], fill='toself', mode='lines', line_color='#C81D25', opacity = 0.3))fig.add_trace(go.Scatter(x=[102,119,119,102], y=[0,0,50,50], fill='toself', mode='lines', line_color='#0B3954', opacity = 0.3))fig.add_trace(go.Scatter(x=[119,135,135,119], y=[0,0,50,50], fill='toself', mode='lines', line_color='#087E8B', opacity = 0.3))fig.add_trace(go.Scatter( x=[77.5, 93.5, 110.5, 127], y=[40, 40, 40, 40], mode="text", name="Regions", text=["Low Risk", "High Risk", "Stabilization", "Recovery"], textposition="top center", textfont=dict( family="sans serif", size=20, color="black" )))fig.show()
We end up the following figure.
If you are still curious regarding what I’m up to, please check out my next blog here, where all these techniques are used to visualize “Global Status of Covid-19". Stay tuned, cheers.
A full Jupyter notebook implementation of Binomial Curve can be found here. | [
{
"code": null,
"e": 492,
"s": 172,
"text": "Sometimes, Python graphs are necessary elements of your argument or the data case you are trying to build. This tutorial is about creating a binomial or normal distribution graph. We would start by declaring an array of numbers that are binomially distributed. We can do this by simply importing binom from scipy.stats."
},
{
"code": null,
"e": 584,
"s": 492,
"text": "from scipy.stats import binomn = 1024size = 1000prob = 0.1y = binom.rvs(n, prob, size=size)"
},
{
"code": null,
"e": 859,
"s": 584,
"text": "This chunk of code generating a thousand numbers with 1024 turns with 0.1 as the probability of success. Once done with this, next we want to count the frequency of numbers in the array. We can do this by making this a data frame and create frequency bins using logic below."
},
{
"code": null,
"e": 1479,
"s": 859,
"text": "import numpy as npimport pandas as pd# Creating X array for numbers between the maximum and minimum values of y and making it a dataframex = np.arange(y.min(), y.max())xx = pd.DataFrame(x)# Making y a dataframe and generating an empty array yyd = pd.DataFrame(y, columns = ['Data'])yy = []# Calculating frequency of all numbers between maxiumum and minimum valuesfor k in range(len(x)): yy.append(d[d['Data'] == x[k]].count()[0])# Making frequency data frame and concatenating it with the xx freq = pd.DataFrame(yy, columns=['Frequency'])data = pd.concat([xx, freq], axis=1)data.columns = ['Score', 'Frequency']"
},
{
"code": null,
"e": 1591,
"s": 1479,
"text": "Now we have the score and frequency bins. We can use this data to generate a binomial graph using plotly.graph."
},
{
"code": null,
"e": 2263,
"s": 1591,
"text": "import plotly.graph_objects as gofig = go.Figure( # Loading the data into the figur data=[go.Scatter(x=data['Score'], y=data['Frequency'], mode=\"lines\", line=dict(width=2, color=\"blue\"))], # Setting the layout of the graph layout=go.Layout( xaxis=dict(range=[y.min(), y.max()], autorange=False), yaxis=dict(range=[data['Frequency'].min(), data['Frequency'].max()], autorange=False), title=\"Binomial Curve\", updatemenus=[dict( type=\"buttons\", buttons=[dict(label=\"Play\", method=\"animate\", args=[None])])] ))fig.show()"
},
{
"code": null,
"e": 2318,
"s": 2263,
"text": "The following graph is generated using the code above."
},
{
"code": null,
"e": 2682,
"s": 2318,
"text": "As we can see, the curve demonstrates a basic binomial behavior with a lot of noise, random hovering above and below the expected paths. But it can be easily turned into a complete binomial graph by repeating this procedure a lot of times and averaging out the results. In my case, I performed the above-mentioned step 1500 times. Please check out the code below:"
},
{
"code": null,
"e": 3091,
"s": 2682,
"text": "n = 1024size = 1000prob = p / 10x = np.arange(70, 135)yy = []tt = []# Repeating the step 1500 times, rest code is same as abovefor a in range(1500): y = binom.rvs(n, prob, size=size) d = pd.DataFrame(y, columns = ['Data']) for k in range(len(x)): yy.append(d[d['Data'] == x[k]].count()[0]) tt.append(yy) yy = [] y = []kk = pd.DataFrame(tt).Ty = kk.mean(axis=1)N = len(y)"
},
{
"code": null,
"e": 3267,
"s": 3091,
"text": "The above code generates a new array “y”, which has averaged frequencies of all the scores in the data. We can generate a new data frame and see the data using the code below:"
},
{
"code": null,
"e": 3344,
"s": 3267,
"text": "data = pd.DataFrame([x,y]).Tdata.columns = ['Score', 'Frequency']data.head()"
},
{
"code": null,
"e": 3430,
"s": 3344,
"text": "plotting this data again using the plotly code, we get a good looking binomial graph."
},
{
"code": null,
"e": 3607,
"s": 3430,
"text": "With the above graph in our hand, we can play with the data a little more, like we can animate the gradient of the graph, or its derivative at every point using plotly as well."
},
{
"code": null,
"e": 3692,
"s": 3607,
"text": "Derivative at any point can be calculated numerically using the formula shown below."
},
{
"code": null,
"e": 3794,
"s": 3692,
"text": "We can implement this formula using pandas to calculate the value of gradient at all relevant points."
},
{
"code": null,
"e": 4209,
"s": 3794,
"text": "# Declaring an empty arrayderi = []# Setting first derivative to zerofir = 0deri.append(fir)# Calculating the derivative all points other than first and last pointsfor a in range(1,64): diff = (data['Frequency'][a+1] - data['Frequency'][a-1])/2 deri.append(diff)# Setting last derivative to zeroend = 0deri.append(end)der = pd.DataFrame(deri, columns = ['Derivatives'])data = pd.concat([data, der], axis = 1)"
},
{
"code": null,
"e": 4551,
"s": 4209,
"text": "Please note that we have deliberately kept zero as a value of the first and last points in the data. This is done since the derivative formula requires preceding and proceeding values. The preceding value is missing for the first value and the proceeding value is missing for the last value. Henceforth both are kept to zero for convenience."
},
{
"code": null,
"e": 4689,
"s": 4551,
"text": "Now that we have derivatives, we need to calculate the starting and ending coordinates of the gradient line we need to animate on plotly."
},
{
"code": null,
"e": 5157,
"s": 4689,
"text": "sx = []sy = []ex = []ey = []Gap = 3.5for b in range(0,65): #Computing Start Coordinates ssx =data['Score'][b] - Gap sx.append(ssx) ssy = data['Frequency'][b] - Gap * data['Derivatives'][b] sy.append(ssy) #Computing End Coordinates eex = data['Score'][b] + Gap ex.append(eex) eey = data['Frequency'][b] + Gap * data['Derivatives'][b] ey.append(eey)cord = pd.DataFrame([sx, sy, ex, ey]).Tcord.columns = ['XStart', 'YStart', 'XEnd', 'YEnd']"
},
{
"code": null,
"e": 5222,
"s": 5157,
"text": "Now that we are done, we can visualize the resulting animations."
},
{
"code": null,
"e": 5344,
"s": 5222,
"text": "Further, If we want to mark regions onto this figure and add text to that, we can easily do this using the snippet below."
},
{
"code": null,
"e": 6155,
"s": 5344,
"text": "fig.add_trace(go.Scatter(x=[70,85,85,70], y=[0,0,50,50], fill='toself', mode='lines', line_color='#FF5A5F', opacity = 0.3))fig.add_trace(go.Scatter(x=[85,102,102,85], y=[0,0,50,50], fill='toself', mode='lines', line_color='#C81D25', opacity = 0.3))fig.add_trace(go.Scatter(x=[102,119,119,102], y=[0,0,50,50], fill='toself', mode='lines', line_color='#0B3954', opacity = 0.3))fig.add_trace(go.Scatter(x=[119,135,135,119], y=[0,0,50,50], fill='toself', mode='lines', line_color='#087E8B', opacity = 0.3))fig.add_trace(go.Scatter( x=[77.5, 93.5, 110.5, 127], y=[40, 40, 40, 40], mode=\"text\", name=\"Regions\", text=[\"Low Risk\", \"High Risk\", \"Stabilization\", \"Recovery\"], textposition=\"top center\", textfont=dict( family=\"sans serif\", size=20, color=\"black\" )))fig.show()"
},
{
"code": null,
"e": 6187,
"s": 6155,
"text": "We end up the following figure."
},
{
"code": null,
"e": 6372,
"s": 6187,
"text": "If you are still curious regarding what I’m up to, please check out my next blog here, where all these techniques are used to visualize “Global Status of Covid-19\". Stay tuned, cheers."
}
] |
A table detection, cell recognition and text extraction algorithm to convert tables in images to excel files | by Hucker Marius | Towards Data Science | Let’s say you have a table in an article, pdf or image and want to transfer it into an excel sheet or dataframe to have the possibility to edit it. Especially in the field of preprocessing for Machine Learning this algorithm will be exceptionally helpful to convert many images and tables to editable data. In the case that your data exists of text-based PDFs there is already a handful of free solutions. The most popular ones are tabular, camelot/excalibur, which you can find under https://tabula.technology/, https://camelot-py.readthedocs.io/en/master/, https://excalibur-py.readthedocs.io/en/master/.
However, what if your PDF is image-based or if you find an article with a table online? Why not just take a screenshot and convert it into an excel sheet? Since there seems to be no free or open source software for image-based data (jpg, png, image-based pdf etc.) the idea came up to develop a generic solution to convert tables into editable excel-files.
But that’s enough for now, let’s see how it works.
The algorithm consists of three parts: the first is the table detection and cell recognition with Open CV, the second the thorough allocation of the cells to the proper row and column and the third part is the extraction of each allocated cell through Optical Character Recognition (OCR) with pytesseract.
As most table recognition algorithms, this one is based on the line structure of the table. Clear and detectable lines are necessary for the proper identification of cells. Tables with broken lines, gaps and holes lead to a worse identification and the cells only partially surrounded by lines are not detected. In case some of your documents have broken lines make sure to read this article and repair the lines: Click here.
First, we need the input data, which is in my case a screenshot in png-format. The goal is to have a dataframe and excel-file with the identical tabular structure, where each cell can be edited and used for further analysis.
Let’s import the necessary libraries.
For more information on the libraries:cv2 — https://opencv.org/pytesseract — https://pypi.org/project/pytesseract/
import cv2import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport csvtry: from PIL import Imageexcept ImportError: import Imageimport pytesseract
The first step is to read in your file from the proper path, using thresholding to convert the input image to a binary image and inverting it to get a black background and white lines and fonts.
#read your filefile=r'/Users/YOURPATH/testcv.png'img = cv2.imread(file,0)img.shape#thresholding the image to a binary imagethresh,img_bin = cv2.threshold(img,128,255,cv2.THRESH_BINARY |cv2.THRESH_OTSU)#inverting the image img_bin = 255-img_bincv2.imwrite('/Users/YOURPATH/cv_inverted.png',img_bin)#Plotting the image to see the outputplotting = plt.imshow(img_bin,cmap='gray')plt.show()
medium.com
The next step is to define a kernel to detect rectangular boxes, and followingly the tabular structure. First, we define the length of the kernel and following the vertical and horizontal kernels to detect later on all vertical lines and all horizontal lines.
# Length(width) of kernel as 100th of total widthkernel_len = np.array(img).shape[1]//100# Defining a vertical kernel to detect all vertical lines of image ver_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_len))# Defining a horizontal kernel to detect all horizontal lines of imagehor_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_len, 1))# A kernel of 2x2kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))
The next step is the detection of the vertical lines.
#Use vertical kernel to detect and save the vertical lines in a jpgimage_1 = cv2.erode(img_bin, ver_kernel, iterations=3)vertical_lines = cv2.dilate(image_1, ver_kernel, iterations=3)cv2.imwrite("/Users/YOURPATH/vertical.jpg",vertical_lines)#Plot the generated imageplotting = plt.imshow(image_1,cmap='gray')plt.show()
And now the same for all horizontal lines.
#Use horizontal kernel to detect and save the horizontal lines in a jpgimage_2 = cv2.erode(img_bin, hor_kernel, iterations=3)horizontal_lines = cv2.dilate(image_2, hor_kernel, iterations=3)cv2.imwrite("/Users/YOURPATH/horizontal.jpg",horizontal_lines)#Plot the generated imageplotting = plt.imshow(image_2,cmap='gray')plt.show()
We combine the horizontal and vertical lines to a third image, by weighting both with 0.5. The aim is to get a clear tabular structure to detect each cell.
# Combine horizontal and vertical lines in a new third image, with both having same weight.img_vh = cv2.addWeighted(vertical_lines, 0.5, horizontal_lines, 0.5, 0.0)#Eroding and thesholding the imageimg_vh = cv2.erode(~img_vh, kernel, iterations=2)thresh, img_vh = cv2.threshold(img_vh,128,255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)cv2.imwrite("/Users/YOURPATH/img_vh.jpg", img_vh)bitxor = cv2.bitwise_xor(img,img_vh)bitnot = cv2.bitwise_not(bitxor)#Plotting the generated imageplotting = plt.imshow(bitnot,cmap='gray')plt.show()
After having the tabular structure we use the findContours function to detect the contours. This helps us to retrieve the exact coordinates of each box.
# Detect contours for following box detectioncontours, hierarchy = cv2.findContours(img_vh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
The following function is necessary to get a sequence of the contours and to sort them from top-to-bottom (https://www.pyimagesearch.com/2015/04/20/sorting-contours-using-python-and-opencv/).
def sort_contours(cnts, method="left-to-right"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == "right-to-left" or method == "bottom-to-top": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == "top-to-bottom" or method == "bottom-to-top": i = 1 # construct the list of bounding boxes and sort them from top to # bottom boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b:b[1][i], reverse=reverse)) # return the list of sorted contours and bounding boxes return (cnts, boundingBoxes)# Sort all the contours by top to bottom.contours, boundingBoxes = sort_contours(contours, method=”top-to-bottom”)
The further steps are necessary to define the right location, which means proper column and row, of each cell. First, we need to retrieve the height for each cell and store it in the list heights. Then we take the mean from the heights.
#Creating a list of heights for all detected boxesheights = [boundingBoxes[i][3] for i in range(len(boundingBoxes))]#Get mean of heightsmean = np.mean(heights)
Next we retrieve the position, width and height of each contour and store it in the box list. Then we draw rectangles around all our boxes and plot the image. In my case I only did it for boxes smaller then a width of 1000 px and a height of 500 px to neglect rectangles which might be no cells, e.g. the table as a whole. These two values depend on your image size, so in case your image is a lot smaller or bigger you need to adjust both.
#Create list box to store all boxes in box = []# Get position (x,y), width and height for every contour and show the contour on imagefor c in contours: x, y, w, h = cv2.boundingRect(c) if (w<1000 and h<500): image = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) box.append([x,y,w,h])plotting = plt.imshow(image,cmap=’gray’)plt.show()
Now as we have every cell, its location, height and width we need to get the right location within the table. Therefore, we need to know in which row and which column it is located. As long as a box does not differ more than its own (height + mean/2) the box is in the same row. As soon as the height difference is higher than the current (height + mean/2) , we know that a new row starts. Columns are logically arranged from left to right.
#Creating two lists to define row and column in which cell is locatedrow=[]column=[]j=0#Sorting the boxes to their respective row and columnfor i in range(len(box)): if(i==0): column.append(box[i]) previous=box[i] else: if(box[i][1]<=previous[1]+mean/2): column.append(box[i]) previous=box[i] if(i==len(box)-1): row.append(column) else: row.append(column) column=[] previous = box[i] column.append(box[i])print(column)print(row)
Next we calculate the maximum number of columns (meaning cells) to understand how many columns our final dataframe/table will have.
#calculating maximum number of cellscountcol = 0for i in range(len(row)): countcol = len(row[i]) if countcol > countcol: countcol = countcol
After having the maximum number of cells we store the midpoint of each column in a list, create an array and sort the values.
#Retrieving the center of each columncenter = [int(row[i][j][0]+row[i][j][2]/2) for j in range(len(row[i])) if row[0]]center=np.array(center)center.sort()
At this point, we have all boxes and their values, but as you might see in the output of your row list the values are not always sorted in the right order. That’s what we do next regarding the distance to the columns center. The proper sequence we store in the list finalboxes.
#Regarding the distance to the columns center, the boxes are arranged in respective orderfinalboxes = []for i in range(len(row)): lis=[] for k in range(countcol): lis.append([]) for j in range(len(row[i])): diff = abs(center-(row[i][j][0]+row[i][j][2]/4)) minimum = min(diff) indexing = list(diff).index(minimum) lis[indexing].append(row[i][j]) finalboxes.append(lis)
In the next step we make use of our list finalboxes. We take every image-based box, prepare it for Optical Character Recognition by dilating and eroding it and let pytesseract recognize the containing strings. The loop runs over every cell and stores the value in the outer list.
#from every single image-based cell/box the strings are extracted via pytesseract and stored in a listouter=[]for i in range(len(finalboxes)): for j in range(len(finalboxes[i])): inner=’’ if(len(finalboxes[i][j])==0): outer.append(' ') else: for k in range(len(finalboxes[i][j])): y,x,w,h = finalboxes[i][j][k][0],finalboxes[i][j][k][1], finalboxes[i][j][k][2],finalboxes[i][j][k][3] finalimg = bitnot[x:x+h, y:y+w] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 1)) border = cv2.copyMakeBorder(finalimg,2,2,2,2, cv2.BORDER_CONSTANT,value=[255,255]) resizing = cv2.resize(border, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) dilation = cv2.dilate(resizing, kernel,iterations=1) erosion = cv2.erode(dilation, kernel,iterations=1) out = pytesseract.image_to_string(erosion) if(len(out)==0): out = pytesseract.image_to_string(erosion, config='--psm 3') inner = inner +" "+ out outer.append(inner)
The last step is the conversion of the list to a dataframe and storing it into an excel-file.
#Creating a dataframe of the generated OCR listarr = np.array(outer)dataframe = pd.DataFrame(arr.reshape(len(row),countcol))print(dataframe)data = dataframe.style.set_properties(align="left")#Converting it in a excel-filedata.to_excel(“/Users/YOURPATH/output.xlsx”)
That’s it! Your table should now be stored in a dataframe and in an excel-file and can be used for Nature Language Processing, for further analysis via statistics or just for editing it. This works for tables with a clear and simple structure. In case your table has an extraordinary structure, in the sense that many cells are combined, that the cells size varies strongly or that many colours are used, the algorithm may has to be adopted. Furthermore OCR (pytesseract) is nearly perfect in recognizing computer fonts. However, if you have tables containing handwritten input, the results may vary.
If you use it for your own table(s), let me know how it worked.
medium.com
Also Read:
How to Fix Broken Lines in Table Recognition | [
{
"code": null,
"e": 779,
"s": 172,
"text": "Let’s say you have a table in an article, pdf or image and want to transfer it into an excel sheet or dataframe to have the possibility to edit it. Especially in the field of preprocessing for Machine Learning this algorithm will be exceptionally helpful to convert many images and tables to editable data. In the case that your data exists of text-based PDFs there is already a handful of free solutions. The most popular ones are tabular, camelot/excalibur, which you can find under https://tabula.technology/, https://camelot-py.readthedocs.io/en/master/, https://excalibur-py.readthedocs.io/en/master/."
},
{
"code": null,
"e": 1136,
"s": 779,
"text": "However, what if your PDF is image-based or if you find an article with a table online? Why not just take a screenshot and convert it into an excel sheet? Since there seems to be no free or open source software for image-based data (jpg, png, image-based pdf etc.) the idea came up to develop a generic solution to convert tables into editable excel-files."
},
{
"code": null,
"e": 1187,
"s": 1136,
"text": "But that’s enough for now, let’s see how it works."
},
{
"code": null,
"e": 1493,
"s": 1187,
"text": "The algorithm consists of three parts: the first is the table detection and cell recognition with Open CV, the second the thorough allocation of the cells to the proper row and column and the third part is the extraction of each allocated cell through Optical Character Recognition (OCR) with pytesseract."
},
{
"code": null,
"e": 1919,
"s": 1493,
"text": "As most table recognition algorithms, this one is based on the line structure of the table. Clear and detectable lines are necessary for the proper identification of cells. Tables with broken lines, gaps and holes lead to a worse identification and the cells only partially surrounded by lines are not detected. In case some of your documents have broken lines make sure to read this article and repair the lines: Click here."
},
{
"code": null,
"e": 2144,
"s": 1919,
"text": "First, we need the input data, which is in my case a screenshot in png-format. The goal is to have a dataframe and excel-file with the identical tabular structure, where each cell can be edited and used for further analysis."
},
{
"code": null,
"e": 2182,
"s": 2144,
"text": "Let’s import the necessary libraries."
},
{
"code": null,
"e": 2297,
"s": 2182,
"text": "For more information on the libraries:cv2 — https://opencv.org/pytesseract — https://pypi.org/project/pytesseract/"
},
{
"code": null,
"e": 2468,
"s": 2297,
"text": "import cv2import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport csvtry: from PIL import Imageexcept ImportError: import Imageimport pytesseract"
},
{
"code": null,
"e": 2663,
"s": 2468,
"text": "The first step is to read in your file from the proper path, using thresholding to convert the input image to a binary image and inverting it to get a black background and white lines and fonts."
},
{
"code": null,
"e": 3050,
"s": 2663,
"text": "#read your filefile=r'/Users/YOURPATH/testcv.png'img = cv2.imread(file,0)img.shape#thresholding the image to a binary imagethresh,img_bin = cv2.threshold(img,128,255,cv2.THRESH_BINARY |cv2.THRESH_OTSU)#inverting the image img_bin = 255-img_bincv2.imwrite('/Users/YOURPATH/cv_inverted.png',img_bin)#Plotting the image to see the outputplotting = plt.imshow(img_bin,cmap='gray')plt.show()"
},
{
"code": null,
"e": 3061,
"s": 3050,
"text": "medium.com"
},
{
"code": null,
"e": 3321,
"s": 3061,
"text": "The next step is to define a kernel to detect rectangular boxes, and followingly the tabular structure. First, we define the length of the kernel and following the vertical and horizontal kernels to detect later on all vertical lines and all horizontal lines."
},
{
"code": null,
"e": 3765,
"s": 3321,
"text": "# Length(width) of kernel as 100th of total widthkernel_len = np.array(img).shape[1]//100# Defining a vertical kernel to detect all vertical lines of image ver_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, kernel_len))# Defining a horizontal kernel to detect all horizontal lines of imagehor_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (kernel_len, 1))# A kernel of 2x2kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))"
},
{
"code": null,
"e": 3819,
"s": 3765,
"text": "The next step is the detection of the vertical lines."
},
{
"code": null,
"e": 4138,
"s": 3819,
"text": "#Use vertical kernel to detect and save the vertical lines in a jpgimage_1 = cv2.erode(img_bin, ver_kernel, iterations=3)vertical_lines = cv2.dilate(image_1, ver_kernel, iterations=3)cv2.imwrite(\"/Users/YOURPATH/vertical.jpg\",vertical_lines)#Plot the generated imageplotting = plt.imshow(image_1,cmap='gray')plt.show()"
},
{
"code": null,
"e": 4181,
"s": 4138,
"text": "And now the same for all horizontal lines."
},
{
"code": null,
"e": 4510,
"s": 4181,
"text": "#Use horizontal kernel to detect and save the horizontal lines in a jpgimage_2 = cv2.erode(img_bin, hor_kernel, iterations=3)horizontal_lines = cv2.dilate(image_2, hor_kernel, iterations=3)cv2.imwrite(\"/Users/YOURPATH/horizontal.jpg\",horizontal_lines)#Plot the generated imageplotting = plt.imshow(image_2,cmap='gray')plt.show()"
},
{
"code": null,
"e": 4666,
"s": 4510,
"text": "We combine the horizontal and vertical lines to a third image, by weighting both with 0.5. The aim is to get a clear tabular structure to detect each cell."
},
{
"code": null,
"e": 5194,
"s": 4666,
"text": "# Combine horizontal and vertical lines in a new third image, with both having same weight.img_vh = cv2.addWeighted(vertical_lines, 0.5, horizontal_lines, 0.5, 0.0)#Eroding and thesholding the imageimg_vh = cv2.erode(~img_vh, kernel, iterations=2)thresh, img_vh = cv2.threshold(img_vh,128,255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)cv2.imwrite(\"/Users/YOURPATH/img_vh.jpg\", img_vh)bitxor = cv2.bitwise_xor(img,img_vh)bitnot = cv2.bitwise_not(bitxor)#Plotting the generated imageplotting = plt.imshow(bitnot,cmap='gray')plt.show()"
},
{
"code": null,
"e": 5347,
"s": 5194,
"text": "After having the tabular structure we use the findContours function to detect the contours. This helps us to retrieve the exact coordinates of each box."
},
{
"code": null,
"e": 5479,
"s": 5347,
"text": "# Detect contours for following box detectioncontours, hierarchy = cv2.findContours(img_vh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)"
},
{
"code": null,
"e": 5671,
"s": 5479,
"text": "The following function is necessary to get a sequence of the contours and to sort them from top-to-bottom (https://www.pyimagesearch.com/2015/04/20/sorting-contours-using-python-and-opencv/)."
},
{
"code": null,
"e": 6546,
"s": 5671,
"text": "def sort_contours(cnts, method=\"left-to-right\"): # initialize the reverse flag and sort index reverse = False i = 0 # handle if we need to sort in reverse if method == \"right-to-left\" or method == \"bottom-to-top\": reverse = True # handle if we are sorting against the y-coordinate rather than # the x-coordinate of the bounding box if method == \"top-to-bottom\" or method == \"bottom-to-top\": i = 1 # construct the list of bounding boxes and sort them from top to # bottom boundingBoxes = [cv2.boundingRect(c) for c in cnts] (cnts, boundingBoxes) = zip(*sorted(zip(cnts, boundingBoxes), key=lambda b:b[1][i], reverse=reverse)) # return the list of sorted contours and bounding boxes return (cnts, boundingBoxes)# Sort all the contours by top to bottom.contours, boundingBoxes = sort_contours(contours, method=”top-to-bottom”)"
},
{
"code": null,
"e": 6783,
"s": 6546,
"text": "The further steps are necessary to define the right location, which means proper column and row, of each cell. First, we need to retrieve the height for each cell and store it in the list heights. Then we take the mean from the heights."
},
{
"code": null,
"e": 6943,
"s": 6783,
"text": "#Creating a list of heights for all detected boxesheights = [boundingBoxes[i][3] for i in range(len(boundingBoxes))]#Get mean of heightsmean = np.mean(heights)"
},
{
"code": null,
"e": 7384,
"s": 6943,
"text": "Next we retrieve the position, width and height of each contour and store it in the box list. Then we draw rectangles around all our boxes and plot the image. In my case I only did it for boxes smaller then a width of 1000 px and a height of 500 px to neglect rectangles which might be no cells, e.g. the table as a whole. These two values depend on your image size, so in case your image is a lot smaller or bigger you need to adjust both."
},
{
"code": null,
"e": 7740,
"s": 7384,
"text": "#Create list box to store all boxes in box = []# Get position (x,y), width and height for every contour and show the contour on imagefor c in contours: x, y, w, h = cv2.boundingRect(c) if (w<1000 and h<500): image = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2) box.append([x,y,w,h])plotting = plt.imshow(image,cmap=’gray’)plt.show()"
},
{
"code": null,
"e": 8181,
"s": 7740,
"text": "Now as we have every cell, its location, height and width we need to get the right location within the table. Therefore, we need to know in which row and which column it is located. As long as a box does not differ more than its own (height + mean/2) the box is in the same row. As soon as the height difference is higher than the current (height + mean/2) , we know that a new row starts. Columns are logically arranged from left to right."
},
{
"code": null,
"e": 8736,
"s": 8181,
"text": "#Creating two lists to define row and column in which cell is locatedrow=[]column=[]j=0#Sorting the boxes to their respective row and columnfor i in range(len(box)): if(i==0): column.append(box[i]) previous=box[i] else: if(box[i][1]<=previous[1]+mean/2): column.append(box[i]) previous=box[i] if(i==len(box)-1): row.append(column) else: row.append(column) column=[] previous = box[i] column.append(box[i])print(column)print(row)"
},
{
"code": null,
"e": 8868,
"s": 8736,
"text": "Next we calculate the maximum number of columns (meaning cells) to understand how many columns our final dataframe/table will have."
},
{
"code": null,
"e": 9022,
"s": 8868,
"text": "#calculating maximum number of cellscountcol = 0for i in range(len(row)): countcol = len(row[i]) if countcol > countcol: countcol = countcol"
},
{
"code": null,
"e": 9148,
"s": 9022,
"text": "After having the maximum number of cells we store the midpoint of each column in a list, create an array and sort the values."
},
{
"code": null,
"e": 9303,
"s": 9148,
"text": "#Retrieving the center of each columncenter = [int(row[i][j][0]+row[i][j][2]/2) for j in range(len(row[i])) if row[0]]center=np.array(center)center.sort()"
},
{
"code": null,
"e": 9581,
"s": 9303,
"text": "At this point, we have all boxes and their values, but as you might see in the output of your row list the values are not always sorted in the right order. That’s what we do next regarding the distance to the columns center. The proper sequence we store in the list finalboxes."
},
{
"code": null,
"e": 9996,
"s": 9581,
"text": "#Regarding the distance to the columns center, the boxes are arranged in respective orderfinalboxes = []for i in range(len(row)): lis=[] for k in range(countcol): lis.append([]) for j in range(len(row[i])): diff = abs(center-(row[i][j][0]+row[i][j][2]/4)) minimum = min(diff) indexing = list(diff).index(minimum) lis[indexing].append(row[i][j]) finalboxes.append(lis)"
},
{
"code": null,
"e": 10276,
"s": 9996,
"text": "In the next step we make use of our list finalboxes. We take every image-based box, prepare it for Optical Character Recognition by dilating and eroding it and let pytesseract recognize the containing strings. The loop runs over every cell and stores the value in the outer list."
},
{
"code": null,
"e": 11426,
"s": 10276,
"text": "#from every single image-based cell/box the strings are extracted via pytesseract and stored in a listouter=[]for i in range(len(finalboxes)): for j in range(len(finalboxes[i])): inner=’’ if(len(finalboxes[i][j])==0): outer.append(' ') else: for k in range(len(finalboxes[i][j])): y,x,w,h = finalboxes[i][j][k][0],finalboxes[i][j][k][1], finalboxes[i][j][k][2],finalboxes[i][j][k][3] finalimg = bitnot[x:x+h, y:y+w] kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 1)) border = cv2.copyMakeBorder(finalimg,2,2,2,2, cv2.BORDER_CONSTANT,value=[255,255]) resizing = cv2.resize(border, None, fx=2, fy=2, interpolation=cv2.INTER_CUBIC) dilation = cv2.dilate(resizing, kernel,iterations=1) erosion = cv2.erode(dilation, kernel,iterations=1) out = pytesseract.image_to_string(erosion) if(len(out)==0): out = pytesseract.image_to_string(erosion, config='--psm 3') inner = inner +\" \"+ out outer.append(inner)"
},
{
"code": null,
"e": 11520,
"s": 11426,
"text": "The last step is the conversion of the list to a dataframe and storing it into an excel-file."
},
{
"code": null,
"e": 11786,
"s": 11520,
"text": "#Creating a dataframe of the generated OCR listarr = np.array(outer)dataframe = pd.DataFrame(arr.reshape(len(row),countcol))print(dataframe)data = dataframe.style.set_properties(align=\"left\")#Converting it in a excel-filedata.to_excel(“/Users/YOURPATH/output.xlsx”)"
},
{
"code": null,
"e": 12387,
"s": 11786,
"text": "That’s it! Your table should now be stored in a dataframe and in an excel-file and can be used for Nature Language Processing, for further analysis via statistics or just for editing it. This works for tables with a clear and simple structure. In case your table has an extraordinary structure, in the sense that many cells are combined, that the cells size varies strongly or that many colours are used, the algorithm may has to be adopted. Furthermore OCR (pytesseract) is nearly perfect in recognizing computer fonts. However, if you have tables containing handwritten input, the results may vary."
},
{
"code": null,
"e": 12451,
"s": 12387,
"text": "If you use it for your own table(s), let me know how it worked."
},
{
"code": null,
"e": 12462,
"s": 12451,
"text": "medium.com"
},
{
"code": null,
"e": 12473,
"s": 12462,
"text": "Also Read:"
}
] |
Check For Star Graph | A graph is given; we have to check the given graph is a star graph or not.
By traversing the graph, we have to find the number of vertices has degree one, and number of vertices, whose degree is n-1. (Here n is the number of vertices in the given graph). When the number of vertices with degree 1 is n-1 and a number of vertices with a degree (n-1) is one, then it is a star graph.
Input:
The adjacency matrix:
0 1 1 1
1 0 0 0
1 0 0 0
1 0 0 0
Output:
It is a star graph.
checkStarGraph(graph)
Input: The given Graph.
Output: True when the graph is a star graph.
Begin
degOneVert := 0 and degNminOneGraph := 0
if graph has only one vertex, then
return true, if there is no self-loop
else if graph has two vertices, then
return true if there is only one vertex between two vertices
else
for all vertices i in the graph, do
degree := 0
for all vertices j, adjacent with i, do
degree := degree + 1
done
if degree = 1, then
degOneVert := degOneVert + 1
else if degree = n-1, then
degNminOneGraph := degNminOneGraph + 1
done
if degOneVert = n-1, and degNminOneGraph = 1, then
return true
otherwise return false
End
#include<iostream>
#define NODE 4
using namespace std;
int graph[NODE][NODE] = {
{0, 1, 1, 1},
{1, 0, 0, 0},
{1, 0, 0, 0},
{1, 0, 0, 0}
};
bool checkStarGraph() {
int degOneVert = 0, degVert = 0; //initially vertex with degree 1 and with degree n - 1 are 0
if (NODE == 1) //when there is only one node
return (graph[0][0] == 0);
if (NODE == 2)
return (graph[0][0] == 0 && graph[0][1] == 1 && graph[1][0] == 1 && graph[1][1] == 0 );
for (int i = 0; i < NODE; i++) { //for graph more than 2
int degree = 0;
for (int j = 0; j < NODE; j++) //count degree for vertex i
if (graph[i][j])
degree++;
if (degree == 1)
degOneVert++;
else if (degree == NODE-1)
degVert++;
}
//when only vertex of degree n-1, and all other vertex of degree 1, it is a star graph
return (degOneVert == (NODE-1) && degVert == 1);
}
int main() {
if(checkStarGraph())
cout << "It is a star graph.";
else
cout << "It is not a star graph.";
}
It is a star graph. | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "A graph is given; we have to check the given graph is a star graph or not."
},
{
"code": null,
"e": 1444,
"s": 1137,
"text": "By traversing the graph, we have to find the number of vertices has degree one, and number of vertices, whose degree is n-1. (Here n is the number of vertices in the given graph). When the number of vertices with degree 1 is n-1 and a number of vertices with a degree (n-1) is one, then it is a star graph."
},
{
"code": null,
"e": 1534,
"s": 1444,
"text": "Input:\nThe adjacency matrix:\n0 1 1 1\n1 0 0 0\n1 0 0 0\n1 0 0 0\n\nOutput:\nIt is a star graph."
},
{
"code": null,
"e": 1556,
"s": 1534,
"text": "checkStarGraph(graph)"
},
{
"code": null,
"e": 1580,
"s": 1556,
"text": "Input: The given Graph."
},
{
"code": null,
"e": 1625,
"s": 1580,
"text": "Output: True when the graph is a star graph."
},
{
"code": null,
"e": 2302,
"s": 1625,
"text": "Begin\n degOneVert := 0 and degNminOneGraph := 0\n if graph has only one vertex, then\n return true, if there is no self-loop\n else if graph has two vertices, then\n return true if there is only one vertex between two vertices\n else\n for all vertices i in the graph, do\n degree := 0\n for all vertices j, adjacent with i, do\n degree := degree + 1\n done\n if degree = 1, then\n degOneVert := degOneVert + 1\n else if degree = n-1, then\n degNminOneGraph := degNminOneGraph + 1\n done\n\n if degOneVert = n-1, and degNminOneGraph = 1, then\n return true\n otherwise return false\nEnd"
},
{
"code": null,
"e": 3353,
"s": 2302,
"text": "#include<iostream>\n#define NODE 4\nusing namespace std;\n\nint graph[NODE][NODE] = {\n {0, 1, 1, 1},\n {1, 0, 0, 0},\n {1, 0, 0, 0},\n {1, 0, 0, 0}\n};\n\nbool checkStarGraph() {\n int degOneVert = 0, degVert = 0; //initially vertex with degree 1 and with degree n - 1 are 0\n if (NODE == 1) //when there is only one node\n return (graph[0][0] == 0);\n\n if (NODE == 2) \n return (graph[0][0] == 0 && graph[0][1] == 1 && graph[1][0] == 1 && graph[1][1] == 0 );\n\n for (int i = 0; i < NODE; i++) { //for graph more than 2\n int degree = 0;\n for (int j = 0; j < NODE; j++) //count degree for vertex i\n if (graph[i][j])\n degree++;\n if (degree == 1)\n degOneVert++;\n else if (degree == NODE-1)\n degVert++;\n }\n //when only vertex of degree n-1, and all other vertex of degree 1, it is a star graph\n return (degOneVert == (NODE-1) && degVert == 1);\n}\n\nint main() {\n if(checkStarGraph())\n cout << \"It is a star graph.\";\n else\n cout << \"It is not a star graph.\";\n}"
},
{
"code": null,
"e": 3373,
"s": 3353,
"text": "It is a star graph."
}
] |
ExpressJS - Best Practices | Unlike Django and Rails which have a defined way of doing things, file structure, etc., Express does not follow a defined way. This means you can structure the application the way you like. But as your application grows in size, it is very difficult to maintain it if it doesn't have a well-defined structure. In this chapter, we will look at the generally used directory structures and separation of concerns to build our applications.
First, we will discuss the best practices for creating node and Express applications.
Always begin a node project using npm init.
Always begin a node project using npm init.
Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies.
Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies.
Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase.
Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase.
Don’t push node_modules to your repositories. Instead npm installs everything on development machines.
Don’t push node_modules to your repositories. Instead npm installs everything on development machines.
Use a config file to store variables
Use a config file to store variables
Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page.
Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page.
Let us now discuss the Express’ Directory Structure.
Express does not have a community defined structure for creating applications. The following is a majorly used project structure for a website.
test-project/
node_modules/
config/
db.js //Database connection and configuration
credentials.js //Passwords/API keys for external services used by your app
config.js //Other environment variables
models/ //For mongoose schemas
users.js
things.js
routes/ //All routes for different entities in different files
users.js
things.js
views/
index.pug
404.pug
...
public/ //All static content being served
images/
css/
javascript/
app.js
routes.js //Require all routes in this and then require this file in
app.js
package.json
There are other approaches to build websites with Express as well. You can build a website using the MVC design pattern. For more information, you can visit the following links.
https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168
and,
https://www.terlici.com/2014/08/25/best-practices-express-structure.html.
APIs are simpler to design; they don't need a public or a views directory. Use the following structure to build APIs −
test-project/
node_modules/
config/
db.js //Database connection and configuration
credentials.js //Passwords/API keys for external services used by your app
models/ //For mongoose schemas
users.js
things.js
routes/ //All routes for different entities in different files
users.js
things.js
app.js
routes.js //Require all routes in this and then require this file in
app.js
package.json
You can also use a yeoman generator to get a similar structure.
16 Lectures
1 hours
Anadi Sharma
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2498,
"s": 2061,
"text": "Unlike Django and Rails which have a defined way of doing things, file structure, etc., Express does not follow a defined way. This means you can structure the application the way you like. But as your application grows in size, it is very difficult to maintain it if it doesn't have a well-defined structure. In this chapter, we will look at the generally used directory structures and separation of concerns to build our applications."
},
{
"code": null,
"e": 2584,
"s": 2498,
"text": "First, we will discuss the best practices for creating node and Express applications."
},
{
"code": null,
"e": 2628,
"s": 2584,
"text": "Always begin a node project using npm init."
},
{
"code": null,
"e": 2672,
"s": 2628,
"text": "Always begin a node project using npm init."
},
{
"code": null,
"e": 2846,
"s": 2672,
"text": "Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies."
},
{
"code": null,
"e": 3020,
"s": 2846,
"text": "Always install dependencies with a --save or --save-dev. This will ensure that if you move to a different platform, you can just run npm install to install all dependencies."
},
{
"code": null,
"e": 3209,
"s": 3020,
"text": "Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase."
},
{
"code": null,
"e": 3398,
"s": 3209,
"text": "Stick with lowercase file names and camelCase variables. If you look at any npm module, its named in lowercase and separated with dashes. Whenever you require these modules, use camelCase."
},
{
"code": null,
"e": 3501,
"s": 3398,
"text": "Don’t push node_modules to your repositories. Instead npm installs everything on development machines."
},
{
"code": null,
"e": 3604,
"s": 3501,
"text": "Don’t push node_modules to your repositories. Instead npm installs everything on development machines."
},
{
"code": null,
"e": 3641,
"s": 3604,
"text": "Use a config file to store variables"
},
{
"code": null,
"e": 3678,
"s": 3641,
"text": "Use a config file to store variables"
},
{
"code": null,
"e": 3811,
"s": 3678,
"text": "Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page."
},
{
"code": null,
"e": 3944,
"s": 3811,
"text": "Group and isolate routes to their own file. For example, take the CRUD operations in the movies example we saw in the REST API page."
},
{
"code": null,
"e": 3997,
"s": 3944,
"text": "Let us now discuss the Express’ Directory Structure."
},
{
"code": null,
"e": 4141,
"s": 3997,
"text": "Express does not have a community defined structure for creating applications. The following is a majorly used project structure for a website."
},
{
"code": null,
"e": 4869,
"s": 4141,
"text": "test-project/\n node_modules/\n config/\n db.js //Database connection and configuration\n credentials.js //Passwords/API keys for external services used by your app\n config.js //Other environment variables\n models/ //For mongoose schemas\n users.js\n things.js\n routes/ //All routes for different entities in different files \n users.js\n things.js\n views/\n index.pug\n 404.pug\n ...\n public/ //All static content being served\n images/\n css/\n javascript/\n app.js\n routes.js //Require all routes in this and then require this file in \n app.js \n package.json"
},
{
"code": null,
"e": 5047,
"s": 4869,
"text": "There are other approaches to build websites with Express as well. You can build a website using the MVC design pattern. For more information, you can visit the following links."
},
{
"code": null,
"e": 5138,
"s": 5047,
"text": "https://code.tutsplus.com/tutorials/build-a-complete-mvc-website-with-expressjs--net-34168"
},
{
"code": null,
"e": 5143,
"s": 5138,
"text": "and,"
},
{
"code": null,
"e": 5217,
"s": 5143,
"text": "https://www.terlici.com/2014/08/25/best-practices-express-structure.html."
},
{
"code": null,
"e": 5336,
"s": 5217,
"text": "APIs are simpler to design; they don't need a public or a views directory. Use the following structure to build APIs −"
},
{
"code": null,
"e": 5851,
"s": 5336,
"text": "test-project/\n node_modules/\n config/\n db.js //Database connection and configuration\n credentials.js //Passwords/API keys for external services used by your app\n models/ //For mongoose schemas\n users.js\n things.js\n routes/ //All routes for different entities in different files \n users.js\n things.js\n app.js\n routes.js //Require all routes in this and then require this file in \n app.js \n package.json"
},
{
"code": null,
"e": 5915,
"s": 5851,
"text": "You can also use a yeoman generator to get a similar structure."
},
{
"code": null,
"e": 5948,
"s": 5915,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5962,
"s": 5948,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 5969,
"s": 5962,
"text": " Print"
},
{
"code": null,
"e": 5980,
"s": 5969,
"text": " Add Notes"
}
] |
JavaScript | Pass string parameter in onClick function - GeeksforGeeks | 21 Jun, 2019
The task is to pass a string as a parameter on onClick function using javascript, we’re going to discuss few techniques.
Example 1: This example simply put the argument which is string in the onClick attribute of the button which calls a function with a string as an argument using onClick() method.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Pass string parameter in onClick function. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <button onclick="GFG_Fun('Parameter'); "> click here </button> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = 'Click on button to pass the '+ 'string parameter to the function'; function GFG_Fun(parameter) { down.innerHTML = "String '" + parameter + "' Received"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
Example 2: This example simply put the argument which is a string in the onClick attribute of the button which calls a function with string as an argument using onClick() method. Here the input button is created dynamically. This example uses the same approach as the previous one.
<!DOCTYPE HTML><html> <head> <title> JavaScript | Pass string parameter in onClick function. </title></head> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 19px; font-weight: bold;"> </p> <p id="GFG_DOWN" style="color: green; font-size: 24px; font-weight: bold;"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var inputEl = document.createElement('input'); inputEl.type = 'button'; inputEl.value = "Click here"; inputEl.addEventListener('click', function() { GFG_Fun('Parameter'); }); document.body.insertBefore(inputEl, down); up.innerHTML = 'Click on button to pass the '+ 'string parameter to the function'; function GFG_Fun(parameter) { down.innerHTML = "String '" + parameter + "' Received"; } </script></body> </html>
Output:
Before clicking on the button:
After clicking on the button:
JavaScript-Misc
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
Set the value of an input field in JavaScript
Difference Between PUT and PATCH Request
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 25024,
"s": 24996,
"text": "\n21 Jun, 2019"
},
{
"code": null,
"e": 25145,
"s": 25024,
"text": "The task is to pass a string as a parameter on onClick function using javascript, we’re going to discuss few techniques."
},
{
"code": null,
"e": 25324,
"s": 25145,
"text": "Example 1: This example simply put the argument which is string in the onClick attribute of the button which calls a function with a string as an argument using onClick() method."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Pass string parameter in onClick function. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <button onclick=\"GFG_Fun('Parameter'); \"> click here </button> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); up.innerHTML = 'Click on button to pass the '+ 'string parameter to the function'; function GFG_Fun(parameter) { down.innerHTML = \"String '\" + parameter + \"' Received\"; } </script></body> </html>",
"e": 26270,
"s": 25324,
"text": null
},
{
"code": null,
"e": 26278,
"s": 26270,
"text": "Output:"
},
{
"code": null,
"e": 26309,
"s": 26278,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 26339,
"s": 26309,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 26621,
"s": 26339,
"text": "Example 2: This example simply put the argument which is a string in the onClick attribute of the button which calls a function with string as an argument using onClick() method. Here the input button is created dynamically. This example uses the same approach as the previous one."
},
{
"code": "<!DOCTYPE HTML><html> <head> <title> JavaScript | Pass string parameter in onClick function. </title></head> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 19px; font-weight: bold;\"> </p> <p id=\"GFG_DOWN\" style=\"color: green; font-size: 24px; font-weight: bold;\"> </p> <script> var up = document.getElementById('GFG_UP'); var down = document.getElementById('GFG_DOWN'); var inputEl = document.createElement('input'); inputEl.type = 'button'; inputEl.value = \"Click here\"; inputEl.addEventListener('click', function() { GFG_Fun('Parameter'); }); document.body.insertBefore(inputEl, down); up.innerHTML = 'Click on button to pass the '+ 'string parameter to the function'; function GFG_Fun(parameter) { down.innerHTML = \"String '\" + parameter + \"' Received\"; } </script></body> </html>",
"e": 27738,
"s": 26621,
"text": null
},
{
"code": null,
"e": 27746,
"s": 27738,
"text": "Output:"
},
{
"code": null,
"e": 27777,
"s": 27746,
"text": "Before clicking on the button:"
},
{
"code": null,
"e": 27807,
"s": 27777,
"text": "After clicking on the button:"
},
{
"code": null,
"e": 27823,
"s": 27807,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27834,
"s": 27823,
"text": "JavaScript"
},
{
"code": null,
"e": 27851,
"s": 27834,
"text": "Web Technologies"
},
{
"code": null,
"e": 27949,
"s": 27851,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27958,
"s": 27949,
"text": "Comments"
},
{
"code": null,
"e": 27971,
"s": 27958,
"text": "Old Comments"
},
{
"code": null,
"e": 28032,
"s": 27971,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 28104,
"s": 28032,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28149,
"s": 28104,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28195,
"s": 28149,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 28236,
"s": 28195,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 28278,
"s": 28236,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 28311,
"s": 28278,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28373,
"s": 28311,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28416,
"s": 28373,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Bisect Algorithm Functions in Python | This module provides support for maintaining a list in sorted order without having to sort the list after each insertion of new element. We will focus on two functions namely insort_left and insort_right.
This function returns the sorted list after inserting number in the required position, if the element is already present in the list, the element is inserted at the leftmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered. The default value of the beginning and end position is 0 and length of the string respectively.
This is similar to inser_left except that the new element is inserted after inserting existing entries without maintaining a strict sort order.
bisect.insort_left(a, x, lo=0, hi=len(a))
bisect.insort_left(a, x, lo=0, hi=len(a))
a is the given sequence
x is the number to be inserted
In the example below we see that we take a list and first apply bisect.insort_left function to it.
Live Demo
import bisect
listA = [11,13,23,7,13,15]
print("Given list:",listA)
bisect.insort_left(listA,14)
print("Bisect left:\n",listA)
listB = [11,13,23,7,13,15]
print("Given list:",listB)
bisect.insort_right(listB,14,0,4)
print("Bisect righ:\n",listB)
Running the above code gives us the following result −
Given list: [11, 13, 23, 7, 13, 15]
Bisect left:
[11, 13, 23, 7, 13, 14, 15]
Given list: [11, 13, 23, 7, 13, 15]
Bisect righ:
[11, 13, 14, 23, 7, 13, 15] | [
{
"code": null,
"e": 1267,
"s": 1062,
"text": "This module provides support for maintaining a list in sorted order without having to sort the list after each insertion of new element. We will focus on two functions namely insort_left and insort_right."
},
{
"code": null,
"e": 1724,
"s": 1267,
"text": "This function returns the sorted list after inserting number in the required position, if the element is already present in the list, the element is inserted at the leftmost possible position. This function takes 4 arguments, list which has to be worked with, number to insert, starting position in list to consider, ending position which has to be considered. The default value of the beginning and end position is 0 and length of the string respectively."
},
{
"code": null,
"e": 1868,
"s": 1724,
"text": "This is similar to inser_left except that the new element is inserted after inserting existing entries without maintaining a strict sort order."
},
{
"code": null,
"e": 2007,
"s": 1868,
"text": "bisect.insort_left(a, x, lo=0, hi=len(a))\nbisect.insort_left(a, x, lo=0, hi=len(a))\na is the given sequence\nx is the number to be inserted"
},
{
"code": null,
"e": 2106,
"s": 2007,
"text": "In the example below we see that we take a list and first apply bisect.insort_left function to it."
},
{
"code": null,
"e": 2117,
"s": 2106,
"text": " Live Demo"
},
{
"code": null,
"e": 2364,
"s": 2117,
"text": "import bisect\n\nlistA = [11,13,23,7,13,15]\nprint(\"Given list:\",listA)\nbisect.insort_left(listA,14)\nprint(\"Bisect left:\\n\",listA)\n\nlistB = [11,13,23,7,13,15]\nprint(\"Given list:\",listB)\nbisect.insort_right(listB,14,0,4)\nprint(\"Bisect righ:\\n\",listB)"
},
{
"code": null,
"e": 2419,
"s": 2364,
"text": "Running the above code gives us the following result −"
},
{
"code": null,
"e": 2579,
"s": 2419,
"text": "Given list: [11, 13, 23, 7, 13, 15]\nBisect left:\n [11, 13, 23, 7, 13, 14, 15]\nGiven list: [11, 13, 23, 7, 13, 15]\nBisect righ:\n [11, 13, 14, 23, 7, 13, 15]"
}
] |
Matplotlib – How to set xticks and yticks with imshow plot? | To set xticks and yticks with imshow() plot, we can take the following steps −
Set the figure size and adjust the padding between and around the subplots.
Get the current axis.
Create a random dataset.
Display the data as an image, i.e., on a 2D regular raster.
Set x and y ticks using set_xticks() and set_yticks() method.
To display the figure, use show() method.
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
ax = plt.gca()
data = np.random.rand(6, 6)
ax.imshow(data)
# Set xticks and yticks
ax.set_xticks([1, 2, 3, 4, 5])
ax.set_yticks([1, 2, 3, 4, 5])
plt.show()
It will produce the following output | [
{
"code": null,
"e": 1141,
"s": 1062,
"text": "To set xticks and yticks with imshow() plot, we can take the following steps −"
},
{
"code": null,
"e": 1217,
"s": 1141,
"text": "Set the figure size and adjust the padding between and around the subplots."
},
{
"code": null,
"e": 1239,
"s": 1217,
"text": "Get the current axis."
},
{
"code": null,
"e": 1264,
"s": 1239,
"text": "Create a random dataset."
},
{
"code": null,
"e": 1324,
"s": 1264,
"text": "Display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1386,
"s": 1324,
"text": "Set x and y ticks using set_xticks() and set_yticks() method."
},
{
"code": null,
"e": 1428,
"s": 1386,
"text": "To display the figure, use show() method."
},
{
"code": null,
"e": 1726,
"s": 1428,
"text": "import numpy as np\nimport matplotlib.pyplot as plt\n\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\n\nax = plt.gca()\ndata = np.random.rand(6, 6)\nax.imshow(data)\n\n# Set xticks and yticks\nax.set_xticks([1, 2, 3, 4, 5])\nax.set_yticks([1, 2, 3, 4, 5])\n\nplt.show()"
},
{
"code": null,
"e": 1763,
"s": 1726,
"text": "It will produce the following output"
}
] |
How to remove only the first word from columns values with a MySQL query? | To remove only the first word from column values, use substring(). Following is the syntax −
select substring(yourColumnName,locate(' ',yourColumnName)+1) AS anyAliasName from yourTableName;
Let us first create a table −
mysql> create table DemoTable
(
Title text
);
Query OK, 0 rows affected (0.50 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable values('Java in Depth');
Query OK, 1 row affected (0.49 sec)
mysql> insert into DemoTable values('C++ is an object oriented programming language');
Query OK, 1 row affected (0.47 sec)
mysql> insert into DemoTable values('MySQL is a relational database');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('Python with data structure');
Query OK, 1 row affected (0.24 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable;
This will produce the following output −
+------------------------------------------------+
| Title |
+------------------------------------------------+
| Java in Depth |
| C++ is an object oriented programming language |
| MySQL is a relational database |
| Python with data structure |
+------------------------------------------------+
4 rows in set (0.00 sec)
Following is the query to remove the first word from column values −
mysql> select substring(Title,locate(' ',Title)+1) AS RemoveFirstWord from DemoTable;
This will produce the following output −
+--------------------------------------------+
| RemoveFirstWord |
+--------------------------------------------+
| in Depth |
| is an object oriented programming language |
| is a relational database |
| with data structure |
+--------------------------------------------+
4 rows in set (0.00 sec) | [
{
"code": null,
"e": 1155,
"s": 1062,
"text": "To remove only the first word from column values, use substring(). Following is the syntax −"
},
{
"code": null,
"e": 1253,
"s": 1155,
"text": "select substring(yourColumnName,locate(' ',yourColumnName)+1) AS anyAliasName from yourTableName;"
},
{
"code": null,
"e": 1283,
"s": 1253,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1369,
"s": 1283,
"text": "mysql> create table DemoTable\n(\n Title text\n);\nQuery OK, 0 rows affected (0.50 sec)"
},
{
"code": null,
"e": 1425,
"s": 1369,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1848,
"s": 1425,
"text": "mysql> insert into DemoTable values('Java in Depth');\nQuery OK, 1 row affected (0.49 sec)\nmysql> insert into DemoTable values('C++ is an object oriented programming language');\nQuery OK, 1 row affected (0.47 sec)\nmysql> insert into DemoTable values('MySQL is a relational database');\nQuery OK, 1 row affected (0.17 sec)\nmysql> insert into DemoTable values('Python with data structure');\nQuery OK, 1 row affected (0.24 sec)"
},
{
"code": null,
"e": 1908,
"s": 1848,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1939,
"s": 1908,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 1980,
"s": 1939,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 2413,
"s": 1980,
"text": "+------------------------------------------------+\n| Title |\n+------------------------------------------------+\n| Java in Depth |\n| C++ is an object oriented programming language |\n| MySQL is a relational database |\n| Python with data structure |\n+------------------------------------------------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2482,
"s": 2413,
"text": "Following is the query to remove the first word from column values −"
},
{
"code": null,
"e": 2568,
"s": 2482,
"text": "mysql> select substring(Title,locate(' ',Title)+1) AS RemoveFirstWord from DemoTable;"
},
{
"code": null,
"e": 2609,
"s": 2568,
"text": "This will produce the following output −"
},
{
"code": null,
"e": 3010,
"s": 2609,
"text": "+--------------------------------------------+\n| RemoveFirstWord |\n+--------------------------------------------+\n| in Depth |\n| is an object oriented programming language |\n| is a relational database |\n| with data structure |\n+--------------------------------------------+\n4 rows in set (0.00 sec)"
}
] |
List Comprehensions in Python | Towards Data Science | List is a built-in data structure in Python and a collection of data points in square brackets. Other built-in data structures in Python are set, tuple, and dictionary.
list_a = [4, 'data', 3.2, True]list_a[4, 'data', 3.2, True]
In this post, we will cover list comprehensions in python and their advantages. Although list comprehensions are highly practical, there are cases in which list comprehension is not the optimal choice. We will also go through situations when not to use list comprehensions.
List comprehension is basically creating lists based on existing lists. Following is a list comprehension that creates a list based on the lenghts of words in another list.
words = ['data', 'science', 'machine', 'learning']word_length = [len(i) for i in words]word_length[4, 7, 7, 8]
The basic syntax for the list comprehension is:
In the previous example, expression is len(i), item is the elements in “words” list represented by “i”. The iterable is, of course, the “words” list. We did not have a conditional statement but let’s do another one with a condition. For instance, the following list comprehension creates a list with the words with a length greater than 5.
words = ['data', 'science', 'machine', 'learning']long_words = [i for i in words if len(i) > 5]long_words['science', 'machine', 'learning']
Expression can be any expression that returns a value. Iterable can be any object that can iteratively return its elements such as a list, set, generator.
Conditionals are critical because they allow to filter out values or select only what we need.
For instance, the following piece of code creates a list consists of the squares of even numbers in range(20).
even_squares = [i*i for i in range(20) if i%2 == 0]even_squares[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]
We can create a list with the maximum numbers of rows of a matrix.
#Create a matriximport numpy as npA = np.random.randint(10, size=(4,4))Aarray([[1, 7, 4, 4], [5, 0, 0, 6], [7, 5, 8, 4], [1, 3, 2, 2]])#select the max of rowsmax_element = [max(i) for i in A]max_element[7, 6, 8, 3]
We can also put a condition on the expression. The following piece of code iterates over “words” list. It gets the words if the length is greater than 7. It writes “short word” instead of the elements whose length is not greater than 7.
words = ['data', 'science', 'artificial', 'intelligence', 'machine', 'learning']long_words = [i if len(i) > 7 else 'short word' for i in words]print(long_words)['short word', 'short word', 'artificial', 'intelligence', 'short word', 'learning']
What we do with list comprehensions can also be done with for loops or map function. Let’s do the first example using both for loop and map function:
#for loopword_length = []for word in words: word_length.append(len(word))word_length[4, 7, 7, 8]#map functionword_length = list(map(lambda x: len(x), words))word_length[4, 7, 7, 8]
The advantage to use list comprehensions:
They are relatively faster than for loops.
They are considered to be more pythonic than for loop and map function.
The syntax of list comprehension is easier to read and understand.
Let’s do a comparison by creating a list with the squares of first 50000 integers:
As we can see, the list comprehension is the fastest.
Note: Every list comprehension can be written using a for loop but not every for loop can be represented with a list comprehension.
List comprehension loads the entire output list into memory. This is acceptable or even desirable for small or medium-sized lists because it makes the operation faster. However, when we are working with large lists (e.g. 1 billion elements), list comprehension should be avoided. It may cause your computer to crash due to the extreme amount of memory requirement.
A better alternative for such large lists is using a generator which does not actually create a large data structure in memory. A generator creates items when they are used. After the items are used, generator throws them away. Using a generator, we can ask for the next item in an iterable until we reach the end and store a single value at a time.
The following generator sums the squares of first 10 million integers.
sum(i*i for i in range(10000000))333333283333335000000
Map function does not also cause a memory problem.
sum(map(lambda i: i*i, range(10000000)))333333283333335000000
There is no free lunch! Generators or map functions do not cause a memory issue but they’re relatively slower than list comprehensions. Similarly, the speed of list comprehensions comes from the excessive memory usage. You can decide on which one to use depending on your application.
Thank you for reading. Please let me know if you have any feedback. | [
{
"code": null,
"e": 341,
"s": 172,
"text": "List is a built-in data structure in Python and a collection of data points in square brackets. Other built-in data structures in Python are set, tuple, and dictionary."
},
{
"code": null,
"e": 401,
"s": 341,
"text": "list_a = [4, 'data', 3.2, True]list_a[4, 'data', 3.2, True]"
},
{
"code": null,
"e": 675,
"s": 401,
"text": "In this post, we will cover list comprehensions in python and their advantages. Although list comprehensions are highly practical, there are cases in which list comprehension is not the optimal choice. We will also go through situations when not to use list comprehensions."
},
{
"code": null,
"e": 848,
"s": 675,
"text": "List comprehension is basically creating lists based on existing lists. Following is a list comprehension that creates a list based on the lenghts of words in another list."
},
{
"code": null,
"e": 959,
"s": 848,
"text": "words = ['data', 'science', 'machine', 'learning']word_length = [len(i) for i in words]word_length[4, 7, 7, 8]"
},
{
"code": null,
"e": 1007,
"s": 959,
"text": "The basic syntax for the list comprehension is:"
},
{
"code": null,
"e": 1347,
"s": 1007,
"text": "In the previous example, expression is len(i), item is the elements in “words” list represented by “i”. The iterable is, of course, the “words” list. We did not have a conditional statement but let’s do another one with a condition. For instance, the following list comprehension creates a list with the words with a length greater than 5."
},
{
"code": null,
"e": 1487,
"s": 1347,
"text": "words = ['data', 'science', 'machine', 'learning']long_words = [i for i in words if len(i) > 5]long_words['science', 'machine', 'learning']"
},
{
"code": null,
"e": 1642,
"s": 1487,
"text": "Expression can be any expression that returns a value. Iterable can be any object that can iteratively return its elements such as a list, set, generator."
},
{
"code": null,
"e": 1737,
"s": 1642,
"text": "Conditionals are critical because they allow to filter out values or select only what we need."
},
{
"code": null,
"e": 1848,
"s": 1737,
"text": "For instance, the following piece of code creates a list consists of the squares of even numbers in range(20)."
},
{
"code": null,
"e": 1955,
"s": 1848,
"text": "even_squares = [i*i for i in range(20) if i%2 == 0]even_squares[0, 4, 16, 36, 64, 100, 144, 196, 256, 324]"
},
{
"code": null,
"e": 2022,
"s": 1955,
"text": "We can create a list with the maximum numbers of rows of a matrix."
},
{
"code": null,
"e": 2279,
"s": 2022,
"text": "#Create a matriximport numpy as npA = np.random.randint(10, size=(4,4))Aarray([[1, 7, 4, 4], [5, 0, 0, 6], [7, 5, 8, 4], [1, 3, 2, 2]])#select the max of rowsmax_element = [max(i) for i in A]max_element[7, 6, 8, 3]"
},
{
"code": null,
"e": 2516,
"s": 2279,
"text": "We can also put a condition on the expression. The following piece of code iterates over “words” list. It gets the words if the length is greater than 7. It writes “short word” instead of the elements whose length is not greater than 7."
},
{
"code": null,
"e": 2761,
"s": 2516,
"text": "words = ['data', 'science', 'artificial', 'intelligence', 'machine', 'learning']long_words = [i if len(i) > 7 else 'short word' for i in words]print(long_words)['short word', 'short word', 'artificial', 'intelligence', 'short word', 'learning']"
},
{
"code": null,
"e": 2911,
"s": 2761,
"text": "What we do with list comprehensions can also be done with for loops or map function. Let’s do the first example using both for loop and map function:"
},
{
"code": null,
"e": 3094,
"s": 2911,
"text": "#for loopword_length = []for word in words: word_length.append(len(word))word_length[4, 7, 7, 8]#map functionword_length = list(map(lambda x: len(x), words))word_length[4, 7, 7, 8]"
},
{
"code": null,
"e": 3136,
"s": 3094,
"text": "The advantage to use list comprehensions:"
},
{
"code": null,
"e": 3179,
"s": 3136,
"text": "They are relatively faster than for loops."
},
{
"code": null,
"e": 3251,
"s": 3179,
"text": "They are considered to be more pythonic than for loop and map function."
},
{
"code": null,
"e": 3318,
"s": 3251,
"text": "The syntax of list comprehension is easier to read and understand."
},
{
"code": null,
"e": 3401,
"s": 3318,
"text": "Let’s do a comparison by creating a list with the squares of first 50000 integers:"
},
{
"code": null,
"e": 3455,
"s": 3401,
"text": "As we can see, the list comprehension is the fastest."
},
{
"code": null,
"e": 3587,
"s": 3455,
"text": "Note: Every list comprehension can be written using a for loop but not every for loop can be represented with a list comprehension."
},
{
"code": null,
"e": 3952,
"s": 3587,
"text": "List comprehension loads the entire output list into memory. This is acceptable or even desirable for small or medium-sized lists because it makes the operation faster. However, when we are working with large lists (e.g. 1 billion elements), list comprehension should be avoided. It may cause your computer to crash due to the extreme amount of memory requirement."
},
{
"code": null,
"e": 4302,
"s": 3952,
"text": "A better alternative for such large lists is using a generator which does not actually create a large data structure in memory. A generator creates items when they are used. After the items are used, generator throws them away. Using a generator, we can ask for the next item in an iterable until we reach the end and store a single value at a time."
},
{
"code": null,
"e": 4373,
"s": 4302,
"text": "The following generator sums the squares of first 10 million integers."
},
{
"code": null,
"e": 4428,
"s": 4373,
"text": "sum(i*i for i in range(10000000))333333283333335000000"
},
{
"code": null,
"e": 4479,
"s": 4428,
"text": "Map function does not also cause a memory problem."
},
{
"code": null,
"e": 4541,
"s": 4479,
"text": "sum(map(lambda i: i*i, range(10000000)))333333283333335000000"
},
{
"code": null,
"e": 4826,
"s": 4541,
"text": "There is no free lunch! Generators or map functions do not cause a memory issue but they’re relatively slower than list comprehensions. Similarly, the speed of list comprehensions comes from the excessive memory usage. You can decide on which one to use depending on your application."
}
] |
Java Program to Find the closest pair from two sorted arrays | To find the closest pair from two sorted array, the Java code is as follows −
Live Demo
public class Demo {
void closest_pair(int my_arr_1[], int my_arr_2[], int arr_1_len, int arr_2_len, int sum){
int diff = Integer.MAX_VALUE;
int result_l = 0, result_r = 0;
int l = 0, r = arr_2_len-1;
while (l<arr_1_len && r>=0){
if (Math.abs(my_arr_1[l] + my_arr_2[r] - sum) < diff){
result_l = l;
result_r = r;
diff = Math.abs(my_arr_1[l] + my_arr_2[r] - result_l);
}
if (my_arr_1[l] + my_arr_2[r] > result_l)
r--;
else
l++;
}
System.out.print("The closest pair that matches two arrays is [" + my_arr_1[result_l] + ", " +
my_arr_2[result_r] + "]");
}
public static void main(String args[]){
Demo my_ob = new Demo();
int my_arr_1[] = {56, 78, 99, 11};
int my_arr_2[] = {33, 12, 69, 87};
int arr_1_len = my_arr_1.length;
int arr_2_len = my_arr_2.length;
int val = 79;
my_ob.closest_pair(my_arr_1, my_arr_2, arr_1_len, arr_2_len, val);
}
}
The closest pair that matches two arrays is [56, 33]
A class named Demo contains a function named ‘closest_pair’, that iterates through both the arrays and checks to see which sum adds up to a number that is very near to a number previously specified. This pair from the array is returned as output. In the main function, a new instance of the Demo class is defined, the arrays are defined, and their lengths are assigned to two variables respectively. The function is called by passing the arrays, their lengths, and the value. The relevant message is displayed on the console. | [
{
"code": null,
"e": 1140,
"s": 1062,
"text": "To find the closest pair from two sorted array, the Java code is as follows −"
},
{
"code": null,
"e": 1151,
"s": 1140,
"text": " Live Demo"
},
{
"code": null,
"e": 2177,
"s": 1151,
"text": "public class Demo {\n void closest_pair(int my_arr_1[], int my_arr_2[], int arr_1_len, int arr_2_len, int sum){\n int diff = Integer.MAX_VALUE;\n int result_l = 0, result_r = 0;\n int l = 0, r = arr_2_len-1;\n while (l<arr_1_len && r>=0){\n if (Math.abs(my_arr_1[l] + my_arr_2[r] - sum) < diff){\n result_l = l;\n result_r = r;\n diff = Math.abs(my_arr_1[l] + my_arr_2[r] - result_l);\n }\n if (my_arr_1[l] + my_arr_2[r] > result_l)\n r--;\n else\n l++;\n }\n System.out.print(\"The closest pair that matches two arrays is [\" + my_arr_1[result_l] + \", \" +\n my_arr_2[result_r] + \"]\");\n }\n public static void main(String args[]){\n Demo my_ob = new Demo();\n int my_arr_1[] = {56, 78, 99, 11};\n int my_arr_2[] = {33, 12, 69, 87};\n int arr_1_len = my_arr_1.length;\n int arr_2_len = my_arr_2.length;\n int val = 79;\n my_ob.closest_pair(my_arr_1, my_arr_2, arr_1_len, arr_2_len, val);\n }\n}"
},
{
"code": null,
"e": 2230,
"s": 2177,
"text": "The closest pair that matches two arrays is [56, 33]"
},
{
"code": null,
"e": 2756,
"s": 2230,
"text": "A class named Demo contains a function named ‘closest_pair’, that iterates through both the arrays and checks to see which sum adds up to a number that is very near to a number previously specified. This pair from the array is returned as output. In the main function, a new instance of the Demo class is defined, the arrays are defined, and their lengths are assigned to two variables respectively. The function is called by passing the arrays, their lengths, and the value. The relevant message is displayed on the console."
}
] |
Defining a discrete colormap for imshow in Matplotlib | To define a discrete colormap for imshow in matplotlib, we can take following the steps −
Create data using numpy.
Create data using numpy.
Initialize the data using get_cmap, so that scatter knows.
Initialize the data using get_cmap, so that scatter knows.
Using imshow() method with colormap, display the data as an image, i.e., on a 2D regular raster.
Using imshow() method with colormap, display the data as an image, i.e., on a 2D regular raster.
Create the colorbar using the colorbar() method.
Create the colorbar using the colorbar() method.
To display the figure, use the show() method.
To display the figure, use the show() method.
import numpy as np
from matplotlib import pyplot as plt
import matplotlib
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
data = np.random.rand(10, 10)
cmap = matplotlib.cm.get_cmap('Paired_r', 10)
plt.imshow(data, cmap=cmap)
plt.colorbar()
plt.show() | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "To define a discrete colormap for imshow in matplotlib, we can take following the steps −"
},
{
"code": null,
"e": 1177,
"s": 1152,
"text": "Create data using numpy."
},
{
"code": null,
"e": 1202,
"s": 1177,
"text": "Create data using numpy."
},
{
"code": null,
"e": 1261,
"s": 1202,
"text": "Initialize the data using get_cmap, so that scatter knows."
},
{
"code": null,
"e": 1320,
"s": 1261,
"text": "Initialize the data using get_cmap, so that scatter knows."
},
{
"code": null,
"e": 1417,
"s": 1320,
"text": "Using imshow() method with colormap, display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1514,
"s": 1417,
"text": "Using imshow() method with colormap, display the data as an image, i.e., on a 2D regular raster."
},
{
"code": null,
"e": 1563,
"s": 1514,
"text": "Create the colorbar using the colorbar() method."
},
{
"code": null,
"e": 1612,
"s": 1563,
"text": "Create the colorbar using the colorbar() method."
},
{
"code": null,
"e": 1658,
"s": 1612,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1704,
"s": 1658,
"text": "To display the figure, use the show() method."
},
{
"code": null,
"e": 1995,
"s": 1704,
"text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport matplotlib\nplt.rcParams[\"figure.figsize\"] = [7.50, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\ndata = np.random.rand(10, 10)\ncmap = matplotlib.cm.get_cmap('Paired_r', 10)\nplt.imshow(data, cmap=cmap)\nplt.colorbar()\nplt.show()"
}
] |
How to clear an ImageView in Android using Kotlin? | This example demonstrates how to clear an ImageView in Android using Kotlin.
Step 1 − Create a new project in Android Studio, go to File? New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:onClick="clickHere"
android:text="Click here" />
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="@+id/button"
android:layout_centerInParent="true"
android:background="@drawable/image" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.kt
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.ImageView
import android.widget.Toast
class MainActivity : AppCompatActivity() {
lateinit var imageView: ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
title = "KotlinApp"
imageView = findViewById(R.id.imageView)
}
fun clickHere(view: View) {
imageView.setBackgroundDrawable(null)
Toast.makeText(this, "Image cleared", Toast.LENGTH_SHORT).show()
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code. | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "This example demonstrates how to clear an ImageView in Android using Kotlin."
},
{
"code": null,
"e": 1267,
"s": 1139,
"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": 1332,
"s": 1267,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml."
},
{
"code": null,
"e": 2167,
"s": 1332,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n<Button\n android:id=\"@+id/button\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_alignParentBottom=\"true\"\n android:layout_centerHorizontal=\"true\"\n android:layout_marginTop=\"10dp\"\n android:onClick=\"clickHere\"\n android:text=\"Click here\" />\n<ImageView\n android:id=\"@+id/imageView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_above=\"@+id/button\"\n android:layout_centerInParent=\"true\"\n android:background=\"@drawable/image\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2222,
"s": 2167,
"text": "Step 3 − Add the following code to src/MainActivity.kt"
},
{
"code": null,
"e": 2833,
"s": 2222,
"text": "import androidx.appcompat.app.AppCompatActivity\nimport android.os.Bundle\nimport android.view.View\nimport android.widget.ImageView\nimport android.widget.Toast\nclass MainActivity : AppCompatActivity() {\n lateinit var imageView: ImageView\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n imageView = findViewById(R.id.imageView)\n }\n fun clickHere(view: View) {\n imageView.setBackgroundDrawable(null)\n Toast.makeText(this, \"Image cleared\", Toast.LENGTH_SHORT).show()\n }\n}"
},
{
"code": null,
"e": 2888,
"s": 2833,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3559,
"s": 2888,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.example.q11\">\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": 3907,
"s": 3559,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 3948,
"s": 3907,
"text": "Click here to download the project code."
}
] |
Python - Extract words starting with K in String List - GeeksforGeeks | 01 Aug, 2020
Given list of phrases, extract all the Strings with begin with character K.
Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = lOutput : [‘learning’, ‘love’]Explanation : All elements with L as starting letter are extracted.
Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = mOutput : []Explanation : No words started from “m” hence no word extracted.
Method #1 : Using loop + split()
This is brute way in which this problem can be solved. In this, we convert each phrase into list of words and then for each word, check if it’s initial character is K.
Python3
# Python3 code to demonstrate working of # Extract words starting with K in String List# Using loop + split() # initializing listtest_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = "g" res = []for sub in test_list: # splitting phrases temp = sub.split() for ele in temp: # checking for matching elements if ele[0].lower() == K.lower(): res.append(ele) # printing result print("The filtered elements : " + str(res))
The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']
Method #2 : Using list comprehension + split()
This is yet another way in which this task can be performed. In this we run double nested loops inside single list comprehension and perform required conditional checks.
Python3
# Python3 code to demonstrate working of # Extract words starting with K in String List# Using list comprehension + split() # initializing listtest_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"] # printing original listprint("The original list is : " + str(test_list)) # initializing K K = "g"res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()] # printing result print("The filtered elements : " + str(res))
The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']
Python list-programs
Python string-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Python program to convert a list to string
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary | [
{
"code": null,
"e": 24541,
"s": 24513,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 24617,
"s": 24541,
"text": "Given list of phrases, extract all the Strings with begin with character K."
},
{
"code": null,
"e": 24803,
"s": 24617,
"text": "Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = lOutput : [‘learning’, ‘love’]Explanation : All elements with L as starting letter are extracted."
},
{
"code": null,
"e": 24968,
"s": 24803,
"text": "Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = mOutput : []Explanation : No words started from “m” hence no word extracted."
},
{
"code": null,
"e": 25001,
"s": 24968,
"text": "Method #1 : Using loop + split()"
},
{
"code": null,
"e": 25170,
"s": 25001,
"text": "This is brute way in which this problem can be solved. In this, we convert each phrase into list of words and then for each word, check if it’s initial character is K. "
},
{
"code": null,
"e": 25178,
"s": 25170,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract words starting with K in String List# Using loop + split() # initializing listtest_list = [\"Gfg is best\", \"Gfg is for geeks\", \"I love G4G\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = \"g\" res = []for sub in test_list: # splitting phrases temp = sub.split() for ele in temp: # checking for matching elements if ele[0].lower() == K.lower(): res.append(ele) # printing result print(\"The filtered elements : \" + str(res))",
"e": 25748,
"s": 25178,
"text": null
},
{
"code": null,
"e": 25878,
"s": 25748,
"text": "The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']\nThe filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']\n\n"
},
{
"code": null,
"e": 25926,
"s": 25878,
"text": "Method #2 : Using list comprehension + split() "
},
{
"code": null,
"e": 26096,
"s": 25926,
"text": "This is yet another way in which this task can be performed. In this we run double nested loops inside single list comprehension and perform required conditional checks."
},
{
"code": null,
"e": 26104,
"s": 26096,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of # Extract words starting with K in String List# Using list comprehension + split() # initializing listtest_list = [\"Gfg is best\", \"Gfg is for geeks\", \"I love G4G\"] # printing original listprint(\"The original list is : \" + str(test_list)) # initializing K K = \"g\"res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()] # printing result print(\"The filtered elements : \" + str(res))",
"e": 26565,
"s": 26104,
"text": null
},
{
"code": null,
"e": 26695,
"s": 26565,
"text": "The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']\nThe filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']\n\n"
},
{
"code": null,
"e": 26716,
"s": 26695,
"text": "Python list-programs"
},
{
"code": null,
"e": 26739,
"s": 26716,
"text": "Python string-programs"
},
{
"code": null,
"e": 26746,
"s": 26739,
"text": "Python"
},
{
"code": null,
"e": 26762,
"s": 26746,
"text": "Python Programs"
},
{
"code": null,
"e": 26860,
"s": 26762,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26869,
"s": 26860,
"text": "Comments"
},
{
"code": null,
"e": 26882,
"s": 26869,
"text": "Old Comments"
},
{
"code": null,
"e": 26900,
"s": 26882,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26935,
"s": 26900,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26957,
"s": 26935,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26989,
"s": 26957,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27019,
"s": 26989,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27062,
"s": 27019,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27084,
"s": 27062,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27123,
"s": 27084,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27169,
"s": 27123,
"text": "Python | Split string into list of characters"
}
] |
Check if binary representations of two numbers are anagram in Python | Suppose we have two numbers x and y we have to check whether the binary representation of x and y are anagram of each other or not.
So, if the input is like x = 9 y = 12, then the output will be True as binary representation of 9 is 1001 and binary representation of 12 is 1100, so these two are anagram of each other.
To solve this, we will follow these steps −
if number of 1s in x and y are same, thenreturn True
return True
return False
Let us see the following implementation to get better understanding −
Live Demo
def set_bit_count(num) :
cnt = 0
while num:
cnt += num & 1
num >>= 1
return cnt
def solve(x, y) :
if set_bit_count(x) == set_bit_count(y):
return True
return False
x = 9
y = 12
print(solve(x, y))
9, 12
True | [
{
"code": null,
"e": 1194,
"s": 1062,
"text": "Suppose we have two numbers x and y we have to check whether the binary representation of x and y are anagram of each other or not."
},
{
"code": null,
"e": 1381,
"s": 1194,
"text": "So, if the input is like x = 9 y = 12, then the output will be True as binary representation of 9 is 1001 and binary representation of 12 is 1100, so these two are anagram of each other."
},
{
"code": null,
"e": 1425,
"s": 1381,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1478,
"s": 1425,
"text": "if number of 1s in x and y are same, thenreturn True"
},
{
"code": null,
"e": 1490,
"s": 1478,
"text": "return True"
},
{
"code": null,
"e": 1503,
"s": 1490,
"text": "return False"
},
{
"code": null,
"e": 1573,
"s": 1503,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1584,
"s": 1573,
"text": " Live Demo"
},
{
"code": null,
"e": 1813,
"s": 1584,
"text": "def set_bit_count(num) :\n cnt = 0\n while num:\n cnt += num & 1\n num >>= 1\n return cnt\ndef solve(x, y) :\n if set_bit_count(x) == set_bit_count(y):\n return True\n return False\nx = 9\ny = 12\nprint(solve(x, y))"
},
{
"code": null,
"e": 1819,
"s": 1813,
"text": "9, 12"
},
{
"code": null,
"e": 1824,
"s": 1819,
"text": "True"
}
] |
How to find set difference between two Numpy arrays? | In this program, we will find the set difference of two numpy arrays. We will use the setdiff1d() function in the numpy library. This function takes two parameters: array1 and array2 and returns the unique values in array1 that are not in array2.
Step 1: Import numpy.
Step 2: Define two numpy arrays.
Step 3: Find the set difference between these arrays using the setdiff1d() function.
Step 4: Print the output.
import numpy as np
array_1 = np.array([2,4,6,8,10,12])
print("Array 1: \n", array_1)
array_2 = np.array([4,8,12])
print("\nArray 2: \n", array_2)
set_diff = np.setdiff1d(array_1, array_2)
print("\nThe set difference between array_1 and array_2 is:\n",set_diff)
Array 1:
[ 2 4 6 8 10 12]
Array 2:
[ 4 8 12]
The set difference between array_1 and array_2 is:
[ 2 6 10]
Array 1 has elements 2, 6, and 10 which are not in Array 2. Hence [2 6 10] are is the set difference between the two arrays. | [
{
"code": null,
"e": 1309,
"s": 1062,
"text": "In this program, we will find the set difference of two numpy arrays. We will use the setdiff1d() function in the numpy library. This function takes two parameters: array1 and array2 and returns the unique values in array1 that are not in array2."
},
{
"code": null,
"e": 1475,
"s": 1309,
"text": "Step 1: Import numpy.\nStep 2: Define two numpy arrays.\nStep 3: Find the set difference between these arrays using the setdiff1d() function.\nStep 4: Print the output."
},
{
"code": null,
"e": 1739,
"s": 1475,
"text": "import numpy as np\n\narray_1 = np.array([2,4,6,8,10,12])\nprint(\"Array 1: \\n\", array_1)\n\narray_2 = np.array([4,8,12])\nprint(\"\\nArray 2: \\n\", array_2)\n\nset_diff = np.setdiff1d(array_1, array_2)\nprint(\"\\nThe set difference between array_1 and array_2 is:\\n\",set_diff)"
},
{
"code": null,
"e": 1850,
"s": 1739,
"text": "Array 1:\n[ 2 4 6 8 10 12]\nArray 2:\n[ 4 8 12]\nThe set difference between array_1 and array_2 is:\n[ 2 6 10]"
},
{
"code": null,
"e": 1975,
"s": 1850,
"text": "Array 1 has elements 2, 6, and 10 which are not in Array 2. Hence [2 6 10] are is the set difference between the two arrays."
}
] |
How to expire session after 1 min of inactivity in express-session of Express.js ? - GeeksforGeeks | 09 Sep, 2021
In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js.
Prerequisites
Installation of Node.js on Windows
To set up Node Project in Editor see here.
Requires Modules:
npm install express
npm install express-session
Call API:
var session = require('express-session')
To expire the session after 1 min of inactivity in express-session of Express.js we use expires: 60000 in the middleware function.
Project Structure:
Below example illustrates above approach:
Example:
Filename: app.js
Javascript
// Call Express Api.var express = require('express'), // Call express Session Api. session = require('express-session'), app = express(); // Session Setupapp.use( session({ // It holds the secret key for session secret: "I am girl", // Forces the session to be saved // back to the session store resave: true, // Forces a session that is "uninitialized" // to be saved to the store saveUninitialized: false, cookie: { // Session expires after 1 min of inactivity. expires: 60000 } })); // Get function in which send session as routes.app.get('/session', function (req, res, next) { if (req.session.views) { // Increment the number of views. req.session.views++ // Session will expires after 1 min // of in activity res.write('<p> Session expires after 1 min of in activity: '+ (req.session.cookie.expires) + '</p>') res.end() } else { req.session.views = 1 res.end(' New session is started') }}) // The server object listens on port 3000.app.listen(3000, function () { console.log("Express Started on Port 3000");});
Run index.js file using below command:
node app.js
Now to set your session, just open the browser and type this URL :
http://localhost:3000/session
Output: After 1 min of inactivity it will start the new session,old session is expired.
sagartomar9927
Express.js
NodeJS-Questions
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Installation of Node.js on Linux
How to update Node.js and NPM to next version ?
Node.js fs.readFileSync() Method
Node.js fs.readFile() Method
How to update NPM ?
Top 10 Front End Developer Skills That You Need in 2022
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 29225,
"s": 29197,
"text": "\n09 Sep, 2021"
},
{
"code": null,
"e": 29340,
"s": 29225,
"text": "In this article, we will see how to expire the session after 1 min of inactivity in express-session of Express.js."
},
{
"code": null,
"e": 29354,
"s": 29340,
"text": "Prerequisites"
},
{
"code": null,
"e": 29389,
"s": 29354,
"text": "Installation of Node.js on Windows"
},
{
"code": null,
"e": 29432,
"s": 29389,
"text": "To set up Node Project in Editor see here."
},
{
"code": null,
"e": 29450,
"s": 29432,
"text": "Requires Modules:"
},
{
"code": null,
"e": 29498,
"s": 29450,
"text": "npm install express\nnpm install express-session"
},
{
"code": null,
"e": 29508,
"s": 29498,
"text": "Call API:"
},
{
"code": null,
"e": 29549,
"s": 29508,
"text": "var session = require('express-session')"
},
{
"code": null,
"e": 29680,
"s": 29549,
"text": "To expire the session after 1 min of inactivity in express-session of Express.js we use expires: 60000 in the middleware function."
},
{
"code": null,
"e": 29699,
"s": 29680,
"text": "Project Structure:"
},
{
"code": null,
"e": 29741,
"s": 29699,
"text": "Below example illustrates above approach:"
},
{
"code": null,
"e": 29750,
"s": 29741,
"text": "Example:"
},
{
"code": null,
"e": 29767,
"s": 29750,
"text": "Filename: app.js"
},
{
"code": null,
"e": 29778,
"s": 29767,
"text": "Javascript"
},
{
"code": "// Call Express Api.var express = require('express'), // Call express Session Api. session = require('express-session'), app = express(); // Session Setupapp.use( session({ // It holds the secret key for session secret: \"I am girl\", // Forces the session to be saved // back to the session store resave: true, // Forces a session that is \"uninitialized\" // to be saved to the store saveUninitialized: false, cookie: { // Session expires after 1 min of inactivity. expires: 60000 } })); // Get function in which send session as routes.app.get('/session', function (req, res, next) { if (req.session.views) { // Increment the number of views. req.session.views++ // Session will expires after 1 min // of in activity res.write('<p> Session expires after 1 min of in activity: '+ (req.session.cookie.expires) + '</p>') res.end() } else { req.session.views = 1 res.end(' New session is started') }}) // The server object listens on port 3000.app.listen(3000, function () { console.log(\"Express Started on Port 3000\");});",
"e": 30979,
"s": 29778,
"text": null
},
{
"code": null,
"e": 31018,
"s": 30979,
"text": "Run index.js file using below command:"
},
{
"code": null,
"e": 31030,
"s": 31018,
"text": "node app.js"
},
{
"code": null,
"e": 31097,
"s": 31030,
"text": "Now to set your session, just open the browser and type this URL :"
},
{
"code": null,
"e": 31129,
"s": 31097,
"text": "http://localhost:3000/session\n "
},
{
"code": null,
"e": 31217,
"s": 31129,
"text": "Output: After 1 min of inactivity it will start the new session,old session is expired."
},
{
"code": null,
"e": 31232,
"s": 31217,
"text": "sagartomar9927"
},
{
"code": null,
"e": 31243,
"s": 31232,
"text": "Express.js"
},
{
"code": null,
"e": 31260,
"s": 31243,
"text": "NodeJS-Questions"
},
{
"code": null,
"e": 31267,
"s": 31260,
"text": "Picked"
},
{
"code": null,
"e": 31275,
"s": 31267,
"text": "Node.js"
},
{
"code": null,
"e": 31292,
"s": 31275,
"text": "Web Technologies"
},
{
"code": null,
"e": 31390,
"s": 31292,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31399,
"s": 31390,
"text": "Comments"
},
{
"code": null,
"e": 31412,
"s": 31399,
"text": "Old Comments"
},
{
"code": null,
"e": 31445,
"s": 31412,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31493,
"s": 31445,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 31526,
"s": 31493,
"text": "Node.js fs.readFileSync() Method"
},
{
"code": null,
"e": 31555,
"s": 31526,
"text": "Node.js fs.readFile() Method"
},
{
"code": null,
"e": 31575,
"s": 31555,
"text": "How to update NPM ?"
},
{
"code": null,
"e": 31631,
"s": 31575,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 31664,
"s": 31631,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 31726,
"s": 31664,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 31769,
"s": 31726,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
Guide to implementing Linear Regression in Pyspark and R | by Kieran Tan Kah Wang | Towards Data Science | Which programming tool should I use to build my Linear Regression model? Is there any differences in terms of the prediction accuracy? Which is simpler to implement with just a few lines of codes? Does the size of my training data plays a difference? Let’s explore all these questions in this article.
The dataset I’ve used is a dummy dataset which contains just two variables, YearsExperience and Salary. We are trying to find out if the salary of an employee is linearly dependent on the number of years of work experience the employee has, and logically, we will expect such a relationship to exists.
We will make use of Pyspark to train our Linear Regression model in Python as Pyspark has the ability to scale up data processing speed which is highly valued in the world of big data. As this article focused more on implementing Linear Regression model, I will not be touching on the technical aspects in setting up Pyspark (i.e. SparkContext, SparkSession, SparkConf) which you can find in my previous post.
from pyspark import SQLContext, SparkConf, SparkContextfrom pyspark.sql import SparkSessionsc = SparkContext.getOrCreate()if (sc is None): sc = SparkContext(master="local[*]", appName="Linear Regression")spark = SparkSession(sparkContext=sc)sqlcontext = SQLContext(sc)data = sqlcontext.read.csv('./Salary_Data.csv', header = True, inferSchema = True)
Once we get the data into Pyspark, we will need to tell it which is our feature variables and which is our target variable. For this dataset, it’s quite straightforward that YearsExperience is our feature variable while Salary is our target variable. We have our data, and we are going to build our model, but how do we know if our model performs well or not? Splitting our dataset into training and testing data is one way to do it among data scientists, and the usual ratio is 70:30 or 80:20. Another thing to note in implementing machine learning algorithms in Pyspark is that we can make use of vector assembler, which combine all features into a sparse single vector that greatly reduce the training time for machine learning models.
from pyspark.ml.feature import VectorAssembler# defining Salary as our label/predictor variabledataset = data.select(data.YearsExperience, data.Salary.alias('label'))# split data into 70% training and 30% testing datatraining, test = dataset.randomSplit([0.7, 0.3], seed = 100)# assembler to assemble the features into vector formassembler = VectorAssembler().setInputCols(['YearsExperience',]).setOutputCol('features')trainingSet = assembler.transform(training)# select only features column and label column since we have already vectorised our featurestrainingSet = trainingSet.select("features","label")
Finally, we are ready to train a Linear Regression model using our training dataset. And as mentioned above, we will also make use of a testing dataset to know how well our model performed. As seen in the output below, our model now contains a prediction column which contains the predicted salary when we fit our feature column (i.e. YearsExperience) as testing dataset into our Linear Regression model. We can see that some predicted values are close to the actual values, while some are not.
from pyspark.ml.regression import LinearRegression# fit the training set to linear regression modellr = LinearRegression()lr_Model = lr.fit(trainingSet)# assembler to assemble the features into vector formtestSet = assembler.transform(test)# select only features column and label column since we have already vectorised our featurestestSet = testSet.select("features", "label")# fit the testing data into our linear regression modeltestSet = lr_Model.transform(testSet)testSet.show(truncate=False)
So how do we measure how well our Linear Regression model performed? We can make use of R2, which is a measure of the goodness of fit between a value of 0 to 100%. We can implement in Pyspark easily with just 2 lines of code.
from pyspark.ml.evaluation import RegressionEvaluatorevaluator = RegressionEvaluator()print(evaluator.evaluate(testSet, {evaluator.metricName: "r2"}))
A R2 value of 93.9% suggests that our Linear Regression has performed significantly well in terms of predicting Salary when we fit our trained model using YearsExperience.
Now, let’s build our Linear Regression model in R. We split the data into 70% training data and 30% testing data as what we have did in Pyspark. Whereas, let’s try to use the same testing data as we used in Pyspark to see if there’s any difference in R2 performance in the model’s predictions.
data = read.csv("./Salary_Data.csv")# sample data# set.seed(100)# dt = sort(sample(nrow(data), nrow(data)*.7))dt = c(5,8,9,10,16,19,20,22,26,27)# split data into training and testing datatrainingSet<-data[-dt,]testingSet<-data[dt,]
After obtaining the training and testing dataset, we train our Linear Regression model with the training dataset and predict the Salary using the testing dataset.
# fit linear regression modellm_model = lm(data = trainingSet, Salary~.)# predict the target variable with testing datapredicted_salary = predict(lm_model, testingSet)
Then, we measure the goodness of fit on our predicted values by calculating R2. Note that in R, there’s no libraries or commands we can run to directly get R2. Hence, we have to calculate them manually by obtaining the residual sum of squares and total sum of squares which can further explored here.
# residual sum of squaresrss <- sum((predicted_salary - testingSet$Salary) ^ 2) # total sum of squarestss <- sum((testingSet$Salary - mean(testingSet$Salary)) ^ 2) # obtain r^2rsq <- 1 - rss/tssrsq
We obtained the same R2 as we did in Pyspark, which means in terms of accuracy of models, choosing Pyspark or R to train your model does not matter. And it might seem obvious that training Linear Regression model in R is a lot more simpler than in Pyspark. Whereas, a point to note is that Pyspark is more preferable in terms of training big data and the processing speed will be significantly faster than in R itself.
Here’s my recommendation when it comes to deciding between R or Pyspark in building Linear Regression model:
Pyspark -> Suitable for processing large amount of data
R -> Suitable for easy implementation
Thanks for reading and I will look into several other Machine Learning algorithms over my next few posts, cheers! | [
{
"code": null,
"e": 473,
"s": 171,
"text": "Which programming tool should I use to build my Linear Regression model? Is there any differences in terms of the prediction accuracy? Which is simpler to implement with just a few lines of codes? Does the size of my training data plays a difference? Let’s explore all these questions in this article."
},
{
"code": null,
"e": 775,
"s": 473,
"text": "The dataset I’ve used is a dummy dataset which contains just two variables, YearsExperience and Salary. We are trying to find out if the salary of an employee is linearly dependent on the number of years of work experience the employee has, and logically, we will expect such a relationship to exists."
},
{
"code": null,
"e": 1185,
"s": 775,
"text": "We will make use of Pyspark to train our Linear Regression model in Python as Pyspark has the ability to scale up data processing speed which is highly valued in the world of big data. As this article focused more on implementing Linear Regression model, I will not be touching on the technical aspects in setting up Pyspark (i.e. SparkContext, SparkSession, SparkConf) which you can find in my previous post."
},
{
"code": null,
"e": 1539,
"s": 1185,
"text": "from pyspark import SQLContext, SparkConf, SparkContextfrom pyspark.sql import SparkSessionsc = SparkContext.getOrCreate()if (sc is None): sc = SparkContext(master=\"local[*]\", appName=\"Linear Regression\")spark = SparkSession(sparkContext=sc)sqlcontext = SQLContext(sc)data = sqlcontext.read.csv('./Salary_Data.csv', header = True, inferSchema = True)"
},
{
"code": null,
"e": 2278,
"s": 1539,
"text": "Once we get the data into Pyspark, we will need to tell it which is our feature variables and which is our target variable. For this dataset, it’s quite straightforward that YearsExperience is our feature variable while Salary is our target variable. We have our data, and we are going to build our model, but how do we know if our model performs well or not? Splitting our dataset into training and testing data is one way to do it among data scientists, and the usual ratio is 70:30 or 80:20. Another thing to note in implementing machine learning algorithms in Pyspark is that we can make use of vector assembler, which combine all features into a sparse single vector that greatly reduce the training time for machine learning models."
},
{
"code": null,
"e": 2885,
"s": 2278,
"text": "from pyspark.ml.feature import VectorAssembler# defining Salary as our label/predictor variabledataset = data.select(data.YearsExperience, data.Salary.alias('label'))# split data into 70% training and 30% testing datatraining, test = dataset.randomSplit([0.7, 0.3], seed = 100)# assembler to assemble the features into vector formassembler = VectorAssembler().setInputCols(['YearsExperience',]).setOutputCol('features')trainingSet = assembler.transform(training)# select only features column and label column since we have already vectorised our featurestrainingSet = trainingSet.select(\"features\",\"label\")"
},
{
"code": null,
"e": 3380,
"s": 2885,
"text": "Finally, we are ready to train a Linear Regression model using our training dataset. And as mentioned above, we will also make use of a testing dataset to know how well our model performed. As seen in the output below, our model now contains a prediction column which contains the predicted salary when we fit our feature column (i.e. YearsExperience) as testing dataset into our Linear Regression model. We can see that some predicted values are close to the actual values, while some are not."
},
{
"code": null,
"e": 3878,
"s": 3380,
"text": "from pyspark.ml.regression import LinearRegression# fit the training set to linear regression modellr = LinearRegression()lr_Model = lr.fit(trainingSet)# assembler to assemble the features into vector formtestSet = assembler.transform(test)# select only features column and label column since we have already vectorised our featurestestSet = testSet.select(\"features\", \"label\")# fit the testing data into our linear regression modeltestSet = lr_Model.transform(testSet)testSet.show(truncate=False)"
},
{
"code": null,
"e": 4104,
"s": 3878,
"text": "So how do we measure how well our Linear Regression model performed? We can make use of R2, which is a measure of the goodness of fit between a value of 0 to 100%. We can implement in Pyspark easily with just 2 lines of code."
},
{
"code": null,
"e": 4255,
"s": 4104,
"text": "from pyspark.ml.evaluation import RegressionEvaluatorevaluator = RegressionEvaluator()print(evaluator.evaluate(testSet, {evaluator.metricName: \"r2\"}))"
},
{
"code": null,
"e": 4427,
"s": 4255,
"text": "A R2 value of 93.9% suggests that our Linear Regression has performed significantly well in terms of predicting Salary when we fit our trained model using YearsExperience."
},
{
"code": null,
"e": 4721,
"s": 4427,
"text": "Now, let’s build our Linear Regression model in R. We split the data into 70% training data and 30% testing data as what we have did in Pyspark. Whereas, let’s try to use the same testing data as we used in Pyspark to see if there’s any difference in R2 performance in the model’s predictions."
},
{
"code": null,
"e": 4953,
"s": 4721,
"text": "data = read.csv(\"./Salary_Data.csv\")# sample data# set.seed(100)# dt = sort(sample(nrow(data), nrow(data)*.7))dt = c(5,8,9,10,16,19,20,22,26,27)# split data into training and testing datatrainingSet<-data[-dt,]testingSet<-data[dt,]"
},
{
"code": null,
"e": 5116,
"s": 4953,
"text": "After obtaining the training and testing dataset, we train our Linear Regression model with the training dataset and predict the Salary using the testing dataset."
},
{
"code": null,
"e": 5284,
"s": 5116,
"text": "# fit linear regression modellm_model = lm(data = trainingSet, Salary~.)# predict the target variable with testing datapredicted_salary = predict(lm_model, testingSet)"
},
{
"code": null,
"e": 5585,
"s": 5284,
"text": "Then, we measure the goodness of fit on our predicted values by calculating R2. Note that in R, there’s no libraries or commands we can run to directly get R2. Hence, we have to calculate them manually by obtaining the residual sum of squares and total sum of squares which can further explored here."
},
{
"code": null,
"e": 5783,
"s": 5585,
"text": "# residual sum of squaresrss <- sum((predicted_salary - testingSet$Salary) ^ 2) # total sum of squarestss <- sum((testingSet$Salary - mean(testingSet$Salary)) ^ 2) # obtain r^2rsq <- 1 - rss/tssrsq"
},
{
"code": null,
"e": 6202,
"s": 5783,
"text": "We obtained the same R2 as we did in Pyspark, which means in terms of accuracy of models, choosing Pyspark or R to train your model does not matter. And it might seem obvious that training Linear Regression model in R is a lot more simpler than in Pyspark. Whereas, a point to note is that Pyspark is more preferable in terms of training big data and the processing speed will be significantly faster than in R itself."
},
{
"code": null,
"e": 6311,
"s": 6202,
"text": "Here’s my recommendation when it comes to deciding between R or Pyspark in building Linear Regression model:"
},
{
"code": null,
"e": 6367,
"s": 6311,
"text": "Pyspark -> Suitable for processing large amount of data"
},
{
"code": null,
"e": 6405,
"s": 6367,
"text": "R -> Suitable for easy implementation"
}
] |
io.ReadFull() Function in Golang with Examples - GeeksforGeeks | 05 May, 2020
In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The ReadFull() function in Go language is used to read from the stated reader “r” into the stated buffer “buf” and the bytes copied is exactly equal to the length of the buffer specified. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions.
Syntax:
func ReadFull(r Reader, buf []byte) (n int, err error)
Here, “r” is the reader stated, “buf” is the buffer stated of the specified length.
Return value: It returns the number of bytes that the stated buffer copies and also returns an error if the number of bytes reads are less than the length of the buffer specified. Here, “n” returned will be equal to the length of the buffer specified if and only if the error is nil. However, the error returned is “EOF” if and only if no bytes are read.
Note: If an EOF takes place after reading fewer bytes but not all the bytes then this method returns an ErrUnexpectedEOF error. However, if the stated reader returns an error after reading at least length of the buffer then the error is declined.
Example 1:
// Golang program to illustrate the usage of// io.ReadFull() function // Including main packagepackage main // Importing fmt, io, and stringsimport ( "fmt" "io" "strings") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader("Geeks") // Defining buffer of specified length // using make keyword buffer := make([]byte, 4) // Calling ReadFull method with its parameters n, err := io.ReadFull(reader, buffer) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("Number of bytes in the buffer: %d\n", n) fmt.Printf("Content in buffer: %s\n", buffer)}
Output:
Number of bytes in the buffer: 4
Content in buffer: Geek
Here, the ‘n’ returned i.e, 4 is equal to the length of ‘buf’ as the error is nil.
Example 2:
// Golang program to illustrate the usage of// io.ReadFull() function // Including main packagepackage main // Importing fmt, io, and stringsimport ( "fmt" "io" "strings") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader("Geeks") // Defining buffer of specified length // using make keyword buffer := make([]byte, 6) // Calling ReadFull method with its parameters n, err := io.ReadFull(reader, buffer) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf("Number of bytes in the buffer: %d\n", n) fmt.Printf("Content in buffer: %s\n", buffer)}
Output:
panic: unexpected EOF
goroutine 1 [running]:
main.main()
/tmp/sandbox503804944/prog.go:29 +0x210
Here, the buffer stated in above code has length greater than the bytes read from the reader so an EOF error is thrown.
Golang-io
Go Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
strings.Replace() Function in Golang With Examples
Arrays in Go
fmt.Sprintf() Function in Golang With Examples
How to Split a String in Golang?
Slices in Golang
Golang Maps
How to convert a string in lower case in Golang?
Different Ways to Find the Type of Variable in Golang
How to compare times in Golang?
How to Trim a String in Golang? | [
{
"code": null,
"e": 23919,
"s": 23891,
"text": "\n05 May, 2020"
},
{
"code": null,
"e": 24412,
"s": 23919,
"text": "In Go language, io packages supply fundamental interfaces to the I/O primitives. And its principal job is to enclose the ongoing implementations of such king of primitives. The ReadFull() function in Go language is used to read from the stated reader “r” into the stated buffer “buf” and the bytes copied is exactly equal to the length of the buffer specified. Moreover, this function is defined under the io package. Here, you need to import the “io” package in order to use these functions."
},
{
"code": null,
"e": 24420,
"s": 24412,
"text": "Syntax:"
},
{
"code": null,
"e": 24476,
"s": 24420,
"text": "func ReadFull(r Reader, buf []byte) (n int, err error)\n"
},
{
"code": null,
"e": 24560,
"s": 24476,
"text": "Here, “r” is the reader stated, “buf” is the buffer stated of the specified length."
},
{
"code": null,
"e": 24915,
"s": 24560,
"text": "Return value: It returns the number of bytes that the stated buffer copies and also returns an error if the number of bytes reads are less than the length of the buffer specified. Here, “n” returned will be equal to the length of the buffer specified if and only if the error is nil. However, the error returned is “EOF” if and only if no bytes are read."
},
{
"code": null,
"e": 25162,
"s": 24915,
"text": "Note: If an EOF takes place after reading fewer bytes but not all the bytes then this method returns an ErrUnexpectedEOF error. However, if the stated reader returns an error after reading at least length of the buffer then the error is declined."
},
{
"code": null,
"e": 25173,
"s": 25162,
"text": "Example 1:"
},
{
"code": "// Golang program to illustrate the usage of// io.ReadFull() function // Including main packagepackage main // Importing fmt, io, and stringsimport ( \"fmt\" \"io\" \"strings\") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader(\"Geeks\") // Defining buffer of specified length // using make keyword buffer := make([]byte, 4) // Calling ReadFull method with its parameters n, err := io.ReadFull(reader, buffer) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"Number of bytes in the buffer: %d\\n\", n) fmt.Printf(\"Content in buffer: %s\\n\", buffer)}",
"e": 25874,
"s": 25173,
"text": null
},
{
"code": null,
"e": 25882,
"s": 25874,
"text": "Output:"
},
{
"code": null,
"e": 25940,
"s": 25882,
"text": "Number of bytes in the buffer: 4\nContent in buffer: Geek\n"
},
{
"code": null,
"e": 26023,
"s": 25940,
"text": "Here, the ‘n’ returned i.e, 4 is equal to the length of ‘buf’ as the error is nil."
},
{
"code": null,
"e": 26034,
"s": 26023,
"text": "Example 2:"
},
{
"code": "// Golang program to illustrate the usage of// io.ReadFull() function // Including main packagepackage main // Importing fmt, io, and stringsimport ( \"fmt\" \"io\" \"strings\") // Calling mainfunc main() { // Defining reader using NewReader method reader := strings.NewReader(\"Geeks\") // Defining buffer of specified length // using make keyword buffer := make([]byte, 6) // Calling ReadFull method with its parameters n, err := io.ReadFull(reader, buffer) // If error is not nil then panics if err != nil { panic(err) } // Prints output fmt.Printf(\"Number of bytes in the buffer: %d\\n\", n) fmt.Printf(\"Content in buffer: %s\\n\", buffer)}",
"e": 26735,
"s": 26034,
"text": null
},
{
"code": null,
"e": 26743,
"s": 26735,
"text": "Output:"
},
{
"code": null,
"e": 26846,
"s": 26743,
"text": "panic: unexpected EOF\n\ngoroutine 1 [running]:\nmain.main()\n /tmp/sandbox503804944/prog.go:29 +0x210\n"
},
{
"code": null,
"e": 26966,
"s": 26846,
"text": "Here, the buffer stated in above code has length greater than the bytes read from the reader so an EOF error is thrown."
},
{
"code": null,
"e": 26976,
"s": 26966,
"text": "Golang-io"
},
{
"code": null,
"e": 26988,
"s": 26976,
"text": "Go Language"
},
{
"code": null,
"e": 27086,
"s": 26988,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27095,
"s": 27086,
"text": "Comments"
},
{
"code": null,
"e": 27108,
"s": 27095,
"text": "Old Comments"
},
{
"code": null,
"e": 27159,
"s": 27108,
"text": "strings.Replace() Function in Golang With Examples"
},
{
"code": null,
"e": 27172,
"s": 27159,
"text": "Arrays in Go"
},
{
"code": null,
"e": 27219,
"s": 27172,
"text": "fmt.Sprintf() Function in Golang With Examples"
},
{
"code": null,
"e": 27252,
"s": 27219,
"text": "How to Split a String in Golang?"
},
{
"code": null,
"e": 27269,
"s": 27252,
"text": "Slices in Golang"
},
{
"code": null,
"e": 27281,
"s": 27269,
"text": "Golang Maps"
},
{
"code": null,
"e": 27330,
"s": 27281,
"text": "How to convert a string in lower case in Golang?"
},
{
"code": null,
"e": 27384,
"s": 27330,
"text": "Different Ways to Find the Type of Variable in Golang"
},
{
"code": null,
"e": 27416,
"s": 27384,
"text": "How to compare times in Golang?"
}
] |
Bad Character Heuristic | The bad character heuristic method is one of the approaches of Boyer Moore Algorithm. Another approach is Good Suffix Heuristic. In this method we will try to find a bad character, that means a character of the main string, which is not matching with the pattern. When the mismatch has occurred, we will shift the entire pattern until the mismatch becomes a match, otherwise, pattern moves past the bad character.
Here the time complexity is O(m/n) for best case and O(mn)for the worst case, where n is the length of the text and m is the length of the pattern.
Input:
Main String: “ABAAABCDBBABCDDEBCABC”, Pattern “ABC”
Output:
Pattern found at position: 4
Pattern found at position: 10
Pattern found at position: 18
badCharacterHeuristic(pattern, badCharacterArray)
Input − pattern, which will be searched, the bad character array to store location
Output: Fill the bad character array for future use
Begin
n := pattern length
for all entries of badCharacterArray, do
set all entries to -1
done
for all characters of the pattern, do
set last position of each character in badCharacterArray.
done
End
searchPattern(pattern, text)
Input − pattern, which will be searched and the main text
Output − the locations where the pattern is found
Begin
patLen := length of pattern
strLen := length of text.
call badCharacterHeuristic(pattern, badCharacterArray)
shift := 0
while shift <= (strLen - patLen), do
j := patLen -1
while j >= 0 and pattern[j] = text[shift + j], do
decrease j by 1
done
if j < 0, then
print the shift as, there is a match
if shift + patLen < strLen, then
shift:= shift + patLen – badCharacterArray[text[shift + patLen]]
else
increment shift by 1
else
shift := shift + max(1, j-badCharacterArray[text[shift+j]])
done
End
#include<iostream>
#define MAXCHAR 256
using namespace std;
int maximum(int data1, int data2) {
if(data1 > data2)
return data1;
return data2;
}
void badCharacterHeuristic(string pattern, int badCharacter[MAXCHAR]) {
int n = pattern.size(); //find length of pattern
for(int i = 0; i<MAXCHAR; i++)
badCharacter[i] = -1; //set all character distance as -1
for(int i = 0; i < n; i++) {
badCharacter[(int)pattern[i]] = i; //set position of character in the array.
}
}
void searchPattern(string mainString, string pattern, int *array, int *index) {
int patLen = pattern.size();
int strLen = mainString.size();
int badCharacter[MAXCHAR]; //make array for bad character position
badCharacterHeuristic(pattern, badCharacter); //fill bad character array
int shift = 0;
while(shift <= (strLen - patLen)) {
int j = patLen - 1;
while(j >= 0 && pattern[j] == mainString[shift+j]) {
j--; //reduce j when pattern and main string character is matching
}
if(j < 0) {
(*index)++;
array[(*index)] = shift;
if((shift + patLen) < strLen) {
shift += patLen - badCharacter[mainString[shift + patLen]];
}else {
shift += 1;
}
}else {
shift += maximum(1, j - badCharacter[mainString[shift+j]]);
}
}
}
int main() {
string mainString = "ABAAABCDBBABCDDEBCABC";
string pattern = "ABC";
int locArray[mainString.size()];
int index = -1;
searchPattern(mainString, pattern, locArray, &index);
for(int i = 0; i <= index; i++) {
cout << "Pattern found at position: " << locArray[i]<<endl;
}
}
Pattern found at position: 4
Pattern found at position: 10
Pattern found at position: 18 | [
{
"code": null,
"e": 1476,
"s": 1062,
"text": "The bad character heuristic method is one of the approaches of Boyer Moore Algorithm. Another approach is Good Suffix Heuristic. In this method we will try to find a bad character, that means a character of the main string, which is not matching with the pattern. When the mismatch has occurred, we will shift the entire pattern until the mismatch becomes a match, otherwise, pattern moves past the bad character."
},
{
"code": null,
"e": 1624,
"s": 1476,
"text": "Here the time complexity is O(m/n) for best case and O(mn)for the worst case, where n is the length of the text and m is the length of the pattern."
},
{
"code": null,
"e": 1780,
"s": 1624,
"text": "Input:\nMain String: “ABAAABCDBBABCDDEBCABC”, Pattern “ABC”\nOutput:\nPattern found at position: 4\nPattern found at position: 10\nPattern found at position: 18"
},
{
"code": null,
"e": 1830,
"s": 1780,
"text": "badCharacterHeuristic(pattern, badCharacterArray)"
},
{
"code": null,
"e": 1913,
"s": 1830,
"text": "Input − pattern, which will be searched, the bad character array to store location"
},
{
"code": null,
"e": 1965,
"s": 1913,
"text": "Output: Fill the bad character array for future use"
},
{
"code": null,
"e": 2192,
"s": 1965,
"text": "Begin\n n := pattern length\n for all entries of badCharacterArray, do\n set all entries to -1\n done\n\n for all characters of the pattern, do\n set last position of each character in badCharacterArray.\n done\nEnd"
},
{
"code": null,
"e": 2221,
"s": 2192,
"text": "searchPattern(pattern, text)"
},
{
"code": null,
"e": 2279,
"s": 2221,
"text": "Input − pattern, which will be searched and the main text"
},
{
"code": null,
"e": 2329,
"s": 2279,
"text": "Output − the locations where the pattern is found"
},
{
"code": null,
"e": 2946,
"s": 2329,
"text": "Begin\n patLen := length of pattern\n strLen := length of text.\n call badCharacterHeuristic(pattern, badCharacterArray)\n shift := 0\n\n while shift <= (strLen - patLen), do\n j := patLen -1\n while j >= 0 and pattern[j] = text[shift + j], do\n decrease j by 1\n done\n if j < 0, then\n print the shift as, there is a match\n if shift + patLen < strLen, then\n shift:= shift + patLen – badCharacterArray[text[shift + patLen]]\n else\n increment shift by 1\n else\n shift := shift + max(1, j-badCharacterArray[text[shift+j]])\n done\nEnd"
},
{
"code": null,
"e": 4677,
"s": 2946,
"text": "#include<iostream>\n#define MAXCHAR 256\nusing namespace std;\n\nint maximum(int data1, int data2) {\n if(data1 > data2)\n return data1;\n return data2;\n}\n\nvoid badCharacterHeuristic(string pattern, int badCharacter[MAXCHAR]) {\n int n = pattern.size(); //find length of pattern\n for(int i = 0; i<MAXCHAR; i++)\n badCharacter[i] = -1; //set all character distance as -1\n\n for(int i = 0; i < n; i++) {\n badCharacter[(int)pattern[i]] = i; //set position of character in the array.\n } \n}\n\nvoid searchPattern(string mainString, string pattern, int *array, int *index) {\n int patLen = pattern.size();\n int strLen = mainString.size();\n int badCharacter[MAXCHAR]; //make array for bad character position\n badCharacterHeuristic(pattern, badCharacter); //fill bad character array\n int shift = 0;\n\n while(shift <= (strLen - patLen)) {\n int j = patLen - 1;\n while(j >= 0 && pattern[j] == mainString[shift+j]) {\n j--; //reduce j when pattern and main string character is matching\n }\n\n if(j < 0) {\n (*index)++;\n array[(*index)] = shift;\n\n if((shift + patLen) < strLen) {\n shift += patLen - badCharacter[mainString[shift + patLen]];\n }else {\n shift += 1;\n }\n }else {\n shift += maximum(1, j - badCharacter[mainString[shift+j]]);\n }\n }\n}\n\nint main() {\n string mainString = \"ABAAABCDBBABCDDEBCABC\";\n string pattern = \"ABC\";\n int locArray[mainString.size()];\n int index = -1;\n searchPattern(mainString, pattern, locArray, &index);\n\n for(int i = 0; i <= index; i++) {\n cout << \"Pattern found at position: \" << locArray[i]<<endl;\n }\n}"
},
{
"code": null,
"e": 4766,
"s": 4677,
"text": "Pattern found at position: 4\nPattern found at position: 10\nPattern found at position: 18"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.