title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
C++ Fstream Library - Close Function | Closes the file currently associated with the object, disassociating it from the stream. If the stream is currently not associated with any file (i.e., no file has successfully been open with it), calling this function fails.
Following is the declaration for fstream::close.
void close();
none
If the operation fails (including if no file was open before the call), the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions).
Basic guarantee − if an exception is thrown, the stream is in a valid state.
Any exception thrown by an internal operation is caught by the function and rethrown after closing the file.
It throws an exception of member type failure if the function fails (setting the failbit state flag) and member exceptions was set to throw for that state.
Modifies the fstream object.
Concurrent access to the same stream may introduce data races.
In below example explains about fstream close function.
#include <fstream>
int main () {
std::fstream fs;
fs.open ("test.txt", std::fstream::in | std::fstream::out | std::fstream::app);
fs << " more lorem ipsum";
fs.close();
return 0;
}
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2829,
"s": 2603,
"text": "Closes the file currently associated with the object, disassociating it from the stream. If the stream is currently not associated with any file (i.e., no file has successfully been open with it), calling this function fails."
},
{
"code": null,
"e": 2878,
"s": 2829,
"text": "Following is the declaration for fstream::close."
},
{
"code": null,
"e": 2892,
"s": 2878,
"text": "void close();"
},
{
"code": null,
"e": 2897,
"s": 2892,
"text": "none"
},
{
"code": null,
"e": 3109,
"s": 2897,
"text": "If the operation fails (including if no file was open before the call), the failbit state flag is set for the stream (which may throw ios_base::failure if that state flag was registered using member exceptions)."
},
{
"code": null,
"e": 3186,
"s": 3109,
"text": "Basic guarantee − if an exception is thrown, the stream is in a valid state."
},
{
"code": null,
"e": 3295,
"s": 3186,
"text": "Any exception thrown by an internal operation is caught by the function and rethrown after closing the file."
},
{
"code": null,
"e": 3451,
"s": 3295,
"text": "It throws an exception of member type failure if the function fails (setting the failbit state flag) and member exceptions was set to throw for that state."
},
{
"code": null,
"e": 3480,
"s": 3451,
"text": "Modifies the fstream object."
},
{
"code": null,
"e": 3543,
"s": 3480,
"text": "Concurrent access to the same stream may introduce data races."
},
{
"code": null,
"e": 3599,
"s": 3543,
"text": "In below example explains about fstream close function."
},
{
"code": null,
"e": 3806,
"s": 3599,
"text": "#include <fstream> \n\nint main () {\n\n std::fstream fs;\n fs.open (\"test.txt\", std::fstream::in | std::fstream::out | std::fstream::app);\n\n fs << \" more lorem ipsum\";\n\n fs.close();\n\n return 0;\n}"
},
{
"code": null,
"e": 3813,
"s": 3806,
"text": " Print"
},
{
"code": null,
"e": 3824,
"s": 3813,
"text": " Add Notes"
}
] |
How to install Minikube on Windows 10 | Install Kubeadm kubelet kubectl | PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC
EXCEPTIONS
COLLECTIONS
SWING
JDBC
JAVA 8
SPRING
SPRING BOOT
HIBERNATE
PYTHON
PHP
JQUERY
PROGRAMMINGJava ExamplesC Examples
Java Examples
C Examples
C Tutorials
aws
In this tutorial, I am going to show you how to install Minikube on Windows 10 operating system.
Installing Minikube on Windows 10 is a simple process; here I am providing an easy technique to install minikube along with kubeadm and kubectl on windows.
I am going to install the minicube on the below-configured system.
Windows 10 Pro 64 Bit Operating system
RAM 8 GB
HDD 1TB
Oracle VirtualBox 5.2.8
Hyper-V Requirements:
VM Monitor Mode Extensions: Yes
Virtualization Enabled In Firmware: Yes
Second Level Address Translation: Yes
Data Execution Prevention Available: Yes
VM Monitor Mode Extensions: Yes
Virtualization Enabled In Firmware: Yes
Second Level Address Translation: Yes
Data Execution Prevention Available: Yes
However I am working on the above configurations, the Minikube can be installed, if your system met the below minimum requirements.
Windows 8 Or above
Make sure you should install kubectl, before Minicube installation. (No issue – we will install it as part of this tutorial)
Install Hypervisor (Install Hyper-V or Virtual Box); If you install the Docker Toolbox on your windows machine, it comes along with Virtual Box, you can see my previous tutorial on it.
Virtualization supported on Windows
You can check this virtualisation support by using systeminfo command on your windows command prompt.
You should see the below information when you hit the systeminfo command on your terminal.
systeminfo
....
....
Hyper-V Requirements: VM Monitor Mode Extensions: Yes
Virtualization Enabled In Firmware: Yes
Second Level Address Translation: Yes
Data Execution Prevention Available: Yes
Installing Minicube on windows operating system can be done in 3 different ways,
Install Minikube using Chocolatey
Install Minikube using installer
Install Minikube via the direct download
Out of these three options, in this tutorial, I am going with the third option because of the first two needs installation, whereas third options don’t need any installation process.
Download the Minikube from official git-hub repository.
Click on above-highlighted minikube-windows-amd64.exe; then the minikube executable will be downloaded into your machine.
Move the downloaded file to C:/minikube (create minikube folder in C: directory) directory and rename it as minikube.exe.
Download the kubeCtl from the official website.
Click on the above-highlighted hyperlink; then the kubectl.exe executable will be downloaded into your machine.
Move this kubectl.exe file into the above-created folder (C:/minikube).
Till this, we can confirm that we have downloaded Minikube.exe and kubectl.exe file and copied these two files into C:/minikube directory like below.
Now let’s create a path for the C:/minikube folder.
Goto-> View Advanced System Settings -> Environment Variables -> Select the Path from User variable section -> Click on Edit.
Then you could see the below Edit environment variables window. Click on New button and paste the C:/minikube and click on the Ok button.
Open the windows command prompt and hit the minikube start command. Then it starts downloading minikube, kubeadm and kubelet. It will take time to download and set up the things based on your internet speed.
If you see the above Done! message, then you can confirm that minikube,kubectl, kubeadm and kubelet have been successfully installed on your machine.
To verify the things, you can fire a simple kubectl command, here I am checking for nodes by firing kubectl get nodes command, then I could see the master node information as minikube comes along with a master node.
Install kubectl
install minikube
install Docker toolbox on windows 10
Happy Learning 🙂
How to Install Kubernetes on Ubuntu 18.04
How to install Docker Toolbox on Windows 10
Install Mysql on Windows 10 Step by Step
How to install Maven on windows 7 command line
How to Install Java8 on Windows 10
How to Install Ant on Windows 10
How install Python on Windows 10
How to install Elasticsearch on Windows 10
How to install PuTTY on windows 10
How to install RabbitMQ on Windows 10
How to install Gradle on Windows 10
How to install SOAPUI on Windows 10
How to install AWS CLI on Windows 10
How to Install Git windows 10 Operating System
How to install Android Studio on Windows 10
How to Install Kubernetes on Ubuntu 18.04
How to install Docker Toolbox on Windows 10
Install Mysql on Windows 10 Step by Step
How to install Maven on windows 7 command line
How to Install Java8 on Windows 10
How to Install Ant on Windows 10
How install Python on Windows 10
How to install Elasticsearch on Windows 10
How to install PuTTY on windows 10
How to install RabbitMQ on Windows 10
How to install Gradle on Windows 10
How to install SOAPUI on Windows 10
How to install AWS CLI on Windows 10
How to Install Git windows 10 Operating System
How to install Android Studio on Windows 10
Praveen Siva
January 20, 2021 at 2:41 am - Reply
Thanks for details. But I am getting following error when I run minikube start command. I ahve downloaded Virtual Box 6.X version.
C:\minikube>minikube start
* minikube v1.2.0 on windows (amd64)
* Tip: Use ‘minikube start -p ‘ to create a new cluster, or ‘minikube delete’ to delete this one.
* Restarting existing virtualbox VM for “minikube” ...
E0119 15:56:54.796452 9192 start.go:559] StartHost: start: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube –type headless failed:
VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))
X Unable to start VM: start: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube –type headless failed:
VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))
* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:
– https://github.com/kubernetes/minikube/issues/new
Lahari
September 25, 2021 at 7:44 pm - Reply
Is this problem solved?
Bcoz I’m facing the same issue
Praveen Siva
January 20, 2021 at 2:41 am - Reply
Thanks for details. But I am getting following error when I run minikube start command. I ahve downloaded Virtual Box 6.X version.
C:\minikube>minikube start
* minikube v1.2.0 on windows (amd64)
* Tip: Use ‘minikube start -p ‘ to create a new cluster, or ‘minikube delete’ to delete this one.
* Restarting existing virtualbox VM for “minikube” ...
E0119 15:56:54.796452 9192 start.go:559] StartHost: start: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube –type headless failed:
VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))
X Unable to start VM: start: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube –type headless failed:
VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))
* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:
– https://github.com/kubernetes/minikube/issues/new
Lahari
September 25, 2021 at 7:44 pm - Reply
Is this problem solved?
Bcoz I’m facing the same issue
Thanks for details. But I am getting following error when I run minikube start command. I ahve downloaded Virtual Box 6.X version.
C:\minikube>minikube start
* minikube v1.2.0 on windows (amd64)
* Tip: Use ‘minikube start -p ‘ to create a new cluster, or ‘minikube delete’ to delete this one.
* Restarting existing virtualbox VM for “minikube” ...
E0119 15:56:54.796452 9192 start.go:559] StartHost: start: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube –type headless failed:
VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))
X Unable to start VM: start: Unable to start the VM: C:\Program Files\Oracle\VirtualBox\VBoxManage.exe startvm minikube –type headless failed:
VBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)
VBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole
Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))
* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:
– https://github.com/kubernetes/minikube/issues/new
Lahari
September 25, 2021 at 7:44 pm - Reply
Is this problem solved?
Bcoz I’m facing the same issue
Is this problem solved?
Bcoz I’m facing the same issue | [
{
"code": null,
"e": 158,
"s": 123,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 172,
"s": 158,
"text": "Java Examples"
},
{
"code": null,
"e": 183,
"s": 172,
"text": "C Examples"
},
{
"code": null,
"e": 195,
"s": 183,
"text": "C Tutorials"
},
{
"code": null,
"e": 199,
"s": 195,
"text": "aws"
},
{
"code": null,
"e": 234,
"s": 199,
"text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC"
},
{
"code": null,
"e": 245,
"s": 234,
"text": "EXCEPTIONS"
},
{
"code": null,
"e": 257,
"s": 245,
"text": "COLLECTIONS"
},
{
"code": null,
"e": 263,
"s": 257,
"text": "SWING"
},
{
"code": null,
"e": 268,
"s": 263,
"text": "JDBC"
},
{
"code": null,
"e": 275,
"s": 268,
"text": "JAVA 8"
},
{
"code": null,
"e": 282,
"s": 275,
"text": "SPRING"
},
{
"code": null,
"e": 294,
"s": 282,
"text": "SPRING BOOT"
},
{
"code": null,
"e": 304,
"s": 294,
"text": "HIBERNATE"
},
{
"code": null,
"e": 311,
"s": 304,
"text": "PYTHON"
},
{
"code": null,
"e": 315,
"s": 311,
"text": "PHP"
},
{
"code": null,
"e": 322,
"s": 315,
"text": "JQUERY"
},
{
"code": null,
"e": 357,
"s": 322,
"text": "PROGRAMMINGJava ExamplesC Examples"
},
{
"code": null,
"e": 371,
"s": 357,
"text": "Java Examples"
},
{
"code": null,
"e": 382,
"s": 371,
"text": "C Examples"
},
{
"code": null,
"e": 394,
"s": 382,
"text": "C Tutorials"
},
{
"code": null,
"e": 398,
"s": 394,
"text": "aws"
},
{
"code": null,
"e": 495,
"s": 398,
"text": "In this tutorial, I am going to show you how to install Minikube on Windows 10 operating system."
},
{
"code": null,
"e": 651,
"s": 495,
"text": "Installing Minikube on Windows 10 is a simple process; here I am providing an easy technique to install minikube along with kubeadm and kubectl on windows."
},
{
"code": null,
"e": 718,
"s": 651,
"text": "I am going to install the minicube on the below-configured system."
},
{
"code": null,
"e": 757,
"s": 718,
"text": "Windows 10 Pro 64 Bit Operating system"
},
{
"code": null,
"e": 766,
"s": 757,
"text": "RAM 8 GB"
},
{
"code": null,
"e": 774,
"s": 766,
"text": "HDD 1TB"
},
{
"code": null,
"e": 798,
"s": 774,
"text": "Oracle VirtualBox 5.2.8"
},
{
"code": null,
"e": 974,
"s": 798,
"text": "Hyper-V Requirements:\n\nVM Monitor Mode Extensions: Yes\nVirtualization Enabled In Firmware: Yes\nSecond Level Address Translation: Yes\nData Execution Prevention Available: Yes\n\n"
},
{
"code": null,
"e": 1006,
"s": 974,
"text": "VM Monitor Mode Extensions: Yes"
},
{
"code": null,
"e": 1046,
"s": 1006,
"text": "Virtualization Enabled In Firmware: Yes"
},
{
"code": null,
"e": 1084,
"s": 1046,
"text": "Second Level Address Translation: Yes"
},
{
"code": null,
"e": 1125,
"s": 1084,
"text": "Data Execution Prevention Available: Yes"
},
{
"code": null,
"e": 1257,
"s": 1125,
"text": "However I am working on the above configurations, the Minikube can be installed, if your system met the below minimum requirements."
},
{
"code": null,
"e": 1276,
"s": 1257,
"text": "Windows 8 Or above"
},
{
"code": null,
"e": 1401,
"s": 1276,
"text": "Make sure you should install kubectl, before Minicube installation. (No issue – we will install it as part of this tutorial)"
},
{
"code": null,
"e": 1586,
"s": 1401,
"text": "Install Hypervisor (Install Hyper-V or Virtual Box); If you install the Docker Toolbox on your windows machine, it comes along with Virtual Box, you can see my previous tutorial on it."
},
{
"code": null,
"e": 1622,
"s": 1586,
"text": "Virtualization supported on Windows"
},
{
"code": null,
"e": 1724,
"s": 1622,
"text": "You can check this virtualisation support by using systeminfo command on your windows command prompt."
},
{
"code": null,
"e": 1815,
"s": 1724,
"text": "You should see the below information when you hit the systeminfo command on your terminal."
},
{
"code": null,
"e": 2095,
"s": 1815,
"text": "systeminfo\n....\n....\nHyper-V Requirements: VM Monitor Mode Extensions: Yes\n Virtualization Enabled In Firmware: Yes\n Second Level Address Translation: Yes\n Data Execution Prevention Available: Yes"
},
{
"code": null,
"e": 2176,
"s": 2095,
"text": "Installing Minicube on windows operating system can be done in 3 different ways,"
},
{
"code": null,
"e": 2210,
"s": 2176,
"text": "Install Minikube using Chocolatey"
},
{
"code": null,
"e": 2243,
"s": 2210,
"text": "Install Minikube using installer"
},
{
"code": null,
"e": 2284,
"s": 2243,
"text": "Install Minikube via the direct download"
},
{
"code": null,
"e": 2467,
"s": 2284,
"text": "Out of these three options, in this tutorial, I am going with the third option because of the first two needs installation, whereas third options don’t need any installation process."
},
{
"code": null,
"e": 2523,
"s": 2467,
"text": "Download the Minikube from official git-hub repository."
},
{
"code": null,
"e": 2645,
"s": 2523,
"text": "Click on above-highlighted minikube-windows-amd64.exe; then the minikube executable will be downloaded into your machine."
},
{
"code": null,
"e": 2767,
"s": 2645,
"text": "Move the downloaded file to C:/minikube (create minikube folder in C: directory) directory and rename it as minikube.exe."
},
{
"code": null,
"e": 2815,
"s": 2767,
"text": "Download the kubeCtl from the official website."
},
{
"code": null,
"e": 2927,
"s": 2815,
"text": "Click on the above-highlighted hyperlink; then the kubectl.exe executable will be downloaded into your machine."
},
{
"code": null,
"e": 2999,
"s": 2927,
"text": "Move this kubectl.exe file into the above-created folder (C:/minikube)."
},
{
"code": null,
"e": 3149,
"s": 2999,
"text": "Till this, we can confirm that we have downloaded Minikube.exe and kubectl.exe file and copied these two files into C:/minikube directory like below."
},
{
"code": null,
"e": 3201,
"s": 3149,
"text": "Now let’s create a path for the C:/minikube folder."
},
{
"code": null,
"e": 3327,
"s": 3201,
"text": "Goto-> View Advanced System Settings -> Environment Variables -> Select the Path from User variable section -> Click on Edit."
},
{
"code": null,
"e": 3465,
"s": 3327,
"text": "Then you could see the below Edit environment variables window. Click on New button and paste the C:/minikube and click on the Ok button."
},
{
"code": null,
"e": 3673,
"s": 3465,
"text": "Open the windows command prompt and hit the minikube start command. Then it starts downloading minikube, kubeadm and kubelet. It will take time to download and set up the things based on your internet speed."
},
{
"code": null,
"e": 3823,
"s": 3673,
"text": "If you see the above Done! message, then you can confirm that minikube,kubectl, kubeadm and kubelet have been successfully installed on your machine."
},
{
"code": null,
"e": 4039,
"s": 3823,
"text": "To verify the things, you can fire a simple kubectl command, here I am checking for nodes by firing kubectl get nodes command, then I could see the master node information as minikube comes along with a master node."
},
{
"code": null,
"e": 4055,
"s": 4039,
"text": "Install kubectl"
},
{
"code": null,
"e": 4072,
"s": 4055,
"text": "install minikube"
},
{
"code": null,
"e": 4109,
"s": 4072,
"text": "install Docker toolbox on windows 10"
},
{
"code": null,
"e": 4126,
"s": 4109,
"text": "Happy Learning 🙂"
},
{
"code": null,
"e": 4719,
"s": 4126,
"text": "\nHow to Install Kubernetes on Ubuntu 18.04\nHow to install Docker Toolbox on Windows 10\nInstall Mysql on Windows 10 Step by Step\nHow to install Maven on windows 7 command line\nHow to Install Java8 on Windows 10\nHow to Install Ant on Windows 10\nHow install Python on Windows 10\nHow to install Elasticsearch on Windows 10\nHow to install PuTTY on windows 10\nHow to install RabbitMQ on Windows 10\nHow to install Gradle on Windows 10\nHow to install SOAPUI on Windows 10\nHow to install AWS CLI on Windows 10\nHow to Install Git windows 10 Operating System\nHow to install Android Studio on Windows 10\n"
},
{
"code": null,
"e": 4761,
"s": 4719,
"text": "How to Install Kubernetes on Ubuntu 18.04"
},
{
"code": null,
"e": 4805,
"s": 4761,
"text": "How to install Docker Toolbox on Windows 10"
},
{
"code": null,
"e": 4846,
"s": 4805,
"text": "Install Mysql on Windows 10 Step by Step"
},
{
"code": null,
"e": 4893,
"s": 4846,
"text": "How to install Maven on windows 7 command line"
},
{
"code": null,
"e": 4928,
"s": 4893,
"text": "How to Install Java8 on Windows 10"
},
{
"code": null,
"e": 4961,
"s": 4928,
"text": "How to Install Ant on Windows 10"
},
{
"code": null,
"e": 4994,
"s": 4961,
"text": "How install Python on Windows 10"
},
{
"code": null,
"e": 5037,
"s": 4994,
"text": "How to install Elasticsearch on Windows 10"
},
{
"code": null,
"e": 5072,
"s": 5037,
"text": "How to install PuTTY on windows 10"
},
{
"code": null,
"e": 5110,
"s": 5072,
"text": "How to install RabbitMQ on Windows 10"
},
{
"code": null,
"e": 5146,
"s": 5110,
"text": "How to install Gradle on Windows 10"
},
{
"code": null,
"e": 5182,
"s": 5146,
"text": "How to install SOAPUI on Windows 10"
},
{
"code": null,
"e": 5219,
"s": 5182,
"text": "How to install AWS CLI on Windows 10"
},
{
"code": null,
"e": 5266,
"s": 5219,
"text": "How to Install Git windows 10 Operating System"
},
{
"code": null,
"e": 5310,
"s": 5266,
"text": "How to install Android Studio on Windows 10"
},
{
"code": null,
"e": 6925,
"s": 5310,
"text": "\n\n\n\n\n\nPraveen Siva\nJanuary 20, 2021 at 2:41 am - Reply \n\nThanks for details. But I am getting following error when I run minikube start command. I ahve downloaded Virtual Box 6.X version.\nC:\\minikube>minikube start\n* minikube v1.2.0 on windows (amd64)\n* Tip: Use ‘minikube start -p ‘ to create a new cluster, or ‘minikube delete’ to delete this one.\n* Restarting existing virtualbox VM for “minikube” ...\nE0119 15:56:54.796452 9192 start.go:559] StartHost: start: Unable to start the VM: C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe startvm minikube –type headless failed:\nVBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)\nVBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole\nDetails: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))\nX Unable to start VM: start: Unable to start the VM: C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe startvm minikube –type headless failed:\nVBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)\nVBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole\nDetails: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))\n* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:\n– https://github.com/kubernetes/minikube/issues/new\n\n\n\n\n\n\n\n\n\nLahari\nSeptember 25, 2021 at 7:44 pm - Reply \n\nIs this problem solved?\nBcoz I’m facing the same issue\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 8538,
"s": 6925,
"text": "\n\n\n\n\nPraveen Siva\nJanuary 20, 2021 at 2:41 am - Reply \n\nThanks for details. But I am getting following error when I run minikube start command. I ahve downloaded Virtual Box 6.X version.\nC:\\minikube>minikube start\n* minikube v1.2.0 on windows (amd64)\n* Tip: Use ‘minikube start -p ‘ to create a new cluster, or ‘minikube delete’ to delete this one.\n* Restarting existing virtualbox VM for “minikube” ...\nE0119 15:56:54.796452 9192 start.go:559] StartHost: start: Unable to start the VM: C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe startvm minikube –type headless failed:\nVBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)\nVBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole\nDetails: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))\nX Unable to start VM: start: Unable to start the VM: C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe startvm minikube –type headless failed:\nVBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)\nVBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole\nDetails: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))\n* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:\n– https://github.com/kubernetes/minikube/issues/new\n\n\n\n\n\n\n\n\n\nLahari\nSeptember 25, 2021 at 7:44 pm - Reply \n\nIs this problem solved?\nBcoz I’m facing the same issue\n\n\n\n\n\n"
},
{
"code": null,
"e": 8669,
"s": 8538,
"text": "Thanks for details. But I am getting following error when I run minikube start command. I ahve downloaded Virtual Box 6.X version."
},
{
"code": null,
"e": 9282,
"s": 8669,
"text": "C:\\minikube>minikube start\n* minikube v1.2.0 on windows (amd64)\n* Tip: Use ‘minikube start -p ‘ to create a new cluster, or ‘minikube delete’ to delete this one.\n* Restarting existing virtualbox VM for “minikube” ...\nE0119 15:56:54.796452 9192 start.go:559] StartHost: start: Unable to start the VM: C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe startvm minikube –type headless failed:\nVBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)\nVBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole"
},
{
"code": null,
"e": 9379,
"s": 9282,
"text": "Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))"
},
{
"code": null,
"e": 9742,
"s": 9379,
"text": "X Unable to start VM: start: Unable to start the VM: C:\\Program Files\\Oracle\\VirtualBox\\VBoxManage.exe startvm minikube –type headless failed:\nVBoxManage.exe: error: Call to WHvSetupPartition failed: ERROR_SUCCESS (Last=0xc000000d/87) (VERR_NEM_VM_CREATE_FAILED)\nVBoxManage.exe: error: Details: code E_FAIL (0x80004005), component ConsoleWrap, interface IConsole"
},
{
"code": null,
"e": 9839,
"s": 9742,
"text": "Details: 00:00:01.436792 Power up failed (vrc=VERR_NEM_VM_CREATE_FAILED, rc=E_FAIL (0X80004005))"
},
{
"code": null,
"e": 9978,
"s": 9839,
"text": "* Sorry that minikube crashed. If this was unexpected, we would love to hear from you:\n– https://github.com/kubernetes/minikube/issues/new"
},
{
"code": null,
"e": 10089,
"s": 9978,
"text": "\n\n\n\n\nLahari\nSeptember 25, 2021 at 7:44 pm - Reply \n\nIs this problem solved?\nBcoz I’m facing the same issue\n\n\n\n"
}
] |
How to differentiate mouse “click” and “drag” event using JavaScript ? - GeeksforGeeks | 15 Oct, 2020
Working with web elements a user may drag or click an element as per requirement. It is important to distinguish between drag and click events. JavaScript is a high level, dynamically typed programming language that can be used to distinguish between the drag and click events. JavaScript has a drag and clicks events that help to differentiate between the two. This article demonstrates two methods of differentiating between click and drag events. In the first method, we will display the output on the console whereas in the second approach we will display the output on the webpage itself. The user can choose either method at his convenience.
Approach 1: We have a web page where any kind of click or drag event is logged in the console. The basic difference between a click and a drag event is the mouse movement. The mouse event that differentiates a click and drag event is the “mouse move” event. In a “click” event, there is no “mouse move” event. However, the “mouse down” and “mouse up” event remains the same for both click and drag.The JavaScript code below shows that a variable named drag is initiated with a ‘false‘ boolean value. For the “mouse down” event ‘drag‘ variable remains false. But as soon as a “mouse move” event is triggered the drag variable is set to ‘true‘. On the “mouse up” event, the value of drag variable is checked. If the value is true, a “drag” event has occurred and the output is displayed in the console. If the value is ‘false‘ which means there has been no “mouse move” event which also implies that a “click” event had occurred. Hence the click output is displayed to the console.
<script type="text/javascript"> let drag = false; document.addEventListener( 'mousedown', () => drag = false); document.addEventListener( 'mousemove', () => drag = true); document.addEventListener( 'mouseup', () => console.log( drag ? 'drag' : 'click'));</script>
Output: On click and drag events , the output is displayed in the console as shown below.
Approach 2: The second approach is element specific and does not work for all the other elements in the web page. We choose an element to log the “click” or “drag” events. In the example below, a paragraph is chosen as the required element and we assign ‘draggable‘ and ‘clickable‘ attributes as true which means the element can be dragged as well as clicked.
The JavaScript events ondrag and onclick help us achieve the desired result. When the element is clicked, a click message is displayed just below the element in the web page itself. When the element is dragged, a drag message is displayed just below the element in the web page itself. The click and drag events are fired as per the user user activity and then the actions corresponding to the events are executed.
<!DOCTYPE html><html> <body> <p id="dragtarget" draggable="true" clickable="true"> Click Me or Drag Me! </p> <p id="demo" style="color:red;"></p> <script type="text/javascript"> document.ondrag = function (event) { document.getElementById("demo").innerHTML = "Element is being dragged"; }; document.onclick = function (event) { document.getElementById("demo").innerHTML = "Element is being clicked!"; }; </script></body> </html>
Output:
When the element is clicked:
When the element is clicked:
When the element is dragged:
When the element is dragged:
JavaScript-Misc
HTML
JavaScript
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
Form validation using HTML and JavaScript
HTML Introduction
How to Upload Image into Database and Display it using PHP ?
Differences between Functional Components and Class Components in React
Convert a string to an integer in JavaScript
How to read a local text file using JavaScript?
How to Open URL in New Tab using JavaScript ?
Set the value of an input field in JavaScript | [
{
"code": null,
"e": 24171,
"s": 24143,
"text": "\n15 Oct, 2020"
},
{
"code": null,
"e": 24819,
"s": 24171,
"text": "Working with web elements a user may drag or click an element as per requirement. It is important to distinguish between drag and click events. JavaScript is a high level, dynamically typed programming language that can be used to distinguish between the drag and click events. JavaScript has a drag and clicks events that help to differentiate between the two. This article demonstrates two methods of differentiating between click and drag events. In the first method, we will display the output on the console whereas in the second approach we will display the output on the webpage itself. The user can choose either method at his convenience."
},
{
"code": null,
"e": 25799,
"s": 24819,
"text": "Approach 1: We have a web page where any kind of click or drag event is logged in the console. The basic difference between a click and a drag event is the mouse movement. The mouse event that differentiates a click and drag event is the “mouse move” event. In a “click” event, there is no “mouse move” event. However, the “mouse down” and “mouse up” event remains the same for both click and drag.The JavaScript code below shows that a variable named drag is initiated with a ‘false‘ boolean value. For the “mouse down” event ‘drag‘ variable remains false. But as soon as a “mouse move” event is triggered the drag variable is set to ‘true‘. On the “mouse up” event, the value of drag variable is checked. If the value is true, a “drag” event has occurred and the output is displayed in the console. If the value is ‘false‘ which means there has been no “mouse move” event which also implies that a “click” event had occurred. Hence the click output is displayed to the console."
},
{
"code": "<script type=\"text/javascript\"> let drag = false; document.addEventListener( 'mousedown', () => drag = false); document.addEventListener( 'mousemove', () => drag = true); document.addEventListener( 'mouseup', () => console.log( drag ? 'drag' : 'click'));</script>",
"e": 26111,
"s": 25799,
"text": null
},
{
"code": null,
"e": 26201,
"s": 26111,
"text": "Output: On click and drag events , the output is displayed in the console as shown below."
},
{
"code": null,
"e": 26561,
"s": 26201,
"text": "Approach 2: The second approach is element specific and does not work for all the other elements in the web page. We choose an element to log the “click” or “drag” events. In the example below, a paragraph is chosen as the required element and we assign ‘draggable‘ and ‘clickable‘ attributes as true which means the element can be dragged as well as clicked."
},
{
"code": null,
"e": 26976,
"s": 26561,
"text": "The JavaScript events ondrag and onclick help us achieve the desired result. When the element is clicked, a click message is displayed just below the element in the web page itself. When the element is dragged, a drag message is displayed just below the element in the web page itself. The click and drag events are fired as per the user user activity and then the actions corresponding to the events are executed."
},
{
"code": "<!DOCTYPE html><html> <body> <p id=\"dragtarget\" draggable=\"true\" clickable=\"true\"> Click Me or Drag Me! </p> <p id=\"demo\" style=\"color:red;\"></p> <script type=\"text/javascript\"> document.ondrag = function (event) { document.getElementById(\"demo\").innerHTML = \"Element is being dragged\"; }; document.onclick = function (event) { document.getElementById(\"demo\").innerHTML = \"Element is being clicked!\"; }; </script></body> </html>",
"e": 27535,
"s": 26976,
"text": null
},
{
"code": null,
"e": 27543,
"s": 27535,
"text": "Output:"
},
{
"code": null,
"e": 27572,
"s": 27543,
"text": "When the element is clicked:"
},
{
"code": null,
"e": 27601,
"s": 27572,
"text": "When the element is clicked:"
},
{
"code": null,
"e": 27630,
"s": 27601,
"text": "When the element is dragged:"
},
{
"code": null,
"e": 27659,
"s": 27630,
"text": "When the element is dragged:"
},
{
"code": null,
"e": 27675,
"s": 27659,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 27680,
"s": 27675,
"text": "HTML"
},
{
"code": null,
"e": 27691,
"s": 27680,
"text": "JavaScript"
},
{
"code": null,
"e": 27708,
"s": 27691,
"text": "Web Technologies"
},
{
"code": null,
"e": 27735,
"s": 27708,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 27740,
"s": 27735,
"text": "HTML"
},
{
"code": null,
"e": 27838,
"s": 27740,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27847,
"s": 27838,
"text": "Comments"
},
{
"code": null,
"e": 27860,
"s": 27847,
"text": "Old Comments"
},
{
"code": null,
"e": 27897,
"s": 27860,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 27926,
"s": 27897,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 27968,
"s": 27926,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 27986,
"s": 27968,
"text": "HTML Introduction"
},
{
"code": null,
"e": 28047,
"s": 27986,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 28119,
"s": 28047,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 28164,
"s": 28119,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 28212,
"s": 28164,
"text": "How to read a local text file using JavaScript?"
},
{
"code": null,
"e": 28258,
"s": 28212,
"text": "How to Open URL in New Tab using JavaScript ?"
}
] |
Create Scatter plot from CSV in R - GeeksforGeeks | 27 Aug, 2021
In R Programming Language we use plot() function to display scatterplot. It takes eight parameters.
Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)
Parameters:
x: sets variable to be used for horizontal coordinates.
y: sets variable to be used for vertical coordinates.
xlab: label for horizontal axis.
ylab: label for vertical axis.
main: title of the chart.
xlim: limits of x for plotting values of x.
ylim: limits of y for plotting values of y.
axes: it indicates whether both axes should be drawn on the plot.
To set attributes of scatter plot like color and shape of scatter plot points we use “col” attribute to set the color of scatter plot and to set shape we use “pch”, where pch takes numeric values between 0 and 25.
Here we are going to create dataframe from this dataset. We use read.csv() to read csv file and store that data in a variable.
R
csv_data<-read.csv("diamonds.csv")print(csv_data)
Output:
Example 1: In this example we create a simple scatter plot, where x is set to carat and y, is set to price. We label the plot as Price vs Carat.
Syntax: plot(x, y, main, xlab, ylab, col, pch)
Where x is carat data, y is price data, xlab is label for x as “Carat” and ylab is label for y as “Price”.
R
plot(x = csv_data$carat, y = csv_data$price, xlab = "Carat", ylab = "Price", main = "Price vs Carat")
Output:
Example 2: In this example we try to set attributes of scatter plot like color and shape of scatter plot points. We set pch value 4 where value 4 is represented as “x” and color is set to green.
R
plot(x = csv_data$carat, y = csv_data$price, xlab = "Carat", ylab = "Price", col = "green", pch = 4, main = "Price vs Carat")
Output:
Example 3: We can also add a regression line to our scatter plot by using abline() function. We pass 2 parameters in which first we pass lm() function(lm() function is used to fit linear models.) where we specify x and y of our dataset and name of our data and, the second parameter is color of the line.
R
plot(x = csv_data$carat, y = csv_data$price, xlab = "Carat", ylab = "Price", col = "green", pch = 4, main = "Price vs Carat") abline(lm(csv_data$price ~ csv_data$carat, data = csv_data), col = "black")
Output:
anikakapoor
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.
Comments
Old Comments
Change Color of Bars in Barchart using ggplot2 in R
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
How to filter R DataFrame by values in a column?
Replace Specific Characters in String in R
How to filter R dataframe by multiple conditions?
R - if statement
How to import an Excel File into R ?
Time Series Analysis in R | [
{
"code": null,
"e": 24851,
"s": 24823,
"text": "\n27 Aug, 2021"
},
{
"code": null,
"e": 24951,
"s": 24851,
"text": "In R Programming Language we use plot() function to display scatterplot. It takes eight parameters."
},
{
"code": null,
"e": 25006,
"s": 24951,
"text": "Syntax: plot(x, y, main, xlab, ylab, xlim, ylim, axes)"
},
{
"code": null,
"e": 25018,
"s": 25006,
"text": "Parameters:"
},
{
"code": null,
"e": 25074,
"s": 25018,
"text": "x: sets variable to be used for horizontal coordinates."
},
{
"code": null,
"e": 25128,
"s": 25074,
"text": "y: sets variable to be used for vertical coordinates."
},
{
"code": null,
"e": 25161,
"s": 25128,
"text": "xlab: label for horizontal axis."
},
{
"code": null,
"e": 25192,
"s": 25161,
"text": "ylab: label for vertical axis."
},
{
"code": null,
"e": 25218,
"s": 25192,
"text": "main: title of the chart."
},
{
"code": null,
"e": 25262,
"s": 25218,
"text": "xlim: limits of x for plotting values of x."
},
{
"code": null,
"e": 25306,
"s": 25262,
"text": "ylim: limits of y for plotting values of y."
},
{
"code": null,
"e": 25372,
"s": 25306,
"text": "axes: it indicates whether both axes should be drawn on the plot."
},
{
"code": null,
"e": 25586,
"s": 25372,
"text": "To set attributes of scatter plot like color and shape of scatter plot points we use “col” attribute to set the color of scatter plot and to set shape we use “pch”, where pch takes numeric values between 0 and 25."
},
{
"code": null,
"e": 25713,
"s": 25586,
"text": "Here we are going to create dataframe from this dataset. We use read.csv() to read csv file and store that data in a variable."
},
{
"code": null,
"e": 25715,
"s": 25713,
"text": "R"
},
{
"code": "csv_data<-read.csv(\"diamonds.csv\")print(csv_data)",
"e": 25765,
"s": 25715,
"text": null
},
{
"code": null,
"e": 25777,
"s": 25769,
"text": "Output:"
},
{
"code": null,
"e": 25926,
"s": 25781,
"text": "Example 1: In this example we create a simple scatter plot, where x is set to carat and y, is set to price. We label the plot as Price vs Carat."
},
{
"code": null,
"e": 25976,
"s": 25928,
"text": "Syntax: plot(x, y, main, xlab, ylab, col, pch) "
},
{
"code": null,
"e": 26084,
"s": 25976,
"text": "Where x is carat data, y is price data, xlab is label for x as “Carat” and ylab is label for y as “Price”. "
},
{
"code": null,
"e": 26088,
"s": 26086,
"text": "R"
},
{
"code": "plot(x = csv_data$carat, y = csv_data$price, xlab = \"Carat\", ylab = \"Price\", main = \"Price vs Carat\")",
"e": 26206,
"s": 26088,
"text": null
},
{
"code": null,
"e": 26218,
"s": 26210,
"text": "Output:"
},
{
"code": null,
"e": 26417,
"s": 26222,
"text": "Example 2: In this example we try to set attributes of scatter plot like color and shape of scatter plot points. We set pch value 4 where value 4 is represented as “x” and color is set to green."
},
{
"code": null,
"e": 26421,
"s": 26419,
"text": "R"
},
{
"code": "plot(x = csv_data$carat, y = csv_data$price, xlab = \"Carat\", ylab = \"Price\", col = \"green\", pch = 4, main = \"Price vs Carat\")",
"e": 26571,
"s": 26421,
"text": null
},
{
"code": null,
"e": 26583,
"s": 26575,
"text": "Output:"
},
{
"code": null,
"e": 26892,
"s": 26587,
"text": "Example 3: We can also add a regression line to our scatter plot by using abline() function. We pass 2 parameters in which first we pass lm() function(lm() function is used to fit linear models.) where we specify x and y of our dataset and name of our data and, the second parameter is color of the line."
},
{
"code": null,
"e": 26896,
"s": 26894,
"text": "R"
},
{
"code": "plot(x = csv_data$carat, y = csv_data$price, xlab = \"Carat\", ylab = \"Price\", col = \"green\", pch = 4, main = \"Price vs Carat\") abline(lm(csv_data$price ~ csv_data$carat, data = csv_data), col = \"black\")",
"e": 27131,
"s": 26896,
"text": null
},
{
"code": null,
"e": 27139,
"s": 27131,
"text": "Output:"
},
{
"code": null,
"e": 27151,
"s": 27139,
"text": "anikakapoor"
},
{
"code": null,
"e": 27158,
"s": 27151,
"text": "Picked"
},
{
"code": null,
"e": 27167,
"s": 27158,
"text": "R-Charts"
},
{
"code": null,
"e": 27176,
"s": 27167,
"text": "R-Graphs"
},
{
"code": null,
"e": 27184,
"s": 27176,
"text": "R-plots"
},
{
"code": null,
"e": 27195,
"s": 27184,
"text": "R Language"
},
{
"code": null,
"e": 27293,
"s": 27195,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27302,
"s": 27293,
"text": "Comments"
},
{
"code": null,
"e": 27315,
"s": 27302,
"text": "Old Comments"
},
{
"code": null,
"e": 27367,
"s": 27315,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 27405,
"s": 27367,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 27440,
"s": 27405,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 27498,
"s": 27440,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
},
{
"code": null,
"e": 27547,
"s": 27498,
"text": "How to filter R DataFrame by values in a column?"
},
{
"code": null,
"e": 27590,
"s": 27547,
"text": "Replace Specific Characters in String in R"
},
{
"code": null,
"e": 27640,
"s": 27590,
"text": "How to filter R dataframe by multiple conditions?"
},
{
"code": null,
"e": 27657,
"s": 27640,
"text": "R - if statement"
},
{
"code": null,
"e": 27694,
"s": 27657,
"text": "How to import an Excel File into R ?"
}
] |
How to change font color of textView in android? | This example demonstrates how do I change font color of TextView in android.
Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project.
Step 2 − Add the following code to res/layout/activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="My color is Blue"
android:layout_centerInParent="true"
android:textStyle="bold"
android:textSize="36sp"/>
<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@id/textView1"
android:layout_marginBottom="10dp"
android:text="My color is Green"
android:textStyle="bold"
android:layout_centerInParent="true"
android:textSize="36sp" />
</RelativeLayout>
Step 3 − Add the following code to src/MainActivity.java
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView textView1 = findViewById(R.id.textView1);
textView1.setTextColor(Color.BLUE);
TextView textView2 = findViewById(R.id.textView2);
textView2.setTextColor(Color.parseColor("#006400"));
}
}
Step 4 − Add the following code to androidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen
Click here to download the project code. | [
{
"code": null,
"e": 1139,
"s": 1062,
"text": "This example demonstrates how do I change font color of TextView in android."
},
{
"code": null,
"e": 1268,
"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": 1268,
"text": "Step 2 − Add the following code to res/layout/activity_main.xml"
},
{
"code": null,
"e": 2268,
"s": 1332,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<RelativeLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n tools:context=\".MainActivity\">\n <TextView\n android:id=\"@+id/textView1\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"My color is Blue\"\n android:layout_centerInParent=\"true\"\n android:textStyle=\"bold\"\n android:textSize=\"36sp\"/>\n <TextView\n android:id=\"@+id/textView2\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:layout_below=\"@id/textView1\"\n android:layout_marginBottom=\"10dp\"\n android:text=\"My color is Green\"\n android:textStyle=\"bold\"\n android:layout_centerInParent=\"true\"\n android:textSize=\"36sp\" />\n</RelativeLayout>"
},
{
"code": null,
"e": 2325,
"s": 2268,
"text": "Step 3 − Add the following code to src/MainActivity.java"
},
{
"code": null,
"e": 2896,
"s": 2325,
"text": "import android.graphics.Color;\nimport android.support.v7.app.AppCompatActivity;\nimport android.os.Bundle;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n TextView textView1 = findViewById(R.id.textView1);\n textView1.setTextColor(Color.BLUE);\n TextView textView2 = findViewById(R.id.textView2);\n textView2.setTextColor(Color.parseColor(\"#006400\"));\n }\n}"
},
{
"code": null,
"e": 2951,
"s": 2896,
"text": "Step 4 − Add the following code to androidManifest.xml"
},
{
"code": null,
"e": 3621,
"s": 2951,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>"
},
{
"code": null,
"e": 3966,
"s": 3621,
"text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen"
},
{
"code": null,
"e": 4007,
"s": 3966,
"text": "Click here to download the project code."
}
] |
Difference Between ConcurrentHashMap, HashTable and Synchronized Map in Java - GeeksforGeeks | 26 Jul, 2021
Here we will be discussing out one by one individually then rolling onto the difference after having an adequate understanding of all three of them. We will be discussing ConcurrentHashMap first followed by HashTable, lastly followed by Synchronized Map. Let us start with ConcurrentHashMap first.
The underlying data structure for ConcurrentHashMap is HashTable. ConcurrentHashMap allows concurrent read and thread-safe update operations. To perform read operation thread won’t require any lock but to perform update operation thread require a lock, but it is the lock of only a particular part of Map(Bucket level lock). Instead of whole map concurrent update achieved by internally dividing the map into a smaller portion which is defined by concurrency level. The default concurrency level is 16 i.e ConcurrentHashMap allows simultaneously read and 16 write(update) operations. The value null is not allowed for both keys and values. While one thread is iterating the other thread can perform update operation and ConcurrentHashMap never throws ConcurrentModificationException.
Syntax:
ConcurrentHashMap<K,V> CHM = new ConcurrentHashMap<>();
The above constructor creates an empty ConcurrentHashMap with
Default initial capacity equals 16
Default fill ratio equals 0.75
Default concurrency level 16 where K is key and V is the value of ConcurrentHashMap
Example:
Java
// Java program to illustrate ConcurrentHashMap // Importing required packagesimport java.io.*;import java.util.*;import java.util.concurrent.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating ConcurrentHashMap class object // Declaring object of integer an string type ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<>(); // Adding entry to ConcurrentHashMap // Custom input entries chm.put(65, "A"); chm.put(66, "B"); // Print and display the ConcurrentHashMap System.out.println(chm); // Adding the entry if the given entry is not // present in the ConcurrentHashMap Custom input // entries chm.putIfAbsent(67, "C"); chm.putIfAbsent(68, "D"); // Printand display the ConcurrentHashMap System.out.println(chm); // Removing entry With Key and Value as 68 and D chm.remove(68, "D"); // Print and display the ConcurrentHashMap System.out.println(chm); // Replacing Value of an entry chm.replace(66, "B", "E"); // Again, print and display the ConcurrentHashMap System.out.println(chm); }}
{65=A, 66=B}
{65=A, 66=B, 67=C, 68=D}
{65=A, 66=B, 67=C}
{65=A, 66=E, 67=C}
Now dwelling on the second concept that is HashTable. The underlying data structure for HashTable is HashTable. Insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. The value null is not allowed for both key and value otherwise we will get RunTimeException saying NullPointerException. It implements Serializable and cloneable interfaces but not RandomAccess. Every method inside it is synchronized and hence HashTable objects are thread-safe. HashTable is the best choice if our frequent operation is search operation.
Syntax:
Hashtable<K,V> ht = new Hashtable<>();
The above constructor creates an empty hashtable object with an initial default capacity of 11 and a default fill ratio of 0.75. Where K is key and V is the value of a hashtable.
Example:
Java
// Java program to illustrate HashTable // Importing required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating Hashtable object Hashtable<Integer, String> ht = new Hashtable<>(); // Adding entry to Hashtable // Custom input entries ht.put(65, "A"); ht.put(66, "B"); ht.put(67, "C"); ht.put(68, "D"); // Print and display the HashTable elements System.out.println(ht); }}
{65=A, 68=D, 67=C, 66=B}
Lastly, discussing out Synchronized Map before landing upon conclusive differences between all three of them. The synchronizedMap() method is used to return a synchronized(thread-safe) map backed by the specified map. This method is present in java.util.Collections.
Syntax:
public static <K,V> Map<K,V> synchronizedMap(Map<K,V> M)
// where M is the map to be synchronized K is key
// and V is value for the resultant synchronized map.
Example:
Java
// Java program to demonstrate synchronizedMap() method // Importing required packagesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of HashMap // Declaring object of integer and string type HashMap<Integer, String> map = new HashMap<>(); // Adding entry to map object created above // Custom input entries map.put(65, "A"); map.put(66, "B"); map.put(67, "C"); map.put(68, "D"); // Print and display the map object System.out.println("Map is " + map); // Creating a synchronized map object // Declaring object of type integer and string Map<Integer, String> synmap = Collections.synchronizedMap(map); // Print and display the synchronized map // elements System.out.println("Synchronized map is : " + synmap); } // Catch block to handle the exceptions catch (IllegalArgumentException e) { // Display the exception on the console System.out.println(e); } }}
Map is {65=A, 66=B, 67=C, 68=D}
Synchronized map is : {65=A, 66=B, 67=C, 68=D}
By far we have discussed enough the concepts along with internal working through implementation in the programs. Let us finally conclude out the differences between them to get a tight grip to understand the minute difference between them.
anikaseth98
adnanirshad158
Java-Collections
Java-ConcurrentHashMap
Java-HashTable
Picked
Difference Between
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Difference Between Method Overloading and Method Overriding in Java
Difference between Synchronous and Asynchronous Transmission
Comparison between Adjacency List and Adjacency Matrix representation of Graph
Difference between LAN, MAN and WAN
Difference between Waterfall Model and Spiral Model
Arrays in Java
Split() String method in Java with examples
Arrays.sort() in Java with examples
For-each loop in Java
Initialize an ArrayList in Java | [
{
"code": null,
"e": 24467,
"s": 24439,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 24765,
"s": 24467,
"text": "Here we will be discussing out one by one individually then rolling onto the difference after having an adequate understanding of all three of them. We will be discussing ConcurrentHashMap first followed by HashTable, lastly followed by Synchronized Map. Let us start with ConcurrentHashMap first."
},
{
"code": null,
"e": 25551,
"s": 24765,
"text": "The underlying data structure for ConcurrentHashMap is HashTable. ConcurrentHashMap allows concurrent read and thread-safe update operations. To perform read operation thread won’t require any lock but to perform update operation thread require a lock, but it is the lock of only a particular part of Map(Bucket level lock). Instead of whole map concurrent update achieved by internally dividing the map into a smaller portion which is defined by concurrency level. The default concurrency level is 16 i.e ConcurrentHashMap allows simultaneously read and 16 write(update) operations. The value null is not allowed for both keys and values. While one thread is iterating the other thread can perform update operation and ConcurrentHashMap never throws ConcurrentModificationException."
},
{
"code": null,
"e": 25559,
"s": 25551,
"text": "Syntax:"
},
{
"code": null,
"e": 25616,
"s": 25559,
"text": "ConcurrentHashMap<K,V> CHM = new ConcurrentHashMap<>();"
},
{
"code": null,
"e": 25679,
"s": 25616,
"text": "The above constructor creates an empty ConcurrentHashMap with "
},
{
"code": null,
"e": 25714,
"s": 25679,
"text": "Default initial capacity equals 16"
},
{
"code": null,
"e": 25745,
"s": 25714,
"text": "Default fill ratio equals 0.75"
},
{
"code": null,
"e": 25829,
"s": 25745,
"text": "Default concurrency level 16 where K is key and V is the value of ConcurrentHashMap"
},
{
"code": null,
"e": 25838,
"s": 25829,
"text": "Example:"
},
{
"code": null,
"e": 25843,
"s": 25838,
"text": "Java"
},
{
"code": "// Java program to illustrate ConcurrentHashMap // Importing required packagesimport java.io.*;import java.util.*;import java.util.concurrent.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Creating ConcurrentHashMap class object // Declaring object of integer an string type ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<>(); // Adding entry to ConcurrentHashMap // Custom input entries chm.put(65, \"A\"); chm.put(66, \"B\"); // Print and display the ConcurrentHashMap System.out.println(chm); // Adding the entry if the given entry is not // present in the ConcurrentHashMap Custom input // entries chm.putIfAbsent(67, \"C\"); chm.putIfAbsent(68, \"D\"); // Printand display the ConcurrentHashMap System.out.println(chm); // Removing entry With Key and Value as 68 and D chm.remove(68, \"D\"); // Print and display the ConcurrentHashMap System.out.println(chm); // Replacing Value of an entry chm.replace(66, \"B\", \"E\"); // Again, print and display the ConcurrentHashMap System.out.println(chm); }}",
"e": 27106,
"s": 25843,
"text": null
},
{
"code": null,
"e": 27182,
"s": 27106,
"text": "{65=A, 66=B}\n{65=A, 66=B, 67=C, 68=D}\n{65=A, 66=B, 67=C}\n{65=A, 66=E, 67=C}"
},
{
"code": null,
"e": 27860,
"s": 27182,
"text": "Now dwelling on the second concept that is HashTable. The underlying data structure for HashTable is HashTable. Insertion order in HashTable is not preserved, and it is based on the hashcode of keys. Duplicates keys are not allowed, but values can be duplicated. Heterogeneous objects are allowed for both keys and values. The value null is not allowed for both key and value otherwise we will get RunTimeException saying NullPointerException. It implements Serializable and cloneable interfaces but not RandomAccess. Every method inside it is synchronized and hence HashTable objects are thread-safe. HashTable is the best choice if our frequent operation is search operation."
},
{
"code": null,
"e": 27869,
"s": 27860,
"text": "Syntax: "
},
{
"code": null,
"e": 27908,
"s": 27869,
"text": "Hashtable<K,V> ht = new Hashtable<>();"
},
{
"code": null,
"e": 28087,
"s": 27908,
"text": "The above constructor creates an empty hashtable object with an initial default capacity of 11 and a default fill ratio of 0.75. Where K is key and V is the value of a hashtable."
},
{
"code": null,
"e": 28097,
"s": 28087,
"text": "Example: "
},
{
"code": null,
"e": 28102,
"s": 28097,
"text": "Java"
},
{
"code": "// Java program to illustrate HashTable // Importing required packagesimport java.io.*;import java.util.*; // Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating Hashtable object Hashtable<Integer, String> ht = new Hashtable<>(); // Adding entry to Hashtable // Custom input entries ht.put(65, \"A\"); ht.put(66, \"B\"); ht.put(67, \"C\"); ht.put(68, \"D\"); // Print and display the HashTable elements System.out.println(ht); }}",
"e": 28655,
"s": 28102,
"text": null
},
{
"code": null,
"e": 28680,
"s": 28655,
"text": "{65=A, 68=D, 67=C, 66=B}"
},
{
"code": null,
"e": 28948,
"s": 28680,
"text": "Lastly, discussing out Synchronized Map before landing upon conclusive differences between all three of them. The synchronizedMap() method is used to return a synchronized(thread-safe) map backed by the specified map. This method is present in java.util.Collections."
},
{
"code": null,
"e": 28957,
"s": 28948,
"text": "Syntax: "
},
{
"code": null,
"e": 29126,
"s": 28957,
"text": "public static <K,V> Map<K,V> synchronizedMap(Map<K,V> M)\n\n// where M is the map to be synchronized K is key \n// and V is value for the resultant synchronized map. "
},
{
"code": null,
"e": 29135,
"s": 29126,
"text": "Example:"
},
{
"code": null,
"e": 29140,
"s": 29135,
"text": "Java"
},
{
"code": "// Java program to demonstrate synchronizedMap() method // Importing required packagesimport java.io.*;import java.util.*; // Main classpublic class GFG { // Main driver method public static void main(String[] args) { // Try block to check for exceptions try { // Creating object of HashMap // Declaring object of integer and string type HashMap<Integer, String> map = new HashMap<>(); // Adding entry to map object created above // Custom input entries map.put(65, \"A\"); map.put(66, \"B\"); map.put(67, \"C\"); map.put(68, \"D\"); // Print and display the map object System.out.println(\"Map is \" + map); // Creating a synchronized map object // Declaring object of type integer and string Map<Integer, String> synmap = Collections.synchronizedMap(map); // Print and display the synchronized map // elements System.out.println(\"Synchronized map is : \" + synmap); } // Catch block to handle the exceptions catch (IllegalArgumentException e) { // Display the exception on the console System.out.println(e); } }}",
"e": 30461,
"s": 29140,
"text": null
},
{
"code": null,
"e": 30540,
"s": 30461,
"text": "Map is {65=A, 66=B, 67=C, 68=D}\nSynchronized map is : {65=A, 66=B, 67=C, 68=D}"
},
{
"code": null,
"e": 30780,
"s": 30540,
"text": "By far we have discussed enough the concepts along with internal working through implementation in the programs. Let us finally conclude out the differences between them to get a tight grip to understand the minute difference between them."
},
{
"code": null,
"e": 30794,
"s": 30782,
"text": "anikaseth98"
},
{
"code": null,
"e": 30809,
"s": 30794,
"text": "adnanirshad158"
},
{
"code": null,
"e": 30826,
"s": 30809,
"text": "Java-Collections"
},
{
"code": null,
"e": 30849,
"s": 30826,
"text": "Java-ConcurrentHashMap"
},
{
"code": null,
"e": 30864,
"s": 30849,
"text": "Java-HashTable"
},
{
"code": null,
"e": 30871,
"s": 30864,
"text": "Picked"
},
{
"code": null,
"e": 30890,
"s": 30871,
"text": "Difference Between"
},
{
"code": null,
"e": 30895,
"s": 30890,
"text": "Java"
},
{
"code": null,
"e": 30900,
"s": 30895,
"text": "Java"
},
{
"code": null,
"e": 30917,
"s": 30900,
"text": "Java-Collections"
},
{
"code": null,
"e": 31015,
"s": 30917,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31024,
"s": 31015,
"text": "Comments"
},
{
"code": null,
"e": 31037,
"s": 31024,
"text": "Old Comments"
},
{
"code": null,
"e": 31105,
"s": 31037,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 31166,
"s": 31105,
"text": "Difference between Synchronous and Asynchronous Transmission"
},
{
"code": null,
"e": 31245,
"s": 31166,
"text": "Comparison between Adjacency List and Adjacency Matrix representation of Graph"
},
{
"code": null,
"e": 31281,
"s": 31245,
"text": "Difference between LAN, MAN and WAN"
},
{
"code": null,
"e": 31333,
"s": 31281,
"text": "Difference between Waterfall Model and Spiral Model"
},
{
"code": null,
"e": 31348,
"s": 31333,
"text": "Arrays in Java"
},
{
"code": null,
"e": 31392,
"s": 31348,
"text": "Split() String method in Java with examples"
},
{
"code": null,
"e": 31428,
"s": 31392,
"text": "Arrays.sort() in Java with examples"
},
{
"code": null,
"e": 31450,
"s": 31428,
"text": "For-each loop in Java"
}
] |
response.elapsed – Python requests | 01 Mar, 2020
Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.elapsed out of a response object. response.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response. It is often used to stop the connection after a certain point of time is “elapsed”.
To illustrate use of response.elapsed, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC.
Download and Install Python 3 Latest Version
How to install requests in Python – For windows, linux, mac
response.elapsed# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print elapsed timeprint(response.elapsed)
Save above file as request.py and run using
Python request.py
Check that 0:00:00.347420 at the start of output, it shows the elapsed time since the request is made.
There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute.
requests.status_code
If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources.
Python-requests
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n01 Mar, 2020"
},
{
"code": null,
"e": 627,
"s": 53,
"text": "Python requests are generally used to fetch the content from a particular resource URI. Whenever we make a request to a specified URI through Python, it returns a response object. Now, this response object would be used to access certain features such as content, headers, etc. This article revolves around how to check the response.elapsed out of a response object. response.elapsed returns a timedelta object with the time elapsed from sending the request to the arrival of the response. It is often used to stop the connection after a certain point of time is “elapsed”."
},
{
"code": null,
"e": 771,
"s": 627,
"text": "To illustrate use of response.elapsed, let’s ping API of Github. To run this script, you need to have Python and requests installed on your PC."
},
{
"code": null,
"e": 816,
"s": 771,
"text": "Download and Install Python 3 Latest Version"
},
{
"code": null,
"e": 876,
"s": 816,
"text": "How to install requests in Python – For windows, linux, mac"
},
{
"code": "response.elapsed# import requests moduleimport requests # Making a get requestresponse = requests.get('https://api.github.com') # print responseprint(response) # print elapsed timeprint(response.elapsed)",
"e": 1083,
"s": 876,
"text": null
},
{
"code": null,
"e": 1127,
"s": 1083,
"text": "Save above file as request.py and run using"
},
{
"code": null,
"e": 1146,
"s": 1127,
"text": "Python request.py\n"
},
{
"code": null,
"e": 1249,
"s": 1146,
"text": "Check that 0:00:00.347420 at the start of output, it shows the elapsed time since the request is made."
},
{
"code": null,
"e": 1500,
"s": 1249,
"text": "There are many libraries to make an HTTP request in Python, which are httplib, urllib, httplib2, treq, etc., but requests is the one of the best with cool features. If any attribute of requests shows NULL, check the status code using below attribute."
},
{
"code": null,
"e": 1521,
"s": 1500,
"text": "requests.status_code"
},
{
"code": null,
"e": 1678,
"s": 1521,
"text": "If status_code doesn’t lie in range of 200-29. You probably need to check method begin used for making a request + the url you are requesting for resources."
},
{
"code": null,
"e": 1694,
"s": 1678,
"text": "Python-requests"
},
{
"code": null,
"e": 1701,
"s": 1694,
"text": "Python"
}
] |
Python | Create video using multiple images using OpenCV | 08 Apr, 2019
As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let’s see how to create video using multiple images using OpenCV.
Install the following libraries:
PILcv2
Also, check the path before running the code otherwise you will be full with errors.
How it works ?Using PIL library we are opening images and resizing them to their mean_height and mean_width because the video which will be created using cv2 library required the input images of same height and width.Resized images are included in an array and frame of video is set with the mean_height and mean_width. Then by looping, we are appending each image to that frame.
Below is the implementation :
# importing librariesimport osimport cv2 from PIL import Image # Checking the current directory pathprint(os.getcwd()) # Folder which contains all the images# from which video is to be generatedos.chdir("C:\\Python\\Geekfolder2") path = "C:\\Python\\Geekfolder2" mean_height = 0mean_width = 0 num_of_images = len(os.listdir('.'))# print(num_of_images) for file in os.listdir('.'): im = Image.open(os.path.join(path, file)) width, height = im.size mean_width += width mean_height += height # im.show() # uncomment this for displaying the image # Finding the mean height and width of all images.# This is required because the video frame needs# to be set with same width and height. Otherwise# images not equal to that width height will not get # embedded into the videomean_width = int(mean_width / num_of_images)mean_height = int(mean_height / num_of_images) # print(mean_height)# print(mean_width) # Resizing of the images to give# them same width and height for file in os.listdir('.'): if file.endswith(".jpg") or file.endswith(".jpeg") or file.endswith("png"): # opening image using PIL Image im = Image.open(os.path.join(path, file)) # im.size includes the height and width of image width, height = im.size print(width, height) # resizing imResize = im.resize((mean_width, mean_height), Image.ANTIALIAS) imResize.save( file, 'JPEG', quality = 95) # setting quality # printing each resized image name print(im.filename.split('\\')[-1], " is resized") # Video Generating functiondef generate_video(): image_folder = '.' # make sure to use your folder video_name = 'mygeneratedvideo.avi' os.chdir("C:\\Python\\Geekfolder2") images = [img for img in os.listdir(image_folder) if img.endswith(".jpg") or img.endswith(".jpeg") or img.endswith("png")] # Array images should only consider # the image files ignoring others if any print(images) frame = cv2.imread(os.path.join(image_folder, images[0])) # setting the frame width, height width # the width, height of first image height, width, layers = frame.shape video = cv2.VideoWriter(video_name, 0, 1, (width, height)) # Appending the images to the video one by one for image in images: video.write(cv2.imread(os.path.join(image_folder, image))) # Deallocating memories taken for window creation cv2.destroyAllWindows() video.release() # releasing the video generated # Calling the generate_video functiongenerate_video()
Output:
Get the link to the input images used and output video from here.
Better alternatives:If we want more effects, sound with the video then it will be good to use the ffmpeg python library which offers this kind of functionalities.
Image-Processing
OpenCV
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Enumerate() in Python
Different ways to create Pandas Dataframe
How to Install PIP on Windows ?
Python String | replace()
Introduction To PYTHON
Python OOPs Concepts
Python Classes and Objects
*args and **kwargs in Python
Create a Pandas DataFrame from Lists | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n08 Apr, 2019"
},
{
"code": null,
"e": 230,
"s": 53,
"text": "As we know OpenCV is a widely used library for image processing. It provides a wide sense of image processing. Let’s see how to create video using multiple images using OpenCV."
},
{
"code": null,
"e": 263,
"s": 230,
"text": "Install the following libraries:"
},
{
"code": null,
"e": 270,
"s": 263,
"text": "PILcv2"
},
{
"code": null,
"e": 355,
"s": 270,
"text": "Also, check the path before running the code otherwise you will be full with errors."
},
{
"code": null,
"e": 735,
"s": 355,
"text": "How it works ?Using PIL library we are opening images and resizing them to their mean_height and mean_width because the video which will be created using cv2 library required the input images of same height and width.Resized images are included in an array and frame of video is set with the mean_height and mean_width. Then by looping, we are appending each image to that frame."
},
{
"code": null,
"e": 765,
"s": 735,
"text": "Below is the implementation :"
},
{
"code": "# importing librariesimport osimport cv2 from PIL import Image # Checking the current directory pathprint(os.getcwd()) # Folder which contains all the images# from which video is to be generatedos.chdir(\"C:\\\\Python\\\\Geekfolder2\") path = \"C:\\\\Python\\\\Geekfolder2\" mean_height = 0mean_width = 0 num_of_images = len(os.listdir('.'))# print(num_of_images) for file in os.listdir('.'): im = Image.open(os.path.join(path, file)) width, height = im.size mean_width += width mean_height += height # im.show() # uncomment this for displaying the image # Finding the mean height and width of all images.# This is required because the video frame needs# to be set with same width and height. Otherwise# images not equal to that width height will not get # embedded into the videomean_width = int(mean_width / num_of_images)mean_height = int(mean_height / num_of_images) # print(mean_height)# print(mean_width) # Resizing of the images to give# them same width and height for file in os.listdir('.'): if file.endswith(\".jpg\") or file.endswith(\".jpeg\") or file.endswith(\"png\"): # opening image using PIL Image im = Image.open(os.path.join(path, file)) # im.size includes the height and width of image width, height = im.size print(width, height) # resizing imResize = im.resize((mean_width, mean_height), Image.ANTIALIAS) imResize.save( file, 'JPEG', quality = 95) # setting quality # printing each resized image name print(im.filename.split('\\\\')[-1], \" is resized\") # Video Generating functiondef generate_video(): image_folder = '.' # make sure to use your folder video_name = 'mygeneratedvideo.avi' os.chdir(\"C:\\\\Python\\\\Geekfolder2\") images = [img for img in os.listdir(image_folder) if img.endswith(\".jpg\") or img.endswith(\".jpeg\") or img.endswith(\"png\")] # Array images should only consider # the image files ignoring others if any print(images) frame = cv2.imread(os.path.join(image_folder, images[0])) # setting the frame width, height width # the width, height of first image height, width, layers = frame.shape video = cv2.VideoWriter(video_name, 0, 1, (width, height)) # Appending the images to the video one by one for image in images: video.write(cv2.imread(os.path.join(image_folder, image))) # Deallocating memories taken for window creation cv2.destroyAllWindows() video.release() # releasing the video generated # Calling the generate_video functiongenerate_video()",
"e": 3391,
"s": 765,
"text": null
},
{
"code": null,
"e": 3399,
"s": 3391,
"text": "Output:"
},
{
"code": null,
"e": 3465,
"s": 3399,
"text": "Get the link to the input images used and output video from here."
},
{
"code": null,
"e": 3628,
"s": 3465,
"text": "Better alternatives:If we want more effects, sound with the video then it will be good to use the ffmpeg python library which offers this kind of functionalities."
},
{
"code": null,
"e": 3645,
"s": 3628,
"text": "Image-Processing"
},
{
"code": null,
"e": 3652,
"s": 3645,
"text": "OpenCV"
},
{
"code": null,
"e": 3659,
"s": 3652,
"text": "Python"
},
{
"code": null,
"e": 3757,
"s": 3659,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3775,
"s": 3757,
"text": "Python Dictionary"
},
{
"code": null,
"e": 3797,
"s": 3775,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 3839,
"s": 3797,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 3871,
"s": 3839,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 3897,
"s": 3871,
"text": "Python String | replace()"
},
{
"code": null,
"e": 3920,
"s": 3897,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 3941,
"s": 3920,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 3968,
"s": 3941,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 3997,
"s": 3968,
"text": "*args and **kwargs in Python"
}
] |
GATE | GATE-CS-2015 (Set 3) | Question 65 | 28 Jun, 2021
Consider the following relation
Cinema (theater, address, capacity)
Which of the following options will be needed at the end of the SQL query
SELECT P1. address
FROM Cinema P1
Such that it always finds the addresses of theaters with maximum capacity?(A) WHERE P1. Capacity> = All (select P2. Capacity from Cinema P2)(B) WHERE P1. Capacity> = Any (select P2. Capacity from Cinema P2)(C) WHERE P1. Capacity > All (select max(P2. Capacity) from Cinema P2)(D) WHERE P1. Capacity > Any (select max (P2. Capacity) from Cinema P2)Answer: (A)Explanation: When the ALL condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with AND operators.
When the ANY condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with OR operators, as shown below.
Source: http://oracle-base.com/articles/misc/all-any-some-comparison-conditions-in-sql.phpQuiz of this Question
GATE-CS-2015 (Set 3)
GATE-GATE-CS-2015 (Set 3)
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 60,
"s": 28,
"text": "Consider the following relation"
},
{
"code": null,
"e": 99,
"s": 60,
"text": " Cinema (theater, address, capacity) "
},
{
"code": null,
"e": 173,
"s": 99,
"text": "Which of the following options will be needed at the end of the SQL query"
},
{
"code": null,
"e": 208,
"s": 173,
"text": "SELECT P1. address\nFROM Cinema P1 "
},
{
"code": null,
"e": 743,
"s": 208,
"text": "Such that it always finds the addresses of theaters with maximum capacity?(A) WHERE P1. Capacity> = All (select P2. Capacity from Cinema P2)(B) WHERE P1. Capacity> = Any (select P2. Capacity from Cinema P2)(C) WHERE P1. Capacity > All (select max(P2. Capacity) from Cinema P2)(D) WHERE P1. Capacity > Any (select max (P2. Capacity) from Cinema P2)Answer: (A)Explanation: When the ALL condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with AND operators."
},
{
"code": null,
"e": 922,
"s": 743,
"text": "When the ANY condition is followed by a list, the optimizer expands the initial condition to all elements of the list and strings them together with OR operators, as shown below."
},
{
"code": null,
"e": 1034,
"s": 922,
"text": "Source: http://oracle-base.com/articles/misc/all-any-some-comparison-conditions-in-sql.phpQuiz of this Question"
},
{
"code": null,
"e": 1055,
"s": 1034,
"text": "GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 1081,
"s": 1055,
"text": "GATE-GATE-CS-2015 (Set 3)"
},
{
"code": null,
"e": 1086,
"s": 1081,
"text": "GATE"
}
] |
TimeField – Django Forms | 13 Feb, 2020
TimeField in Django Forms is a time input field, for input of time for particular instance or similar. The default widget for this input is TimeInput. It validates that the given value is either a datetime.time or string formatted in a particular time format.
TimeField has following optional argument:
input_formats :- A list of formats used to attempt to convert a string to a valid datetime.time object. If no input_formats argument is provided, the default input formats are:
'%H:%M:%S', # '14:30:59'
'%H:%M', # '14:30'
Syntax
field_name = forms.TimeField(**options)
Illustration of TimeField using an Example. Consider a project named geeksforgeeks having an app named geeks.
Refer to the following articles to check how to create a project and an app in Django.
How to Create a Basic Project using MVT in Django?
How to Create an App in Django ?
Enter the following code into forms.py file of geeks app.
from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.TimeField( )
Add the geeks app to INSTALLED_APPS
# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]
Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, "home.html", context)
Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html.
<form method = "POST"> {% csrf_token %} {{ form }} <input type = "submit" value = "Submit"></form>
Finally, a URL to map to this view in urls.py
from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]
Let’s run the server and check what has actually happened, Run
Python manage.py runserver
Thus, an geeks_field TimeField is created by replacing “_” with ” “.
TimeField is used for input of time in the database through Django forms. One can input the current time, time of birth etc. Till now we have discussed how to implement TimeField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance. To get working code of TimeField click here.In views.py,
from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.POST: temp = request.POST['geeks_field'] print(temp) return render(request, "home.html", context)
Now let’s try entering something else into the field.
Since it needs to be verified according to the time, Let’s enter “09:00” in the field.
Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose.
Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to TimeField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:
NaveenArora
Django-forms
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n13 Feb, 2020"
},
{
"code": null,
"e": 288,
"s": 28,
"text": "TimeField in Django Forms is a time input field, for input of time for particular instance or similar. The default widget for this input is TimeInput. It validates that the given value is either a datetime.time or string formatted in a particular time format."
},
{
"code": null,
"e": 331,
"s": 288,
"text": "TimeField has following optional argument:"
},
{
"code": null,
"e": 508,
"s": 331,
"text": "input_formats :- A list of formats used to attempt to convert a string to a valid datetime.time object. If no input_formats argument is provided, the default input formats are:"
},
{
"code": null,
"e": 564,
"s": 508,
"text": "'%H:%M:%S', # '14:30:59'\n'%H:%M', # '14:30'\n"
},
{
"code": null,
"e": 571,
"s": 564,
"text": "Syntax"
},
{
"code": null,
"e": 611,
"s": 571,
"text": "field_name = forms.TimeField(**options)"
},
{
"code": null,
"e": 721,
"s": 611,
"text": "Illustration of TimeField using an Example. Consider a project named geeksforgeeks having an app named geeks."
},
{
"code": null,
"e": 808,
"s": 721,
"text": "Refer to the following articles to check how to create a project and an app in Django."
},
{
"code": null,
"e": 859,
"s": 808,
"text": "How to Create a Basic Project using MVT in Django?"
},
{
"code": null,
"e": 892,
"s": 859,
"text": "How to Create an App in Django ?"
},
{
"code": null,
"e": 950,
"s": 892,
"text": "Enter the following code into forms.py file of geeks app."
},
{
"code": "from django import forms # creating a form class GeeksForm(forms.Form): geeks_field = forms.TimeField( )",
"e": 1059,
"s": 950,
"text": null
},
{
"code": null,
"e": 1095,
"s": 1059,
"text": "Add the geeks app to INSTALLED_APPS"
},
{
"code": "# Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'geeks',]",
"e": 1333,
"s": 1095,
"text": null
},
{
"code": null,
"e": 1466,
"s": 1333,
"text": "Now to render this form into a view we need a view and a URL mapped to that URL. Let’s create a view first in views.py of geeks app,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context = {} context['form'] = GeeksForm() return render( request, \"home.html\", context)",
"e": 1678,
"s": 1466,
"text": null
},
{
"code": null,
"e": 1964,
"s": 1678,
"text": "Here we are importing that particular form from forms.py and creating an object of it in the view so that it can be rendered in a template.Now, to initiate a Django form you need to create home.html where one would be designing the stuff as they like. Let’s create a form in home.html."
},
{
"code": "<form method = \"POST\"> {% csrf_token %} {{ form }} <input type = \"submit\" value = \"Submit\"></form>",
"e": 2072,
"s": 1964,
"text": null
},
{
"code": null,
"e": 2118,
"s": 2072,
"text": "Finally, a URL to map to this view in urls.py"
},
{
"code": "from django.urls import path # importing views from views..pyfrom .views import home_view urlpatterns = [ path('', home_view ),]",
"e": 2252,
"s": 2118,
"text": null
},
{
"code": null,
"e": 2315,
"s": 2252,
"text": "Let’s run the server and check what has actually happened, Run"
},
{
"code": null,
"e": 2342,
"s": 2315,
"text": "Python manage.py runserver"
},
{
"code": null,
"e": 2411,
"s": 2342,
"text": "Thus, an geeks_field TimeField is created by replacing “_” with ” “."
},
{
"code": null,
"e": 2813,
"s": 2411,
"text": "TimeField is used for input of time in the database through Django forms. One can input the current time, time of birth etc. Till now we have discussed how to implement TimeField but how to use it in the view for performing the logical part. To perform some logic we would need to get the value entered into field into a python string instance. To get working code of TimeField click here.In views.py,"
},
{
"code": "from django.shortcuts import renderfrom .forms import GeeksForm # Create your views here.def home_view(request): context ={} form = GeeksForm() context['form']= form if request.POST: temp = request.POST['geeks_field'] print(temp) return render(request, \"home.html\", context)",
"e": 3118,
"s": 2813,
"text": null
},
{
"code": null,
"e": 3172,
"s": 3118,
"text": "Now let’s try entering something else into the field."
},
{
"code": null,
"e": 3259,
"s": 3172,
"text": "Since it needs to be verified according to the time, Let’s enter “09:00” in the field."
},
{
"code": null,
"e": 3505,
"s": 3259,
"text": "Now this data can be fetched using corresponding request dictionary. If method is GET, data would be available in request.GET and if post, request.POST correspondingly. In above example we have the value in temp which we can use for any purpose."
},
{
"code": null,
"e": 3932,
"s": 3505,
"text": "Core Field arguments are the arguments given to each field for applying some constraint or imparting a particular characteristic to a particular Field. For example, adding an argument required = False to TimeField will enable it to be left blank by the user. Each Field class constructor takes at least these arguments. Some Field classes take additional, field-specific arguments, but the following should always be accepted:"
},
{
"code": null,
"e": 3944,
"s": 3932,
"text": "NaveenArora"
},
{
"code": null,
"e": 3957,
"s": 3944,
"text": "Django-forms"
},
{
"code": null,
"e": 3971,
"s": 3957,
"text": "Python Django"
},
{
"code": null,
"e": 3978,
"s": 3971,
"text": "Python"
}
] |
HashSet clear() Method in Java | 26 Nov, 2018
The Java.util.HashSet.clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet.
Syntax:
Hash_Set.clear()
Parameters: The method does not take any parameter
Return Value: The function does not returns any value.
Below program illustrate the Java.util.HashSet.clear() method:
// Java code to illustrate clear()import java.io.*;import java.util.HashSet; public class HashSetDemo{ public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add("Welcome"); set.add("To"); set.add("Geeks"); set.add("4"); set.add("Geeks"); // Displaying the HashSet System.out.println("HashSet: " + set); // Clearing the HashSet using clear() method set.clear(); // Displaying the final Set after clearing; System.out.println("The final set: " + set); }}
HashSet: [4, Geeks, Welcome, To]
The final set: []
Java - util package
Java-Collections
Java-Functions
java-hashset
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Nov, 2018"
},
{
"code": null,
"e": 301,
"s": 28,
"text": "The Java.util.HashSet.clear() method is used to remove all the elements from a HashSet. Using the clear() method only clears all the element from the set and not deletes the set. In other words, we can say that the clear() method is used to only empty an existing HashSet."
},
{
"code": null,
"e": 309,
"s": 301,
"text": "Syntax:"
},
{
"code": null,
"e": 326,
"s": 309,
"text": "Hash_Set.clear()"
},
{
"code": null,
"e": 377,
"s": 326,
"text": "Parameters: The method does not take any parameter"
},
{
"code": null,
"e": 432,
"s": 377,
"text": "Return Value: The function does not returns any value."
},
{
"code": null,
"e": 495,
"s": 432,
"text": "Below program illustrate the Java.util.HashSet.clear() method:"
},
{
"code": "// Java code to illustrate clear()import java.io.*;import java.util.HashSet; public class HashSetDemo{ public static void main(String args[]) { // Creating an empty HashSet HashSet<String> set = new HashSet<String>(); // Use add() method to add elements into the Set set.add(\"Welcome\"); set.add(\"To\"); set.add(\"Geeks\"); set.add(\"4\"); set.add(\"Geeks\"); // Displaying the HashSet System.out.println(\"HashSet: \" + set); // Clearing the HashSet using clear() method set.clear(); // Displaying the final Set after clearing; System.out.println(\"The final set: \" + set); }}",
"e": 1178,
"s": 495,
"text": null
},
{
"code": null,
"e": 1230,
"s": 1178,
"text": "HashSet: [4, Geeks, Welcome, To]\nThe final set: []\n"
},
{
"code": null,
"e": 1250,
"s": 1230,
"text": "Java - util package"
},
{
"code": null,
"e": 1267,
"s": 1250,
"text": "Java-Collections"
},
{
"code": null,
"e": 1282,
"s": 1267,
"text": "Java-Functions"
},
{
"code": null,
"e": 1295,
"s": 1282,
"text": "java-hashset"
},
{
"code": null,
"e": 1300,
"s": 1295,
"text": "Java"
},
{
"code": null,
"e": 1305,
"s": 1300,
"text": "Java"
},
{
"code": null,
"e": 1322,
"s": 1305,
"text": "Java-Collections"
}
] |
Program to replace a word with asterisks in a sentence | 15 Jul, 2022
For the given sentence as input, censor a specific word with asterisks ‘ * ‘. Example :
Input : word = “computer” text = “GeeksforGeeks is a computer science portal for geeks. People who love computer and computer codes can contribute their valuables/ideas on computer codes/structures on here.” Output : GeeksforGeeks is a ******** science portal for geeks. People who love ******** and ******** codes can contribute their valuables/ideas on ******** codes/structures on here.
Chapters
descriptions off, selected
captions settings, opens captions settings dialog
captions off, selected
English
This is a modal window.
Beginning of dialog window. Escape will cancel and close the window.
End of dialog window.
The idea is to first split given sentence into different words. Then traverse the word list. For every word in the word list, check if it matches with given word. If yes, then replace the word with stars in the list. Finally merge the words of list and print.
C++
Java
Python3
C#
PHP
Javascript
// C++ program to censor a word// with asterisks in a sentence#include<bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function takes two parameterstring censor(string text, string word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list vector<string> word_list; boost::split(word_list, text, boost::is_any_of("\\ +")); // A new string to store the result string result = ""; // Creating the censor which is an asterisks // "*" text of the length of censor word string stars = ""; for (int i = 0; i < word.size(); i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; for (string i : word_list) { if (i.compare(word) == 0) { // changing the censored word to // created asterisks censor word_list[index] = stars; } index++; } // join the words for (string i : word_list) { result += i + ' '; } return result;} // Driver codeint main(){ string extract = "GeeksforGeeks is a computer science " "portal for geeks. I am pursuing my " "major in computer science. "; string cen = "computer"; cout << (censor(extract, cen));} // This code is contributed by Rajput-Ji
// Java program to censor a word// with asterisks in a sentenceclass GFG{ // Function takes two parameterstatic String censor(String text, String word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list String[] word_list = text.split("\\s+"); // A new string to store the result String result = ""; // Creating the censor which is an asterisks // "*" text of the length of censor word String stars = ""; for (int i = 0; i < word.length(); i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; for (String i : word_list) { if (i.compareTo(word) == 0) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words for (String i : word_list) result += i + ' '; return result;} // Driver codepublic static void main(String[] args){ String extract = "GeeksforGeeks is a computer science "+ "portal for geeks. I am pursuing my " + "major in computer science. "; String cen = "computer"; System.out.println(censor(extract, cen));}} // This code is contributed by// sanjeev2552
# Python Program to censor a word# with asterisks in a sentence # Function takes two parameterdef censor(text, word): # Break down sentence by ' ' spaces # and store each individual word in # a different list word_list = text.split() # A new string to store the result result = '' # Creating the censor which is an asterisks # "*" text of the length of censor word stars = '*' * len(word) # count variable to # access our word_list count = 0 # Iterating through our list # of extracted words index = 0; for i in word_list: if i == word: # changing the censored word to # created asterisks censor word_list[index] = stars index += 1 # join the words result =' '.join(word_list) return result # Driver codeif __name__== '__main__': extract = "GeeksforGeeks is a computer science portal for geeks.\ I am pursuing my major in computer science. " cen = "computer" print(censor(extract, cen))
// C# program to censor a word// with asterisks in a sentenceusing System;using System.Collections.Generic; class GFG{ // Function takes two parameterstatic String censor(String text, String word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list String[] word_list = text.Split(' '); // A new string to store the result String result = ""; // Creating the censor which is an asterisks // "*" text of the length of censor word String stars = ""; for (int i = 0; i < word.Length; i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; foreach (String i in word_list) { if (i.CompareTo(word) == 0) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words foreach (String i in word_list) result += i + " "; return result;} // Driver codepublic static void Main(String[] args){ String extract = "GeeksforGeeks is a computer science "+ "portal for geeks. I am pursuing my " + "major in computer science. "; String cen = "computer"; Console.WriteLine(censor(extract, cen));}} // This code is contributed by PrinciRaj1992
<?php// PHP Program to censor a word// with asterisks in a sentence // Function takes two parameterfunction censor($text, $word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list $word_list = explode(" ", $text); // A new string to store the result $result = ''; // Creating the censor which is an // asterisks "*" text of the length // of censor word $stars = ""; for($i = 0; $i < strlen($word); $i++) $stars .= "*"; // count variable to access // our word_list $count = 0; // Iterating through our list of // extracted words $index = 0; for($i = 0; $i < sizeof($word_list); $i++) { if($word_list[$i] == $word) // changing the censored word to // created asterisks censor $word_list[$index] = $stars; $index += 1; } // join the words return implode(' ', $word_list);} // Driver code$extract = "GeeksforGeeks is a computer science ". "portal for geeks.\nI am pursuing my ". "major in computer science. "; $cen = "computer";echo censor($extract, $cen); // This code is contributed// by Aman ojha?>
<script> // JavaScript program to censor a word // with asterisks in a sentence // Function takes two parameter function censor(text, word) { // Break down sentence by ' ' spaces // and store each individual word in // a different list var word_list = text.split(" "); // A new string to store the result var result = ""; // Creating the censor which is an asterisks // "*" text of the length of censor word var stars = ""; for (var i = 0; i < word.length; i++) stars += "*"; // Iterating through our list // of extracted words var index = 0; for (const i of word_list) { if (i === word) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words for (const i of word_list) { result += i + " "; } return result; } // Driver code var extract = "GeeksforGeeks is a computer science " + "portal for geeks. I am pursuing my " + "major in computer science. "; var cen = "computer"; document.write(censor(extract, cen) + "<br>"); </script>
GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science.
Time complexity: O(length(word)+M), where M is the number of words in text
Auxiliary Space: O(1)
Approach : Using replace() in python3.Replace() method searches for the string passed as the first argument in the given string and then replaces that with the second argument.
Python3
# Python Program to censor a word# with asterisks in a sentence extract = "GeeksforGeeks is a computer science portal for geeks.I am pursuing my major in computer science. " cen = "computer"extract=extract.replace(cen,'*'*len(cen))print(extract)
GeeksforGeeks is a ******** science portal for geeks.\I am pursuing my major in ******** science.
Aman ojha
sanjeev2552
princiraj1992
Rajput-Ji
rdtank
hasani
kogantibhavya
Python string-programs
python-string
Pattern Searching
Python
Python Programs
Strings
Strings
Pattern Searching
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n15 Jul, 2022"
},
{
"code": null,
"e": 141,
"s": 52,
"text": "For the given sentence as input, censor a specific word with asterisks ‘ * ‘. Example : "
},
{
"code": null,
"e": 531,
"s": 141,
"text": "Input : word = “computer” text = “GeeksforGeeks is a computer science portal for geeks. People who love computer and computer codes can contribute their valuables/ideas on computer codes/structures on here.” Output : GeeksforGeeks is a ******** science portal for geeks. People who love ******** and ******** codes can contribute their valuables/ideas on ******** codes/structures on here."
},
{
"code": null,
"e": 540,
"s": 531,
"text": "Chapters"
},
{
"code": null,
"e": 567,
"s": 540,
"text": "descriptions off, selected"
},
{
"code": null,
"e": 617,
"s": 567,
"text": "captions settings, opens captions settings dialog"
},
{
"code": null,
"e": 640,
"s": 617,
"text": "captions off, selected"
},
{
"code": null,
"e": 648,
"s": 640,
"text": "English"
},
{
"code": null,
"e": 672,
"s": 648,
"text": "This is a modal window."
},
{
"code": null,
"e": 741,
"s": 672,
"text": "Beginning of dialog window. Escape will cancel and close the window."
},
{
"code": null,
"e": 763,
"s": 741,
"text": "End of dialog window."
},
{
"code": null,
"e": 1025,
"s": 763,
"text": "The idea is to first split given sentence into different words. Then traverse the word list. For every word in the word list, check if it matches with given word. If yes, then replace the word with stars in the list. Finally merge the words of list and print. "
},
{
"code": null,
"e": 1029,
"s": 1025,
"text": "C++"
},
{
"code": null,
"e": 1034,
"s": 1029,
"text": "Java"
},
{
"code": null,
"e": 1042,
"s": 1034,
"text": "Python3"
},
{
"code": null,
"e": 1045,
"s": 1042,
"text": "C#"
},
{
"code": null,
"e": 1049,
"s": 1045,
"text": "PHP"
},
{
"code": null,
"e": 1060,
"s": 1049,
"text": "Javascript"
},
{
"code": "// C++ program to censor a word// with asterisks in a sentence#include<bits/stdc++.h>#include <boost/algorithm/string.hpp>using namespace std; // Function takes two parameterstring censor(string text, string word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list vector<string> word_list; boost::split(word_list, text, boost::is_any_of(\"\\\\ +\")); // A new string to store the result string result = \"\"; // Creating the censor which is an asterisks // \"*\" text of the length of censor word string stars = \"\"; for (int i = 0; i < word.size(); i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; for (string i : word_list) { if (i.compare(word) == 0) { // changing the censored word to // created asterisks censor word_list[index] = stars; } index++; } // join the words for (string i : word_list) { result += i + ' '; } return result;} // Driver codeint main(){ string extract = \"GeeksforGeeks is a computer science \" \"portal for geeks. I am pursuing my \" \"major in computer science. \"; string cen = \"computer\"; cout << (censor(extract, cen));} // This code is contributed by Rajput-Ji",
"e": 2445,
"s": 1060,
"text": null
},
{
"code": "// Java program to censor a word// with asterisks in a sentenceclass GFG{ // Function takes two parameterstatic String censor(String text, String word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list String[] word_list = text.split(\"\\\\s+\"); // A new string to store the result String result = \"\"; // Creating the censor which is an asterisks // \"*\" text of the length of censor word String stars = \"\"; for (int i = 0; i < word.length(); i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; for (String i : word_list) { if (i.compareTo(word) == 0) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words for (String i : word_list) result += i + ' '; return result;} // Driver codepublic static void main(String[] args){ String extract = \"GeeksforGeeks is a computer science \"+ \"portal for geeks. I am pursuing my \" + \"major in computer science. \"; String cen = \"computer\"; System.out.println(censor(extract, cen));}} // This code is contributed by// sanjeev2552",
"e": 3740,
"s": 2445,
"text": null
},
{
"code": "# Python Program to censor a word# with asterisks in a sentence # Function takes two parameterdef censor(text, word): # Break down sentence by ' ' spaces # and store each individual word in # a different list word_list = text.split() # A new string to store the result result = '' # Creating the censor which is an asterisks # \"*\" text of the length of censor word stars = '*' * len(word) # count variable to # access our word_list count = 0 # Iterating through our list # of extracted words index = 0; for i in word_list: if i == word: # changing the censored word to # created asterisks censor word_list[index] = stars index += 1 # join the words result =' '.join(word_list) return result # Driver codeif __name__== '__main__': extract = \"GeeksforGeeks is a computer science portal for geeks.\\ I am pursuing my major in computer science. \" cen = \"computer\" print(censor(extract, cen))",
"e": 4798,
"s": 3740,
"text": null
},
{
"code": "// C# program to censor a word// with asterisks in a sentenceusing System;using System.Collections.Generic; class GFG{ // Function takes two parameterstatic String censor(String text, String word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list String[] word_list = text.Split(' '); // A new string to store the result String result = \"\"; // Creating the censor which is an asterisks // \"*\" text of the length of censor word String stars = \"\"; for (int i = 0; i < word.Length; i++) stars += '*'; // Iterating through our list // of extracted words int index = 0; foreach (String i in word_list) { if (i.CompareTo(word) == 0) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words foreach (String i in word_list) result += i + \" \"; return result;} // Driver codepublic static void Main(String[] args){ String extract = \"GeeksforGeeks is a computer science \"+ \"portal for geeks. I am pursuing my \" + \"major in computer science. \"; String cen = \"computer\"; Console.WriteLine(censor(extract, cen));}} // This code is contributed by PrinciRaj1992",
"e": 6146,
"s": 4798,
"text": null
},
{
"code": "<?php// PHP Program to censor a word// with asterisks in a sentence // Function takes two parameterfunction censor($text, $word){ // Break down sentence by ' ' spaces // and store each individual word in // a different list $word_list = explode(\" \", $text); // A new string to store the result $result = ''; // Creating the censor which is an // asterisks \"*\" text of the length // of censor word $stars = \"\"; for($i = 0; $i < strlen($word); $i++) $stars .= \"*\"; // count variable to access // our word_list $count = 0; // Iterating through our list of // extracted words $index = 0; for($i = 0; $i < sizeof($word_list); $i++) { if($word_list[$i] == $word) // changing the censored word to // created asterisks censor $word_list[$index] = $stars; $index += 1; } // join the words return implode(' ', $word_list);} // Driver code$extract = \"GeeksforGeeks is a computer science \". \"portal for geeks.\\nI am pursuing my \". \"major in computer science. \"; $cen = \"computer\";echo censor($extract, $cen); // This code is contributed// by Aman ojha?>",
"e": 7363,
"s": 6146,
"text": null
},
{
"code": "<script> // JavaScript program to censor a word // with asterisks in a sentence // Function takes two parameter function censor(text, word) { // Break down sentence by ' ' spaces // and store each individual word in // a different list var word_list = text.split(\" \"); // A new string to store the result var result = \"\"; // Creating the censor which is an asterisks // \"*\" text of the length of censor word var stars = \"\"; for (var i = 0; i < word.length; i++) stars += \"*\"; // Iterating through our list // of extracted words var index = 0; for (const i of word_list) { if (i === word) // changing the censored word to // created asterisks censor word_list[index] = stars; index++; } // join the words for (const i of word_list) { result += i + \" \"; } return result; } // Driver code var extract = \"GeeksforGeeks is a computer science \" + \"portal for geeks. I am pursuing my \" + \"major in computer science. \"; var cen = \"computer\"; document.write(censor(extract, cen) + \"<br>\"); </script>",
"e": 8642,
"s": 7363,
"text": null
},
{
"code": null,
"e": 8742,
"s": 8642,
"text": "GeeksforGeeks is a ******** science portal for geeks. I am pursuing my major in ******** science. "
},
{
"code": null,
"e": 8817,
"s": 8742,
"text": "Time complexity: O(length(word)+M), where M is the number of words in text"
},
{
"code": null,
"e": 8839,
"s": 8817,
"text": "Auxiliary Space: O(1)"
},
{
"code": null,
"e": 9016,
"s": 8839,
"text": "Approach : Using replace() in python3.Replace() method searches for the string passed as the first argument in the given string and then replaces that with the second argument."
},
{
"code": null,
"e": 9024,
"s": 9016,
"text": "Python3"
},
{
"code": "# Python Program to censor a word# with asterisks in a sentence extract = \"GeeksforGeeks is a computer science portal for geeks.I am pursuing my major in computer science. \" cen = \"computer\"extract=extract.replace(cen,'*'*len(cen))print(extract)",
"e": 9280,
"s": 9024,
"text": null
},
{
"code": null,
"e": 9379,
"s": 9280,
"text": "GeeksforGeeks is a ******** science portal for geeks.\\I am pursuing my major in ******** science. "
},
{
"code": null,
"e": 9389,
"s": 9379,
"text": "Aman ojha"
},
{
"code": null,
"e": 9401,
"s": 9389,
"text": "sanjeev2552"
},
{
"code": null,
"e": 9415,
"s": 9401,
"text": "princiraj1992"
},
{
"code": null,
"e": 9425,
"s": 9415,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 9432,
"s": 9425,
"text": "rdtank"
},
{
"code": null,
"e": 9439,
"s": 9432,
"text": "hasani"
},
{
"code": null,
"e": 9453,
"s": 9439,
"text": "kogantibhavya"
},
{
"code": null,
"e": 9476,
"s": 9453,
"text": "Python string-programs"
},
{
"code": null,
"e": 9490,
"s": 9476,
"text": "python-string"
},
{
"code": null,
"e": 9508,
"s": 9490,
"text": "Pattern Searching"
},
{
"code": null,
"e": 9515,
"s": 9508,
"text": "Python"
},
{
"code": null,
"e": 9531,
"s": 9515,
"text": "Python Programs"
},
{
"code": null,
"e": 9539,
"s": 9531,
"text": "Strings"
},
{
"code": null,
"e": 9547,
"s": 9539,
"text": "Strings"
},
{
"code": null,
"e": 9565,
"s": 9547,
"text": "Pattern Searching"
}
] |
Introduction to SAS programming | 09 Jun, 2022
Statistical Analysis System (SAS) is a software suite that has been developed by SAS Institute, one of the leaders in analytics. It is useful for performing advanced analytics, multivariate analyses, business intelligence, data management functions, and also for conducting predictive analytics.
Use of SAS:
SAS is used by many top organizations which include Google, Facebook, Twitter and Accenture for answering the many questions which persist at a business and organizational level and is also used for generating informative reports. It helps in business forecasting, quality improvement, operations research and project management. It is particularly useful in applications development and graphics design. This article should help you get an intuition about the working of SAS applications and a hint about it’s raw power.
Types of SAS software:
There are various types of SAS software that are available.In general there are 4 types of SAS software which are given below.
SAS for WindowsSAS EG (Enterprise Guide)SAS Enterprise Miner (EM)SAS Stat Software
SAS for Windows
SAS EG (Enterprise Guide)
SAS Enterprise Miner (EM)
SAS Stat Software
The most used software among the above types is SAS for Windows. It can be easily deployed and allows for modernization of your SAS environment by enabling grid processing.
SAS Libraries:
Libraries are the storage mechanisms in SAS. It can store the programs which can be similar in nature. Broadly speaking there are 2 types of libraries viz. temporary and permanent. Temporary libraries are those that exist only during the current SAS session or job. Permanent libraries, as the name suggests are stored in the external storage and are not deleted at the end of a session.
SAS programming workflow:
SAS programming applications are characterized by the flow control specified in the below diagram.
In the first phase of the above diagram a SAS program will read the data which is usually stored as worksheets in an Excel Workbook. A connection to the workbook is made in this phase and the data is imported in a format suitable for usage in the following phases.
Explore Data:
In the second phase we check for inconsistencies or incorrect values. Here frequency reports and summary statistics may also be generated. Looking at these reports and summaries at first glance we might find some inconsistencies right off the bat. For example all the label names of a categorical attribute except for one might be in capitalized letters. Another example of an incorrect value is a negative value for the minimum number of runs scored by a batsman during a string of matches. The first 5 rows are also shown in this phase.
Prepare Data:
In this phase the issues found in the earlier phase are fixed. Here we create new columns with existing values or concatenate them. Conditional processing is also done in this phase. Certain tables are also joined to provide more consistent representations of data. These tables have clean and validated values.
Analyze and Reporting on data and exporting the results:
The last two phases are combined into one in SAS programming applications. Here we create maps based on geographical coordinates, summary statistics etc. which are some of the output models used for displaying results. We can also save the output models created in an Excel Workbook and download it for later offline use.
Also, there are 200+ components present in SAS, Some popular components are:
Base SAS
SAS/GRAPH
SAS/STAT
SAS/INSIGHT
SAS/PH
SAS/ETS etc.
This is the overall framework of a SAS programming application. Hope this article helps you to get a clear view of the workflow of a SAS program.
ankthon
SAS Programming
Technical Scripter 2018
GBlog
Misc
Misc
Misc
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n09 Jun, 2022"
},
{
"code": null,
"e": 351,
"s": 54,
"text": "Statistical Analysis System (SAS) is a software suite that has been developed by SAS Institute, one of the leaders in analytics. It is useful for performing advanced analytics, multivariate analyses, business intelligence, data management functions, and also for conducting predictive analytics. "
},
{
"code": null,
"e": 364,
"s": 351,
"text": "Use of SAS: "
},
{
"code": null,
"e": 886,
"s": 364,
"text": "SAS is used by many top organizations which include Google, Facebook, Twitter and Accenture for answering the many questions which persist at a business and organizational level and is also used for generating informative reports. It helps in business forecasting, quality improvement, operations research and project management. It is particularly useful in applications development and graphics design. This article should help you get an intuition about the working of SAS applications and a hint about it’s raw power."
},
{
"code": null,
"e": 910,
"s": 886,
"text": "Types of SAS software: "
},
{
"code": null,
"e": 1037,
"s": 910,
"text": "There are various types of SAS software that are available.In general there are 4 types of SAS software which are given below."
},
{
"code": null,
"e": 1120,
"s": 1037,
"text": "SAS for WindowsSAS EG (Enterprise Guide)SAS Enterprise Miner (EM)SAS Stat Software"
},
{
"code": null,
"e": 1136,
"s": 1120,
"text": "SAS for Windows"
},
{
"code": null,
"e": 1162,
"s": 1136,
"text": "SAS EG (Enterprise Guide)"
},
{
"code": null,
"e": 1188,
"s": 1162,
"text": "SAS Enterprise Miner (EM)"
},
{
"code": null,
"e": 1206,
"s": 1188,
"text": "SAS Stat Software"
},
{
"code": null,
"e": 1380,
"s": 1206,
"text": "The most used software among the above types is SAS for Windows. It can be easily deployed and allows for modernization of your SAS environment by enabling grid processing. "
},
{
"code": null,
"e": 1396,
"s": 1380,
"text": "SAS Libraries: "
},
{
"code": null,
"e": 1784,
"s": 1396,
"text": "Libraries are the storage mechanisms in SAS. It can store the programs which can be similar in nature. Broadly speaking there are 2 types of libraries viz. temporary and permanent. Temporary libraries are those that exist only during the current SAS session or job. Permanent libraries, as the name suggests are stored in the external storage and are not deleted at the end of a session."
},
{
"code": null,
"e": 1811,
"s": 1784,
"text": "SAS programming workflow: "
},
{
"code": null,
"e": 1912,
"s": 1811,
"text": "SAS programming applications are characterized by the flow control specified in the below diagram. "
},
{
"code": null,
"e": 2178,
"s": 1912,
"text": "In the first phase of the above diagram a SAS program will read the data which is usually stored as worksheets in an Excel Workbook. A connection to the workbook is made in this phase and the data is imported in a format suitable for usage in the following phases. "
},
{
"code": null,
"e": 2193,
"s": 2178,
"text": "Explore Data: "
},
{
"code": null,
"e": 2733,
"s": 2193,
"text": "In the second phase we check for inconsistencies or incorrect values. Here frequency reports and summary statistics may also be generated. Looking at these reports and summaries at first glance we might find some inconsistencies right off the bat. For example all the label names of a categorical attribute except for one might be in capitalized letters. Another example of an incorrect value is a negative value for the minimum number of runs scored by a batsman during a string of matches. The first 5 rows are also shown in this phase. "
},
{
"code": null,
"e": 2748,
"s": 2733,
"text": "Prepare Data: "
},
{
"code": null,
"e": 3061,
"s": 2748,
"text": "In this phase the issues found in the earlier phase are fixed. Here we create new columns with existing values or concatenate them. Conditional processing is also done in this phase. Certain tables are also joined to provide more consistent representations of data. These tables have clean and validated values. "
},
{
"code": null,
"e": 3119,
"s": 3061,
"text": "Analyze and Reporting on data and exporting the results: "
},
{
"code": null,
"e": 3442,
"s": 3119,
"text": "The last two phases are combined into one in SAS programming applications. Here we create maps based on geographical coordinates, summary statistics etc. which are some of the output models used for displaying results. We can also save the output models created in an Excel Workbook and download it for later offline use. "
},
{
"code": null,
"e": 3519,
"s": 3442,
"text": "Also, there are 200+ components present in SAS, Some popular components are:"
},
{
"code": null,
"e": 3528,
"s": 3519,
"text": "Base SAS"
},
{
"code": null,
"e": 3538,
"s": 3528,
"text": "SAS/GRAPH"
},
{
"code": null,
"e": 3547,
"s": 3538,
"text": "SAS/STAT"
},
{
"code": null,
"e": 3559,
"s": 3547,
"text": "SAS/INSIGHT"
},
{
"code": null,
"e": 3566,
"s": 3559,
"text": "SAS/PH"
},
{
"code": null,
"e": 3579,
"s": 3566,
"text": "SAS/ETS etc."
},
{
"code": null,
"e": 3725,
"s": 3579,
"text": "This is the overall framework of a SAS programming application. Hope this article helps you to get a clear view of the workflow of a SAS program."
},
{
"code": null,
"e": 3733,
"s": 3725,
"text": "ankthon"
},
{
"code": null,
"e": 3749,
"s": 3733,
"text": "SAS Programming"
},
{
"code": null,
"e": 3773,
"s": 3749,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 3779,
"s": 3773,
"text": "GBlog"
},
{
"code": null,
"e": 3784,
"s": 3779,
"text": "Misc"
},
{
"code": null,
"e": 3789,
"s": 3784,
"text": "Misc"
},
{
"code": null,
"e": 3794,
"s": 3789,
"text": "Misc"
}
] |
Smallest string divisible by two given strings | 30 Jun, 2021
Given two strings S and T of length N and M respectively, the task is to find the smallest string that is divisible by both the two strings. If no such string exists, then print -1.
For any two strings A and B, B divides A if and only if A is the concatenation of B at least once.
Examples:
Input: S = “abab”, T = “ab”Output: ababExplanation: The string “abab” is the same as S and twice the concatenation of string T (“abab” = “ab” + “ab” = T + T)
Input: S = “ccc”, T = “cc”Output: ccccccExplanation: The string “cccccc” is a concatenation of S and T twice and thrice respectively.(“cccccc” = “ccc” + “ccc” = S + S)(“cccccc” = “cc” + “cc” + “cc” = T + T + T)
Approach: The idea is based on the observation that the length of the required string, say, L, must be equal to the least common multiple of N and M. Check if string S concatenated L / N number of times is equal to string T being concatenated L / M number of times or not. If found to be true, print any one of them. Otherwise, print -1. Follow the steps below to solve the problem:
Store the Least Common Multiple of N and M in a variable, say L.
Initialize two strings S1 and T1.
Concatenate the string, S1 with string, S, (L/N) number of times.
Concatenate the string, T1 with string, T, (L/M) number of times.
If the strings S1 and T1 are equal, then print S1 as the result.
Otherwise, print -1.
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 calculate// GCD of two numbersint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to calculate// LCM of two numbersint lcm(int a, int b){ return (a / gcd(a, b)) * b;} // Function to find the smallest string// which is divisible by strings S and Tvoid findSmallestString(string s, string t){ // Store the length of both strings int n = s.length(), m = t.length(); // Store LCM of n and m int l = lcm(n, m); // Temporary strings to store // concatenated strings string s1 = "", t1 = ""; // Concatenate s1 (l / n) times for (int i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (int i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1 == t1) cout << s1; // Otherwise, print -1 else cout << -1;} // Driver Codeint main(){ string S = "baba", T = "ba"; findSmallestString(S, T); return 0;}
// Java program for above approachimport java.io.*; class GFG{ // Function to calculate // GCD of two numbers static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Function to calculate // LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Function to find the smallest string // which is divisible by strings S and T static void findSmallestString(String s, String t) { // Store the length of both strings int n = s.length(), m = t.length(); // Store LCM of n and m int l = lcm(n, m); // Temporary strings to store // concatenated strings String s1 = "", t1 = ""; // Concatenate s1 (l / n) times for (int i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (int i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1.equals(t1)){ System.out.println(s1); } // Otherwise, print -1 else{ System.out.println(-1); } } // Driver code public static void main(String[] args) { String S = "baba", T = "ba"; findSmallestString(S, T); }} // This code is contributed by susmitakundugoaldanga.
# Python3 program for the above approach # Function to calculate# GCD of two numbersdef gcd(a, b): if (b == 0): return a return gcd(b, a % b) # Function to calculate# LCM of two numbersdef lcm(a, b): return (a // gcd(a, b)) * b # Function to find the smallest string# which is divisible by strings S and Tdef findSmallestString(s, t): # Store the length of both strings n, m = len(s), len(t) # Store LCM of n and m l = lcm(n, m) # Temporary strings to store # concatenated strings s1, t1 = "", "" # Concatenate s1 (l / n) times for i in range(l//n): s1 += s # Concatenate t1 (l / m) times for i in range(l//m): t1 += t # If s1 and t1 are equal if (s1 == t1): print(s1) # Otherwise, pr-1 else: print(-1) # Driver Codeif __name__ == '__main__': S, T = "baba", "ba" findSmallestString(S, T) # This code is contributed by mohit kumar 29.
// C# program for above approachusing System; public class GFG{ // Function to calculate // GCD of two numbers static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Function to calculate // LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Function to find the smallest string // which is divisible by strings S and T static void findSmallestString(string s, string t) { // Store the length of both strings int n = s.Length, m = t.Length; // Store LCM of n and m int l = lcm(n, m); // Temporary strings to store // concatenated strings string s1 = "", t1 = ""; // Concatenate s1 (l / n) times for (int i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (int i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1 == t1) Console.WriteLine(s1); // Otherwise, print -1 else Console.WriteLine(-1); } // Driver code public static void Main(String[] args) { string S = "baba", T = "ba"; findSmallestString(S, T); }} // This code is contributed by sanjoy_62.
<script>// Javascript program for above approach // Function to calculate// GCD of two numbersfunction gcd(a,b){ if (b == 0) return a; return gcd(b, a % b);} // Function to calculate// LCM of two numbersfunction lcm(a,b){ return (a / gcd(a, b)) * b;} // Function to find the smallest string// which is divisible by strings S and Tfunction findSmallestString(s,t){ // Store the length of both strings let n = s.length, m = t.length; // Store LCM of n and m let l = lcm(n, m); // Temporary strings to store // concatenated strings let s1 = "", t1 = ""; // Concatenate s1 (l / n) times for (let i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (let i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1 == (t1)){ document.write(s1+"<br>"); } // Otherwise, print -1 else{ document.write(-1+"<br>"); }} // Driver codelet S = "baba", T = "ba";findSmallestString(S, T); // This code is contributed by unknown2108</script>
baba
Time Complexity: O(max(N, M))Auxiliary Space: O(max(N, M))
mohit kumar 29
sanjoy_62
susmitakundugoaldanga
unknown2108
divisibility
HCF
LCM
Technical Scripter 2020
Mathematical
Strings
Strings
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n30 Jun, 2021"
},
{
"code": null,
"e": 236,
"s": 54,
"text": "Given two strings S and T of length N and M respectively, the task is to find the smallest string that is divisible by both the two strings. If no such string exists, then print -1."
},
{
"code": null,
"e": 335,
"s": 236,
"text": "For any two strings A and B, B divides A if and only if A is the concatenation of B at least once."
},
{
"code": null,
"e": 345,
"s": 335,
"text": "Examples:"
},
{
"code": null,
"e": 503,
"s": 345,
"text": "Input: S = “abab”, T = “ab”Output: ababExplanation: The string “abab” is the same as S and twice the concatenation of string T (“abab” = “ab” + “ab” = T + T)"
},
{
"code": null,
"e": 714,
"s": 503,
"text": "Input: S = “ccc”, T = “cc”Output: ccccccExplanation: The string “cccccc” is a concatenation of S and T twice and thrice respectively.(“cccccc” = “ccc” + “ccc” = S + S)(“cccccc” = “cc” + “cc” + “cc” = T + T + T)"
},
{
"code": null,
"e": 1097,
"s": 714,
"text": "Approach: The idea is based on the observation that the length of the required string, say, L, must be equal to the least common multiple of N and M. Check if string S concatenated L / N number of times is equal to string T being concatenated L / M number of times or not. If found to be true, print any one of them. Otherwise, print -1. Follow the steps below to solve the problem:"
},
{
"code": null,
"e": 1162,
"s": 1097,
"text": "Store the Least Common Multiple of N and M in a variable, say L."
},
{
"code": null,
"e": 1196,
"s": 1162,
"text": "Initialize two strings S1 and T1."
},
{
"code": null,
"e": 1262,
"s": 1196,
"text": "Concatenate the string, S1 with string, S, (L/N) number of times."
},
{
"code": null,
"e": 1328,
"s": 1262,
"text": "Concatenate the string, T1 with string, T, (L/M) number of times."
},
{
"code": null,
"e": 1393,
"s": 1328,
"text": "If the strings S1 and T1 are equal, then print S1 as the result."
},
{
"code": null,
"e": 1414,
"s": 1393,
"text": "Otherwise, print -1."
},
{
"code": null,
"e": 1465,
"s": 1414,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1469,
"s": 1465,
"text": "C++"
},
{
"code": null,
"e": 1474,
"s": 1469,
"text": "Java"
},
{
"code": null,
"e": 1482,
"s": 1474,
"text": "Python3"
},
{
"code": null,
"e": 1485,
"s": 1482,
"text": "C#"
},
{
"code": null,
"e": 1496,
"s": 1485,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate// GCD of two numbersint gcd(int a, int b){ if (b == 0) return a; return gcd(b, a % b);} // Function to calculate// LCM of two numbersint lcm(int a, int b){ return (a / gcd(a, b)) * b;} // Function to find the smallest string// which is divisible by strings S and Tvoid findSmallestString(string s, string t){ // Store the length of both strings int n = s.length(), m = t.length(); // Store LCM of n and m int l = lcm(n, m); // Temporary strings to store // concatenated strings string s1 = \"\", t1 = \"\"; // Concatenate s1 (l / n) times for (int i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (int i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1 == t1) cout << s1; // Otherwise, print -1 else cout << -1;} // Driver Codeint main(){ string S = \"baba\", T = \"ba\"; findSmallestString(S, T); return 0;}",
"e": 2556,
"s": 1496,
"text": null
},
{
"code": "// Java program for above approachimport java.io.*; class GFG{ // Function to calculate // GCD of two numbers static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Function to calculate // LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Function to find the smallest string // which is divisible by strings S and T static void findSmallestString(String s, String t) { // Store the length of both strings int n = s.length(), m = t.length(); // Store LCM of n and m int l = lcm(n, m); // Temporary strings to store // concatenated strings String s1 = \"\", t1 = \"\"; // Concatenate s1 (l / n) times for (int i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (int i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1.equals(t1)){ System.out.println(s1); } // Otherwise, print -1 else{ System.out.println(-1); } } // Driver code public static void main(String[] args) { String S = \"baba\", T = \"ba\"; findSmallestString(S, T); }} // This code is contributed by susmitakundugoaldanga.",
"e": 3757,
"s": 2556,
"text": null
},
{
"code": "# Python3 program for the above approach # Function to calculate# GCD of two numbersdef gcd(a, b): if (b == 0): return a return gcd(b, a % b) # Function to calculate# LCM of two numbersdef lcm(a, b): return (a // gcd(a, b)) * b # Function to find the smallest string# which is divisible by strings S and Tdef findSmallestString(s, t): # Store the length of both strings n, m = len(s), len(t) # Store LCM of n and m l = lcm(n, m) # Temporary strings to store # concatenated strings s1, t1 = \"\", \"\" # Concatenate s1 (l / n) times for i in range(l//n): s1 += s # Concatenate t1 (l / m) times for i in range(l//m): t1 += t # If s1 and t1 are equal if (s1 == t1): print(s1) # Otherwise, pr-1 else: print(-1) # Driver Codeif __name__ == '__main__': S, T = \"baba\", \"ba\" findSmallestString(S, T) # This code is contributed by mohit kumar 29.",
"e": 4692,
"s": 3757,
"text": null
},
{
"code": "// C# program for above approachusing System; public class GFG{ // Function to calculate // GCD of two numbers static int gcd(int a, int b) { if (b == 0) return a; return gcd(b, a % b); } // Function to calculate // LCM of two numbers static int lcm(int a, int b) { return (a / gcd(a, b)) * b; } // Function to find the smallest string // which is divisible by strings S and T static void findSmallestString(string s, string t) { // Store the length of both strings int n = s.Length, m = t.Length; // Store LCM of n and m int l = lcm(n, m); // Temporary strings to store // concatenated strings string s1 = \"\", t1 = \"\"; // Concatenate s1 (l / n) times for (int i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (int i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1 == t1) Console.WriteLine(s1); // Otherwise, print -1 else Console.WriteLine(-1); } // Driver code public static void Main(String[] args) { string S = \"baba\", T = \"ba\"; findSmallestString(S, T); }} // This code is contributed by sanjoy_62.",
"e": 5858,
"s": 4692,
"text": null
},
{
"code": "<script>// Javascript program for above approach // Function to calculate// GCD of two numbersfunction gcd(a,b){ if (b == 0) return a; return gcd(b, a % b);} // Function to calculate// LCM of two numbersfunction lcm(a,b){ return (a / gcd(a, b)) * b;} // Function to find the smallest string// which is divisible by strings S and Tfunction findSmallestString(s,t){ // Store the length of both strings let n = s.length, m = t.length; // Store LCM of n and m let l = lcm(n, m); // Temporary strings to store // concatenated strings let s1 = \"\", t1 = \"\"; // Concatenate s1 (l / n) times for (let i = 0; i < l / n; i++) { s1 += s; } // Concatenate t1 (l / m) times for (let i = 0; i < l / m; i++) { t1 += t; } // If s1 and t1 are equal if (s1 == (t1)){ document.write(s1+\"<br>\"); } // Otherwise, print -1 else{ document.write(-1+\"<br>\"); }} // Driver codelet S = \"baba\", T = \"ba\";findSmallestString(S, T); // This code is contributed by unknown2108</script>",
"e": 6917,
"s": 5858,
"text": null
},
{
"code": null,
"e": 6922,
"s": 6917,
"text": "baba"
},
{
"code": null,
"e": 6983,
"s": 6924,
"text": "Time Complexity: O(max(N, M))Auxiliary Space: O(max(N, M))"
},
{
"code": null,
"e": 7000,
"s": 6985,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 7010,
"s": 7000,
"text": "sanjoy_62"
},
{
"code": null,
"e": 7032,
"s": 7010,
"text": "susmitakundugoaldanga"
},
{
"code": null,
"e": 7044,
"s": 7032,
"text": "unknown2108"
},
{
"code": null,
"e": 7057,
"s": 7044,
"text": "divisibility"
},
{
"code": null,
"e": 7061,
"s": 7057,
"text": "HCF"
},
{
"code": null,
"e": 7065,
"s": 7061,
"text": "LCM"
},
{
"code": null,
"e": 7089,
"s": 7065,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 7102,
"s": 7089,
"text": "Mathematical"
},
{
"code": null,
"e": 7110,
"s": 7102,
"text": "Strings"
},
{
"code": null,
"e": 7118,
"s": 7110,
"text": "Strings"
},
{
"code": null,
"e": 7131,
"s": 7118,
"text": "Mathematical"
}
] |
Python | Sympy Plane.equation() method | 22 Apr, 2020
Syntax : Plane.equation(x, y, z)
Parameters :
x : optional
y : optional
z : optional
Returns : Equation of Plane
Example #1:
# import sympy, Point3D and Planefrom sympy import Point3D, Plane # using Plane() p1 = Plane(Point3D(1, 2, 3), Point3D(4, 5, 6), Point3D(0, 2, 0))p2 = p1.equation() print(p2)
Output:
-9*x + 6*y + 3*z - 12
Example #2:
# import sympy, Point3D and Planefrom sympy import Point3D, Plane # using Plane() p3 = Plane(Point3D(1, 2, 3), normal_vector =(2, 2, 2))p4 = p3.equation() print(p4)
Output:
2*x + 2*y + 2*z - 12
Python SymPy-Geometry
SymPy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
How to drop one or multiple columns in Pandas Dataframe
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | datetime.timedelta() function
Python | Get unique values from a list | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 148,
"s": 28,
"text": "Syntax : Plane.equation(x, y, z)\n\nParameters :\nx : optional\ny : optional\nz : optional\n\nReturns : Equation of Plane\n"
},
{
"code": null,
"e": 160,
"s": 148,
"text": "Example #1:"
},
{
"code": "# import sympy, Point3D and Planefrom sympy import Point3D, Plane # using Plane() p1 = Plane(Point3D(1, 2, 3), Point3D(4, 5, 6), Point3D(0, 2, 0))p2 = p1.equation() print(p2)",
"e": 338,
"s": 160,
"text": null
},
{
"code": null,
"e": 346,
"s": 338,
"text": "Output:"
},
{
"code": null,
"e": 368,
"s": 346,
"text": "-9*x + 6*y + 3*z - 12"
},
{
"code": null,
"e": 380,
"s": 368,
"text": "Example #2:"
},
{
"code": "# import sympy, Point3D and Planefrom sympy import Point3D, Plane # using Plane() p3 = Plane(Point3D(1, 2, 3), normal_vector =(2, 2, 2))p4 = p3.equation() print(p4)",
"e": 548,
"s": 380,
"text": null
},
{
"code": null,
"e": 556,
"s": 548,
"text": "Output:"
},
{
"code": null,
"e": 577,
"s": 556,
"text": "2*x + 2*y + 2*z - 12"
},
{
"code": null,
"e": 599,
"s": 577,
"text": "Python SymPy-Geometry"
},
{
"code": null,
"e": 605,
"s": 599,
"text": "SymPy"
},
{
"code": null,
"e": 612,
"s": 605,
"text": "Python"
},
{
"code": null,
"e": 710,
"s": 612,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 742,
"s": 710,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 769,
"s": 742,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 790,
"s": 769,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 813,
"s": 790,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 869,
"s": 813,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 900,
"s": 869,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 942,
"s": 900,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 984,
"s": 942,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 1023,
"s": 984,
"text": "Python | datetime.timedelta() function"
}
] |
Finding Difference between Images using PIL | 14 Feb, 2022
Python interpreter in itself doesn’t contain the ability to process images and making out a conclusion to it. So, PIL(Python Imaging Library) adds image processing powers to the interpreter. PIL is an open-source library that provides python with external file support and efficiency to process images and their representations. Basically, PIL is designed to access data in the form of images (pixels) to make the analysis faster.
PIL supports image formats like-
jpeg
tiff
png
jpg
gif
There are a lot of functions that can be performed using PIL, they are-
1) Uploading images
Using PIL, we can load an image and display it.
Code: After installing the PIL library, run the following code to display any image say abc–
Python3
from PIL import Image img1 = Image.open('abc.jpg')img1.show()
Output:
The image will display like this after running the code
2) Saving images
Code: For saving image
Python3
from PIL import Image img1 = Image.open('flower.png')img1.save('flower.png')
Note: Other functions using PIL – Image processing, difference using ImageChops, downloading, Reading pixels, etc.
To find the difference, upload 2 images in the interpreter and then using ImageChops find the difference between both of them, output will be self-explanatory.
Images used for difference:
r.jpg
p.jpg
Python3
from PIL import Image, ImageChops img1 = Image.open('p.jpg')img2 = Image.open('r.jpg') diff = ImageChops.difference(img1, img2) if diff.getbbox(): diff.show()
Output:
The extra portions / difference between both image is green in colour.
sumitgumber28
Python-pil
Technical Scripter 2020
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n14 Feb, 2022"
},
{
"code": null,
"e": 459,
"s": 28,
"text": "Python interpreter in itself doesn’t contain the ability to process images and making out a conclusion to it. So, PIL(Python Imaging Library) adds image processing powers to the interpreter. PIL is an open-source library that provides python with external file support and efficiency to process images and their representations. Basically, PIL is designed to access data in the form of images (pixels) to make the analysis faster."
},
{
"code": null,
"e": 492,
"s": 459,
"text": "PIL supports image formats like-"
},
{
"code": null,
"e": 497,
"s": 492,
"text": "jpeg"
},
{
"code": null,
"e": 502,
"s": 497,
"text": "tiff"
},
{
"code": null,
"e": 506,
"s": 502,
"text": "png"
},
{
"code": null,
"e": 510,
"s": 506,
"text": "jpg"
},
{
"code": null,
"e": 514,
"s": 510,
"text": "gif"
},
{
"code": null,
"e": 586,
"s": 514,
"text": "There are a lot of functions that can be performed using PIL, they are-"
},
{
"code": null,
"e": 606,
"s": 586,
"text": "1) Uploading images"
},
{
"code": null,
"e": 655,
"s": 606,
"text": "Using PIL, we can load an image and display it. "
},
{
"code": null,
"e": 748,
"s": 655,
"text": "Code: After installing the PIL library, run the following code to display any image say abc–"
},
{
"code": null,
"e": 756,
"s": 748,
"text": "Python3"
},
{
"code": "from PIL import Image img1 = Image.open('abc.jpg')img1.show()",
"e": 819,
"s": 756,
"text": null
},
{
"code": null,
"e": 827,
"s": 819,
"text": "Output:"
},
{
"code": null,
"e": 883,
"s": 827,
"text": "The image will display like this after running the code"
},
{
"code": null,
"e": 900,
"s": 883,
"text": "2) Saving images"
},
{
"code": null,
"e": 924,
"s": 900,
"text": "Code: For saving image "
},
{
"code": null,
"e": 932,
"s": 924,
"text": "Python3"
},
{
"code": "from PIL import Image img1 = Image.open('flower.png')img1.save('flower.png')",
"e": 1010,
"s": 932,
"text": null
},
{
"code": null,
"e": 1125,
"s": 1010,
"text": "Note: Other functions using PIL – Image processing, difference using ImageChops, downloading, Reading pixels, etc."
},
{
"code": null,
"e": 1285,
"s": 1125,
"text": "To find the difference, upload 2 images in the interpreter and then using ImageChops find the difference between both of them, output will be self-explanatory."
},
{
"code": null,
"e": 1313,
"s": 1285,
"text": "Images used for difference:"
},
{
"code": null,
"e": 1319,
"s": 1313,
"text": "r.jpg"
},
{
"code": null,
"e": 1325,
"s": 1319,
"text": "p.jpg"
},
{
"code": null,
"e": 1333,
"s": 1325,
"text": "Python3"
},
{
"code": "from PIL import Image, ImageChops img1 = Image.open('p.jpg')img2 = Image.open('r.jpg') diff = ImageChops.difference(img1, img2) if diff.getbbox(): diff.show()",
"e": 1496,
"s": 1333,
"text": null
},
{
"code": null,
"e": 1505,
"s": 1496,
"text": "Output: "
},
{
"code": null,
"e": 1576,
"s": 1505,
"text": "The extra portions / difference between both image is green in colour."
},
{
"code": null,
"e": 1590,
"s": 1576,
"text": "sumitgumber28"
},
{
"code": null,
"e": 1601,
"s": 1590,
"text": "Python-pil"
},
{
"code": null,
"e": 1625,
"s": 1601,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 1632,
"s": 1625,
"text": "Python"
},
{
"code": null,
"e": 1651,
"s": 1632,
"text": "Technical Scripter"
}
] |
Find Union and Intersection of two unsorted arrays | 07 Jul, 2022
Given two unsorted arrays that represent two sets (elements in every array are distinct), find the union and intersection of two arrays.
For example, if the input arrays are:
arr1[] = {7, 1, 5, 2, 3, 6}
arr2[] = {3, 8, 6, 20, 7}
Then your program should print Union as {1, 2, 3, 5, 6, 7, 8, 20} and Intersection as {3, 6, 7}. Note that the elements of union and intersection can be printed in any order.
Method 1 (Using Set):
Union of two arrays we can get with the Set data structure very easily. Set is a data structure that allows only the distinct elements in it. So, when we put the elements of both the array into the set we will get only the distinct elements that are equal to the union operation over the arrays. Let’s code it now –>
C++
Java
Python3
C#
Javascript
// C++ program for the union of two arrays using Set#include <bits/stdc++.h>using namespace std;void getUnion(int a[], int n, int b[], int m){ // Defining set container s set<int> s; // Inserting array elements in s for (int i = 0; i < n; i++) s.insert(a[i]); for (int i = 0; i < m; i++) s.insert(b[i]); cout << "Number of elements after union operation: " << s.size() << endl; cout << "The union set of both arrays is :" << endl; for (auto itr = s.begin(); itr != s.end(); itr++) cout << *itr << " "; // s will contain only distinct // elements from array a and b} // Driver Codeint main(){ int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10);} // contributed by Anirban Chand
// Java program for the union of two arrays using Setimport java.util.*; class GFG{static void getUnion(int a[], int n, int b[], int m){ // Defining set container s HashSet<Integer> s = new HashSet<>(); // Inserting array elements in s for (int i = 0; i < n; i++) s.add(a[i]); for (int i = 0; i < m; i++) s.add(b[i]); System.out.print("Number of elements after union operation: " + s.size() +"\n"); System.out.print("The union set of both arrays is :" +"\n"); System.out.print(s.toString()+ " "); // s will contain only distinct // elements from array a and b} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10);}} // This code is contributed by gauravrajput1
# Python program for the union of two arrays using Setdef getUnion(a, n, b, m): # Defining set container s s =set(); # Inserting array elements in s for i in range(n): s.add(a[i]); for i in range(m): s.add(b[i]); print("Number of elements after union operation: " , len(s) , ""); print("The union set of both arrays is :" + ""); print(s, end=""); # s will contain only distinct # elements from array a and b # Driver Codeif __name__ == '__main__': a = [ 1, 2, 5, 6, 2, 3, 5, 7, 3 ]; b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 ]; getUnion(a, 9, b, 10); # This code is contributed by gauravrajput1
// C# program for the union of two arrays using Setusing System;using System.Collections.Generic; public class GFG { static void getUnion(int []a, int n, int []b, int m) { // Defining set container s HashSet<int> s = new HashSet<int>(); // Inserting array elements in s for (int i = 0; i < n; i++) s.Add(a[i]); for (int i = 0; i < m; i++) s.Add(b[i]); Console.Write("Number of elements after union operation: " + s.Count + "\n"); Console.Write("The union set of both arrays is :" + "\n"); foreach(int i in s) Console.Write(i + " "); // s will contain only distinct // elements from array a and b } // Driver Code public static void Main(String[] args) { int []a = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10); }} // This code is contributed by umadevi9616
<script> // JavaScript program for the above // approach using Set function getUnion(a, n, b, m) { // Defining set container s var s = new Set(); // Inserting array elements in s for (let i = 0; i < n; i++) s.add(a[i]); for (let i = 0; i < m; i++) s.add(b[i]); document.write( "Number of elements after union operation: " + s.size + "<br>"); document.write("The union set of both arrays is :"); document.write("<br>"); var arr = []; for (let itr of s) arr.push(itr); // s will contain only distinct // elements from array a and b arr.sort(function (a, b) { return a - b; }) for (let i = 0; i < arr.length; i++) { document.write(arr[i] + " "); } } // Driver Code let a = [1, 2, 5, 6, 2, 3, 5, 7, 3]; let b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4]; getUnion(a, 9, b, 10); // This code is contributed by Potta Lokesh </script>
Number of elements after union operation: 9
The union set of both arrays is :
1 2 3 4 5 6 7 8 9
Time Complexity: O(m * log(m) + n * log(n))
Note: O(m + n) in case of Python because in python the set built-in method is quite different than that of C++ once, Python uses an hash map internally.
We can improve performance of getUnion method by iterating over both the arrays for index from 0 to min(n, m)-1 adding all the elements in both the arrays to the set, and then iterate over the other array with the remaining elements and add them to the set.
C++
Java
Python3
C#
Javascript
// C++ program for the union of two arrays using Set#include <bits/stdc++.h>using namespace std;void getUnion(int a[], int n, int b[], int m){ int min=(n<m)? n : m; // Defining set container s set<int> s; // add elements from both the arrays for // index from 0 to min(n, m)-1 for (int i = 0; i < min; i++) { s.insert(a[i]); s.insert(b[i]); } if (n > m) { for (int i = m; i < n; i++) { s.insert(a[i]); } } else if (n < m) { for (int i = n; i < m; i++) { s.insert(b[i]); } } cout << "Number of elements after union operation: " << s.size() << endl; cout << "The union set of both arrays is :" << endl; for (auto itr = s.begin(); itr != s.end(); itr++) cout << *itr << " "; // s will contain only distinct // elements from array a and b} // Driver Codeint main(){ int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10);} // This code is contributed by Aarti_Rathi
// Java program for the union of two arrays using Setimport java.util.*; class GFG { static void getUnion(int a[], int n, int b[], int m) { // find min of n and m int min = (n < m) ? n : m; // set container Set<Integer> set = new HashSet<>(); // add elements from both the arrays for // index from 0 to min(n, m)-1 for (int i = 0; i < min; i++) { set.add(a[i]); set.add(b[i]); } // add remiaining elements to the set from the other // array (having greater length) // note that only one of the loops will execute if (n > m) { for (int i = m; i < n; i++) { set.add(a[i]); } } else if (n < m) { for (int i = n; i < m; i++) { set.add(b[i]); } } // driver code to print the output System.out.println("Number of elements after union operation: " + set.size()); System.out.println("The union set of both arrays is :"); System.out.print(set.toString()); } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10); }} // This code is contributed by Parth Malhotra
# Python program for the union of two arrays using Setdef getUnion(a, n, b, m): # Defining set container s hs = set() if(n<m): min=n else: min=m # add elements from both the arrays for # index from 0 to min(n, m)-1 for i in range(0, min): hs.add(a[i]) hs.add(b[i]) if(n>m): for i in range(m, n): hs.add(a[i]) else: if(n<m): for i in range(m, n): hs.add(b[i]) print("Number of elements after union operation: ",len(hs)) print("The union set of both arrays is :") for i in hs: print(i, end=" ") print("\n") # s will contain only distinct # elements from array a and b # Driver Programa = [1, 2, 5, 6, 2, 3, 5, 7, 3]b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4]n1 = len(a)n2 = len(b) # Function callgetUnion(a, n1, b, n2) # This code is contributed by Aarti_Rathi
// C# program for the union of two arrays using Setusing System;using System.Collections.Generic; public class GFG { static void getUnion(int []a, int n, int []b, int m) { // find min of n and m int min = (n < m) ? n : m; // set container HashSet<int> set = new HashSet<int>(); // add elements from both the arrays for // index from 0 to min(n, m)-1 for (int i = 0; i < min; i++) { set.Add(a[i]); set.Add(b[i]); } // add remiaining elements to the set from the other // array (having greater length) // note that only one of the loops will execute if (n > m) { for (int i = m; i < n; i++) { set.Add(a[i]); } } else if (n < m) { for (int i = n; i < m; i++) { set.Add(b[i]); } } // driver code to print the output Console.WriteLine("Number of elements after union operation: " + set.Count); Console.WriteLine("The union set of both arrays is :["); foreach(int x in set) Console.Write(x+", "); Console.Write("]"); } // Driver Code public static void Main(String[] args) { int []a = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10); }} // This code is contributed by Rajput-Ji
<script>// javascript program for the union of two arrays using Set function getUnion(a , n , b , m) { // find min of n and m var min = (n < m) ? n : m; // set container var set = new Set(); // add elements from both the arrays for // index from 0 to min(n, m)-1 for (i = 0; i < min; i++) { set.add(a[i]); set.add(b[i]); } // add remiaining elements to the set from the other // array (having greater length) // note that only one of the loops will execute if (n > m) { for (i = m; i < n; i++) { set.add(a[i]); } } else if (n < m) { for (i = n; i < m; i++) { set.add(b[i]); } } // driver code to print the output document.write("Number of elements after union operation: " + set.size); document.write("<br/>The union set of both arrays is :<br/>"); set.forEach (function(value) {document.write(value+" ");}) } // Driver Code var a = [ 1, 2, 5, 6, 2, 3, 5, 7, 3 ]; var b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 ]; getUnion(a, 9, b, 10);// This code contributed by Rajput-Ji</script>
Number of elements after union operation: 9
The union set of both arrays is :
[1, 2, 3, 4, 5, 6, 7, 8, 9]
Time Complexity: O( max(m,n) )
Method 2: (Using map data structure)
From the knowledge of data structures, we know that map stores distinct keys only. So if we insert any key appearing more than one time it gets stored only once. The idea is to insert both the arrays in one common map which would then store the distinct elements of both arrays (union of both the array).
Below is the implementation of the above method:
C++
Java
Python3
C#
Javascript
// C++ program for the above approach#include <bits/stdc++.h>using namespace std;void printUnion(int* a, int n, int* b, int m){ // Defining map container mp map<int, int> mp; // Inserting array elements in mp for (int i = 0; i < n; i++) mp.insert({ a[i], i }); for (int i = 0; i < m; i++) mp.insert({ b[i], i }); cout << "The union set of both arrays is :" << endl; for (auto itr = mp.begin(); itr != mp.end(); itr++) cout << itr->first << " "; // mp will contain only distinct // elements from array a and b} // Driver Codeint main(){ int a[7] = { 1, 2, 5, 6, 2, 3, 5 }; int b[9] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; printUnion(a, 7, b, 9);}
// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ static void printUnion(int[] a, int n, int[] b, int m){ Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Inserting array elements in mp for(int i = 0; i < n; i++) { mp.put(a[i], i); } for(int i = 0; i < m; i++) { mp.put(b[i], i); } System.out.println("The union set of both arrays is :"); for(Map.Entry mapElement : mp.entrySet()) { System.out.print(mapElement.getKey() + " "); // mp will contain only distinct // elements from array a and b }} // Driver Codepublic static void main (String[] args){ int a[] = { 1, 2, 5, 6, 2, 3, 5 }; int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; printUnion(a, 7, b, 9);}} // This code is contributed by avanitrachhadiya2155
# Python program for the above approachdef printUnion(a , n, b , m): mp = {} # Inserting array elements in mp for i in range(n): mp[a[i]] = i for i in range(m): mp[b[i]] = i print("The union set of both arrays is : "); for key in mp.keys(): print(key,end=" ") # Driver Codea = [ 1, 2, 5, 6, 2, 3, 5 ];b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5 ]; printUnion(a, 7, b, 9) # This code is contributed by shinjanpatra
// C# program for the above approach using System;using System.Collections.Generic; public class GFG{ static void printUnion(int[] a, int n, int[] b, int m){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Inserting array elements in mp for(int i = 0; i < n; i++) { if(!mp.ContainsKey(a[i])) mp.Add(a[i], i); } for(int i = 0; i < m; i++) { if(!mp.ContainsKey(b[i])) mp.Add(b[i], i); } Console.WriteLine("The union set of both arrays is :"); foreach(KeyValuePair<int,int> mapElement in mp) { Console.Write(mapElement.Key + " "); // mp will contain only distinct // elements from array a and b }} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 2, 5, 6, 2, 3, 5 }; int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; printUnion(a, 7, b, 9);}} // This code contributed by gauravrajput1
<script>// javascript program for the above approachfunction printUnion(a , n, b , m){ var mp = new Map(); // Inserting array elements in mp for(var i = 0; i < n; i++) { mp.set(a[i], i); } for(var i = 0; i < m; i++) { mp.set(b[i], i); } document.write("The union set of both arrays is :<br/>"); for(var key of mp.keys()) { document.write(key + " "); }} // Driver Code var a = [ 1, 2, 5, 6, 2, 3, 5 ]; var b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5 ]; printUnion(a, 7, b, 9); // This code is contributed by gauravrajput1</script>
The union set of both arrays is :
1 2 3 4 5 6 8 9
The above method has time complexity O(m+n).
*This method is suggested by Vinay Verma
Method 3 (Naive)
Union:
Initialize union U as empty.Copy all elements of the first array to U.Do the following for every element x of the second array:If x is not present in the first array, then copy x to U.Return U.
Initialize union U as empty.
Copy all elements of the first array to U.
Do the following for every element x of the second array:If x is not present in the first array, then copy x to U.
If x is not present in the first array, then copy x to U.
If x is not present in the first array, then copy x to U.
Return U.
Intersection:
Initialize intersection I as empty.Do the following for every element x of the first arrayIf x is present in the second array, then copy x to I.Return I.
Initialize intersection I as empty.
Do the following for every element x of the first arrayIf x is present in the second array, then copy x to I.
If x is present in the second array, then copy x to I.
If x is present in the second array, then copy x to I.
Return I.
The time complexity of this method is O(mn) for both operations. Here m and n are numbers of elements in arr1[] and arr2[] respectively.
However, above method works only for distinct elements in input arrays.
Method 4 (Use Sorting)
Sort arr1[] and arr2[]. This step takes O(mLogm + nLogn) time.Use O(m + n) algorithms to find the union and intersection of two sorted arrays.
Sort arr1[] and arr2[]. This step takes O(mLogm + nLogn) time.
Use O(m + n) algorithms to find the union and intersection of two sorted arrays.
The overall time complexity of this method is O(mLogm + nLogn).
Method 5 (Use Sorting and Searching) Union:
Initialize union U as empty.Find smaller m and n and sort the smaller array.Copy the smaller array to U.For every element x of a larger array, do the followingBinary Search x in the smaller array. If, x is not present, then copy it to U.Return U.
Initialize union U as empty.
Find smaller m and n and sort the smaller array.
Copy the smaller array to U.
For every element x of a larger array, do the followingBinary Search x in the smaller array. If, x is not present, then copy it to U.
Binary Search x in the smaller array. If, x is not present, then copy it to U.
Binary Search x in the smaller array. If, x is not present, then copy it to U.
Return U.
Intersection:
Initialize intersection I as empty.Find smaller of m and n and sort the smaller array.For every element x of a larger array, do the followingBinary Search x in the smaller array. If x is present, then copy it to I.Return I.
Initialize intersection I as empty.
Find smaller of m and n and sort the smaller array.
For every element x of a larger array, do the followingBinary Search x in the smaller array. If x is present, then copy it to I.
Binary Search x in the smaller array. If x is present, then copy it to I.
Binary Search x in the smaller array. If x is present, then copy it to I.
Return I.
Time complexity of this method is min(mLogm + nLogm, mLogn + nLogn) which can also be written as O((m+n)Logm, (m+n)Logn). This approach works much better than the previous approach when the difference between the sizes of two arrays is significant.Thanks to use_the_force for suggesting this method in a comment here.
Below is the implementation of this method. However, this method also works only for distinct elements in input arrays.
C++
Java
Python3
C#
PHP
Javascript
// A C++ program to print union and intersection/// of two unsorted arrays#include <algorithm>#include <iostream>using namespace std; int binarySearch(int arr[], int l, int r, int x); // Prints union of arr1[0..m-1] and arr2[0..n-1]void printUnion(int arr1[], int arr2[], int m, int n){ // Before finding union, make sure arr1[0..m-1] // is smaller if (m > n) { int* tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print its elements (these // two steps can be swapped as order in output is not // important) sort(arr1, arr1 + m); for (int i = 0; i < m; i++) cout << arr1[i] << " "; // Search every element of bigger array in smaller array // and print the element if not found for (int i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) cout << arr2[i] << " ";} // Prints intersection of arr1[0..m-1] and arr2[0..n-1]void printIntersection(int arr1[], int arr2[], int m, int n){ // Before finding intersection, make sure arr1[0..m-1] // is smaller if (m > n) { int* tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] sort(arr1, arr1 + m); // Search every element of bigger array in smaller // array and print the element if found for (int i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) cout << arr2[i] << " ";} // A recursive binary search function. It returns// location of x in given array arr[l..r] is present,// otherwise -1int binarySearch(int arr[], int l, int r, int x){ if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only // be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right // subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in array return -1;} /* Driver program to test above function */int main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); // Function call cout << "Union of two arrays is n"; printUnion(arr1, arr2, m, n); cout << "nIntersection of two arrays is n"; printIntersection(arr1, arr2, m, n); return 0;}
// A Java program to print union and intersection/// of two unsorted arraysimport java.util.Arrays; class UnionAndIntersection { // Prints union of arr1[0..m-1] and arr2[0..n-1] void printUnion(int arr1[], int arr2[], int m, int n) { // Before finding union, make sure arr1[0..m-1] // is smaller if (m > n) { int tempp[] = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print its elements // (these two steps can be swapped as order in // output is not important) Arrays.sort(arr1); for (int i = 0; i < m; i++) System.out.print(arr1[i] + " "); // Search every element of bigger array in smaller // array and print the element if not found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) System.out.print(arr2[i] + " "); } } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] void printIntersection(int arr1[], int arr2[], int m, int n) { // Before finding intersection, make sure // arr1[0..m-1] is smaller if (m > n) { int tempp[] = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] Arrays.sort(arr1); // Search every element of bigger array in smaller // array and print the element if found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) System.out.print(arr2[i] + " "); } } // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can // only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right // subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in // array return -1; } // Driver code public static void main(String[] args) { UnionAndIntersection u_i = new UnionAndIntersection(); int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int m = arr1.length; int n = arr2.length; // Function call System.out.println("Union of two arrays is "); u_i.printUnion(arr1, arr2, m, n); System.out.println(""); System.out.println( "Intersection of two arrays is "); u_i.printIntersection(arr1, arr2, m, n); }}
# A Python3 program to print union and intersection# of two unsorted arrays # Prints union of arr1[0..m-1] and arr2[0..n-1] def printUnion(arr1, arr2, m, n): # Before finding union, make sure arr1[0..m-1] # is smaller if (m > n): tempp = arr1 arr1 = arr2 arr2 = tempp temp = m m = n n = temp # Now arr1[] is smaller # Sort the first array and print its elements (these two # steps can be swapped as order in output is not important) arr1.sort() for i in range(0, m): print(arr1[i], end=" ") # Search every element of bigger array in smaller array # and print the element if not found for i in range(0, n): if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): print(arr2[i], end=" ") # Prints intersection of arr1[0..m-1] and arr2[0..n-1] def printIntersection(arr1, arr2, m, n): # Before finding intersection, make sure arr1[0..m-1] # is smaller if (m > n): tempp = arr1 arr1 = arr2 arr2 = tempp temp = m m = n n = temp # Now arr1[] is smaller # Sort smaller array arr1[0..m-1] arr1.sort() # Search every element of bigger array in smaller # array and print the element if found for i in range(0, n): if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1): print(arr2[i], end=" ") # A recursive binary search function. It returns# location of x in given array arr[l..r] is present,# otherwise -1 def binarySearch(arr, l, r, x): if (r >= l): mid = int(l + (r - l)/2) # If the element is present at the middle itself if (arr[mid] == x): return mid # If element is smaller than mid, then it can only # be present in left subarray if (arr[mid] > x): return binarySearch(arr, l, mid - 1, x) # Else the element can only be present in right subarray return binarySearch(arr, mid + 1, r, x) # We reach here when element is not present in array return -1 # Driver codearr1 = [7, 1, 5, 2, 3, 6]arr2 = [3, 8, 6, 20, 7]m = len(arr1)n = len(arr2) # Function callprint("Union of two arrays is ")printUnion(arr1, arr2, m, n)print("\nIntersection of two arrays is ")printIntersection(arr1, arr2, m, n) # This code is contributed by mits
// A C# program to print union and// intersection of two unsorted arraysusing System; class GFG { // Prints union of arr1[0..m-1] and arr2[0..n-1] static void printUnion(int[] arr1, int[] arr2, int m, int n) { // Before finding union, make // sure arr1[0..m-1] is smaller if (m > n) { int[] tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print // its elements (these two steps can // be swapped as order in output is // not important) Array.Sort(arr1); for (int i = 0; i < m; i++) Console.Write(arr1[i] + " "); // Search every element of bigger // array in smaller array and print // the element if not found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) Console.Write(arr2[i] + " "); } } // Prints intersection of arr1[0..m-1] // and arr2[0..n-1] static void printIntersection(int[] arr1, int[] arr2, int m, int n) { // Before finding intersection, // make sure arr1[0..m-1] is smaller if (m > n) { int[] tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] Array.Sort(arr1); // Search every element of bigger array in // smaller array and print the element if found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) Console.Write(arr2[i] + " "); } } // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, otherwise -1 static int binarySearch(int[] arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at // the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it // can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be // present in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is // not present in array return -1; } // Driver Code static public void Main() { int[] arr1 = { 7, 1, 5, 2, 3, 6 }; int[] arr2 = { 3, 8, 6, 20, 7 }; int m = arr1.Length; int n = arr2.Length; // Function call Console.WriteLine("Union of two arrays is "); printUnion(arr1, arr2, m, n); Console.WriteLine(""); Console.WriteLine("Intersection of two arrays is "); printIntersection(arr1, arr2, m, n); }} // This code is contributed// by Sach_Code
<?php// A PHP program to print union and intersection/// of two unsorted arrays // Prints union of arr1[0..m-1] and arr2[0..n-1]function printUnion($arr1, $arr2, $m, $n){ // Before finding union, make sure arr1[0..m-1] // is smaller if ($m > $n) { $tempp = $arr1; $arr1 = $arr2; $arr2 = $tempp; $temp = $m; $m = $n; $n = $temp; } // Now arr1[] is smaller // Sort the first array and print its elements (these two // steps can be swapped as order in output is not important) sort($arr1); for ($i = 0; $i < $m; $i++) echo $arr1[$i]." "; // Search every element of bigger array in smaller array // and print the element if not found for ($i = 0; $i < $n; $i++) if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) == -1) echo $arr2[$i]." ";} // Prints intersection of arr1[0..m-1] and arr2[0..n-1]function printIntersection($arr1, $arr2, $m, $n){ // Before finding intersection, make sure arr1[0..m-1] // is smaller if ($m > $n) { $tempp = $arr1; $arr1 = $arr2; $arr2 = $tempp; $temp = $m; $m = $n; $n = $temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] sort($arr1); // Search every element of bigger array in smaller // array and print the element if found for ($i = 0; $i < $n; $i++) if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) != -1) echo $arr2[$i]." ";} // A recursive binary search function. It returns// location of x in given array arr[l..r] is present,// otherwise -1function binarySearch($arr, $l, $r,$x){ if ($r >= $l) { $mid = (int)($l + ($r - $l)/2); // If the element is present at the middle itself if ($arr[$mid] == $x) return $mid; // If element is smaller than mid, then it can only // be present in left subarray if ($arr[$mid] > $x) return binarySearch($arr, $l, $mid - 1, $x); // Else the element can only be present in right subarray return binarySearch($arr, $mid + 1, $r, $x); } // We reach here when element is not present in array return -1;} /* Driver program to test above function */ $arr1 = array(7, 1, 5, 2, 3, 6); $arr2 = array(3, 8, 6, 20, 7); $m = count($arr1); $n = count($arr2); echo "Union of two arrays is \n"; printUnion($arr1, $arr2, $m, $n); echo "\nIntersection of two arrays is \n"; printIntersection($arr1, $arr2, $m, $n); // This code is contributed by mits?>
<script> // A JavaScript program to// print union and intersection// of two unsorted arrays // A recursive binary search function. It returns// location of x in given array arr[l..r] is present,// otherwise -1function binarySearch(arr, l, r, x){ if (r >= l) { let mid = l + Math.floor((r - l) / 2); // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only // be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right // subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in array return -1;} // Prints union of arr1[0..m-1] and arr2[0..n-1]function printUnion(arr1, arr2, m, n){ // Before finding union, make sure arr1[0..m-1] // is smaller if (m > n) { let tempp = arr1; arr1 = arr2; arr2 = tempp; let temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print its elements (these // two steps can be swapped as order in output is not // important) arr1.sort((a, b) => a - b); for (let i = 0; i < m; i++) document.write(arr1[i] + " "); // Search every element of bigger array in smaller array // and print the element if not found for (let i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) document.write(arr2[i] + " ");} // Prints intersection of arr1[0..m-1] and arr2[0..n-1]function printIntersection(arr1, arr2, m, n){ // Before finding intersection, make sure arr1[0..m-1] // is smaller if (m > n) { let tempp = arr1; arr1 = arr2; arr2 = tempp; let temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] arr1.sort((a, b) => a - b); // Search every element of bigger array in smaller // array and print the element if found for (let i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) document.write(arr2[i] + " ");} /* Driver program to test above function */ let arr1 = [ 7, 1, 5, 2, 3, 6 ]; let arr2 = [ 3, 8, 6, 20, 7 ]; let m = arr1.length; let n = arr2.length; // Function call document.write("Union of two arrays is <br>"); printUnion(arr1, arr2, m, n); document.write("<br>Intersection of two arrays is<br>"); printIntersection(arr1, arr2, m, n); // This code is contributed by Surbhi Tyagi.</script>
Union of two arrays is n3 6 7 8 20 1 5 2 nIntersection of two arrays is n7 3 6
Another Approach (When elements in the array may not be distinct) :
C++
Java
Python3
C#
PHP
Javascript
// C++ code to find intersection when// elements may not be distinct#include <bits/stdc++.h> using namespace std; // Function to find intersectionvoid intersection(int a[], int b[], int n, int m){ int i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal cout << a[i] << " "; i++; j++; } }} // Driver Codeint main(){ int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 }; int b[] = { 3, 3, 5 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // sort sort(a, a + n); sort(b, b + m); // Function call intersection(a, b, n, m);}
// Java code to find intersection when// elements may not be distinct import java.io.*;import java.util.Arrays; class GFG { // Function to find intersection static void intersection(int a[], int b[], int n, int m) { int i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal System.out.print(a[i] + " "); i++; j++; } } } // Driver Code public static void main(String[] args) { int a[] = { 1, 3, 2, 3, 4, 5, 5, 6 }; int b[] = { 3, 3, 5 }; int n = a.length; int m = b.length; // sort Arrays.sort(a); Arrays.sort(b); // Function call intersection(a, b, n, m); }}
# Python 3 code to find intersection# when elements may not be distinct # Function to find intersection def intersection(a, b, n, m): i = 0 j = 0 while (i < n and j < m): if (a[i] > b[j]): j += 1 else: if (b[j] > a[i]): i += 1 else: # when both are equal print(a[i], end=" ") i += 1 j += 1 # Driver Codeif __name__ == "__main__": a = [1, 3, 2, 3, 4, 5, 5, 6] b = [3, 3, 5] n = len(a) m = len(b) # sort a.sort() b.sort() # function call intersection(a, b, n, m) # This code is contributed by Ita_c
// C# code to find intersection when// elements may not be distinct using System; class GFG { // Function to find intersection static void intersection(int[] a, int[] b, int n, int m) { int i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal Console.Write(a[i] + " "); i++; j++; } } } // Driver Code public static void Main() { int[] a = { 1, 3, 2, 3, 4, 5, 5, 6 }; int[] b = { 3, 3, 5 }; int n = a.Length; int m = b.Length; // sort Array.Sort(a); Array.Sort(b); // Function call intersection(a, b, n, m); }}// this code is contributed by mukul singh
<?php// PHP code to find intersection when// elements may not be distinct // Function to find intersectionfunction intersection($a, $b, $n, $m){ $i = 0; $j = 0; while ($i < $n && $j < $m) { if ($a[$i] > $b[$j]) { $j++; } else if ($b[$j] > $a[$i]) { $i++; } else { // when both are equal echo($a[$i] . " "); $i++; $j++; } }} // Driver Code$a = array(1, 3, 2, 3, 4, 5, 5, 6);$b = array(3, 3, 5); $n = sizeof($a);$m = sizeof($b); // sortsort($a);sort($b); // Function callintersection($a, $b, $n, $m); // This code is contributed// by Mukul Singh?>
<script>// Javascript code to find intersection when// elements may not be distinct // Function to find intersection function intersection(a,b,n,m) { let i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal document.write(a[i] + " "); i++; j++; } } } // Driver Code let a = [1, 3, 2, 3, 4, 5, 5, 6 ]; let b = [3, 3, 5 ] let n = a.length; let m = b.length; // sort a.sort(); b.sort(); // Function call intersection(a, b, n, m); // This code is contributed by rag2127</script>
3 3 5
Thanks, Sanny Kumar for suggesting the above method.
Method 6(Without using hashing or any predefined library like sets or maps and works even for both repeated and distant elements)
First of all we sort both arrays and proceed as below:
Union
Iterate in while loop until any one array is finished.In each iteration we look for smaller in both arrays and we print it and increment its pointer only if it is not same as the last element printed in union.After we finish while we iterate the remaining of two array in the similar way as above and print the union.
Iterate in while loop until any one array is finished.
In each iteration we look for smaller in both arrays and we print it and increment its pointer only if it is not same as the last element printed in union.
After we finish while we iterate the remaining of two array in the similar way as above and print the union.
Intersection
Iterate in while loop till any of the one array is finished.In each iteration we look for smaller of the two elements from both the array and increase its pointer because it will not be in other list, hence not part of intersection.For intersection,ff both the elements are equal we print it and increment both pointer only if it is not same as the last element printed in intersection.
Iterate in while loop till any of the one array is finished.
In each iteration we look for smaller of the two elements from both the array and increase its pointer because it will not be in other list, hence not part of intersection.
For intersection,ff both the elements are equal we print it and increment both pointer only if it is not same as the last element printed in intersection.
C++
#include <bits/stdc++.h> using namespace std; // Function to find union void Union(int a[], int b[], int n, int m) { int *result=new int[n+m]; int index=0; int left=0,right=0; while(left<n && right<m){ if(a[left]<b[right]){ if(index!=0 && a[left]==result[index-1]){ left++; }else{ result[index]=a[left]; left++; index++; } }else{ if(index!=0 && b[right]==result[index-1]){ right++; }else{ result[index]=b[right]; right++; index++; } } } while(left<n){ if(index!=0 && a[left]==result[index-1]){ left++; }else{ result[index]=a[left]; left++; index++; } } while(right<m){ if(index!=0 && b[right]==result[index-1]){ right++; }else{ result[index]=b[right]; right++; index++; } } cout<<"Union: "; for(int k=0;k<index;k++) cout<<result[k]<<" "; cout<<endl; }; // Function to find intersectionvoid intersection(int a[], int b[], int n, int m) { int i=0,j=0,k=0; int *result=new int[n+m]; while(i<n && j<m){ if(a[i]<b[j]) i++; else if(a[i]>b[j]) j++; else{ if(k!=0 && a[i]==result[k-1]){ i++; j++; } else{ result[k]=a[i]; i++; j++; k++; } } } cout<<"Intersection: "; for(int x=0;x<k;x++) cout<<result[x]<<" "; cout<<endl; } // Driver Codeint main(){ int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 }; int b[] = { 3, 3, 5 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // sort sort(a, a + n); sort(b, b + m); // Function call Union(a,b,n,m); intersection(a, b, n, m);}
Method 7 (Use Hashing) Union
Initialize an empty hash set hs.Iterate through the first array and put every element of the first array in the set S.Repeat the process for the second array.Print the set hs.
Initialize an empty hash set hs.
Iterate through the first array and put every element of the first array in the set S.
Repeat the process for the second array.
Print the set hs.
Intersection
Initialize an empty set hs.Iterate through the first array and put every element of the first array in the set S.For every element x of the second array, do the following :
Initialize an empty set hs.
Iterate through the first array and put every element of the first array in the set S.
For every element x of the second array, do the following :
Search x in the set hs. If x is present, then print it. Time complexity of this method is ?(m+n) under the assumption that hash table search and insert operations take ?(1) time.
Below is the implementation of the above idea:
C++
Java
Python
C#
Javascript
// CPP program to find union and intersection// using sets#include <bits/stdc++.h>using namespace std; // Prints union of arr1[0..n1-1] and arr2[0..n2-1]void printUnion(int arr1[], int arr2[], int n1, int n2){ set<int> hs; // Insert the elements of arr1[] to set hs for (int i = 0; i < n1; i++) hs.insert(arr1[i]); // Insert the elements of arr2[] to set hs for (int i = 0; i < n2; i++) hs.insert(arr2[i]); // Print the content of set hs for (auto it = hs.begin(); it != hs.end(); it++) cout << *it << " "; cout << endl;} // Prints intersection of arr1[0..n1-1] and// arr2[0..n2-1]void printIntersection(int arr1[], int arr2[], int n1, int n2){ set<int> hs; // Insert the elements of arr1[] to set S for (int i = 0; i < n1; i++) hs.insert(arr1[i]); for (int i = 0; i < n2; i++) // If element is present in set then // push it to vector V if (hs.find(arr2[i]) != hs.end()) cout << arr2[i] << " ";} // Driver Programint main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Function call printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2); return 0;}
// Java program to find union and intersection// using Hashingimport java.util.HashSet; class Test { // Prints union of arr1[0..m-1] and arr2[0..n-1] static void printUnion(int arr1[], int arr2[]) { HashSet<Integer> hs = new HashSet<>(); for (int i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (int i = 0; i < arr2.length; i++) hs.add(arr2[i]); System.out.println(hs); } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] static void printIntersection(int arr1[], int arr2[]) { HashSet<Integer> hs = new HashSet<>(); HashSet<Integer> hs1 = new HashSet<>(); for (int i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (int i = 0; i < arr2.length; i++) if (hs.contains(arr2[i])) System.out.print(arr2[i] + " "); } // Driver code public static void main(String[] args) { int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; // Function call System.out.println("Union of two arrays is : "); printUnion(arr1, arr2); System.out.println( "Intersection of two arrays is : "); printIntersection(arr1, arr2); }}
# Python program to find union and intersection# using sets def printUnion(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set hs for i in range(0, n1): hs.add(arr1[i]) # Insert the elements of arr1[] to set hs for i in range(0, n2): hs.add(arr2[i]) print("Union:") for i in hs: print(i, end=" ") print("\n") # Prints intersection of arr1[0..n1-1] and # arr2[0..n2-1] def printIntersection(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set S for i in range(0, n1): hs.add(arr1[i]) print("Intersection:") for i in range(0, n2): # If element is present in set then # push it to vector V if arr2[i] in hs: print(arr2[i], end=" ") # Driver Programarr1 = [7, 1, 5, 2, 3, 6]arr2 = [3, 8, 6, 20, 7]n1 = len(arr1)n2 = len(arr2) # Function callprintUnion(arr1, arr2, n1, n2)printIntersection(arr1, arr2, n1, n2) # This article is contributed by Kumar Suman .
// C# program to find union and intersection// using Hashingusing System;using System.Linq;using System.Collections.Generic; class GFG{ // Prints union of arr1[0..m-1] and arr2[0..n-1] static void printUnion(int []arr1, int []arr2) { HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < arr1.Length; i++) hs.Add(arr1[i]); for (int i = 0; i < arr2.Length; i++) hs.Add(arr2[i]); Console.WriteLine(string.Join(", ", hs)); } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] static void printIntersection(int []arr1, int []arr2) { HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < arr1.Length; i++) hs.Add(arr1[i]); for (int i = 0; i < arr2.Length; i++) if (hs.Contains(arr2[i])) Console.Write(arr2[i] + " "); } // Driver Code static void Main() { int []arr1 = {7, 1, 5, 2, 3, 6}; int []arr2 = {3, 8, 6, 20, 7}; Console.WriteLine("Union of two arrays is : "); printUnion(arr1, arr2); Console.WriteLine("\nIntersection of two arrays is : "); printIntersection(arr1, arr2); }} // This code is contributed by mits
<script>// javascript program to find union and intersection// using Hashing // Prints union of arr1[0..m-1] and arr2[0..n-1] function printUnion(arr1 , arr2) { var hs = new Set(); for (i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (i = 0; i < arr2.length; i++) hs.add(arr2[i]); for(var k of hs) document.write(k+" "); } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] function printIntersection(arr1 , arr2) { var hs = new Set(); var hs1 = new Set(); for (i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (var i = 0; i < arr2.length; i++) if (hs.has(arr2[i])) document.write(arr2[i] + " "); } // Driver code var arr1 = [ 7, 1, 5, 2, 3, 6 ]; var arr2 = [ 3, 8, 6, 20, 7 ]; // Function call document.write("Union of two arrays is :<br/> "); printUnion(arr1, arr2); document.write("<br/>Intersection of two arrays is : <br/>"); printIntersection(arr1, arr2); // This code is contributed by gauravrajput1</script>
1 2 3 5 6 7 8 20
3 6 7
This method is contributed by Ankur Singh.The time complexity of this method is O(m+n) under the assumption that hash table search and insert operations take O(1) time.
Method 8 (Kind of hashing technique without using any predefined Java Collections)
Initialize the array with a size of m+nFill first array value in a resultant array by doing hashing(to find appropriate position)Repeat for the second arrayWhile doing hashing if a collision happens increment the position in a recursive way
Initialize the array with a size of m+n
Fill first array value in a resultant array by doing hashing(to find appropriate position)
Repeat for the second array
While doing hashing if a collision happens increment the position in a recursive way
Below is the implementation of the above code:
C++
Java
Python3
C#
Javascript
// CPP program to find union and intersection #include <bits/stdc++.h>using namespace std; // Prints union of arr1[0..n1-1] and arr2[0..n2-1]void printUnion(int v, int ans[], int zero){ int zero1 = 0; cout<<"\nUnion : "; for (int i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; cout<<ans[i] << ","; }} void placeValue(int a[], int ans[], int i, int p, int v){ p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) cout<<a[i] << ","; else { // Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } }} void placeZeros(int v, int ans[], int zero){ if (zero == 2) { cout<<"0"<<endl; int d[] = { 0 }; placeValue(d, ans, 0, 0, v); } if (zero == 1) { int d[] = { 0 }; placeValue(d, ans, 0, 0, v); }} // Function to iterate arrayint iterateArray(int a[], int v, int ans[], int i){ if (a[i] != 0) { int p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0;} // Prints intersection of arr1[0..n1-1] and// arr2[0..n2-1]void findPosition(int a[], int b[], int n1, int n2){ int v = (n1+n2); int ans[v]; for(int i=0;i<v;i++) { ans[i]=0; } int zero1 = 0; int zero2 = 0; cout<<"Intersection : "; // Iterate first array for (int i = 0; i < n1; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (int j = 0; j < n2; j++) zero2 = iterateArray(b, v, ans, j); int zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero);} // Driver Programint main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Function call findPosition(arr1, arr2, n1, n2); return 0;} // This code is contributed by Aarti_Rathi
// Java program to find union and intersection// using similar Hashing Technique// without using any predefined Java Collections// Time Complexity best case & avg case = O(m+n)// Worst case = O(nlogn) // package com.arrays.math; public class UnsortedIntersectionUnion { // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1] public void findPosition(int a[], int b[]) { int v = (a.length + b.length); int ans[] = new int[v]; int zero1 = 0; int zero2 = 0; System.out.print("Intersection : "); // Iterate first array for (int i = 0; i < a.length; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (int j = 0; j < b.length; j++) zero2 = iterateArray(b, v, ans, j); int zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); } // Prints union of arr1[0..n1-1] and arr2[0..n2-1] private void printUnion(int v, int[] ans, int zero) { int zero1 = 0; System.out.print("\nUnion : "); for (int i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; System.out.print(ans[i] + ","); } } private void placeZeros(int v, int[] ans, int zero) { if (zero == 2) { System.out.println("0"); int d[] = { 0 }; placeValue(d, ans, 0, 0, v); } if (zero == 1) { int d[] = { 0 }; placeValue(d, ans, 0, 0, v); } } // Function to iterate array private int iterateArray(int[] a, int v, int[] ans, int i) { if (a[i] != 0) { int p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0; } private void placeValue(int[] a, int[] ans, int i, int p, int v) { p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) System.out.print(a[i] + ","); else { // Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } } } // Driver code public static void main(String args[]) { int a[] = { 7, 1, 5, 2, 3, 6 }; int b[] = { 3, 8, 6, 20, 7 }; // Function call UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion(); uiu.findPosition(a, b); }}// This code is contributed by Mohanakrishnan S.
# Python3 program to find union and intersection# using similar Hashing Technique# without using any predefined Java Collections# Time Complexity best case & avg case = O(m+n)# Worst case = O(nlogn) # Prints intersection of arr1[0..n1-1] and# arr2[0..n2-1]def findPosition(a, b): v = len(a) + len(b); ans = [0]*v; zero1 = zero2 = 0; print("Intersection :",end=" "); # Iterate first array for i in range(len(a)): zero1 = iterateArray(a, v, ans, i); # Iterate second array for j in range(len(b)): zero2 = iterateArray(b, v, ans, j); zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); # Prints union of arr1[0..n1-1] and arr2[0..n2-1]def printUnion(v, ans,zero): zero1 = 0; print("\nUnion :",end=" "); for i in range(v): if ((zero == 0 and ans[i] == 0) or (ans[i] == 0 and zero1 > 0)): continue; if (ans[i] == 0): zero1+=1; print(ans[i],end=","); def placeZeros(v, ans, zero): if (zero == 2): print("0"); d = [0]; placeValue(d, ans, 0, 0, v); if (zero == 1): d=[0]; placeValue(d, ans, 0, 0, v); # Function to iterate arraydef iterateArray(a,v,ans,i): if (a[i] != 0): p = a[i] % v; placeValue(a, ans, i, p, v); else: return 1; return 0; def placeValue(a,ans,i,p,v): p = p % v; if (ans[p] == 0): ans[p] = a[i]; else: if (ans[p] == a[i]): print(a[i],end=","); else: # Hashing collision happened increment # position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); # Driver codea = [ 7, 1, 5, 2, 3, 6 ];b = [ 3, 8, 6, 20, 7 ];findPosition(a, b); # This code is contributed by mits
// C# program to find union and intersection// using similar Hashing Technique// without using any predefined Java Collections// Time Complexity best case & avg case = O(m+n)// Worst case = O(nlogn) //package com.arrays.math;using System;class UnsortedIntersectionUnion{ // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1] public void findPosition(int []a, int []b) { int v = (a.Length + b.Length); int []ans = new int[v]; int zero1 = 0; int zero2 = 0; Console.Write("Intersection : "); // Iterate first array for (int i = 0; i < a.Length; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (int j = 0; j < b.Length; j++) zero2 = iterateArray(b, v, ans, j); int zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); } // Prints union of arr1[0..n1-1] // and arr2[0..n2-1] private void printUnion(int v, int[] ans, int zero) { int zero1 = 0; Console.Write("\nUnion : "); for (int i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; Console.Write(ans[i] + ","); } } private void placeZeros(int v, int[] ans, int zero) { if (zero == 2) { Console.WriteLine("0"); int []d = { 0 }; placeValue(d, ans, 0, 0, v); } if (zero == 1) { int []d = { 0 }; placeValue(d, ans, 0, 0, v); } } // Function to iterate array private int iterateArray(int[] a, int v, int[] ans, int i) { if (a[i] != 0) { int p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0; } private void placeValue(int[] a, int[] ans, int i, int p, int v) { p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) Console.Write(a[i] + ","); else { //Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } } } // Driver code public static void Main() { int []a = { 7, 1, 5, 2, 3, 6 }; int []b = { 3, 8, 6, 20, 7 }; UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion(); uiu.findPosition(a, b); }} // This code is contributed by PrinciRaj1992
<script>// javascript program to find union and intersection// using similar Hashing Technique// without using any predefined javascript Collections// Time Complexity best case & avg case = O(m+n)// Worst case = O(nlogn) // package com.arrays.math; // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1] function findPosition(a , b) { var v = (a.length + b.length); var ans = Array(v).fill(0); var zero1 = 0; var zero2 = 0; document.write("Intersection : "); // Iterate first array for (var i = 0; i < a.length; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (var j = 0; j < b.length; j++) zero2 = iterateArray(b, v, ans, j); var zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); } // Prints union of arr1[0..n1-1] and arr2[0..n2-1] function printUnion(v, ans , zero) { var zero1 = 0; document.write("<br/>Union : "); for (i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; document.write(ans[i] + ","); } } function placeZeros(v, ans , zero) { if (zero == 2) { document.write("0"); var d = [ 0 ]; placeValue(d, ans, 0, 0, v); } if (zero == 1) { var d = [ 0 ]; placeValue(d, ans, 0, 0, v); } } // Function to iterate array function iterateArray(a , v, ans , i) { if (a[i] != 0) { var p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0; } function placeValue(a, ans , i , p , v) { p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) document.write(a[i] + ","); else { // Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } } } // Driver code var a = [ 7, 1, 5, 2, 3, 6 ]; var b = [ 3, 8, 6, 20, 7 ]; // Function call findPosition(a, b); // This code is contributed by gauravrajput1</script>
Intersection : 3,6,7,
Union : 1,2,3,5,6,7,8,20,
C++
Java
Python3
C#
// C++ program to find union and intersection// using sets #include <bits/stdc++.h>using namespace std; void printUnion(int arr1[], int arr2[], int n1, int n2){ // Defining set container s set<int> s; // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.insert(arr1[i]); } // Insert the elements of arr2[] to set s for (int i = 0; i < n2; i++) { s.insert(arr2[i]); } cout << "Union:" << endl; for (auto itr = s.begin(); itr != s.end(); itr++) // s will contain only distinct // elements from array a and b cout << *itr<< " "; cout <<endl; // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1]} void printIntersection(int arr1[], int arr2[], int n1, int n2){ // Defining set container s set<int> s; // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.insert(arr1[i]); } cout << "Intersection:" << endl; for (int i = 0; i < n2; i++) { // If element is present in set then if(s.count(arr2[i])) { cout<<arr2[i]<<" "; } } cout <<endl;} // Driver Codeint main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2);} // This code is contributed by Aarti_Rathi
// Java program to find union and intersection// using sets import java.util.*; public class GFG { static void printUnion(int arr1[], int arr2[], int n1, int n2) { // Defining set container s Set<Integer> s = new HashSet<Integer>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.add(arr1[i]); } // Insert the elements of arr2[] to set s for (int i = 0; i < n2; i++) { s.add(arr2[i]); } System.out.println("Union"); for (int itr : s) // s will contain only distinct // elements from array a and b System.out.print(itr + " "); System.out.println(); } static void printIntersection(int arr1[], int arr2[], int n1, int n2) { // Defining set container s Set<Integer> s = new HashSet<Integer>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.add(arr1[i]); } System.out.println("Intersection"); for (int i = 0; i < n2; i++) { // If element is present in set then if (s.contains(arr2[i])) { System.out.print(arr2[i] + " "); } } System.out.println(); } // Driver code public static void main(String args[]) { int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = arr1.length; int n2 = arr2.length; // Function call printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2); }}// This code is contributed by Aarti_Rathi
# Python program to find union and intersection# using sets def printUnion(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set hs for i in range(0, n1): hs.add(arr1[i]) # Insert the elements of arr1[] to set hs for i in range(0, n2): hs.add(arr2[i]) print("Union:") for i in hs: print(i, end=" ") print("\n") # Prints intersection of arr1[0..n1-1] and # arr2[0..n2-1] def printIntersection(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set S for i in range(0, n1): hs.add(arr1[i]) print("Intersection:") for i in range(0, n2): # If element is present in set then # push it to vector V if arr2[i] in hs: print(arr2[i], end=" ") # Driver Programarr1 = [7, 1, 5, 2, 3, 6]arr2 = [3, 8, 6, 20, 7]n1 = len(arr1)n2 = len(arr2) # Function callprintUnion(arr1, arr2, n1, n2)printIntersection(arr1, arr2, n1, n2) # This code is contributed by Kumar Suman .
// C# program to find union and intersection// using sets using System;using System.Collections.Generic; public class GFG { static void printUnion(int[] arr1, int[] arr2, int n1, int n2) { // Defining set container s SortedSet<int> s = new SortedSet<int>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.Add(arr1[i]); } // Insert the elements of arr2[] to set s for (int i = 0; i < n2; i++) { s.Add(arr2[i]); } Console.WriteLine("Union"); foreach(var itr in s) // s will contain only distinct // elements from array a and b Console.Write(itr + " "); Console.WriteLine(); } static void printIntersection(int[] arr1, int[] arr2, int n1, int n2) { // Defining set container s SortedSet<int> s = new SortedSet<int>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.Add(arr1[i]); } Console.WriteLine("Intersection"); for (int i = 0; i < n2; i++) { // If element is present in set then if (s.Contains(arr2[i])) { Console.Write(arr2[i] + " "); } } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int[] arr1 = { 7, 1, 5, 2, 3, 6 }; int[] arr2 = { 3, 8, 6, 20, 7 }; int n1 = arr1.Length; int n2 = arr2.Length; // Function call printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2); }} // This code is contributed by phasing17
Union:
1 2 3 5 6 7 8 20
Intersection:
3 6 7
See the following post for sorted arrays. Find Union and Intersection of two sorted arrays
Sach_Code
Code_Mech
ukasp
smkrishnan22
princiraj1992
Mithun Kumar
Kirti_Mangal
ks120198
meemurumkar
sudheersahu
vinayverma8948
avanitrachhadiya2155
rag2127
anirbanchand54
surbhityagi15
arorakashish0911
lokeshpotta20
19bcs1298
imposter22
simranarora5sos
GauravRajput1
umadevi9616
kk9826225
kiranu941
parthmalhotra
shinjanpatra
Rajput-Ji
sagartomar9927
_shinchancode
codewithshinchan
adi1212
sachinvinod1904
rajrajgupta18
Amazon
Rockstand
Arrays
Mathematical
Amazon
Rockstand
Arrays
Mathematical
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Multidimensional Arrays in Java
Stack Data Structure (Introduction and Program)
Linear Search
Program for Fibonacci numbers
Set in C++ Standard Template Library (STL)
Write a program to print all permutations of a given string
C++ Data Types
Merge two sorted arrays | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 189,
"s": 52,
"text": "Given two unsorted arrays that represent two sets (elements in every array are distinct), find the union and intersection of two arrays."
},
{
"code": null,
"e": 228,
"s": 189,
"text": "For example, if the input arrays are: "
},
{
"code": null,
"e": 284,
"s": 228,
"text": "arr1[] = {7, 1, 5, 2, 3, 6} \narr2[] = {3, 8, 6, 20, 7} "
},
{
"code": null,
"e": 459,
"s": 284,
"text": "Then your program should print Union as {1, 2, 3, 5, 6, 7, 8, 20} and Intersection as {3, 6, 7}. Note that the elements of union and intersection can be printed in any order."
},
{
"code": null,
"e": 481,
"s": 459,
"text": "Method 1 (Using Set):"
},
{
"code": null,
"e": 799,
"s": 481,
"text": "Union of two arrays we can get with the Set data structure very easily. Set is a data structure that allows only the distinct elements in it. So, when we put the elements of both the array into the set we will get only the distinct elements that are equal to the union operation over the arrays. Let’s code it now –> "
},
{
"code": null,
"e": 803,
"s": 799,
"text": "C++"
},
{
"code": null,
"e": 808,
"s": 803,
"text": "Java"
},
{
"code": null,
"e": 816,
"s": 808,
"text": "Python3"
},
{
"code": null,
"e": 819,
"s": 816,
"text": "C#"
},
{
"code": null,
"e": 830,
"s": 819,
"text": "Javascript"
},
{
"code": "// C++ program for the union of two arrays using Set#include <bits/stdc++.h>using namespace std;void getUnion(int a[], int n, int b[], int m){ // Defining set container s set<int> s; // Inserting array elements in s for (int i = 0; i < n; i++) s.insert(a[i]); for (int i = 0; i < m; i++) s.insert(b[i]); cout << \"Number of elements after union operation: \" << s.size() << endl; cout << \"The union set of both arrays is :\" << endl; for (auto itr = s.begin(); itr != s.end(); itr++) cout << *itr << \" \"; // s will contain only distinct // elements from array a and b} // Driver Codeint main(){ int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10);} // contributed by Anirban Chand",
"e": 1664,
"s": 830,
"text": null
},
{
"code": "// Java program for the union of two arrays using Setimport java.util.*; class GFG{static void getUnion(int a[], int n, int b[], int m){ // Defining set container s HashSet<Integer> s = new HashSet<>(); // Inserting array elements in s for (int i = 0; i < n; i++) s.add(a[i]); for (int i = 0; i < m; i++) s.add(b[i]); System.out.print(\"Number of elements after union operation: \" + s.size() +\"\\n\"); System.out.print(\"The union set of both arrays is :\" +\"\\n\"); System.out.print(s.toString()+ \" \"); // s will contain only distinct // elements from array a and b} // Driver Codepublic static void main(String[] args){ int a[] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10);}} // This code is contributed by gauravrajput1",
"e": 2523,
"s": 1664,
"text": null
},
{
"code": "# Python program for the union of two arrays using Setdef getUnion(a, n, b, m): # Defining set container s s =set(); # Inserting array elements in s for i in range(n): s.add(a[i]); for i in range(m): s.add(b[i]); print(\"Number of elements after union operation: \" , len(s) , \"\"); print(\"The union set of both arrays is :\" + \"\"); print(s, end=\"\"); # s will contain only distinct # elements from array a and b # Driver Codeif __name__ == '__main__': a = [ 1, 2, 5, 6, 2, 3, 5, 7, 3 ]; b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 ]; getUnion(a, 9, b, 10); # This code is contributed by gauravrajput1",
"e": 3166,
"s": 2523,
"text": null
},
{
"code": "// C# program for the union of two arrays using Setusing System;using System.Collections.Generic; public class GFG { static void getUnion(int []a, int n, int []b, int m) { // Defining set container s HashSet<int> s = new HashSet<int>(); // Inserting array elements in s for (int i = 0; i < n; i++) s.Add(a[i]); for (int i = 0; i < m; i++) s.Add(b[i]); Console.Write(\"Number of elements after union operation: \" + s.Count + \"\\n\"); Console.Write(\"The union set of both arrays is :\" + \"\\n\"); foreach(int i in s) Console.Write(i + \" \"); // s will contain only distinct // elements from array a and b } // Driver Code public static void Main(String[] args) { int []a = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10); }} // This code is contributed by umadevi9616",
"e": 4107,
"s": 3166,
"text": null
},
{
"code": "<script> // JavaScript program for the above // approach using Set function getUnion(a, n, b, m) { // Defining set container s var s = new Set(); // Inserting array elements in s for (let i = 0; i < n; i++) s.add(a[i]); for (let i = 0; i < m; i++) s.add(b[i]); document.write( \"Number of elements after union operation: \" + s.size + \"<br>\"); document.write(\"The union set of both arrays is :\"); document.write(\"<br>\"); var arr = []; for (let itr of s) arr.push(itr); // s will contain only distinct // elements from array a and b arr.sort(function (a, b) { return a - b; }) for (let i = 0; i < arr.length; i++) { document.write(arr[i] + \" \"); } } // Driver Code let a = [1, 2, 5, 6, 2, 3, 5, 7, 3]; let b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4]; getUnion(a, 9, b, 10); // This code is contributed by Potta Lokesh </script>",
"e": 5213,
"s": 4107,
"text": null
},
{
"code": null,
"e": 5310,
"s": 5213,
"text": "Number of elements after union operation: 9\nThe union set of both arrays is :\n1 2 3 4 5 6 7 8 9 "
},
{
"code": null,
"e": 5354,
"s": 5310,
"text": "Time Complexity: O(m * log(m) + n * log(n))"
},
{
"code": null,
"e": 5507,
"s": 5354,
"text": "Note: O(m + n) in case of Python because in python the set built-in method is quite different than that of C++ once, Python uses an hash map internally."
},
{
"code": null,
"e": 5765,
"s": 5507,
"text": "We can improve performance of getUnion method by iterating over both the arrays for index from 0 to min(n, m)-1 adding all the elements in both the arrays to the set, and then iterate over the other array with the remaining elements and add them to the set."
},
{
"code": null,
"e": 5769,
"s": 5765,
"text": "C++"
},
{
"code": null,
"e": 5774,
"s": 5769,
"text": "Java"
},
{
"code": null,
"e": 5782,
"s": 5774,
"text": "Python3"
},
{
"code": null,
"e": 5785,
"s": 5782,
"text": "C#"
},
{
"code": null,
"e": 5796,
"s": 5785,
"text": "Javascript"
},
{
"code": "// C++ program for the union of two arrays using Set#include <bits/stdc++.h>using namespace std;void getUnion(int a[], int n, int b[], int m){ int min=(n<m)? n : m; // Defining set container s set<int> s; // add elements from both the arrays for // index from 0 to min(n, m)-1 for (int i = 0; i < min; i++) { s.insert(a[i]); s.insert(b[i]); } if (n > m) { for (int i = m; i < n; i++) { s.insert(a[i]); } } else if (n < m) { for (int i = n; i < m; i++) { s.insert(b[i]); } } cout << \"Number of elements after union operation: \" << s.size() << endl; cout << \"The union set of both arrays is :\" << endl; for (auto itr = s.begin(); itr != s.end(); itr++) cout << *itr << \" \"; // s will contain only distinct // elements from array a and b} // Driver Codeint main(){ int a[9] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[10] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10);} // This code is contributed by Aarti_Rathi",
"e": 6911,
"s": 5796,
"text": null
},
{
"code": "// Java program for the union of two arrays using Setimport java.util.*; class GFG { static void getUnion(int a[], int n, int b[], int m) { // find min of n and m int min = (n < m) ? n : m; // set container Set<Integer> set = new HashSet<>(); // add elements from both the arrays for // index from 0 to min(n, m)-1 for (int i = 0; i < min; i++) { set.add(a[i]); set.add(b[i]); } // add remiaining elements to the set from the other // array (having greater length) // note that only one of the loops will execute if (n > m) { for (int i = m; i < n; i++) { set.add(a[i]); } } else if (n < m) { for (int i = n; i < m; i++) { set.add(b[i]); } } // driver code to print the output System.out.println(\"Number of elements after union operation: \" + set.size()); System.out.println(\"The union set of both arrays is :\"); System.out.print(set.toString()); } // Driver Code public static void main(String[] args) { int a[] = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10); }} // This code is contributed by Parth Malhotra",
"e": 8249,
"s": 6911,
"text": null
},
{
"code": "# Python program for the union of two arrays using Setdef getUnion(a, n, b, m): # Defining set container s hs = set() if(n<m): min=n else: min=m # add elements from both the arrays for # index from 0 to min(n, m)-1 for i in range(0, min): hs.add(a[i]) hs.add(b[i]) if(n>m): for i in range(m, n): hs.add(a[i]) else: if(n<m): for i in range(m, n): hs.add(b[i]) print(\"Number of elements after union operation: \",len(hs)) print(\"The union set of both arrays is :\") for i in hs: print(i, end=\" \") print(\"\\n\") # s will contain only distinct # elements from array a and b # Driver Programa = [1, 2, 5, 6, 2, 3, 5, 7, 3]b = [2, 4, 5, 6, 8, 9, 4, 6, 5, 4]n1 = len(a)n2 = len(b) # Function callgetUnion(a, n1, b, n2) # This code is contributed by Aarti_Rathi",
"e": 9173,
"s": 8249,
"text": null
},
{
"code": "// C# program for the union of two arrays using Setusing System;using System.Collections.Generic; public class GFG { static void getUnion(int []a, int n, int []b, int m) { // find min of n and m int min = (n < m) ? n : m; // set container HashSet<int> set = new HashSet<int>(); // add elements from both the arrays for // index from 0 to min(n, m)-1 for (int i = 0; i < min; i++) { set.Add(a[i]); set.Add(b[i]); } // add remiaining elements to the set from the other // array (having greater length) // note that only one of the loops will execute if (n > m) { for (int i = m; i < n; i++) { set.Add(a[i]); } } else if (n < m) { for (int i = n; i < m; i++) { set.Add(b[i]); } } // driver code to print the output Console.WriteLine(\"Number of elements after union operation: \" + set.Count); Console.WriteLine(\"The union set of both arrays is :[\"); foreach(int x in set) Console.Write(x+\", \"); Console.Write(\"]\"); } // Driver Code public static void Main(String[] args) { int []a = { 1, 2, 5, 6, 2, 3, 5, 7, 3 }; int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 }; getUnion(a, 9, b, 10); }} // This code is contributed by Rajput-Ji",
"e": 10422,
"s": 9173,
"text": null
},
{
"code": "<script>// javascript program for the union of two arrays using Set function getUnion(a , n , b , m) { // find min of n and m var min = (n < m) ? n : m; // set container var set = new Set(); // add elements from both the arrays for // index from 0 to min(n, m)-1 for (i = 0; i < min; i++) { set.add(a[i]); set.add(b[i]); } // add remiaining elements to the set from the other // array (having greater length) // note that only one of the loops will execute if (n > m) { for (i = m; i < n; i++) { set.add(a[i]); } } else if (n < m) { for (i = n; i < m; i++) { set.add(b[i]); } } // driver code to print the output document.write(\"Number of elements after union operation: \" + set.size); document.write(\"<br/>The union set of both arrays is :<br/>\"); set.forEach (function(value) {document.write(value+\" \");}) } // Driver Code var a = [ 1, 2, 5, 6, 2, 3, 5, 7, 3 ]; var b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5, 4 ]; getUnion(a, 9, b, 10);// This code contributed by Rajput-Ji</script>",
"e": 11669,
"s": 10422,
"text": null
},
{
"code": null,
"e": 11775,
"s": 11669,
"text": "Number of elements after union operation: 9\nThe union set of both arrays is :\n[1, 2, 3, 4, 5, 6, 7, 8, 9]"
},
{
"code": null,
"e": 11806,
"s": 11775,
"text": "Time Complexity: O( max(m,n) )"
},
{
"code": null,
"e": 11843,
"s": 11806,
"text": "Method 2: (Using map data structure)"
},
{
"code": null,
"e": 12148,
"s": 11843,
"text": "From the knowledge of data structures, we know that map stores distinct keys only. So if we insert any key appearing more than one time it gets stored only once. The idea is to insert both the arrays in one common map which would then store the distinct elements of both arrays (union of both the array)."
},
{
"code": null,
"e": 12197,
"s": 12148,
"text": "Below is the implementation of the above method:"
},
{
"code": null,
"e": 12201,
"s": 12197,
"text": "C++"
},
{
"code": null,
"e": 12206,
"s": 12201,
"text": "Java"
},
{
"code": null,
"e": 12214,
"s": 12206,
"text": "Python3"
},
{
"code": null,
"e": 12217,
"s": 12214,
"text": "C#"
},
{
"code": null,
"e": 12228,
"s": 12217,
"text": "Javascript"
},
{
"code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;void printUnion(int* a, int n, int* b, int m){ // Defining map container mp map<int, int> mp; // Inserting array elements in mp for (int i = 0; i < n; i++) mp.insert({ a[i], i }); for (int i = 0; i < m; i++) mp.insert({ b[i], i }); cout << \"The union set of both arrays is :\" << endl; for (auto itr = mp.begin(); itr != mp.end(); itr++) cout << itr->first << \" \"; // mp will contain only distinct // elements from array a and b} // Driver Codeint main(){ int a[7] = { 1, 2, 5, 6, 2, 3, 5 }; int b[9] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; printUnion(a, 7, b, 9);}",
"e": 12962,
"s": 12228,
"text": null
},
{
"code": "// Java program for the above approachimport java.io.*;import java.util.*; class GFG{ static void printUnion(int[] a, int n, int[] b, int m){ Map<Integer, Integer> mp = new HashMap<Integer, Integer>(); // Inserting array elements in mp for(int i = 0; i < n; i++) { mp.put(a[i], i); } for(int i = 0; i < m; i++) { mp.put(b[i], i); } System.out.println(\"The union set of both arrays is :\"); for(Map.Entry mapElement : mp.entrySet()) { System.out.print(mapElement.getKey() + \" \"); // mp will contain only distinct // elements from array a and b }} // Driver Codepublic static void main (String[] args){ int a[] = { 1, 2, 5, 6, 2, 3, 5 }; int b[] = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; printUnion(a, 7, b, 9);}} // This code is contributed by avanitrachhadiya2155",
"e": 13882,
"s": 12962,
"text": null
},
{
"code": "# Python program for the above approachdef printUnion(a , n, b , m): mp = {} # Inserting array elements in mp for i in range(n): mp[a[i]] = i for i in range(m): mp[b[i]] = i print(\"The union set of both arrays is : \"); for key in mp.keys(): print(key,end=\" \") # Driver Codea = [ 1, 2, 5, 6, 2, 3, 5 ];b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5 ]; printUnion(a, 7, b, 9) # This code is contributed by shinjanpatra",
"e": 14340,
"s": 13882,
"text": null
},
{
"code": "// C# program for the above approach using System;using System.Collections.Generic; public class GFG{ static void printUnion(int[] a, int n, int[] b, int m){ Dictionary<int, int> mp = new Dictionary<int, int>(); // Inserting array elements in mp for(int i = 0; i < n; i++) { if(!mp.ContainsKey(a[i])) mp.Add(a[i], i); } for(int i = 0; i < m; i++) { if(!mp.ContainsKey(b[i])) mp.Add(b[i], i); } Console.WriteLine(\"The union set of both arrays is :\"); foreach(KeyValuePair<int,int> mapElement in mp) { Console.Write(mapElement.Key + \" \"); // mp will contain only distinct // elements from array a and b }} // Driver Codepublic static void Main(String[] args){ int []a = { 1, 2, 5, 6, 2, 3, 5 }; int []b = { 2, 4, 5, 6, 8, 9, 4, 6, 5 }; printUnion(a, 7, b, 9);}} // This code contributed by gauravrajput1",
"e": 15322,
"s": 14340,
"text": null
},
{
"code": "<script>// javascript program for the above approachfunction printUnion(a , n, b , m){ var mp = new Map(); // Inserting array elements in mp for(var i = 0; i < n; i++) { mp.set(a[i], i); } for(var i = 0; i < m; i++) { mp.set(b[i], i); } document.write(\"The union set of both arrays is :<br/>\"); for(var key of mp.keys()) { document.write(key + \" \"); }} // Driver Code var a = [ 1, 2, 5, 6, 2, 3, 5 ]; var b = [ 2, 4, 5, 6, 8, 9, 4, 6, 5 ]; printUnion(a, 7, b, 9); // This code is contributed by gauravrajput1</script>",
"e": 15923,
"s": 15322,
"text": null
},
{
"code": null,
"e": 15974,
"s": 15923,
"text": "The union set of both arrays is :\n1 2 3 4 5 6 8 9 "
},
{
"code": null,
"e": 16019,
"s": 15974,
"text": "The above method has time complexity O(m+n)."
},
{
"code": null,
"e": 16060,
"s": 16019,
"text": "*This method is suggested by Vinay Verma"
},
{
"code": null,
"e": 16078,
"s": 16060,
"text": "Method 3 (Naive) "
},
{
"code": null,
"e": 16086,
"s": 16078,
"text": "Union: "
},
{
"code": null,
"e": 16280,
"s": 16086,
"text": "Initialize union U as empty.Copy all elements of the first array to U.Do the following for every element x of the second array:If x is not present in the first array, then copy x to U.Return U."
},
{
"code": null,
"e": 16309,
"s": 16280,
"text": "Initialize union U as empty."
},
{
"code": null,
"e": 16352,
"s": 16309,
"text": "Copy all elements of the first array to U."
},
{
"code": null,
"e": 16467,
"s": 16352,
"text": "Do the following for every element x of the second array:If x is not present in the first array, then copy x to U."
},
{
"code": null,
"e": 16525,
"s": 16467,
"text": "If x is not present in the first array, then copy x to U."
},
{
"code": null,
"e": 16583,
"s": 16525,
"text": "If x is not present in the first array, then copy x to U."
},
{
"code": null,
"e": 16593,
"s": 16583,
"text": "Return U."
},
{
"code": null,
"e": 16608,
"s": 16593,
"text": "Intersection: "
},
{
"code": null,
"e": 16762,
"s": 16608,
"text": "Initialize intersection I as empty.Do the following for every element x of the first arrayIf x is present in the second array, then copy x to I.Return I."
},
{
"code": null,
"e": 16798,
"s": 16762,
"text": "Initialize intersection I as empty."
},
{
"code": null,
"e": 16908,
"s": 16798,
"text": "Do the following for every element x of the first arrayIf x is present in the second array, then copy x to I."
},
{
"code": null,
"e": 16963,
"s": 16908,
"text": "If x is present in the second array, then copy x to I."
},
{
"code": null,
"e": 17018,
"s": 16963,
"text": "If x is present in the second array, then copy x to I."
},
{
"code": null,
"e": 17028,
"s": 17018,
"text": "Return I."
},
{
"code": null,
"e": 17165,
"s": 17028,
"text": "The time complexity of this method is O(mn) for both operations. Here m and n are numbers of elements in arr1[] and arr2[] respectively."
},
{
"code": null,
"e": 17237,
"s": 17165,
"text": "However, above method works only for distinct elements in input arrays."
},
{
"code": null,
"e": 17261,
"s": 17237,
"text": "Method 4 (Use Sorting) "
},
{
"code": null,
"e": 17404,
"s": 17261,
"text": "Sort arr1[] and arr2[]. This step takes O(mLogm + nLogn) time.Use O(m + n) algorithms to find the union and intersection of two sorted arrays."
},
{
"code": null,
"e": 17467,
"s": 17404,
"text": "Sort arr1[] and arr2[]. This step takes O(mLogm + nLogn) time."
},
{
"code": null,
"e": 17548,
"s": 17467,
"text": "Use O(m + n) algorithms to find the union and intersection of two sorted arrays."
},
{
"code": null,
"e": 17612,
"s": 17548,
"text": "The overall time complexity of this method is O(mLogm + nLogn)."
},
{
"code": null,
"e": 17657,
"s": 17612,
"text": "Method 5 (Use Sorting and Searching) Union: "
},
{
"code": null,
"e": 17904,
"s": 17657,
"text": "Initialize union U as empty.Find smaller m and n and sort the smaller array.Copy the smaller array to U.For every element x of a larger array, do the followingBinary Search x in the smaller array. If, x is not present, then copy it to U.Return U."
},
{
"code": null,
"e": 17933,
"s": 17904,
"text": "Initialize union U as empty."
},
{
"code": null,
"e": 17982,
"s": 17933,
"text": "Find smaller m and n and sort the smaller array."
},
{
"code": null,
"e": 18011,
"s": 17982,
"text": "Copy the smaller array to U."
},
{
"code": null,
"e": 18145,
"s": 18011,
"text": "For every element x of a larger array, do the followingBinary Search x in the smaller array. If, x is not present, then copy it to U."
},
{
"code": null,
"e": 18224,
"s": 18145,
"text": "Binary Search x in the smaller array. If, x is not present, then copy it to U."
},
{
"code": null,
"e": 18303,
"s": 18224,
"text": "Binary Search x in the smaller array. If, x is not present, then copy it to U."
},
{
"code": null,
"e": 18313,
"s": 18303,
"text": "Return U."
},
{
"code": null,
"e": 18328,
"s": 18313,
"text": "Intersection: "
},
{
"code": null,
"e": 18552,
"s": 18328,
"text": "Initialize intersection I as empty.Find smaller of m and n and sort the smaller array.For every element x of a larger array, do the followingBinary Search x in the smaller array. If x is present, then copy it to I.Return I."
},
{
"code": null,
"e": 18588,
"s": 18552,
"text": "Initialize intersection I as empty."
},
{
"code": null,
"e": 18640,
"s": 18588,
"text": "Find smaller of m and n and sort the smaller array."
},
{
"code": null,
"e": 18769,
"s": 18640,
"text": "For every element x of a larger array, do the followingBinary Search x in the smaller array. If x is present, then copy it to I."
},
{
"code": null,
"e": 18843,
"s": 18769,
"text": "Binary Search x in the smaller array. If x is present, then copy it to I."
},
{
"code": null,
"e": 18917,
"s": 18843,
"text": "Binary Search x in the smaller array. If x is present, then copy it to I."
},
{
"code": null,
"e": 18927,
"s": 18917,
"text": "Return I."
},
{
"code": null,
"e": 19246,
"s": 18927,
"text": "Time complexity of this method is min(mLogm + nLogm, mLogn + nLogn) which can also be written as O((m+n)Logm, (m+n)Logn). This approach works much better than the previous approach when the difference between the sizes of two arrays is significant.Thanks to use_the_force for suggesting this method in a comment here. "
},
{
"code": null,
"e": 19366,
"s": 19246,
"text": "Below is the implementation of this method. However, this method also works only for distinct elements in input arrays."
},
{
"code": null,
"e": 19370,
"s": 19366,
"text": "C++"
},
{
"code": null,
"e": 19375,
"s": 19370,
"text": "Java"
},
{
"code": null,
"e": 19383,
"s": 19375,
"text": "Python3"
},
{
"code": null,
"e": 19386,
"s": 19383,
"text": "C#"
},
{
"code": null,
"e": 19390,
"s": 19386,
"text": "PHP"
},
{
"code": null,
"e": 19401,
"s": 19390,
"text": "Javascript"
},
{
"code": "// A C++ program to print union and intersection/// of two unsorted arrays#include <algorithm>#include <iostream>using namespace std; int binarySearch(int arr[], int l, int r, int x); // Prints union of arr1[0..m-1] and arr2[0..n-1]void printUnion(int arr1[], int arr2[], int m, int n){ // Before finding union, make sure arr1[0..m-1] // is smaller if (m > n) { int* tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print its elements (these // two steps can be swapped as order in output is not // important) sort(arr1, arr1 + m); for (int i = 0; i < m; i++) cout << arr1[i] << \" \"; // Search every element of bigger array in smaller array // and print the element if not found for (int i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) cout << arr2[i] << \" \";} // Prints intersection of arr1[0..m-1] and arr2[0..n-1]void printIntersection(int arr1[], int arr2[], int m, int n){ // Before finding intersection, make sure arr1[0..m-1] // is smaller if (m > n) { int* tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] sort(arr1, arr1 + m); // Search every element of bigger array in smaller // array and print the element if found for (int i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) cout << arr2[i] << \" \";} // A recursive binary search function. It returns// location of x in given array arr[l..r] is present,// otherwise -1int binarySearch(int arr[], int l, int r, int x){ if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only // be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right // subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in array return -1;} /* Driver program to test above function */int main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int m = sizeof(arr1) / sizeof(arr1[0]); int n = sizeof(arr2) / sizeof(arr2[0]); // Function call cout << \"Union of two arrays is n\"; printUnion(arr1, arr2, m, n); cout << \"nIntersection of two arrays is n\"; printIntersection(arr1, arr2, m, n); return 0;}",
"e": 22130,
"s": 19401,
"text": null
},
{
"code": "// A Java program to print union and intersection/// of two unsorted arraysimport java.util.Arrays; class UnionAndIntersection { // Prints union of arr1[0..m-1] and arr2[0..n-1] void printUnion(int arr1[], int arr2[], int m, int n) { // Before finding union, make sure arr1[0..m-1] // is smaller if (m > n) { int tempp[] = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print its elements // (these two steps can be swapped as order in // output is not important) Arrays.sort(arr1); for (int i = 0; i < m; i++) System.out.print(arr1[i] + \" \"); // Search every element of bigger array in smaller // array and print the element if not found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) System.out.print(arr2[i] + \" \"); } } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] void printIntersection(int arr1[], int arr2[], int m, int n) { // Before finding intersection, make sure // arr1[0..m-1] is smaller if (m > n) { int tempp[] = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] Arrays.sort(arr1); // Search every element of bigger array in smaller // array and print the element if found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) System.out.print(arr2[i] + \" \"); } } // A recursive binary search function. It returns // location of x in given array arr[l..r] is present, // otherwise -1 int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at the middle // itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can // only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right // subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in // array return -1; } // Driver code public static void main(String[] args) { UnionAndIntersection u_i = new UnionAndIntersection(); int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int m = arr1.length; int n = arr2.length; // Function call System.out.println(\"Union of two arrays is \"); u_i.printUnion(arr1, arr2, m, n); System.out.println(\"\"); System.out.println( \"Intersection of two arrays is \"); u_i.printIntersection(arr1, arr2, m, n); }}",
"e": 25322,
"s": 22130,
"text": null
},
{
"code": "# A Python3 program to print union and intersection# of two unsorted arrays # Prints union of arr1[0..m-1] and arr2[0..n-1] def printUnion(arr1, arr2, m, n): # Before finding union, make sure arr1[0..m-1] # is smaller if (m > n): tempp = arr1 arr1 = arr2 arr2 = tempp temp = m m = n n = temp # Now arr1[] is smaller # Sort the first array and print its elements (these two # steps can be swapped as order in output is not important) arr1.sort() for i in range(0, m): print(arr1[i], end=\" \") # Search every element of bigger array in smaller array # and print the element if not found for i in range(0, n): if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1): print(arr2[i], end=\" \") # Prints intersection of arr1[0..m-1] and arr2[0..n-1] def printIntersection(arr1, arr2, m, n): # Before finding intersection, make sure arr1[0..m-1] # is smaller if (m > n): tempp = arr1 arr1 = arr2 arr2 = tempp temp = m m = n n = temp # Now arr1[] is smaller # Sort smaller array arr1[0..m-1] arr1.sort() # Search every element of bigger array in smaller # array and print the element if found for i in range(0, n): if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1): print(arr2[i], end=\" \") # A recursive binary search function. It returns# location of x in given array arr[l..r] is present,# otherwise -1 def binarySearch(arr, l, r, x): if (r >= l): mid = int(l + (r - l)/2) # If the element is present at the middle itself if (arr[mid] == x): return mid # If element is smaller than mid, then it can only # be present in left subarray if (arr[mid] > x): return binarySearch(arr, l, mid - 1, x) # Else the element can only be present in right subarray return binarySearch(arr, mid + 1, r, x) # We reach here when element is not present in array return -1 # Driver codearr1 = [7, 1, 5, 2, 3, 6]arr2 = [3, 8, 6, 20, 7]m = len(arr1)n = len(arr2) # Function callprint(\"Union of two arrays is \")printUnion(arr1, arr2, m, n)print(\"\\nIntersection of two arrays is \")printIntersection(arr1, arr2, m, n) # This code is contributed by mits",
"e": 27627,
"s": 25322,
"text": null
},
{
"code": "// A C# program to print union and// intersection of two unsorted arraysusing System; class GFG { // Prints union of arr1[0..m-1] and arr2[0..n-1] static void printUnion(int[] arr1, int[] arr2, int m, int n) { // Before finding union, make // sure arr1[0..m-1] is smaller if (m > n) { int[] tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print // its elements (these two steps can // be swapped as order in output is // not important) Array.Sort(arr1); for (int i = 0; i < m; i++) Console.Write(arr1[i] + \" \"); // Search every element of bigger // array in smaller array and print // the element if not found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) Console.Write(arr2[i] + \" \"); } } // Prints intersection of arr1[0..m-1] // and arr2[0..n-1] static void printIntersection(int[] arr1, int[] arr2, int m, int n) { // Before finding intersection, // make sure arr1[0..m-1] is smaller if (m > n) { int[] tempp = arr1; arr1 = arr2; arr2 = tempp; int temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] Array.Sort(arr1); // Search every element of bigger array in // smaller array and print the element if found for (int i = 0; i < n; i++) { if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) Console.Write(arr2[i] + \" \"); } } // A recursive binary search function. // It returns location of x in given // array arr[l..r] is present, otherwise -1 static int binarySearch(int[] arr, int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; // If the element is present at // the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it // can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be // present in right subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is // not present in array return -1; } // Driver Code static public void Main() { int[] arr1 = { 7, 1, 5, 2, 3, 6 }; int[] arr2 = { 3, 8, 6, 20, 7 }; int m = arr1.Length; int n = arr2.Length; // Function call Console.WriteLine(\"Union of two arrays is \"); printUnion(arr1, arr2, m, n); Console.WriteLine(\"\"); Console.WriteLine(\"Intersection of two arrays is \"); printIntersection(arr1, arr2, m, n); }} // This code is contributed// by Sach_Code",
"e": 30791,
"s": 27627,
"text": null
},
{
"code": "<?php// A PHP program to print union and intersection/// of two unsorted arrays // Prints union of arr1[0..m-1] and arr2[0..n-1]function printUnion($arr1, $arr2, $m, $n){ // Before finding union, make sure arr1[0..m-1] // is smaller if ($m > $n) { $tempp = $arr1; $arr1 = $arr2; $arr2 = $tempp; $temp = $m; $m = $n; $n = $temp; } // Now arr1[] is smaller // Sort the first array and print its elements (these two // steps can be swapped as order in output is not important) sort($arr1); for ($i = 0; $i < $m; $i++) echo $arr1[$i].\" \"; // Search every element of bigger array in smaller array // and print the element if not found for ($i = 0; $i < $n; $i++) if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) == -1) echo $arr2[$i].\" \";} // Prints intersection of arr1[0..m-1] and arr2[0..n-1]function printIntersection($arr1, $arr2, $m, $n){ // Before finding intersection, make sure arr1[0..m-1] // is smaller if ($m > $n) { $tempp = $arr1; $arr1 = $arr2; $arr2 = $tempp; $temp = $m; $m = $n; $n = $temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] sort($arr1); // Search every element of bigger array in smaller // array and print the element if found for ($i = 0; $i < $n; $i++) if (binarySearch($arr1, 0, $m - 1, $arr2[$i]) != -1) echo $arr2[$i].\" \";} // A recursive binary search function. It returns// location of x in given array arr[l..r] is present,// otherwise -1function binarySearch($arr, $l, $r,$x){ if ($r >= $l) { $mid = (int)($l + ($r - $l)/2); // If the element is present at the middle itself if ($arr[$mid] == $x) return $mid; // If element is smaller than mid, then it can only // be present in left subarray if ($arr[$mid] > $x) return binarySearch($arr, $l, $mid - 1, $x); // Else the element can only be present in right subarray return binarySearch($arr, $mid + 1, $r, $x); } // We reach here when element is not present in array return -1;} /* Driver program to test above function */ $arr1 = array(7, 1, 5, 2, 3, 6); $arr2 = array(3, 8, 6, 20, 7); $m = count($arr1); $n = count($arr2); echo \"Union of two arrays is \\n\"; printUnion($arr1, $arr2, $m, $n); echo \"\\nIntersection of two arrays is \\n\"; printIntersection($arr1, $arr2, $m, $n); // This code is contributed by mits?>",
"e": 33319,
"s": 30791,
"text": null
},
{
"code": "<script> // A JavaScript program to// print union and intersection// of two unsorted arrays // A recursive binary search function. It returns// location of x in given array arr[l..r] is present,// otherwise -1function binarySearch(arr, l, r, x){ if (r >= l) { let mid = l + Math.floor((r - l) / 2); // If the element is present at the middle itself if (arr[mid] == x) return mid; // If element is smaller than mid, then it can only // be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); // Else the element can only be present in right // subarray return binarySearch(arr, mid + 1, r, x); } // We reach here when element is not present in array return -1;} // Prints union of arr1[0..m-1] and arr2[0..n-1]function printUnion(arr1, arr2, m, n){ // Before finding union, make sure arr1[0..m-1] // is smaller if (m > n) { let tempp = arr1; arr1 = arr2; arr2 = tempp; let temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort the first array and print its elements (these // two steps can be swapped as order in output is not // important) arr1.sort((a, b) => a - b); for (let i = 0; i < m; i++) document.write(arr1[i] + \" \"); // Search every element of bigger array in smaller array // and print the element if not found for (let i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) == -1) document.write(arr2[i] + \" \");} // Prints intersection of arr1[0..m-1] and arr2[0..n-1]function printIntersection(arr1, arr2, m, n){ // Before finding intersection, make sure arr1[0..m-1] // is smaller if (m > n) { let tempp = arr1; arr1 = arr2; arr2 = tempp; let temp = m; m = n; n = temp; } // Now arr1[] is smaller // Sort smaller array arr1[0..m-1] arr1.sort((a, b) => a - b); // Search every element of bigger array in smaller // array and print the element if found for (let i = 0; i < n; i++) if (binarySearch(arr1, 0, m - 1, arr2[i]) != -1) document.write(arr2[i] + \" \");} /* Driver program to test above function */ let arr1 = [ 7, 1, 5, 2, 3, 6 ]; let arr2 = [ 3, 8, 6, 20, 7 ]; let m = arr1.length; let n = arr2.length; // Function call document.write(\"Union of two arrays is <br>\"); printUnion(arr1, arr2, m, n); document.write(\"<br>Intersection of two arrays is<br>\"); printIntersection(arr1, arr2, m, n); // This code is contributed by Surbhi Tyagi.</script>",
"e": 35965,
"s": 33319,
"text": null
},
{
"code": null,
"e": 36045,
"s": 35965,
"text": "Union of two arrays is n3 6 7 8 20 1 5 2 nIntersection of two arrays is n7 3 6 "
},
{
"code": null,
"e": 36113,
"s": 36045,
"text": "Another Approach (When elements in the array may not be distinct) :"
},
{
"code": null,
"e": 36117,
"s": 36113,
"text": "C++"
},
{
"code": null,
"e": 36122,
"s": 36117,
"text": "Java"
},
{
"code": null,
"e": 36130,
"s": 36122,
"text": "Python3"
},
{
"code": null,
"e": 36133,
"s": 36130,
"text": "C#"
},
{
"code": null,
"e": 36137,
"s": 36133,
"text": "PHP"
},
{
"code": null,
"e": 36148,
"s": 36137,
"text": "Javascript"
},
{
"code": "// C++ code to find intersection when// elements may not be distinct#include <bits/stdc++.h> using namespace std; // Function to find intersectionvoid intersection(int a[], int b[], int n, int m){ int i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal cout << a[i] << \" \"; i++; j++; } }} // Driver Codeint main(){ int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 }; int b[] = { 3, 3, 5 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // sort sort(a, a + n); sort(b, b + m); // Function call intersection(a, b, n, m);}",
"e": 36917,
"s": 36148,
"text": null
},
{
"code": "// Java code to find intersection when// elements may not be distinct import java.io.*;import java.util.Arrays; class GFG { // Function to find intersection static void intersection(int a[], int b[], int n, int m) { int i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal System.out.print(a[i] + \" \"); i++; j++; } } } // Driver Code public static void main(String[] args) { int a[] = { 1, 3, 2, 3, 4, 5, 5, 6 }; int b[] = { 3, 3, 5 }; int n = a.length; int m = b.length; // sort Arrays.sort(a); Arrays.sort(b); // Function call intersection(a, b, n, m); }}",
"e": 37832,
"s": 36917,
"text": null
},
{
"code": "# Python 3 code to find intersection# when elements may not be distinct # Function to find intersection def intersection(a, b, n, m): i = 0 j = 0 while (i < n and j < m): if (a[i] > b[j]): j += 1 else: if (b[j] > a[i]): i += 1 else: # when both are equal print(a[i], end=\" \") i += 1 j += 1 # Driver Codeif __name__ == \"__main__\": a = [1, 3, 2, 3, 4, 5, 5, 6] b = [3, 3, 5] n = len(a) m = len(b) # sort a.sort() b.sort() # function call intersection(a, b, n, m) # This code is contributed by Ita_c",
"e": 38506,
"s": 37832,
"text": null
},
{
"code": "// C# code to find intersection when// elements may not be distinct using System; class GFG { // Function to find intersection static void intersection(int[] a, int[] b, int n, int m) { int i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal Console.Write(a[i] + \" \"); i++; j++; } } } // Driver Code public static void Main() { int[] a = { 1, 3, 2, 3, 4, 5, 5, 6 }; int[] b = { 3, 3, 5 }; int n = a.Length; int m = b.Length; // sort Array.Sort(a); Array.Sort(b); // Function call intersection(a, b, n, m); }}// this code is contributed by mukul singh",
"e": 39415,
"s": 38506,
"text": null
},
{
"code": "<?php// PHP code to find intersection when// elements may not be distinct // Function to find intersectionfunction intersection($a, $b, $n, $m){ $i = 0; $j = 0; while ($i < $n && $j < $m) { if ($a[$i] > $b[$j]) { $j++; } else if ($b[$j] > $a[$i]) { $i++; } else { // when both are equal echo($a[$i] . \" \"); $i++; $j++; } }} // Driver Code$a = array(1, 3, 2, 3, 4, 5, 5, 6);$b = array(3, 3, 5); $n = sizeof($a);$m = sizeof($b); // sortsort($a);sort($b); // Function callintersection($a, $b, $n, $m); // This code is contributed// by Mukul Singh?>",
"e": 40148,
"s": 39415,
"text": null
},
{
"code": "<script>// Javascript code to find intersection when// elements may not be distinct // Function to find intersection function intersection(a,b,n,m) { let i = 0, j = 0; while (i < n && j < m) { if (a[i] > b[j]) { j++; } else if (b[j] > a[i]) { i++; } else { // when both are equal document.write(a[i] + \" \"); i++; j++; } } } // Driver Code let a = [1, 3, 2, 3, 4, 5, 5, 6 ]; let b = [3, 3, 5 ] let n = a.length; let m = b.length; // sort a.sort(); b.sort(); // Function call intersection(a, b, n, m); // This code is contributed by rag2127</script>",
"e": 40985,
"s": 40148,
"text": null
},
{
"code": null,
"e": 40992,
"s": 40985,
"text": "3 3 5 "
},
{
"code": null,
"e": 41046,
"s": 40992,
"text": " Thanks, Sanny Kumar for suggesting the above method."
},
{
"code": null,
"e": 41176,
"s": 41046,
"text": "Method 6(Without using hashing or any predefined library like sets or maps and works even for both repeated and distant elements)"
},
{
"code": null,
"e": 41231,
"s": 41176,
"text": "First of all we sort both arrays and proceed as below:"
},
{
"code": null,
"e": 41237,
"s": 41231,
"text": "Union"
},
{
"code": null,
"e": 41555,
"s": 41237,
"text": "Iterate in while loop until any one array is finished.In each iteration we look for smaller in both arrays and we print it and increment its pointer only if it is not same as the last element printed in union.After we finish while we iterate the remaining of two array in the similar way as above and print the union."
},
{
"code": null,
"e": 41610,
"s": 41555,
"text": "Iterate in while loop until any one array is finished."
},
{
"code": null,
"e": 41766,
"s": 41610,
"text": "In each iteration we look for smaller in both arrays and we print it and increment its pointer only if it is not same as the last element printed in union."
},
{
"code": null,
"e": 41875,
"s": 41766,
"text": "After we finish while we iterate the remaining of two array in the similar way as above and print the union."
},
{
"code": null,
"e": 41888,
"s": 41875,
"text": "Intersection"
},
{
"code": null,
"e": 42275,
"s": 41888,
"text": "Iterate in while loop till any of the one array is finished.In each iteration we look for smaller of the two elements from both the array and increase its pointer because it will not be in other list, hence not part of intersection.For intersection,ff both the elements are equal we print it and increment both pointer only if it is not same as the last element printed in intersection."
},
{
"code": null,
"e": 42336,
"s": 42275,
"text": "Iterate in while loop till any of the one array is finished."
},
{
"code": null,
"e": 42509,
"s": 42336,
"text": "In each iteration we look for smaller of the two elements from both the array and increase its pointer because it will not be in other list, hence not part of intersection."
},
{
"code": null,
"e": 42664,
"s": 42509,
"text": "For intersection,ff both the elements are equal we print it and increment both pointer only if it is not same as the last element printed in intersection."
},
{
"code": null,
"e": 42668,
"s": 42664,
"text": "C++"
},
{
"code": "#include <bits/stdc++.h> using namespace std; // Function to find union void Union(int a[], int b[], int n, int m) { int *result=new int[n+m]; int index=0; int left=0,right=0; while(left<n && right<m){ if(a[left]<b[right]){ if(index!=0 && a[left]==result[index-1]){ left++; }else{ result[index]=a[left]; left++; index++; } }else{ if(index!=0 && b[right]==result[index-1]){ right++; }else{ result[index]=b[right]; right++; index++; } } } while(left<n){ if(index!=0 && a[left]==result[index-1]){ left++; }else{ result[index]=a[left]; left++; index++; } } while(right<m){ if(index!=0 && b[right]==result[index-1]){ right++; }else{ result[index]=b[right]; right++; index++; } } cout<<\"Union: \"; for(int k=0;k<index;k++) cout<<result[k]<<\" \"; cout<<endl; }; // Function to find intersectionvoid intersection(int a[], int b[], int n, int m) { int i=0,j=0,k=0; int *result=new int[n+m]; while(i<n && j<m){ if(a[i]<b[j]) i++; else if(a[i]>b[j]) j++; else{ if(k!=0 && a[i]==result[k-1]){ i++; j++; } else{ result[k]=a[i]; i++; j++; k++; } } } cout<<\"Intersection: \"; for(int x=0;x<k;x++) cout<<result[x]<<\" \"; cout<<endl; } // Driver Codeint main(){ int a[] = { 1, 3, 2, 3, 3, 4, 5, 5, 6 }; int b[] = { 3, 3, 5 }; int n = sizeof(a) / sizeof(a[0]); int m = sizeof(b) / sizeof(b[0]); // sort sort(a, a + n); sort(b, b + m); // Function call Union(a,b,n,m); intersection(a, b, n, m);}",
"e": 45058,
"s": 42668,
"text": null
},
{
"code": null,
"e": 45088,
"s": 45058,
"text": "Method 7 (Use Hashing) Union "
},
{
"code": null,
"e": 45264,
"s": 45088,
"text": "Initialize an empty hash set hs.Iterate through the first array and put every element of the first array in the set S.Repeat the process for the second array.Print the set hs."
},
{
"code": null,
"e": 45297,
"s": 45264,
"text": "Initialize an empty hash set hs."
},
{
"code": null,
"e": 45384,
"s": 45297,
"text": "Iterate through the first array and put every element of the first array in the set S."
},
{
"code": null,
"e": 45425,
"s": 45384,
"text": "Repeat the process for the second array."
},
{
"code": null,
"e": 45443,
"s": 45425,
"text": "Print the set hs."
},
{
"code": null,
"e": 45457,
"s": 45443,
"text": "Intersection "
},
{
"code": null,
"e": 45630,
"s": 45457,
"text": "Initialize an empty set hs.Iterate through the first array and put every element of the first array in the set S.For every element x of the second array, do the following :"
},
{
"code": null,
"e": 45658,
"s": 45630,
"text": "Initialize an empty set hs."
},
{
"code": null,
"e": 45745,
"s": 45658,
"text": "Iterate through the first array and put every element of the first array in the set S."
},
{
"code": null,
"e": 45805,
"s": 45745,
"text": "For every element x of the second array, do the following :"
},
{
"code": null,
"e": 45984,
"s": 45805,
"text": "Search x in the set hs. If x is present, then print it. Time complexity of this method is ?(m+n) under the assumption that hash table search and insert operations take ?(1) time."
},
{
"code": null,
"e": 46031,
"s": 45984,
"text": "Below is the implementation of the above idea:"
},
{
"code": null,
"e": 46035,
"s": 46031,
"text": "C++"
},
{
"code": null,
"e": 46040,
"s": 46035,
"text": "Java"
},
{
"code": null,
"e": 46047,
"s": 46040,
"text": "Python"
},
{
"code": null,
"e": 46050,
"s": 46047,
"text": "C#"
},
{
"code": null,
"e": 46061,
"s": 46050,
"text": "Javascript"
},
{
"code": "// CPP program to find union and intersection// using sets#include <bits/stdc++.h>using namespace std; // Prints union of arr1[0..n1-1] and arr2[0..n2-1]void printUnion(int arr1[], int arr2[], int n1, int n2){ set<int> hs; // Insert the elements of arr1[] to set hs for (int i = 0; i < n1; i++) hs.insert(arr1[i]); // Insert the elements of arr2[] to set hs for (int i = 0; i < n2; i++) hs.insert(arr2[i]); // Print the content of set hs for (auto it = hs.begin(); it != hs.end(); it++) cout << *it << \" \"; cout << endl;} // Prints intersection of arr1[0..n1-1] and// arr2[0..n2-1]void printIntersection(int arr1[], int arr2[], int n1, int n2){ set<int> hs; // Insert the elements of arr1[] to set S for (int i = 0; i < n1; i++) hs.insert(arr1[i]); for (int i = 0; i < n2; i++) // If element is present in set then // push it to vector V if (hs.find(arr2[i]) != hs.end()) cout << arr2[i] << \" \";} // Driver Programint main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Function call printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2); return 0;}",
"e": 47386,
"s": 46061,
"text": null
},
{
"code": "// Java program to find union and intersection// using Hashingimport java.util.HashSet; class Test { // Prints union of arr1[0..m-1] and arr2[0..n-1] static void printUnion(int arr1[], int arr2[]) { HashSet<Integer> hs = new HashSet<>(); for (int i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (int i = 0; i < arr2.length; i++) hs.add(arr2[i]); System.out.println(hs); } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] static void printIntersection(int arr1[], int arr2[]) { HashSet<Integer> hs = new HashSet<>(); HashSet<Integer> hs1 = new HashSet<>(); for (int i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (int i = 0; i < arr2.length; i++) if (hs.contains(arr2[i])) System.out.print(arr2[i] + \" \"); } // Driver code public static void main(String[] args) { int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; // Function call System.out.println(\"Union of two arrays is : \"); printUnion(arr1, arr2); System.out.println( \"Intersection of two arrays is : \"); printIntersection(arr1, arr2); }}",
"e": 48628,
"s": 47386,
"text": null
},
{
"code": "# Python program to find union and intersection# using sets def printUnion(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set hs for i in range(0, n1): hs.add(arr1[i]) # Insert the elements of arr1[] to set hs for i in range(0, n2): hs.add(arr2[i]) print(\"Union:\") for i in hs: print(i, end=\" \") print(\"\\n\") # Prints intersection of arr1[0..n1-1] and # arr2[0..n2-1] def printIntersection(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set S for i in range(0, n1): hs.add(arr1[i]) print(\"Intersection:\") for i in range(0, n2): # If element is present in set then # push it to vector V if arr2[i] in hs: print(arr2[i], end=\" \") # Driver Programarr1 = [7, 1, 5, 2, 3, 6]arr2 = [3, 8, 6, 20, 7]n1 = len(arr1)n2 = len(arr2) # Function callprintUnion(arr1, arr2, n1, n2)printIntersection(arr1, arr2, n1, n2) # This article is contributed by Kumar Suman .",
"e": 49631,
"s": 48628,
"text": null
},
{
"code": "// C# program to find union and intersection// using Hashingusing System;using System.Linq;using System.Collections.Generic; class GFG{ // Prints union of arr1[0..m-1] and arr2[0..n-1] static void printUnion(int []arr1, int []arr2) { HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < arr1.Length; i++) hs.Add(arr1[i]); for (int i = 0; i < arr2.Length; i++) hs.Add(arr2[i]); Console.WriteLine(string.Join(\", \", hs)); } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] static void printIntersection(int []arr1, int []arr2) { HashSet<int> hs = new HashSet<int>(); for (int i = 0; i < arr1.Length; i++) hs.Add(arr1[i]); for (int i = 0; i < arr2.Length; i++) if (hs.Contains(arr2[i])) Console.Write(arr2[i] + \" \"); } // Driver Code static void Main() { int []arr1 = {7, 1, 5, 2, 3, 6}; int []arr2 = {3, 8, 6, 20, 7}; Console.WriteLine(\"Union of two arrays is : \"); printUnion(arr1, arr2); Console.WriteLine(\"\\nIntersection of two arrays is : \"); printIntersection(arr1, arr2); }} // This code is contributed by mits",
"e": 50899,
"s": 49631,
"text": null
},
{
"code": "<script>// javascript program to find union and intersection// using Hashing // Prints union of arr1[0..m-1] and arr2[0..n-1] function printUnion(arr1 , arr2) { var hs = new Set(); for (i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (i = 0; i < arr2.length; i++) hs.add(arr2[i]); for(var k of hs) document.write(k+\" \"); } // Prints intersection of arr1[0..m-1] and arr2[0..n-1] function printIntersection(arr1 , arr2) { var hs = new Set(); var hs1 = new Set(); for (i = 0; i < arr1.length; i++) hs.add(arr1[i]); for (var i = 0; i < arr2.length; i++) if (hs.has(arr2[i])) document.write(arr2[i] + \" \"); } // Driver code var arr1 = [ 7, 1, 5, 2, 3, 6 ]; var arr2 = [ 3, 8, 6, 20, 7 ]; // Function call document.write(\"Union of two arrays is :<br/> \"); printUnion(arr1, arr2); document.write(\"<br/>Intersection of two arrays is : <br/>\"); printIntersection(arr1, arr2); // This code is contributed by gauravrajput1</script>",
"e": 52046,
"s": 50899,
"text": null
},
{
"code": null,
"e": 52071,
"s": 52046,
"text": "1 2 3 5 6 7 8 20 \n3 6 7 "
},
{
"code": null,
"e": 52240,
"s": 52071,
"text": "This method is contributed by Ankur Singh.The time complexity of this method is O(m+n) under the assumption that hash table search and insert operations take O(1) time."
},
{
"code": null,
"e": 52324,
"s": 52240,
"text": "Method 8 (Kind of hashing technique without using any predefined Java Collections) "
},
{
"code": null,
"e": 52565,
"s": 52324,
"text": "Initialize the array with a size of m+nFill first array value in a resultant array by doing hashing(to find appropriate position)Repeat for the second arrayWhile doing hashing if a collision happens increment the position in a recursive way"
},
{
"code": null,
"e": 52605,
"s": 52565,
"text": "Initialize the array with a size of m+n"
},
{
"code": null,
"e": 52696,
"s": 52605,
"text": "Fill first array value in a resultant array by doing hashing(to find appropriate position)"
},
{
"code": null,
"e": 52724,
"s": 52696,
"text": "Repeat for the second array"
},
{
"code": null,
"e": 52809,
"s": 52724,
"text": "While doing hashing if a collision happens increment the position in a recursive way"
},
{
"code": null,
"e": 52857,
"s": 52809,
"text": "Below is the implementation of the above code: "
},
{
"code": null,
"e": 52861,
"s": 52857,
"text": "C++"
},
{
"code": null,
"e": 52866,
"s": 52861,
"text": "Java"
},
{
"code": null,
"e": 52874,
"s": 52866,
"text": "Python3"
},
{
"code": null,
"e": 52877,
"s": 52874,
"text": "C#"
},
{
"code": null,
"e": 52888,
"s": 52877,
"text": "Javascript"
},
{
"code": "// CPP program to find union and intersection #include <bits/stdc++.h>using namespace std; // Prints union of arr1[0..n1-1] and arr2[0..n2-1]void printUnion(int v, int ans[], int zero){ int zero1 = 0; cout<<\"\\nUnion : \"; for (int i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; cout<<ans[i] << \",\"; }} void placeValue(int a[], int ans[], int i, int p, int v){ p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) cout<<a[i] << \",\"; else { // Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } }} void placeZeros(int v, int ans[], int zero){ if (zero == 2) { cout<<\"0\"<<endl; int d[] = { 0 }; placeValue(d, ans, 0, 0, v); } if (zero == 1) { int d[] = { 0 }; placeValue(d, ans, 0, 0, v); }} // Function to iterate arrayint iterateArray(int a[], int v, int ans[], int i){ if (a[i] != 0) { int p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0;} // Prints intersection of arr1[0..n1-1] and// arr2[0..n2-1]void findPosition(int a[], int b[], int n1, int n2){ int v = (n1+n2); int ans[v]; for(int i=0;i<v;i++) { ans[i]=0; } int zero1 = 0; int zero2 = 0; cout<<\"Intersection : \"; // Iterate first array for (int i = 0; i < n1; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (int j = 0; j < n2; j++) zero2 = iterateArray(b, v, ans, j); int zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero);} // Driver Programint main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); // Function call findPosition(arr1, arr2, n1, n2); return 0;} // This code is contributed by Aarti_Rathi",
"e": 55014,
"s": 52888,
"text": null
},
{
"code": "// Java program to find union and intersection// using similar Hashing Technique// without using any predefined Java Collections// Time Complexity best case & avg case = O(m+n)// Worst case = O(nlogn) // package com.arrays.math; public class UnsortedIntersectionUnion { // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1] public void findPosition(int a[], int b[]) { int v = (a.length + b.length); int ans[] = new int[v]; int zero1 = 0; int zero2 = 0; System.out.print(\"Intersection : \"); // Iterate first array for (int i = 0; i < a.length; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (int j = 0; j < b.length; j++) zero2 = iterateArray(b, v, ans, j); int zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); } // Prints union of arr1[0..n1-1] and arr2[0..n2-1] private void printUnion(int v, int[] ans, int zero) { int zero1 = 0; System.out.print(\"\\nUnion : \"); for (int i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; System.out.print(ans[i] + \",\"); } } private void placeZeros(int v, int[] ans, int zero) { if (zero == 2) { System.out.println(\"0\"); int d[] = { 0 }; placeValue(d, ans, 0, 0, v); } if (zero == 1) { int d[] = { 0 }; placeValue(d, ans, 0, 0, v); } } // Function to iterate array private int iterateArray(int[] a, int v, int[] ans, int i) { if (a[i] != 0) { int p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0; } private void placeValue(int[] a, int[] ans, int i, int p, int v) { p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) System.out.print(a[i] + \",\"); else { // Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } } } // Driver code public static void main(String args[]) { int a[] = { 7, 1, 5, 2, 3, 6 }; int b[] = { 3, 8, 6, 20, 7 }; // Function call UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion(); uiu.findPosition(a, b); }}// This code is contributed by Mohanakrishnan S.",
"e": 57745,
"s": 55014,
"text": null
},
{
"code": "# Python3 program to find union and intersection# using similar Hashing Technique# without using any predefined Java Collections# Time Complexity best case & avg case = O(m+n)# Worst case = O(nlogn) # Prints intersection of arr1[0..n1-1] and# arr2[0..n2-1]def findPosition(a, b): v = len(a) + len(b); ans = [0]*v; zero1 = zero2 = 0; print(\"Intersection :\",end=\" \"); # Iterate first array for i in range(len(a)): zero1 = iterateArray(a, v, ans, i); # Iterate second array for j in range(len(b)): zero2 = iterateArray(b, v, ans, j); zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); # Prints union of arr1[0..n1-1] and arr2[0..n2-1]def printUnion(v, ans,zero): zero1 = 0; print(\"\\nUnion :\",end=\" \"); for i in range(v): if ((zero == 0 and ans[i] == 0) or (ans[i] == 0 and zero1 > 0)): continue; if (ans[i] == 0): zero1+=1; print(ans[i],end=\",\"); def placeZeros(v, ans, zero): if (zero == 2): print(\"0\"); d = [0]; placeValue(d, ans, 0, 0, v); if (zero == 1): d=[0]; placeValue(d, ans, 0, 0, v); # Function to iterate arraydef iterateArray(a,v,ans,i): if (a[i] != 0): p = a[i] % v; placeValue(a, ans, i, p, v); else: return 1; return 0; def placeValue(a,ans,i,p,v): p = p % v; if (ans[p] == 0): ans[p] = a[i]; else: if (ans[p] == a[i]): print(a[i],end=\",\"); else: # Hashing collision happened increment # position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); # Driver codea = [ 7, 1, 5, 2, 3, 6 ];b = [ 3, 8, 6, 20, 7 ];findPosition(a, b); # This code is contributed by mits",
"e": 59547,
"s": 57745,
"text": null
},
{
"code": "// C# program to find union and intersection// using similar Hashing Technique// without using any predefined Java Collections// Time Complexity best case & avg case = O(m+n)// Worst case = O(nlogn) //package com.arrays.math;using System;class UnsortedIntersectionUnion{ // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1] public void findPosition(int []a, int []b) { int v = (a.Length + b.Length); int []ans = new int[v]; int zero1 = 0; int zero2 = 0; Console.Write(\"Intersection : \"); // Iterate first array for (int i = 0; i < a.Length; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (int j = 0; j < b.Length; j++) zero2 = iterateArray(b, v, ans, j); int zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); } // Prints union of arr1[0..n1-1] // and arr2[0..n2-1] private void printUnion(int v, int[] ans, int zero) { int zero1 = 0; Console.Write(\"\\nUnion : \"); for (int i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; Console.Write(ans[i] + \",\"); } } private void placeZeros(int v, int[] ans, int zero) { if (zero == 2) { Console.WriteLine(\"0\"); int []d = { 0 }; placeValue(d, ans, 0, 0, v); } if (zero == 1) { int []d = { 0 }; placeValue(d, ans, 0, 0, v); } } // Function to iterate array private int iterateArray(int[] a, int v, int[] ans, int i) { if (a[i] != 0) { int p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0; } private void placeValue(int[] a, int[] ans, int i, int p, int v) { p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) Console.Write(a[i] + \",\"); else { //Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } } } // Driver code public static void Main() { int []a = { 7, 1, 5, 2, 3, 6 }; int []b = { 3, 8, 6, 20, 7 }; UnsortedIntersectionUnion uiu = new UnsortedIntersectionUnion(); uiu.findPosition(a, b); }} // This code is contributed by PrinciRaj1992",
"e": 62297,
"s": 59547,
"text": null
},
{
"code": "<script>// javascript program to find union and intersection// using similar Hashing Technique// without using any predefined javascript Collections// Time Complexity best case & avg case = O(m+n)// Worst case = O(nlogn) // package com.arrays.math; // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1] function findPosition(a , b) { var v = (a.length + b.length); var ans = Array(v).fill(0); var zero1 = 0; var zero2 = 0; document.write(\"Intersection : \"); // Iterate first array for (var i = 0; i < a.length; i++) zero1 = iterateArray(a, v, ans, i); // Iterate second array for (var j = 0; j < b.length; j++) zero2 = iterateArray(b, v, ans, j); var zero = zero1 + zero2; placeZeros(v, ans, zero); printUnion(v, ans, zero); } // Prints union of arr1[0..n1-1] and arr2[0..n2-1] function printUnion(v, ans , zero) { var zero1 = 0; document.write(\"<br/>Union : \"); for (i = 0; i < v; i++) { if ((zero == 0 && ans[i] == 0) || (ans[i] == 0 && zero1 > 0)) continue; if (ans[i] == 0) zero1++; document.write(ans[i] + \",\"); } } function placeZeros(v, ans , zero) { if (zero == 2) { document.write(\"0\"); var d = [ 0 ]; placeValue(d, ans, 0, 0, v); } if (zero == 1) { var d = [ 0 ]; placeValue(d, ans, 0, 0, v); } } // Function to iterate array function iterateArray(a , v, ans , i) { if (a[i] != 0) { var p = a[i] % v; placeValue(a, ans, i, p, v); } else return 1; return 0; } function placeValue(a, ans , i , p , v) { p = p % v; if (ans[p] == 0) ans[p] = a[i]; else { if (ans[p] == a[i]) document.write(a[i] + \",\"); else { // Hashing collision happened increment // position and do recursive call p = p + 1; placeValue(a, ans, i, p, v); } } } // Driver code var a = [ 7, 1, 5, 2, 3, 6 ]; var b = [ 3, 8, 6, 20, 7 ]; // Function call findPosition(a, b); // This code is contributed by gauravrajput1</script>",
"e": 64679,
"s": 62297,
"text": null
},
{
"code": null,
"e": 64727,
"s": 64679,
"text": "Intersection : 3,6,7,\nUnion : 1,2,3,5,6,7,8,20,"
},
{
"code": null,
"e": 64731,
"s": 64727,
"text": "C++"
},
{
"code": null,
"e": 64736,
"s": 64731,
"text": "Java"
},
{
"code": null,
"e": 64744,
"s": 64736,
"text": "Python3"
},
{
"code": null,
"e": 64747,
"s": 64744,
"text": "C#"
},
{
"code": "// C++ program to find union and intersection// using sets #include <bits/stdc++.h>using namespace std; void printUnion(int arr1[], int arr2[], int n1, int n2){ // Defining set container s set<int> s; // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.insert(arr1[i]); } // Insert the elements of arr2[] to set s for (int i = 0; i < n2; i++) { s.insert(arr2[i]); } cout << \"Union:\" << endl; for (auto itr = s.begin(); itr != s.end(); itr++) // s will contain only distinct // elements from array a and b cout << *itr<< \" \"; cout <<endl; // Prints intersection of arr1[0..n1-1] and // arr2[0..n2-1]} void printIntersection(int arr1[], int arr2[], int n1, int n2){ // Defining set container s set<int> s; // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.insert(arr1[i]); } cout << \"Intersection:\" << endl; for (int i = 0; i < n2; i++) { // If element is present in set then if(s.count(arr2[i])) { cout<<arr2[i]<<\" \"; } } cout <<endl;} // Driver Codeint main(){ int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = sizeof(arr1) / sizeof(arr1[0]); int n2 = sizeof(arr2) / sizeof(arr2[0]); printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2);} // This code is contributed by Aarti_Rathi",
"e": 66253,
"s": 64747,
"text": null
},
{
"code": "// Java program to find union and intersection// using sets import java.util.*; public class GFG { static void printUnion(int arr1[], int arr2[], int n1, int n2) { // Defining set container s Set<Integer> s = new HashSet<Integer>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.add(arr1[i]); } // Insert the elements of arr2[] to set s for (int i = 0; i < n2; i++) { s.add(arr2[i]); } System.out.println(\"Union\"); for (int itr : s) // s will contain only distinct // elements from array a and b System.out.print(itr + \" \"); System.out.println(); } static void printIntersection(int arr1[], int arr2[], int n1, int n2) { // Defining set container s Set<Integer> s = new HashSet<Integer>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.add(arr1[i]); } System.out.println(\"Intersection\"); for (int i = 0; i < n2; i++) { // If element is present in set then if (s.contains(arr2[i])) { System.out.print(arr2[i] + \" \"); } } System.out.println(); } // Driver code public static void main(String args[]) { int arr1[] = { 7, 1, 5, 2, 3, 6 }; int arr2[] = { 3, 8, 6, 20, 7 }; int n1 = arr1.length; int n2 = arr2.length; // Function call printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2); }}// This code is contributed by Aarti_Rathi",
"e": 67769,
"s": 66253,
"text": null
},
{
"code": "# Python program to find union and intersection# using sets def printUnion(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set hs for i in range(0, n1): hs.add(arr1[i]) # Insert the elements of arr1[] to set hs for i in range(0, n2): hs.add(arr2[i]) print(\"Union:\") for i in hs: print(i, end=\" \") print(\"\\n\") # Prints intersection of arr1[0..n1-1] and # arr2[0..n2-1] def printIntersection(arr1, arr2, n1, n2): hs = set() # Insert the elements of arr1[] to set S for i in range(0, n1): hs.add(arr1[i]) print(\"Intersection:\") for i in range(0, n2): # If element is present in set then # push it to vector V if arr2[i] in hs: print(arr2[i], end=\" \") # Driver Programarr1 = [7, 1, 5, 2, 3, 6]arr2 = [3, 8, 6, 20, 7]n1 = len(arr1)n2 = len(arr2) # Function callprintUnion(arr1, arr2, n1, n2)printIntersection(arr1, arr2, n1, n2) # This code is contributed by Kumar Suman .",
"e": 68774,
"s": 67769,
"text": null
},
{
"code": "// C# program to find union and intersection// using sets using System;using System.Collections.Generic; public class GFG { static void printUnion(int[] arr1, int[] arr2, int n1, int n2) { // Defining set container s SortedSet<int> s = new SortedSet<int>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.Add(arr1[i]); } // Insert the elements of arr2[] to set s for (int i = 0; i < n2; i++) { s.Add(arr2[i]); } Console.WriteLine(\"Union\"); foreach(var itr in s) // s will contain only distinct // elements from array a and b Console.Write(itr + \" \"); Console.WriteLine(); } static void printIntersection(int[] arr1, int[] arr2, int n1, int n2) { // Defining set container s SortedSet<int> s = new SortedSet<int>(); // Insert the elements of arr1[] to set s for (int i = 0; i < n1; i++) { s.Add(arr1[i]); } Console.WriteLine(\"Intersection\"); for (int i = 0; i < n2; i++) { // If element is present in set then if (s.Contains(arr2[i])) { Console.Write(arr2[i] + \" \"); } } Console.WriteLine(); } // Driver code public static void Main(string[] args) { int[] arr1 = { 7, 1, 5, 2, 3, 6 }; int[] arr2 = { 3, 8, 6, 20, 7 }; int n1 = arr1.Length; int n2 = arr2.Length; // Function call printUnion(arr1, arr2, n1, n2); printIntersection(arr1, arr2, n1, n2); }} // This code is contributed by phasing17",
"e": 70502,
"s": 68774,
"text": null
},
{
"code": null,
"e": 70549,
"s": 70502,
"text": "Union:\n1 2 3 5 6 7 8 20 \n\nIntersection:\n3 6 7 "
},
{
"code": null,
"e": 70640,
"s": 70549,
"text": "See the following post for sorted arrays. Find Union and Intersection of two sorted arrays"
},
{
"code": null,
"e": 70650,
"s": 70640,
"text": "Sach_Code"
},
{
"code": null,
"e": 70660,
"s": 70650,
"text": "Code_Mech"
},
{
"code": null,
"e": 70666,
"s": 70660,
"text": "ukasp"
},
{
"code": null,
"e": 70679,
"s": 70666,
"text": "smkrishnan22"
},
{
"code": null,
"e": 70693,
"s": 70679,
"text": "princiraj1992"
},
{
"code": null,
"e": 70706,
"s": 70693,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 70719,
"s": 70706,
"text": "Kirti_Mangal"
},
{
"code": null,
"e": 70728,
"s": 70719,
"text": "ks120198"
},
{
"code": null,
"e": 70740,
"s": 70728,
"text": "meemurumkar"
},
{
"code": null,
"e": 70752,
"s": 70740,
"text": "sudheersahu"
},
{
"code": null,
"e": 70767,
"s": 70752,
"text": "vinayverma8948"
},
{
"code": null,
"e": 70788,
"s": 70767,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 70796,
"s": 70788,
"text": "rag2127"
},
{
"code": null,
"e": 70811,
"s": 70796,
"text": "anirbanchand54"
},
{
"code": null,
"e": 70825,
"s": 70811,
"text": "surbhityagi15"
},
{
"code": null,
"e": 70842,
"s": 70825,
"text": "arorakashish0911"
},
{
"code": null,
"e": 70856,
"s": 70842,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 70866,
"s": 70856,
"text": "19bcs1298"
},
{
"code": null,
"e": 70877,
"s": 70866,
"text": "imposter22"
},
{
"code": null,
"e": 70893,
"s": 70877,
"text": "simranarora5sos"
},
{
"code": null,
"e": 70907,
"s": 70893,
"text": "GauravRajput1"
},
{
"code": null,
"e": 70919,
"s": 70907,
"text": "umadevi9616"
},
{
"code": null,
"e": 70929,
"s": 70919,
"text": "kk9826225"
},
{
"code": null,
"e": 70939,
"s": 70929,
"text": "kiranu941"
},
{
"code": null,
"e": 70953,
"s": 70939,
"text": "parthmalhotra"
},
{
"code": null,
"e": 70966,
"s": 70953,
"text": "shinjanpatra"
},
{
"code": null,
"e": 70976,
"s": 70966,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 70991,
"s": 70976,
"text": "sagartomar9927"
},
{
"code": null,
"e": 71005,
"s": 70991,
"text": "_shinchancode"
},
{
"code": null,
"e": 71022,
"s": 71005,
"text": "codewithshinchan"
},
{
"code": null,
"e": 71030,
"s": 71022,
"text": "adi1212"
},
{
"code": null,
"e": 71046,
"s": 71030,
"text": "sachinvinod1904"
},
{
"code": null,
"e": 71060,
"s": 71046,
"text": "rajrajgupta18"
},
{
"code": null,
"e": 71067,
"s": 71060,
"text": "Amazon"
},
{
"code": null,
"e": 71077,
"s": 71067,
"text": "Rockstand"
},
{
"code": null,
"e": 71084,
"s": 71077,
"text": "Arrays"
},
{
"code": null,
"e": 71097,
"s": 71084,
"text": "Mathematical"
},
{
"code": null,
"e": 71104,
"s": 71097,
"text": "Amazon"
},
{
"code": null,
"e": 71114,
"s": 71104,
"text": "Rockstand"
},
{
"code": null,
"e": 71121,
"s": 71114,
"text": "Arrays"
},
{
"code": null,
"e": 71134,
"s": 71121,
"text": "Mathematical"
},
{
"code": null,
"e": 71232,
"s": 71134,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 71300,
"s": 71232,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 71344,
"s": 71300,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 71376,
"s": 71344,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 71424,
"s": 71376,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 71438,
"s": 71424,
"text": "Linear Search"
},
{
"code": null,
"e": 71468,
"s": 71438,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 71511,
"s": 71468,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 71571,
"s": 71511,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 71586,
"s": 71571,
"text": "C++ Data Types"
}
] |
Kotlin Variables | 09 May, 2019
In Kotlin, every variable should be declared before it’s used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location.
In case of local variables, the type of variable can be inferred from the initialized value.
var rollno = 55
var name = "Praveen"
println(rollno)
println(name)
Above we have the local variable rollno whose value is 55 and it’s type is Integer because the literal type is Int and another variable is name whose type is String.
In Kotlin, variables are declared using two types –
Immutable using val keywordMutable using var keyword
Immutable using val keyword
Mutable using var keyword
Immutable is also called read-only variables. Hence, we can not change the value of the variable declared using val keyword.
val myName = "Gaurav"
myName = "Praveen" // compile time error
// It gives error Kotlin Val cannot be reassigned
Note: Immutable variable is not a constant because it can be initialized with the value of a variable. It means the value of immutable variable doesn’t need to be known at compile-time, and if it is declared inside a construct that is called repeatedly, it can take on a different value on each function call.
var myBirthDate = "02/12/1993"
val myNewBirthDate = myBirthDate
println(myNewBirthDate)
In Mutable variable we can change the value of the variable.
var myAge = 25
myAge = 26 // compiles successfully
println("My new Age is ${myAge}")
Output:
My new Age is 26
Scope of a variable –A variable exists only inside the block of code( {.............} ) where it has been declared. You can not access the variable outside the loop. Same variable can be declared inside the nested loop – so if a function contains an argument x and we declare a new variable x inside the same loop, then x inside the loop is different then the argument.
Naming Convention –Every variable should be named using lowerCamelCase.
val myBirthDate = "02/12/1994"
Kotlin
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Android RecyclerView in Kotlin
How to Add Views Dynamically and Store Data in Arraylist in Android?
Broadcast Receiver in Android With Example
Content Providers in Android with Example
Retrofit with Kotlin Coroutine in Android
Kotlin constructor
Kotlin Setters and Getters
How to Add and Customize Back Button of Action Bar in Android?
How to Communicate Between Fragments in Android?
Suspend Function In Kotlin Coroutines | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 May, 2019"
},
{
"code": null,
"e": 310,
"s": 52,
"text": "In Kotlin, every variable should be declared before it’s used. Without declaring a variable, an attempt to use the variable gives a syntax error. Declaration of the variable type also decides the kind of data you are allowed to store in the memory location."
},
{
"code": null,
"e": 403,
"s": 310,
"text": "In case of local variables, the type of variable can be inferred from the initialized value."
},
{
"code": null,
"e": 471,
"s": 403,
"text": "var rollno = 55\nvar name = \"Praveen\"\nprintln(rollno)\nprintln(name)\n"
},
{
"code": null,
"e": 637,
"s": 471,
"text": "Above we have the local variable rollno whose value is 55 and it’s type is Integer because the literal type is Int and another variable is name whose type is String."
},
{
"code": null,
"e": 689,
"s": 637,
"text": "In Kotlin, variables are declared using two types –"
},
{
"code": null,
"e": 742,
"s": 689,
"text": "Immutable using val keywordMutable using var keyword"
},
{
"code": null,
"e": 770,
"s": 742,
"text": "Immutable using val keyword"
},
{
"code": null,
"e": 796,
"s": 770,
"text": "Mutable using var keyword"
},
{
"code": null,
"e": 921,
"s": 796,
"text": "Immutable is also called read-only variables. Hence, we can not change the value of the variable declared using val keyword."
},
{
"code": null,
"e": 1039,
"s": 921,
"text": "val myName = \"Gaurav\"\nmyName = \"Praveen\" // compile time error\n\n// It gives error Kotlin Val cannot be reassigned\n"
},
{
"code": null,
"e": 1349,
"s": 1039,
"text": "Note: Immutable variable is not a constant because it can be initialized with the value of a variable. It means the value of immutable variable doesn’t need to be known at compile-time, and if it is declared inside a construct that is called repeatedly, it can take on a different value on each function call."
},
{
"code": null,
"e": 1438,
"s": 1349,
"text": "var myBirthDate = \"02/12/1993\"\nval myNewBirthDate = myBirthDate\nprintln(myNewBirthDate)\n"
},
{
"code": null,
"e": 1499,
"s": 1438,
"text": "In Mutable variable we can change the value of the variable."
},
{
"code": null,
"e": 1596,
"s": 1499,
"text": "var myAge = 25\nmyAge = 26 // compiles successfully\nprintln(\"My new Age is ${myAge}\")\n"
},
{
"code": null,
"e": 1604,
"s": 1596,
"text": "Output:"
},
{
"code": null,
"e": 1621,
"s": 1604,
"text": "My new Age is 26"
},
{
"code": null,
"e": 1992,
"s": 1621,
"text": " Scope of a variable –A variable exists only inside the block of code( {.............} ) where it has been declared. You can not access the variable outside the loop. Same variable can be declared inside the nested loop – so if a function contains an argument x and we declare a new variable x inside the same loop, then x inside the loop is different then the argument."
},
{
"code": null,
"e": 2064,
"s": 1992,
"text": "Naming Convention –Every variable should be named using lowerCamelCase."
},
{
"code": null,
"e": 2096,
"s": 2064,
"text": "val myBirthDate = \"02/12/1994\"\n"
},
{
"code": null,
"e": 2103,
"s": 2096,
"text": "Kotlin"
},
{
"code": null,
"e": 2201,
"s": 2103,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2232,
"s": 2201,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 2301,
"s": 2232,
"text": "How to Add Views Dynamically and Store Data in Arraylist in Android?"
},
{
"code": null,
"e": 2344,
"s": 2301,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 2386,
"s": 2344,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 2428,
"s": 2386,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 2447,
"s": 2428,
"text": "Kotlin constructor"
},
{
"code": null,
"e": 2474,
"s": 2447,
"text": "Kotlin Setters and Getters"
},
{
"code": null,
"e": 2537,
"s": 2474,
"text": "How to Add and Customize Back Button of Action Bar in Android?"
},
{
"code": null,
"e": 2586,
"s": 2537,
"text": "How to Communicate Between Fragments in Android?"
}
] |
How to get the text without HTML element using JavaScript ? | 27 Apr, 2020
Given an HTML document containing some elements and the task is to get the text inside an HTML element using JavaScript. There are two methods to get the text without HTML element which are listed below:
Using innerText propertyUsing textContent property
Using innerText property
Using textContent property
Using innerText property: We can use innerText property to get the text from HTML element.
Example:
<!DOCTYPE html> <html> <head> <title> Get the text inside HTML element using JavaScript </title> </head> <body> <div class="main"> Welcome to GeeksforGeeks </div> <script> const div = document.querySelector('.main'); alert(div.innerText); </script></body> </html>
Output:
Using textContent property: We can also use textContent property to get the text from HTML element.
Example:
<!DOCTYPE html> <html> <head> <title> Get the text inside HTML element using JavaScript </title> </head> <body> <div class="main"> Welcome to GeeksforGeeks </div> <script> const div = document.querySelector('.main'); alert(div.textContent); </script></body> </html>
Output:
Difference between innerText and textContent:
The innerText property returns only human-readable text while the textContent property returns all the text including <script> and <style> tag.The innerText property take care of styling of elements and did not return any hidden elements while textContent property returns all the elements including the hidden ones.The innerText property is defined only for HTMLElement objects, whereas textContent property is defined for all Node objects.
The innerText property returns only human-readable text while the textContent property returns all the text including <script> and <style> tag.
The innerText property take care of styling of elements and did not return any hidden elements while textContent property returns all the elements including the hidden ones.
The innerText property is defined only for HTMLElement objects, whereas textContent property is defined for all Node objects.
HTML-Misc
JavaScript-Misc
Picked
HTML
JavaScript
Web Technologies
Web technologies Questions
Write From Home
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n27 Apr, 2020"
},
{
"code": null,
"e": 232,
"s": 28,
"text": "Given an HTML document containing some elements and the task is to get the text inside an HTML element using JavaScript. There are two methods to get the text without HTML element which are listed below:"
},
{
"code": null,
"e": 283,
"s": 232,
"text": "Using innerText propertyUsing textContent property"
},
{
"code": null,
"e": 308,
"s": 283,
"text": "Using innerText property"
},
{
"code": null,
"e": 335,
"s": 308,
"text": "Using textContent property"
},
{
"code": null,
"e": 426,
"s": 335,
"text": "Using innerText property: We can use innerText property to get the text from HTML element."
},
{
"code": null,
"e": 435,
"s": 426,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Get the text inside HTML element using JavaScript </title> </head> <body> <div class=\"main\"> Welcome to GeeksforGeeks </div> <script> const div = document.querySelector('.main'); alert(div.innerText); </script></body> </html>",
"e": 762,
"s": 435,
"text": null
},
{
"code": null,
"e": 770,
"s": 762,
"text": "Output:"
},
{
"code": null,
"e": 870,
"s": 770,
"text": "Using textContent property: We can also use textContent property to get the text from HTML element."
},
{
"code": null,
"e": 879,
"s": 870,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title> Get the text inside HTML element using JavaScript </title> </head> <body> <div class=\"main\"> Welcome to GeeksforGeeks </div> <script> const div = document.querySelector('.main'); alert(div.textContent); </script></body> </html>",
"e": 1210,
"s": 879,
"text": null
},
{
"code": null,
"e": 1218,
"s": 1210,
"text": "Output:"
},
{
"code": null,
"e": 1264,
"s": 1218,
"text": "Difference between innerText and textContent:"
},
{
"code": null,
"e": 1706,
"s": 1264,
"text": "The innerText property returns only human-readable text while the textContent property returns all the text including <script> and <style> tag.The innerText property take care of styling of elements and did not return any hidden elements while textContent property returns all the elements including the hidden ones.The innerText property is defined only for HTMLElement objects, whereas textContent property is defined for all Node objects."
},
{
"code": null,
"e": 1850,
"s": 1706,
"text": "The innerText property returns only human-readable text while the textContent property returns all the text including <script> and <style> tag."
},
{
"code": null,
"e": 2024,
"s": 1850,
"text": "The innerText property take care of styling of elements and did not return any hidden elements while textContent property returns all the elements including the hidden ones."
},
{
"code": null,
"e": 2150,
"s": 2024,
"text": "The innerText property is defined only for HTMLElement objects, whereas textContent property is defined for all Node objects."
},
{
"code": null,
"e": 2160,
"s": 2150,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2176,
"s": 2160,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2183,
"s": 2176,
"text": "Picked"
},
{
"code": null,
"e": 2188,
"s": 2183,
"text": "HTML"
},
{
"code": null,
"e": 2199,
"s": 2188,
"text": "JavaScript"
},
{
"code": null,
"e": 2216,
"s": 2199,
"text": "Web Technologies"
},
{
"code": null,
"e": 2243,
"s": 2216,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2259,
"s": 2243,
"text": "Write From Home"
},
{
"code": null,
"e": 2264,
"s": 2259,
"text": "HTML"
}
] |
Map.delete() In JavaScript | 22 Nov, 2021
What is a map in JavaScript?
Map is a data structure in JavaScript which allows storing of [key, value] pairs where any value can be either used as a key or value.
The keys and values in the map collection may be of any type and if a value is added to the map collection using a key which already exists in the collection, then the new value replaces the old value.
The iteration of elements in a map object is done in the insertion order and a “for...” loop returns an array of all [key, value] pairs for each iteration.
Differences between Objects and Maps in JavaScriptBoth of these data structures are similar in many ways such as both store values using keys, allow retrieval of those values using keys, deletion of keys and verify whether a key holds any value or not. However, there are quite significant differences between Objects and Maps in JavaScript which make the usage of maps a better and more preferable option in many cases.
The keys used in maps can be any type of values such as functions, objects etc whereas the keys in objects are limited to symbols and strings.
The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually.
A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterative data type and can be directly iterated whereas iterating an object requires obtaining its keys in a specific manner.
Map.delete() Method in JavaScriptThe Map.delete() method in JavaScript is used to delete the specified element among all the elements which are present in the map.
The Map.delete() method takes the key which needs to be removed from the map, thus removes the element associated with that key and returns true. If the key is not present then it returns false.
Applications:
Map.delete() is used to delete an element associated with the key among all the elements present in the map.
Syntax:
my_map.delete(key)
Parameters Used:
key: The element associated with this key is to be removed from the map
Return value:
The Map.delete() method returns true, if the key is present whose associated element is to removed which is passed as an argument, otherwise returns false.
Examples:
Input : my_map.set(1, 'first');
my_map.set(2, 'second');
my_map.set(3,'third');
my_map.set(4,'fourth');
document.write(my_map.delete(3));
Output : true
Explanation: The key ‘3’ is present in the map hence element associated with it is removed and return true
Input : my_map.set(1, 'first');
my_map.set(2, 'second');
my_map.set(3,'third');
my_map.set(4,'fourth');
document.write(my_map.delete(5));
Output : false
Explanation: The key ‘5’ is not present in the map hence it returns false.
Code 1:
<script>// creating a map objectvar my_map = new Map(); // Adding [key, value] pair to the mapmy_map.set(1, 'first');my_map.set(2, 'second');my_map.set(3,'third');my_map.set(4,'fourth'); // will display true as key '3'// is present and its associated // element is removed as welldocument.write(my_map.delete(3),"</br>","</br>"); // elements left in the map after deletiondocument.write("key-value pair of the map", " after deletion-","</br>"); my_map.forEach(function (item, key, mapObj) { document.write(key.toString(),":", " ",item.toString() + "<br />"); }); </script>
Output:
true
key-value pair of the map after deletion-
1: first
2: second
4: fourth
Code 2:
<script>// creating a map objectvar my_map = new Map(); // Adding [key, value] pair to the mapmy_map.set(1, 'first');my_map.set(2, 'second');my_map.set(3,'third');my_map.set(4,'fourth'); // will display false as key '5'// is not present and its associated // element is removed as welldocument.write(my_map.delete(5), "</br>","</br>"); // elements left in the map after deletiondocument.write("key-value pair of the map", " after deletion-","</br>"); my_map.forEach(function (item, key, mapObj) { document.write(key.toString(),":"," ", item.toString() + "<br />"); }); </script>
Output:
false
key-value pair of the map after deletion-
1: first
2: second
3: third
4: fourth
If the key passed as an argument to the function is not present in the map then it returns false. Basically, it neither throws any exception nor does it have any error.
Difference in working of Map.clear(),Map.erase() and this functionMap.clear() removes all key-value pairs of the map and reduces the size of the map to zero. Whereas Map.erase() removes the specified mapped value whose key is passed as an argument or iterator or in range to remove pairs.
Supported Browser:
Chrome 38 and above
Edge 12 and above
Firefox 13 and above
Internet Explorer 11 and above
Opera 25 and above
safari 8 and above
ysachin2314
javascript-functions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Remove elements from a JavaScript Array
Roadmap to Learn JavaScript For Beginners
Difference Between PUT and PATCH Request
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n22 Nov, 2021"
},
{
"code": null,
"e": 57,
"s": 28,
"text": "What is a map in JavaScript?"
},
{
"code": null,
"e": 192,
"s": 57,
"text": "Map is a data structure in JavaScript which allows storing of [key, value] pairs where any value can be either used as a key or value."
},
{
"code": null,
"e": 394,
"s": 192,
"text": "The keys and values in the map collection may be of any type and if a value is added to the map collection using a key which already exists in the collection, then the new value replaces the old value."
},
{
"code": null,
"e": 550,
"s": 394,
"text": "The iteration of elements in a map object is done in the insertion order and a “for...” loop returns an array of all [key, value] pairs for each iteration."
},
{
"code": null,
"e": 971,
"s": 550,
"text": "Differences between Objects and Maps in JavaScriptBoth of these data structures are similar in many ways such as both store values using keys, allow retrieval of those values using keys, deletion of keys and verify whether a key holds any value or not. However, there are quite significant differences between Objects and Maps in JavaScript which make the usage of maps a better and more preferable option in many cases."
},
{
"code": null,
"e": 1114,
"s": 971,
"text": "The keys used in maps can be any type of values such as functions, objects etc whereas the keys in objects are limited to symbols and strings."
},
{
"code": null,
"e": 1251,
"s": 1114,
"text": "The size of a map can be known easily by using the size property but while dealing with objects, the size has to be determined manually."
},
{
"code": null,
"e": 1516,
"s": 1251,
"text": "A Map should be preferred in cases where the requirement involves frequent addition and removal of [key, value] pairs because a map is an iterative data type and can be directly iterated whereas iterating an object requires obtaining its keys in a specific manner."
},
{
"code": null,
"e": 1680,
"s": 1516,
"text": "Map.delete() Method in JavaScriptThe Map.delete() method in JavaScript is used to delete the specified element among all the elements which are present in the map."
},
{
"code": null,
"e": 1875,
"s": 1680,
"text": "The Map.delete() method takes the key which needs to be removed from the map, thus removes the element associated with that key and returns true. If the key is not present then it returns false."
},
{
"code": null,
"e": 1889,
"s": 1875,
"text": "Applications:"
},
{
"code": null,
"e": 1998,
"s": 1889,
"text": "Map.delete() is used to delete an element associated with the key among all the elements present in the map."
},
{
"code": null,
"e": 2006,
"s": 1998,
"text": "Syntax:"
},
{
"code": null,
"e": 2026,
"s": 2006,
"text": "my_map.delete(key)\n"
},
{
"code": null,
"e": 2043,
"s": 2026,
"text": "Parameters Used:"
},
{
"code": null,
"e": 2115,
"s": 2043,
"text": "key: The element associated with this key is to be removed from the map"
},
{
"code": null,
"e": 2129,
"s": 2115,
"text": "Return value:"
},
{
"code": null,
"e": 2285,
"s": 2129,
"text": "The Map.delete() method returns true, if the key is present whose associated element is to removed which is passed as an argument, otherwise returns false."
},
{
"code": null,
"e": 2295,
"s": 2285,
"text": "Examples:"
},
{
"code": null,
"e": 2487,
"s": 2295,
"text": "Input : my_map.set(1, 'first');\n my_map.set(2, 'second');\n my_map.set(3,'third');\n my_map.set(4,'fourth');\n\n document.write(my_map.delete(3));\n\nOutput : true\n"
},
{
"code": null,
"e": 2594,
"s": 2487,
"text": "Explanation: The key ‘3’ is present in the map hence element associated with it is removed and return true"
},
{
"code": null,
"e": 2790,
"s": 2594,
"text": "Input : my_map.set(1, 'first');\n my_map.set(2, 'second');\n my_map.set(3,'third');\n my_map.set(4,'fourth');\n \n document.write(my_map.delete(5));\n\nOutput : false\n"
},
{
"code": null,
"e": 2865,
"s": 2790,
"text": "Explanation: The key ‘5’ is not present in the map hence it returns false."
},
{
"code": null,
"e": 2873,
"s": 2865,
"text": "Code 1:"
},
{
"code": "<script>// creating a map objectvar my_map = new Map(); // Adding [key, value] pair to the mapmy_map.set(1, 'first');my_map.set(2, 'second');my_map.set(3,'third');my_map.set(4,'fourth'); // will display true as key '3'// is present and its associated // element is removed as welldocument.write(my_map.delete(3),\"</br>\",\"</br>\"); // elements left in the map after deletiondocument.write(\"key-value pair of the map\", \" after deletion-\",\"</br>\"); my_map.forEach(function (item, key, mapObj) { document.write(key.toString(),\":\", \" \",item.toString() + \"<br />\"); }); </script> ",
"e": 3516,
"s": 2873,
"text": null
},
{
"code": null,
"e": 3524,
"s": 3516,
"text": "Output:"
},
{
"code": null,
"e": 3602,
"s": 3524,
"text": "true\n\nkey-value pair of the map after deletion-\n1: first\n2: second\n4: fourth\n"
},
{
"code": null,
"e": 3610,
"s": 3602,
"text": "Code 2:"
},
{
"code": "<script>// creating a map objectvar my_map = new Map(); // Adding [key, value] pair to the mapmy_map.set(1, 'first');my_map.set(2, 'second');my_map.set(3,'third');my_map.set(4,'fourth'); // will display false as key '5'// is not present and its associated // element is removed as welldocument.write(my_map.delete(5), \"</br>\",\"</br>\"); // elements left in the map after deletiondocument.write(\"key-value pair of the map\", \" after deletion-\",\"</br>\"); my_map.forEach(function (item, key, mapObj) { document.write(key.toString(),\":\",\" \", item.toString() + \"<br />\"); }); </script> ",
"e": 4266,
"s": 3610,
"text": null
},
{
"code": null,
"e": 4274,
"s": 4266,
"text": "Output:"
},
{
"code": null,
"e": 4362,
"s": 4274,
"text": "false\n\nkey-value pair of the map after deletion-\n1: first\n2: second\n3: third\n4: fourth\n"
},
{
"code": null,
"e": 4531,
"s": 4362,
"text": "If the key passed as an argument to the function is not present in the map then it returns false. Basically, it neither throws any exception nor does it have any error."
},
{
"code": null,
"e": 4820,
"s": 4531,
"text": "Difference in working of Map.clear(),Map.erase() and this functionMap.clear() removes all key-value pairs of the map and reduces the size of the map to zero. Whereas Map.erase() removes the specified mapped value whose key is passed as an argument or iterator or in range to remove pairs."
},
{
"code": null,
"e": 4839,
"s": 4820,
"text": "Supported Browser:"
},
{
"code": null,
"e": 4859,
"s": 4839,
"text": "Chrome 38 and above"
},
{
"code": null,
"e": 4877,
"s": 4859,
"text": "Edge 12 and above"
},
{
"code": null,
"e": 4898,
"s": 4877,
"text": "Firefox 13 and above"
},
{
"code": null,
"e": 4929,
"s": 4898,
"text": "Internet Explorer 11 and above"
},
{
"code": null,
"e": 4948,
"s": 4929,
"text": "Opera 25 and above"
},
{
"code": null,
"e": 4967,
"s": 4948,
"text": "safari 8 and above"
},
{
"code": null,
"e": 4979,
"s": 4967,
"text": "ysachin2314"
},
{
"code": null,
"e": 5000,
"s": 4979,
"text": "javascript-functions"
},
{
"code": null,
"e": 5011,
"s": 5000,
"text": "JavaScript"
},
{
"code": null,
"e": 5028,
"s": 5011,
"text": "Web Technologies"
},
{
"code": null,
"e": 5126,
"s": 5028,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5187,
"s": 5126,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5259,
"s": 5187,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 5299,
"s": 5259,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 5341,
"s": 5299,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 5382,
"s": 5341,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 5415,
"s": 5382,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5477,
"s": 5415,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5538,
"s": 5477,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5588,
"s": 5538,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Difference between Int32 and UInt32 in C# | 26 May, 2020
Int32: This Struct is used to represents 32-bit signed integer. The Int32 can store both types of values including negative and positive between the ranges of -2147483648 to +2147483647.
Example :
C#
// C# program to show the// difference between Int32// and UInt32 using System;using System.Text; publicclass GFG { // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of Int32: " + Int32.MinValue); Console.WriteLine("Maximum value of Int32: " + Int32.MaxValue); Console.WriteLine(); // Int32 array Int32[] arr1 = {-3, 0, 1, 3, 7}; foreach (Int32 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of Int32: -2147483648
Maximum value of Int32: 2147483647
-3
0
1
3
7
UInt32: This Struct is used to represents 32-bit unsigned integer. The UInt32 can store only positive value only which ranges from 0 to 4294967295.
Example :
C#
// C# program to show the // difference between Int32 // and UInt32 using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine("Minimum value of UInt32: " + UInt32.MinValue); Console.WriteLine("Maximum value of UInt32: " + UInt32.MaxValue); Console.WriteLine(); // Int32 array UInt32[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt32 i in arr1) { Console.WriteLine(i); } }}
Output:
Minimum value of UInt32: 0
Maximum value of UInt32: 4294967295
13
0
1
3
7
Differences between Int32 and UInt32 in C#
Sr.No
INT32
UINT32
1.
2.
3.
4.
5.
6.
Syntax to declare the Int32 :
Int32 variable_name;
Syntax to declare the UInt32:
UInt32 variable_name;
CSharp-Int32-Struct
CSharp-UInt32-Struct
C#
Difference Between
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Introduction to .NET Framework
C# | Delegates
C# | Multiple inheritance using interfaces
Differences Between .NET Core and .NET Framework
C# | Data Types
Class method vs Static method in Python
Difference between BFS and DFS
Difference between var, let and const keywords in JavaScript
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 May, 2020"
},
{
"code": null,
"e": 215,
"s": 28,
"text": "Int32: This Struct is used to represents 32-bit signed integer. The Int32 can store both types of values including negative and positive between the ranges of -2147483648 to +2147483647."
},
{
"code": null,
"e": 225,
"s": 215,
"text": "Example :"
},
{
"code": null,
"e": 228,
"s": 225,
"text": "C#"
},
{
"code": "// C# program to show the// difference between Int32// and UInt32 using System;using System.Text; publicclass GFG { // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of Int32: \" + Int32.MinValue); Console.WriteLine(\"Maximum value of Int32: \" + Int32.MaxValue); Console.WriteLine(); // Int32 array Int32[] arr1 = {-3, 0, 1, 3, 7}; foreach (Int32 i in arr1) { Console.WriteLine(i); } }}",
"e": 772,
"s": 228,
"text": null
},
{
"code": null,
"e": 780,
"s": 772,
"text": "Output:"
},
{
"code": null,
"e": 865,
"s": 780,
"text": "Minimum value of Int32: -2147483648\nMaximum value of Int32: 2147483647\n\n-3\n0\n1\n3\n7\n\n"
},
{
"code": null,
"e": 1013,
"s": 865,
"text": "UInt32: This Struct is used to represents 32-bit unsigned integer. The UInt32 can store only positive value only which ranges from 0 to 4294967295."
},
{
"code": null,
"e": 1023,
"s": 1013,
"text": "Example :"
},
{
"code": null,
"e": 1026,
"s": 1023,
"text": "C#"
},
{
"code": "// C# program to show the // difference between Int32 // and UInt32 using System;using System.Text; public class GFG{ // Main Method static void Main(string[] args) { // printing minimum & maximum values Console.WriteLine(\"Minimum value of UInt32: \" + UInt32.MinValue); Console.WriteLine(\"Maximum value of UInt32: \" + UInt32.MaxValue); Console.WriteLine(); // Int32 array UInt32[] arr1 = { 13, 0, 1, 3, 7}; foreach (UInt32 i in arr1) { Console.WriteLine(i); } }}",
"e": 1655,
"s": 1026,
"text": null
},
{
"code": null,
"e": 1663,
"s": 1655,
"text": "Output:"
},
{
"code": null,
"e": 1740,
"s": 1663,
"text": "Minimum value of UInt32: 0\nMaximum value of UInt32: 4294967295\n\n13\n0\n1\n3\n7\n\n"
},
{
"code": null,
"e": 1783,
"s": 1740,
"text": "Differences between Int32 and UInt32 in C#"
},
{
"code": null,
"e": 1789,
"s": 1783,
"text": "Sr.No"
},
{
"code": null,
"e": 1795,
"s": 1789,
"text": "INT32"
},
{
"code": null,
"e": 1802,
"s": 1795,
"text": "UINT32"
},
{
"code": null,
"e": 1805,
"s": 1802,
"text": "1."
},
{
"code": null,
"e": 1808,
"s": 1805,
"text": "2."
},
{
"code": null,
"e": 1811,
"s": 1808,
"text": "3."
},
{
"code": null,
"e": 1814,
"s": 1811,
"text": "4."
},
{
"code": null,
"e": 1817,
"s": 1814,
"text": "5."
},
{
"code": null,
"e": 1821,
"s": 1817,
"text": " 6."
},
{
"code": null,
"e": 1852,
"s": 1821,
"text": " Syntax to declare the Int32 :"
},
{
"code": null,
"e": 1874,
"s": 1852,
"text": "Int32 variable_name;\n"
},
{
"code": null,
"e": 1906,
"s": 1874,
"text": " Syntax to declare the UInt32:"
},
{
"code": null,
"e": 1929,
"s": 1906,
"text": "UInt32 variable_name;\n"
},
{
"code": null,
"e": 1949,
"s": 1929,
"text": "CSharp-Int32-Struct"
},
{
"code": null,
"e": 1970,
"s": 1949,
"text": "CSharp-UInt32-Struct"
},
{
"code": null,
"e": 1973,
"s": 1970,
"text": "C#"
},
{
"code": null,
"e": 1992,
"s": 1973,
"text": "Difference Between"
},
{
"code": null,
"e": 2090,
"s": 1992,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2121,
"s": 2090,
"text": "Introduction to .NET Framework"
},
{
"code": null,
"e": 2136,
"s": 2121,
"text": "C# | Delegates"
},
{
"code": null,
"e": 2179,
"s": 2136,
"text": "C# | Multiple inheritance using interfaces"
},
{
"code": null,
"e": 2228,
"s": 2179,
"text": "Differences Between .NET Core and .NET Framework"
},
{
"code": null,
"e": 2244,
"s": 2228,
"text": "C# | Data Types"
},
{
"code": null,
"e": 2284,
"s": 2244,
"text": "Class method vs Static method in Python"
},
{
"code": null,
"e": 2315,
"s": 2284,
"text": "Difference between BFS and DFS"
},
{
"code": null,
"e": 2376,
"s": 2315,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2444,
"s": 2376,
"text": "Difference Between Method Overloading and Method Overriding in Java"
}
] |
Subarray with 0 sum | Practice | GeeksforGeeks | Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum.
Example 1:
Input:
5
4 2 -3 1 6
Output:
Yes
Explanation:
2, -3, 1 is the subarray
with sum 0.
Example 2:
Input:
5
4 2 0 1 6
Output:
Yes
Explanation:
0 is one of the element
in the array so there exist a
subarray with sum 0.
Your Task:
You only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code.
Expected Time Complexity: O(n).
Expected Auxiliary Space: O(n).
Constraints:
1 <= n <= 104
-105 <= a[i] <= 105
0
ishubham0109 hours ago
HashSet<Integer> map = new HashSet<>();
int sum = 0;
for(int i=0; i<n; i++) {
sum = sum + arr[i];
if(sum==0 || arr[i] == 0 || map.contains(sum)) {
return true;
}
map.add(sum);
}
return false;
0
ishubham010
This comment was deleted.
0
anil19j1m2q1 day ago
bool subArrayExists(int arr[], int n) { unordered_map<int,int> map; int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; if(sum==0 or map[sum] or arr[i]==0){ return true; } map[sum]++; } return false; }
+2
sm21mtech120084 days ago
simple explanation in C++
logic:
for subarray sum to be zero ,if sum is zero or sum value is repeated.
(if we add array elements from first index,let it be stored in sum.)
(store sum values in map or set)
let array is 9,1,-1
sum=9 ,sum=10 ,sum=9
here 9 is repeated ,so subarray sum is zero
bool subArrayExists(int arr[], int n)
{
unordered_map<int,int>m;
int sum=0;
for(int i=0;i<n;i++)
{
sum+=arr[i];
if(sum==0)return true;
if(m.find(sum)!=m.end()) return true;
m[sum]++;
}
return false;
}
0
nishraut74 days ago
Python code:
class Solution: #Function to check whether there is a subarray present with 0-sum or not. def subArrayExists(self,arr,n): ##Your code here #Return true or false sum = 0 hashmap = {} for i in arr: if i == 0: return True sum += i if sum == 0: return True if sum not in hashmap.keys(): hashmap[sum] = 1 else: hashmap[sum]+= 1 for i in hashmap.values(): if i > 1: return True return False
0
evansubedi9991 week ago
unordered_map<int,int>m; int sum=0; int p=0; for(int i=0;i<n;i++){ sum=sum+arr[i]; if(sum==p)return true; if(m.find(sum-p)!=m.end()){ return true; } m[sum]++; } return false;
0
anujpathare1 week ago
#Total Time Taken: 0.57/1.61
def subArrayExists(self,arr,n): hash_set = {} sum = 0 for i in range(n): sum += arr[i] if sum == 0: return True if sum not in hash_set: hash_set[sum] = 1 else: hash_set[sum] += 1
for i in hash_set.values(): if i > 1: return True
return False
+1
vishalkamble2k181 week ago
THE SIMPLEST SOL. EVER USING C++😍😍😍
bool subArrayExists(int arr[], int n) { //Your code here int pre_sum=0; unordered_set<int> s; for(int i=0;i<n;i++){ pre_sum += arr[i]; if(pre_sum == 0) { return true; } if(s.find(pre_sum) != s.end()) return true; s.insert(pre_sum);}return false; }
0
ayushkumarmin201 week ago
unordered_set<int>s; int curr=0;
for( int i=0;i<n; i++){
curr+=arr[i];
if(curr==0)return true;
if(s.find(curr)!=s.end()) return true;
else s.insert(curr);
}return false;
0
ashivamsahu141 week ago
<<CPP Solution >>
class Solution
{
public:
bool subArrayExists(int arr[], int n)
{
unordered_set<int>s;
int i,cur_sum=0;
for(i=0;i<n;i++)
{
cur_sum=cur_sum+arr[i];
if(cur_sum==0)
return true;
if(s.find(cur_sum) != s.end())
return true;
else
s.insert(cur_sum);
}
return false;
}
};
We strongly recommend solving this problem on your own before viewing its editorial. Do you still
want to view the editorial?
Login to access your submissions.
Problem
Contest
Reset the IDE using the second button on the top right corner.
Avoid using static/global variables in your code as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases does not guarantee the correctness of code.
On submission, your code is tested against multiple test cases consisting of all
possible corner cases and stress constraints.
You can access the hints to get an idea about what is expected of you as well as
the final solution code.
You can view the solutions submitted by other users from the submission tab.
Make sure you are not using ad-blockers.
Disable browser extensions.
We recommend using latest version of your browser for best experience.
Avoid using static/global variables in coding problems as your code is tested
against multiple test cases and these tend to retain their previous values.
Passing the Sample/Custom Test cases in coding problems does not guarantee the
correctness of code. On submission, your code is tested against multiple test cases
consisting of all possible corner cases and stress constraints. | [
{
"code": null,
"e": 350,
"s": 238,
"text": "Given an array of positive and negative numbers. Find if there is a subarray (of size at-least one) with 0 sum."
},
{
"code": null,
"e": 361,
"s": 350,
"text": "Example 1:"
},
{
"code": null,
"e": 448,
"s": 361,
"text": "Input:\n5\n4 2 -3 1 6\n\nOutput: \nYes\n\nExplanation: \n2, -3, 1 is the subarray \nwith sum 0."
},
{
"code": null,
"e": 459,
"s": 448,
"text": "Example 2:"
},
{
"code": null,
"e": 585,
"s": 459,
"text": "Input:\n5\n4 2 0 1 6\n\nOutput: \nYes\n\nExplanation: \n0 is one of the element \nin the array so there exist a \nsubarray with sum 0.\n"
},
{
"code": null,
"e": 834,
"s": 585,
"text": "Your Task:\nYou only need to complete the function subArrayExists() that takes array and n as parameters and returns true or false depending upon whether there is a subarray present with 0-sum or not. Printing will be taken care by the drivers code."
},
{
"code": null,
"e": 898,
"s": 834,
"text": "Expected Time Complexity: O(n).\nExpected Auxiliary Space: O(n)."
},
{
"code": null,
"e": 945,
"s": 898,
"text": "Constraints:\n1 <= n <= 104\n-105 <= a[i] <= 105"
},
{
"code": null,
"e": 949,
"s": 947,
"text": "0"
},
{
"code": null,
"e": 972,
"s": 949,
"text": "ishubham0109 hours ago"
},
{
"code": null,
"e": 1190,
"s": 972,
"text": "HashSet<Integer> map = new HashSet<>();\nint sum = 0;\nfor(int i=0; i<n; i++) {\n sum = sum + arr[i];\n if(sum==0 || arr[i] == 0 || map.contains(sum)) {\n return true;\n }\n map.add(sum);\n }\n return false;"
},
{
"code": null,
"e": 1192,
"s": 1190,
"text": "0"
},
{
"code": null,
"e": 1204,
"s": 1192,
"text": "ishubham010"
},
{
"code": null,
"e": 1230,
"s": 1204,
"text": "This comment was deleted."
},
{
"code": null,
"e": 1232,
"s": 1230,
"text": "0"
},
{
"code": null,
"e": 1253,
"s": 1232,
"text": "anil19j1m2q1 day ago"
},
{
"code": null,
"e": 1527,
"s": 1253,
"text": "bool subArrayExists(int arr[], int n) { unordered_map<int,int> map; int sum=0; for(int i=0;i<n;i++){ sum+=arr[i]; if(sum==0 or map[sum] or arr[i]==0){ return true; } map[sum]++; } return false; }"
},
{
"code": null,
"e": 1530,
"s": 1527,
"text": "+2"
},
{
"code": null,
"e": 1555,
"s": 1530,
"text": "sm21mtech120084 days ago"
},
{
"code": null,
"e": 1581,
"s": 1555,
"text": "simple explanation in C++"
},
{
"code": null,
"e": 1590,
"s": 1581,
"text": "logic: "
},
{
"code": null,
"e": 1660,
"s": 1590,
"text": "for subarray sum to be zero ,if sum is zero or sum value is repeated."
},
{
"code": null,
"e": 1729,
"s": 1660,
"text": "(if we add array elements from first index,let it be stored in sum.)"
},
{
"code": null,
"e": 1762,
"s": 1729,
"text": "(store sum values in map or set)"
},
{
"code": null,
"e": 1785,
"s": 1764,
"text": " let array is 9,1,-1"
},
{
"code": null,
"e": 1806,
"s": 1785,
"text": "sum=9 ,sum=10 ,sum=9"
},
{
"code": null,
"e": 1851,
"s": 1806,
"text": "here 9 is repeated ,so subarray sum is zero "
},
{
"code": null,
"e": 2116,
"s": 1853,
"text": "bool subArrayExists(int arr[], int n)\n {\n unordered_map<int,int>m;\n int sum=0;\n for(int i=0;i<n;i++)\n {\n sum+=arr[i];\n if(sum==0)return true;\n if(m.find(sum)!=m.end()) return true;\n m[sum]++;\n }\n return false;\n }"
},
{
"code": null,
"e": 2118,
"s": 2116,
"text": "0"
},
{
"code": null,
"e": 2138,
"s": 2118,
"text": "nishraut74 days ago"
},
{
"code": null,
"e": 2151,
"s": 2138,
"text": "Python code:"
},
{
"code": null,
"e": 2776,
"s": 2153,
"text": "class Solution: #Function to check whether there is a subarray present with 0-sum or not. def subArrayExists(self,arr,n): ##Your code here #Return true or false sum = 0 hashmap = {} for i in arr: if i == 0: return True sum += i if sum == 0: return True if sum not in hashmap.keys(): hashmap[sum] = 1 else: hashmap[sum]+= 1 for i in hashmap.values(): if i > 1: return True return False"
},
{
"code": null,
"e": 2778,
"s": 2776,
"text": "0"
},
{
"code": null,
"e": 2802,
"s": 2778,
"text": "evansubedi9991 week ago"
},
{
"code": null,
"e": 3049,
"s": 2802,
"text": "unordered_map<int,int>m; int sum=0; int p=0; for(int i=0;i<n;i++){ sum=sum+arr[i]; if(sum==p)return true; if(m.find(sum-p)!=m.end()){ return true; } m[sum]++; } return false;"
},
{
"code": null,
"e": 3051,
"s": 3049,
"text": "0"
},
{
"code": null,
"e": 3073,
"s": 3051,
"text": "anujpathare1 week ago"
},
{
"code": null,
"e": 3102,
"s": 3073,
"text": "#Total Time Taken: 0.57/1.61"
},
{
"code": null,
"e": 3399,
"s": 3106,
"text": "def subArrayExists(self,arr,n): hash_set = {} sum = 0 for i in range(n): sum += arr[i] if sum == 0: return True if sum not in hash_set: hash_set[sum] = 1 else: hash_set[sum] += 1"
},
{
"code": null,
"e": 3483,
"s": 3399,
"text": " for i in hash_set.values(): if i > 1: return True"
},
{
"code": null,
"e": 3503,
"s": 3483,
"text": " return False"
},
{
"code": null,
"e": 3506,
"s": 3503,
"text": "+1"
},
{
"code": null,
"e": 3533,
"s": 3506,
"text": "vishalkamble2k181 week ago"
},
{
"code": null,
"e": 3570,
"s": 3533,
"text": "THE SIMPLEST SOL. EVER USING C++😍😍😍"
},
{
"code": null,
"e": 3898,
"s": 3572,
"text": "bool subArrayExists(int arr[], int n) { //Your code here int pre_sum=0; unordered_set<int> s; for(int i=0;i<n;i++){ pre_sum += arr[i]; if(pre_sum == 0) { return true; } if(s.find(pre_sum) != s.end()) return true; s.insert(pre_sum);}return false; }"
},
{
"code": null,
"e": 3900,
"s": 3898,
"text": "0"
},
{
"code": null,
"e": 3926,
"s": 3900,
"text": "ayushkumarmin201 week ago"
},
{
"code": null,
"e": 4136,
"s": 3926,
"text": "unordered_set<int>s; int curr=0;\n for( int i=0;i<n; i++){\n curr+=arr[i];\n if(curr==0)return true;\n if(s.find(curr)!=s.end()) return true;\n else s.insert(curr);\n }return false;"
},
{
"code": null,
"e": 4138,
"s": 4136,
"text": "0"
},
{
"code": null,
"e": 4162,
"s": 4138,
"text": "ashivamsahu141 week ago"
},
{
"code": null,
"e": 4180,
"s": 4162,
"text": "<<CPP Solution >>"
},
{
"code": null,
"e": 4603,
"s": 4180,
"text": "class Solution\n{\n public:\n bool subArrayExists(int arr[], int n)\n {\n unordered_set<int>s;\n int i,cur_sum=0;\n for(i=0;i<n;i++)\n {\n cur_sum=cur_sum+arr[i];\n if(cur_sum==0)\n return true;\n if(s.find(cur_sum) != s.end())\n return true;\n else\n s.insert(cur_sum);\n }\n return false;\n }\n};"
},
{
"code": null,
"e": 4749,
"s": 4603,
"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": 4785,
"s": 4749,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4795,
"s": 4785,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4805,
"s": 4795,
"text": "\nContest\n"
},
{
"code": null,
"e": 4868,
"s": 4805,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 5053,
"s": 4868,
"text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values."
},
{
"code": null,
"e": 5337,
"s": 5053,
"text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints."
},
{
"code": null,
"e": 5483,
"s": 5337,
"text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code."
},
{
"code": null,
"e": 5560,
"s": 5483,
"text": "You can view the solutions submitted by other users from the submission tab."
},
{
"code": null,
"e": 5601,
"s": 5560,
"text": "Make sure you are not using ad-blockers."
},
{
"code": null,
"e": 5629,
"s": 5601,
"text": "Disable browser extensions."
},
{
"code": null,
"e": 5700,
"s": 5629,
"text": "We recommend using latest version of your browser for best experience."
},
{
"code": null,
"e": 5887,
"s": 5700,
"text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values."
}
] |
A scale transform the element by using x-axis with CSS3 | The scaleX(x) method is used to scale transform the element using x-axis.
Let us see the syntax −
scaleX(x)
Here, x is a number representing the scaling factor to apply on the abscissa of each point of the element.
Let us see an example −
div {
width: 60px;
height: 60px;
background-color: yellow;
}
.scaled {
transform: scaleX(0.5);
background-color: black;
} | [
{
"code": null,
"e": 1136,
"s": 1062,
"text": "The scaleX(x) method is used to scale transform the element using x-axis."
},
{
"code": null,
"e": 1160,
"s": 1136,
"text": "Let us see the syntax −"
},
{
"code": null,
"e": 1170,
"s": 1160,
"text": "scaleX(x)"
},
{
"code": null,
"e": 1277,
"s": 1170,
"text": "Here, x is a number representing the scaling factor to apply on the abscissa of each point of the element."
},
{
"code": null,
"e": 1301,
"s": 1277,
"text": "Let us see an example −"
},
{
"code": null,
"e": 1438,
"s": 1301,
"text": "div {\n width: 60px;\n height: 60px;\n background-color: yellow;\n}\n.scaled {\n transform: scaleX(0.5);\n background-color: black;\n}"
}
] |
Getting Started with Randomized Optimization in Python | by Genevieve Hayes | Towards Data Science | mlrose provides functionality for implementing some of the most popular randomization and search algorithms, and applying them to a range of different optimization problem domains.
In this tutorial, we will discuss what is meant by an optimization problem and step through an example of how mlrose can be used to solve them. This is the first in a series of three tutorials. Part 2 can be found here and Part 3 can be found here.
An optimization problem is defined by Russell and Norvig (2010) as a problem in which “the aim is to find the best state according to an objective function.”
What is meant by a “state” depends on the context of the problem. Some examples of states are:
the weights used in a machine learning model, such as a neural network;
the placement of chess pieces on a chess board;
the order that cities are visited in a tour of all cities on a map of a country;
the colors selected to color the countries in a map of the world.
What is important, for our purposes, is that the state can be represented numerically, ideally as a one-dimensional array (or vector) of values.
What is meant by “best” is defined by a mathematical formula or function (known as an objective function, fitness function, cost function or loss function), which we want to either maximize or minimize. The function accepts a state array as an input and returns a “fitness” value as an output.
The output fitness values allow us to compare the inputted state to other states we might be considering. In this context, the elements of the state array can be thought of as the variables (or parameters) of the function.
Therefore, an optimization problem can be simply thought of as a mathematical function that we would like to maximize/minimize by selecting the optimal values for each of its parameters.
The five-dimensional One-Max optimization problem involves finding the value of state vector x = [x0, x1, x2, x3, x4] which maximizes Fitness(x) = x0 + x1 + x2 + x3 + x4.
If each of the elements of x can only take the values 0 or 1, then the solution to this problem is x = [1, 1, 1, 1, 1]. When x is set equal to this optimal value, Fitness(x) = 5, the maximum value it can take.
For the One-Max example given above, even if the solution was not immediately obvious, it would be possible to calculate the fitness value for all possible state vectors, x, and then select the best of those vectors.
However, for more complicated problems, this cannot always be done within a reasonable period of time. Randomized optimization overcomes this issue.
Randomized optimization algorithms typically start at an initial “best” state vector (or population of multiple state vectors) and then randomly generate a new state vector (often a neighbor of the current “best” state).
If the new state is better than the current “best” state, then the new vector becomes the new “best” state vector.
This process is repeated until it is no longer possible to find a better state vector than the current “best” state, or if a better state vector cannot be found within a pre-specified number of attempts.
There is no guarantee a randomized optimization algorithm will find the optimal solution to a given optimization problem (for example, it is possible that the algorithm may find a local maximum of the fitness function, instead of the global maximum).
However, if a sufficiently large number of attempts are made to find a better state at each step of the algorithm, then the algorithm will return a “good” solution to the problem.
There is a trade-off between the time spent searching for the optimal solution to an optimization problem and the quality of the solution ultimately found.
Solving an optimization problem using mlrose involves three simple steps:
Define a fitness function object.Define an optimization problem object.Select and run a randomized optimization algorithm.
Define a fitness function object.
Define an optimization problem object.
Select and run a randomized optimization algorithm.
To illustrate each of these steps, we will work through the example of the 8-Queens optimization problem, described below:
In chess, the queen is the most powerful piece on the board. It can attack any piece in the same row, column or diagonal. In the 8-Queens problem, you are given an 8 x 8 chessboard with eight queens (and no other pieces) and the aim is to place the queens on the board so that none of them can attack each other.
Clearly, in an optimal solution to this problem, there will be exactly one queen in each column of the chessboard. So, we only need to determine the row position of each queen, and we can define the state vector for this problem as x = [x0, x1, x2, x3, x4, x5, x6, x7], where xi denotes the row position of the queen in column i (for i = 0, 1, ..., 7).
The chessboard pictured below could, therefore, be described by the state vector x = [6, 1, 7, 5, 0, 2, 3, 4], where the bottom left corner of the chessboard is assumed to be in column 0 and row 0.
This is not an optimal solution to the 8-Queens problem, since the three queens in columns 5, 6 and 7 are attacking each other diagonally, as are the queens in columns 2 and 6.
Before starting with this example, you will need to import the mlrose and Numpy Python packages.
import mlroseimport numpy as np
The first step in solving any optimization problem is to define the fitness function. This is the function we would ultimately like to maximize or minimize, and which can be used to evaluate the fitness of a given state vector, x.
In the context of the 8-Queens problem, our goal is to find a state vector for which no pairs of attacking queens exist. Therefore, we could define our fitness function as evaluating the number of pairs of attacking queens for a given state and try to minimize this function.
mlrose includes pre-defined fitness function classes for a range of common optimization problems, including the N-Queens family of problems (of which 8-Queens is a member). The pre-defined Queens() class includes an implementation of the (8-)Queens fitness function described above.
We can initialize a fitness function object for this class, as follows:
fitness = mlrose.Queens()
Alternatively, we could look at the 8-Queens problem as one where the aim is to find a state vector for which all pairs of queens do not attack each other. In this context, we could define our fitness function as evaluating the number of pairs of non-attacking queens for a given state and try to maximize this function.
This definition of the 8-Queens fitness function is different from that used by mlrose’s pre-defined Queens() class, so to use it, we will need to create a custom fitness function. This can be done by first defining a fitness function with a signature of the form fitness_fn(state, **kwargs), and then using mlrose’s CustomFitness() class to create a fitness function object, as follows:
Once we have created a fitness function object, we can use it as an input into an optimization problem object. In mlrose, optimization problem objects are used to contain all of the important information about the optimization problem we are trying to solve.
mlrose provides classes for defining three types of optimization problem objects:
DiscreteOpt(): This is used to describe discrete-state optimization problems. A discrete-state optimization problem is one where each element of the state vector can only take on a discrete set of values. In mlrose, these values are assumed to be integers in the range 0 to (max_val -1), where max_val is defined at initialization.
ContinuousOpt(): This is used to describe continuous-state optimization problems. Continuous-state optimization problems are similar to discrete-state optimization problems, except that each value in the state vector can take any value in the continuous range between min_val and max_val, as specified at initialization.
TSPOpt(): This is used to describe travelling salesperson (or tour) optimization problems. Travelling salesperson optimization problems differ from the previous two problem types in that we know the elements of the optimal state vector are the integers 0 to (n-1), where n is the length of the state vector, and our goal is to find the optimal ordering of those integers.
The 8-Queens problem is an example of a discrete-state optimization problem, since each of the elements of the state vector must take on an integer value in the range 0 to 7.
To initialize a discrete-state optimization problem object, it is necessary to specify the problem length (i.e. the length of the state vector, which is 8 in this case); max_val, as defined above (also 8); the fitness function object created in the previous step; and whether the problem is a maximization or minimization problem.
For this example, we will use the first of the two fitness function objects defined above, so we want to solve a minimization problem.
problem = mlrose.DiscreteOpt(length = 8, fitness_fn = fitness, maximize = False, max_val = 8)
However, had we chosen to use the second (custom) fitness function object, we would be dealing with a maximization problem, so, in the above code, we would have to set the maximize parameter to True instead of False (in addition to changing the value of the fitness_fn parameter).
Now that we have defined an optimization problem object, we are ready to solve our optimization problem. mlrose includes implementations of the (random-restart) hill climbing, randomized hill climbing (also known as stochastic hill climbing), simulated annealing, genetic algorithm and MIMIC (Mutual-Information-Maximizing Input Clustering) randomized optimization algorithms.
For discrete-state and travelling salesperson optimization problems, we can choose any of these algorithms. However, continuous-state problems are not supported in the case of MIMIC.
For our example, suppose we wish to use simulated annealing. To implement this algorithm, in addition to defining an optimization problem object, we must also define a schedule object (to specify how the simulated annealing temperature parameter changes over time); the number of attempts the algorithm should make to find a “better” state at each step (max_attempts); and the maximum number of iterations the algorithm should run for overall (max_iters). We can also specify the starting state for the algorithm, if desired (init_state).
To specify the schedule object, mlrose includes pre-defined decay schedule classes for geometric, arithmetic and expontential decay, as well as a class for defining your own decay schedule in a manner similar to the way in which we created a customized fitness function object.
Suppose we wish to use an exponential decay schedule (with default parameter settings); make at most 10 attempts to find a “better” state at each algorithm step; limit ourselves to at most 1000 iterations of the algorithm; and start at an initial state of x = [0, 1, 2, 3, 4, 5, 6, 7]. This can be done using the following code.
The algorithm returns the best state it can find, given the parameter values it has been provided, as well as the fitness value for that state.
The best state found is: [6 4 7 3 6 2 5 1]The fitness at the best state is: 2.0
Running this code gives us a good solution to the 8-Queens problem, but not the optimal solution. The solution found by the algorithm, is pictured below:
The solution state has a fitness value of 2, indicating there are still two pairs of attacking queens on the chessboard (the queens in columns 0 and 3; and the two queens in row 6). Ideally, we would like our solution to have a fitness value of 0.
We can try to improve on our solution by tuning the parameters of our algorithm. Any of the algorithm’s parameters can be tuned. However, in this case, let’s focus on tuning the max_attempts parameter only, and increase it from 10 to 100.
This time when we run our code, we get a solution with a fitness value of 0, indicating that none of the queens on the chessboard are attacking each other.
The best state found is: [4 1 3 5 7 2 0 6]The fitness at the best state is: 0.0
This can be verified below:
In this tutorial we defined what is meant by an optimization problem and went through a simple example of how mlrose can be used to solve them. This is all you need to solve the majority of optimization problems.
However, there is one type of problem we have only briefly touched upon so far: the travelling salesperson optimization problem. In Part 2 of this tutorial we will go through an example of how mlrose can be used to solve this problem type. You can find Part 2 here.
To learn more about mlrose, visit the GitHub repository for this package, available here. | [
{
"code": null,
"e": 353,
"s": 172,
"text": "mlrose provides functionality for implementing some of the most popular randomization and search algorithms, and applying them to a range of different optimization problem domains."
},
{
"code": null,
"e": 602,
"s": 353,
"text": "In this tutorial, we will discuss what is meant by an optimization problem and step through an example of how mlrose can be used to solve them. This is the first in a series of three tutorials. Part 2 can be found here and Part 3 can be found here."
},
{
"code": null,
"e": 760,
"s": 602,
"text": "An optimization problem is defined by Russell and Norvig (2010) as a problem in which “the aim is to find the best state according to an objective function.”"
},
{
"code": null,
"e": 855,
"s": 760,
"text": "What is meant by a “state” depends on the context of the problem. Some examples of states are:"
},
{
"code": null,
"e": 927,
"s": 855,
"text": "the weights used in a machine learning model, such as a neural network;"
},
{
"code": null,
"e": 975,
"s": 927,
"text": "the placement of chess pieces on a chess board;"
},
{
"code": null,
"e": 1056,
"s": 975,
"text": "the order that cities are visited in a tour of all cities on a map of a country;"
},
{
"code": null,
"e": 1122,
"s": 1056,
"text": "the colors selected to color the countries in a map of the world."
},
{
"code": null,
"e": 1267,
"s": 1122,
"text": "What is important, for our purposes, is that the state can be represented numerically, ideally as a one-dimensional array (or vector) of values."
},
{
"code": null,
"e": 1561,
"s": 1267,
"text": "What is meant by “best” is defined by a mathematical formula or function (known as an objective function, fitness function, cost function or loss function), which we want to either maximize or minimize. The function accepts a state array as an input and returns a “fitness” value as an output."
},
{
"code": null,
"e": 1784,
"s": 1561,
"text": "The output fitness values allow us to compare the inputted state to other states we might be considering. In this context, the elements of the state array can be thought of as the variables (or parameters) of the function."
},
{
"code": null,
"e": 1971,
"s": 1784,
"text": "Therefore, an optimization problem can be simply thought of as a mathematical function that we would like to maximize/minimize by selecting the optimal values for each of its parameters."
},
{
"code": null,
"e": 2142,
"s": 1971,
"text": "The five-dimensional One-Max optimization problem involves finding the value of state vector x = [x0, x1, x2, x3, x4] which maximizes Fitness(x) = x0 + x1 + x2 + x3 + x4."
},
{
"code": null,
"e": 2352,
"s": 2142,
"text": "If each of the elements of x can only take the values 0 or 1, then the solution to this problem is x = [1, 1, 1, 1, 1]. When x is set equal to this optimal value, Fitness(x) = 5, the maximum value it can take."
},
{
"code": null,
"e": 2569,
"s": 2352,
"text": "For the One-Max example given above, even if the solution was not immediately obvious, it would be possible to calculate the fitness value for all possible state vectors, x, and then select the best of those vectors."
},
{
"code": null,
"e": 2718,
"s": 2569,
"text": "However, for more complicated problems, this cannot always be done within a reasonable period of time. Randomized optimization overcomes this issue."
},
{
"code": null,
"e": 2939,
"s": 2718,
"text": "Randomized optimization algorithms typically start at an initial “best” state vector (or population of multiple state vectors) and then randomly generate a new state vector (often a neighbor of the current “best” state)."
},
{
"code": null,
"e": 3054,
"s": 2939,
"text": "If the new state is better than the current “best” state, then the new vector becomes the new “best” state vector."
},
{
"code": null,
"e": 3258,
"s": 3054,
"text": "This process is repeated until it is no longer possible to find a better state vector than the current “best” state, or if a better state vector cannot be found within a pre-specified number of attempts."
},
{
"code": null,
"e": 3509,
"s": 3258,
"text": "There is no guarantee a randomized optimization algorithm will find the optimal solution to a given optimization problem (for example, it is possible that the algorithm may find a local maximum of the fitness function, instead of the global maximum)."
},
{
"code": null,
"e": 3689,
"s": 3509,
"text": "However, if a sufficiently large number of attempts are made to find a better state at each step of the algorithm, then the algorithm will return a “good” solution to the problem."
},
{
"code": null,
"e": 3845,
"s": 3689,
"text": "There is a trade-off between the time spent searching for the optimal solution to an optimization problem and the quality of the solution ultimately found."
},
{
"code": null,
"e": 3919,
"s": 3845,
"text": "Solving an optimization problem using mlrose involves three simple steps:"
},
{
"code": null,
"e": 4042,
"s": 3919,
"text": "Define a fitness function object.Define an optimization problem object.Select and run a randomized optimization algorithm."
},
{
"code": null,
"e": 4076,
"s": 4042,
"text": "Define a fitness function object."
},
{
"code": null,
"e": 4115,
"s": 4076,
"text": "Define an optimization problem object."
},
{
"code": null,
"e": 4167,
"s": 4115,
"text": "Select and run a randomized optimization algorithm."
},
{
"code": null,
"e": 4290,
"s": 4167,
"text": "To illustrate each of these steps, we will work through the example of the 8-Queens optimization problem, described below:"
},
{
"code": null,
"e": 4603,
"s": 4290,
"text": "In chess, the queen is the most powerful piece on the board. It can attack any piece in the same row, column or diagonal. In the 8-Queens problem, you are given an 8 x 8 chessboard with eight queens (and no other pieces) and the aim is to place the queens on the board so that none of them can attack each other."
},
{
"code": null,
"e": 4957,
"s": 4603,
"text": "Clearly, in an optimal solution to this problem, there will be exactly one queen in each column of the chessboard. So, we only need to determine the row position of each queen, and we can define the state vector for this problem as x = [x0, x1, x2, x3, x4, x5, x6, x7], where xi denotes the row position of the queen in column i (for i = 0, 1, ..., 7)."
},
{
"code": null,
"e": 5155,
"s": 4957,
"text": "The chessboard pictured below could, therefore, be described by the state vector x = [6, 1, 7, 5, 0, 2, 3, 4], where the bottom left corner of the chessboard is assumed to be in column 0 and row 0."
},
{
"code": null,
"e": 5332,
"s": 5155,
"text": "This is not an optimal solution to the 8-Queens problem, since the three queens in columns 5, 6 and 7 are attacking each other diagonally, as are the queens in columns 2 and 6."
},
{
"code": null,
"e": 5429,
"s": 5332,
"text": "Before starting with this example, you will need to import the mlrose and Numpy Python packages."
},
{
"code": null,
"e": 5461,
"s": 5429,
"text": "import mlroseimport numpy as np"
},
{
"code": null,
"e": 5692,
"s": 5461,
"text": "The first step in solving any optimization problem is to define the fitness function. This is the function we would ultimately like to maximize or minimize, and which can be used to evaluate the fitness of a given state vector, x."
},
{
"code": null,
"e": 5968,
"s": 5692,
"text": "In the context of the 8-Queens problem, our goal is to find a state vector for which no pairs of attacking queens exist. Therefore, we could define our fitness function as evaluating the number of pairs of attacking queens for a given state and try to minimize this function."
},
{
"code": null,
"e": 6251,
"s": 5968,
"text": "mlrose includes pre-defined fitness function classes for a range of common optimization problems, including the N-Queens family of problems (of which 8-Queens is a member). The pre-defined Queens() class includes an implementation of the (8-)Queens fitness function described above."
},
{
"code": null,
"e": 6323,
"s": 6251,
"text": "We can initialize a fitness function object for this class, as follows:"
},
{
"code": null,
"e": 6349,
"s": 6323,
"text": "fitness = mlrose.Queens()"
},
{
"code": null,
"e": 6670,
"s": 6349,
"text": "Alternatively, we could look at the 8-Queens problem as one where the aim is to find a state vector for which all pairs of queens do not attack each other. In this context, we could define our fitness function as evaluating the number of pairs of non-attacking queens for a given state and try to maximize this function."
},
{
"code": null,
"e": 7058,
"s": 6670,
"text": "This definition of the 8-Queens fitness function is different from that used by mlrose’s pre-defined Queens() class, so to use it, we will need to create a custom fitness function. This can be done by first defining a fitness function with a signature of the form fitness_fn(state, **kwargs), and then using mlrose’s CustomFitness() class to create a fitness function object, as follows:"
},
{
"code": null,
"e": 7317,
"s": 7058,
"text": "Once we have created a fitness function object, we can use it as an input into an optimization problem object. In mlrose, optimization problem objects are used to contain all of the important information about the optimization problem we are trying to solve."
},
{
"code": null,
"e": 7399,
"s": 7317,
"text": "mlrose provides classes for defining three types of optimization problem objects:"
},
{
"code": null,
"e": 7731,
"s": 7399,
"text": "DiscreteOpt(): This is used to describe discrete-state optimization problems. A discrete-state optimization problem is one where each element of the state vector can only take on a discrete set of values. In mlrose, these values are assumed to be integers in the range 0 to (max_val -1), where max_val is defined at initialization."
},
{
"code": null,
"e": 8052,
"s": 7731,
"text": "ContinuousOpt(): This is used to describe continuous-state optimization problems. Continuous-state optimization problems are similar to discrete-state optimization problems, except that each value in the state vector can take any value in the continuous range between min_val and max_val, as specified at initialization."
},
{
"code": null,
"e": 8424,
"s": 8052,
"text": "TSPOpt(): This is used to describe travelling salesperson (or tour) optimization problems. Travelling salesperson optimization problems differ from the previous two problem types in that we know the elements of the optimal state vector are the integers 0 to (n-1), where n is the length of the state vector, and our goal is to find the optimal ordering of those integers."
},
{
"code": null,
"e": 8599,
"s": 8424,
"text": "The 8-Queens problem is an example of a discrete-state optimization problem, since each of the elements of the state vector must take on an integer value in the range 0 to 7."
},
{
"code": null,
"e": 8930,
"s": 8599,
"text": "To initialize a discrete-state optimization problem object, it is necessary to specify the problem length (i.e. the length of the state vector, which is 8 in this case); max_val, as defined above (also 8); the fitness function object created in the previous step; and whether the problem is a maximization or minimization problem."
},
{
"code": null,
"e": 9065,
"s": 8930,
"text": "For this example, we will use the first of the two fitness function objects defined above, so we want to solve a minimization problem."
},
{
"code": null,
"e": 9187,
"s": 9065,
"text": "problem = mlrose.DiscreteOpt(length = 8, fitness_fn = fitness, maximize = False, max_val = 8)"
},
{
"code": null,
"e": 9468,
"s": 9187,
"text": "However, had we chosen to use the second (custom) fitness function object, we would be dealing with a maximization problem, so, in the above code, we would have to set the maximize parameter to True instead of False (in addition to changing the value of the fitness_fn parameter)."
},
{
"code": null,
"e": 9845,
"s": 9468,
"text": "Now that we have defined an optimization problem object, we are ready to solve our optimization problem. mlrose includes implementations of the (random-restart) hill climbing, randomized hill climbing (also known as stochastic hill climbing), simulated annealing, genetic algorithm and MIMIC (Mutual-Information-Maximizing Input Clustering) randomized optimization algorithms."
},
{
"code": null,
"e": 10028,
"s": 9845,
"text": "For discrete-state and travelling salesperson optimization problems, we can choose any of these algorithms. However, continuous-state problems are not supported in the case of MIMIC."
},
{
"code": null,
"e": 10567,
"s": 10028,
"text": "For our example, suppose we wish to use simulated annealing. To implement this algorithm, in addition to defining an optimization problem object, we must also define a schedule object (to specify how the simulated annealing temperature parameter changes over time); the number of attempts the algorithm should make to find a “better” state at each step (max_attempts); and the maximum number of iterations the algorithm should run for overall (max_iters). We can also specify the starting state for the algorithm, if desired (init_state)."
},
{
"code": null,
"e": 10845,
"s": 10567,
"text": "To specify the schedule object, mlrose includes pre-defined decay schedule classes for geometric, arithmetic and expontential decay, as well as a class for defining your own decay schedule in a manner similar to the way in which we created a customized fitness function object."
},
{
"code": null,
"e": 11174,
"s": 10845,
"text": "Suppose we wish to use an exponential decay schedule (with default parameter settings); make at most 10 attempts to find a “better” state at each algorithm step; limit ourselves to at most 1000 iterations of the algorithm; and start at an initial state of x = [0, 1, 2, 3, 4, 5, 6, 7]. This can be done using the following code."
},
{
"code": null,
"e": 11318,
"s": 11174,
"text": "The algorithm returns the best state it can find, given the parameter values it has been provided, as well as the fitness value for that state."
},
{
"code": null,
"e": 11400,
"s": 11318,
"text": "The best state found is: [6 4 7 3 6 2 5 1]The fitness at the best state is: 2.0"
},
{
"code": null,
"e": 11554,
"s": 11400,
"text": "Running this code gives us a good solution to the 8-Queens problem, but not the optimal solution. The solution found by the algorithm, is pictured below:"
},
{
"code": null,
"e": 11802,
"s": 11554,
"text": "The solution state has a fitness value of 2, indicating there are still two pairs of attacking queens on the chessboard (the queens in columns 0 and 3; and the two queens in row 6). Ideally, we would like our solution to have a fitness value of 0."
},
{
"code": null,
"e": 12041,
"s": 11802,
"text": "We can try to improve on our solution by tuning the parameters of our algorithm. Any of the algorithm’s parameters can be tuned. However, in this case, let’s focus on tuning the max_attempts parameter only, and increase it from 10 to 100."
},
{
"code": null,
"e": 12197,
"s": 12041,
"text": "This time when we run our code, we get a solution with a fitness value of 0, indicating that none of the queens on the chessboard are attacking each other."
},
{
"code": null,
"e": 12279,
"s": 12197,
"text": "The best state found is: [4 1 3 5 7 2 0 6]The fitness at the best state is: 0.0"
},
{
"code": null,
"e": 12307,
"s": 12279,
"text": "This can be verified below:"
},
{
"code": null,
"e": 12520,
"s": 12307,
"text": "In this tutorial we defined what is meant by an optimization problem and went through a simple example of how mlrose can be used to solve them. This is all you need to solve the majority of optimization problems."
},
{
"code": null,
"e": 12786,
"s": 12520,
"text": "However, there is one type of problem we have only briefly touched upon so far: the travelling salesperson optimization problem. In Part 2 of this tutorial we will go through an example of how mlrose can be used to solve this problem type. You can find Part 2 here."
}
] |
JavaScript Architecture Flux Components - GeeksforGeeks | 19 Jul, 2021
Flux: It is a JavaScript Architecture or pattern for UI which runs on a unidirectional data flow and has a centralized dispatcher. It is an application architecture designed to build client-side web apps. It is also one of the popular architectures that Facebook uses for building client-side web applications. The Flux architecture is based on the following components.
Four major components of Flux:
Dispatcher: It coordinates actions and updates to stores.Stores: It serves as a container for the app state and logicActions: It enables data passing to the dispatcherViews: It is the same as the view in MVC architecture but in the context of React components.
Dispatcher: It coordinates actions and updates to stores.
Stores: It serves as a container for the app state and logic
Actions: It enables data passing to the dispatcher
Views: It is the same as the view in MVC architecture but in the context of React components.
With simple words if we understand the whole then in Flux architecture basically suppose a user clicked on something, the view creates actions; Actions creates a new data and send it to the dispatcher, here comes the work of the dispatcher, the dispatcher dispatches the action results to the appropriate store. Then the store updates the state that is based upon the result and sends an update to the view.
Data in a flux application flows in a single direction, or we can say that data in a flux flow in a unidirectional flow, the significance of unidirectional flow is that since the data flows through your application in a single direction we can have better control over it.
Flow:
Action => Dispatcher => Store => View
The dispatcher is the central hub that manages all Data flow in a flux application, essentially a registry of callbacks into the stores having no intelligence of its own, or we can say that it is a simple mechanism for distributing the actions to the stores.
It is the epicenter of the data flow in any Flux application
It controls what flows into the stores of the Flux application.
It servers as the housing place for the callbacks that are created by the stores and which are linked to the dispatcher.
Each store in the application creates a callback that registers it with the dispatcher.
When an action creator sends a new action to the dispatcher, the dispatcher ensures that due to the callback provided all the registered stores get that action.
Note: The dispatcher is the ultimate arbiter of data dependencies.
Flux architecture is helpful for actions that included the effects of making the code clearer, updating other views, and debug by new developers. It also includes a singleton dispatcher and all actions are passing through the dispatcher. This design defends hard-to-debug cascading updates.
The store is the hub of the application’s state and logic, the role is similar to a model in a traditional MVC. It registers itself with the dispatcher and provides it with a callback, and this receives action as the parameter.
It contains the logic and state of the Flux application.
Instead of representing a single data structure like a traditional model, the store in Flux can actually represent the state of management of many objects.
It registers itself with a dispatcher and provides it with a callback.
The callback passed to have a parameter that is known as the action, passed to it via the dispatcher.
Note: Stores are where the state lives, and only stores themselves can change this state.
Flux architecture uses Stores to cache any applications associated with data or state. It includes multiple stores. It also has logical handling capabilities and flexibility to decide what parts of your data to show publicly.
When dispatcher exposes a method that allows us to trigger a dispatch to the stores, and to include a payload of data, which we call an action. Actions may also come from other places such as servers for example types data during initialization or when the server returns an error code or when the servers have updates to provide to the application.
Actions define the methods, which will be called by the view.
It is the form of data that has been dispatched to the stores.
The methods contain arguments, which contain further instructions on how the view wants to change the store.
The action is responsible for translating dispatch calls to events; which are understandable by the Stores.
Note: If it’s not an action, it can’t happen.
Actions in Flux architecture are collections of methods that are called within or inside views to send actions to the Dispatcher. It is one of the actual payloads that are delivered via the dispatcher. The action-type example typesets are used to define what action must occur and are sent along with the action data.
It’s not a technical part of Flux but at the same time, views are obviously a critical part of our application. It is mostly understood as the part of our architecture that’s responsible for displaying data to the user, It’s the last stop of our data flow architecture. Views exist outside of flux but are constrained by the unidirectional nature of Flux.
It is simply the composition of the components.
It is the part of the architecture that’s responsible for displaying data to the user.
The view layer is the layer where React fits into this architecture.
Note: The only way data-flows out of a view is by dispatching an action.
It is basically just a React Components that listens to changes events and retrieves applications’ state from stores hence pass that data down to their child components.
JavaScript-Questions
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n19 Jul, 2021"
},
{
"code": null,
"e": 26917,
"s": 26545,
"text": "Flux: It is a JavaScript Architecture or pattern for UI which runs on a unidirectional data flow and has a centralized dispatcher. It is an application architecture designed to build client-side web apps. It is also one of the popular architectures that Facebook uses for building client-side web applications. The Flux architecture is based on the following components."
},
{
"code": null,
"e": 26948,
"s": 26917,
"text": "Four major components of Flux:"
},
{
"code": null,
"e": 27209,
"s": 26948,
"text": "Dispatcher: It coordinates actions and updates to stores.Stores: It serves as a container for the app state and logicActions: It enables data passing to the dispatcherViews: It is the same as the view in MVC architecture but in the context of React components."
},
{
"code": null,
"e": 27267,
"s": 27209,
"text": "Dispatcher: It coordinates actions and updates to stores."
},
{
"code": null,
"e": 27328,
"s": 27267,
"text": "Stores: It serves as a container for the app state and logic"
},
{
"code": null,
"e": 27379,
"s": 27328,
"text": "Actions: It enables data passing to the dispatcher"
},
{
"code": null,
"e": 27473,
"s": 27379,
"text": "Views: It is the same as the view in MVC architecture but in the context of React components."
},
{
"code": null,
"e": 27881,
"s": 27473,
"text": "With simple words if we understand the whole then in Flux architecture basically suppose a user clicked on something, the view creates actions; Actions creates a new data and send it to the dispatcher, here comes the work of the dispatcher, the dispatcher dispatches the action results to the appropriate store. Then the store updates the state that is based upon the result and sends an update to the view."
},
{
"code": null,
"e": 28154,
"s": 27881,
"text": "Data in a flux application flows in a single direction, or we can say that data in a flux flow in a unidirectional flow, the significance of unidirectional flow is that since the data flows through your application in a single direction we can have better control over it."
},
{
"code": null,
"e": 28162,
"s": 28156,
"text": "Flow:"
},
{
"code": null,
"e": 28200,
"s": 28162,
"text": "Action => Dispatcher => Store => View"
},
{
"code": null,
"e": 28459,
"s": 28200,
"text": "The dispatcher is the central hub that manages all Data flow in a flux application, essentially a registry of callbacks into the stores having no intelligence of its own, or we can say that it is a simple mechanism for distributing the actions to the stores."
},
{
"code": null,
"e": 28520,
"s": 28459,
"text": "It is the epicenter of the data flow in any Flux application"
},
{
"code": null,
"e": 28584,
"s": 28520,
"text": "It controls what flows into the stores of the Flux application."
},
{
"code": null,
"e": 28705,
"s": 28584,
"text": "It servers as the housing place for the callbacks that are created by the stores and which are linked to the dispatcher."
},
{
"code": null,
"e": 28793,
"s": 28705,
"text": "Each store in the application creates a callback that registers it with the dispatcher."
},
{
"code": null,
"e": 28954,
"s": 28793,
"text": "When an action creator sends a new action to the dispatcher, the dispatcher ensures that due to the callback provided all the registered stores get that action."
},
{
"code": null,
"e": 29021,
"s": 28954,
"text": "Note: The dispatcher is the ultimate arbiter of data dependencies."
},
{
"code": null,
"e": 29312,
"s": 29021,
"text": "Flux architecture is helpful for actions that included the effects of making the code clearer, updating other views, and debug by new developers. It also includes a singleton dispatcher and all actions are passing through the dispatcher. This design defends hard-to-debug cascading updates."
},
{
"code": null,
"e": 29540,
"s": 29312,
"text": "The store is the hub of the application’s state and logic, the role is similar to a model in a traditional MVC. It registers itself with the dispatcher and provides it with a callback, and this receives action as the parameter."
},
{
"code": null,
"e": 29597,
"s": 29540,
"text": "It contains the logic and state of the Flux application."
},
{
"code": null,
"e": 29753,
"s": 29597,
"text": "Instead of representing a single data structure like a traditional model, the store in Flux can actually represent the state of management of many objects."
},
{
"code": null,
"e": 29824,
"s": 29753,
"text": "It registers itself with a dispatcher and provides it with a callback."
},
{
"code": null,
"e": 29926,
"s": 29824,
"text": "The callback passed to have a parameter that is known as the action, passed to it via the dispatcher."
},
{
"code": null,
"e": 30016,
"s": 29926,
"text": "Note: Stores are where the state lives, and only stores themselves can change this state."
},
{
"code": null,
"e": 30242,
"s": 30016,
"text": "Flux architecture uses Stores to cache any applications associated with data or state. It includes multiple stores. It also has logical handling capabilities and flexibility to decide what parts of your data to show publicly."
},
{
"code": null,
"e": 30592,
"s": 30242,
"text": "When dispatcher exposes a method that allows us to trigger a dispatch to the stores, and to include a payload of data, which we call an action. Actions may also come from other places such as servers for example types data during initialization or when the server returns an error code or when the servers have updates to provide to the application."
},
{
"code": null,
"e": 30654,
"s": 30592,
"text": "Actions define the methods, which will be called by the view."
},
{
"code": null,
"e": 30717,
"s": 30654,
"text": "It is the form of data that has been dispatched to the stores."
},
{
"code": null,
"e": 30826,
"s": 30717,
"text": "The methods contain arguments, which contain further instructions on how the view wants to change the store."
},
{
"code": null,
"e": 30934,
"s": 30826,
"text": "The action is responsible for translating dispatch calls to events; which are understandable by the Stores."
},
{
"code": null,
"e": 30980,
"s": 30934,
"text": "Note: If it’s not an action, it can’t happen."
},
{
"code": null,
"e": 31298,
"s": 30980,
"text": "Actions in Flux architecture are collections of methods that are called within or inside views to send actions to the Dispatcher. It is one of the actual payloads that are delivered via the dispatcher. The action-type example typesets are used to define what action must occur and are sent along with the action data."
},
{
"code": null,
"e": 31654,
"s": 31298,
"text": "It’s not a technical part of Flux but at the same time, views are obviously a critical part of our application. It is mostly understood as the part of our architecture that’s responsible for displaying data to the user, It’s the last stop of our data flow architecture. Views exist outside of flux but are constrained by the unidirectional nature of Flux."
},
{
"code": null,
"e": 31702,
"s": 31654,
"text": "It is simply the composition of the components."
},
{
"code": null,
"e": 31789,
"s": 31702,
"text": "It is the part of the architecture that’s responsible for displaying data to the user."
},
{
"code": null,
"e": 31858,
"s": 31789,
"text": "The view layer is the layer where React fits into this architecture."
},
{
"code": null,
"e": 31931,
"s": 31858,
"text": "Note: The only way data-flows out of a view is by dispatching an action."
},
{
"code": null,
"e": 32101,
"s": 31931,
"text": "It is basically just a React Components that listens to changes events and retrieves applications’ state from stores hence pass that data down to their child components."
},
{
"code": null,
"e": 32122,
"s": 32101,
"text": "JavaScript-Questions"
},
{
"code": null,
"e": 32133,
"s": 32122,
"text": "JavaScript"
},
{
"code": null,
"e": 32150,
"s": 32133,
"text": "Web Technologies"
},
{
"code": null,
"e": 32248,
"s": 32150,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32288,
"s": 32248,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32349,
"s": 32288,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 32390,
"s": 32349,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 32412,
"s": 32390,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 32466,
"s": 32412,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 32506,
"s": 32466,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 32539,
"s": 32506,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 32582,
"s": 32539,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 32632,
"s": 32582,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Count Subarrays with Consecutive elements differing by 1 - GeeksforGeeks | 07 May, 2021
Given an array arr[] of N integers. The task is to count the total number of subarrays of the given array such that difference between the consecutive elements in the subarrays is one. That is, for any index in the subarrays, arr[i+1] – arr[i] = 1.Note: Do not consider subarrays with single element.Examples:
Input : arr[] = {1, 2, 3}
Output : 3
The subarrays are {1, 2}. {2, 3} and {1, 2, 3}
Input : arr[] = {1, 2, 3, 5, 6, 7}
Output : 6
Naive Approach: A simple approach is to run two nested loops and check every subarray and calculate the count of subarrays with consecutive elements differing by 1.Efficient Approach: An efficient approach is to observe that in an array of length say K, total number of subarrays of size greater than 1 = (K)*(K-1)/2. So, the idea is to traverse the array by using two pointers to calculate subarrays with consecutive elements in a window of maximum length and then calculate all subarrays in that window using the above formula.Below is the step by step algorithm:
Take two pointers say fast and slow, for maintaining a window of consecutive elements.
Start traversing the array.
If elements differ by 1 increment only the fast pointer.
Else, calculate the length of current window between the indexes fast and slow.
Below is the implementation of the given approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ program to count Subarrays with// Consecutive elements differing by 1 #include <iostream>using namespace std; // Function to count Subarrays with// Consecutive elements differing by 1int subarrayCount(int arr[], int n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subarrayCount(arr, n); return 0;}
// Java program to count Subarrays with// Consecutive elements differing by 1class cfg{ // Function to count Subarrays with// Consecutive elements differing by 1static int subarrayCount(int arr[], int n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 5, 6, 7 }; int n = arr.length; System.out.println(subarrayCount(arr, n)); }}//This code is contributed by Mukul Singh
# Python3 program to count Subarrays with# Consecutive elements differing by 1 # Function to count Subarrays with# Consecutive elements differing by 1def subarrayCount(arr, n) : # Variable to store count of subarrays # whose consecutive elements differ by 1 result = 0 # Take two pointers for maintaining a # window of consecutive elements fast, slow = 0, 0 # Traverse the array for i in range(1, n) : # If elements differ by 1 # increment only the fast pointer if (arr[i] - arr[i - 1] == 1) : fast += 1 else : # Calculate length of subarray length = fast - slow + 1 # Calculate total subarrays except # Subarrays with single element result += length * (length - 1) // 2; # Update fast and slow fast = i slow = i # For last iteration. That is if array is # traversed and fast > slow if (fast != slow) : length = fast - slow + 1 result += length * (length - 1) // 2; return result # Driver Codeif __name__ == "__main__" : arr = [ 1, 2, 3, 5, 6, 7 ] n = len(arr) print(subarrayCount(arr, n)) # This code is contributed by Ryuga
// C# program to count Subarrays with// Consecutive elements differing by 1using System;class cfg{ // Function to count Subarrays with// Consecutive elements differing by 1static int subarrayCount(int []arr, int n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result;} // Driver Codepublic static void Main(){ int []arr = { 1, 2, 3, 5, 6, 7 }; int n = arr.Length; Console.WriteLine(subarrayCount(arr, n)); }}//This code is contributed by inder_verma..
<?php// PHP program to count Subarrays with// Consecutive elements differing by 1 // Function to count Subarrays with// Consecutive elements differing by 1function subarrayCount($arr, $n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 $result = 0; // Take two pointers for maintaining a // window of consecutive elements $fast = 0; $slow = 0; // Traverse the array for ($i = 1; $i < $n; $i++) { // If elements differ by 1 // increment only the fast pointer if ($arr[$i] - $arr[$i - 1] == 1) { $fast++; } else { // Calculate length of subarray $len = $fast - $slow + 1; // Calculate total subarrays except // Subarrays with single element $result += $len * ($len - 1) / 2; // Update fast and slow $fast = $i; $slow = $i; } } // For last iteration. That is if array // is traversed and fast > slow if ($fast != $slow) { $len = $fast - $slow + 1; $result += $len * ($len - 1) / 2; } return $result;} // Driver Code$arr = array(1, 2, 3, 5, 6, 7);$n = sizeof($arr); echo subarrayCount($arr, $n); // This code is contributed// by Akanksha Rai?>
<script> // Javascript program to count Subarrays with// Consecutive elements differing by 1 // Function to count Subarrays with // Consecutive elements differing by 1 function subarrayCount(arr , n) { // Variable to store count of subarrays // whose consecutive elements differ by 1 var result = 0; // Take two pointers for maintaining a // window of consecutive elements var fast = 0, slow = 0; // Traverse the array for (i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray var len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { var len = fast - slow + 1; result += len * (len - 1) / 2; } return result; } // Driver Code var arr = [ 1, 2, 3, 5, 6, 7 ]; var n = arr.length; document.write(subarrayCount(arr, n)); // This code contributed by aashish1995 </script>
6
Time Complexity: O(N) Auxiliary Space: (1)
ankthon
Akanksha_Rai
Code_Mech
inderDuMCA
aashish1995
array-traversal-question
subarray
Arrays
Arrays
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Chocolate Distribution Problem
Reversal algorithm for array rotation
Window Sliding Technique
Next Greater Element
Find duplicates in O(n) time and O(1) extra space | Set 1
Count pairs with given sum
Remove duplicates from sorted array
Find subarray with given sum | Set 1 (Nonnegative Numbers)
Building Heap from Array
Move all negative numbers to beginning and positive to end with constant extra space | [
{
"code": null,
"e": 26175,
"s": 26147,
"text": "\n07 May, 2021"
},
{
"code": null,
"e": 26487,
"s": 26175,
"text": "Given an array arr[] of N integers. The task is to count the total number of subarrays of the given array such that difference between the consecutive elements in the subarrays is one. That is, for any index in the subarrays, arr[i+1] – arr[i] = 1.Note: Do not consider subarrays with single element.Examples: "
},
{
"code": null,
"e": 26618,
"s": 26487,
"text": "Input : arr[] = {1, 2, 3}\nOutput : 3\nThe subarrays are {1, 2}. {2, 3} and {1, 2, 3}\n\nInput : arr[] = {1, 2, 3, 5, 6, 7}\nOutput : 6"
},
{
"code": null,
"e": 27188,
"s": 26620,
"text": "Naive Approach: A simple approach is to run two nested loops and check every subarray and calculate the count of subarrays with consecutive elements differing by 1.Efficient Approach: An efficient approach is to observe that in an array of length say K, total number of subarrays of size greater than 1 = (K)*(K-1)/2. So, the idea is to traverse the array by using two pointers to calculate subarrays with consecutive elements in a window of maximum length and then calculate all subarrays in that window using the above formula.Below is the step by step algorithm: "
},
{
"code": null,
"e": 27275,
"s": 27188,
"text": "Take two pointers say fast and slow, for maintaining a window of consecutive elements."
},
{
"code": null,
"e": 27303,
"s": 27275,
"text": "Start traversing the array."
},
{
"code": null,
"e": 27360,
"s": 27303,
"text": "If elements differ by 1 increment only the fast pointer."
},
{
"code": null,
"e": 27440,
"s": 27360,
"text": "Else, calculate the length of current window between the indexes fast and slow."
},
{
"code": null,
"e": 27493,
"s": 27440,
"text": "Below is the implementation of the given approach: "
},
{
"code": null,
"e": 27497,
"s": 27493,
"text": "C++"
},
{
"code": null,
"e": 27502,
"s": 27497,
"text": "Java"
},
{
"code": null,
"e": 27510,
"s": 27502,
"text": "Python3"
},
{
"code": null,
"e": 27513,
"s": 27510,
"text": "C#"
},
{
"code": null,
"e": 27517,
"s": 27513,
"text": "PHP"
},
{
"code": null,
"e": 27528,
"s": 27517,
"text": "Javascript"
},
{
"code": "// C++ program to count Subarrays with// Consecutive elements differing by 1 #include <iostream>using namespace std; // Function to count Subarrays with// Consecutive elements differing by 1int subarrayCount(int arr[], int n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 5, 6, 7 }; int n = sizeof(arr) / sizeof(arr[0]); cout << subarrayCount(arr, n); return 0;}",
"e": 28848,
"s": 27528,
"text": null
},
{
"code": "// Java program to count Subarrays with// Consecutive elements differing by 1class cfg{ // Function to count Subarrays with// Consecutive elements differing by 1static int subarrayCount(int arr[], int n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result;} // Driver Codepublic static void main(String[] args){ int arr[] = { 1, 2, 3, 5, 6, 7 }; int n = arr.length; System.out.println(subarrayCount(arr, n)); }}//This code is contributed by Mukul Singh",
"e": 30197,
"s": 28848,
"text": null
},
{
"code": "# Python3 program to count Subarrays with# Consecutive elements differing by 1 # Function to count Subarrays with# Consecutive elements differing by 1def subarrayCount(arr, n) : # Variable to store count of subarrays # whose consecutive elements differ by 1 result = 0 # Take two pointers for maintaining a # window of consecutive elements fast, slow = 0, 0 # Traverse the array for i in range(1, n) : # If elements differ by 1 # increment only the fast pointer if (arr[i] - arr[i - 1] == 1) : fast += 1 else : # Calculate length of subarray length = fast - slow + 1 # Calculate total subarrays except # Subarrays with single element result += length * (length - 1) // 2; # Update fast and slow fast = i slow = i # For last iteration. That is if array is # traversed and fast > slow if (fast != slow) : length = fast - slow + 1 result += length * (length - 1) // 2; return result # Driver Codeif __name__ == \"__main__\" : arr = [ 1, 2, 3, 5, 6, 7 ] n = len(arr) print(subarrayCount(arr, n)) # This code is contributed by Ryuga",
"e": 31437,
"s": 30197,
"text": null
},
{
"code": "// C# program to count Subarrays with// Consecutive elements differing by 1using System;class cfg{ // Function to count Subarrays with// Consecutive elements differing by 1static int subarrayCount(int []arr, int n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 int result = 0; // Take two pointers for maintaining a // window of consecutive elements int fast = 0, slow = 0; // Traverse the array for (int i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray int len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { int len = fast - slow + 1; result += len * (len - 1) / 2; } return result;} // Driver Codepublic static void Main(){ int []arr = { 1, 2, 3, 5, 6, 7 }; int n = arr.Length; Console.WriteLine(subarrayCount(arr, n)); }}//This code is contributed by inder_verma..",
"e": 32785,
"s": 31437,
"text": null
},
{
"code": "<?php// PHP program to count Subarrays with// Consecutive elements differing by 1 // Function to count Subarrays with// Consecutive elements differing by 1function subarrayCount($arr, $n){ // Variable to store count of subarrays // whose consecutive elements differ by 1 $result = 0; // Take two pointers for maintaining a // window of consecutive elements $fast = 0; $slow = 0; // Traverse the array for ($i = 1; $i < $n; $i++) { // If elements differ by 1 // increment only the fast pointer if ($arr[$i] - $arr[$i - 1] == 1) { $fast++; } else { // Calculate length of subarray $len = $fast - $slow + 1; // Calculate total subarrays except // Subarrays with single element $result += $len * ($len - 1) / 2; // Update fast and slow $fast = $i; $slow = $i; } } // For last iteration. That is if array // is traversed and fast > slow if ($fast != $slow) { $len = $fast - $slow + 1; $result += $len * ($len - 1) / 2; } return $result;} // Driver Code$arr = array(1, 2, 3, 5, 6, 7);$n = sizeof($arr); echo subarrayCount($arr, $n); // This code is contributed// by Akanksha Rai?>",
"e": 34085,
"s": 32785,
"text": null
},
{
"code": "<script> // Javascript program to count Subarrays with// Consecutive elements differing by 1 // Function to count Subarrays with // Consecutive elements differing by 1 function subarrayCount(arr , n) { // Variable to store count of subarrays // whose consecutive elements differ by 1 var result = 0; // Take two pointers for maintaining a // window of consecutive elements var fast = 0, slow = 0; // Traverse the array for (i = 1; i < n; i++) { // If elements differ by 1 // increment only the fast pointer if (arr[i] - arr[i - 1] == 1) { fast++; } else { // Calculate length of subarray var len = fast - slow + 1; // Calculate total subarrays except // Subarrays with single element result += len * (len - 1) / 2; // Update fast and slow fast = i; slow = i; } } // For last iteration. That is if array is // traversed and fast > slow if (fast != slow) { var len = fast - slow + 1; result += len * (len - 1) / 2; } return result; } // Driver Code var arr = [ 1, 2, 3, 5, 6, 7 ]; var n = arr.length; document.write(subarrayCount(arr, n)); // This code contributed by aashish1995 </script>",
"e": 35538,
"s": 34085,
"text": null
},
{
"code": null,
"e": 35540,
"s": 35538,
"text": "6"
},
{
"code": null,
"e": 35586,
"s": 35542,
"text": "Time Complexity: O(N) Auxiliary Space: (1) "
},
{
"code": null,
"e": 35594,
"s": 35586,
"text": "ankthon"
},
{
"code": null,
"e": 35607,
"s": 35594,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 35617,
"s": 35607,
"text": "Code_Mech"
},
{
"code": null,
"e": 35628,
"s": 35617,
"text": "inderDuMCA"
},
{
"code": null,
"e": 35640,
"s": 35628,
"text": "aashish1995"
},
{
"code": null,
"e": 35665,
"s": 35640,
"text": "array-traversal-question"
},
{
"code": null,
"e": 35674,
"s": 35665,
"text": "subarray"
},
{
"code": null,
"e": 35681,
"s": 35674,
"text": "Arrays"
},
{
"code": null,
"e": 35688,
"s": 35681,
"text": "Arrays"
},
{
"code": null,
"e": 35786,
"s": 35688,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35817,
"s": 35786,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 35855,
"s": 35817,
"text": "Reversal algorithm for array rotation"
},
{
"code": null,
"e": 35880,
"s": 35855,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 35901,
"s": 35880,
"text": "Next Greater Element"
},
{
"code": null,
"e": 35959,
"s": 35901,
"text": "Find duplicates in O(n) time and O(1) extra space | Set 1"
},
{
"code": null,
"e": 35986,
"s": 35959,
"text": "Count pairs with given sum"
},
{
"code": null,
"e": 36022,
"s": 35986,
"text": "Remove duplicates from sorted array"
},
{
"code": null,
"e": 36081,
"s": 36022,
"text": "Find subarray with given sum | Set 1 (Nonnegative Numbers)"
},
{
"code": null,
"e": 36106,
"s": 36081,
"text": "Building Heap from Array"
}
] |
Python | Join tuple elements in a list - GeeksforGeeks | 21 Feb, 2019
Now days, data is something that is backbone of any Machine Learning technique. The data can come in any form and its sometimes required to be extracted out to be processed. This article deals with the issue of extracting information which is present in tuples in list. Let’s discuss certain ways in which this can be performed.
Method #1 : Using join() + list comprehensionThe join function can be used to join each tuple elements with each other and list comprehension handles the task of iterating through the tuples.
# Python3 code to demonstrate # joining tuple elements# using join() + list comprehension # initializing tuple list test_list = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')] # printing original listprint ("The original list is : " + str(test_list)) # using join() + list comprehension# joining tuple elements res = [' '.join(tups) for tups in test_list] # printing result print ("The joined data is : " + str(res))
The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)]The joined data is : [‘geeks for geeks’, ‘computer science portal’]
Output :
Method #2 : Using map() + join()The functionality of list comprehension in the above method can also be done using the map function. This reduces the size of the code increasing its readability.
# Python3 code to demonstrate # joining tuple elements# using join() + map() # initializing tuple list test_list = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')] # printing original listprint ("The original list is : " + str(test_list)) # using join() + map()# joining tuple elements res = list(map(" ".join, test_list)) # printing result print ("The joined data is : " + str(res))
The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)]The joined data is : [‘geeks for geeks’, ‘computer science portal’]
Python list-programs
Python tuple-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
Enumerate() in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Convert a list to dictionary
How to print without newline in Python?
Python program to check whether a number is Prime or not | [
{
"code": null,
"e": 24390,
"s": 24362,
"text": "\n21 Feb, 2019"
},
{
"code": null,
"e": 24719,
"s": 24390,
"text": "Now days, data is something that is backbone of any Machine Learning technique. The data can come in any form and its sometimes required to be extracted out to be processed. This article deals with the issue of extracting information which is present in tuples in list. Let’s discuss certain ways in which this can be performed."
},
{
"code": null,
"e": 24911,
"s": 24719,
"text": "Method #1 : Using join() + list comprehensionThe join function can be used to join each tuple elements with each other and list comprehension handles the task of iterating through the tuples."
},
{
"code": "# Python3 code to demonstrate # joining tuple elements# using join() + list comprehension # initializing tuple list test_list = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')] # printing original listprint (\"The original list is : \" + str(test_list)) # using join() + list comprehension# joining tuple elements res = [' '.join(tups) for tups in test_list] # printing result print (\"The joined data is : \" + str(res))",
"e": 25360,
"s": 24911,
"text": null
},
{
"code": null,
"e": 25513,
"s": 25360,
"text": "The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)]The joined data is : [‘geeks for geeks’, ‘computer science portal’]"
},
{
"code": null,
"e": 25522,
"s": 25513,
"text": "Output :"
},
{
"code": null,
"e": 25718,
"s": 25522,
"text": " Method #2 : Using map() + join()The functionality of list comprehension in the above method can also be done using the map function. This reduces the size of the code increasing its readability."
},
{
"code": "# Python3 code to demonstrate # joining tuple elements# using join() + map() # initializing tuple list test_list = [('geeks', 'for', 'geeks'), ('computer', 'science', 'portal')] # printing original listprint (\"The original list is : \" + str(test_list)) # using join() + map()# joining tuple elements res = list(map(\" \".join, test_list)) # printing result print (\"The joined data is : \" + str(res))",
"e": 26133,
"s": 25718,
"text": null
},
{
"code": null,
"e": 26286,
"s": 26133,
"text": "The original list is : [(‘geeks’, ‘for’, ‘geeks’), (‘computer’, ‘science’, ‘portal’)]The joined data is : [‘geeks for geeks’, ‘computer science portal’]"
},
{
"code": null,
"e": 26307,
"s": 26286,
"text": "Python list-programs"
},
{
"code": null,
"e": 26329,
"s": 26307,
"text": "Python tuple-programs"
},
{
"code": null,
"e": 26336,
"s": 26329,
"text": "Python"
},
{
"code": null,
"e": 26352,
"s": 26336,
"text": "Python Programs"
},
{
"code": null,
"e": 26450,
"s": 26352,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26459,
"s": 26450,
"text": "Comments"
},
{
"code": null,
"e": 26472,
"s": 26459,
"text": "Old Comments"
},
{
"code": null,
"e": 26490,
"s": 26472,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26512,
"s": 26490,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26544,
"s": 26512,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26586,
"s": 26544,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26612,
"s": 26586,
"text": "Python String | replace()"
},
{
"code": null,
"e": 26634,
"s": 26612,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 26673,
"s": 26634,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 26711,
"s": 26673,
"text": "Python | Convert a list to dictionary"
},
{
"code": null,
"e": 26751,
"s": 26711,
"text": "How to print without newline in Python?"
}
] |
Merging only one file from a git branch (patching) | by Daniel Ellis | Towards Data Science | Say you have branches for different aspects of the same project and you want to merge only a single file (e.g. the configuration file). Short of copy-pasting all the changes by hand, how might you approach this problem?
So we have a branch. This branch contains an update, bug-fix or enchantment and we wish to pass that on to all our other branches. This can be for reasons that you want to keep a testing copy or share information between code that no longer has the same function between different parts of the same repository.
Here merging the entire body of code is impractical and overwriting the chosen file (e.g. with git checkout <branchname> <file> ) is counter-productive. So how else can we achieve such a feat? Well, the answer is simple and comes in the form of a --patch within git’s checkout function.
To start we begin by creating a new branch. This is good practice as it reduces the likeliness of something going wrong with our existing code.
git checkout -b mypatch
Next, we note down the branch name of our updated file and its location. This allows us to insert it into our current directory using
git checkout --patch fix_branch folder1/update.txt
If we forget to include the --patch argument the current file will be overwritten by that within the ‘fix_branch’.
After running the command our file is separated into sections (called husks). Here the changes (difference) within each section are shown and you are asked to decide what to do with them.
Although there are many available options, you only really need to know three to get started. These are:
y : Yes, implement all the changes shown
n : No, I want to keep the file as it is
e : Edit, I wish to pick which changes to keep
By default, the editor that will be opened is vim. Here we get the same segment of code displayed, but with an option to edit sections of it. For example, our files may have had the following change:
# this file only contains a staus- STATUS = idle+ STATUS = engaged
Here the local file has its status set as ‘idle’ when the updated version has it as ‘engaged’. The + and - signs denote that we wish to remove the line STATUS = idle and add the line STATUS = engaged to our text file.
If we want to keep the code that is being added, and/or removed we do not need to do anything but save the file.
If the updated file contains a line of code we do not wish to merge, we need to prefix the + sign with a # comment character. Anything prefixed with a # will not be merged into the file.
+ added change#+ ignored add change
If we do not wish to have a line of code removed, we need to replace the - sign with a whitespace character ' ' .
- removed line removed line (being kept)
It is worth noting that any edits to the file should be done after the merge and not within the hunks themselves. If you disrupt the formatting of a file you will get an error in the following format;
error: corrupt patch at line 74Your edited hunk does not apply. Edit again (saying “no” discards!) [y/n]? y
Here we have changed something on line 74 and need to redo the whole file again. If you are merging something with many changes — this gets frustrating and fast!
Once we have chosen which changes to keep, and which to discard, we can save our file ( escape the :wq in vim).
At this stage, it is important to review the changes and ensure the code works as it was originally intended.
Add ( git add -A ), commit ( git commit -m 'my merged file' ) and push ( git push ). In having updated our branch we now submit a pull request to update the original branch with our work, having just merged an individual file from another branch.
We can use git checkout for far more than simply changing branches. If we supply it with a branch name and a file, we can replace a corrupted or broken file. Instead, if we want to pass some of the changed content we can use the --patch flag to manually merge an individual file. Just remember not to make any changes until we have finished the merge. | [
{
"code": null,
"e": 391,
"s": 171,
"text": "Say you have branches for different aspects of the same project and you want to merge only a single file (e.g. the configuration file). Short of copy-pasting all the changes by hand, how might you approach this problem?"
},
{
"code": null,
"e": 702,
"s": 391,
"text": "So we have a branch. This branch contains an update, bug-fix or enchantment and we wish to pass that on to all our other branches. This can be for reasons that you want to keep a testing copy or share information between code that no longer has the same function between different parts of the same repository."
},
{
"code": null,
"e": 989,
"s": 702,
"text": "Here merging the entire body of code is impractical and overwriting the chosen file (e.g. with git checkout <branchname> <file> ) is counter-productive. So how else can we achieve such a feat? Well, the answer is simple and comes in the form of a --patch within git’s checkout function."
},
{
"code": null,
"e": 1133,
"s": 989,
"text": "To start we begin by creating a new branch. This is good practice as it reduces the likeliness of something going wrong with our existing code."
},
{
"code": null,
"e": 1157,
"s": 1133,
"text": "git checkout -b mypatch"
},
{
"code": null,
"e": 1291,
"s": 1157,
"text": "Next, we note down the branch name of our updated file and its location. This allows us to insert it into our current directory using"
},
{
"code": null,
"e": 1342,
"s": 1291,
"text": "git checkout --patch fix_branch folder1/update.txt"
},
{
"code": null,
"e": 1457,
"s": 1342,
"text": "If we forget to include the --patch argument the current file will be overwritten by that within the ‘fix_branch’."
},
{
"code": null,
"e": 1645,
"s": 1457,
"text": "After running the command our file is separated into sections (called husks). Here the changes (difference) within each section are shown and you are asked to decide what to do with them."
},
{
"code": null,
"e": 1750,
"s": 1645,
"text": "Although there are many available options, you only really need to know three to get started. These are:"
},
{
"code": null,
"e": 1791,
"s": 1750,
"text": "y : Yes, implement all the changes shown"
},
{
"code": null,
"e": 1832,
"s": 1791,
"text": "n : No, I want to keep the file as it is"
},
{
"code": null,
"e": 1879,
"s": 1832,
"text": "e : Edit, I wish to pick which changes to keep"
},
{
"code": null,
"e": 2079,
"s": 1879,
"text": "By default, the editor that will be opened is vim. Here we get the same segment of code displayed, but with an option to edit sections of it. For example, our files may have had the following change:"
},
{
"code": null,
"e": 2146,
"s": 2079,
"text": "# this file only contains a staus- STATUS = idle+ STATUS = engaged"
},
{
"code": null,
"e": 2364,
"s": 2146,
"text": "Here the local file has its status set as ‘idle’ when the updated version has it as ‘engaged’. The + and - signs denote that we wish to remove the line STATUS = idle and add the line STATUS = engaged to our text file."
},
{
"code": null,
"e": 2477,
"s": 2364,
"text": "If we want to keep the code that is being added, and/or removed we do not need to do anything but save the file."
},
{
"code": null,
"e": 2664,
"s": 2477,
"text": "If the updated file contains a line of code we do not wish to merge, we need to prefix the + sign with a # comment character. Anything prefixed with a # will not be merged into the file."
},
{
"code": null,
"e": 2700,
"s": 2664,
"text": "+ added change#+ ignored add change"
},
{
"code": null,
"e": 2814,
"s": 2700,
"text": "If we do not wish to have a line of code removed, we need to replace the - sign with a whitespace character ' ' ."
},
{
"code": null,
"e": 2856,
"s": 2814,
"text": "- removed line removed line (being kept)"
},
{
"code": null,
"e": 3057,
"s": 2856,
"text": "It is worth noting that any edits to the file should be done after the merge and not within the hunks themselves. If you disrupt the formatting of a file you will get an error in the following format;"
},
{
"code": null,
"e": 3165,
"s": 3057,
"text": "error: corrupt patch at line 74Your edited hunk does not apply. Edit again (saying “no” discards!) [y/n]? y"
},
{
"code": null,
"e": 3327,
"s": 3165,
"text": "Here we have changed something on line 74 and need to redo the whole file again. If you are merging something with many changes — this gets frustrating and fast!"
},
{
"code": null,
"e": 3439,
"s": 3327,
"text": "Once we have chosen which changes to keep, and which to discard, we can save our file ( escape the :wq in vim)."
},
{
"code": null,
"e": 3549,
"s": 3439,
"text": "At this stage, it is important to review the changes and ensure the code works as it was originally intended."
},
{
"code": null,
"e": 3796,
"s": 3549,
"text": "Add ( git add -A ), commit ( git commit -m 'my merged file' ) and push ( git push ). In having updated our branch we now submit a pull request to update the original branch with our work, having just merged an individual file from another branch."
}
] |
Python MySQL - Update Query - GeeksforGeeks | 09 Mar, 2020
A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server.
The update is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table.The basic advantage provided by this command is that it keeps the table accurate.
Syntax:
UPDATE tablename
SET ="new value"
WHERE ="old value";
The following programs will help you understand this better.DATABASE IN USE:
Example 1: Program to update the age of student named Rishi Kumar.
# Python program to demonstrate# update clause import mysql.connector # Connecting to the Databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # drop clausestatement ="UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'" cs.execute(statement)mydb.commit() # Disconnecting from the databasemydb.close()
Output:
Example 2: Program to correct the spelling of an Student named SK
# Python program to demonstrate# update clause import mysql.connector # Connecting to the Databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # drop clausestatement ="UPDATE STUDENT SET Name = 'S.K. Anirban' WHERE Name ='SK Anirban'" cs.execute(statement)mydb.commit() # Disconnecting from the databasemydb.close()
Output:
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Enumerate() in Python
Iterate over a list in Python
Python String | replace() | [
{
"code": null,
"e": 41614,
"s": 41586,
"text": "\n09 Mar, 2020"
},
{
"code": null,
"e": 41876,
"s": 41614,
"text": "A connector is employed when we have to use MySQL with other programming languages. The work of MySQL-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server."
},
{
"code": null,
"e": 42144,
"s": 41876,
"text": "The update is used to change the existing values in a database. By using update a specific value can be corrected or updated. It only affects the data and not the structure of the table.The basic advantage provided by this command is that it keeps the table accurate."
},
{
"code": null,
"e": 42152,
"s": 42144,
"text": "Syntax:"
},
{
"code": null,
"e": 42207,
"s": 42152,
"text": "UPDATE tablename\nSET =\"new value\"\nWHERE =\"old value\";\n"
},
{
"code": null,
"e": 42284,
"s": 42207,
"text": "The following programs will help you understand this better.DATABASE IN USE:"
},
{
"code": null,
"e": 42351,
"s": 42284,
"text": "Example 1: Program to update the age of student named Rishi Kumar."
},
{
"code": "# Python program to demonstrate# update clause import mysql.connector # Connecting to the Databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # drop clausestatement =\"UPDATE STUDENT SET AGE = 23 WHERE Name ='Rishi Kumar'\" cs.execute(statement)mydb.commit() # Disconnecting from the databasemydb.close()",
"e": 42727,
"s": 42351,
"text": null
},
{
"code": null,
"e": 42735,
"s": 42727,
"text": "Output:"
},
{
"code": null,
"e": 42801,
"s": 42735,
"text": "Example 2: Program to correct the spelling of an Student named SK"
},
{
"code": "# Python program to demonstrate# update clause import mysql.connector # Connecting to the Databasemydb = mysql.connector.connect( host ='localhost', database ='College', user ='root',) cs = mydb.cursor() # drop clausestatement =\"UPDATE STUDENT SET Name = 'S.K. Anirban' WHERE Name ='SK Anirban'\" cs.execute(statement)mydb.commit() # Disconnecting from the databasemydb.close()",
"e": 43189,
"s": 42801,
"text": null
},
{
"code": null,
"e": 43197,
"s": 43189,
"text": "Output:"
},
{
"code": null,
"e": 43210,
"s": 43197,
"text": "Python-mySQL"
},
{
"code": null,
"e": 43217,
"s": 43210,
"text": "Python"
},
{
"code": null,
"e": 43315,
"s": 43217,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 43343,
"s": 43315,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 43393,
"s": 43343,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 43415,
"s": 43393,
"text": "Python map() function"
},
{
"code": null,
"e": 43459,
"s": 43415,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 43494,
"s": 43459,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 43526,
"s": 43494,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 43568,
"s": 43526,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 43590,
"s": 43568,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 43620,
"s": 43590,
"text": "Iterate over a list in Python"
}
] |
CSS | Pseudo Elements - GeeksforGeeks | 12 Sep, 2021
A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected elements. For Example, Styling the first letter or line of an element,
Insert content before or after the content of an element. All of these can be done using Pseudo Elements in CSS.
Note that in contrast to pseudo-elements, pseudo-classes can be used to style an element based on its state.
Syntax:
selector::pseudo-element {
property: value;
}
There are many Pseudo Elements in CSS but the ones which are most commonly used are as follows:
::first-line Pseudo-element applies styles to the first line of a block-level element. Note that the length of the first line depends on many factors, including the width of the element, the width of the document, and the font size of the text. Note that only a few properties are applied for first-line pseudo-element like font properties, color properties, background properties, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height, clear, etc.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>first-line Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::first-line{ color:Red; font-weight: bold; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::first-line element</h2> <p>This is a paragraph using first-line pseudo-element to style first line of the paragraph.Content in the first line turns red and becomes bold.</p> </body></html>
Output:
::first-letter Pseudo-element applies styles to the first letter of the first line of a block-level element, but only when not preceded by other content (such as images or inline tables). Note that only a few properties are applied for first-line pseudo-element like font properties, color properties, background properties, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height, clear, etc.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>first-letter Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::first-letter{ color:Red; font-size: 30px; font-weight: bold; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::first-letter element</h2> <p>This is a paragraph using first-letter pseudo-element to style first letter of the paragraph.first-letter element turned the first letter of this paragraph to red and made it bold.</p> </body></html>
Output:
::before Pseudo-element creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>before Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::before{ content: '"'; color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::before element</h2> <p>This is a paragraph to which we added red color quotation marks using ::before element.</p> </body></html>
Output:
::after Pseudo-element creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>after Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::after{ content: '"'; color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::after element</h2> <p>This is a paragraph to which we added red color quotation marks using ::after element.</p> </body></html>
Output:
::marker Pseudo-element selects the marker box of a list item, which typically contains a bullet or number. It works on any element or pseudo-element set to display: list-item, such as the <li> and <summary> elements.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>marker Demo</title> <style> body{ background-color: whitesmoke; color: green; text-align: center; } ul{ width: 40px; } ul li::marker{ color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::marker element</h2> <ul> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> </ul></body></html>
Output:
::selection Pseudo-element applies styles to the part of a document that has been highlighted by the user such as clicking and dragging the mouse across the text.
Example:
HTML
<!DOCTYPE html><html lang="en"><head> <title>selection Demo</title> <style> body{ background-color: whitesmoke; color: green; text-align: center; } p::selection{ color: red; background-color: green; font-size: 30px; } ::selection{ color: green; background-color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::selection element</h2> <p>Content in this paragraph turns red with green background on selection.</p> <span>As this is not a paragraph, you can notice red background and green text on selection.</span></body></html>
Output:
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
vidyasagar4069
sweetyty
CSS-Basics
CSS
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to create footer to stay at the bottom of a Web page?
How to update Node.js and NPM to next version ?
CSS to put icon inside an input element in a form
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to set the default value for an HTML <select> element ?
How to update Node.js and NPM to next version ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 29401,
"s": 29373,
"text": "\n12 Sep, 2021"
},
{
"code": null,
"e": 29578,
"s": 29401,
"text": "A CSS pseudo-element is a keyword added to a selector that lets you style a specific part of the selected elements. For Example, Styling the first letter or line of an element,"
},
{
"code": null,
"e": 29691,
"s": 29578,
"text": "Insert content before or after the content of an element. All of these can be done using Pseudo Elements in CSS."
},
{
"code": null,
"e": 29800,
"s": 29691,
"text": "Note that in contrast to pseudo-elements, pseudo-classes can be used to style an element based on its state."
},
{
"code": null,
"e": 29809,
"s": 29800,
"text": "Syntax: "
},
{
"code": null,
"e": 29856,
"s": 29809,
"text": "selector::pseudo-element {\n property: value;\n}"
},
{
"code": null,
"e": 29952,
"s": 29856,
"text": "There are many Pseudo Elements in CSS but the ones which are most commonly used are as follows:"
},
{
"code": null,
"e": 30438,
"s": 29952,
"text": "::first-line Pseudo-element applies styles to the first line of a block-level element. Note that the length of the first line depends on many factors, including the width of the element, the width of the document, and the font size of the text. Note that only a few properties are applied for first-line pseudo-element like font properties, color properties, background properties, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height, clear, etc."
},
{
"code": null,
"e": 30447,
"s": 30438,
"text": "Example:"
},
{
"code": null,
"e": 30452,
"s": 30447,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>first-line Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::first-line{ color:Red; font-weight: bold; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::first-line element</h2> <p>This is a paragraph using first-line pseudo-element to style first line of the paragraph.Content in the first line turns red and becomes bold.</p> </body></html>",
"e": 31022,
"s": 30452,
"text": null
},
{
"code": null,
"e": 31030,
"s": 31022,
"text": "Output:"
},
{
"code": null,
"e": 31459,
"s": 31030,
"text": "::first-letter Pseudo-element applies styles to the first letter of the first line of a block-level element, but only when not preceded by other content (such as images or inline tables). Note that only a few properties are applied for first-line pseudo-element like font properties, color properties, background properties, word-spacing, letter-spacing, text-decoration, vertical-align, text-transform, line-height, clear, etc."
},
{
"code": null,
"e": 31468,
"s": 31459,
"text": "Example:"
},
{
"code": null,
"e": 31473,
"s": 31468,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>first-letter Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::first-letter{ color:Red; font-size: 30px; font-weight: bold; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::first-letter element</h2> <p>This is a paragraph using first-letter pseudo-element to style first letter of the paragraph.first-letter element turned the first letter of this paragraph to red and made it bold.</p> </body></html>",
"e": 32111,
"s": 31473,
"text": null
},
{
"code": null,
"e": 32119,
"s": 32111,
"text": "Output:"
},
{
"code": null,
"e": 32324,
"s": 32119,
"text": "::before Pseudo-element creates a pseudo-element that is the first child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default."
},
{
"code": null,
"e": 32333,
"s": 32324,
"text": "Example:"
},
{
"code": null,
"e": 32338,
"s": 32333,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>before Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::before{ content: '\"'; color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::before element</h2> <p>This is a paragraph to which we added red color quotation marks using ::before element.</p> </body></html>",
"e": 32851,
"s": 32338,
"text": null
},
{
"code": null,
"e": 32859,
"s": 32851,
"text": "Output:"
},
{
"code": null,
"e": 33062,
"s": 32859,
"text": "::after Pseudo-element creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default."
},
{
"code": null,
"e": 33071,
"s": 33062,
"text": "Example:"
},
{
"code": null,
"e": 33076,
"s": 33071,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>after Demo</title> <style> body{ background-color:whitesmoke; color:green; font-size: large; text-align: center; } p::after{ content: '\"'; color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::after element</h2> <p>This is a paragraph to which we added red color quotation marks using ::after element.</p> </body></html>",
"e": 33591,
"s": 33076,
"text": null
},
{
"code": null,
"e": 33599,
"s": 33591,
"text": "Output:"
},
{
"code": null,
"e": 33817,
"s": 33599,
"text": "::marker Pseudo-element selects the marker box of a list item, which typically contains a bullet or number. It works on any element or pseudo-element set to display: list-item, such as the <li> and <summary> elements."
},
{
"code": null,
"e": 33826,
"s": 33817,
"text": "Example:"
},
{
"code": null,
"e": 33831,
"s": 33826,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>marker Demo</title> <style> body{ background-color: whitesmoke; color: green; text-align: center; } ul{ width: 40px; } ul li::marker{ color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::marker element</h2> <ul> <li>HTML</li> <li>CSS</li> <li>JavaScript</li> </ul></body></html>",
"e": 34324,
"s": 33831,
"text": null
},
{
"code": null,
"e": 34333,
"s": 34324,
"text": "Output: "
},
{
"code": null,
"e": 34496,
"s": 34333,
"text": "::selection Pseudo-element applies styles to the part of a document that has been highlighted by the user such as clicking and dragging the mouse across the text."
},
{
"code": null,
"e": 34505,
"s": 34496,
"text": "Example:"
},
{
"code": null,
"e": 34510,
"s": 34505,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"><head> <title>selection Demo</title> <style> body{ background-color: whitesmoke; color: green; text-align: center; } p::selection{ color: red; background-color: green; font-size: 30px; } ::selection{ color: green; background-color: red; font-size: 30px; } </style></head><body> <h1>Geeks For Geeks</h1> <h2>::selection element</h2> <p>Content in this paragraph turns red with green background on selection.</p> <span>As this is not a paragraph, you can notice red background and green text on selection.</span></body></html>",
"e": 35242,
"s": 34510,
"text": null
},
{
"code": null,
"e": 35250,
"s": 35242,
"text": "Output:"
},
{
"code": null,
"e": 35387,
"s": 35250,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 35402,
"s": 35387,
"text": "vidyasagar4069"
},
{
"code": null,
"e": 35411,
"s": 35402,
"text": "sweetyty"
},
{
"code": null,
"e": 35422,
"s": 35411,
"text": "CSS-Basics"
},
{
"code": null,
"e": 35426,
"s": 35422,
"text": "CSS"
},
{
"code": null,
"e": 35431,
"s": 35426,
"text": "HTML"
},
{
"code": null,
"e": 35448,
"s": 35431,
"text": "Web Technologies"
},
{
"code": null,
"e": 35453,
"s": 35448,
"text": "HTML"
},
{
"code": null,
"e": 35551,
"s": 35453,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35601,
"s": 35551,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35663,
"s": 35601,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35721,
"s": 35663,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 35769,
"s": 35721,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 35819,
"s": 35769,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 35869,
"s": 35819,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 35931,
"s": 35869,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 35991,
"s": 35931,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 36039,
"s": 35991,
"text": "How to update Node.js and NPM to next version ?"
}
] |
PyQt efficiently works with relational databases. No SQL queries needed. | Towards Data Science | Python is an easy-to-learn and powerful programming language.
You can get sophisticated outputs, and compared to other languages, you’ll need to write significantly fewer lines of code.
However, when it comes to GUI application development, you can experience difficulties. Especially when you need to work with huge datasets.
This article is part of PyQt & Relational Databases Series:
Stefan Melo
If you’d like to read more content like this, become a member:
melo-stefan.medium.com
Or you can subscribe to my newsletter below. Thank you.
The first issue with GUI in python is the proper framework to choose.
For database applications, I strongly recommend PyQt. It saves a vast amount of boilerplate code, and its database support is extensive.
For this purpose, I’ve tried to avoid third-party module imports as much as possible. The most important advantage of this approach is code independence when it comes to package updates.
Thus maintenance is being reduced significantly. The only package, outside of python’s internal modules, needed here is PyQt.
Note: I assume you are familiar with
PyQt installation
Basic usage of the framework
SQLite databases
Basics of relational databases
It’s essential to understand that a relational database consists of at least two tables, which is the simplest case. To avoid our example look boring, we’ll have three tables.
Relational database groups data into tables based on specific criteria. Some tables can relate to each other; they are linked together.
These links are based on shared data. Instead of challenging definitions, let’s see an example of related tables.
To maintain simplicity, we’ll use the SQLite database. There are multiple rationales behind this decision.
SQLite is a fast, small, self-contained, highly reliable, and full-featured SQL database engine.
The database is stored in a single disc file. It’s accessible to everyone for any purpose, and thesqlite3 module is python’s in-built module.
We create the main table ‘orders’ with some data:
Now, we have an elementary order booking system to play with. The table is hideous since it contains non-human-readable values. Yes, indeed!
AlthoughOrderID, Customer_id, and Product_id values make sense — they’re ids, there are the same weird values in column Price as in column Product_id.
It’s not an accident. The Price value in table orders is not an actual price. It’s a reference to Product_id in theproducts table. It’s the developer’s responsibility to assign the Product_id value to Price whenever the Product_id changes.
We also have customers and products tables, as shown below. These tables hold the information (values) needed for the orders table.
Let’s start coding now. First, we import the inevitable modules.
import sysfrom PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox, QTableViewfrom PyQt6.QtSql import QSqlDatabase, QSqlRelation, QSqlRelationalTableModel
Here I’d like to note that I use PyQt6. However, the code will work with PyQt5 without any issues.
Next, we’ll include the typical code snippet needed for the PyQt application to run. Nothing special.
if __name__ == "__main__": app = QApplication(sys.argv) form = MainWindow() form.show() app.exec()
Here we created app, an instance of PyQt QApplication class, form which is an instance of MainWindow class; we’ll create it later.
We make sure the form will show, and we execute the app.
Next, we’ll create a function createConnection() which returns a boolean value.
The function will handle the database connection and returns True when everything is correct, and the database connection is stable.
# Type hint for return valuedef createConnection() -> bool: # SQLite type database connection instance con = QSqlDatabase.addDatabase('QSQLITE') # Connect to the database file con.setDatabaseName('testDB.db') # Show message box when there is a connection issue if not con.open(): QMessageBox.critical( None, 'QTableView Example - Error!', 'Database Error: %s' % con.lastError().databaseText(), ) return False return True
We don’t want the application to start without a proper database connection.
The best moment to validate the link is before GUI fully starts. So we have to modify the application initialization code above.
if __name__ == "__main__": app = QApplication(sys.argv) if not createConnection(): sys.exit(1) form = MainWindow() form.show() app.exec()
It’s time to code our desired GUI for convenient data presentation.
We’ve already prepared our main form (window) of the application. You can see above form = MainWindow(), the MainWindow class instance named form. Nevertheless, we still don’t have the MainWindow class!
We’ll do something about it right now. This is the most appealing part.
I can reveal now that we’ll be using the QTableView widget. It’s capable of the magic we need.
# Inherit from QMainWindowclass MainWindow(QMainWindow): def __init__(self, parent = None): super().__init__(parent) # Set the window title self.setWindowTitle('QTable Example') # Create the model model = QSqlRelationalTableModel(self) # Set the table to display model.setTable('orders') # Set relations for related columns to be displayed model.setRelation(1, QSqlRelation('products', 'ProductID', 'Price')) model.setRelation(2, QSqlRelation('customers', 'CustomerID', 'Customer')) model.setRelation(3, QSqlRelation('products', 'ProductID', 'Product')) model.select() # Setup the view # Create the view = a table widget view = QTableView(self) # Set the data model for table widget view.setModel(model) # Adjust column widths to their content view.resizeColumnsToContents() # Add the widget to main window self.setCentralWidget(view)
The code above shows the whole application GUI setup. Comments explain the details of every step.
However, I’d like to clarify and analyze the model’s setRelation() method and use of the QSqlRelation object.
Let’s see what we’ve done here except lines linked to GUI itself. We’ll focus on our data model.
PyQt includes several model objects we can use effectively. In a view, we work with a relational table; the SqlRelationalTableModel class fits entirely. The model we’ll use does all the hard work we need.
The setRelation() method requires two arguments: column and relation. The method specifies that the column (a foreign key) has its behavior defined by relation object.
Let’s take the first case as an example:
model.setTable(‘orders’) model.setRelation(1, QSqlRelation('products', 'ProductID', 'Price'))
The behavior is that column 1 in table orders maps with field ProductID of table customers, and the view should present the customers’ Customer field to the user.
Using the QSqlRelationalTableModel, we gracefully avoided SQL language knowledge and other boilerplate code for constructing complex SQL queries.
Next, we’ll make our table widget more engaging. | [
{
"code": null,
"e": 234,
"s": 172,
"text": "Python is an easy-to-learn and powerful programming language."
},
{
"code": null,
"e": 358,
"s": 234,
"text": "You can get sophisticated outputs, and compared to other languages, you’ll need to write significantly fewer lines of code."
},
{
"code": null,
"e": 499,
"s": 358,
"text": "However, when it comes to GUI application development, you can experience difficulties. Especially when you need to work with huge datasets."
},
{
"code": null,
"e": 559,
"s": 499,
"text": "This article is part of PyQt & Relational Databases Series:"
},
{
"code": null,
"e": 571,
"s": 559,
"text": "Stefan Melo"
},
{
"code": null,
"e": 634,
"s": 571,
"text": "If you’d like to read more content like this, become a member:"
},
{
"code": null,
"e": 657,
"s": 634,
"text": "melo-stefan.medium.com"
},
{
"code": null,
"e": 713,
"s": 657,
"text": "Or you can subscribe to my newsletter below. Thank you."
},
{
"code": null,
"e": 783,
"s": 713,
"text": "The first issue with GUI in python is the proper framework to choose."
},
{
"code": null,
"e": 920,
"s": 783,
"text": "For database applications, I strongly recommend PyQt. It saves a vast amount of boilerplate code, and its database support is extensive."
},
{
"code": null,
"e": 1107,
"s": 920,
"text": "For this purpose, I’ve tried to avoid third-party module imports as much as possible. The most important advantage of this approach is code independence when it comes to package updates."
},
{
"code": null,
"e": 1233,
"s": 1107,
"text": "Thus maintenance is being reduced significantly. The only package, outside of python’s internal modules, needed here is PyQt."
},
{
"code": null,
"e": 1270,
"s": 1233,
"text": "Note: I assume you are familiar with"
},
{
"code": null,
"e": 1288,
"s": 1270,
"text": "PyQt installation"
},
{
"code": null,
"e": 1317,
"s": 1288,
"text": "Basic usage of the framework"
},
{
"code": null,
"e": 1334,
"s": 1317,
"text": "SQLite databases"
},
{
"code": null,
"e": 1365,
"s": 1334,
"text": "Basics of relational databases"
},
{
"code": null,
"e": 1541,
"s": 1365,
"text": "It’s essential to understand that a relational database consists of at least two tables, which is the simplest case. To avoid our example look boring, we’ll have three tables."
},
{
"code": null,
"e": 1677,
"s": 1541,
"text": "Relational database groups data into tables based on specific criteria. Some tables can relate to each other; they are linked together."
},
{
"code": null,
"e": 1791,
"s": 1677,
"text": "These links are based on shared data. Instead of challenging definitions, let’s see an example of related tables."
},
{
"code": null,
"e": 1898,
"s": 1791,
"text": "To maintain simplicity, we’ll use the SQLite database. There are multiple rationales behind this decision."
},
{
"code": null,
"e": 1995,
"s": 1898,
"text": "SQLite is a fast, small, self-contained, highly reliable, and full-featured SQL database engine."
},
{
"code": null,
"e": 2137,
"s": 1995,
"text": "The database is stored in a single disc file. It’s accessible to everyone for any purpose, and thesqlite3 module is python’s in-built module."
},
{
"code": null,
"e": 2187,
"s": 2137,
"text": "We create the main table ‘orders’ with some data:"
},
{
"code": null,
"e": 2328,
"s": 2187,
"text": "Now, we have an elementary order booking system to play with. The table is hideous since it contains non-human-readable values. Yes, indeed!"
},
{
"code": null,
"e": 2479,
"s": 2328,
"text": "AlthoughOrderID, Customer_id, and Product_id values make sense — they’re ids, there are the same weird values in column Price as in column Product_id."
},
{
"code": null,
"e": 2719,
"s": 2479,
"text": "It’s not an accident. The Price value in table orders is not an actual price. It’s a reference to Product_id in theproducts table. It’s the developer’s responsibility to assign the Product_id value to Price whenever the Product_id changes."
},
{
"code": null,
"e": 2851,
"s": 2719,
"text": "We also have customers and products tables, as shown below. These tables hold the information (values) needed for the orders table."
},
{
"code": null,
"e": 2916,
"s": 2851,
"text": "Let’s start coding now. First, we import the inevitable modules."
},
{
"code": null,
"e": 3081,
"s": 2916,
"text": "import sysfrom PyQt6.QtWidgets import QApplication, QMainWindow, QMessageBox, QTableViewfrom PyQt6.QtSql import QSqlDatabase, QSqlRelation, QSqlRelationalTableModel"
},
{
"code": null,
"e": 3180,
"s": 3081,
"text": "Here I’d like to note that I use PyQt6. However, the code will work with PyQt5 without any issues."
},
{
"code": null,
"e": 3282,
"s": 3180,
"text": "Next, we’ll include the typical code snippet needed for the PyQt application to run. Nothing special."
},
{
"code": null,
"e": 3393,
"s": 3282,
"text": "if __name__ == \"__main__\": app = QApplication(sys.argv) form = MainWindow() form.show() app.exec()"
},
{
"code": null,
"e": 3524,
"s": 3393,
"text": "Here we created app, an instance of PyQt QApplication class, form which is an instance of MainWindow class; we’ll create it later."
},
{
"code": null,
"e": 3581,
"s": 3524,
"text": "We make sure the form will show, and we execute the app."
},
{
"code": null,
"e": 3661,
"s": 3581,
"text": "Next, we’ll create a function createConnection() which returns a boolean value."
},
{
"code": null,
"e": 3794,
"s": 3661,
"text": "The function will handle the database connection and returns True when everything is correct, and the database connection is stable."
},
{
"code": null,
"e": 4295,
"s": 3794,
"text": "# Type hint for return valuedef createConnection() -> bool: # SQLite type database connection instance con = QSqlDatabase.addDatabase('QSQLITE') # Connect to the database file con.setDatabaseName('testDB.db') # Show message box when there is a connection issue if not con.open(): QMessageBox.critical( None, 'QTableView Example - Error!', 'Database Error: %s' % con.lastError().databaseText(), ) return False return True"
},
{
"code": null,
"e": 4372,
"s": 4295,
"text": "We don’t want the application to start without a proper database connection."
},
{
"code": null,
"e": 4501,
"s": 4372,
"text": "The best moment to validate the link is before GUI fully starts. So we have to modify the application initialization code above."
},
{
"code": null,
"e": 4661,
"s": 4501,
"text": "if __name__ == \"__main__\": app = QApplication(sys.argv) if not createConnection(): sys.exit(1) form = MainWindow() form.show() app.exec()"
},
{
"code": null,
"e": 4729,
"s": 4661,
"text": "It’s time to code our desired GUI for convenient data presentation."
},
{
"code": null,
"e": 4932,
"s": 4729,
"text": "We’ve already prepared our main form (window) of the application. You can see above form = MainWindow(), the MainWindow class instance named form. Nevertheless, we still don’t have the MainWindow class!"
},
{
"code": null,
"e": 5004,
"s": 4932,
"text": "We’ll do something about it right now. This is the most appealing part."
},
{
"code": null,
"e": 5099,
"s": 5004,
"text": "I can reveal now that we’ll be using the QTableView widget. It’s capable of the magic we need."
},
{
"code": null,
"e": 6084,
"s": 5099,
"text": "# Inherit from QMainWindowclass MainWindow(QMainWindow): def __init__(self, parent = None): super().__init__(parent) # Set the window title self.setWindowTitle('QTable Example') # Create the model model = QSqlRelationalTableModel(self) # Set the table to display model.setTable('orders') # Set relations for related columns to be displayed model.setRelation(1, QSqlRelation('products', 'ProductID', 'Price')) model.setRelation(2, QSqlRelation('customers', 'CustomerID', 'Customer')) model.setRelation(3, QSqlRelation('products', 'ProductID', 'Product')) model.select() # Setup the view # Create the view = a table widget view = QTableView(self) # Set the data model for table widget view.setModel(model) # Adjust column widths to their content view.resizeColumnsToContents() # Add the widget to main window self.setCentralWidget(view)"
},
{
"code": null,
"e": 6182,
"s": 6084,
"text": "The code above shows the whole application GUI setup. Comments explain the details of every step."
},
{
"code": null,
"e": 6292,
"s": 6182,
"text": "However, I’d like to clarify and analyze the model’s setRelation() method and use of the QSqlRelation object."
},
{
"code": null,
"e": 6389,
"s": 6292,
"text": "Let’s see what we’ve done here except lines linked to GUI itself. We’ll focus on our data model."
},
{
"code": null,
"e": 6594,
"s": 6389,
"text": "PyQt includes several model objects we can use effectively. In a view, we work with a relational table; the SqlRelationalTableModel class fits entirely. The model we’ll use does all the hard work we need."
},
{
"code": null,
"e": 6762,
"s": 6594,
"text": "The setRelation() method requires two arguments: column and relation. The method specifies that the column (a foreign key) has its behavior defined by relation object."
},
{
"code": null,
"e": 6803,
"s": 6762,
"text": "Let’s take the first case as an example:"
},
{
"code": null,
"e": 6897,
"s": 6803,
"text": "model.setTable(‘orders’) model.setRelation(1, QSqlRelation('products', 'ProductID', 'Price'))"
},
{
"code": null,
"e": 7060,
"s": 6897,
"text": "The behavior is that column 1 in table orders maps with field ProductID of table customers, and the view should present the customers’ Customer field to the user."
},
{
"code": null,
"e": 7206,
"s": 7060,
"text": "Using the QSqlRelationalTableModel, we gracefully avoided SQL language knowledge and other boilerplate code for constructing complex SQL queries."
}
] |
How to delete all records from a table in Oracle using JDBC API? | The SQL TRUNCATE statement is used to delete all the records from a table.
TRUNCATE TABLE table_name;
To delete all the records from a table from using JDBC API you need to −
Register the Driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.
Establish a connection: Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
Create Statement: Create a Statement object using the createStatement() method of the Connection interface.
Execute the Query: Execute the query using the execute() method of the Statement interface.
Following JDBC program establishes connection with oracle database and deletes all the records in the table named dispatches −
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class DeletingAllRows_Oracle {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//Getting the connection
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to delete all records in a table
String query = "Truncate table DISPATCHES";
//Executing the query
stmt.execute(query);
System.out.println("Table truncated....");
}
}
Connection established......
Table truncated....
After deleting, if you verify the contents of the Dispatches table using select statement, you will get the output as −
SQL> select * from dispatches;
no rows selected | [
{
"code": null,
"e": 1137,
"s": 1062,
"text": "The SQL TRUNCATE statement is used to delete all the records from a table."
},
{
"code": null,
"e": 1164,
"s": 1137,
"text": "TRUNCATE TABLE table_name;"
},
{
"code": null,
"e": 1237,
"s": 1164,
"text": "To delete all the records from a table from using JDBC API you need to −"
},
{
"code": null,
"e": 1394,
"s": 1237,
"text": "Register the Driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter."
},
{
"code": null,
"e": 1583,
"s": 1394,
"text": "Establish a connection: Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it."
},
{
"code": null,
"e": 1691,
"s": 1583,
"text": "Create Statement: Create a Statement object using the createStatement() method of the Connection interface."
},
{
"code": null,
"e": 1783,
"s": 1691,
"text": "Execute the Query: Execute the query using the execute() method of the Statement interface."
},
{
"code": null,
"e": 1910,
"s": 1783,
"text": "Following JDBC program establishes connection with oracle database and deletes all the records in the table named dispatches −"
},
{
"code": null,
"e": 2757,
"s": 1910,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class DeletingAllRows_Oracle {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());\n //Getting the connection\n String oracleUrl = \"jdbc:oracle:thin:@localhost:1521/xe\";\n Connection con = DriverManager.getConnection(oracleUrl, \"system\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to delete all records in a table\n String query = \"Truncate table DISPATCHES\";\n //Executing the query\n stmt.execute(query);\n System.out.println(\"Table truncated....\");\n }\n}"
},
{
"code": null,
"e": 2806,
"s": 2757,
"text": "Connection established......\nTable truncated...."
},
{
"code": null,
"e": 2926,
"s": 2806,
"text": "After deleting, if you verify the contents of the Dispatches table using select statement, you will get the output as −"
},
{
"code": null,
"e": 2974,
"s": 2926,
"text": "SQL> select * from dispatches;\nno rows selected"
}
] |
C++ Program to Find Fibonacci Numbers using Iteration | The following is an example to find fibonacci series using iteration.
Live Demo
#include <iostream>
using namespace std;
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
}
int main() {
int num;
cout << "Enter the number : ";
cin >> num;
cout << "\nThe fibonacci series : " ;
fib(num);
return 0;
}
Enter the number : 10
The fibonacci series : 0 1 1 2 3 5 8 13 21 34
In the above program, the actual code is present in function fib() to calculate the fibonacci series.
void fib(int num) {
int x = 0, y = 1, z = 0;
for (int i = 0; i < num; i++) {
cout << x << " ";
z = x + y;
x = y;
y = z;
}
}
In the main() function, a number is entered by the user. The function fib() is called and fibonacci series is printed as follows −
cout << "Enter the number : ";
cin >> num;
cout << "\nThe fibonacci series : " ;
fib(num); | [
{
"code": null,
"e": 1132,
"s": 1062,
"text": "The following is an example to find fibonacci series using iteration."
},
{
"code": null,
"e": 1143,
"s": 1132,
"text": " Live Demo"
},
{
"code": null,
"e": 1484,
"s": 1143,
"text": "#include <iostream>\nusing namespace std;\nvoid fib(int num) {\n int x = 0, y = 1, z = 0;\n for (int i = 0; i < num; i++) {\n cout << x << \" \";\n z = x + y;\n x = y;\n y = z;\n }\n}\nint main() {\n int num;\n cout << \"Enter the number : \";\n cin >> num;\n cout << \"\\nThe fibonacci series : \" ;\n fib(num);\n return 0;\n}"
},
{
"code": null,
"e": 1552,
"s": 1484,
"text": "Enter the number : 10\nThe fibonacci series : 0 1 1 2 3 5 8 13 21 34"
},
{
"code": null,
"e": 1654,
"s": 1552,
"text": "In the above program, the actual code is present in function fib() to calculate the fibonacci series."
},
{
"code": null,
"e": 1811,
"s": 1654,
"text": "void fib(int num) {\n int x = 0, y = 1, z = 0;\n for (int i = 0; i < num; i++) {\n cout << x << \" \";\n z = x + y;\n x = y;\n y = z;\n }\n}"
},
{
"code": null,
"e": 1942,
"s": 1811,
"text": "In the main() function, a number is entered by the user. The function fib() is called and fibonacci series is printed as follows −"
},
{
"code": null,
"e": 2033,
"s": 1942,
"text": "cout << \"Enter the number : \";\ncin >> num;\ncout << \"\\nThe fibonacci series : \" ;\nfib(num);"
}
] |
Send CSV payload to API with Data Factory | by Miia Rämö | Towards Data Science | One might think that there is a straight forward way to read data from SQL table/CSV Blob with Data Factory and send it to an API expecting a text body with CSV format. Well, to my knowledge there is not, and we need to create a Function app to achieve this.
One example use case, where I’ve come across this problem is when uploading data to Salesforce Bulk API 2.0.
In this article, I’ll show you a solution where
I read data from an SQL Database and write it to Blob storage as a CSV file,I fetch the Blob content as bytes with an Azure Function app, andI send the Function response to an example API I created.
I read data from an SQL Database and write it to Blob storage as a CSV file,
I fetch the Blob content as bytes with an Azure Function app, and
I send the Function response to an example API I created.
If you want to preserve history of files sent, I recommend setting the Blob name as a pipeline variable. If preserving the history is not necessary, you may use a hardcoded Blob name.
My Blob name includes the current timestamp and a file name:
@concat(substring(utcnow(), 0, 19), 'canada_climate_data.csv')
We’ll use Data Factory Copy Activity to create our Blob. In this example, my source is a table in my SQL DB. Both the source and sink datasets are created as generic datasets. See my article Keep your Data Factory clean with generic datasets for explanation.
To create my Python Function app, I followed these instructions by Microsoft. My __init__.py file is as follows:
The dynamic content for JSON body is as follows (replace ‘yourstorage’ and ‘container’ with your storage account name and the correct container name):
@concat('{"blob_location":"https://yourstorage.blob.core.windows.net/container/',variables('blob_name'),'"}')
The dynamic content for body is the response from my function:
@activity('Blob to bytes').output.Response
And that’s it!
Thank you for reading! If you learned something new or enjoyed this article, follow me on Medium. I publish articles about data engineering and data science. You can learn more about me from be web page.
Have you found a better way to achieve this, or was something unclear? Let me know in the comments 😊 | [
{
"code": null,
"e": 431,
"s": 172,
"text": "One might think that there is a straight forward way to read data from SQL table/CSV Blob with Data Factory and send it to an API expecting a text body with CSV format. Well, to my knowledge there is not, and we need to create a Function app to achieve this."
},
{
"code": null,
"e": 540,
"s": 431,
"text": "One example use case, where I’ve come across this problem is when uploading data to Salesforce Bulk API 2.0."
},
{
"code": null,
"e": 588,
"s": 540,
"text": "In this article, I’ll show you a solution where"
},
{
"code": null,
"e": 787,
"s": 588,
"text": "I read data from an SQL Database and write it to Blob storage as a CSV file,I fetch the Blob content as bytes with an Azure Function app, andI send the Function response to an example API I created."
},
{
"code": null,
"e": 864,
"s": 787,
"text": "I read data from an SQL Database and write it to Blob storage as a CSV file,"
},
{
"code": null,
"e": 930,
"s": 864,
"text": "I fetch the Blob content as bytes with an Azure Function app, and"
},
{
"code": null,
"e": 988,
"s": 930,
"text": "I send the Function response to an example API I created."
},
{
"code": null,
"e": 1172,
"s": 988,
"text": "If you want to preserve history of files sent, I recommend setting the Blob name as a pipeline variable. If preserving the history is not necessary, you may use a hardcoded Blob name."
},
{
"code": null,
"e": 1233,
"s": 1172,
"text": "My Blob name includes the current timestamp and a file name:"
},
{
"code": null,
"e": 1296,
"s": 1233,
"text": "@concat(substring(utcnow(), 0, 19), 'canada_climate_data.csv')"
},
{
"code": null,
"e": 1555,
"s": 1296,
"text": "We’ll use Data Factory Copy Activity to create our Blob. In this example, my source is a table in my SQL DB. Both the source and sink datasets are created as generic datasets. See my article Keep your Data Factory clean with generic datasets for explanation."
},
{
"code": null,
"e": 1668,
"s": 1555,
"text": "To create my Python Function app, I followed these instructions by Microsoft. My __init__.py file is as follows:"
},
{
"code": null,
"e": 1819,
"s": 1668,
"text": "The dynamic content for JSON body is as follows (replace ‘yourstorage’ and ‘container’ with your storage account name and the correct container name):"
},
{
"code": null,
"e": 1929,
"s": 1819,
"text": "@concat('{\"blob_location\":\"https://yourstorage.blob.core.windows.net/container/',variables('blob_name'),'\"}')"
},
{
"code": null,
"e": 1992,
"s": 1929,
"text": "The dynamic content for body is the response from my function:"
},
{
"code": null,
"e": 2035,
"s": 1992,
"text": "@activity('Blob to bytes').output.Response"
},
{
"code": null,
"e": 2050,
"s": 2035,
"text": "And that’s it!"
},
{
"code": null,
"e": 2254,
"s": 2050,
"text": "Thank you for reading! If you learned something new or enjoyed this article, follow me on Medium. I publish articles about data engineering and data science. You can learn more about me from be web page."
}
] |
How to Format date using strftime() in Python ? - GeeksforGeeks | 17 Apr, 2021
In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime().
Syntax:
time.strftime(format[, sec])
sec: This is the time in number of seconds to be formatted.
format: This is the directive or format code which would be used to format.
Below are some examples for better understanding.
Example 1:
Python3
from datetime import datetime # current time and date# datetime objecttime = datetime.now()print("Without formating:", time) # formating date using strftimeprint("After formating:", time.strftime("%b %d, %Y"))
Output:
Example 2:
Python3
from datetime import datetime # current time and date# datetime objecttime = datetime.now()print("Without formating:", time) # formating date using strftimeprint("Year", time.strftime("%Y"))print("Month name", time.strftime("%B"))print("Day", time.strftime("%d"))
Output:
Example 3:
Python3
from datetime import datetime # current time and date# datetime objecttime = datetime.now() # formating date using strftime# format = MM/DD/YYprint(time.strftime("%m/%d/%y")) # format = Month D, Yrprint(time.strftime("%B %d, %Y")) # time formating# HH:MM:SSprint(time.strftime("%H:%M:%S"))
Output:
Picked
Python-datetime
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How To Convert Python Dictionary To JSON? | [
{
"code": null,
"e": 24858,
"s": 24830,
"text": "\n17 Apr, 2021"
},
{
"code": null,
"e": 25110,
"s": 24858,
"text": "In this article, we will see how to format date using strftime() in Python. localtime() and gmtime() returns a tuple representing a time and this tuple is converted into a string as specified by the format argument using python time method strftime()."
},
{
"code": null,
"e": 25118,
"s": 25110,
"text": "Syntax:"
},
{
"code": null,
"e": 25147,
"s": 25118,
"text": "time.strftime(format[, sec])"
},
{
"code": null,
"e": 25207,
"s": 25147,
"text": "sec: This is the time in number of seconds to be formatted."
},
{
"code": null,
"e": 25283,
"s": 25207,
"text": "format: This is the directive or format code which would be used to format."
},
{
"code": null,
"e": 25333,
"s": 25283,
"text": "Below are some examples for better understanding."
},
{
"code": null,
"e": 25345,
"s": 25333,
"text": "Example 1: "
},
{
"code": null,
"e": 25353,
"s": 25345,
"text": "Python3"
},
{
"code": "from datetime import datetime # current time and date# datetime objecttime = datetime.now()print(\"Without formating:\", time) # formating date using strftimeprint(\"After formating:\", time.strftime(\"%b %d, %Y\"))",
"e": 25565,
"s": 25353,
"text": null
},
{
"code": null,
"e": 25573,
"s": 25565,
"text": "Output:"
},
{
"code": null,
"e": 25585,
"s": 25573,
"text": "Example 2: "
},
{
"code": null,
"e": 25593,
"s": 25585,
"text": "Python3"
},
{
"code": "from datetime import datetime # current time and date# datetime objecttime = datetime.now()print(\"Without formating:\", time) # formating date using strftimeprint(\"Year\", time.strftime(\"%Y\"))print(\"Month name\", time.strftime(\"%B\"))print(\"Day\", time.strftime(\"%d\"))",
"e": 25859,
"s": 25593,
"text": null
},
{
"code": null,
"e": 25867,
"s": 25859,
"text": "Output:"
},
{
"code": null,
"e": 25879,
"s": 25867,
"text": "Example 3: "
},
{
"code": null,
"e": 25887,
"s": 25879,
"text": "Python3"
},
{
"code": "from datetime import datetime # current time and date# datetime objecttime = datetime.now() # formating date using strftime# format = MM/DD/YYprint(time.strftime(\"%m/%d/%y\")) # format = Month D, Yrprint(time.strftime(\"%B %d, %Y\")) # time formating# HH:MM:SSprint(time.strftime(\"%H:%M:%S\"))",
"e": 26181,
"s": 25887,
"text": null
},
{
"code": null,
"e": 26189,
"s": 26181,
"text": "Output:"
},
{
"code": null,
"e": 26196,
"s": 26189,
"text": "Picked"
},
{
"code": null,
"e": 26212,
"s": 26196,
"text": "Python-datetime"
},
{
"code": null,
"e": 26219,
"s": 26212,
"text": "Python"
},
{
"code": null,
"e": 26317,
"s": 26219,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26335,
"s": 26317,
"text": "Python Dictionary"
},
{
"code": null,
"e": 26370,
"s": 26335,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 26392,
"s": 26370,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 26424,
"s": 26392,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 26454,
"s": 26424,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 26496,
"s": 26454,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 26533,
"s": 26496,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 26577,
"s": 26533,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 26606,
"s": 26577,
"text": "*args and **kwargs in Python"
}
] |
Go - Slices | Go Slice is an abstraction over Go Array. Go Array allows you to define variables that can hold several data items of the same kind but it does not provide any inbuilt method to increase its size dynamically or get a sub-array of its own. Slices overcome this limitation. It provides many utility functions required on Array and is widely used in Go programming.
To define a slice, you can declare it as an array without specifying its size. Alternatively, you can use make function to create a slice.
var numbers []int /* a slice of unspecified size */
/* numbers == []int{0,0,0,0,0}*/
numbers = make([]int,5,5) /* a slice of length 5 and capacity 5*/
A slice is an abstraction over array. It actually uses arrays as an underlying structure. The len() function returns the elements presents in the slice where cap() function returns the capacity of the slice (i.e., how many elements it can be accommodate). The following example explains the usage of slice −
package main
import "fmt"
func main() {
var numbers = make([]int,3,5)
printSlice(numbers)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 3 cap = 5 slice = [0 0 0]
If a slice is declared with no inputs, then by default, it is initialized as nil. Its length and capacity are zero. For example −
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
if(numbers == nil){
fmt.Printf("slice is nil")
}
}
func printSlice(x []int){
fmt.Printf("len = %d cap = %d slice = %v\n", len(x), cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 0 cap = 0 slice = []
slice is nil
Slice allows lower-bound and upper bound to be specified to get the subslice of it using[lower-bound:upper-bound]. For example −
package main
import "fmt"
func main() {
/* create a slice */
numbers := []int{0,1,2,3,4,5,6,7,8}
printSlice(numbers)
/* print the original slice */
fmt.Println("numbers ==", numbers)
/* print the sub slice starting from index 1(included) to index 4(excluded)*/
fmt.Println("numbers[1:4] ==", numbers[1:4])
/* missing lower bound implies 0*/
fmt.Println("numbers[:3] ==", numbers[:3])
/* missing upper bound implies len(s)*/
fmt.Println("numbers[4:] ==", numbers[4:])
numbers1 := make([]int,0,5)
printSlice(numbers1)
/* print the sub slice starting from index 0(included) to index 2(excluded) */
number2 := numbers[:2]
printSlice(number2)
/* print the sub slice starting from index 2(included) to index 5(excluded) */
number3 := numbers[2:5]
printSlice(number3)
}
func printSlice(x []int){
fmt.Printf("len = %d cap = %d slice = %v\n", len(x), cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 9 cap = 9 slice = [0 1 2 3 4 5 6 7 8]
numbers == [0 1 2 3 4 5 6 7 8]
numbers[1:4] == [1 2 3]
numbers[:3] == [0 1 2]
numbers[4:] == [4 5 6 7 8]
len = 0 cap = 5 slice = []
len = 2 cap = 9 slice = [0 1]
len = 3 cap = 7 slice = [2 3 4]
One can increase the capacity of a slice using the append() function. Using copy()function, the contents of a source slice are copied to a destination slice. For example −
package main
import "fmt"
func main() {
var numbers []int
printSlice(numbers)
/* append allows nil slice */
numbers = append(numbers, 0)
printSlice(numbers)
/* add one element to slice*/
numbers = append(numbers, 1)
printSlice(numbers)
/* add more than one element at a time*/
numbers = append(numbers, 2,3,4)
printSlice(numbers)
/* create a slice numbers1 with double the capacity of earlier slice*/
numbers1 := make([]int, len(numbers), (cap(numbers))*2)
/* copy content of numbers to numbers1 */
copy(numbers1,numbers)
printSlice(numbers1)
}
func printSlice(x []int){
fmt.Printf("len=%d cap=%d slice=%v\n",len(x),cap(x),x)
}
When the above code is compiled and executed, it produces the following result −
len = 0 cap = 0 slice = []
len = 1 cap = 2 slice = [0]
len = 2 cap = 2 slice = [0 1]
len = 5 cap = 8 slice = [0 1 2 3 4]
len = 5 cap = 16 slice = [0 1 2 3 4]
64 Lectures
6.5 hours
Ridhi Arora
20 Lectures
2.5 hours
Asif Hussain
22 Lectures
4 hours
Dilip Padmanabhan
48 Lectures
6 hours
Arnab Chakraborty
7 Lectures
1 hours
Aditya Kulkarni
44 Lectures
3 hours
Arnab Chakraborty
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2300,
"s": 1937,
"text": "Go Slice is an abstraction over Go Array. Go Array allows you to define variables that can hold several data items of the same kind but it does not provide any inbuilt method to increase its size dynamically or get a sub-array of its own. Slices overcome this limitation. It provides many utility functions required on Array and is widely used in Go programming."
},
{
"code": null,
"e": 2439,
"s": 2300,
"text": "To define a slice, you can declare it as an array without specifying its size. Alternatively, you can use make function to create a slice."
},
{
"code": null,
"e": 2591,
"s": 2439,
"text": "var numbers []int /* a slice of unspecified size */\n/* numbers == []int{0,0,0,0,0}*/\nnumbers = make([]int,5,5) /* a slice of length 5 and capacity 5*/\n"
},
{
"code": null,
"e": 2899,
"s": 2591,
"text": "A slice is an abstraction over array. It actually uses arrays as an underlying structure. The len() function returns the elements presents in the slice where cap() function returns the capacity of the slice (i.e., how many elements it can be accommodate). The following example explains the usage of slice −"
},
{
"code": null,
"e": 3085,
"s": 2899,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var numbers = make([]int,3,5)\n printSlice(numbers)\n}\nfunc printSlice(x []int){\n fmt.Printf(\"len=%d cap=%d slice=%v\\n\",len(x),cap(x),x)\n}"
},
{
"code": null,
"e": 3166,
"s": 3085,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3199,
"s": 3166,
"text": "len = 3 cap = 5 slice = [0 0 0]\n"
},
{
"code": null,
"e": 3329,
"s": 3199,
"text": "If a slice is declared with no inputs, then by default, it is initialized as nil. Its length and capacity are zero. For example −"
},
{
"code": null,
"e": 3576,
"s": 3329,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var numbers []int\n printSlice(numbers)\n \n if(numbers == nil){\n fmt.Printf(\"slice is nil\")\n }\n}\nfunc printSlice(x []int){\n fmt.Printf(\"len = %d cap = %d slice = %v\\n\", len(x), cap(x),x)\n}"
},
{
"code": null,
"e": 3657,
"s": 3576,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 3698,
"s": 3657,
"text": "len = 0 cap = 0 slice = []\nslice is nil\n"
},
{
"code": null,
"e": 3827,
"s": 3698,
"text": "Slice allows lower-bound and upper bound to be specified to get the subslice of it using[lower-bound:upper-bound]. For example −"
},
{
"code": null,
"e": 4778,
"s": 3827,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n /* create a slice */\n numbers := []int{0,1,2,3,4,5,6,7,8} \n printSlice(numbers)\n \n /* print the original slice */\n fmt.Println(\"numbers ==\", numbers)\n \n /* print the sub slice starting from index 1(included) to index 4(excluded)*/\n fmt.Println(\"numbers[1:4] ==\", numbers[1:4])\n \n /* missing lower bound implies 0*/\n fmt.Println(\"numbers[:3] ==\", numbers[:3])\n \n /* missing upper bound implies len(s)*/\n fmt.Println(\"numbers[4:] ==\", numbers[4:])\n \n numbers1 := make([]int,0,5)\n printSlice(numbers1)\n \n /* print the sub slice starting from index 0(included) to index 2(excluded) */\n number2 := numbers[:2]\n printSlice(number2)\n \n /* print the sub slice starting from index 2(included) to index 5(excluded) */\n number3 := numbers[2:5]\n printSlice(number3)\n \n}\nfunc printSlice(x []int){\n fmt.Printf(\"len = %d cap = %d slice = %v\\n\", len(x), cap(x),x)\n}"
},
{
"code": null,
"e": 4859,
"s": 4778,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 5099,
"s": 4859,
"text": "len = 9 cap = 9 slice = [0 1 2 3 4 5 6 7 8]\nnumbers == [0 1 2 3 4 5 6 7 8]\nnumbers[1:4] == [1 2 3]\nnumbers[:3] == [0 1 2]\nnumbers[4:] == [4 5 6 7 8]\nlen = 0 cap = 5 slice = []\nlen = 2 cap = 9 slice = [0 1]\nlen = 3 cap = 7 slice = [2 3 4]\n"
},
{
"code": null,
"e": 5271,
"s": 5099,
"text": "One can increase the capacity of a slice using the append() function. Using copy()function, the contents of a source slice are copied to a destination slice. For example −"
},
{
"code": null,
"e": 5975,
"s": 5271,
"text": "package main\n\nimport \"fmt\"\n\nfunc main() {\n var numbers []int\n printSlice(numbers)\n \n /* append allows nil slice */\n numbers = append(numbers, 0)\n printSlice(numbers)\n \n /* add one element to slice*/\n numbers = append(numbers, 1)\n printSlice(numbers)\n \n /* add more than one element at a time*/\n numbers = append(numbers, 2,3,4)\n printSlice(numbers)\n \n /* create a slice numbers1 with double the capacity of earlier slice*/\n numbers1 := make([]int, len(numbers), (cap(numbers))*2)\n \n /* copy content of numbers to numbers1 */\n copy(numbers1,numbers)\n printSlice(numbers1) \n}\nfunc printSlice(x []int){\n fmt.Printf(\"len=%d cap=%d slice=%v\\n\",len(x),cap(x),x)\n}"
},
{
"code": null,
"e": 6056,
"s": 5975,
"text": "When the above code is compiled and executed, it produces the following result −"
},
{
"code": null,
"e": 6215,
"s": 6056,
"text": "len = 0 cap = 0 slice = []\nlen = 1 cap = 2 slice = [0]\nlen = 2 cap = 2 slice = [0 1]\nlen = 5 cap = 8 slice = [0 1 2 3 4]\nlen = 5 cap = 16 slice = [0 1 2 3 4]\n"
},
{
"code": null,
"e": 6250,
"s": 6215,
"text": "\n 64 Lectures \n 6.5 hours \n"
},
{
"code": null,
"e": 6263,
"s": 6250,
"text": " Ridhi Arora"
},
{
"code": null,
"e": 6298,
"s": 6263,
"text": "\n 20 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6312,
"s": 6298,
"text": " Asif Hussain"
},
{
"code": null,
"e": 6345,
"s": 6312,
"text": "\n 22 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6364,
"s": 6345,
"text": " Dilip Padmanabhan"
},
{
"code": null,
"e": 6397,
"s": 6364,
"text": "\n 48 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 6416,
"s": 6397,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6448,
"s": 6416,
"text": "\n 7 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6465,
"s": 6448,
"text": " Aditya Kulkarni"
},
{
"code": null,
"e": 6498,
"s": 6465,
"text": "\n 44 Lectures \n 3 hours \n"
},
{
"code": null,
"e": 6517,
"s": 6498,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 6524,
"s": 6517,
"text": " Print"
},
{
"code": null,
"e": 6535,
"s": 6524,
"text": " Add Notes"
}
] |
3 Great Julia Editors — VSCode, Juno and Jupyter Notebooks | by Alan Jones | Towards Data Science | Julia is a young language and so support is not as comprehensive as it is for other more established languages such as Java or Python. However, while there may not be a vast number of development environments available for it, you do have the choice of some good ones.
I’m going to introduce you to my favorites; this won’t be a comprehensive guide, just a brief overview but, I hope, useful.
The choice of editor or IDE is to some extent subjective and so the three environments that I have chosen to talk about here are bound to reflect my own prejudices.
They are all open source and thus free, and they are: Visual Studio Code from Microsoft, Juno, which is promoted by the Julia language people themselves and is based upon the Atom editor, and finally Jupyter Notebooks.
All of these environments support multiple languages and each requires its own plugin or extension to customize it to support Julia.
Juno and VSCode are fairly conventional IDEs, the sort of thing you might use for many types of software or web development. Jupyter Notebooks is not a conventional IDE and is more associated with Data Science and the Python language but it is also perfect for Julia (and other languages, too). That being said, you probably wouldn’t want to develop large Julia programs with Jupyter; it is much better suited to the relatively short routines that data scientists or data journalists are likely to want to use.
I’ll come to Jupyter last and of the two conventional IDEs, I’ll start with the one that is probably most associated with the Julia language.
(Update: it seems that Juno is no longer being developed and that the development effort has been moved to the Julia extension for VSCode)
If you go to the Julia language home page ( julialang.org) one of the things you will be invited to do is download the JuliaPro package. This is the Juno IDE bundled with the Julia language. You need to register to download JuliaPro but it is free.
Alternatively, if you already have Julia, you can download and configure Juno very simply. This is the route I took and it comprises of a few simple steps. First, download the Atom editor, then from within the editor download and install ‘uber-juno’ the Juno extension and, when it has finished tell the Juno extension where the Julia binary is.
Follow the Juno link on the Julialang web site for full instructions, it’s quite straightforward although on my rather weak and feeble Linux machine, installing the extension took a while. If you have a reasonably up-to-date computer with a decent amount of memory, you probably won’t have to wait too long.
When you start Juno you will see what looks like a normal Atom editor but with the addition of a Juno menu and Juno controls down the left side of the window.
To run a file simply open it from the file menu and then click the run icon (like a play button) and two things will happen. First a Julia console, or REPL is started (you can also start this manually) and then the program will run with any output sent to the console.
A word of warning: the first time that I ran a program it took a long time to start Julia, so you may need to be patient. Subsequent runs were much quicker.
Below, you can see a screen shot of Juno running a simple plotting program. There is no output to the console but you can see that the plot is drawn in its own window.
As you would expect from a fairly sophisticated IDE, Juno has code completion, a debugger and you can write interactive commands in the REPL.
Again,as with Juno, the first run took a while to get going. Subsequent runs were quicker and, it may be my imagination, but it felt that VSCode might be marginally quicker than Juno.
Jupyter is not a conventional IDE. It consists of cells that can be either code or text and which can be executed individually. In the screenshot below you can see the same plotting program in a single code cell and the output — the graph — just below it.
Typically, another cell would be opened below the first with the next bit of code to be executed. These code cells can have text cells interspersed between them — the text being in Markdown — so allowing for the creation of a complete executable document comprising of rich text and program code.
You wouldn’t use Jupyter to develop conventional programs but for the data scientist or data journalist who wants to manipulate and analyse data it can be a great tool.
To use Jupyter as a tool for Julia you will need to download and install both (you will also need Python to run Jupyter). The easiest way to install Jupyter and Python simultaneously is to use Anaconda — I’ve already written an article about this, so rather than repeat myself, please take a look at this: Setting Up Jupyter Notebooks for Data Visualization with Anaconda.
By default, Jupyter uses the Python language. To let Jupyter know about Julia, start up Julia and you will see the command prompt in a window like this (it’s the same REPL as you see in the editors):
Then type this at the prompt and the press <return>:
using Pkg
this tells Julia that you are going to use the package manager. Then type the following and hit <return>:
Pkg.add("IJulia")
IJulia is the package that will provide the connection between Jupyter and Julia. You may need to wait while it downloads and installs.
Once you have installed IJulia you can close the Julia window. When you start up Jupyter, you will be able to open a new Julia Notebook instead of Python (though Python will still be an option).
One of the advantages of Julia over Python is that it is fast. This is great if you have a lot of processing to do. However, the speed comes from compiling the Julia code into lower level code and this in itself takes time.
This compilation takes place the first time you run a program and so this first run takes considerably longer than subsequent ones: if you run the same program a second time you will notice that it is much faster.
I use Jupyter to develop both Python and Julia code particularly for articles like this. I like the way I can use a prototyping approach, writing small pieces of code at a time, trying them out and then moving on to the next part.
With both of the IDEs you can run blocks of code and so work in a similar way to this but, of course, you cannot include text cells.
So, if I was writing an article or a report that required me to build up small pieces of code with descriptive text then I would definitely use Jupyter. On the other hand if I was writing a single standalone program, I’d use a normal IDE, either Juno or VSCode.
To be honest, I can’t decide which is best which is why I use all three!
Why not try them all out and see which you are most comfortable with.
You might also be interest in:
towardsdatascience.com
towardsdatascience.com
Originally published at https://projectcodeed.blogspot.com on June 6, 2020. | [
{
"code": null,
"e": 315,
"s": 46,
"text": "Julia is a young language and so support is not as comprehensive as it is for other more established languages such as Java or Python. However, while there may not be a vast number of development environments available for it, you do have the choice of some good ones."
},
{
"code": null,
"e": 439,
"s": 315,
"text": "I’m going to introduce you to my favorites; this won’t be a comprehensive guide, just a brief overview but, I hope, useful."
},
{
"code": null,
"e": 604,
"s": 439,
"text": "The choice of editor or IDE is to some extent subjective and so the three environments that I have chosen to talk about here are bound to reflect my own prejudices."
},
{
"code": null,
"e": 823,
"s": 604,
"text": "They are all open source and thus free, and they are: Visual Studio Code from Microsoft, Juno, which is promoted by the Julia language people themselves and is based upon the Atom editor, and finally Jupyter Notebooks."
},
{
"code": null,
"e": 956,
"s": 823,
"text": "All of these environments support multiple languages and each requires its own plugin or extension to customize it to support Julia."
},
{
"code": null,
"e": 1467,
"s": 956,
"text": "Juno and VSCode are fairly conventional IDEs, the sort of thing you might use for many types of software or web development. Jupyter Notebooks is not a conventional IDE and is more associated with Data Science and the Python language but it is also perfect for Julia (and other languages, too). That being said, you probably wouldn’t want to develop large Julia programs with Jupyter; it is much better suited to the relatively short routines that data scientists or data journalists are likely to want to use."
},
{
"code": null,
"e": 1609,
"s": 1467,
"text": "I’ll come to Jupyter last and of the two conventional IDEs, I’ll start with the one that is probably most associated with the Julia language."
},
{
"code": null,
"e": 1748,
"s": 1609,
"text": "(Update: it seems that Juno is no longer being developed and that the development effort has been moved to the Julia extension for VSCode)"
},
{
"code": null,
"e": 1997,
"s": 1748,
"text": "If you go to the Julia language home page ( julialang.org) one of the things you will be invited to do is download the JuliaPro package. This is the Juno IDE bundled with the Julia language. You need to register to download JuliaPro but it is free."
},
{
"code": null,
"e": 2343,
"s": 1997,
"text": "Alternatively, if you already have Julia, you can download and configure Juno very simply. This is the route I took and it comprises of a few simple steps. First, download the Atom editor, then from within the editor download and install ‘uber-juno’ the Juno extension and, when it has finished tell the Juno extension where the Julia binary is."
},
{
"code": null,
"e": 2651,
"s": 2343,
"text": "Follow the Juno link on the Julialang web site for full instructions, it’s quite straightforward although on my rather weak and feeble Linux machine, installing the extension took a while. If you have a reasonably up-to-date computer with a decent amount of memory, you probably won’t have to wait too long."
},
{
"code": null,
"e": 2810,
"s": 2651,
"text": "When you start Juno you will see what looks like a normal Atom editor but with the addition of a Juno menu and Juno controls down the left side of the window."
},
{
"code": null,
"e": 3079,
"s": 2810,
"text": "To run a file simply open it from the file menu and then click the run icon (like a play button) and two things will happen. First a Julia console, or REPL is started (you can also start this manually) and then the program will run with any output sent to the console."
},
{
"code": null,
"e": 3236,
"s": 3079,
"text": "A word of warning: the first time that I ran a program it took a long time to start Julia, so you may need to be patient. Subsequent runs were much quicker."
},
{
"code": null,
"e": 3404,
"s": 3236,
"text": "Below, you can see a screen shot of Juno running a simple plotting program. There is no output to the console but you can see that the plot is drawn in its own window."
},
{
"code": null,
"e": 3546,
"s": 3404,
"text": "As you would expect from a fairly sophisticated IDE, Juno has code completion, a debugger and you can write interactive commands in the REPL."
},
{
"code": null,
"e": 3730,
"s": 3546,
"text": "Again,as with Juno, the first run took a while to get going. Subsequent runs were quicker and, it may be my imagination, but it felt that VSCode might be marginally quicker than Juno."
},
{
"code": null,
"e": 3986,
"s": 3730,
"text": "Jupyter is not a conventional IDE. It consists of cells that can be either code or text and which can be executed individually. In the screenshot below you can see the same plotting program in a single code cell and the output — the graph — just below it."
},
{
"code": null,
"e": 4283,
"s": 3986,
"text": "Typically, another cell would be opened below the first with the next bit of code to be executed. These code cells can have text cells interspersed between them — the text being in Markdown — so allowing for the creation of a complete executable document comprising of rich text and program code."
},
{
"code": null,
"e": 4452,
"s": 4283,
"text": "You wouldn’t use Jupyter to develop conventional programs but for the data scientist or data journalist who wants to manipulate and analyse data it can be a great tool."
},
{
"code": null,
"e": 4825,
"s": 4452,
"text": "To use Jupyter as a tool for Julia you will need to download and install both (you will also need Python to run Jupyter). The easiest way to install Jupyter and Python simultaneously is to use Anaconda — I’ve already written an article about this, so rather than repeat myself, please take a look at this: Setting Up Jupyter Notebooks for Data Visualization with Anaconda."
},
{
"code": null,
"e": 5025,
"s": 4825,
"text": "By default, Jupyter uses the Python language. To let Jupyter know about Julia, start up Julia and you will see the command prompt in a window like this (it’s the same REPL as you see in the editors):"
},
{
"code": null,
"e": 5078,
"s": 5025,
"text": "Then type this at the prompt and the press <return>:"
},
{
"code": null,
"e": 5088,
"s": 5078,
"text": "using Pkg"
},
{
"code": null,
"e": 5194,
"s": 5088,
"text": "this tells Julia that you are going to use the package manager. Then type the following and hit <return>:"
},
{
"code": null,
"e": 5212,
"s": 5194,
"text": "Pkg.add(\"IJulia\")"
},
{
"code": null,
"e": 5348,
"s": 5212,
"text": "IJulia is the package that will provide the connection between Jupyter and Julia. You may need to wait while it downloads and installs."
},
{
"code": null,
"e": 5543,
"s": 5348,
"text": "Once you have installed IJulia you can close the Julia window. When you start up Jupyter, you will be able to open a new Julia Notebook instead of Python (though Python will still be an option)."
},
{
"code": null,
"e": 5767,
"s": 5543,
"text": "One of the advantages of Julia over Python is that it is fast. This is great if you have a lot of processing to do. However, the speed comes from compiling the Julia code into lower level code and this in itself takes time."
},
{
"code": null,
"e": 5981,
"s": 5767,
"text": "This compilation takes place the first time you run a program and so this first run takes considerably longer than subsequent ones: if you run the same program a second time you will notice that it is much faster."
},
{
"code": null,
"e": 6212,
"s": 5981,
"text": "I use Jupyter to develop both Python and Julia code particularly for articles like this. I like the way I can use a prototyping approach, writing small pieces of code at a time, trying them out and then moving on to the next part."
},
{
"code": null,
"e": 6345,
"s": 6212,
"text": "With both of the IDEs you can run blocks of code and so work in a similar way to this but, of course, you cannot include text cells."
},
{
"code": null,
"e": 6607,
"s": 6345,
"text": "So, if I was writing an article or a report that required me to build up small pieces of code with descriptive text then I would definitely use Jupyter. On the other hand if I was writing a single standalone program, I’d use a normal IDE, either Juno or VSCode."
},
{
"code": null,
"e": 6680,
"s": 6607,
"text": "To be honest, I can’t decide which is best which is why I use all three!"
},
{
"code": null,
"e": 6750,
"s": 6680,
"text": "Why not try them all out and see which you are most comfortable with."
},
{
"code": null,
"e": 6781,
"s": 6750,
"text": "You might also be interest in:"
},
{
"code": null,
"e": 6804,
"s": 6781,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 6827,
"s": 6804,
"text": "towardsdatascience.com"
}
] |
How to create a Stored procedure in Oracle database using JDBC API? | Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures.
Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets.
To create a stored procedure in (MySQL) a database using JDBC API you need to −
Register the Driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter.
Establish a connection: Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it.
Create Statement: Create a Statement object using the createStatement() method of the Connection interface.
Execute the Query: Execute the query to create stored procedures, using the execute() method of the Statement interface.
Let us create a table with name dispatches in Oracle database using CREATE statement as shown below −
CREATE TABLE Dispatches(
PRODUCTNAME VARCHAR2(20),
CUSTOMERNAME VARCHAR2(20),
DISPATCHDATE DATE,
DELIVERYTIME TIMESTAMP(6),
PRICE NUMBER(38),
LOCATION VARCHAR2(20)
);
Now, we will insert 5 records in dispatches table using INSERT statements −
insert into dispatches values('Key-Board', 'Raja', TO_DATE('2019-09-01', 'yyyy/mm/dd'), TO_DATE('11:00:00', 'hh:mi:ss'), 7000, 'India');
insert into dispatches values('Earphones', 'Roja', TO_DATE('2019-05-01', 'yyyy/mm/dd'), TO_DATE('11:00:00', 'hh:mi:ss'), 2000, 'Vishakhapatnam');
insert into dispatches values('Mouse', 'Puja', TO_DATE('2019-03-01', 'yyyy/mm/dd'), TO_DATE('10:59:59', 'hh:mi:ss'), 3000, 'Vijayawada');
insert into dispatches values('Mobile', 'Vanaja', TO_DATE('2019-03-01', 'yyyy/mm/dd'), TO_DATE('10:10:52', 'hh:mi:ss'), 9000, 'Chennai');
insert into dispatches values('Headset', 'Jalaja', TO_DATE('2019-04-06', 'yyyy/mm/dd'), TO_DATE('11:08:59', 'hh:mi:ss' ), 6000, 'Goa');
Following JDBC program establishes connection with the Oracle database and creates a procedure named retrieveData which retrives the contents of the above created table.
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
public class CreatingStoredProcedures_Oracle {
public static void main(String args[]) throws SQLException {
//Registering the Driver
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
//Getting the connection
String oracleUrl = "jdbc:oracle:thin:@localhost:1521/xe";
Connection con = DriverManager.getConnection(oracleUrl, "system", "password");
System.out.println("Connection established......");
//Creating the Statement
Statement stmt = con.createStatement();
//Query to create stored procedures
String query = "CREATE PROCEDURE retrieveData() " +
"BEGIN "+
" SELECT * FROM Customers; "+
"END";
//Executing the query
stmt.execute(query);
System.out.println("Procedure Created......");
}
}
Connection established......
Procedure Created...... | [
{
"code": null,
"e": 1271,
"s": 1062,
"text": "Stored procedures are sub routines, segment of SQL statements which are stored in SQL catalog. All the applications that can access Relational databases (Java, Python, PHP etc.), can access stored procedures."
},
{
"code": null,
"e": 1442,
"s": 1271,
"text": "Stored procedures contain IN and OUT parameters or both. They may return result sets in case you use SELECT statements. Stored procedures can return multiple result sets."
},
{
"code": null,
"e": 1522,
"s": 1442,
"text": "To create a stored procedure in (MySQL) a database using JDBC API you need to −"
},
{
"code": null,
"e": 1679,
"s": 1522,
"text": "Register the Driver: Register the driver class using the registerDriver() method of the DriverManager class. Pass the driver class name to it, as parameter."
},
{
"code": null,
"e": 1868,
"s": 1679,
"text": "Establish a connection: Connect to the database using the getConnection() method of the DriverManager class. Passing URL (String), username (String), password (String) as parameters to it."
},
{
"code": null,
"e": 1976,
"s": 1868,
"text": "Create Statement: Create a Statement object using the createStatement() method of the Connection interface."
},
{
"code": null,
"e": 2097,
"s": 1976,
"text": "Execute the Query: Execute the query to create stored procedures, using the execute() method of the Statement interface."
},
{
"code": null,
"e": 2199,
"s": 2097,
"text": "Let us create a table with name dispatches in Oracle database using CREATE statement as shown below −"
},
{
"code": null,
"e": 2384,
"s": 2199,
"text": "CREATE TABLE Dispatches(\n PRODUCTNAME VARCHAR2(20),\n CUSTOMERNAME VARCHAR2(20),\n DISPATCHDATE DATE,\n DELIVERYTIME TIMESTAMP(6),\n PRICE NUMBER(38),\n LOCATION VARCHAR2(20)\n);"
},
{
"code": null,
"e": 2460,
"s": 2384,
"text": "Now, we will insert 5 records in dispatches table using INSERT statements −"
},
{
"code": null,
"e": 3155,
"s": 2460,
"text": "insert into dispatches values('Key-Board', 'Raja', TO_DATE('2019-09-01', 'yyyy/mm/dd'), TO_DATE('11:00:00', 'hh:mi:ss'), 7000, 'India');\ninsert into dispatches values('Earphones', 'Roja', TO_DATE('2019-05-01', 'yyyy/mm/dd'), TO_DATE('11:00:00', 'hh:mi:ss'), 2000, 'Vishakhapatnam');\ninsert into dispatches values('Mouse', 'Puja', TO_DATE('2019-03-01', 'yyyy/mm/dd'), TO_DATE('10:59:59', 'hh:mi:ss'), 3000, 'Vijayawada');\ninsert into dispatches values('Mobile', 'Vanaja', TO_DATE('2019-03-01', 'yyyy/mm/dd'), TO_DATE('10:10:52', 'hh:mi:ss'), 9000, 'Chennai');\ninsert into dispatches values('Headset', 'Jalaja', TO_DATE('2019-04-06', 'yyyy/mm/dd'), TO_DATE('11:08:59', 'hh:mi:ss' ), 6000, 'Goa');"
},
{
"code": null,
"e": 3325,
"s": 3155,
"text": "Following JDBC program establishes connection with the Oracle database and creates a procedure named retrieveData which retrives the contents of the above created table."
},
{
"code": null,
"e": 4256,
"s": 3325,
"text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class CreatingStoredProcedures_Oracle {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());\n //Getting the connection\n String oracleUrl = \"jdbc:oracle:thin:@localhost:1521/xe\";\n Connection con = DriverManager.getConnection(oracleUrl, \"system\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to create stored procedures\n String query = \"CREATE PROCEDURE retrieveData() \" +\n \"BEGIN \"+\n \" SELECT * FROM Customers; \"+\n \"END\";\n //Executing the query\n stmt.execute(query);\n System.out.println(\"Procedure Created......\");\n }\n}"
},
{
"code": null,
"e": 4309,
"s": 4256,
"text": "Connection established......\nProcedure Created......"
}
] |
Arcade Library in Python - GeeksforGeeks | 02 Nov, 2020
For many years, Python game programmers were limited to the Pygame Module. But, now we have other choices as well i.e Arcade Python Library. The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. It was written by Paul Vincent Craven, a computer science professor at Simpson College in Iowa, USA.
To install this module, just simply run the following command on your command prompt:
pip install arcade
The following steps illustrate how to create a basic drawing using an arcade module:
Import module.
Specify the parameters for your output screen like width, height, etc.
Open the window using the inbuilt open_window() in the arcade. This command opens a window with a given size i.e width and height along with the screen title.
Syntax-
arcade.open_window(Width, Height, Title)
Set a background color (optional). It can be done using set_background_color() method built into arcade
Syntax-
arcade.set_background_color(arcade.color.color_name)
Tell your module to start drawing using start_render() command which is again built into arcade.
Syntax-
arcade.start_render()
Start designing, you can use functions already available with arcade to do so.
Tell arcade module that you have completed the drawing using finish_render().
Syntax-
arcade.finish_render()
Run your code using run().
Syntax-
arcade.run()
Example 1: Python program that uses arcade to draw a circle.
Python3
# Import moduleimport arcade # Specify ParametersWidth = 500Height = 700Title = "Welcome to Arcade"Radius = 100 # Open the windowarcade.open_window(Width, Height, Title) # Set the background colorarcade.set_background_color(arcade.color.BLUE) # start drawingarcade.start_render() # Draw a Pink circlearcade.draw_circle_filled( Width/2 , Height/2 , Radius , arcade.color.PINK)# Finish drawingarcade.finish_render() # Display everythingarcade.run()
Output:
Example 2: Python program that creates a pattern of circles using the arcade
Python3
# Import moduleimport arcade #Specify ParametersWidth = 500Height = 700Title = "Welcome to Arcade"Radius = 200 # Open the windowarcade.open_window(Width, Height, Title) # Set the background colorarcade.set_background_color(arcade.color.BLACK) # start drawingarcade.start_render() # Draw a BLUE circlearcade.draw_circle_filled( Width/2 , Height/2 , Radius , arcade.color.BLUE) # Draw a Red circlearcade.draw_circle_filled( Width/2 , Height , Radius , arcade.color.RED) # Finish drawingarcade.finish_render()# Display everythingarcade.run()
Output:
Arcade is a set of python modules which is a modern Python framework used in designing 2D video games. In Arcade, we have gripping computer graphics and sound libraries in order to design high quality and user-friendly games. Arcade was developed by Paul Vincent Craven. Arcade needs support for OpenGL 3.3+.
Arcade is built on top of Pyglet and OpenGL.
In order to replace Pygame, Arcade came into existence.
Arcade runs on Windows, Mac OS X, and Linux.
Arcade requires Python 3.6 or newer. It does not run on Python 2.x.
Arcade needs support for OpenGL 3.3+. It does not run on Raspberry Pi or Wayland. If on Linux, sound support needs at least GLIB 2.29+.
Arcade uses SoLoud. which Supports panning and volume.
It is possible to create open-source free, shareware, and commercial games with it.
Supports Python 3 type hinting.
Basic drawing does not require knowledge on how to define functions or classes or how to do loops.
Uses a standard coordinate system you learned about in math. (0, 0) is in the lower left, and not upper left. Y-coordinates are not reversed.
API documentation for the commands is better.
Version 2.4.3 was released 2020-09-30. It is the latest version of arcade that has Added PyInstalled hook and tutorial, ShapeLists have no longer share position between instances and with GUI improvement.Version 2.4.2 was released 2020-09-08. It has GPU transformations with the mouse and Updates downloadable .zip for platformer example code to match current code in documentation and much more. Arcade 2.4.1 was released 2020-07-13. Support for defining your own frame buffers, shaders, and more advanced OpenGL programming, PyMunk engine for a platform, etc.
Version 2.4.3 was released 2020-09-30. It is the latest version of arcade that has Added PyInstalled hook and tutorial, ShapeLists have no longer share position between instances and with GUI improvement.
Version 2.4.2 was released 2020-09-08. It has GPU transformations with the mouse and Updates downloadable .zip for platformer example code to match current code in documentation and much more.
Arcade 2.4.1 was released 2020-07-13. Support for defining your own frame buffers, shaders, and more advanced OpenGL programming, PyMunk engine for a platform, etc.
anshitaagarwal
Python-Arcade
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Python Dictionary
Read a file line by line in Python
How to Install PIP on Windows ?
Different ways to create Pandas Dataframe
Python String | replace()
Python program to convert a list to string
Create a Pandas DataFrame from Lists
Reading and Writing to text files in Python
*args and **kwargs in Python
How to drop one or multiple columns in Pandas Dataframe | [
{
"code": null,
"e": 24368,
"s": 24340,
"text": "\n02 Nov, 2020"
},
{
"code": null,
"e": 24823,
"s": 24368,
"text": "For many years, Python game programmers were limited to the Pygame Module. But, now we have other choices as well i.e Arcade Python Library. The Arcade library is a modern Python Module used widely for developing 2D video games with compelling graphics and sound. Arcade is an object-oriented library. It can be installed like any other Python Package. It was written by Paul Vincent Craven, a computer science professor at Simpson College in Iowa, USA. "
},
{
"code": null,
"e": 24909,
"s": 24823,
"text": "To install this module, just simply run the following command on your command prompt:"
},
{
"code": null,
"e": 24935,
"s": 24909,
"text": "pip install arcade\n\n\n\n\n\n\n"
},
{
"code": null,
"e": 25020,
"s": 24935,
"text": "The following steps illustrate how to create a basic drawing using an arcade module:"
},
{
"code": null,
"e": 25035,
"s": 25020,
"text": "Import module."
},
{
"code": null,
"e": 25106,
"s": 25035,
"text": "Specify the parameters for your output screen like width, height, etc."
},
{
"code": null,
"e": 25265,
"s": 25106,
"text": "Open the window using the inbuilt open_window() in the arcade. This command opens a window with a given size i.e width and height along with the screen title."
},
{
"code": null,
"e": 25273,
"s": 25265,
"text": "Syntax-"
},
{
"code": null,
"e": 25314,
"s": 25273,
"text": "arcade.open_window(Width, Height, Title)"
},
{
"code": null,
"e": 25418,
"s": 25314,
"text": "Set a background color (optional). It can be done using set_background_color() method built into arcade"
},
{
"code": null,
"e": 25426,
"s": 25418,
"text": "Syntax-"
},
{
"code": null,
"e": 25479,
"s": 25426,
"text": "arcade.set_background_color(arcade.color.color_name)"
},
{
"code": null,
"e": 25576,
"s": 25479,
"text": "Tell your module to start drawing using start_render() command which is again built into arcade."
},
{
"code": null,
"e": 25584,
"s": 25576,
"text": "Syntax-"
},
{
"code": null,
"e": 25606,
"s": 25584,
"text": "arcade.start_render()"
},
{
"code": null,
"e": 25685,
"s": 25606,
"text": "Start designing, you can use functions already available with arcade to do so."
},
{
"code": null,
"e": 25763,
"s": 25685,
"text": "Tell arcade module that you have completed the drawing using finish_render()."
},
{
"code": null,
"e": 25771,
"s": 25763,
"text": "Syntax-"
},
{
"code": null,
"e": 25794,
"s": 25771,
"text": "arcade.finish_render()"
},
{
"code": null,
"e": 25821,
"s": 25794,
"text": "Run your code using run()."
},
{
"code": null,
"e": 25829,
"s": 25821,
"text": "Syntax-"
},
{
"code": null,
"e": 25842,
"s": 25829,
"text": "arcade.run()"
},
{
"code": null,
"e": 25903,
"s": 25842,
"text": "Example 1: Python program that uses arcade to draw a circle."
},
{
"code": null,
"e": 25911,
"s": 25903,
"text": "Python3"
},
{
"code": "# Import moduleimport arcade # Specify ParametersWidth = 500Height = 700Title = \"Welcome to Arcade\"Radius = 100 # Open the windowarcade.open_window(Width, Height, Title) # Set the background colorarcade.set_background_color(arcade.color.BLUE) # start drawingarcade.start_render() # Draw a Pink circlearcade.draw_circle_filled( Width/2 , Height/2 , Radius , arcade.color.PINK)# Finish drawingarcade.finish_render() # Display everythingarcade.run()",
"e": 26361,
"s": 25911,
"text": null
},
{
"code": null,
"e": 26372,
"s": 26364,
"text": "Output:"
},
{
"code": null,
"e": 26453,
"s": 26376,
"text": "Example 2: Python program that creates a pattern of circles using the arcade"
},
{
"code": null,
"e": 26463,
"s": 26455,
"text": "Python3"
},
{
"code": "# Import moduleimport arcade #Specify ParametersWidth = 500Height = 700Title = \"Welcome to Arcade\"Radius = 200 # Open the windowarcade.open_window(Width, Height, Title) # Set the background colorarcade.set_background_color(arcade.color.BLACK) # start drawingarcade.start_render() # Draw a BLUE circlearcade.draw_circle_filled( Width/2 , Height/2 , Radius , arcade.color.BLUE) # Draw a Red circlearcade.draw_circle_filled( Width/2 , Height , Radius , arcade.color.RED) # Finish drawingarcade.finish_render()# Display everythingarcade.run()",
"e": 27008,
"s": 26463,
"text": null
},
{
"code": null,
"e": 27019,
"s": 27011,
"text": "Output:"
},
{
"code": null,
"e": 27330,
"s": 27021,
"text": "Arcade is a set of python modules which is a modern Python framework used in designing 2D video games. In Arcade, we have gripping computer graphics and sound libraries in order to design high quality and user-friendly games. Arcade was developed by Paul Vincent Craven. Arcade needs support for OpenGL 3.3+."
},
{
"code": null,
"e": 27375,
"s": 27330,
"text": "Arcade is built on top of Pyglet and OpenGL."
},
{
"code": null,
"e": 27431,
"s": 27375,
"text": "In order to replace Pygame, Arcade came into existence."
},
{
"code": null,
"e": 27476,
"s": 27431,
"text": "Arcade runs on Windows, Mac OS X, and Linux."
},
{
"code": null,
"e": 27544,
"s": 27476,
"text": "Arcade requires Python 3.6 or newer. It does not run on Python 2.x."
},
{
"code": null,
"e": 27680,
"s": 27544,
"text": "Arcade needs support for OpenGL 3.3+. It does not run on Raspberry Pi or Wayland. If on Linux, sound support needs at least GLIB 2.29+."
},
{
"code": null,
"e": 27735,
"s": 27680,
"text": "Arcade uses SoLoud. which Supports panning and volume."
},
{
"code": null,
"e": 27819,
"s": 27735,
"text": "It is possible to create open-source free, shareware, and commercial games with it."
},
{
"code": null,
"e": 27851,
"s": 27819,
"text": "Supports Python 3 type hinting."
},
{
"code": null,
"e": 27950,
"s": 27851,
"text": "Basic drawing does not require knowledge on how to define functions or classes or how to do loops."
},
{
"code": null,
"e": 28092,
"s": 27950,
"text": "Uses a standard coordinate system you learned about in math. (0, 0) is in the lower left, and not upper left. Y-coordinates are not reversed."
},
{
"code": null,
"e": 28138,
"s": 28092,
"text": "API documentation for the commands is better."
},
{
"code": null,
"e": 28700,
"s": 28138,
"text": "Version 2.4.3 was released 2020-09-30. It is the latest version of arcade that has Added PyInstalled hook and tutorial, ShapeLists have no longer share position between instances and with GUI improvement.Version 2.4.2 was released 2020-09-08. It has GPU transformations with the mouse and Updates downloadable .zip for platformer example code to match current code in documentation and much more. Arcade 2.4.1 was released 2020-07-13. Support for defining your own frame buffers, shaders, and more advanced OpenGL programming, PyMunk engine for a platform, etc."
},
{
"code": null,
"e": 28905,
"s": 28700,
"text": "Version 2.4.3 was released 2020-09-30. It is the latest version of arcade that has Added PyInstalled hook and tutorial, ShapeLists have no longer share position between instances and with GUI improvement."
},
{
"code": null,
"e": 29098,
"s": 28905,
"text": "Version 2.4.2 was released 2020-09-08. It has GPU transformations with the mouse and Updates downloadable .zip for platformer example code to match current code in documentation and much more."
},
{
"code": null,
"e": 29264,
"s": 29098,
"text": " Arcade 2.4.1 was released 2020-07-13. Support for defining your own frame buffers, shaders, and more advanced OpenGL programming, PyMunk engine for a platform, etc."
},
{
"code": null,
"e": 29279,
"s": 29264,
"text": "anshitaagarwal"
},
{
"code": null,
"e": 29293,
"s": 29279,
"text": "Python-Arcade"
},
{
"code": null,
"e": 29308,
"s": 29293,
"text": "python-modules"
},
{
"code": null,
"e": 29315,
"s": 29308,
"text": "Python"
},
{
"code": null,
"e": 29413,
"s": 29315,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29422,
"s": 29413,
"text": "Comments"
},
{
"code": null,
"e": 29435,
"s": 29422,
"text": "Old Comments"
},
{
"code": null,
"e": 29453,
"s": 29435,
"text": "Python Dictionary"
},
{
"code": null,
"e": 29488,
"s": 29453,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 29520,
"s": 29488,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 29562,
"s": 29520,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 29588,
"s": 29562,
"text": "Python String | replace()"
},
{
"code": null,
"e": 29631,
"s": 29588,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 29668,
"s": 29631,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 29712,
"s": 29668,
"text": "Reading and Writing to text files in Python"
},
{
"code": null,
"e": 29741,
"s": 29712,
"text": "*args and **kwargs in Python"
}
] |
HTML | <frameset> cols Attribute - GeeksforGeeks | 17 Dec, 2021
The HTML <frameset> cols Attribute is used to specify the size and the number of columns in a frameset. The width of each frame is separated by a comma.
Note: It is not supported in HTML5.
Syntax:
<frameset cols="pixels | % | *">
Attribute Values:
pixels: The width of column is set in terms of pixels. Example: “50px” or “50”.
%: The width of columns is set in terms of percentage. Example “70%”.
*: The width of columns is set to all available space.
Example:
<!DOCTYPE html> <html> <head> <title>HTML frameset cols Attribute</title> </head> <frameset cols = "30%, 40%, 30%"> <frame name = "top" src = "attr1.png" /> <frame name = "main" src = "gradient3.png" /> <frame name = "bottom" src = "col_last.png" /> </frameset> </html>
Output:
Supported Browsers: The browser supported by HTML <frameset> cols Attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Safari
Opera
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
chhabradhanvi
HTML-Attributes
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to update Node.js and NPM to next version ?
How to Insert Form Data into Database using PHP ?
CSS to put icon inside an input element in a form
REST API (Introduction)
Types of CSS (Cascading Style Sheet)
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Convert a string to an integer in JavaScript
How to calculate the number of days between two dates in javascript? | [
{
"code": null,
"e": 24636,
"s": 24608,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 24789,
"s": 24636,
"text": "The HTML <frameset> cols Attribute is used to specify the size and the number of columns in a frameset. The width of each frame is separated by a comma."
},
{
"code": null,
"e": 24825,
"s": 24789,
"text": "Note: It is not supported in HTML5."
},
{
"code": null,
"e": 24833,
"s": 24825,
"text": "Syntax:"
},
{
"code": null,
"e": 24866,
"s": 24833,
"text": "<frameset cols=\"pixels | % | *\">"
},
{
"code": null,
"e": 24884,
"s": 24866,
"text": "Attribute Values:"
},
{
"code": null,
"e": 24964,
"s": 24884,
"text": "pixels: The width of column is set in terms of pixels. Example: “50px” or “50”."
},
{
"code": null,
"e": 25034,
"s": 24964,
"text": "%: The width of columns is set in terms of percentage. Example “70%”."
},
{
"code": null,
"e": 25089,
"s": 25034,
"text": "*: The width of columns is set to all available space."
},
{
"code": null,
"e": 25098,
"s": 25089,
"text": "Example:"
},
{
"code": "<!DOCTYPE html> <html> <head> <title>HTML frameset cols Attribute</title> </head> <frameset cols = \"30%, 40%, 30%\"> <frame name = \"top\" src = \"attr1.png\" /> <frame name = \"main\" src = \"gradient3.png\" /> <frame name = \"bottom\" src = \"col_last.png\" /> </frameset> </html>",
"e": 25438,
"s": 25098,
"text": null
},
{
"code": null,
"e": 25446,
"s": 25438,
"text": "Output:"
},
{
"code": null,
"e": 25540,
"s": 25446,
"text": "Supported Browsers: The browser supported by HTML <frameset> cols Attribute are listed below:"
},
{
"code": null,
"e": 25554,
"s": 25540,
"text": "Google Chrome"
},
{
"code": null,
"e": 25572,
"s": 25554,
"text": "Internet Explorer"
},
{
"code": null,
"e": 25580,
"s": 25572,
"text": "Firefox"
},
{
"code": null,
"e": 25587,
"s": 25580,
"text": "Safari"
},
{
"code": null,
"e": 25593,
"s": 25587,
"text": "Opera"
},
{
"code": null,
"e": 25730,
"s": 25593,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 25744,
"s": 25730,
"text": "chhabradhanvi"
},
{
"code": null,
"e": 25760,
"s": 25744,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 25765,
"s": 25760,
"text": "HTML"
},
{
"code": null,
"e": 25782,
"s": 25765,
"text": "Web Technologies"
},
{
"code": null,
"e": 25787,
"s": 25782,
"text": "HTML"
},
{
"code": null,
"e": 25885,
"s": 25787,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25894,
"s": 25885,
"text": "Comments"
},
{
"code": null,
"e": 25907,
"s": 25894,
"text": "Old Comments"
},
{
"code": null,
"e": 25955,
"s": 25907,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 26005,
"s": 25955,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 26055,
"s": 26005,
"text": "CSS to put icon inside an input element in a form"
},
{
"code": null,
"e": 26079,
"s": 26055,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 26116,
"s": 26079,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26158,
"s": 26116,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 26191,
"s": 26158,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26234,
"s": 26191,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 26279,
"s": 26234,
"text": "Convert a string to an integer in JavaScript"
}
] |
Absolute and Relative Imports in Python - GeeksforGeeks | 29 Dec, 2018
Working of import in python :
Import in Python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. Import statement consists of the import keyword along with the name of the module.
The import statement involves two operations, it searches for a module and it binds the result of the search to name in local scope. When a module is imported, Python runs all of the code in the module file and made available to the importer file.
When a module is imported then interpreter first searches it in sys.modules , which is the cache of all modules which have been previously imported. If it is not found then it searches in all built-in modules with that name, if it is found then interpreter runs all of the code and made available to file. If the module is not found then it searches for a file with the same name in the list of directories given by the variable sys.path.sys.path is a variable containing a list of paths that contains python libraries, packages, and a directory containing the input script. For example a module named math is imported then interpreter search it in a built-in modules, if it is not found then it searches for a file named math.py in list of directories given by sys.path.
# Python program importing# math module import mathprint(math.pi)
Output:
3.141592653589793
Syntax of import statements :User can import both packages and modules. (Note that importing a package essentially imports the package’s __init__.py file as a module.) User can also import specific objects from a package or module.There are generally two types of import syntax. When you use the first one, you import the resource directly.
import gfg
gfg can be a package or a module.
When user uses the second syntax, then user import the resource from another package or module.
from gfg import geek
geek can be a module, subpackage, or object, such as a class or function. Styling of import statements :PEP8, the official style guide for python, has set of rules for how to formulate the python code to maximize its readability. For writing import statements there are some points to follow:
Imports should always be written at the top of the file, just after any module comments and docstrings.Imports should usually be separated by a blank space.Imports should be grouped in the following order.Standard library imports (Python’s built-in modules)Related third party imports.Local application/library specific imports
Imports should always be written at the top of the file, just after any module comments and docstrings.
Imports should usually be separated by a blank space.
Imports should be grouped in the following order.Standard library imports (Python’s built-in modules)Related third party imports.Local application/library specific imports
Standard library imports (Python’s built-in modules)
Related third party imports.
Local application/library specific imports
It is also good to order import statements alphabetically within each import group.
# Python program showing# how to style import statements import mathimport os # Third party importsfrom flask import Flaskfrom flask_restful import Apifrom flask_sqlalchemy import SQLAlchemy # Local application importsfrom local_module import local_classfrom local_package import local_function
Absolute import involves full path i.e., from the project’s root folder to the desired module. An absolute import state that the resource to be imported using its full path from the project’s root folder.
Syntax and Practical Examples :Let’s see we have the following directory structure:Here a directory named project, under which two subdirectories namely pkg1, pkg2. pkg1 has two modules, module1 and module2.pkg2 contains three modules, module3, module4, __init__.py and one subpackage name subpkg1 which contains module5.py. Let’s assume the following:
pkg1 / module1.py contain a function, fun1
pkg2 / module3.py contain a function, fun2
pkg2 / subpkg1 / module5.py contain a function fun3
# Python program showing# practical example of# absolute imports # importing a fun1 from pkg1/module1from pkg1.import module1 import fun1 from pkg1 import module2 # importing a fun2 from pkg2/module3from pkg2 import module3 import fun2 # importing a fun3 from pkg2/subpkg1/module5from pkg2.subpkg1.module5 import fun3
In this example, we are importing the modules by writing full path from its root folder. Pros and Cons of Absolute imports :Pros:
Absolute imports are very useful because they are clear and straight to the point.
Absolute import is easy to tell exactly from where the imported resource is, just by looking at the statement.
Absolute import remain valid even if the current location of the import statement changes.
Cons:If the directory structure is very big then usage of absolute imports is not meaningful. In such case using relative imports works well.
from pkg1.subpkg2.subpkg3.subpkg4.module5 import fun6
Relative import specifies object or module imported from its current location, that is the location where import statement resides. There two types of relative imports :
Implicit relative imports :Implicit relative import have been disapproved in Python(3.x).
Implicit relative import have been disapproved in Python(3.x).
Explicit relative imports :Explicit relative import have been approved in Python(3.x).
Explicit relative import have been approved in Python(3.x).
Syntax and Practical Examples :The syntax of relative import depends on current location as well as a location of module or object to be imported. Relative imports use dot(.) notation to specify a location. Single dot specifies that the module is in the current directory, two dots indicate that module is in its parent directory of the current location and three dots indicate that it is in grandparent directory and so on.Let’s see we have the following directory structure:Let’s assume the following:
pkg1 / module1.py contain a function, fun1
pkg2 / module3.py contain a function, fun2
pkg2 / subpkg1 / module5.py contain a function fun3
# Python program showing# practical example of# relative imports # importing fun1 into pkg1/module1.pyfrom .module1 import fun1 # importing fun2 and fun3 into pkg2/module3.py from .module3 import fun2from .subpackage1.module5 import fun3
Pros and Cons of Relative imports :Pros:
Working with relative imports is concise and clear.
Based on current location it reduces the complexity of an import statement .Cons:Relative imports is not so readable as absolute ones.Using relative imports it is not easy because it is very hard to tell the location of a module.My Personal Notes
arrow_drop_upSave
Relative imports is not so readable as absolute ones.
Using relative imports it is not easy because it is very hard to tell the location of a module.
Picked
python-modules
Technical Scripter 2018
Python
Technical Scripter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24647,
"s": 24619,
"text": "\n29 Dec, 2018"
},
{
"code": null,
"e": 24677,
"s": 24647,
"text": "Working of import in python :"
},
{
"code": null,
"e": 25031,
"s": 24677,
"text": "Import in Python is similar to #include header_file in C/C++. Python modules can get access to code from another module by importing the file/function using import. The import statement is the most common way of invoking the import machinery, but it is not the only way. Import statement consists of the import keyword along with the name of the module."
},
{
"code": null,
"e": 25279,
"s": 25031,
"text": "The import statement involves two operations, it searches for a module and it binds the result of the search to name in local scope. When a module is imported, Python runs all of the code in the module file and made available to the importer file."
},
{
"code": null,
"e": 26051,
"s": 25279,
"text": "When a module is imported then interpreter first searches it in sys.modules , which is the cache of all modules which have been previously imported. If it is not found then it searches in all built-in modules with that name, if it is found then interpreter runs all of the code and made available to file. If the module is not found then it searches for a file with the same name in the list of directories given by the variable sys.path.sys.path is a variable containing a list of paths that contains python libraries, packages, and a directory containing the input script. For example a module named math is imported then interpreter search it in a built-in modules, if it is not found then it searches for a file named math.py in list of directories given by sys.path."
},
{
"code": "# Python program importing# math module import mathprint(math.pi)",
"e": 26118,
"s": 26051,
"text": null
},
{
"code": null,
"e": 26126,
"s": 26118,
"text": "Output:"
},
{
"code": null,
"e": 26145,
"s": 26126,
"text": "3.141592653589793\n"
},
{
"code": null,
"e": 26487,
"s": 26145,
"text": " Syntax of import statements :User can import both packages and modules. (Note that importing a package essentially imports the package’s __init__.py file as a module.) User can also import specific objects from a package or module.There are generally two types of import syntax. When you use the first one, you import the resource directly."
},
{
"code": null,
"e": 26499,
"s": 26487,
"text": "import gfg\n"
},
{
"code": null,
"e": 26533,
"s": 26499,
"text": "gfg can be a package or a module."
},
{
"code": null,
"e": 26629,
"s": 26533,
"text": "When user uses the second syntax, then user import the resource from another package or module."
},
{
"code": null,
"e": 26651,
"s": 26629,
"text": "from gfg import geek\n"
},
{
"code": null,
"e": 26944,
"s": 26651,
"text": "geek can be a module, subpackage, or object, such as a class or function. Styling of import statements :PEP8, the official style guide for python, has set of rules for how to formulate the python code to maximize its readability. For writing import statements there are some points to follow:"
},
{
"code": null,
"e": 27272,
"s": 26944,
"text": "Imports should always be written at the top of the file, just after any module comments and docstrings.Imports should usually be separated by a blank space.Imports should be grouped in the following order.Standard library imports (Python’s built-in modules)Related third party imports.Local application/library specific imports"
},
{
"code": null,
"e": 27376,
"s": 27272,
"text": "Imports should always be written at the top of the file, just after any module comments and docstrings."
},
{
"code": null,
"e": 27430,
"s": 27376,
"text": "Imports should usually be separated by a blank space."
},
{
"code": null,
"e": 27602,
"s": 27430,
"text": "Imports should be grouped in the following order.Standard library imports (Python’s built-in modules)Related third party imports.Local application/library specific imports"
},
{
"code": null,
"e": 27655,
"s": 27602,
"text": "Standard library imports (Python’s built-in modules)"
},
{
"code": null,
"e": 27684,
"s": 27655,
"text": "Related third party imports."
},
{
"code": null,
"e": 27727,
"s": 27684,
"text": "Local application/library specific imports"
},
{
"code": null,
"e": 27811,
"s": 27727,
"text": "It is also good to order import statements alphabetically within each import group."
},
{
"code": "# Python program showing# how to style import statements import mathimport os # Third party importsfrom flask import Flaskfrom flask_restful import Apifrom flask_sqlalchemy import SQLAlchemy # Local application importsfrom local_module import local_classfrom local_package import local_function",
"e": 28109,
"s": 27811,
"text": null
},
{
"code": null,
"e": 28316,
"s": 28111,
"text": "Absolute import involves full path i.e., from the project’s root folder to the desired module. An absolute import state that the resource to be imported using its full path from the project’s root folder."
},
{
"code": null,
"e": 28669,
"s": 28316,
"text": "Syntax and Practical Examples :Let’s see we have the following directory structure:Here a directory named project, under which two subdirectories namely pkg1, pkg2. pkg1 has two modules, module1 and module2.pkg2 contains three modules, module3, module4, __init__.py and one subpackage name subpkg1 which contains module5.py. Let’s assume the following:"
},
{
"code": null,
"e": 28712,
"s": 28669,
"text": "pkg1 / module1.py contain a function, fun1"
},
{
"code": null,
"e": 28755,
"s": 28712,
"text": "pkg2 / module3.py contain a function, fun2"
},
{
"code": null,
"e": 28807,
"s": 28755,
"text": "pkg2 / subpkg1 / module5.py contain a function fun3"
},
{
"code": "# Python program showing# practical example of# absolute imports # importing a fun1 from pkg1/module1from pkg1.import module1 import fun1 from pkg1 import module2 # importing a fun2 from pkg2/module3from pkg2 import module3 import fun2 # importing a fun3 from pkg2/subpkg1/module5from pkg2.subpkg1.module5 import fun3",
"e": 29129,
"s": 28807,
"text": null
},
{
"code": null,
"e": 29259,
"s": 29129,
"text": "In this example, we are importing the modules by writing full path from its root folder. Pros and Cons of Absolute imports :Pros:"
},
{
"code": null,
"e": 29342,
"s": 29259,
"text": "Absolute imports are very useful because they are clear and straight to the point."
},
{
"code": null,
"e": 29453,
"s": 29342,
"text": "Absolute import is easy to tell exactly from where the imported resource is, just by looking at the statement."
},
{
"code": null,
"e": 29544,
"s": 29453,
"text": "Absolute import remain valid even if the current location of the import statement changes."
},
{
"code": null,
"e": 29686,
"s": 29544,
"text": "Cons:If the directory structure is very big then usage of absolute imports is not meaningful. In such case using relative imports works well."
},
{
"code": null,
"e": 29741,
"s": 29686,
"text": "from pkg1.subpkg2.subpkg3.subpkg4.module5 import fun6\n"
},
{
"code": null,
"e": 29911,
"s": 29741,
"text": "Relative import specifies object or module imported from its current location, that is the location where import statement resides. There two types of relative imports :"
},
{
"code": null,
"e": 30001,
"s": 29911,
"text": "Implicit relative imports :Implicit relative import have been disapproved in Python(3.x)."
},
{
"code": null,
"e": 30064,
"s": 30001,
"text": "Implicit relative import have been disapproved in Python(3.x)."
},
{
"code": null,
"e": 30151,
"s": 30064,
"text": "Explicit relative imports :Explicit relative import have been approved in Python(3.x)."
},
{
"code": null,
"e": 30211,
"s": 30151,
"text": "Explicit relative import have been approved in Python(3.x)."
},
{
"code": null,
"e": 30715,
"s": 30211,
"text": "Syntax and Practical Examples :The syntax of relative import depends on current location as well as a location of module or object to be imported. Relative imports use dot(.) notation to specify a location. Single dot specifies that the module is in the current directory, two dots indicate that module is in its parent directory of the current location and three dots indicate that it is in grandparent directory and so on.Let’s see we have the following directory structure:Let’s assume the following:"
},
{
"code": null,
"e": 30758,
"s": 30715,
"text": "pkg1 / module1.py contain a function, fun1"
},
{
"code": null,
"e": 30801,
"s": 30758,
"text": "pkg2 / module3.py contain a function, fun2"
},
{
"code": null,
"e": 30853,
"s": 30801,
"text": "pkg2 / subpkg1 / module5.py contain a function fun3"
},
{
"code": "# Python program showing# practical example of# relative imports # importing fun1 into pkg1/module1.pyfrom .module1 import fun1 # importing fun2 and fun3 into pkg2/module3.py from .module3 import fun2from .subpackage1.module5 import fun3",
"e": 31093,
"s": 30853,
"text": null
},
{
"code": null,
"e": 31134,
"s": 31093,
"text": "Pros and Cons of Relative imports :Pros:"
},
{
"code": null,
"e": 31186,
"s": 31134,
"text": "Working with relative imports is concise and clear."
},
{
"code": null,
"e": 31451,
"s": 31186,
"text": "Based on current location it reduces the complexity of an import statement .Cons:Relative imports is not so readable as absolute ones.Using relative imports it is not easy because it is very hard to tell the location of a module.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 31505,
"s": 31451,
"text": "Relative imports is not so readable as absolute ones."
},
{
"code": null,
"e": 31601,
"s": 31505,
"text": "Using relative imports it is not easy because it is very hard to tell the location of a module."
},
{
"code": null,
"e": 31608,
"s": 31601,
"text": "Picked"
},
{
"code": null,
"e": 31623,
"s": 31608,
"text": "python-modules"
},
{
"code": null,
"e": 31647,
"s": 31623,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 31654,
"s": 31647,
"text": "Python"
},
{
"code": null,
"e": 31673,
"s": 31654,
"text": "Technical Scripter"
},
{
"code": null,
"e": 31771,
"s": 31673,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31789,
"s": 31771,
"text": "Python Dictionary"
},
{
"code": null,
"e": 31824,
"s": 31789,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 31846,
"s": 31824,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 31878,
"s": 31846,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 31908,
"s": 31878,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 31950,
"s": 31908,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 31976,
"s": 31950,
"text": "Python String | replace()"
},
{
"code": null,
"e": 32013,
"s": 31976,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 32056,
"s": 32013,
"text": "Python program to convert a list to string"
}
] |
Kafdrop. An Open-Source Kafka UI | by Emil Koutanov | Towards Data Science | As a messaging platform, Kafka needs no introduction. Since its inception, it has virtually rewritten the book on event streaming and has catalyzed the adoption of the now household design patterns — microservices, event-sourcing, and CQRS.
Being such a godsend, it almost gets away with its notorious lack of tooling. You’d be hard-pressed to find a developer who hasn’t at one time looked at the built-in CLI tools, cupped their face and uttered: “Is this it? Are you kidding me?”
With the popularity of Kafka, it’s no surprise that several commercial vendors have jumped on the opportunity to monetize Kafka’s apparent lack of tooling by offering their own. Kafka Tool, Landoop, and KaDeck are some examples, but they’re all for personal use only unless you’re willing to pay. (And it’s not to say that you shouldn’t, au contraire, but that’s rather beside the point.) Any non-trivial use in a commercial setting would be a violation of their licensing terms. It’s one thing using them at home for tutorials or personal projects; when you’re using a commercial tool without the appropriate license, you are putting your employer at risk of litigation and playing Russian Roulette with your career.
But what about open-source?
When it comes to Kafka topic viewers and web UIs, the go-to open-source tool is Kafdrop. With 800K Docker pulls at the time of writing, there aren’t many Kafka tools that have enjoyed this level of adoption. And there’s a reason behind that: Kafdrop does an amazing job of filling the apparent gaps in the observability tooling of Kafka, solving problems that the community has been pointing out for too long.
Kafdrop is an Apache 2.0 licensed project, like Apache Kafka itself. So it’s won’t cost you a penny. If you haven’t used it yet, you probably ought to. So let’s take a deeper look.
View Kafka brokers — topic and partition assignments, and controller status
View topics — partition count, replication status, and custom configuration
Browse messages — JSON, plain text and Avro encoding
View consumer groups — per-partition parked offsets, combined and per-partition lag
Create new topics
View ACLs
The Kafdrop web UI project is hosted on GitHub:
There’s a couple of options at your disposal. You could show a little bravery by cloning the repository and building from source. It’s a Java (JDK 11) Spring Boot project, and you can build it with a single Maven command, providing you have the JDK installed. If you want to go down this path, the repo’s README.md file will guide you through the steps. For now, let's take the easy way — Docker. (I sure would.)
Docker images are hosted on DockerHub. Images are tagged with the Kafdrop release number. The latest tag points to the latest stable release.
To launch the container in the foreground, run the following command:
docker run -it --rm -p 9000:9000 \ -e KAFKA_BROKERCONNECT=<host:port,host:port> \ obsidiandynamics/kafdrop
The KAFKA_BROKERCONNECT environment variable must be set to the bootstrap list of brokers.
That’s it. We should be up and running. Once it starts, you can launch the Kafka web UI by navigating to localhost:9000.
Note: The above example assumes an authenticated connection over a plaintext TCP socket. If your cluster is configured to use authentication and/or transport-level encryption, consult the README.md for connection options. It's actually surprisingly easy to configure Kafdrop for a SASL/SSL locked-down cluster.
Don’t have a Kafka broker running? No worries. Just use the following docker-compose.yaml file to bring up a Kafka + Kafdrop stack:
version: "2"services: kafdrop: image: obsidiandynamics/kafdrop restart: "no" ports: - "9000:9000" environment: KAFKA_BROKERCONNECT: "kafka:29092" depends_on: - "kafka" kafka: image: obsidiandynamics/kafka restart: "no" ports: - "2181:2181" - "9092:9092" environment: KAFKA_LISTENERS: "INTERNAL://:29092,EXTERNAL://:9092" KAFKA_ADVERTISED_LISTENERS: "INTERNAL://kafka:29092,EXTERNAL://localhost:9092" KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: "INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT" KAFKA_INTER_BROKER_LISTENER_NAME: "INTERNAL"
Now launch the stack with docker-compose up. Once started, browse to localhost:9000.
The Cluster Overview screen is the landing page of the web UI.
You get to see the overall layout of the cluster — the individual brokers that make it up, their addresses and some key broker stats — whether they are a controller and the number of partitions each broker owns. The latter is quite important — as your cluster size and the number of topics (and therefore partitions) grows, you generally want to see an approximately level distribution of partitions across the cluster.
Next is the Topics List, which in most cases is what you’re really here for. Any reasonably-sized microservices-based ecosystem might have hundreds, if not thousands of topics. As you’d expect, the list is searchable. The stats displayed alongside each topic are fairly ho-hum. The one worth noting is the under-replicated column. Essentially, it’s telling us the number of partition replicas that have fallen behind the primary. Zero is a good figure. Anything else is indicative of either a broker or a network issue that requires immediate attention.
Note: Kafdrop is a discovery exploration tool; it is not a real-time monitoring tool. You should instrument your brokers and raise alerts when things go awry.
Click on a topic on the list to get to the Topic Overview screen.
The screen is subdivided into four sections.
On the top-left, there is a summary of the topic stats — a handy view, not dissimilar to what you would have seen in the cluster overview.
On the top-right, you can view the custom configuration. In the example above, the topic runs a stock-standard config, so there’s nothing to see. Had the configuration been overridden, you’d see a set of custom values like in the example below.
The bottom-left section enumerates over the partitions. The partition indexes are links — clicking through will reveal the first 100 messages in the topic.
There are several interesting parameters displayed in this section:
Partition ID: The zero-based index of the partition within its encompassing topic.
First offset: The offset of the earliest message in the partition. If the partition is empty, the first offset is the same as the high-water mark.
Last offset: The high-watermark of the partition, is the offset that will be assigned to the next published message.
Size: The number of messages in the partition.
Leader Node: The ID of the broker node that is presently acting as the leader.
Replica Nodes: The IDs of all broker nodes that hold a replica of the partition. This includes the leader ID.
In-sync Replica Nodes: The IDs of replica nodes that are in-sync, inclusive of the leader node.
Offline Replica Nodes: The IDs of replica nodes that are currently offline. Under healthy conditions, this should be an empty set.
Preferred Leader: Whether the current leader node happens to be the preferred one.
Under-replicated: Whether the partition is under-replicated, i.e. there is at least one replica that is not in sync with the primary.
The consumers’ section on the bottom-right lists the consumer group names as well as their aggregate lag (the sum of all individual partition lags).
Clicking on the consumer group on the Topic Overview gets you into the Consumer View. This screen provides a comprehensive breakdown of a single consumer group.
The view is sectioned by topic. For each topic, a separate table lists the underlying partitions. Against each partition, we see the committed offset, which we can compare against the first and last offsets to see how our consumer is tracking. Conveniently, Kafdrop displays the computed lag for each partition, which is aggregated at the footer of each topic table.
Note: Some amount of lag is unavoidable. For every message published, there will invariably be a quantum of time between the point of publishing and the point of consumption. In Kafka, this period is usually in the order of tens or hundreds of milliseconds, depending on both the producer and consumer client options, network configuration, broker I/O capabilities, the size of the pagecache and a myriad of other factors. What you need to look out for is growing lag — suggesting that the consumer is either unable to keep up or has stalled altogether. In the latter case, you’ll also notice that the lag isn’t being depleted even when the producer is idling. This is when you’ll need to ALT-TAB away from Kafdrop into your favourite debugger.
The Message View screen is the coveted topic viewer that has in all likelihood brought you here. You can get to the message view in one of two ways:
Click the View Messages button on the Topic Overview screen.Click the individual partition link in the Topic Overview.
Click the View Messages button on the Topic Overview screen.
Click the individual partition link in the Topic Overview.
It’s exactly what you’d expect — a chronologically-ordered list of messages (or records, in Kafka parlance) for a chosen partition.
Each entry conveniently displays the offset, the record key (if one is set), the timestamp of publication, and any headers that may have been appended by the producer.
There’s another little trick up Kafdrop’s sleeve. If the message happens to be a valid JSON document, the topic viewer can nicely format it. Click on the green arrow on the left of the message to expand it.
The more you use Kafka, the more you come to discover and appreciate its true potential — not just as a versatile event streaming platform, but as a general-purpose messaging middleware that lets you assemble complex business systems from asynchronous, loosely coupled services.
You’ll invariably experience the frustrations that are to be expected from a technology that has only recently entered the mainstream, by comparison with the more mature MQ brokers of yore. What’s reassuring is that the Open Source community hasn’t stood still, producing an evolving ecosystem, complete with the documentation and tooling necessary for us to get on with our jobs. The least we can do in return is raise a pull request once in a while or maybe answer a StackOverflow question or three.
Was this article useful to you? I’d love to hear your feedback, so don’t hold back! If you are interested in Kafka or event streaming, or just have any questions, follow me on Twitter. | [
{
"code": null,
"e": 412,
"s": 171,
"text": "As a messaging platform, Kafka needs no introduction. Since its inception, it has virtually rewritten the book on event streaming and has catalyzed the adoption of the now household design patterns — microservices, event-sourcing, and CQRS."
},
{
"code": null,
"e": 654,
"s": 412,
"text": "Being such a godsend, it almost gets away with its notorious lack of tooling. You’d be hard-pressed to find a developer who hasn’t at one time looked at the built-in CLI tools, cupped their face and uttered: “Is this it? Are you kidding me?”"
},
{
"code": null,
"e": 1372,
"s": 654,
"text": "With the popularity of Kafka, it’s no surprise that several commercial vendors have jumped on the opportunity to monetize Kafka’s apparent lack of tooling by offering their own. Kafka Tool, Landoop, and KaDeck are some examples, but they’re all for personal use only unless you’re willing to pay. (And it’s not to say that you shouldn’t, au contraire, but that’s rather beside the point.) Any non-trivial use in a commercial setting would be a violation of their licensing terms. It’s one thing using them at home for tutorials or personal projects; when you’re using a commercial tool without the appropriate license, you are putting your employer at risk of litigation and playing Russian Roulette with your career."
},
{
"code": null,
"e": 1400,
"s": 1372,
"text": "But what about open-source?"
},
{
"code": null,
"e": 1810,
"s": 1400,
"text": "When it comes to Kafka topic viewers and web UIs, the go-to open-source tool is Kafdrop. With 800K Docker pulls at the time of writing, there aren’t many Kafka tools that have enjoyed this level of adoption. And there’s a reason behind that: Kafdrop does an amazing job of filling the apparent gaps in the observability tooling of Kafka, solving problems that the community has been pointing out for too long."
},
{
"code": null,
"e": 1991,
"s": 1810,
"text": "Kafdrop is an Apache 2.0 licensed project, like Apache Kafka itself. So it’s won’t cost you a penny. If you haven’t used it yet, you probably ought to. So let’s take a deeper look."
},
{
"code": null,
"e": 2067,
"s": 1991,
"text": "View Kafka brokers — topic and partition assignments, and controller status"
},
{
"code": null,
"e": 2143,
"s": 2067,
"text": "View topics — partition count, replication status, and custom configuration"
},
{
"code": null,
"e": 2196,
"s": 2143,
"text": "Browse messages — JSON, plain text and Avro encoding"
},
{
"code": null,
"e": 2280,
"s": 2196,
"text": "View consumer groups — per-partition parked offsets, combined and per-partition lag"
},
{
"code": null,
"e": 2298,
"s": 2280,
"text": "Create new topics"
},
{
"code": null,
"e": 2308,
"s": 2298,
"text": "View ACLs"
},
{
"code": null,
"e": 2356,
"s": 2308,
"text": "The Kafdrop web UI project is hosted on GitHub:"
},
{
"code": null,
"e": 2769,
"s": 2356,
"text": "There’s a couple of options at your disposal. You could show a little bravery by cloning the repository and building from source. It’s a Java (JDK 11) Spring Boot project, and you can build it with a single Maven command, providing you have the JDK installed. If you want to go down this path, the repo’s README.md file will guide you through the steps. For now, let's take the easy way — Docker. (I sure would.)"
},
{
"code": null,
"e": 2911,
"s": 2769,
"text": "Docker images are hosted on DockerHub. Images are tagged with the Kafdrop release number. The latest tag points to the latest stable release."
},
{
"code": null,
"e": 2981,
"s": 2911,
"text": "To launch the container in the foreground, run the following command:"
},
{
"code": null,
"e": 3094,
"s": 2981,
"text": "docker run -it --rm -p 9000:9000 \\ -e KAFKA_BROKERCONNECT=<host:port,host:port> \\ obsidiandynamics/kafdrop"
},
{
"code": null,
"e": 3185,
"s": 3094,
"text": "The KAFKA_BROKERCONNECT environment variable must be set to the bootstrap list of brokers."
},
{
"code": null,
"e": 3306,
"s": 3185,
"text": "That’s it. We should be up and running. Once it starts, you can launch the Kafka web UI by navigating to localhost:9000."
},
{
"code": null,
"e": 3617,
"s": 3306,
"text": "Note: The above example assumes an authenticated connection over a plaintext TCP socket. If your cluster is configured to use authentication and/or transport-level encryption, consult the README.md for connection options. It's actually surprisingly easy to configure Kafdrop for a SASL/SSL locked-down cluster."
},
{
"code": null,
"e": 3749,
"s": 3617,
"text": "Don’t have a Kafka broker running? No worries. Just use the following docker-compose.yaml file to bring up a Kafka + Kafdrop stack:"
},
{
"code": null,
"e": 4346,
"s": 3749,
"text": "version: \"2\"services: kafdrop: image: obsidiandynamics/kafdrop restart: \"no\" ports: - \"9000:9000\" environment: KAFKA_BROKERCONNECT: \"kafka:29092\" depends_on: - \"kafka\" kafka: image: obsidiandynamics/kafka restart: \"no\" ports: - \"2181:2181\" - \"9092:9092\" environment: KAFKA_LISTENERS: \"INTERNAL://:29092,EXTERNAL://:9092\" KAFKA_ADVERTISED_LISTENERS: \"INTERNAL://kafka:29092,EXTERNAL://localhost:9092\" KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: \"INTERNAL:PLAINTEXT,EXTERNAL:PLAINTEXT\" KAFKA_INTER_BROKER_LISTENER_NAME: \"INTERNAL\""
},
{
"code": null,
"e": 4431,
"s": 4346,
"text": "Now launch the stack with docker-compose up. Once started, browse to localhost:9000."
},
{
"code": null,
"e": 4494,
"s": 4431,
"text": "The Cluster Overview screen is the landing page of the web UI."
},
{
"code": null,
"e": 4914,
"s": 4494,
"text": "You get to see the overall layout of the cluster — the individual brokers that make it up, their addresses and some key broker stats — whether they are a controller and the number of partitions each broker owns. The latter is quite important — as your cluster size and the number of topics (and therefore partitions) grows, you generally want to see an approximately level distribution of partitions across the cluster."
},
{
"code": null,
"e": 5468,
"s": 4914,
"text": "Next is the Topics List, which in most cases is what you’re really here for. Any reasonably-sized microservices-based ecosystem might have hundreds, if not thousands of topics. As you’d expect, the list is searchable. The stats displayed alongside each topic are fairly ho-hum. The one worth noting is the under-replicated column. Essentially, it’s telling us the number of partition replicas that have fallen behind the primary. Zero is a good figure. Anything else is indicative of either a broker or a network issue that requires immediate attention."
},
{
"code": null,
"e": 5627,
"s": 5468,
"text": "Note: Kafdrop is a discovery exploration tool; it is not a real-time monitoring tool. You should instrument your brokers and raise alerts when things go awry."
},
{
"code": null,
"e": 5693,
"s": 5627,
"text": "Click on a topic on the list to get to the Topic Overview screen."
},
{
"code": null,
"e": 5738,
"s": 5693,
"text": "The screen is subdivided into four sections."
},
{
"code": null,
"e": 5877,
"s": 5738,
"text": "On the top-left, there is a summary of the topic stats — a handy view, not dissimilar to what you would have seen in the cluster overview."
},
{
"code": null,
"e": 6122,
"s": 5877,
"text": "On the top-right, you can view the custom configuration. In the example above, the topic runs a stock-standard config, so there’s nothing to see. Had the configuration been overridden, you’d see a set of custom values like in the example below."
},
{
"code": null,
"e": 6278,
"s": 6122,
"text": "The bottom-left section enumerates over the partitions. The partition indexes are links — clicking through will reveal the first 100 messages in the topic."
},
{
"code": null,
"e": 6346,
"s": 6278,
"text": "There are several interesting parameters displayed in this section:"
},
{
"code": null,
"e": 6429,
"s": 6346,
"text": "Partition ID: The zero-based index of the partition within its encompassing topic."
},
{
"code": null,
"e": 6576,
"s": 6429,
"text": "First offset: The offset of the earliest message in the partition. If the partition is empty, the first offset is the same as the high-water mark."
},
{
"code": null,
"e": 6693,
"s": 6576,
"text": "Last offset: The high-watermark of the partition, is the offset that will be assigned to the next published message."
},
{
"code": null,
"e": 6740,
"s": 6693,
"text": "Size: The number of messages in the partition."
},
{
"code": null,
"e": 6819,
"s": 6740,
"text": "Leader Node: The ID of the broker node that is presently acting as the leader."
},
{
"code": null,
"e": 6929,
"s": 6819,
"text": "Replica Nodes: The IDs of all broker nodes that hold a replica of the partition. This includes the leader ID."
},
{
"code": null,
"e": 7025,
"s": 6929,
"text": "In-sync Replica Nodes: The IDs of replica nodes that are in-sync, inclusive of the leader node."
},
{
"code": null,
"e": 7156,
"s": 7025,
"text": "Offline Replica Nodes: The IDs of replica nodes that are currently offline. Under healthy conditions, this should be an empty set."
},
{
"code": null,
"e": 7239,
"s": 7156,
"text": "Preferred Leader: Whether the current leader node happens to be the preferred one."
},
{
"code": null,
"e": 7373,
"s": 7239,
"text": "Under-replicated: Whether the partition is under-replicated, i.e. there is at least one replica that is not in sync with the primary."
},
{
"code": null,
"e": 7522,
"s": 7373,
"text": "The consumers’ section on the bottom-right lists the consumer group names as well as their aggregate lag (the sum of all individual partition lags)."
},
{
"code": null,
"e": 7683,
"s": 7522,
"text": "Clicking on the consumer group on the Topic Overview gets you into the Consumer View. This screen provides a comprehensive breakdown of a single consumer group."
},
{
"code": null,
"e": 8050,
"s": 7683,
"text": "The view is sectioned by topic. For each topic, a separate table lists the underlying partitions. Against each partition, we see the committed offset, which we can compare against the first and last offsets to see how our consumer is tracking. Conveniently, Kafdrop displays the computed lag for each partition, which is aggregated at the footer of each topic table."
},
{
"code": null,
"e": 8795,
"s": 8050,
"text": "Note: Some amount of lag is unavoidable. For every message published, there will invariably be a quantum of time between the point of publishing and the point of consumption. In Kafka, this period is usually in the order of tens or hundreds of milliseconds, depending on both the producer and consumer client options, network configuration, broker I/O capabilities, the size of the pagecache and a myriad of other factors. What you need to look out for is growing lag — suggesting that the consumer is either unable to keep up or has stalled altogether. In the latter case, you’ll also notice that the lag isn’t being depleted even when the producer is idling. This is when you’ll need to ALT-TAB away from Kafdrop into your favourite debugger."
},
{
"code": null,
"e": 8944,
"s": 8795,
"text": "The Message View screen is the coveted topic viewer that has in all likelihood brought you here. You can get to the message view in one of two ways:"
},
{
"code": null,
"e": 9063,
"s": 8944,
"text": "Click the View Messages button on the Topic Overview screen.Click the individual partition link in the Topic Overview."
},
{
"code": null,
"e": 9124,
"s": 9063,
"text": "Click the View Messages button on the Topic Overview screen."
},
{
"code": null,
"e": 9183,
"s": 9124,
"text": "Click the individual partition link in the Topic Overview."
},
{
"code": null,
"e": 9315,
"s": 9183,
"text": "It’s exactly what you’d expect — a chronologically-ordered list of messages (or records, in Kafka parlance) for a chosen partition."
},
{
"code": null,
"e": 9483,
"s": 9315,
"text": "Each entry conveniently displays the offset, the record key (if one is set), the timestamp of publication, and any headers that may have been appended by the producer."
},
{
"code": null,
"e": 9690,
"s": 9483,
"text": "There’s another little trick up Kafdrop’s sleeve. If the message happens to be a valid JSON document, the topic viewer can nicely format it. Click on the green arrow on the left of the message to expand it."
},
{
"code": null,
"e": 9969,
"s": 9690,
"text": "The more you use Kafka, the more you come to discover and appreciate its true potential — not just as a versatile event streaming platform, but as a general-purpose messaging middleware that lets you assemble complex business systems from asynchronous, loosely coupled services."
},
{
"code": null,
"e": 10471,
"s": 9969,
"text": "You’ll invariably experience the frustrations that are to be expected from a technology that has only recently entered the mainstream, by comparison with the more mature MQ brokers of yore. What’s reassuring is that the Open Source community hasn’t stood still, producing an evolving ecosystem, complete with the documentation and tooling necessary for us to get on with our jobs. The least we can do in return is raise a pull request once in a while or maybe answer a StackOverflow question or three."
}
] |
My pick for top 48 advanced database systems interview questions | by Saeed Mohajeryami | Towards Data Science | Besides knowing how to query, you should have some knowledge about database systems. This is expected, and these knowledge questions often come up during the interview. Here I try to pick my top favorite advanced database system interview questions. The focus is on “advanced” and I assume you are familiar with database fundamentals, so I skip basic questions like what is DBMS? What is SQL? What is transaction? or ask you to run some basic queries. I also tried to classify these questions to the best of my ability and put them into categories to make learning them easier.
I wanted this article to be short and sweet, but it didn’t turn out that way. So, I want you to be prepared for a long read. If you want to ace database systems interview, you must start putting in time and do your homework, and I believe this article is a great place to start.
I tried to cut unnecessary details and only explain what is necessary. However, when the question itself is interesting and worth reading more, I provided some links for complementary materials.
Ok. Let’s start.
#1 What are the issues of traditional file-based systems that make DBMS a superior alternative?
One main issue is access. In the absence of indexing, your only option is full page scan, which is super slow.
The other issue is redundancy and inconsistency. Files have many duplicate and redundant data and if you change one of them, you probably make them all inconsistent. It is very expensive to keep files consistent.
Another issue is lack of concurrency control. As a result, one operation might lock the entire page, while in DBMS, multiple operations are allowed to work on a single file.
Data isolation, integrity check, atomicity of transactions, and security problem are some other issues with traditional file-based systems, which DBMSs have provided some good solutions for.
#2 What are some examples of open source and commercial Relational DBMSs?
For open source RDBMS, three popular software are MySQL, PostgreSQL, and SQLite. For commercial RDBMSs, you can mention Oracle, Microsoft SQL server, IBM DB2, and Teradata.
#3 What is a database model? and name a few common database models?
A database model is a logical structure of a database describing relationships and constraints to store and access data. Some common database models include:
Relational model
Hierarchical model
Entity-Relationship (ER) model
Document model
Object-Oriented (OO) model
#4 How do you choose a database model?
To some extent it depends on your application, each database model has its own strength. For example, the document model is suitable for text or semi-structured data. On the other hand, if you have atomic data, the relational model is your best option. It also depends on which DBMS you use. Many DBMSs are built to work only with one particular model and the user does not have any other choices.
#5 What is ER modeling?
Entity-Relationship is a form of modeling that tries to imitate the relationships that exist among entities in the real world. In ER modeling, entities are some aspect of the real world, e.g. an event, a location, persons, and relationships, as its name suggests, are the relationship between these entities.
In ER modeling, all entities have their attributes, which in the real world can be looked at characteristics of the object. For example, if employee is an entity, then the name of that employee is one of its attributes.
As an example of ER modeling, we can model one form of relationship among employees as below: two entities, i.e. supervisors and employees, and a relationship, i.e. supervise. You can model your entire organization like this.
#6 What is NoSQL?
NoSQL refers to a group of databases that are built for some specific data models, e.g. graphs, documents, key-pairs, and wide-columns. Unlike relational databases, NoSQL databases have flexible schemas. NoSQL databases are widely recognized for their ease of development, functionality, and performance at scale. Unlike SQL databases, many NoSQL databases can be scaled horizontally across hundreds or thousands of servers.
NoSQL systems are considered very young compared to traditional relational databases. However, because of many innovations and performance improvements, their popularity is on the rise.
Besides all the benefit of these systems, it is worth mentioning that NoSQL databases do not generally provide the same level of data consistency as of relational databases. It is due to the fact that NoSQL systems have sacrificed ACID properties in favor of speed and scalability.
If you want to learn more about NoSQL databases, an awesome source is here.
#7 What is ACID properties of transactions?
ACID stands for Atomicity, Consistency, Isolation, and Durability. In order to maintain consistency of a database, before and after the transaction, these four conditions must be met. Below, I try to briefly describe the concept.
Atomicity: It is also known as “all or nothing rule”. Basically either all parts of a transaction are stored or none of them is stored. No partial transaction is allowed. For example, if a transaction is to take money from an account and deposit it into another account, all parts of it must be completed for a database to stay consistent. If we do this transaction partially, then we made our database inconsistent.
Consistency: There is no consensus over the definition of this term. In general, you can look at this way, before the transaction, the database was consistent, after the transaction, it must stay consistent too.
Isolation: We run a lot of transactions concurrently and the intermediate state of each transaction must stay invisible from the others. For example, in the transfer fund transaction that I described for atomicity, the other transactions must either see the money in one account or the other, and not in neither. In other words, if we make transactions fully isolated from each other, then it must appear that the transactions are run serially and not concurrently.
Durability: When a transaction successfully commits, then it must persist (stored on disk) and can’t be undone, even in the event of a crash.
#8 What are the different levels of data abstraction?
Data abstraction in DBMS is a process of hiding irrelevant details from users. In general, there are three levels of data abstraction. 1) Physical level, which is the lowest level, is the data storage description, this level is managed by DBMS, and the details of this level are typically hidden from system admins, developers, and users; 2) Conceptual or Logical level that describes databases and relationship between different fields. Developers and system admins work on this level; 3) External or VIEW level that describes only part of database. For example, the results of a query is a VIEW level data abstraction. Users typically work on this level and the details of the table schema and its physical storage are hidden from them.
#9 What is the difference between columnar and row-based databases?
Row-based databases store the data on disk row by row, whereas, columnar databases store the data column by column. Each method has its own advantages. The former is very fast and efficient for the operations on rows and the latter is fast and efficient for the operations on columns, e.g. aggregating large volumes of data for a subset of columns.
Typically the operations that need the whole row are writing operations like INSERT, DELETE, UPDATE. The operations that need columns are typically read operations like SELECT, GROUP BY, JOIN , etc.
In general, columnar database are ideal for analytical operations and row databases are ideal for transaction processing.
#10 What are OLTP and OLAP and their differences?
OLTP and OLAP are both online processing systems. OLTP stands for “Online Transaction Processing” and it is a system that manages transaction-oriented applications, and OLAP stands for “Online Analytical Processing”, and it is a system to manage analytical queries.
The major difference between the two systems is that OLTP is a write-heavy system and OLAP is a read-heavy system. This difference has a major impact on their implementation. For example, it is very important for OLTP systems to adopt a proper concurrency control, while this is not a major concern in read-heavy operations. Another difference between the two systems is that OLTP queries are generally simple and return relatively small number of records while OLAP queries are very complex and involve many intricate joins and aggregations.
The other difference is that due to the real-time nature of OLTP systems, they often follow a decentralized architecture to avoid single points of failure, while OLAP systems often have centralized architecture.
Also, in the majority of DBMSs, OLTP is row-based database and OLAP is columnar database.
#11 What is normalization and de-normalization?
Normalization is a process that organizes the data into multiple tables to minimize redundancy. De-normalization is the opposite process. It combines the normalized tables into one table so that data retrieval becomes faster. The main advantage of normalization is the better use of disk spaces. It is also easier to maintain the integrity of the database when it is normalized.
JOIN is the operation that allows us to reverse the normalization and create a de-normalized form of the data.
#12 What is Data Warehousing?
It is a process of collecting (extracting, transforming, and loading) data from heterogeneous sources and storing them into one database. You can consider the data warehouse as a central repository where data flows into it from the transactional systems and other relational databases. It can correlate broad business data to provide greater executive insight into an organization performance. The data warehouse is the core of the business intelligence, which is a system for data analysis and reporting.
This database is maintained separately from standard operational databases. They are two separate systems, the latter are optimized to update real-time data quickly and accurately, while the former is mostly suitable for offline operations to give a long-range view of data over time.
Concurrency control is the procedure in DBMS that ensure simultaneous operations do not conflict with each another.
#13 What are database locks and its types?
In general, it is fair to say that locks are mostly used to ensure that only one user/session is allowed to update a particular data. Here I describe two types of locks: shared lock (S) and exclusive lock (X). These locks can be held on a table, a page, an index key, or an individual row.
Shared lock: When an operation requests a shared lock on a table, if granted, that table becomes open to reading. This lock can be shared with other read operations and they can read the table at the same time.
Exclusive lock: When an operation requests an exclusive lock on a table, if granted, has an exclusive right to write on the table. Other operations, if they request an access on that locked table, will be blocked.
There is another related concept for locks, called Intent (I) locks. We have Intent Shared (IS) and Intent Exclusive (IX) locks. These locks allow more granular concurrency control. Technically, we do not need them. S and X locks are enough, but they are helpful for query optimization. More details about Intent locks are typically beyond the scope of even advanced questions.
#14 What is “lock escalation”?
Database locks can exist on rows, pages or whole tables or indexes. When a transaction is in progress, the locks held by the transaction take up resources. Lock escalation is where the system consolidates multiple locks into a higher level one (for example consolidating multiple row locks to a page or multiple pages to a whole table) typically to recover resources taken up by large numbers of fine-grained locks.
#15 What is “lock contention”?
When multiple operations request an exclusive lock on one table, lock contention occurs. In this scenario, operations must wait in a queue. If you run into chronic lock contention, it means that some parts of your database is hot, you must divide those data blocks further to allow more operations to obtain exclusive lock at the same time. lock contention can be a bottleneck for scaling up a database.
#16 What is “deadlock”?
A deadlock is a situation that some transactions are waiting indefinitely for each other to give up locks. Typically, there is two approach to address this issue, one is the lazy way, which means do nothing, and if it happened then detect it and restart one operation to disentangle the deadlock. The other approach is proactive, which means preventing deadlocks to ever happen. If you want to learn more about deadlock prevention, read it here.
#17 What are isolation levels?
Isolation is the third letter in ACID properties. With this property, our goal is to make all transactions completely isolated from each other (serializable). However, there are some applications that they do not need full isolation. As a result, we define some other isolation levels that are less stringent than full isolation. In general, five isolation levels are defined.
Read Uncommitted: No lock at all. Concurrent transactions can read uncommitted data of other transactions and can also write on them. In the database vernacular, they say DBMS allows dirty reads.
Read Committed: In this level, DBMS does not allow dirty reads. In this level, each transaction holds a read/write lock on the current row and only release when it commits the changes. This isolation level still allows non-repeatable read, which means a transaction return different value when it reads the same row. It is more clear if you take a look at below picture. As it is clear, no dirty read is allowed, but non-repeatable reads still exist.
Repeatable Read: As you saw earlier, the problem with “read committed” isolation level was “non-repeatable reads”. To avoid non-repeatable reads, each transaction must hold a read lock on the rows they read and write lock on the rows they write (e.g. insert, update, and delete) until they commit the changes. This level of isolation is repeatable read.
However, there is still one scenario in this isolation level, which can make the database inconsistent. If we insert or delete new rows to a table and then range query, then the results would be inconsistent. Look at below example. The same query in transaction 1 returns two different results. This scenario is known as ‘phantom read’.
Serializable: This is the highest isolation level. As you saw in “repeatable read”, phantom read can happen. In order to prevent the phantom read, we must hold the lock on the entire table and not the rows. Below picture is summary of all isolation levels so far.
Snapshot: This isolation level is different from the others I have described so far. The others were based on locks and blocks. This one does not use locks. In this isolation level, when a transaction modifies (i.e. insert, update, and delete) a row, the committed version of the modified row will be copied to a temporary database (tempdb) and receives a version number. It is also known as row versioning. Then if another session tries to read the modified object, the committed version of that object will be returned from tempdb to that operation.
If what I described for snapshot isolation sounds fundamentally different from other isolation levels, it is because it really is. Other isolation levels are based on a pessimistic concurrency control model, but snapshot isolation is based an optimistic model. Optimistic model assumes conflicts are rare and decides not to prevent them and handle them if they occur. It is different from pessimistic model, which ensures that no conflict happens whatsoever.
Access methods are organization techniques or data structures that support fast access to subsets of rows/columns. Some of the most common data structures are variants of hash tables and B-trees.
#18 What is hashing and its advantages and disadvantages?
Hashing is a look up technique. Basically, a way to map keys to values. Hash functions convert a string of characters into a usually shorter fixed-length values, which can then be used as an index to store the original element.
Hashing, if we use a good hash function, can be used to index and retrieve items in a database in a constant time, which is faster than the other look up techniques.
Advantages:
Hash table is an ideal data structure for point look up (a.k.a equality queries), especially when the database is large, because regardless of the input size, you can search, insert and delete data in constant time.
Disadvantages:
There are situations that hashing is not necessarily the best option. For example, for small data, the cost of a good hash function makes hashing more expensive than a simple sequential search.
Another situation is range scan operation (a.k.a range query), for this operation, B+ tree is an ideal data structure.
The other situation is looking for a sub-string or prefix matching, hashing is basically useless for these operations.
Another disadvantage of hashing is scalability. The performance of hash table degrades as the database grows (more collisions and higher cost of collision resolution, e.g. adding more buckets or rehashing the existing items)
#19 What is B+ tree and its advantages and disadvantages?
B+ tree is a data structure from the family of B trees. This data structure and its variants is very popular for indexing purpose. This tree is a self-balancing tree and there are mechanisms in place to ensure that the nodes are at least half full. In B+ tree, the data is stored in leaf nodes, and leaf nodes are sequentially linked to each other. These sequential links between leaf nodes allow sequential access to data without traversing the tree structure. This sequential access allows fast and efficient range scan.
B+ tree allows searches, sequential access, insertions, and deletions in logarithmic time. At the end of this answer, you can find a B+ tree sample visualization. If you are interested, you can plot one for yourself by this visualization tool (here).
Typically, in database systems, B+ tree data structure is compared against hash table. So, here I try to explain advantages and disadvantages of B+ tree compared to hash table. Advantages of B+ tree is in range query and also searching for substrings, using LIKE command. On the other hand, for equivalence query, the hash index is better than B+ tree. Another advantage of B+ tree is that it can easily grow with the data, and as a result, it is more suitable for storing large amount of data on disk.
One common follow up question is that what is the difference between B+ tree and Binary Search Tree (BST)? B+ tree is a generalization of BST, which allows tree nodes to have more than two children.
If someone asked you about the difference of B tree and B+ tree, you can mention two things. First, in B+ three, the records are only stored in leaves, and the internal nodes store the pointers (key). Unlike B+ tree, in B tree, keys and records both can be stored in the internal and leaf nodes. Second, the leaf nodes of a B+ tree are linked together, but in B tree, they are not linked. You can see these two differences in the below example.
#20 What is the difference between clustered and non-clustered indexes?
Indexes are used to speed-up query process. Without them, a DBMS needs to perform full table scan, which is very slow.
Clustered index is related to physical storage of data. Basically, we ask our DBMS to sort our rows by a column and physically store them with that order. As you can see, we only can have one clustered index per table. Clustered index allows us to retrieve our data very fast because it provides fast sequential scan. You can either create a customized clustered index or let the DBMS to automatically create one for you using the primary key.
In contrast, non-clustered index is not related to physical storage. These indexes are sorted based on a column and stored somewhere different from the table. You can imagine these indexes as a lookup table with two columns. One column is a sorted form of one of the table columns, the other is the their physical address on memory (row address). For these indexes, if we look for a record, we first go and search its index on the look up table, then we go to the physical memory to fetch all the records associated with that row address.
In summary, non-clustered indexes are slower than clustered indexes because they involve extra lookup step. Moreover, since we need to store these lookup tables, we need extra storage space. The other difference is that we can have one clustered index per table while we can have as many non-clustered index as we want.
#21 What are correlated and non-correlated sub-queries?In terms of inter-dependency, there are two types of sub-queries, in one of them, the inner query is dependent to the value of the outer query, we call this kind of queries “correlated” queries and in the other one, inner and outer queries are independent, which we call them “non-correlated” queries.
It is needless to mention that correlated sub-queries are very slow because it requires the inner sub-query to run once for every row in the outer query.
#22 What are different JOIN algorithms?
There are three major algorithms to perform JOIN. Here I try to describe them briefly and mention their advantages.
Nested Loop: It compares all values of outer and inner tables against each other. It is the only algorithm that is capable of cross join (many-to-many joins). It serves as a fallback option in the absence of better algorithms.
Hash Join: This is the most versatile join method. In a nutshell, it builds an in-memory hash table of the smaller of its two inputs, and then reads the larger input and probes the in-memory hash table to find matches. Hash joins can only be used to compute equi-joins. It is typically more efficient than nested loops, except when the probe side of the join is very small.
Sort-Merge Join: This algorithm, first, sorts two tables based on the join attributes. Then it finds the first match and scrolls down on two tables and merge the rows for the matching attributes.
#23 What is stored procedure?
You can consider it as a semi-program. A set of SQL statements to perform a specific task. If this task is a common task, then instead of running the query each time, we can store that query into a procedure and execute it when we need it. Below is a simple structure of a procedure.
CREATE PROCEDURE <Procedure-Name> ASBegin <SQL STATEMENT>End
After creating a procedure, whenever we need, we can execute it using EXECUTE command
EXECUTE <Procedure-Name>
Stored procedure has many benefits. The major one is reusability of the SQL code. If the procedure is in common use, it helps to avoid writing the code multiple times. Another benefit is when we use distributed databases, it reduces the amount of information sent over the network.
#24 What is a database trigger?
A trigger is a stored procedure, which automatically runs before/after an event occurs. These events can be DML, DDL, DCL, or database operations such as LOGON/LOGOFF. The general trigger syntax is as below:
CREATE [ OR ALTER ] TRIGGER [ Trigger_name ] [BEFORE | AFTER | INSTEAD OF] {[ INSERT ] | [ UPDATE ] | [ DELETE ]} ON [table_name] AS{SQL Statement}
Some applications of triggers are: checking the validity of transaction, enforcing referential integrity, event logging, generating some derived columns automatically, and security authorizations before/after user LOGON.
If you are asked about the difference of trigger and stored procedure, you can mention that triggers can not be called by their own. They are invoked during events. In contrast, a stored procedure is an independent query and can be called independently.
Query planning and optimization is a feature of many RDBMSs. The query optimizer attempts to determine the most efficient way to execute a given query by considering the possible query plans.
#25 What is an execution plan?
An execution plan is the description of the operations that the database engine plans to perform to run the query efficiently. You can look at it as a view into your DBMS query optimizer, which basically is a software to find the most efficient way to implement a query. Execution plan is a primary means of troubleshooting a poorly performing query.
Reading an execution plan, understanding it and troubleshooting based on the plan is an art. So, if If you want to learn more about it, a great reference is here.
#26 What is query optimization?
SQL is a declarative language and not procedural. Basically you tell the DBMS what you want, but you don’t say how to get those results. It is up to DBMS to figure it out. DBMS can adopt multiple query strategies to get the correct results. However, these execution plans incur different costs. It is the query optimizer’s job to compare these strategies and pick the one with the least expected cost. The cost in this context is a weighted combination of I/O and processing costs. The I/O cost is the cost of accessing index and data pages from disk.
#27 Mention a few best practices to improve query performance?
It is a general question, and in practice there are many ways to improve query performance. Here only I mention a few.
Avoid multiple joins in a single query
Use joins instead of sub-queries.
Use stored procedure for frequently used data and more complex queries.
Use WHERE expressions to limit the size of your results as much as possible.
Here is another good read to answer this question.
Crash recovery is the process to roll back to a consistent and usable state. This is done by undoing incomplete transactions and redoing committed transactions that were still in memory when the crash occurred
#28 What is Write-Ahead Log (WAL)?
In DBMSs, the de facto technique for recovery management and maintaining Atomicity and Durability is using Write-Ahead Log (WAL). With WAL, all changes are written to a log first, then the log itself must be written to a stable storage before the changes are allowed to be physically applied. That is why it is called Write-Ahead log. A simple technique that guarantees that when we come back from the crash, we still can figure out what we were doing before the crash and pick up from where we left off.
#29 What is a checkpoint?
checkpoints are relevant to log-based recovery system. For restoring a database after crash, we must redo all the log records. But if we redo all the log records from the beginning, it takes forever to recover a database. So, we must ignore some of the records after a while. Checkpoints are the points where we decide to ignore records before them for the recovery purpose. As you can see, by using checkpoints, the DBMS can reduce the amount of work to restart a database in the event of a crash.
#30 What is a distributed database?
A distributed database is a collection of multiple interconnected databases that are spread physically across various locations. In almost all cases, these physically separated databases have shared-nothing architecture and are independent from each other. However, the DBMS integrates data logically in a way that it appears as one single database to the user/application.
#31 What is database partitioning?
Partitioning is a process where very large tables are divided into multiple smaller manageable pieces. Some benefits of partitioning include faster queries, faster data load, and faster deletion of old data. The benefits of partitioning are constrained by the selection of the partition key and the granularity.
Two are two ways that a table can be partitioned: horizontally and vertically. Vertical partitioning puts different columns into different partitions, whereas horizontal partitioning puts subset of rows in different partitions based on a partition key. For example, a company’s sale records can be horizontally partitioned based on the sale date.
#32 What is database sharding?
Sharding, in essence, is a horizontal partitioning architecture. Each shard has the same schema and columns, but different rows, and they are independent from each other.
The main benefit of sharding is scalability. With automatic sharding architecture, you can simply add more machines to your stack whenever it is needed and reduce the load on existing machines and allow more traffic and faster processing. It is very appealing to applications during the growth stage.
If you want to learn more about it, you can refer to this article (here).
#33 What are different types of SQL statements?
SQL statements are high-level instructions and each statement is responsible for a specific task. These statements can generally be classified into five categories:
Data Definition Language (DDL)* This family of SQL commands is used to define database schema.* Examples include CREATE , DROP, ALTER
Data Manipulation Language (DML)* This family of SQL commands is used to modify the data inside a table.* Examples include INSERT , UPDATE , DELETE
Data Query Language (DQL)* This family of SQL commands performs query on existing tables.* Examples include SELECT
Data Control Language (DCL)* This family of SQL commands deals with the rights and permissions. * Examples include GRANT , REVOKE
Transaction Control Language (TCL)* This family of SQL commands deals with transactions. * Examples include COMMIT , ROLLBACK , SAVEPOINT * You only need these commands if you have OLTP operation.
#34 What is the difference of DDL and DML?
They are closely related. DDL is responsible to define the structure of the table, basically what is allowed to enter the table and what is not allowed. DDL can be regarded as a set of rules that shape the table structure (schema). After DDL defines the schema, then it is DML job to fill the table with the data.
#35 What is the difference between scalar and aggregate functions?
Both of these functions return a single value, the difference is the input, scalar functions operate on a single value while aggregate functions operate on a set of values. I try to clarify the difference with an example. For example, string functions like ISNULL(), ISNUMERIC(), LEN()are scalar functions. They input a single value and return a single value. On the other hand, AVG(), MAX(), SUM() are aggregate functions, they input multiple values and output a single value.
#36 What is database VIEW?
A VIEW is a virtual table. This virtual table can temporarily keep the result of your SQL query for future references. You can look at it as a named query, which you can refer to it later by its name rather than writing the whole query again. One advantage of the VIEW is that instead of creating a brand new table to store the result of your query, you create a VIEW and save your disk space.
#37 What is the difference between VIEW and materialized VIEW?
The VIEW results are not stored on the disk, and every time a VIEW is run, we get updated results. However, in materialized VIEW, things are different. We store the results on the disk and we put some mechanism in place to keep them updated (a.k.a VIEW maintenance).
Materialized VIEW is beneficial when the VIEW is accessed frequently. This way, we don’t need to run it every time. Nonetheless, materialized VIEW has storage cost and update overhead.
#38 What is Common Table Expressions (CTE)?
CTE can be regarded as temporary VIEW or ‘inline’ VIEW . In other words, CTE is a temporary result set that you can reference within another SELECT, INSERT, UPDATE, or DELETE statement. The reason I say CTE is a temporary VIEW because it can only be used by a query attached to it and can not be referenced somewhere else.
CTE is defined with WITH operator. Below is simple blueprint of CTE. You can define multiple CTEs with only one WITH and it allows you to simplify intricate queries.
#39 What are the differences between DROP and TRUNCATE commands?
DROP removes the table altogether and can not be rolled back. TRUNCATE, on the other hand, removes all the rows of that table. With TRUNCATE, the table definition (schema) still exists and we can INSERT data in the future, if we desire.
#40 What are the differences between DELETE and TRUNCATE commands?
DELETE and TRUNCATE belong to two different categories of SQL commands, the former belongs to DML and the latter belongs to DDL. In other words, the former operates on row level while the latter operates on table level. TRUNCATE deletes all the rows of the table at once. DELETE can do the same, but it takes too much time as it deletes them row by row. If you use TRUNCATE, you can’t rollback the data, but with DELETE, you can rollback the row you deleted.
#41 What are the differences between PRIMARY KEY and FOREIGN KEY?
These keys are very important tools in cross-referencing different tables. They also help with referential integrity. However, they are different in nature. A table only has one primary key. Primary key 1) can uniquely identify a record in the table; 2) can not accept NULL value; and 3) for most DBMSs, by default, is the clustered index. A table, unlike primary key, can have more than one foreign key. Foreign key 1) is a primary key in another table; 2) can not uniquely identify a record in the table; 3) can accept NULL values, and 4) is not automatically indexed. It is up to user to create an index for it.
#42 What is the difference between WHERE and HAVING clause?
Both clauses are used to limit the result set by providing some conditions to filter the rows from the result set. However, there is one difference. WHERE clause scans the raw data (row by row) to check the conditions and filter them, but HAVING scans the aggregated results to check the conditions and filter them. For this reason, HAVING comes after GROUP BY in the SQL query. In summary, WHERE filters the raw data, but HAVING filters the processed data.
#43 What is functional dependency?
The attributes of a table are functionally dependent if one of them uniquely identifies the other. It becomes more clear with an example. Suppose we have an employee table with attributes: Id, Name, and Age. Here employee Id uniquely identifies employee Name because if we know the employee Id, we can uniquely say his/her name. A functional dependency is denoted by an arrow →. So, in this case, we can show it by Id -> Name
#44 What are different normalization types?
There are many levels of normalization. As I explained earlier, the goal of normalization is to avoid redundancy and dependency. However, this goal can not be achieved in one step. Each normalization step (type) allows us to get closer to our goal.
We start with Un-normalized form of data (UNF), In UNF, cells can can have multiple values (non-atomic), if we divide those values into multiple cells to make sure each table cell has a single value, and also remove duplicate rows to make sure all the records are unique, then we transformed UNF to 1st normal form (1NF).
The next step is to introduce primary key and foreign key. In this step, we divide the 1NF tables further and create new tables and connect them through primary and foreign keys. If in these new tables, all non-key attributes be fully functional dependent on the primary key, then we reach to 2nd normal form (2NF)
Although with 2NF, we have reduced redundancy and dependency significantly, there is still a lot of room to improve. The next step is to remove transitive functional dependencies, which basically means a situation that if we change a non-key column, we might cause another non-key column to change. To disentangle these non-key columns, we must create a separate tables. When we have no transitive functional dependencies, then we reached to 3rd normal form (3NF).
In almost all databases, 3NF is a point where we can not decompose the database further into a higher forms of normalization. However, in some complex databases, there are situations that you can achieve higher forms of normalization.
Higher forms of normalization are Boyce-Codd Normal Form (BCNF), 4NF, 5NF, and 6NF, which I prefer not to cover. If you are interested to learn more about these higher forms of normalization, you can read them from Wikipedia page of data normalization (here).
#45 What are different integrity rules?
There are two types of integrity rules that if we obey them, we can maintain our database consistency. Entity rule and Referential rule. Entity rule is related to our primary key, if we make a column the primary key, then it can not have any NULL value. Referential rule is related to our foreign keys, our foreign keys must either have a NULL value or their values must be the primary key of another table.
#46 What is DML Compiler?
It is a translator. It transforms DML queries from high-level statements to low-level instructions, executable by query evaluation engine.
#47 What is cursor?
Cursor is a tool that can be employed by user to return the results in a row by row manner. It is in contrast with the typical SELECT statement, which return the entire result set. Typically we are interested in complete set of rows, but there are applications, especially those that are interactive and online, that cannot always work effectively with the entire result set as a unit. These applications prefer to work on the data row by row. Cursors allow them to perform this row by row operation.
You can see the whole process of using a cursor in the below example.
#48 What is cardinality?
Cardinality in the context of database systems means “uniqueness”. For example, when we say a column has a low cardinality, it means it has many duplicate values.
If you found this article helpful, share it with your friends and colleagues. If you have any other questions, you can find me on Linkedin or send me an email [email protected]. | [
{
"code": null,
"e": 750,
"s": 172,
"text": "Besides knowing how to query, you should have some knowledge about database systems. This is expected, and these knowledge questions often come up during the interview. Here I try to pick my top favorite advanced database system interview questions. The focus is on “advanced” and I assume you are familiar with database fundamentals, so I skip basic questions like what is DBMS? What is SQL? What is transaction? or ask you to run some basic queries. I also tried to classify these questions to the best of my ability and put them into categories to make learning them easier."
},
{
"code": null,
"e": 1029,
"s": 750,
"text": "I wanted this article to be short and sweet, but it didn’t turn out that way. So, I want you to be prepared for a long read. If you want to ace database systems interview, you must start putting in time and do your homework, and I believe this article is a great place to start."
},
{
"code": null,
"e": 1224,
"s": 1029,
"text": "I tried to cut unnecessary details and only explain what is necessary. However, when the question itself is interesting and worth reading more, I provided some links for complementary materials."
},
{
"code": null,
"e": 1241,
"s": 1224,
"text": "Ok. Let’s start."
},
{
"code": null,
"e": 1337,
"s": 1241,
"text": "#1 What are the issues of traditional file-based systems that make DBMS a superior alternative?"
},
{
"code": null,
"e": 1448,
"s": 1337,
"text": "One main issue is access. In the absence of indexing, your only option is full page scan, which is super slow."
},
{
"code": null,
"e": 1661,
"s": 1448,
"text": "The other issue is redundancy and inconsistency. Files have many duplicate and redundant data and if you change one of them, you probably make them all inconsistent. It is very expensive to keep files consistent."
},
{
"code": null,
"e": 1835,
"s": 1661,
"text": "Another issue is lack of concurrency control. As a result, one operation might lock the entire page, while in DBMS, multiple operations are allowed to work on a single file."
},
{
"code": null,
"e": 2026,
"s": 1835,
"text": "Data isolation, integrity check, atomicity of transactions, and security problem are some other issues with traditional file-based systems, which DBMSs have provided some good solutions for."
},
{
"code": null,
"e": 2100,
"s": 2026,
"text": "#2 What are some examples of open source and commercial Relational DBMSs?"
},
{
"code": null,
"e": 2273,
"s": 2100,
"text": "For open source RDBMS, three popular software are MySQL, PostgreSQL, and SQLite. For commercial RDBMSs, you can mention Oracle, Microsoft SQL server, IBM DB2, and Teradata."
},
{
"code": null,
"e": 2341,
"s": 2273,
"text": "#3 What is a database model? and name a few common database models?"
},
{
"code": null,
"e": 2499,
"s": 2341,
"text": "A database model is a logical structure of a database describing relationships and constraints to store and access data. Some common database models include:"
},
{
"code": null,
"e": 2516,
"s": 2499,
"text": "Relational model"
},
{
"code": null,
"e": 2535,
"s": 2516,
"text": "Hierarchical model"
},
{
"code": null,
"e": 2566,
"s": 2535,
"text": "Entity-Relationship (ER) model"
},
{
"code": null,
"e": 2581,
"s": 2566,
"text": "Document model"
},
{
"code": null,
"e": 2608,
"s": 2581,
"text": "Object-Oriented (OO) model"
},
{
"code": null,
"e": 2647,
"s": 2608,
"text": "#4 How do you choose a database model?"
},
{
"code": null,
"e": 3045,
"s": 2647,
"text": "To some extent it depends on your application, each database model has its own strength. For example, the document model is suitable for text or semi-structured data. On the other hand, if you have atomic data, the relational model is your best option. It also depends on which DBMS you use. Many DBMSs are built to work only with one particular model and the user does not have any other choices."
},
{
"code": null,
"e": 3069,
"s": 3045,
"text": "#5 What is ER modeling?"
},
{
"code": null,
"e": 3378,
"s": 3069,
"text": "Entity-Relationship is a form of modeling that tries to imitate the relationships that exist among entities in the real world. In ER modeling, entities are some aspect of the real world, e.g. an event, a location, persons, and relationships, as its name suggests, are the relationship between these entities."
},
{
"code": null,
"e": 3598,
"s": 3378,
"text": "In ER modeling, all entities have their attributes, which in the real world can be looked at characteristics of the object. For example, if employee is an entity, then the name of that employee is one of its attributes."
},
{
"code": null,
"e": 3824,
"s": 3598,
"text": "As an example of ER modeling, we can model one form of relationship among employees as below: two entities, i.e. supervisors and employees, and a relationship, i.e. supervise. You can model your entire organization like this."
},
{
"code": null,
"e": 3842,
"s": 3824,
"text": "#6 What is NoSQL?"
},
{
"code": null,
"e": 4267,
"s": 3842,
"text": "NoSQL refers to a group of databases that are built for some specific data models, e.g. graphs, documents, key-pairs, and wide-columns. Unlike relational databases, NoSQL databases have flexible schemas. NoSQL databases are widely recognized for their ease of development, functionality, and performance at scale. Unlike SQL databases, many NoSQL databases can be scaled horizontally across hundreds or thousands of servers."
},
{
"code": null,
"e": 4453,
"s": 4267,
"text": "NoSQL systems are considered very young compared to traditional relational databases. However, because of many innovations and performance improvements, their popularity is on the rise."
},
{
"code": null,
"e": 4735,
"s": 4453,
"text": "Besides all the benefit of these systems, it is worth mentioning that NoSQL databases do not generally provide the same level of data consistency as of relational databases. It is due to the fact that NoSQL systems have sacrificed ACID properties in favor of speed and scalability."
},
{
"code": null,
"e": 4811,
"s": 4735,
"text": "If you want to learn more about NoSQL databases, an awesome source is here."
},
{
"code": null,
"e": 4855,
"s": 4811,
"text": "#7 What is ACID properties of transactions?"
},
{
"code": null,
"e": 5085,
"s": 4855,
"text": "ACID stands for Atomicity, Consistency, Isolation, and Durability. In order to maintain consistency of a database, before and after the transaction, these four conditions must be met. Below, I try to briefly describe the concept."
},
{
"code": null,
"e": 5502,
"s": 5085,
"text": "Atomicity: It is also known as “all or nothing rule”. Basically either all parts of a transaction are stored or none of them is stored. No partial transaction is allowed. For example, if a transaction is to take money from an account and deposit it into another account, all parts of it must be completed for a database to stay consistent. If we do this transaction partially, then we made our database inconsistent."
},
{
"code": null,
"e": 5714,
"s": 5502,
"text": "Consistency: There is no consensus over the definition of this term. In general, you can look at this way, before the transaction, the database was consistent, after the transaction, it must stay consistent too."
},
{
"code": null,
"e": 6180,
"s": 5714,
"text": "Isolation: We run a lot of transactions concurrently and the intermediate state of each transaction must stay invisible from the others. For example, in the transfer fund transaction that I described for atomicity, the other transactions must either see the money in one account or the other, and not in neither. In other words, if we make transactions fully isolated from each other, then it must appear that the transactions are run serially and not concurrently."
},
{
"code": null,
"e": 6322,
"s": 6180,
"text": "Durability: When a transaction successfully commits, then it must persist (stored on disk) and can’t be undone, even in the event of a crash."
},
{
"code": null,
"e": 6376,
"s": 6322,
"text": "#8 What are the different levels of data abstraction?"
},
{
"code": null,
"e": 7115,
"s": 6376,
"text": "Data abstraction in DBMS is a process of hiding irrelevant details from users. In general, there are three levels of data abstraction. 1) Physical level, which is the lowest level, is the data storage description, this level is managed by DBMS, and the details of this level are typically hidden from system admins, developers, and users; 2) Conceptual or Logical level that describes databases and relationship between different fields. Developers and system admins work on this level; 3) External or VIEW level that describes only part of database. For example, the results of a query is a VIEW level data abstraction. Users typically work on this level and the details of the table schema and its physical storage are hidden from them."
},
{
"code": null,
"e": 7183,
"s": 7115,
"text": "#9 What is the difference between columnar and row-based databases?"
},
{
"code": null,
"e": 7532,
"s": 7183,
"text": "Row-based databases store the data on disk row by row, whereas, columnar databases store the data column by column. Each method has its own advantages. The former is very fast and efficient for the operations on rows and the latter is fast and efficient for the operations on columns, e.g. aggregating large volumes of data for a subset of columns."
},
{
"code": null,
"e": 7731,
"s": 7532,
"text": "Typically the operations that need the whole row are writing operations like INSERT, DELETE, UPDATE. The operations that need columns are typically read operations like SELECT, GROUP BY, JOIN , etc."
},
{
"code": null,
"e": 7853,
"s": 7731,
"text": "In general, columnar database are ideal for analytical operations and row databases are ideal for transaction processing."
},
{
"code": null,
"e": 7903,
"s": 7853,
"text": "#10 What are OLTP and OLAP and their differences?"
},
{
"code": null,
"e": 8169,
"s": 7903,
"text": "OLTP and OLAP are both online processing systems. OLTP stands for “Online Transaction Processing” and it is a system that manages transaction-oriented applications, and OLAP stands for “Online Analytical Processing”, and it is a system to manage analytical queries."
},
{
"code": null,
"e": 8712,
"s": 8169,
"text": "The major difference between the two systems is that OLTP is a write-heavy system and OLAP is a read-heavy system. This difference has a major impact on their implementation. For example, it is very important for OLTP systems to adopt a proper concurrency control, while this is not a major concern in read-heavy operations. Another difference between the two systems is that OLTP queries are generally simple and return relatively small number of records while OLAP queries are very complex and involve many intricate joins and aggregations."
},
{
"code": null,
"e": 8924,
"s": 8712,
"text": "The other difference is that due to the real-time nature of OLTP systems, they often follow a decentralized architecture to avoid single points of failure, while OLAP systems often have centralized architecture."
},
{
"code": null,
"e": 9014,
"s": 8924,
"text": "Also, in the majority of DBMSs, OLTP is row-based database and OLAP is columnar database."
},
{
"code": null,
"e": 9062,
"s": 9014,
"text": "#11 What is normalization and de-normalization?"
},
{
"code": null,
"e": 9441,
"s": 9062,
"text": "Normalization is a process that organizes the data into multiple tables to minimize redundancy. De-normalization is the opposite process. It combines the normalized tables into one table so that data retrieval becomes faster. The main advantage of normalization is the better use of disk spaces. It is also easier to maintain the integrity of the database when it is normalized."
},
{
"code": null,
"e": 9552,
"s": 9441,
"text": "JOIN is the operation that allows us to reverse the normalization and create a de-normalized form of the data."
},
{
"code": null,
"e": 9582,
"s": 9552,
"text": "#12 What is Data Warehousing?"
},
{
"code": null,
"e": 10088,
"s": 9582,
"text": "It is a process of collecting (extracting, transforming, and loading) data from heterogeneous sources and storing them into one database. You can consider the data warehouse as a central repository where data flows into it from the transactional systems and other relational databases. It can correlate broad business data to provide greater executive insight into an organization performance. The data warehouse is the core of the business intelligence, which is a system for data analysis and reporting."
},
{
"code": null,
"e": 10373,
"s": 10088,
"text": "This database is maintained separately from standard operational databases. They are two separate systems, the latter are optimized to update real-time data quickly and accurately, while the former is mostly suitable for offline operations to give a long-range view of data over time."
},
{
"code": null,
"e": 10489,
"s": 10373,
"text": "Concurrency control is the procedure in DBMS that ensure simultaneous operations do not conflict with each another."
},
{
"code": null,
"e": 10532,
"s": 10489,
"text": "#13 What are database locks and its types?"
},
{
"code": null,
"e": 10822,
"s": 10532,
"text": "In general, it is fair to say that locks are mostly used to ensure that only one user/session is allowed to update a particular data. Here I describe two types of locks: shared lock (S) and exclusive lock (X). These locks can be held on a table, a page, an index key, or an individual row."
},
{
"code": null,
"e": 11033,
"s": 10822,
"text": "Shared lock: When an operation requests a shared lock on a table, if granted, that table becomes open to reading. This lock can be shared with other read operations and they can read the table at the same time."
},
{
"code": null,
"e": 11247,
"s": 11033,
"text": "Exclusive lock: When an operation requests an exclusive lock on a table, if granted, has an exclusive right to write on the table. Other operations, if they request an access on that locked table, will be blocked."
},
{
"code": null,
"e": 11625,
"s": 11247,
"text": "There is another related concept for locks, called Intent (I) locks. We have Intent Shared (IS) and Intent Exclusive (IX) locks. These locks allow more granular concurrency control. Technically, we do not need them. S and X locks are enough, but they are helpful for query optimization. More details about Intent locks are typically beyond the scope of even advanced questions."
},
{
"code": null,
"e": 11656,
"s": 11625,
"text": "#14 What is “lock escalation”?"
},
{
"code": null,
"e": 12072,
"s": 11656,
"text": "Database locks can exist on rows, pages or whole tables or indexes. When a transaction is in progress, the locks held by the transaction take up resources. Lock escalation is where the system consolidates multiple locks into a higher level one (for example consolidating multiple row locks to a page or multiple pages to a whole table) typically to recover resources taken up by large numbers of fine-grained locks."
},
{
"code": null,
"e": 12103,
"s": 12072,
"text": "#15 What is “lock contention”?"
},
{
"code": null,
"e": 12507,
"s": 12103,
"text": "When multiple operations request an exclusive lock on one table, lock contention occurs. In this scenario, operations must wait in a queue. If you run into chronic lock contention, it means that some parts of your database is hot, you must divide those data blocks further to allow more operations to obtain exclusive lock at the same time. lock contention can be a bottleneck for scaling up a database."
},
{
"code": null,
"e": 12531,
"s": 12507,
"text": "#16 What is “deadlock”?"
},
{
"code": null,
"e": 12977,
"s": 12531,
"text": "A deadlock is a situation that some transactions are waiting indefinitely for each other to give up locks. Typically, there is two approach to address this issue, one is the lazy way, which means do nothing, and if it happened then detect it and restart one operation to disentangle the deadlock. The other approach is proactive, which means preventing deadlocks to ever happen. If you want to learn more about deadlock prevention, read it here."
},
{
"code": null,
"e": 13008,
"s": 12977,
"text": "#17 What are isolation levels?"
},
{
"code": null,
"e": 13385,
"s": 13008,
"text": "Isolation is the third letter in ACID properties. With this property, our goal is to make all transactions completely isolated from each other (serializable). However, there are some applications that they do not need full isolation. As a result, we define some other isolation levels that are less stringent than full isolation. In general, five isolation levels are defined."
},
{
"code": null,
"e": 13581,
"s": 13385,
"text": "Read Uncommitted: No lock at all. Concurrent transactions can read uncommitted data of other transactions and can also write on them. In the database vernacular, they say DBMS allows dirty reads."
},
{
"code": null,
"e": 14032,
"s": 13581,
"text": "Read Committed: In this level, DBMS does not allow dirty reads. In this level, each transaction holds a read/write lock on the current row and only release when it commits the changes. This isolation level still allows non-repeatable read, which means a transaction return different value when it reads the same row. It is more clear if you take a look at below picture. As it is clear, no dirty read is allowed, but non-repeatable reads still exist."
},
{
"code": null,
"e": 14386,
"s": 14032,
"text": "Repeatable Read: As you saw earlier, the problem with “read committed” isolation level was “non-repeatable reads”. To avoid non-repeatable reads, each transaction must hold a read lock on the rows they read and write lock on the rows they write (e.g. insert, update, and delete) until they commit the changes. This level of isolation is repeatable read."
},
{
"code": null,
"e": 14723,
"s": 14386,
"text": "However, there is still one scenario in this isolation level, which can make the database inconsistent. If we insert or delete new rows to a table and then range query, then the results would be inconsistent. Look at below example. The same query in transaction 1 returns two different results. This scenario is known as ‘phantom read’."
},
{
"code": null,
"e": 14987,
"s": 14723,
"text": "Serializable: This is the highest isolation level. As you saw in “repeatable read”, phantom read can happen. In order to prevent the phantom read, we must hold the lock on the entire table and not the rows. Below picture is summary of all isolation levels so far."
},
{
"code": null,
"e": 15539,
"s": 14987,
"text": "Snapshot: This isolation level is different from the others I have described so far. The others were based on locks and blocks. This one does not use locks. In this isolation level, when a transaction modifies (i.e. insert, update, and delete) a row, the committed version of the modified row will be copied to a temporary database (tempdb) and receives a version number. It is also known as row versioning. Then if another session tries to read the modified object, the committed version of that object will be returned from tempdb to that operation."
},
{
"code": null,
"e": 15998,
"s": 15539,
"text": "If what I described for snapshot isolation sounds fundamentally different from other isolation levels, it is because it really is. Other isolation levels are based on a pessimistic concurrency control model, but snapshot isolation is based an optimistic model. Optimistic model assumes conflicts are rare and decides not to prevent them and handle them if they occur. It is different from pessimistic model, which ensures that no conflict happens whatsoever."
},
{
"code": null,
"e": 16194,
"s": 15998,
"text": "Access methods are organization techniques or data structures that support fast access to subsets of rows/columns. Some of the most common data structures are variants of hash tables and B-trees."
},
{
"code": null,
"e": 16252,
"s": 16194,
"text": "#18 What is hashing and its advantages and disadvantages?"
},
{
"code": null,
"e": 16480,
"s": 16252,
"text": "Hashing is a look up technique. Basically, a way to map keys to values. Hash functions convert a string of characters into a usually shorter fixed-length values, which can then be used as an index to store the original element."
},
{
"code": null,
"e": 16646,
"s": 16480,
"text": "Hashing, if we use a good hash function, can be used to index and retrieve items in a database in a constant time, which is faster than the other look up techniques."
},
{
"code": null,
"e": 16658,
"s": 16646,
"text": "Advantages:"
},
{
"code": null,
"e": 16874,
"s": 16658,
"text": "Hash table is an ideal data structure for point look up (a.k.a equality queries), especially when the database is large, because regardless of the input size, you can search, insert and delete data in constant time."
},
{
"code": null,
"e": 16889,
"s": 16874,
"text": "Disadvantages:"
},
{
"code": null,
"e": 17083,
"s": 16889,
"text": "There are situations that hashing is not necessarily the best option. For example, for small data, the cost of a good hash function makes hashing more expensive than a simple sequential search."
},
{
"code": null,
"e": 17202,
"s": 17083,
"text": "Another situation is range scan operation (a.k.a range query), for this operation, B+ tree is an ideal data structure."
},
{
"code": null,
"e": 17321,
"s": 17202,
"text": "The other situation is looking for a sub-string or prefix matching, hashing is basically useless for these operations."
},
{
"code": null,
"e": 17546,
"s": 17321,
"text": "Another disadvantage of hashing is scalability. The performance of hash table degrades as the database grows (more collisions and higher cost of collision resolution, e.g. adding more buckets or rehashing the existing items)"
},
{
"code": null,
"e": 17604,
"s": 17546,
"text": "#19 What is B+ tree and its advantages and disadvantages?"
},
{
"code": null,
"e": 18127,
"s": 17604,
"text": "B+ tree is a data structure from the family of B trees. This data structure and its variants is very popular for indexing purpose. This tree is a self-balancing tree and there are mechanisms in place to ensure that the nodes are at least half full. In B+ tree, the data is stored in leaf nodes, and leaf nodes are sequentially linked to each other. These sequential links between leaf nodes allow sequential access to data without traversing the tree structure. This sequential access allows fast and efficient range scan."
},
{
"code": null,
"e": 18378,
"s": 18127,
"text": "B+ tree allows searches, sequential access, insertions, and deletions in logarithmic time. At the end of this answer, you can find a B+ tree sample visualization. If you are interested, you can plot one for yourself by this visualization tool (here)."
},
{
"code": null,
"e": 18881,
"s": 18378,
"text": "Typically, in database systems, B+ tree data structure is compared against hash table. So, here I try to explain advantages and disadvantages of B+ tree compared to hash table. Advantages of B+ tree is in range query and also searching for substrings, using LIKE command. On the other hand, for equivalence query, the hash index is better than B+ tree. Another advantage of B+ tree is that it can easily grow with the data, and as a result, it is more suitable for storing large amount of data on disk."
},
{
"code": null,
"e": 19080,
"s": 18881,
"text": "One common follow up question is that what is the difference between B+ tree and Binary Search Tree (BST)? B+ tree is a generalization of BST, which allows tree nodes to have more than two children."
},
{
"code": null,
"e": 19525,
"s": 19080,
"text": "If someone asked you about the difference of B tree and B+ tree, you can mention two things. First, in B+ three, the records are only stored in leaves, and the internal nodes store the pointers (key). Unlike B+ tree, in B tree, keys and records both can be stored in the internal and leaf nodes. Second, the leaf nodes of a B+ tree are linked together, but in B tree, they are not linked. You can see these two differences in the below example."
},
{
"code": null,
"e": 19597,
"s": 19525,
"text": "#20 What is the difference between clustered and non-clustered indexes?"
},
{
"code": null,
"e": 19716,
"s": 19597,
"text": "Indexes are used to speed-up query process. Without them, a DBMS needs to perform full table scan, which is very slow."
},
{
"code": null,
"e": 20160,
"s": 19716,
"text": "Clustered index is related to physical storage of data. Basically, we ask our DBMS to sort our rows by a column and physically store them with that order. As you can see, we only can have one clustered index per table. Clustered index allows us to retrieve our data very fast because it provides fast sequential scan. You can either create a customized clustered index or let the DBMS to automatically create one for you using the primary key."
},
{
"code": null,
"e": 20699,
"s": 20160,
"text": "In contrast, non-clustered index is not related to physical storage. These indexes are sorted based on a column and stored somewhere different from the table. You can imagine these indexes as a lookup table with two columns. One column is a sorted form of one of the table columns, the other is the their physical address on memory (row address). For these indexes, if we look for a record, we first go and search its index on the look up table, then we go to the physical memory to fetch all the records associated with that row address."
},
{
"code": null,
"e": 21019,
"s": 20699,
"text": "In summary, non-clustered indexes are slower than clustered indexes because they involve extra lookup step. Moreover, since we need to store these lookup tables, we need extra storage space. The other difference is that we can have one clustered index per table while we can have as many non-clustered index as we want."
},
{
"code": null,
"e": 21376,
"s": 21019,
"text": "#21 What are correlated and non-correlated sub-queries?In terms of inter-dependency, there are two types of sub-queries, in one of them, the inner query is dependent to the value of the outer query, we call this kind of queries “correlated” queries and in the other one, inner and outer queries are independent, which we call them “non-correlated” queries."
},
{
"code": null,
"e": 21530,
"s": 21376,
"text": "It is needless to mention that correlated sub-queries are very slow because it requires the inner sub-query to run once for every row in the outer query."
},
{
"code": null,
"e": 21570,
"s": 21530,
"text": "#22 What are different JOIN algorithms?"
},
{
"code": null,
"e": 21686,
"s": 21570,
"text": "There are three major algorithms to perform JOIN. Here I try to describe them briefly and mention their advantages."
},
{
"code": null,
"e": 21913,
"s": 21686,
"text": "Nested Loop: It compares all values of outer and inner tables against each other. It is the only algorithm that is capable of cross join (many-to-many joins). It serves as a fallback option in the absence of better algorithms."
},
{
"code": null,
"e": 22287,
"s": 21913,
"text": "Hash Join: This is the most versatile join method. In a nutshell, it builds an in-memory hash table of the smaller of its two inputs, and then reads the larger input and probes the in-memory hash table to find matches. Hash joins can only be used to compute equi-joins. It is typically more efficient than nested loops, except when the probe side of the join is very small."
},
{
"code": null,
"e": 22483,
"s": 22287,
"text": "Sort-Merge Join: This algorithm, first, sorts two tables based on the join attributes. Then it finds the first match and scrolls down on two tables and merge the rows for the matching attributes."
},
{
"code": null,
"e": 22513,
"s": 22483,
"text": "#23 What is stored procedure?"
},
{
"code": null,
"e": 22797,
"s": 22513,
"text": "You can consider it as a semi-program. A set of SQL statements to perform a specific task. If this task is a common task, then instead of running the query each time, we can store that query into a procedure and execute it when we need it. Below is a simple structure of a procedure."
},
{
"code": null,
"e": 22862,
"s": 22797,
"text": "CREATE PROCEDURE <Procedure-Name> ASBegin <SQL STATEMENT>End"
},
{
"code": null,
"e": 22948,
"s": 22862,
"text": "After creating a procedure, whenever we need, we can execute it using EXECUTE command"
},
{
"code": null,
"e": 22973,
"s": 22948,
"text": "EXECUTE <Procedure-Name>"
},
{
"code": null,
"e": 23255,
"s": 22973,
"text": "Stored procedure has many benefits. The major one is reusability of the SQL code. If the procedure is in common use, it helps to avoid writing the code multiple times. Another benefit is when we use distributed databases, it reduces the amount of information sent over the network."
},
{
"code": null,
"e": 23287,
"s": 23255,
"text": "#24 What is a database trigger?"
},
{
"code": null,
"e": 23495,
"s": 23287,
"text": "A trigger is a stored procedure, which automatically runs before/after an event occurs. These events can be DML, DDL, DCL, or database operations such as LOGON/LOGOFF. The general trigger syntax is as below:"
},
{
"code": null,
"e": 23646,
"s": 23495,
"text": "CREATE [ OR ALTER ] TRIGGER [ Trigger_name ] [BEFORE | AFTER | INSTEAD OF] {[ INSERT ] | [ UPDATE ] | [ DELETE ]} ON [table_name] AS{SQL Statement}"
},
{
"code": null,
"e": 23867,
"s": 23646,
"text": "Some applications of triggers are: checking the validity of transaction, enforcing referential integrity, event logging, generating some derived columns automatically, and security authorizations before/after user LOGON."
},
{
"code": null,
"e": 24121,
"s": 23867,
"text": "If you are asked about the difference of trigger and stored procedure, you can mention that triggers can not be called by their own. They are invoked during events. In contrast, a stored procedure is an independent query and can be called independently."
},
{
"code": null,
"e": 24313,
"s": 24121,
"text": "Query planning and optimization is a feature of many RDBMSs. The query optimizer attempts to determine the most efficient way to execute a given query by considering the possible query plans."
},
{
"code": null,
"e": 24344,
"s": 24313,
"text": "#25 What is an execution plan?"
},
{
"code": null,
"e": 24695,
"s": 24344,
"text": "An execution plan is the description of the operations that the database engine plans to perform to run the query efficiently. You can look at it as a view into your DBMS query optimizer, which basically is a software to find the most efficient way to implement a query. Execution plan is a primary means of troubleshooting a poorly performing query."
},
{
"code": null,
"e": 24858,
"s": 24695,
"text": "Reading an execution plan, understanding it and troubleshooting based on the plan is an art. So, if If you want to learn more about it, a great reference is here."
},
{
"code": null,
"e": 24890,
"s": 24858,
"text": "#26 What is query optimization?"
},
{
"code": null,
"e": 25442,
"s": 24890,
"text": "SQL is a declarative language and not procedural. Basically you tell the DBMS what you want, but you don’t say how to get those results. It is up to DBMS to figure it out. DBMS can adopt multiple query strategies to get the correct results. However, these execution plans incur different costs. It is the query optimizer’s job to compare these strategies and pick the one with the least expected cost. The cost in this context is a weighted combination of I/O and processing costs. The I/O cost is the cost of accessing index and data pages from disk."
},
{
"code": null,
"e": 25505,
"s": 25442,
"text": "#27 Mention a few best practices to improve query performance?"
},
{
"code": null,
"e": 25624,
"s": 25505,
"text": "It is a general question, and in practice there are many ways to improve query performance. Here only I mention a few."
},
{
"code": null,
"e": 25663,
"s": 25624,
"text": "Avoid multiple joins in a single query"
},
{
"code": null,
"e": 25697,
"s": 25663,
"text": "Use joins instead of sub-queries."
},
{
"code": null,
"e": 25769,
"s": 25697,
"text": "Use stored procedure for frequently used data and more complex queries."
},
{
"code": null,
"e": 25846,
"s": 25769,
"text": "Use WHERE expressions to limit the size of your results as much as possible."
},
{
"code": null,
"e": 25897,
"s": 25846,
"text": "Here is another good read to answer this question."
},
{
"code": null,
"e": 26107,
"s": 25897,
"text": "Crash recovery is the process to roll back to a consistent and usable state. This is done by undoing incomplete transactions and redoing committed transactions that were still in memory when the crash occurred"
},
{
"code": null,
"e": 26142,
"s": 26107,
"text": "#28 What is Write-Ahead Log (WAL)?"
},
{
"code": null,
"e": 26647,
"s": 26142,
"text": "In DBMSs, the de facto technique for recovery management and maintaining Atomicity and Durability is using Write-Ahead Log (WAL). With WAL, all changes are written to a log first, then the log itself must be written to a stable storage before the changes are allowed to be physically applied. That is why it is called Write-Ahead log. A simple technique that guarantees that when we come back from the crash, we still can figure out what we were doing before the crash and pick up from where we left off."
},
{
"code": null,
"e": 26673,
"s": 26647,
"text": "#29 What is a checkpoint?"
},
{
"code": null,
"e": 27172,
"s": 26673,
"text": "checkpoints are relevant to log-based recovery system. For restoring a database after crash, we must redo all the log records. But if we redo all the log records from the beginning, it takes forever to recover a database. So, we must ignore some of the records after a while. Checkpoints are the points where we decide to ignore records before them for the recovery purpose. As you can see, by using checkpoints, the DBMS can reduce the amount of work to restart a database in the event of a crash."
},
{
"code": null,
"e": 27208,
"s": 27172,
"text": "#30 What is a distributed database?"
},
{
"code": null,
"e": 27582,
"s": 27208,
"text": "A distributed database is a collection of multiple interconnected databases that are spread physically across various locations. In almost all cases, these physically separated databases have shared-nothing architecture and are independent from each other. However, the DBMS integrates data logically in a way that it appears as one single database to the user/application."
},
{
"code": null,
"e": 27617,
"s": 27582,
"text": "#31 What is database partitioning?"
},
{
"code": null,
"e": 27929,
"s": 27617,
"text": "Partitioning is a process where very large tables are divided into multiple smaller manageable pieces. Some benefits of partitioning include faster queries, faster data load, and faster deletion of old data. The benefits of partitioning are constrained by the selection of the partition key and the granularity."
},
{
"code": null,
"e": 28276,
"s": 27929,
"text": "Two are two ways that a table can be partitioned: horizontally and vertically. Vertical partitioning puts different columns into different partitions, whereas horizontal partitioning puts subset of rows in different partitions based on a partition key. For example, a company’s sale records can be horizontally partitioned based on the sale date."
},
{
"code": null,
"e": 28307,
"s": 28276,
"text": "#32 What is database sharding?"
},
{
"code": null,
"e": 28478,
"s": 28307,
"text": "Sharding, in essence, is a horizontal partitioning architecture. Each shard has the same schema and columns, but different rows, and they are independent from each other."
},
{
"code": null,
"e": 28779,
"s": 28478,
"text": "The main benefit of sharding is scalability. With automatic sharding architecture, you can simply add more machines to your stack whenever it is needed and reduce the load on existing machines and allow more traffic and faster processing. It is very appealing to applications during the growth stage."
},
{
"code": null,
"e": 28853,
"s": 28779,
"text": "If you want to learn more about it, you can refer to this article (here)."
},
{
"code": null,
"e": 28901,
"s": 28853,
"text": "#33 What are different types of SQL statements?"
},
{
"code": null,
"e": 29066,
"s": 28901,
"text": "SQL statements are high-level instructions and each statement is responsible for a specific task. These statements can generally be classified into five categories:"
},
{
"code": null,
"e": 29200,
"s": 29066,
"text": "Data Definition Language (DDL)* This family of SQL commands is used to define database schema.* Examples include CREATE , DROP, ALTER"
},
{
"code": null,
"e": 29348,
"s": 29200,
"text": "Data Manipulation Language (DML)* This family of SQL commands is used to modify the data inside a table.* Examples include INSERT , UPDATE , DELETE"
},
{
"code": null,
"e": 29463,
"s": 29348,
"text": "Data Query Language (DQL)* This family of SQL commands performs query on existing tables.* Examples include SELECT"
},
{
"code": null,
"e": 29593,
"s": 29463,
"text": "Data Control Language (DCL)* This family of SQL commands deals with the rights and permissions. * Examples include GRANT , REVOKE"
},
{
"code": null,
"e": 29790,
"s": 29593,
"text": "Transaction Control Language (TCL)* This family of SQL commands deals with transactions. * Examples include COMMIT , ROLLBACK , SAVEPOINT * You only need these commands if you have OLTP operation."
},
{
"code": null,
"e": 29833,
"s": 29790,
"text": "#34 What is the difference of DDL and DML?"
},
{
"code": null,
"e": 30147,
"s": 29833,
"text": "They are closely related. DDL is responsible to define the structure of the table, basically what is allowed to enter the table and what is not allowed. DDL can be regarded as a set of rules that shape the table structure (schema). After DDL defines the schema, then it is DML job to fill the table with the data."
},
{
"code": null,
"e": 30214,
"s": 30147,
"text": "#35 What is the difference between scalar and aggregate functions?"
},
{
"code": null,
"e": 30692,
"s": 30214,
"text": "Both of these functions return a single value, the difference is the input, scalar functions operate on a single value while aggregate functions operate on a set of values. I try to clarify the difference with an example. For example, string functions like ISNULL(), ISNUMERIC(), LEN()are scalar functions. They input a single value and return a single value. On the other hand, AVG(), MAX(), SUM() are aggregate functions, they input multiple values and output a single value."
},
{
"code": null,
"e": 30719,
"s": 30692,
"text": "#36 What is database VIEW?"
},
{
"code": null,
"e": 31113,
"s": 30719,
"text": "A VIEW is a virtual table. This virtual table can temporarily keep the result of your SQL query for future references. You can look at it as a named query, which you can refer to it later by its name rather than writing the whole query again. One advantage of the VIEW is that instead of creating a brand new table to store the result of your query, you create a VIEW and save your disk space."
},
{
"code": null,
"e": 31176,
"s": 31113,
"text": "#37 What is the difference between VIEW and materialized VIEW?"
},
{
"code": null,
"e": 31443,
"s": 31176,
"text": "The VIEW results are not stored on the disk, and every time a VIEW is run, we get updated results. However, in materialized VIEW, things are different. We store the results on the disk and we put some mechanism in place to keep them updated (a.k.a VIEW maintenance)."
},
{
"code": null,
"e": 31628,
"s": 31443,
"text": "Materialized VIEW is beneficial when the VIEW is accessed frequently. This way, we don’t need to run it every time. Nonetheless, materialized VIEW has storage cost and update overhead."
},
{
"code": null,
"e": 31672,
"s": 31628,
"text": "#38 What is Common Table Expressions (CTE)?"
},
{
"code": null,
"e": 31995,
"s": 31672,
"text": "CTE can be regarded as temporary VIEW or ‘inline’ VIEW . In other words, CTE is a temporary result set that you can reference within another SELECT, INSERT, UPDATE, or DELETE statement. The reason I say CTE is a temporary VIEW because it can only be used by a query attached to it and can not be referenced somewhere else."
},
{
"code": null,
"e": 32161,
"s": 31995,
"text": "CTE is defined with WITH operator. Below is simple blueprint of CTE. You can define multiple CTEs with only one WITH and it allows you to simplify intricate queries."
},
{
"code": null,
"e": 32226,
"s": 32161,
"text": "#39 What are the differences between DROP and TRUNCATE commands?"
},
{
"code": null,
"e": 32463,
"s": 32226,
"text": "DROP removes the table altogether and can not be rolled back. TRUNCATE, on the other hand, removes all the rows of that table. With TRUNCATE, the table definition (schema) still exists and we can INSERT data in the future, if we desire."
},
{
"code": null,
"e": 32530,
"s": 32463,
"text": "#40 What are the differences between DELETE and TRUNCATE commands?"
},
{
"code": null,
"e": 32989,
"s": 32530,
"text": "DELETE and TRUNCATE belong to two different categories of SQL commands, the former belongs to DML and the latter belongs to DDL. In other words, the former operates on row level while the latter operates on table level. TRUNCATE deletes all the rows of the table at once. DELETE can do the same, but it takes too much time as it deletes them row by row. If you use TRUNCATE, you can’t rollback the data, but with DELETE, you can rollback the row you deleted."
},
{
"code": null,
"e": 33055,
"s": 32989,
"text": "#41 What are the differences between PRIMARY KEY and FOREIGN KEY?"
},
{
"code": null,
"e": 33670,
"s": 33055,
"text": "These keys are very important tools in cross-referencing different tables. They also help with referential integrity. However, they are different in nature. A table only has one primary key. Primary key 1) can uniquely identify a record in the table; 2) can not accept NULL value; and 3) for most DBMSs, by default, is the clustered index. A table, unlike primary key, can have more than one foreign key. Foreign key 1) is a primary key in another table; 2) can not uniquely identify a record in the table; 3) can accept NULL values, and 4) is not automatically indexed. It is up to user to create an index for it."
},
{
"code": null,
"e": 33730,
"s": 33670,
"text": "#42 What is the difference between WHERE and HAVING clause?"
},
{
"code": null,
"e": 34188,
"s": 33730,
"text": "Both clauses are used to limit the result set by providing some conditions to filter the rows from the result set. However, there is one difference. WHERE clause scans the raw data (row by row) to check the conditions and filter them, but HAVING scans the aggregated results to check the conditions and filter them. For this reason, HAVING comes after GROUP BY in the SQL query. In summary, WHERE filters the raw data, but HAVING filters the processed data."
},
{
"code": null,
"e": 34223,
"s": 34188,
"text": "#43 What is functional dependency?"
},
{
"code": null,
"e": 34649,
"s": 34223,
"text": "The attributes of a table are functionally dependent if one of them uniquely identifies the other. It becomes more clear with an example. Suppose we have an employee table with attributes: Id, Name, and Age. Here employee Id uniquely identifies employee Name because if we know the employee Id, we can uniquely say his/her name. A functional dependency is denoted by an arrow →. So, in this case, we can show it by Id -> Name"
},
{
"code": null,
"e": 34693,
"s": 34649,
"text": "#44 What are different normalization types?"
},
{
"code": null,
"e": 34942,
"s": 34693,
"text": "There are many levels of normalization. As I explained earlier, the goal of normalization is to avoid redundancy and dependency. However, this goal can not be achieved in one step. Each normalization step (type) allows us to get closer to our goal."
},
{
"code": null,
"e": 35264,
"s": 34942,
"text": "We start with Un-normalized form of data (UNF), In UNF, cells can can have multiple values (non-atomic), if we divide those values into multiple cells to make sure each table cell has a single value, and also remove duplicate rows to make sure all the records are unique, then we transformed UNF to 1st normal form (1NF)."
},
{
"code": null,
"e": 35579,
"s": 35264,
"text": "The next step is to introduce primary key and foreign key. In this step, we divide the 1NF tables further and create new tables and connect them through primary and foreign keys. If in these new tables, all non-key attributes be fully functional dependent on the primary key, then we reach to 2nd normal form (2NF)"
},
{
"code": null,
"e": 36044,
"s": 35579,
"text": "Although with 2NF, we have reduced redundancy and dependency significantly, there is still a lot of room to improve. The next step is to remove transitive functional dependencies, which basically means a situation that if we change a non-key column, we might cause another non-key column to change. To disentangle these non-key columns, we must create a separate tables. When we have no transitive functional dependencies, then we reached to 3rd normal form (3NF)."
},
{
"code": null,
"e": 36279,
"s": 36044,
"text": "In almost all databases, 3NF is a point where we can not decompose the database further into a higher forms of normalization. However, in some complex databases, there are situations that you can achieve higher forms of normalization."
},
{
"code": null,
"e": 36539,
"s": 36279,
"text": "Higher forms of normalization are Boyce-Codd Normal Form (BCNF), 4NF, 5NF, and 6NF, which I prefer not to cover. If you are interested to learn more about these higher forms of normalization, you can read them from Wikipedia page of data normalization (here)."
},
{
"code": null,
"e": 36579,
"s": 36539,
"text": "#45 What are different integrity rules?"
},
{
"code": null,
"e": 36987,
"s": 36579,
"text": "There are two types of integrity rules that if we obey them, we can maintain our database consistency. Entity rule and Referential rule. Entity rule is related to our primary key, if we make a column the primary key, then it can not have any NULL value. Referential rule is related to our foreign keys, our foreign keys must either have a NULL value or their values must be the primary key of another table."
},
{
"code": null,
"e": 37013,
"s": 36987,
"text": "#46 What is DML Compiler?"
},
{
"code": null,
"e": 37152,
"s": 37013,
"text": "It is a translator. It transforms DML queries from high-level statements to low-level instructions, executable by query evaluation engine."
},
{
"code": null,
"e": 37172,
"s": 37152,
"text": "#47 What is cursor?"
},
{
"code": null,
"e": 37673,
"s": 37172,
"text": "Cursor is a tool that can be employed by user to return the results in a row by row manner. It is in contrast with the typical SELECT statement, which return the entire result set. Typically we are interested in complete set of rows, but there are applications, especially those that are interactive and online, that cannot always work effectively with the entire result set as a unit. These applications prefer to work on the data row by row. Cursors allow them to perform this row by row operation."
},
{
"code": null,
"e": 37743,
"s": 37673,
"text": "You can see the whole process of using a cursor in the below example."
},
{
"code": null,
"e": 37768,
"s": 37743,
"text": "#48 What is cardinality?"
},
{
"code": null,
"e": 37931,
"s": 37768,
"text": "Cardinality in the context of database systems means “uniqueness”. For example, when we say a column has a low cardinality, it means it has many duplicate values."
}
] |
Find distance between two nodes of a Binary Tree in C++ Program | In this problem, we are given a binary tree and two nodes. Our task is to create a program to Find distance between two nodes of a Binary Tree.
We need to find the distance between two nodes which is the minimum number of edges that will be traversed when we go from one node to another node.
Let’s take an example to understand the problem,
Input: binary tree
Node1 = 3 ,Node2 = 5
Output: 3
The path from node 3 to node 5 is 3 -> 1 -> 2 -> 5. There are 3 edges traversed that make distance 3.
A simple solution to the problem is using the lowest common ancestor node for the given nodes and then apply the below formula,
distance(node1, node2) = distance(root, node1) + distance(root, node2) + distance(root, LCA)
Live Demo
#include <iostream>
using namespace std;
struct Node{
struct Node *left, *right;
int key;
};
Node* insertNode(int key){
Node *temp = new Node;
temp->key = key;
temp->left = temp->right = NULL;
return temp;
}
int calcNodeLevel(Node *root, int val, int level) {
if (root == NULL)
return -1;
if (root->key == val)
return level;
int lvl = calcNodeLevel(root->left, val, level+1);
return (lvl != -1)? lvl : calcNodeLevel(root->right, val, level+1);
}
Node *findDistanceRec(Node* root, int node1, int node2, int &dist1, int &dist2, int &dist, int lvl){
if (root == NULL) return NULL;
if (root->key == node1){
dist1 = lvl;
return root;
}
if (root->key == node2){
dist2 = lvl;
return root;
}
Node *leftLCA = findDistanceRec(root->left, node1, node2, dist1,dist2, dist, lvl+1);
Node *rightLCA = findDistanceRec(root->right, node1, node2, dist1,dist2, dist, lvl+1);
if (leftLCA && rightLCA){
dist = dist1 + dist2 - 2*lvl;
return root;
}
return (leftLCA != NULL)? leftLCA: rightLCA;
}
int CalcNodeDistance(Node *root, int node1, int node2) {
int dist1 = -1, dist2 = -1, dist;
Node *lca = findDistanceRec(root, node1, node2, dist1, dist2, dist, 1);
if (dist1 != -1 && dist2 != -1)
return dist;
if (dist1 != -1){
dist = calcNodeLevel(lca, node2, 0);
return dist;
}
if (dist2 != -1){
dist = calcNodeLevel(lca, node1, 0);
return dist;
}
return -1;
}
int main(){
Node * root = insertNode(1);
root->left = insertNode(2);
root->right = insertNode(3);
root->left->left = insertNode(4);
root->left->right = insertNode(5);
root->right->left = insertNode(6);
cout<<"Distance between node with value 5 and node with value 3 is"<<CalcNodeDistance(root, 3, 5);
return 0;
}
Distance between node with value 5 and node with value 3 is 3 | [
{
"code": null,
"e": 1206,
"s": 1062,
"text": "In this problem, we are given a binary tree and two nodes. Our task is to create a program to Find distance between two nodes of a Binary Tree."
},
{
"code": null,
"e": 1355,
"s": 1206,
"text": "We need to find the distance between two nodes which is the minimum number of edges that will be traversed when we go from one node to another node."
},
{
"code": null,
"e": 1404,
"s": 1355,
"text": "Let’s take an example to understand the problem,"
},
{
"code": null,
"e": 1423,
"s": 1404,
"text": "Input: binary tree"
},
{
"code": null,
"e": 1444,
"s": 1423,
"text": "Node1 = 3 ,Node2 = 5"
},
{
"code": null,
"e": 1454,
"s": 1444,
"text": "Output: 3"
},
{
"code": null,
"e": 1556,
"s": 1454,
"text": "The path from node 3 to node 5 is 3 -> 1 -> 2 -> 5. There are 3 edges traversed that make distance 3."
},
{
"code": null,
"e": 1684,
"s": 1556,
"text": "A simple solution to the problem is using the lowest common ancestor node for the given nodes and then apply the below formula,"
},
{
"code": null,
"e": 1777,
"s": 1684,
"text": "distance(node1, node2) = distance(root, node1) + distance(root, node2) + distance(root, LCA)"
},
{
"code": null,
"e": 1788,
"s": 1777,
"text": " Live Demo"
},
{
"code": null,
"e": 3622,
"s": 1788,
"text": "#include <iostream>\nusing namespace std;\nstruct Node{\n struct Node *left, *right;\n int key;\n};\nNode* insertNode(int key){\n Node *temp = new Node;\n temp->key = key;\n temp->left = temp->right = NULL;\n return temp;\n}\nint calcNodeLevel(Node *root, int val, int level) {\n if (root == NULL)\n return -1;\n if (root->key == val)\n return level;\n int lvl = calcNodeLevel(root->left, val, level+1);\n return (lvl != -1)? lvl : calcNodeLevel(root->right, val, level+1);\n}\nNode *findDistanceRec(Node* root, int node1, int node2, int &dist1, int &dist2, int &dist, int lvl){\n if (root == NULL) return NULL;\n if (root->key == node1){\n dist1 = lvl;\n return root;\n }\n if (root->key == node2){\n dist2 = lvl;\n return root;\n }\n Node *leftLCA = findDistanceRec(root->left, node1, node2, dist1,dist2, dist, lvl+1);\n Node *rightLCA = findDistanceRec(root->right, node1, node2, dist1,dist2, dist, lvl+1);\n if (leftLCA && rightLCA){\n dist = dist1 + dist2 - 2*lvl;\n return root;\n }\n return (leftLCA != NULL)? leftLCA: rightLCA;\n}\nint CalcNodeDistance(Node *root, int node1, int node2) {\n int dist1 = -1, dist2 = -1, dist;\n Node *lca = findDistanceRec(root, node1, node2, dist1, dist2, dist, 1);\n if (dist1 != -1 && dist2 != -1)\n return dist;\n if (dist1 != -1){\n dist = calcNodeLevel(lca, node2, 0);\n return dist;\n }\n if (dist2 != -1){\n dist = calcNodeLevel(lca, node1, 0);\n return dist;\n }\n return -1;\n}\nint main(){\n Node * root = insertNode(1);\n root->left = insertNode(2);\n root->right = insertNode(3);\n root->left->left = insertNode(4);\n root->left->right = insertNode(5);\n root->right->left = insertNode(6);\n cout<<\"Distance between node with value 5 and node with value 3 is\"<<CalcNodeDistance(root, 3, 5);\n return 0;\n}"
},
{
"code": null,
"e": 3684,
"s": 3622,
"text": "Distance between node with value 5 and node with value 3 is 3"
}
] |
Find closest value for every element in array - GeeksforGeeks | 02 Dec, 2018
Given an array of integers, find the closest element for every element.
Examples:
Input : arr[] = {10, 5, 11, 6, 20, 12}Output : 6, -1, 10, 5, 12, 11
Input : arr[] = {10, 5, 11, 10, 20, 12}Output : 5 -1 10 5 12 11
A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest element. Time complexity of this solution is O(n*n)
An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time.
// Java program to demonstrate insertions in TreeSetimport java.util.*; class TreeSetDemo { public static void closestGreater(int[] arr) { if (arr.length == -1) { System.out.print(-1 + " "); return; } // Insert all array elements into a TreeMap. // A TreeMap value indicates whether an element // appears once or more. TreeMap<Integer, Boolean> tm = new TreeMap<Integer, Boolean>(); for (int i = 0; i < arr.length; i++) { // A value "True" means that the key // appears more than once. if (tm.containsKey(arr[i])) tm.put(arr[i], true); else tm.put(arr[i], false); } // Find smallest greater element for every // array element for (int i = 0; i < arr.length; i++) { // If there are multiple occurrences if (tm.get(arr[i]) == true) { System.out.print(arr[i] + " "); continue; } // If element appears only once Integer greater = tm.higherKey(arr[i]); Integer lower = tm.lowerKey(arr[i]); if (greater == null) System.out.print(lower + " "); else if (lower == null) System.out.print(greater + " "); else { int d1 = greater - arr[i]; int d2 = arr[i] - lower; if (d1 > d2) System.out.print(lower + " "); else System.out.print(greater + " "); } } } public static void main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12, 10 }; closestGreater(arr); }}
10 6 12 5 12 11 10
Exercise : Another efficient solution is to use sorting that also works in O(n Log n) time. Write complete algorithm and code for sorting based solution.
java-TreeMap
Self-Balancing-BST
Arrays
Binary Search Tree
Sorting
Arrays
Sorting
Binary Search Tree
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Multidimensional Arrays in Java
Introduction to Arrays
Maximum and minimum of an array using minimum number of comparisons
Python | Using 2D arrays/lists the right way
Linked List vs Array
Binary Search Tree | Set 1 (Search and Insertion)
AVL Tree | Set 1 (Insertion)
Binary Search Tree | Set 2 (Delete)
A program to check if a binary tree is BST or not
Sorted Array to Balanced BST | [
{
"code": null,
"e": 24214,
"s": 24186,
"text": "\n02 Dec, 2018"
},
{
"code": null,
"e": 24286,
"s": 24214,
"text": "Given an array of integers, find the closest element for every element."
},
{
"code": null,
"e": 24296,
"s": 24286,
"text": "Examples:"
},
{
"code": null,
"e": 24364,
"s": 24296,
"text": "Input : arr[] = {10, 5, 11, 6, 20, 12}Output : 6, -1, 10, 5, 12, 11"
},
{
"code": null,
"e": 24428,
"s": 24364,
"text": "Input : arr[] = {10, 5, 11, 10, 20, 12}Output : 5 -1 10 5 12 11"
},
{
"code": null,
"e": 24634,
"s": 24428,
"text": "A simple solution is to run two nested loops. We pick an outer element one by one. For every picked element, we traverse remaining array and find closest element. Time complexity of this solution is O(n*n)"
},
{
"code": null,
"e": 24830,
"s": 24634,
"text": "An efficient solution is to use Self Balancing BST (Implemented as set in C++ and TreeSet in Java). In a Self Balancing BST, we can do both insert and closest greater operations in O(Log n) time."
},
{
"code": "// Java program to demonstrate insertions in TreeSetimport java.util.*; class TreeSetDemo { public static void closestGreater(int[] arr) { if (arr.length == -1) { System.out.print(-1 + \" \"); return; } // Insert all array elements into a TreeMap. // A TreeMap value indicates whether an element // appears once or more. TreeMap<Integer, Boolean> tm = new TreeMap<Integer, Boolean>(); for (int i = 0; i < arr.length; i++) { // A value \"True\" means that the key // appears more than once. if (tm.containsKey(arr[i])) tm.put(arr[i], true); else tm.put(arr[i], false); } // Find smallest greater element for every // array element for (int i = 0; i < arr.length; i++) { // If there are multiple occurrences if (tm.get(arr[i]) == true) { System.out.print(arr[i] + \" \"); continue; } // If element appears only once Integer greater = tm.higherKey(arr[i]); Integer lower = tm.lowerKey(arr[i]); if (greater == null) System.out.print(lower + \" \"); else if (lower == null) System.out.print(greater + \" \"); else { int d1 = greater - arr[i]; int d2 = arr[i] - lower; if (d1 > d2) System.out.print(lower + \" \"); else System.out.print(greater + \" \"); } } } public static void main(String[] args) { int[] arr = { 10, 5, 11, 6, 20, 12, 10 }; closestGreater(arr); }}",
"e": 26602,
"s": 24830,
"text": null
},
{
"code": null,
"e": 26622,
"s": 26602,
"text": "10 6 12 5 12 11 10\n"
},
{
"code": null,
"e": 26776,
"s": 26622,
"text": "Exercise : Another efficient solution is to use sorting that also works in O(n Log n) time. Write complete algorithm and code for sorting based solution."
},
{
"code": null,
"e": 26789,
"s": 26776,
"text": "java-TreeMap"
},
{
"code": null,
"e": 26808,
"s": 26789,
"text": "Self-Balancing-BST"
},
{
"code": null,
"e": 26815,
"s": 26808,
"text": "Arrays"
},
{
"code": null,
"e": 26834,
"s": 26815,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 26842,
"s": 26834,
"text": "Sorting"
},
{
"code": null,
"e": 26849,
"s": 26842,
"text": "Arrays"
},
{
"code": null,
"e": 26857,
"s": 26849,
"text": "Sorting"
},
{
"code": null,
"e": 26876,
"s": 26857,
"text": "Binary Search Tree"
},
{
"code": null,
"e": 26974,
"s": 26876,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27006,
"s": 26974,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27029,
"s": 27006,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 27097,
"s": 27029,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 27142,
"s": 27097,
"text": "Python | Using 2D arrays/lists the right way"
},
{
"code": null,
"e": 27163,
"s": 27142,
"text": "Linked List vs Array"
},
{
"code": null,
"e": 27213,
"s": 27163,
"text": "Binary Search Tree | Set 1 (Search and Insertion)"
},
{
"code": null,
"e": 27242,
"s": 27213,
"text": "AVL Tree | Set 1 (Insertion)"
},
{
"code": null,
"e": 27278,
"s": 27242,
"text": "Binary Search Tree | Set 2 (Delete)"
},
{
"code": null,
"e": 27328,
"s": 27278,
"text": "A program to check if a binary tree is BST or not"
}
] |
Array of Arrays Representation in Data Structure | In this section we will see another representation of multidimensional arrays. Here we will see the Array of Arrays representation. In this form, we have an array, that is holding the starting addresses of multiple arrays. The representation will be look like this.
This is a two-dimensional array x of size [7 x 8]. Each row is represented as a single onedimensional array. The initial array is holding the addresses of these single arrays. They are array of addresses, so we can say that, it is an array of pointers. Each pointer is holding addresses of another arrays.
create this kind of array, we can use the new keyword like below −
int [][] x = new int[7][8];
To retrieve an element present at position x[i, j], it will find the address using x[i] at first, then move to jth index in that array. | [
{
"code": null,
"e": 1328,
"s": 1062,
"text": "In this section we will see another representation of multidimensional arrays. Here we will see the Array of Arrays representation. In this form, we have an array, that is holding the starting addresses of multiple arrays. The representation will be look like this."
},
{
"code": null,
"e": 1634,
"s": 1328,
"text": "This is a two-dimensional array x of size [7 x 8]. Each row is represented as a single onedimensional array. The initial array is holding the addresses of these single arrays. They are array of addresses, so we can say that, it is an array of pointers. Each pointer is holding addresses of another arrays."
},
{
"code": null,
"e": 1701,
"s": 1634,
"text": "create this kind of array, we can use the new keyword like below −"
},
{
"code": null,
"e": 1729,
"s": 1701,
"text": "int [][] x = new int[7][8];"
},
{
"code": null,
"e": 1865,
"s": 1729,
"text": "To retrieve an element present at position x[i, j], it will find the address using x[i] at first, then move to jth index in that array."
}
] |
3 Ways To Compute A Weighted Average in Python | by AnBento | Towards Data Science | Update: Many of you contacted me asking for valuable resources to automate Excel tasks with Python or to apply popular statistical concepts in Python. Below I share four courses that I would recommend:
Programming For Data Science In Python (Nano-Degree) →Very high quality course! **UP TO 75% DISCOUNT IN JAN 2022**
Python Programming For Excel Users (Numpy & Pandas)
Python For Data Analysis (Pandas & Numpy)
Practicing Statistics Interview Questions In Python
Hope you’ll find them useful too! Now enjoy the article :D
Suppose you had to analyze the table below, showing the yearly salary for the employees of a small company divided in five groups (from lower to higher salary):
If you computed the simple average of the Salary Per Year column you would obtain:
But is £62,000 an accurate representation of the average salary across the groups? Because data comes already aggregated and each group has a different Employees Number, the average Salary Per Year for each group weights differently in the overall average. In computing the simple average, the same weight was assigned to each group leading to a biased result.
In this cases, the solution is to take into account the weight of each group by computing a weighted average that can be represented algebraically with the formula:
Where x represents the distribution ( Salary Per Year ) and w represents the weight to be assigned ( Employees Number). Given that the table includes five groups, the formula above becomes:
An by replacing x and w with actual figures, you should obtain the result below:
Note how taking weights into account, the average Salary Per Year across the groups is almost £18,000 lower than the one computed with the simple average and this is an accurate way to describe our dataset given the number of employees in each group.
Now that the theory has been covered, let’s see how to obtain a weighted average in Python using 3 different methods. In order to do that, the first step is to import packages and the employees_salary table itself:
import pandas as pdfrom numpy import averagedf = pd.read_csv(‘C:/Users/anbento/Desktop/employee_salary.csv’)df.head()distribution = df[‘salary_p_year’]weights = df[‘employees_number’]
towardsdatascience.com
If you wish to code your own algorithm, the first very straightforward way to compute a weighted average is to use list comprehension to obtain the product of each Salary Per Year with the corresponding Employee Number ( numerator ) and then divide it by the sum of the weights ( denominator).
Output:44225.35
The function above could easily be rewritten as a one liner:
Output:44225.35
Instead of using list comprehensions, you could simply start from and empty list ( weighted_sum ) and append the product of the average salary for each group by its weight . The zip() function is very handy as it generates an iterator of tuples that helps pairing each salary to the corresponding weight .
Output:44225.35
The numpy package includes an average() function (that has been imported above) where you can specify a list of weights to calculate a weighted average. This is by far the easiest and more flexible method to perform these kind of computations in production:
Output:44225.35
towardsdatascience.com
In this brief tutorial, we learnt how weighted averages should be the preferred option every time data is presented in an aggregated or grouped way, where some quantities or frequencies can be identified. We also found at least 3 methods to compute a weighted average with Python either with a self-defined function or a built-in one. I would be curious to know if you use any other algorithm or package to compute weighted averages, so please do leave a comment!
This post includes affiliate links for which I may make a small commission at no extra cost to you, should you make a purchase. | [
{
"code": null,
"e": 248,
"s": 46,
"text": "Update: Many of you contacted me asking for valuable resources to automate Excel tasks with Python or to apply popular statistical concepts in Python. Below I share four courses that I would recommend:"
},
{
"code": null,
"e": 363,
"s": 248,
"text": "Programming For Data Science In Python (Nano-Degree) →Very high quality course! **UP TO 75% DISCOUNT IN JAN 2022**"
},
{
"code": null,
"e": 415,
"s": 363,
"text": "Python Programming For Excel Users (Numpy & Pandas)"
},
{
"code": null,
"e": 457,
"s": 415,
"text": "Python For Data Analysis (Pandas & Numpy)"
},
{
"code": null,
"e": 509,
"s": 457,
"text": "Practicing Statistics Interview Questions In Python"
},
{
"code": null,
"e": 568,
"s": 509,
"text": "Hope you’ll find them useful too! Now enjoy the article :D"
},
{
"code": null,
"e": 729,
"s": 568,
"text": "Suppose you had to analyze the table below, showing the yearly salary for the employees of a small company divided in five groups (from lower to higher salary):"
},
{
"code": null,
"e": 812,
"s": 729,
"text": "If you computed the simple average of the Salary Per Year column you would obtain:"
},
{
"code": null,
"e": 1173,
"s": 812,
"text": "But is £62,000 an accurate representation of the average salary across the groups? Because data comes already aggregated and each group has a different Employees Number, the average Salary Per Year for each group weights differently in the overall average. In computing the simple average, the same weight was assigned to each group leading to a biased result."
},
{
"code": null,
"e": 1338,
"s": 1173,
"text": "In this cases, the solution is to take into account the weight of each group by computing a weighted average that can be represented algebraically with the formula:"
},
{
"code": null,
"e": 1528,
"s": 1338,
"text": "Where x represents the distribution ( Salary Per Year ) and w represents the weight to be assigned ( Employees Number). Given that the table includes five groups, the formula above becomes:"
},
{
"code": null,
"e": 1609,
"s": 1528,
"text": "An by replacing x and w with actual figures, you should obtain the result below:"
},
{
"code": null,
"e": 1860,
"s": 1609,
"text": "Note how taking weights into account, the average Salary Per Year across the groups is almost £18,000 lower than the one computed with the simple average and this is an accurate way to describe our dataset given the number of employees in each group."
},
{
"code": null,
"e": 2075,
"s": 1860,
"text": "Now that the theory has been covered, let’s see how to obtain a weighted average in Python using 3 different methods. In order to do that, the first step is to import packages and the employees_salary table itself:"
},
{
"code": null,
"e": 2259,
"s": 2075,
"text": "import pandas as pdfrom numpy import averagedf = pd.read_csv(‘C:/Users/anbento/Desktop/employee_salary.csv’)df.head()distribution = df[‘salary_p_year’]weights = df[‘employees_number’]"
},
{
"code": null,
"e": 2282,
"s": 2259,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 2576,
"s": 2282,
"text": "If you wish to code your own algorithm, the first very straightforward way to compute a weighted average is to use list comprehension to obtain the product of each Salary Per Year with the corresponding Employee Number ( numerator ) and then divide it by the sum of the weights ( denominator)."
},
{
"code": null,
"e": 2592,
"s": 2576,
"text": "Output:44225.35"
},
{
"code": null,
"e": 2653,
"s": 2592,
"text": "The function above could easily be rewritten as a one liner:"
},
{
"code": null,
"e": 2669,
"s": 2653,
"text": "Output:44225.35"
},
{
"code": null,
"e": 2975,
"s": 2669,
"text": "Instead of using list comprehensions, you could simply start from and empty list ( weighted_sum ) and append the product of the average salary for each group by its weight . The zip() function is very handy as it generates an iterator of tuples that helps pairing each salary to the corresponding weight ."
},
{
"code": null,
"e": 2991,
"s": 2975,
"text": "Output:44225.35"
},
{
"code": null,
"e": 3249,
"s": 2991,
"text": "The numpy package includes an average() function (that has been imported above) where you can specify a list of weights to calculate a weighted average. This is by far the easiest and more flexible method to perform these kind of computations in production:"
},
{
"code": null,
"e": 3265,
"s": 3249,
"text": "Output:44225.35"
},
{
"code": null,
"e": 3288,
"s": 3265,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 3752,
"s": 3288,
"text": "In this brief tutorial, we learnt how weighted averages should be the preferred option every time data is presented in an aggregated or grouped way, where some quantities or frequencies can be identified. We also found at least 3 methods to compute a weighted average with Python either with a self-defined function or a built-in one. I would be curious to know if you use any other algorithm or package to compute weighted averages, so please do leave a comment!"
}
] |
Queue remove() method in Java - GeeksforGeeks | 26 Sep, 2018
The remove() method of Queue Interface returns and removes the element at the front the container. It deletes the head of the container. The method throws an NoSuchElementException when the Queue is empty.
Syntax:
E remove()
Returns: This method returns the head of the Queue.
Exception: The function throws an NoSuchElementException when the Queue is empty.
Below programs illustrate remove() method of Queue:
Program 1: With the help of LinkedList.
// Java Program Demonstrate remove()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head and deletes the head System.out.println("Queue's head: " + Q.remove()); // print head and deleted the head System.out.println("Queue's head: " + Q.remove()); }}
Queue: [7855642, 35658786, 5278367, 74381793]
Queue's head: 7855642
Queue's head: 35658786
Program 2: With the help of ArrayDeque.
// Java Program Demonstrate remove()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head and deletes the head System.out.println("Queue's head: " + Q.remove()); // print head and deleted the head System.out.println("Queue's head: " + Q.remove()); }}
Queue: [7855642, 35658786, 5278367, 74381793]
Queue's head: 7855642
Queue's head: 35658786
Program 3: With the help of LinkedBlockingDeque.
// Java Program Demonstrate remove()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head and deletes the head System.out.println("Queue's head: " + Q.remove()); // print head and deleted the head System.out.println("Queue's head: " + Q.remove()); }}
Queue: [7855642, 35658786, 5278367, 74381793]
Queue's head: 7855642
Queue's head: 35658786
Program 4: With the help of ConcurrentLinkedDeque.
// Java Program Demonstrate remove()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println("Queue: " + Q); // print head and deletes the head System.out.println("Queue's head: " + Q.remove()); // print head and deleted the head System.out.println("Queue's head: " + Q.remove()); }}
Queue: [7855642, 35658786, 5278367, 74381793]
Queue's head: 7855642
Queue's head: 35658786
Below programs illustrate exceptions thrown by this method:
Program 5: To show NoSuchElementException.
// Java Program Demonstrate remove()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(423); Q.add(3432); // print queue System.out.println("Queue: " + Q); // print head and deletes the head System.out.println("Queue's head: " + Q.remove()); // print head and deleted the head System.out.println("Queue's head: " + Q.remove()); // print queue System.out.println("Queue: " + Q); try { // Queue is empty now hence exception System.out.println("Queue's head: " + Q.element()); } catch (Exception e) { System.out.println("Exception: " + e); } }}
Queue: [423, 3432]
Queue's head: 423
Queue's head: 3432
Queue: []
Exception: java.util.NoSuchElementException
Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#remove–
Java - util package
java-basics
Java-Collections
Java-Functions
java-queue
Java
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Constructors in Java
Different ways of Reading a text file in Java
Exceptions in Java
Functional Interfaces in Java
Generics in Java
Comparator Interface in Java with Examples
Introduction to Java
HashMap get() Method in Java
Strings in Java | [
{
"code": null,
"e": 23948,
"s": 23920,
"text": "\n26 Sep, 2018"
},
{
"code": null,
"e": 24154,
"s": 23948,
"text": "The remove() method of Queue Interface returns and removes the element at the front the container. It deletes the head of the container. The method throws an NoSuchElementException when the Queue is empty."
},
{
"code": null,
"e": 24162,
"s": 24154,
"text": "Syntax:"
},
{
"code": null,
"e": 24173,
"s": 24162,
"text": "E remove()"
},
{
"code": null,
"e": 24225,
"s": 24173,
"text": "Returns: This method returns the head of the Queue."
},
{
"code": null,
"e": 24307,
"s": 24225,
"text": "Exception: The function throws an NoSuchElementException when the Queue is empty."
},
{
"code": null,
"e": 24359,
"s": 24307,
"text": "Below programs illustrate remove() method of Queue:"
},
{
"code": null,
"e": 24399,
"s": 24359,
"text": "Program 1: With the help of LinkedList."
},
{
"code": "// Java Program Demonstrate remove()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head and deletes the head System.out.println(\"Queue's head: \" + Q.remove()); // print head and deleted the head System.out.println(\"Queue's head: \" + Q.remove()); }}",
"e": 25087,
"s": 24399,
"text": null
},
{
"code": null,
"e": 25179,
"s": 25087,
"text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\nQueue's head: 35658786\n"
},
{
"code": null,
"e": 25219,
"s": 25179,
"text": "Program 2: With the help of ArrayDeque."
},
{
"code": "// Java Program Demonstrate remove()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ArrayDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head and deletes the head System.out.println(\"Queue's head: \" + Q.remove()); // print head and deleted the head System.out.println(\"Queue's head: \" + Q.remove()); }}",
"e": 25907,
"s": 25219,
"text": null
},
{
"code": null,
"e": 25999,
"s": 25907,
"text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\nQueue's head: 35658786\n"
},
{
"code": null,
"e": 26048,
"s": 25999,
"text": "Program 3: With the help of LinkedBlockingDeque."
},
{
"code": "// Java Program Demonstrate remove()// method of Queue import java.util.*;import java.util.concurrent.LinkedBlockingDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedBlockingDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head and deletes the head System.out.println(\"Queue's head: \" + Q.remove()); // print head and deleted the head System.out.println(\"Queue's head: \" + Q.remove()); }}",
"e": 26793,
"s": 26048,
"text": null
},
{
"code": null,
"e": 26885,
"s": 26793,
"text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\nQueue's head: 35658786\n"
},
{
"code": null,
"e": 26936,
"s": 26885,
"text": "Program 4: With the help of ConcurrentLinkedDeque."
},
{
"code": "// Java Program Demonstrate remove()// method of Queue import java.util.*;import java.util.concurrent.ConcurrentLinkedDeque; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new ConcurrentLinkedDeque<Integer>(); // Add numbers to end of Queue Q.add(7855642); Q.add(35658786); Q.add(5278367); Q.add(74381793); // print queue System.out.println(\"Queue: \" + Q); // print head and deletes the head System.out.println(\"Queue's head: \" + Q.remove()); // print head and deleted the head System.out.println(\"Queue's head: \" + Q.remove()); }}",
"e": 27685,
"s": 26936,
"text": null
},
{
"code": null,
"e": 27777,
"s": 27685,
"text": "Queue: [7855642, 35658786, 5278367, 74381793]\nQueue's head: 7855642\nQueue's head: 35658786\n"
},
{
"code": null,
"e": 27837,
"s": 27777,
"text": "Below programs illustrate exceptions thrown by this method:"
},
{
"code": null,
"e": 27880,
"s": 27837,
"text": "Program 5: To show NoSuchElementException."
},
{
"code": "// Java Program Demonstrate remove()// method of Queue import java.util.*; public class GFG { public static void main(String[] args) throws IllegalStateException { // create object of Queue Queue<Integer> Q = new LinkedList<Integer>(); // Add numbers to end of Queue Q.add(423); Q.add(3432); // print queue System.out.println(\"Queue: \" + Q); // print head and deletes the head System.out.println(\"Queue's head: \" + Q.remove()); // print head and deleted the head System.out.println(\"Queue's head: \" + Q.remove()); // print queue System.out.println(\"Queue: \" + Q); try { // Queue is empty now hence exception System.out.println(\"Queue's head: \" + Q.element()); } catch (Exception e) { System.out.println(\"Exception: \" + e); } }}",
"e": 28803,
"s": 27880,
"text": null
},
{
"code": null,
"e": 28914,
"s": 28803,
"text": "Queue: [423, 3432]\nQueue's head: 423\nQueue's head: 3432\nQueue: []\nException: java.util.NoSuchElementException\n"
},
{
"code": null,
"e": 28996,
"s": 28914,
"text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/Queue.html#remove–"
},
{
"code": null,
"e": 29016,
"s": 28996,
"text": "Java - util package"
},
{
"code": null,
"e": 29028,
"s": 29016,
"text": "java-basics"
},
{
"code": null,
"e": 29045,
"s": 29028,
"text": "Java-Collections"
},
{
"code": null,
"e": 29060,
"s": 29045,
"text": "Java-Functions"
},
{
"code": null,
"e": 29071,
"s": 29060,
"text": "java-queue"
},
{
"code": null,
"e": 29076,
"s": 29071,
"text": "Java"
},
{
"code": null,
"e": 29081,
"s": 29076,
"text": "Java"
},
{
"code": null,
"e": 29098,
"s": 29081,
"text": "Java-Collections"
},
{
"code": null,
"e": 29196,
"s": 29098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29211,
"s": 29196,
"text": "Stream In Java"
},
{
"code": null,
"e": 29232,
"s": 29211,
"text": "Constructors in Java"
},
{
"code": null,
"e": 29278,
"s": 29232,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 29297,
"s": 29278,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 29327,
"s": 29297,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 29344,
"s": 29327,
"text": "Generics in Java"
},
{
"code": null,
"e": 29387,
"s": 29344,
"text": "Comparator Interface in Java with Examples"
},
{
"code": null,
"e": 29408,
"s": 29387,
"text": "Introduction to Java"
},
{
"code": null,
"e": 29437,
"s": 29408,
"text": "HashMap get() Method in Java"
}
] |
Finding the sum of integers from multiple MySQL rows in same column? | Let us first create a table −
mysql> create table DemoTable739 (Price int);
Query OK, 0 rows affected (0.65 sec)
Insert some records in the table using insert command −
mysql> insert into DemoTable739 values(100);
Query OK, 1 row affected (0.15 sec)
mysql> insert into DemoTable739 values(50);
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable739 values(1200);
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable739 values(500);
Query OK, 1 row affected (0.37 sec)
mysql> insert into DemoTable739 values(800);
Query OK, 1 row affected (0.20 sec)
Display all records from the table using select statement −
mysql> select *from DemoTable739;
This will produce the following output -
+-------+
| Price |
+-------+
| 100 |
| 50 |
| 1200 |
| 500 |
| 800 |
+-------+
5 rows in set (0.00 sec)
Following is the query to find the sum of integers from multiple MySQL rows in same column −
mysql> select sum(Price) as Total_Price from DemoTable739;
This will produce the following output -
+-------------+
| Total_Price |
+-------------+
| 2650 |
+-------------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1092,
"s": 1062,
"text": "Let us first create a table −"
},
{
"code": null,
"e": 1175,
"s": 1092,
"text": "mysql> create table DemoTable739 (Price int);\nQuery OK, 0 rows affected (0.65 sec)"
},
{
"code": null,
"e": 1231,
"s": 1175,
"text": "Insert some records in the table using insert command −"
},
{
"code": null,
"e": 1636,
"s": 1231,
"text": "mysql> insert into DemoTable739 values(100);\nQuery OK, 1 row affected (0.15 sec)\nmysql> insert into DemoTable739 values(50);\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable739 values(1200);\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable739 values(500);\nQuery OK, 1 row affected (0.37 sec)\nmysql> insert into DemoTable739 values(800);\nQuery OK, 1 row affected (0.20 sec)"
},
{
"code": null,
"e": 1696,
"s": 1636,
"text": "Display all records from the table using select statement −"
},
{
"code": null,
"e": 1730,
"s": 1696,
"text": "mysql> select *from DemoTable739;"
},
{
"code": null,
"e": 1771,
"s": 1730,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 1886,
"s": 1771,
"text": "+-------+\n| Price |\n+-------+\n| 100 |\n| 50 |\n| 1200 |\n| 500 |\n| 800 |\n+-------+\n5 rows in set (0.00 sec)"
},
{
"code": null,
"e": 1979,
"s": 1886,
"text": "Following is the query to find the sum of integers from multiple MySQL rows in same column −"
},
{
"code": null,
"e": 2038,
"s": 1979,
"text": "mysql> select sum(Price) as Total_Price from DemoTable739;"
},
{
"code": null,
"e": 2079,
"s": 2038,
"text": "This will produce the following output -"
},
{
"code": null,
"e": 2183,
"s": 2079,
"text": "+-------------+\n| Total_Price |\n+-------------+\n| 2650 |\n+-------------+\n1 row in set (0.00 sec)"
}
] |
Django Template Filters - GeeksforGeeks | 07 Feb, 2020
Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one’s own need.
{{ variable_name | filter_name }}
Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags.
{{ value | length }}
If value is [‘a’, ‘b’, ‘c’, ‘d’], the output will be 4.
This article revolves around various Django Template Filters one can use during a project. Filters transform the values of variables and tag arguments. Let’s check some major filters.
addIt is used to add an argument to the value.Example{{ value | add:"2" }}If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates.addslashesIt is used to add slashes before quotes. Useful for escaping strings in CSV.Example{{ value | addslashes }}If value is “I’m Jai”, the output will be “I\’m Jai”.capfirstIt is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.Example{{ value | capfirst }}If value is “jai”, the output will be “Jai”.centerIt is used to center the value in a field of a given width.Example"{{ value | center:"15" }}"If value is “Jai”, the output will be ” Jai “.cutIt is used to remove all values of arg from the given string.Example{{ value | cut:" " }}If value is “String with spaces”, the output will be “Stringwithspaces”.dateIt is used to format a date according to the given format.Example{{ value | date:"D d M Y" }}If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here.defaultIt is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself.Example{{ value | default:"nothing" }}If value is “” (the empty string), the output will be nothing.dictsortIt takes a list of dictionaries and returns that list sorted by the key given in the argument.Example{{ value | dictsort:"name" }}If value is:[
{'name': 'zed', 'age': 19},
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
]then the output would be:[
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
{'name': 'zed', 'age': 19},
] divisiblebyIt returns True if the value is divisible by the argument.Example{{ value | divisibleby:"3" }}If value is 21, the output would be True.escapeIt is used to escapea a string’s HTML. Specifically, it makes these replacements:< is converted to <> is converted to >' (single quote) is converted to '" (double quote) is converted to "& is converted to &Example{{ title | escape }}filesizeformatIt is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).Example{{ value | filesizeformat }}If value is 123456789, the output would be 117.7 MB.firstIt is used to return the first item in a list.Example{{ value | first }}If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’.joinIt is used to join a list with a string, like Python’s str.join(list)Example{{ value | join:" // " }}If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”.lastIt is used to return the last item in a list.Example{{ value | last }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”.lengthIt is used to return the length of the value. This works for both strings and lists.Example{{ value | length }}If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4.linenumbersIt is used to display text with line numbers.Example{{ value | linenumbers }}If value is:one
two
threethe output will be:1. one
2. two
3. threelowerIt is used to converts a string into all lowercase.Example{{ value | lower }}}If value is My Name is Jai, the output will be my name is jai.make_listIt is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.Example{{ value | make_list }}If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’].randomIt is used to return a random item from the given list.Example{{ value | random }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”.sliceIt is used to return a slice of the list.Example{{ some_list | slice:":2" }}If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’].slugifyIt is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.Example{{ value | slugify }}If value is “Jai is a slug”, the output will be “jai-is-a-slug”.timeIt is used to format a time according to the given format.Example{{ value | time:"H:i" }}If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”.timesinceIt is used to format a date as the time since that date (e.g., “4 days, 6 hours”).Example{{ blog_date | timesince:comment_date }}if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”titleIt is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase.Example{{ value | title }}If value is “my FIRST post”, the output will be “My First Post”.unordered_listIt is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.Example{{ var | unordered_list }}if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:<li>States<ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li></ul></li> </li>upperIt is used to convert a string into all uppercase.Example{{ value | upper }}If value is “Jai is a slug”, the output will be “JAI IS A SLUG”.wordcountIt is used to return the number of words.Example{{ value | wordcount }}If value is “jai is a slug”, the output will be 4.
addIt is used to add an argument to the value.Example{{ value | add:"2" }}If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates.
It is used to add an argument to the value.Example
{{ value | add:"2" }}
If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates.
addslashesIt is used to add slashes before quotes. Useful for escaping strings in CSV.Example{{ value | addslashes }}If value is “I’m Jai”, the output will be “I\’m Jai”.
It is used to add slashes before quotes. Useful for escaping strings in CSV.Example
{{ value | addslashes }}
If value is “I’m Jai”, the output will be “I\’m Jai”.
capfirstIt is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.Example{{ value | capfirst }}If value is “jai”, the output will be “Jai”.
It is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.Example
{{ value | capfirst }}
If value is “jai”, the output will be “Jai”.
centerIt is used to center the value in a field of a given width.Example"{{ value | center:"15" }}"If value is “Jai”, the output will be ” Jai “.
It is used to center the value in a field of a given width.Example
"{{ value | center:"15" }}"
If value is “Jai”, the output will be ” Jai “.
cutIt is used to remove all values of arg from the given string.Example{{ value | cut:" " }}If value is “String with spaces”, the output will be “Stringwithspaces”.
It is used to remove all values of arg from the given string.
Example
{{ value | cut:" " }}
If value is “String with spaces”, the output will be “Stringwithspaces”.
dateIt is used to format a date according to the given format.Example{{ value | date:"D d M Y" }}If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here.
It is used to format a date according to the given format.Example
{{ value | date:"D d M Y" }}
If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here.
defaultIt is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself.Example{{ value | default:"nothing" }}If value is “” (the empty string), the output will be nothing.
It is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself.
Example
{{ value | default:"nothing" }}
If value is “” (the empty string), the output will be nothing.
dictsortIt takes a list of dictionaries and returns that list sorted by the key given in the argument.Example{{ value | dictsort:"name" }}If value is:[
{'name': 'zed', 'age': 19},
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
]then the output would be:[
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
{'name': 'zed', 'age': 19},
]
It takes a list of dictionaries and returns that list sorted by the key given in the argument.Example
{{ value | dictsort:"name" }}
If value is:
[
{'name': 'zed', 'age': 19},
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
]
then the output would be:
[
{'name': 'amy', 'age': 22},
{'name': 'joe', 'age': 31},
{'name': 'zed', 'age': 19},
]
divisiblebyIt returns True if the value is divisible by the argument.Example{{ value | divisibleby:"3" }}If value is 21, the output would be True.
It returns True if the value is divisible by the argument.Example
{{ value | divisibleby:"3" }}
If value is 21, the output would be True.
escapeIt is used to escapea a string’s HTML. Specifically, it makes these replacements:< is converted to <> is converted to >' (single quote) is converted to '" (double quote) is converted to "& is converted to &Example{{ title | escape }}
It is used to escapea a string’s HTML. Specifically, it makes these replacements:
< is converted to <> is converted to >' (single quote) is converted to '" (double quote) is converted to "& is converted to &
Example
{{ title | escape }}
filesizeformatIt is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).Example{{ value | filesizeformat }}If value is 123456789, the output would be 117.7 MB.
It is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).Example
{{ value | filesizeformat }}
If value is 123456789, the output would be 117.7 MB.
firstIt is used to return the first item in a list.Example{{ value | first }}If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’.
It is used to return the first item in a list.Example
{{ value | first }}
If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’.
joinIt is used to join a list with a string, like Python’s str.join(list)Example{{ value | join:" // " }}If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”.
It is used to join a list with a string, like Python’s str.join(list)Example
{{ value | join:" // " }}
If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”.
lastIt is used to return the last item in a list.Example{{ value | last }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”.
It is used to return the last item in a list.Example
{{ value | last }}
If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”.
lengthIt is used to return the length of the value. This works for both strings and lists.Example{{ value | length }}If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4.
It is used to return the length of the value. This works for both strings and lists.Example
{{ value | length }}
If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4.
linenumbersIt is used to display text with line numbers.Example{{ value | linenumbers }}If value is:one
two
threethe output will be:1. one
2. two
3. three
It is used to display text with line numbers.Example
{{ value | linenumbers }}
If value is:
one
two
three
the output will be:
1. one
2. two
3. three
lowerIt is used to converts a string into all lowercase.Example{{ value | lower }}}If value is My Name is Jai, the output will be my name is jai.
It is used to converts a string into all lowercase.Example
{{ value | lower }}}
If value is My Name is Jai, the output will be my name is jai.
make_listIt is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.Example{{ value | make_list }}If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’].
It is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.Example
{{ value | make_list }}
If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’].
randomIt is used to return a random item from the given list.Example{{ value | random }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”.
It is used to return a random item from the given list.Example
{{ value | random }}
If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”.
sliceIt is used to return a slice of the list.Example{{ some_list | slice:":2" }}If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’].
It is used to return a slice of the list.Example
{{ some_list | slice:":2" }}
If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’].
slugifyIt is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.Example{{ value | slugify }}If value is “Jai is a slug”, the output will be “jai-is-a-slug”.
It is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.Example
{{ value | slugify }}
If value is “Jai is a slug”, the output will be “jai-is-a-slug”.
timeIt is used to format a time according to the given format.Example{{ value | time:"H:i" }}If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”.
It is used to format a time according to the given format.Example
{{ value | time:"H:i" }}
If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”.
timesinceIt is used to format a date as the time since that date (e.g., “4 days, 6 hours”).Example{{ blog_date | timesince:comment_date }}if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”
It is used to format a date as the time since that date (e.g., “4 days, 6 hours”).
Example
{{ blog_date | timesince:comment_date }}
if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”
titleIt is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase.Example{{ value | title }}If value is “my FIRST post”, the output will be “My First Post”.
It is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase.
Example
{{ value | title }}
If value is “my FIRST post”, the output will be “My First Post”.
unordered_listIt is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.Example{{ var | unordered_list }}if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:<li>States<ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li></ul></li> </li>
It is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.Example
{{ var | unordered_list }}
if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:
<li>States<ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li></ul></li> </li>
upperIt is used to convert a string into all uppercase.Example{{ value | upper }}If value is “Jai is a slug”, the output will be “JAI IS A SLUG”.
It is used to convert a string into all uppercase.Example
{{ value | upper }}
If value is “Jai is a slug”, the output will be “JAI IS A SLUG”.
wordcountIt is used to return the number of words.Example{{ value | wordcount }}If value is “jai is a slug”, the output will be 4.
It is used to return the number of words.Example
{{ value | wordcount }}
If value is “jai is a slug”, the output will be 4.
Django-templates
Python Django
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Read a file line by line in Python
Enumerate() in Python
How to Install PIP on Windows ?
Iterate over a list in Python
Different ways to create Pandas Dataframe
Python String | replace()
Create a Pandas DataFrame from Lists
Python program to convert a list to string
Reading and Writing to text files in Python | [
{
"code": null,
"e": 24221,
"s": 24193,
"text": "\n07 Feb, 2020"
},
{
"code": null,
"e": 24527,
"s": 24221,
"text": "Django Template Engine provides filters which are used to transform the values of variables;es and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify value of a variable whereas filters can be used for incrementing value of a variable or modifying it to one’s own need."
},
{
"code": null,
"e": 24561,
"s": 24527,
"text": "{{ variable_name | filter_name }}"
},
{
"code": null,
"e": 24752,
"s": 24561,
"text": "Filters can be “chained.” The output of one filter is applied to the next. {{ text|escape|linebreaks }} is a common idiom for escaping text contents, then converting line breaks to <p> tags."
},
{
"code": null,
"e": 24773,
"s": 24752,
"text": "{{ value | length }}"
},
{
"code": null,
"e": 24829,
"s": 24773,
"text": "If value is [‘a’, ‘b’, ‘c’, ‘d’], the output will be 4."
},
{
"code": null,
"e": 25013,
"s": 24829,
"text": "This article revolves around various Django Template Filters one can use during a project. Filters transform the values of variables and tag arguments. Let’s check some major filters."
},
{
"code": null,
"e": 30833,
"s": 25013,
"text": "addIt is used to add an argument to the value.Example{{ value | add:\"2\" }}If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates.addslashesIt is used to add slashes before quotes. Useful for escaping strings in CSV.Example{{ value | addslashes }}If value is “I’m Jai”, the output will be “I\\’m Jai”.capfirstIt is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.Example{{ value | capfirst }}If value is “jai”, the output will be “Jai”.centerIt is used to center the value in a field of a given width.Example\"{{ value | center:\"15\" }}\"If value is “Jai”, the output will be ” Jai “.cutIt is used to remove all values of arg from the given string.Example{{ value | cut:\" \" }}If value is “String with spaces”, the output will be “Stringwithspaces”.dateIt is used to format a date according to the given format.Example{{ value | date:\"D d M Y\" }}If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here.defaultIt is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself.Example{{ value | default:\"nothing\" }}If value is “” (the empty string), the output will be nothing.dictsortIt takes a list of dictionaries and returns that list sorted by the key given in the argument.Example{{ value | dictsort:\"name\" }}If value is:[\n {'name': 'zed', 'age': 19},\n {'name': 'amy', 'age': 22},\n {'name': 'joe', 'age': 31},\n]then the output would be:[\n {'name': 'amy', 'age': 22},\n {'name': 'joe', 'age': 31},\n {'name': 'zed', 'age': 19},\n] divisiblebyIt returns True if the value is divisible by the argument.Example{{ value | divisibleby:\"3\" }}If value is 21, the output would be True.escapeIt is used to escapea a string’s HTML. Specifically, it makes these replacements:< is converted to <> is converted to >' (single quote) is converted to '\" (double quote) is converted to \"& is converted to &Example{{ title | escape }}filesizeformatIt is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).Example{{ value | filesizeformat }}If value is 123456789, the output would be 117.7 MB.firstIt is used to return the first item in a list.Example{{ value | first }}If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’.joinIt is used to join a list with a string, like Python’s str.join(list)Example{{ value | join:\" // \" }}If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”.lastIt is used to return the last item in a list.Example{{ value | last }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”.lengthIt is used to return the length of the value. This works for both strings and lists.Example{{ value | length }}If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4.linenumbersIt is used to display text with line numbers.Example{{ value | linenumbers }}If value is:one\ntwo\nthreethe output will be:1. one\n2. two\n3. threelowerIt is used to converts a string into all lowercase.Example{{ value | lower }}}If value is My Name is Jai, the output will be my name is jai.make_listIt is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.Example{{ value | make_list }}If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’].randomIt is used to return a random item from the given list.Example{{ value | random }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”.sliceIt is used to return a slice of the list.Example{{ some_list | slice:\":2\" }}If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’].slugifyIt is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.Example{{ value | slugify }}If value is “Jai is a slug”, the output will be “jai-is-a-slug”.timeIt is used to format a time according to the given format.Example{{ value | time:\"H:i\" }}If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”.timesinceIt is used to format a date as the time since that date (e.g., “4 days, 6 hours”).Example{{ blog_date | timesince:comment_date }}if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”titleIt is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase.Example{{ value | title }}If value is “my FIRST post”, the output will be “My First Post”.unordered_listIt is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.Example{{ var | unordered_list }}if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:<li>States<ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li></ul></li> </li>upperIt is used to convert a string into all uppercase.Example{{ value | upper }}If value is “Jai is a slug”, the output will be “JAI IS A SLUG”.wordcountIt is used to return the number of words.Example{{ value | wordcount }}If value is “jai is a slug”, the output will be 4."
},
{
"code": null,
"e": 31014,
"s": 30833,
"text": "addIt is used to add an argument to the value.Example{{ value | add:\"2\" }}If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates."
},
{
"code": null,
"e": 31065,
"s": 31014,
"text": "It is used to add an argument to the value.Example"
},
{
"code": null,
"e": 31087,
"s": 31065,
"text": "{{ value | add:\"2\" }}"
},
{
"code": null,
"e": 31194,
"s": 31087,
"text": "If value is 4, then the output will be 6. This filter is used to increment a variable in django Templates."
},
{
"code": null,
"e": 31365,
"s": 31194,
"text": "addslashesIt is used to add slashes before quotes. Useful for escaping strings in CSV.Example{{ value | addslashes }}If value is “I’m Jai”, the output will be “I\\’m Jai”."
},
{
"code": null,
"e": 31449,
"s": 31365,
"text": "It is used to add slashes before quotes. Useful for escaping strings in CSV.Example"
},
{
"code": null,
"e": 31474,
"s": 31449,
"text": "{{ value | addslashes }}"
},
{
"code": null,
"e": 31528,
"s": 31474,
"text": "If value is “I’m Jai”, the output will be “I\\’m Jai”."
},
{
"code": null,
"e": 31735,
"s": 31528,
"text": "capfirstIt is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.Example{{ value | capfirst }}If value is “jai”, the output will be “Jai”."
},
{
"code": null,
"e": 31868,
"s": 31735,
"text": "It is used to capitalize the first character of the value. If the first character is not a letter, this filter has no effect.Example"
},
{
"code": null,
"e": 31891,
"s": 31868,
"text": "{{ value | capfirst }}"
},
{
"code": null,
"e": 31936,
"s": 31891,
"text": "If value is “jai”, the output will be “Jai”."
},
{
"code": null,
"e": 32082,
"s": 31936,
"text": "centerIt is used to center the value in a field of a given width.Example\"{{ value | center:\"15\" }}\"If value is “Jai”, the output will be ” Jai “."
},
{
"code": null,
"e": 32149,
"s": 32082,
"text": "It is used to center the value in a field of a given width.Example"
},
{
"code": null,
"e": 32177,
"s": 32149,
"text": "\"{{ value | center:\"15\" }}\""
},
{
"code": null,
"e": 32224,
"s": 32177,
"text": "If value is “Jai”, the output will be ” Jai “."
},
{
"code": null,
"e": 32389,
"s": 32224,
"text": "cutIt is used to remove all values of arg from the given string.Example{{ value | cut:\" \" }}If value is “String with spaces”, the output will be “Stringwithspaces”."
},
{
"code": null,
"e": 32451,
"s": 32389,
"text": "It is used to remove all values of arg from the given string."
},
{
"code": null,
"e": 32459,
"s": 32451,
"text": "Example"
},
{
"code": null,
"e": 32481,
"s": 32459,
"text": "{{ value | cut:\" \" }}"
},
{
"code": null,
"e": 32554,
"s": 32481,
"text": "If value is “String with spaces”, the output will be “Stringwithspaces”."
},
{
"code": null,
"e": 32823,
"s": 32554,
"text": "dateIt is used to format a date according to the given format.Example{{ value | date:\"D d M Y\" }}If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here."
},
{
"code": null,
"e": 32889,
"s": 32823,
"text": "It is used to format a date according to the given format.Example"
},
{
"code": null,
"e": 32918,
"s": 32889,
"text": "{{ value | date:\"D d M Y\" }}"
},
{
"code": null,
"e": 33090,
"s": 32918,
"text": "If value is a datetime object (e.g., the result of datetime.datetime.now()), the output will be the string ‘Thu 06 Feb 2020’. For More information and patterns visit here."
},
{
"code": null,
"e": 33353,
"s": 33090,
"text": "defaultIt is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself.Example{{ value | default:\"nothing\" }}If value is “” (the empty string), the output will be nothing."
},
{
"code": null,
"e": 33509,
"s": 33353,
"text": "It is used to to give a default value to a variable. If variable evaluates to False, it will use the default argument given else the variable value itself."
},
{
"code": null,
"e": 33517,
"s": 33509,
"text": "Example"
},
{
"code": null,
"e": 33549,
"s": 33517,
"text": "{{ value | default:\"nothing\" }}"
},
{
"code": null,
"e": 33612,
"s": 33549,
"text": "If value is “” (the empty string), the output will be nothing."
},
{
"code": null,
"e": 33987,
"s": 33612,
"text": "dictsortIt takes a list of dictionaries and returns that list sorted by the key given in the argument.Example{{ value | dictsort:\"name\" }}If value is:[\n {'name': 'zed', 'age': 19},\n {'name': 'amy', 'age': 22},\n {'name': 'joe', 'age': 31},\n]then the output would be:[\n {'name': 'amy', 'age': 22},\n {'name': 'joe', 'age': 31},\n {'name': 'zed', 'age': 19},\n] "
},
{
"code": null,
"e": 34089,
"s": 33987,
"text": "It takes a list of dictionaries and returns that list sorted by the key given in the argument.Example"
},
{
"code": null,
"e": 34119,
"s": 34089,
"text": "{{ value | dictsort:\"name\" }}"
},
{
"code": null,
"e": 34132,
"s": 34119,
"text": "If value is:"
},
{
"code": null,
"e": 34232,
"s": 34132,
"text": "[\n {'name': 'zed', 'age': 19},\n {'name': 'amy', 'age': 22},\n {'name': 'joe', 'age': 31},\n]"
},
{
"code": null,
"e": 34258,
"s": 34232,
"text": "then the output would be:"
},
{
"code": null,
"e": 34359,
"s": 34258,
"text": "[\n {'name': 'amy', 'age': 22},\n {'name': 'joe', 'age': 31},\n {'name': 'zed', 'age': 19},\n] "
},
{
"code": null,
"e": 34506,
"s": 34359,
"text": "divisiblebyIt returns True if the value is divisible by the argument.Example{{ value | divisibleby:\"3\" }}If value is 21, the output would be True."
},
{
"code": null,
"e": 34572,
"s": 34506,
"text": "It returns True if the value is divisible by the argument.Example"
},
{
"code": null,
"e": 34602,
"s": 34572,
"text": "{{ value | divisibleby:\"3\" }}"
},
{
"code": null,
"e": 34644,
"s": 34602,
"text": "If value is 21, the output would be True."
},
{
"code": null,
"e": 34884,
"s": 34644,
"text": "escapeIt is used to escapea a string’s HTML. Specifically, it makes these replacements:< is converted to <> is converted to >' (single quote) is converted to '\" (double quote) is converted to \"& is converted to &Example{{ title | escape }}"
},
{
"code": null,
"e": 34966,
"s": 34884,
"text": "It is used to escapea a string’s HTML. Specifically, it makes these replacements:"
},
{
"code": "< is converted to <> is converted to >' (single quote) is converted to '\" (double quote) is converted to \"& is converted to &",
"e": 35092,
"s": 34966,
"text": null
},
{
"code": null,
"e": 35100,
"s": 35092,
"text": "Example"
},
{
"code": null,
"e": 35121,
"s": 35100,
"text": "{{ title | escape }}"
},
{
"code": null,
"e": 35332,
"s": 35121,
"text": "filesizeformatIt is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).Example{{ value | filesizeformat }}If value is 123456789, the output would be 117.7 MB."
},
{
"code": null,
"e": 35449,
"s": 35332,
"text": "It is used to format the value like a ‘human-readable’ file size (i.e. ’13 KB’, ‘4.1 MB’, ‘102 bytes’, etc.).Example"
},
{
"code": null,
"e": 35478,
"s": 35449,
"text": "{{ value | filesizeformat }}"
},
{
"code": null,
"e": 35531,
"s": 35478,
"text": "If value is 123456789, the output would be 117.7 MB."
},
{
"code": null,
"e": 35670,
"s": 35531,
"text": "firstIt is used to return the first item in a list.Example{{ value | first }}If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’."
},
{
"code": null,
"e": 35724,
"s": 35670,
"text": "It is used to return the first item in a list.Example"
},
{
"code": null,
"e": 35744,
"s": 35724,
"text": "{{ value | first }}"
},
{
"code": null,
"e": 35806,
"s": 35744,
"text": "If value is the list [‘a’, ‘b’, ‘c’], the output will be ‘a’."
},
{
"code": null,
"e": 35994,
"s": 35806,
"text": "joinIt is used to join a list with a string, like Python’s str.join(list)Example{{ value | join:\" // \" }}If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”."
},
{
"code": null,
"e": 36071,
"s": 35994,
"text": "It is used to join a list with a string, like Python’s str.join(list)Example"
},
{
"code": null,
"e": 36097,
"s": 36071,
"text": "{{ value | join:\" // \" }}"
},
{
"code": null,
"e": 36180,
"s": 36097,
"text": "If value is the list [‘a’, ‘b’, ‘c’], the output will be the string “a // b // c”."
},
{
"code": null,
"e": 36332,
"s": 36180,
"text": "lastIt is used to return the last item in a list.Example{{ value | last }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”."
},
{
"code": null,
"e": 36385,
"s": 36332,
"text": "It is used to return the last item in a list.Example"
},
{
"code": null,
"e": 36404,
"s": 36385,
"text": "{{ value | last }}"
},
{
"code": null,
"e": 36482,
"s": 36404,
"text": "If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output will be the string “d”."
},
{
"code": null,
"e": 36665,
"s": 36482,
"text": "lengthIt is used to return the length of the value. This works for both strings and lists.Example{{ value | length }}If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4."
},
{
"code": null,
"e": 36757,
"s": 36665,
"text": "It is used to return the length of the value. This works for both strings and lists.Example"
},
{
"code": null,
"e": 36778,
"s": 36757,
"text": "{{ value | length }}"
},
{
"code": null,
"e": 36844,
"s": 36778,
"text": "If value is [‘a’, ‘b’, ‘c’, ‘d’] or “abcd”, the output will be 4."
},
{
"code": null,
"e": 36999,
"s": 36844,
"text": "linenumbersIt is used to display text with line numbers.Example{{ value | linenumbers }}If value is:one\ntwo\nthreethe output will be:1. one\n2. two\n3. three"
},
{
"code": null,
"e": 37052,
"s": 36999,
"text": "It is used to display text with line numbers.Example"
},
{
"code": null,
"e": 37078,
"s": 37052,
"text": "{{ value | linenumbers }}"
},
{
"code": null,
"e": 37091,
"s": 37078,
"text": "If value is:"
},
{
"code": null,
"e": 37105,
"s": 37091,
"text": "one\ntwo\nthree"
},
{
"code": null,
"e": 37125,
"s": 37105,
"text": "the output will be:"
},
{
"code": null,
"e": 37148,
"s": 37125,
"text": "1. one\n2. two\n3. three"
},
{
"code": null,
"e": 37294,
"s": 37148,
"text": "lowerIt is used to converts a string into all lowercase.Example{{ value | lower }}}If value is My Name is Jai, the output will be my name is jai."
},
{
"code": null,
"e": 37353,
"s": 37294,
"text": "It is used to converts a string into all lowercase.Example"
},
{
"code": null,
"e": 37374,
"s": 37353,
"text": "{{ value | lower }}}"
},
{
"code": null,
"e": 37437,
"s": 37374,
"text": "If value is My Name is Jai, the output will be my name is jai."
},
{
"code": null,
"e": 37796,
"s": 37437,
"text": "make_listIt is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.Example{{ value | make_list }}If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’]."
},
{
"code": null,
"e": 37968,
"s": 37796,
"text": "It is used to return the value turned into a list. For a string, it’s a list of characters. For an integer, the argument is cast to a string before creating a list.Example"
},
{
"code": null,
"e": 37992,
"s": 37968,
"text": "{{ value | make_list }}"
},
{
"code": null,
"e": 38148,
"s": 37992,
"text": "If value is the string “Naveen”, the output would be the list [‘N’, ‘a’, ‘v’, ‘e’, ‘e’, ‘n’]. If value is 123, the output will be the list [‘1’, ‘2’, ‘3’]."
},
{
"code": null,
"e": 38304,
"s": 38148,
"text": "randomIt is used to return a random item from the given list.Example{{ value | random }}If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”."
},
{
"code": null,
"e": 38367,
"s": 38304,
"text": "It is used to return a random item from the given list.Example"
},
{
"code": null,
"e": 38388,
"s": 38367,
"text": "{{ value | random }}"
},
{
"code": null,
"e": 38456,
"s": 38388,
"text": "If value is the list [‘a’, ‘b’, ‘c’, ‘d’], the output could be “b”."
},
{
"code": null,
"e": 38601,
"s": 38456,
"text": "sliceIt is used to return a slice of the list.Example{{ some_list | slice:\":2\" }}If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’]."
},
{
"code": null,
"e": 38650,
"s": 38601,
"text": "It is used to return a slice of the list.Example"
},
{
"code": null,
"e": 38679,
"s": 38650,
"text": "{{ some_list | slice:\":2\" }}"
},
{
"code": null,
"e": 38743,
"s": 38679,
"text": "If some_list is [‘a’, ‘b’, ‘c’], the output will be [‘a’, ‘b’]."
},
{
"code": null,
"e": 39047,
"s": 38743,
"text": "slugifyIt is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.Example{{ value | slugify }}If value is “Jai is a slug”, the output will be “jai-is-a-slug”."
},
{
"code": null,
"e": 39259,
"s": 39047,
"text": "It is used to convert to ASCII. It converts spaces to hyphens and removes characters that aren’t alphanumerics, underscores, or hyphens. Converts to lowercase. Also strips leading and trailing whitespace.Example"
},
{
"code": null,
"e": 39281,
"s": 39259,
"text": "{{ value | slugify }}"
},
{
"code": null,
"e": 39346,
"s": 39281,
"text": "If value is “Jai is a slug”, the output will be “jai-is-a-slug”."
},
{
"code": null,
"e": 39529,
"s": 39346,
"text": "timeIt is used to format a time according to the given format.Example{{ value | time:\"H:i\" }}If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”."
},
{
"code": null,
"e": 39595,
"s": 39529,
"text": "It is used to format a time according to the given format.Example"
},
{
"code": null,
"e": 39620,
"s": 39595,
"text": "{{ value | time:\"H:i\" }}"
},
{
"code": null,
"e": 39710,
"s": 39620,
"text": "If value is equivalent to datetime.datetime.now(), the output will be the string “01:23”."
},
{
"code": null,
"e": 40022,
"s": 39710,
"text": "timesinceIt is used to format a date as the time since that date (e.g., “4 days, 6 hours”).Example{{ blog_date | timesince:comment_date }}if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”"
},
{
"code": null,
"e": 40105,
"s": 40022,
"text": "It is used to format a date as the time since that date (e.g., “4 days, 6 hours”)."
},
{
"code": null,
"e": 40113,
"s": 40105,
"text": "Example"
},
{
"code": null,
"e": 40154,
"s": 40113,
"text": "{{ blog_date | timesince:comment_date }}"
},
{
"code": null,
"e": 40328,
"s": 40154,
"text": "if blog_date is a date instance representing midnight on 1 June 2006, and comment_date is a date instance for 08:00 on 1 June 2006, then the following would return “8 hours”"
},
{
"code": null,
"e": 40625,
"s": 40328,
"text": "titleIt is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase.Example{{ value | title }}If value is “my FIRST post”, the output will be “My First Post”."
},
{
"code": null,
"e": 40827,
"s": 40625,
"text": "It is used to convert a string into titlecase by making words start with an uppercase character and the remaining characters lowercase. This filter makes no effort to keep “trivial words” in lowercase."
},
{
"code": null,
"e": 40835,
"s": 40827,
"text": "Example"
},
{
"code": null,
"e": 40855,
"s": 40835,
"text": "{{ value | title }}"
},
{
"code": null,
"e": 40920,
"s": 40855,
"text": "If value is “my FIRST post”, the output will be “My First Post”."
},
{
"code": null,
"e": 41395,
"s": 40920,
"text": "unordered_listIt is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.Example{{ var | unordered_list }}if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:<li>States<ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li></ul></li> </li>"
},
{
"code": null,
"e": 41528,
"s": 41395,
"text": "It is used to recursively take a self-nested list and returns an HTML unordered list – WITHOUT opening and closing <ul> tags.Example"
},
{
"code": null,
"e": 41555,
"s": 41528,
"text": "{{ var | unordered_list }}"
},
{
"code": null,
"e": 41675,
"s": 41555,
"text": "if var contains ['States', ['Kansas', ['Lawrence', 'Topeka'], 'Illinois']], then {{ var|unordered_list }} would return:"
},
{
"code": "<li>States<ul> <li>Kansas <ul> <li>Lawrence</li> <li>Topeka</li> </ul> </li> <li>Illinois</li></ul></li> </li>",
"e": 41859,
"s": 41675,
"text": null
},
{
"code": null,
"e": 42005,
"s": 41859,
"text": "upperIt is used to convert a string into all uppercase.Example{{ value | upper }}If value is “Jai is a slug”, the output will be “JAI IS A SLUG”."
},
{
"code": null,
"e": 42063,
"s": 42005,
"text": "It is used to convert a string into all uppercase.Example"
},
{
"code": null,
"e": 42083,
"s": 42063,
"text": "{{ value | upper }}"
},
{
"code": null,
"e": 42148,
"s": 42083,
"text": "If value is “Jai is a slug”, the output will be “JAI IS A SLUG”."
},
{
"code": null,
"e": 42279,
"s": 42148,
"text": "wordcountIt is used to return the number of words.Example{{ value | wordcount }}If value is “jai is a slug”, the output will be 4."
},
{
"code": null,
"e": 42328,
"s": 42279,
"text": "It is used to return the number of words.Example"
},
{
"code": null,
"e": 42352,
"s": 42328,
"text": "{{ value | wordcount }}"
},
{
"code": null,
"e": 42403,
"s": 42352,
"text": "If value is “jai is a slug”, the output will be 4."
},
{
"code": null,
"e": 42420,
"s": 42403,
"text": "Django-templates"
},
{
"code": null,
"e": 42434,
"s": 42420,
"text": "Python Django"
},
{
"code": null,
"e": 42441,
"s": 42434,
"text": "Python"
},
{
"code": null,
"e": 42539,
"s": 42441,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 42557,
"s": 42539,
"text": "Python Dictionary"
},
{
"code": null,
"e": 42592,
"s": 42557,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 42614,
"s": 42592,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 42646,
"s": 42614,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 42676,
"s": 42646,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 42718,
"s": 42676,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 42744,
"s": 42718,
"text": "Python String | replace()"
},
{
"code": null,
"e": 42781,
"s": 42744,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 42824,
"s": 42781,
"text": "Python program to convert a list to string"
}
] |
Accounting - Basic Concepts | The first two accounting concepts, namely, Business Entity Concept and Money Measurement Concept are the fundamental concepts of accounting. Let us go through each one of them briefly:
According to this concept, the business and the owner of the business are two different entities. In other words, I and my business are separate.
For example, Mr A starts a new business in the name and style of M/s Independent Trading Company and introduced a capital of Rs 2,000,000 in cash. It means the cash balance of M/s Independent Trading Company will increase by a sum of Rs 2,000,000/-. At the same time, the liability of M/s Independent Trading Company in the form of capital will also increase. It means M/s Independent Trading Company is liable to pay Rs 2,000,000 to Mr A.
According to this concept, “we can book only those transactions in our accounting record which can be measured in monetary terms.”
Determine and book the value of stock of the following items:
Shirts Rs 5,000/-
Pants Rs 7,500/-
Coats 500 pieces
Jackets 1000 pieces
Value of Stock = ?
Here, if we want to book the value of stock in our accounting record, we need the value of coats and jackets in terms of money. Now if we conclude that the values of coats and jackets are Rs 2,000 and Rs 15,000 respectively, then we can easily book the value of stock as Rs 29,500 (as a result of 5000+7500+2000+15000) in our books. We need to keep quantitative records separately.
Our accounting is based on the assumption that a business unit is a going concern. We record all the financial transaction of a business in keeping this point of view in our mind that a business unit is a going concern; not a gone concern. Otherwise, the banker will not provide loans, the supplier will not supply goods or services, the employees will not work properly, and the method of recording the transaction will change altogether.
For example, a business unit makes investments in the form of fixed assets and we book only depreciation of the assets in our profit & loss account; not the difference of acquisition cost of assets less net realizable value of the assets. The reason is simple; we assume that we will use these assets and earn profit in the future while using them. Similarly, we treat deferred revenue expenditure and prepaid expenditure. The concept of going concern does not work in the following cases:
If a unit is declared sick (unused or unusable unit).
When a company is going to liquidate and a liquidator is appointed for the same.
When a business unit is passing through severe financial crisis and going to wind up.
It is a very important concept based on the Going Concern Concept. We book the value of assets on the cost basis, not on the net realizable value or market value of the assets based on the assumption that a business unit is a going concern. No doubt, we reduce the value of assets providing depreciation to assets, but we ignore the market value of the assets.
The cost concept stops any kind of manipulation while taking into account the net realizable value or the market value. On the downside, this concept ignores the effect of inflation in the market, which can sometimes be very steep. Still, the cost concept is widely and universally accepted on the basis of which we do the accounting of a business unit.
There must be a double entry to complete any financial transaction, means debit should be always equal to credit. Hence, every financial transaction has its dual aspect:
we get some benefit, and
we pay some benefit.
For example, if we buy some stock, then it will have two effects:
the value of stock will increase (get benefit for the same amount), and
it will increase our liability in the form of creditors.
Stock will increase by Rs 25,000 (Increase in debit balance)
Cash will decrease by Rs 25,000 (Decrease in debit balance)
or
Creditor will increase by Rs 25,000 (Increase in credit balance)
The life of a business unit is indefinite as per the going concern concept. To determine the profit or loss of a firm, and to ascertain its financial position, profit & loss accounts and balance sheets are prepared at regular intervals of time, usually at the end of each year. This one-year cycle is known as the accounting period. The purpose of having an accounting period is to take corrective measures keeping in view the past performances, to nullify the effect of seasonal changes, to pay taxes, etc.
Based on this concept, revenue expenditure and capital expenditure are segregated. Revenues expenditure are debited to the profit & loss account to ascertain correct profit or loss during a particular accounting period. Capital expenditure comes in the category of those expenses, the benefit of which will be utilized in the next coming accounting periods as well.
Accounting period helps us ascertain correct position of the firm at regular intervals of time, i.e., at the end of each accounting period.
Matching concept is based on the accounting period concept. The expenditures of a firm for a particular accounting period are to be matched with the revenue of the same accounting period to ascertain accurate profit or loss of the firm for the same period. This practice of matching is widely accepted all over the world. Let us take an example to understand the Matching Concept clearly.
The following data is received from M/s Globe Enterprises during the period 01-04-2012 to 31-03-2013:
Based on the above data, the profit or loss of the firm is calculated as follows:
In the above example, to match expenditures and revenues during the same accounting period, we added the credit purchase as well as the outstanding expenses of this accounting year to ascertain the correct profit for the accounting period 01-04-2012 to 31-03-2013.
It means the collection of cash and payment in cash is ignored while calculating the profit or loss of the year.
As stated above in the matching concept, the revenue generated in the accounting period is considered and the expenditure related to the accounting period is also considered. Based on the accrual concept of accounting, if we sell some items or we rendered some service, then that becomes our point of revenue generation irrespective of whether we received cash or not. The same concept is applicable in case of expenses. All the expenses paid in cash or payable are considered and the advance payment of expenses, if any, is deducted.
Most of the professionals use cash basis of accounting. It means, the cash received in a particular accounting period and the expenses paid cash in the same accounting period is the basis of their accounting. For them, the income of their firm depends upon the collection of revenue in cash. Similar practice is followed for expenditures. It is convenient for them and on the same basis, they pay their Taxes.
According to the Objective Evidence concept, every financial entry should be supported by some objective evidence. Purchase should be supported by purchase bills, sale with sale bills, cash payment of expenditure with cash memos, and payment to creditors with cash receipts and bank statements. Similarly, stock should be checked by physical verification and the value of it should be verified with purchase bills. In the absence of these, the accounting result will not be trustworthy, chances of manipulation in accounting records will be high, and no one will be able to rely on such financial statements.
13 Lectures
2 hours
Manish Gupta
8 Lectures
1 hours
Blair Cook
15 Lectures
59 mins
Prashant Panchal
26 Lectures
2.5 hours
Ross Maynard
12 Lectures
1.5 hours
Dr. John McLellan
5 Lectures
50 mins
Dr. John McLellan
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2824,
"s": 2639,
"text": "The first two accounting concepts, namely, Business Entity Concept and Money Measurement Concept are the fundamental concepts of accounting. Let us go through each one of them briefly:"
},
{
"code": null,
"e": 2970,
"s": 2824,
"text": "According to this concept, the business and the owner of the business are two different entities. In other words, I and my business are separate."
},
{
"code": null,
"e": 3410,
"s": 2970,
"text": "For example, Mr A starts a new business in the name and style of M/s Independent Trading Company and introduced a capital of Rs 2,000,000 in cash. It means the cash balance of M/s Independent Trading Company will increase by a sum of Rs 2,000,000/-. At the same time, the liability of M/s Independent Trading Company in the form of capital will also increase. It means M/s Independent Trading Company is liable to pay Rs 2,000,000 to Mr A."
},
{
"code": null,
"e": 3541,
"s": 3410,
"text": "According to this concept, “we can book only those transactions in our accounting record which can be measured in monetary terms.”"
},
{
"code": null,
"e": 3603,
"s": 3541,
"text": "Determine and book the value of stock of the following items:"
},
{
"code": null,
"e": 3706,
"s": 3603,
"text": "Shirts Rs 5,000/-\nPants Rs 7,500/-\n\nCoats 500 pieces\nJackets 1000 pieces\n\nValue of Stock = ?\n"
},
{
"code": null,
"e": 4088,
"s": 3706,
"text": "Here, if we want to book the value of stock in our accounting record, we need the value of coats and jackets in terms of money. Now if we conclude that the values of coats and jackets are Rs 2,000 and Rs 15,000 respectively, then we can easily book the value of stock as Rs 29,500 (as a result of 5000+7500+2000+15000) in our books. We need to keep quantitative records separately."
},
{
"code": null,
"e": 4528,
"s": 4088,
"text": "Our accounting is based on the assumption that a business unit is a going concern. We record all the financial transaction of a business in keeping this point of view in our mind that a business unit is a going concern; not a gone concern. Otherwise, the banker will not provide loans, the supplier will not supply goods or services, the employees will not work properly, and the method of recording the transaction will change altogether."
},
{
"code": null,
"e": 5018,
"s": 4528,
"text": "For example, a business unit makes investments in the form of fixed assets and we book only depreciation of the assets in our profit & loss account; not the difference of acquisition cost of assets less net realizable value of the assets. The reason is simple; we assume that we will use these assets and earn profit in the future while using them. Similarly, we treat deferred revenue expenditure and prepaid expenditure. The concept of going concern does not work in the following cases:"
},
{
"code": null,
"e": 5072,
"s": 5018,
"text": "If a unit is declared sick (unused or unusable unit)."
},
{
"code": null,
"e": 5153,
"s": 5072,
"text": "When a company is going to liquidate and a liquidator is appointed for the same."
},
{
"code": null,
"e": 5239,
"s": 5153,
"text": "When a business unit is passing through severe financial crisis and going to wind up."
},
{
"code": null,
"e": 5600,
"s": 5239,
"text": "It is a very important concept based on the Going Concern Concept. We book the value of assets on the cost basis, not on the net realizable value or market value of the assets based on the assumption that a business unit is a going concern. No doubt, we reduce the value of assets providing depreciation to assets, but we ignore the market value of the assets."
},
{
"code": null,
"e": 5954,
"s": 5600,
"text": "The cost concept stops any kind of manipulation while taking into account the net realizable value or the market value. On the downside, this concept ignores the effect of inflation in the market, which can sometimes be very steep. Still, the cost concept is widely and universally accepted on the basis of which we do the accounting of a business unit."
},
{
"code": null,
"e": 6124,
"s": 5954,
"text": "There must be a double entry to complete any financial transaction, means debit should be always equal to credit. Hence, every financial transaction has its dual aspect:"
},
{
"code": null,
"e": 6149,
"s": 6124,
"text": "we get some benefit, and"
},
{
"code": null,
"e": 6170,
"s": 6149,
"text": "we pay some benefit."
},
{
"code": null,
"e": 6236,
"s": 6170,
"text": "For example, if we buy some stock, then it will have two effects:"
},
{
"code": null,
"e": 6308,
"s": 6236,
"text": "the value of stock will increase (get benefit for the same amount), and"
},
{
"code": null,
"e": 6365,
"s": 6308,
"text": "it will increase our liability in the form of creditors."
},
{
"code": null,
"e": 6426,
"s": 6365,
"text": "Stock will increase by Rs 25,000 (Increase in debit balance)"
},
{
"code": null,
"e": 6486,
"s": 6426,
"text": "Cash will decrease by Rs 25,000 (Decrease in debit balance)"
},
{
"code": null,
"e": 6489,
"s": 6486,
"text": "or"
},
{
"code": null,
"e": 6554,
"s": 6489,
"text": "Creditor will increase by Rs 25,000 (Increase in credit balance)"
},
{
"code": null,
"e": 7062,
"s": 6554,
"text": "The life of a business unit is indefinite as per the going concern concept. To determine the profit or loss of a firm, and to ascertain its financial position, profit & loss accounts and balance sheets are prepared at regular intervals of time, usually at the end of each year. This one-year cycle is known as the accounting period. The purpose of having an accounting period is to take corrective measures keeping in view the past performances, to nullify the effect of seasonal changes, to pay taxes, etc."
},
{
"code": null,
"e": 7428,
"s": 7062,
"text": "Based on this concept, revenue expenditure and capital expenditure are segregated. Revenues expenditure are debited to the profit & loss account to ascertain correct profit or loss during a particular accounting period. Capital expenditure comes in the category of those expenses, the benefit of which will be utilized in the next coming accounting periods as well."
},
{
"code": null,
"e": 7568,
"s": 7428,
"text": "Accounting period helps us ascertain correct position of the firm at regular intervals of time, i.e., at the end of each accounting period."
},
{
"code": null,
"e": 7957,
"s": 7568,
"text": "Matching concept is based on the accounting period concept. The expenditures of a firm for a particular accounting period are to be matched with the revenue of the same accounting period to ascertain accurate profit or loss of the firm for the same period. This practice of matching is widely accepted all over the world. Let us take an example to understand the Matching Concept clearly."
},
{
"code": null,
"e": 8059,
"s": 7957,
"text": "The following data is received from M/s Globe Enterprises during the period 01-04-2012 to 31-03-2013:"
},
{
"code": null,
"e": 8141,
"s": 8059,
"text": "Based on the above data, the profit or loss of the firm is calculated as follows:"
},
{
"code": null,
"e": 8406,
"s": 8141,
"text": "In the above example, to match expenditures and revenues during the same accounting period, we added the credit purchase as well as the outstanding expenses of this accounting year to ascertain the correct profit for the accounting period 01-04-2012 to 31-03-2013."
},
{
"code": null,
"e": 8519,
"s": 8406,
"text": "It means the collection of cash and payment in cash is ignored while calculating the profit or loss of the year."
},
{
"code": null,
"e": 9054,
"s": 8519,
"text": "As stated above in the matching concept, the revenue generated in the accounting period is considered and the expenditure related to the accounting period is also considered. Based on the accrual concept of accounting, if we sell some items or we rendered some service, then that becomes our point of revenue generation irrespective of whether we received cash or not. The same concept is applicable in case of expenses. All the expenses paid in cash or payable are considered and the advance payment of expenses, if any, is deducted."
},
{
"code": null,
"e": 9464,
"s": 9054,
"text": "Most of the professionals use cash basis of accounting. It means, the cash received in a particular accounting period and the expenses paid cash in the same accounting period is the basis of their accounting. For them, the income of their firm depends upon the collection of revenue in cash. Similar practice is followed for expenditures. It is convenient for them and on the same basis, they pay their Taxes."
},
{
"code": null,
"e": 10073,
"s": 9464,
"text": "According to the Objective Evidence concept, every financial entry should be supported by some objective evidence. Purchase should be supported by purchase bills, sale with sale bills, cash payment of expenditure with cash memos, and payment to creditors with cash receipts and bank statements. Similarly, stock should be checked by physical verification and the value of it should be verified with purchase bills. In the absence of these, the accounting result will not be trustworthy, chances of manipulation in accounting records will be high, and no one will be able to rely on such financial statements."
},
{
"code": null,
"e": 10106,
"s": 10073,
"text": "\n 13 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 10120,
"s": 10106,
"text": " Manish Gupta"
},
{
"code": null,
"e": 10152,
"s": 10120,
"text": "\n 8 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10164,
"s": 10152,
"text": " Blair Cook"
},
{
"code": null,
"e": 10196,
"s": 10164,
"text": "\n 15 Lectures \n 59 mins\n"
},
{
"code": null,
"e": 10214,
"s": 10196,
"text": " Prashant Panchal"
},
{
"code": null,
"e": 10249,
"s": 10214,
"text": "\n 26 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 10263,
"s": 10249,
"text": " Ross Maynard"
},
{
"code": null,
"e": 10298,
"s": 10263,
"text": "\n 12 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10317,
"s": 10298,
"text": " Dr. John McLellan"
},
{
"code": null,
"e": 10348,
"s": 10317,
"text": "\n 5 Lectures \n 50 mins\n"
},
{
"code": null,
"e": 10367,
"s": 10348,
"text": " Dr. John McLellan"
},
{
"code": null,
"e": 10374,
"s": 10367,
"text": " Print"
},
{
"code": null,
"e": 10385,
"s": 10374,
"text": " Add Notes"
}
] |
Applying a Function over an Object in R Programming - sapply() Function - GeeksforGeeks | 19 Jun, 2020
sapply() function in R Language takes list, vector or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of same length of original set.
Syntax: sapply(X, FUN)
Parameters:X: A vector or an objectFUN: Function applied to each element of x
Example 1:
# R program to illustrate# sapply function # Getting the value of Biochemical oxygen# demand data setBOD # Calling sapply() function which# will sum the data of each columns# of BODsapply(BOD, sum)
Output:
Time demand
1 1 8.3
2 2 10.3
3 3 19.0
4 4 16.0
5 5 15.6
6 7 19.8
Time demand
22 89
Example 2:
# R program to illustrate# sapply function # Initializing a listmylist <- list(c(1, 2, 3, 4), c(2, 4, 6, 8), c(1, 3, 5, 7)) # Calling the sapply() function which# will calculate mean of each vector elementssapply(mylist, mean)
Output:
[1] 2.5 5.0 4.0
R DataFrame-Function
R List-Function
R Matrix-Function
R Object-Function
R Vector-Function
R Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Replace specific values in column in R DataFrame ?
How to change Row Names of DataFrame in R ?
Filter data by multiple conditions in R using Dplyr
Change Color of Bars in Barchart using ggplot2 in R
Loops in R (for, while, repeat)
Printing Output of an R Program
How to Change Axis Scales in R Plots?
Group by function in R using Dplyr
How to Split Column Into Multiple Columns in R DataFrame?
K-Means Clustering in R Programming | [
{
"code": null,
"e": 24815,
"s": 24787,
"text": "\n19 Jun, 2020"
},
{
"code": null,
"e": 25029,
"s": 24815,
"text": "sapply() function in R Language takes list, vector or data frame as input and gives output in vector or matrix. It is useful for operations on list objects and returns a list object of same length of original set."
},
{
"code": null,
"e": 25052,
"s": 25029,
"text": "Syntax: sapply(X, FUN)"
},
{
"code": null,
"e": 25130,
"s": 25052,
"text": "Parameters:X: A vector or an objectFUN: Function applied to each element of x"
},
{
"code": null,
"e": 25141,
"s": 25130,
"text": "Example 1:"
},
{
"code": "# R program to illustrate# sapply function # Getting the value of Biochemical oxygen# demand data setBOD # Calling sapply() function which# will sum the data of each columns# of BODsapply(BOD, sum)",
"e": 25341,
"s": 25141,
"text": null
},
{
"code": null,
"e": 25349,
"s": 25341,
"text": "Output:"
},
{
"code": null,
"e": 25477,
"s": 25349,
"text": " Time demand\n1 1 8.3\n2 2 10.3\n3 3 19.0\n4 4 16.0\n5 5 15.6\n6 7 19.8\n Time demand \n 22 89\n"
},
{
"code": null,
"e": 25488,
"s": 25477,
"text": "Example 2:"
},
{
"code": "# R program to illustrate# sapply function # Initializing a listmylist <- list(c(1, 2, 3, 4), c(2, 4, 6, 8), c(1, 3, 5, 7)) # Calling the sapply() function which# will calculate mean of each vector elementssapply(mylist, mean)",
"e": 25717,
"s": 25488,
"text": null
},
{
"code": null,
"e": 25725,
"s": 25717,
"text": "Output:"
},
{
"code": null,
"e": 25742,
"s": 25725,
"text": "[1] 2.5 5.0 4.0\n"
},
{
"code": null,
"e": 25763,
"s": 25742,
"text": "R DataFrame-Function"
},
{
"code": null,
"e": 25779,
"s": 25763,
"text": "R List-Function"
},
{
"code": null,
"e": 25797,
"s": 25779,
"text": "R Matrix-Function"
},
{
"code": null,
"e": 25815,
"s": 25797,
"text": "R Object-Function"
},
{
"code": null,
"e": 25833,
"s": 25815,
"text": "R Vector-Function"
},
{
"code": null,
"e": 25844,
"s": 25833,
"text": "R Language"
},
{
"code": null,
"e": 25942,
"s": 25844,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25951,
"s": 25942,
"text": "Comments"
},
{
"code": null,
"e": 25964,
"s": 25951,
"text": "Old Comments"
},
{
"code": null,
"e": 26022,
"s": 25964,
"text": "How to Replace specific values in column in R DataFrame ?"
},
{
"code": null,
"e": 26066,
"s": 26022,
"text": "How to change Row Names of DataFrame in R ?"
},
{
"code": null,
"e": 26118,
"s": 26066,
"text": "Filter data by multiple conditions in R using Dplyr"
},
{
"code": null,
"e": 26170,
"s": 26118,
"text": "Change Color of Bars in Barchart using ggplot2 in R"
},
{
"code": null,
"e": 26202,
"s": 26170,
"text": "Loops in R (for, while, repeat)"
},
{
"code": null,
"e": 26234,
"s": 26202,
"text": "Printing Output of an R Program"
},
{
"code": null,
"e": 26272,
"s": 26234,
"text": "How to Change Axis Scales in R Plots?"
},
{
"code": null,
"e": 26307,
"s": 26272,
"text": "Group by function in R using Dplyr"
},
{
"code": null,
"e": 26365,
"s": 26307,
"text": "How to Split Column Into Multiple Columns in R DataFrame?"
}
] |
How we can copy Python modules from one system to another? | If you have your own Python modules you want to copy, you can simply copy them and run on other systems with Python installed. If you want to copy installed modules, the best way is to install the same version of Python on the second system. Then run
$ pip freeze > installed_modules.txt
on the first system to get a list of the installed modules in the installed_modules.txt file. Now copy this file over to second system. Now use pip to install these modules using:
$ pip install -r installed_modules.txt
This will install all modules that were installed on the first system. It is the best way as simply copy pasting from one system to the other can cause problems due to differences in OS, Architecture, versions, etc. | [
{
"code": null,
"e": 1313,
"s": 1062,
"text": "If you have your own Python modules you want to copy, you can simply copy them and run on other systems with Python installed. If you want to copy installed modules, the best way is to install the same version of Python on the second system. Then run"
},
{
"code": null,
"e": 1350,
"s": 1313,
"text": "$ pip freeze > installed_modules.txt"
},
{
"code": null,
"e": 1530,
"s": 1350,
"text": "on the first system to get a list of the installed modules in the installed_modules.txt file. Now copy this file over to second system. Now use pip to install these modules using:"
},
{
"code": null,
"e": 1569,
"s": 1530,
"text": "$ pip install -r installed_modules.txt"
},
{
"code": null,
"e": 1785,
"s": 1569,
"text": "This will install all modules that were installed on the first system. It is the best way as simply copy pasting from one system to the other can cause problems due to differences in OS, Architecture, versions, etc."
}
] |
C# Switch | Use the switch statement to select one of many code blocks to be executed.
switch(expression)
{
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
break;
}
This is how it works:
The switch expression is evaluated once
The value of the expression is compared with the values of each case
If there is a match, the associated block of code is executed
The break and default keywords will be described later in this chapter
The example below uses the weekday number to calculate the weekday name:
int day = 4;
switch (day)
{
case 1:
Console.WriteLine("Monday");
break;
case 2:
Console.WriteLine("Tuesday");
break;
case 3:
Console.WriteLine("Wednesday");
break;
case 4:
Console.WriteLine("Thursday");
break;
case 5:
Console.WriteLine("Friday");
break;
case 6:
Console.WriteLine("Saturday");
break;
case 7:
Console.WriteLine("Sunday");
break;
}
// Outputs "Thursday" (day 4)
Try it Yourself »
When C# reaches a break
keyword, it breaks out of the switch block.
This will stop the execution of more code and case testing inside
the block.
When a match is found, and the job is done, it's time for a break. There is no need for more testing.
A break can save a lot of execution time because it "ignores" the execution
of all the rest of the code in the switch block.
The default keyword is optional and specifies some code to run if there is no
case match:
int day = 4;
switch (day)
{
case 6:
Console.WriteLine("Today is Saturday.");
break;
case 7:
Console.WriteLine("Today is Sunday.");
break;
default:
Console.WriteLine("Looking forward to the Weekend.");
break;
}
// Outputs "Looking forward to the Weekend."
Try it Yourself »
Insert the missing parts to complete the following switch statement.
int day = 2;
switch ()
{
1:
Console.WriteLine("Monday");
break;
2:
Console.WriteLine("Tuesday");
;
}
Start the Exercise
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 75,
"s": 0,
"text": "Use the switch statement to select one of many code blocks to be executed."
},
{
"code": null,
"e": 218,
"s": 75,
"text": "switch(expression) \n{\n case x:\n // code block\n break;\n case y:\n // code block\n break;\n default:\n // code block\n break;\n}\n"
},
{
"code": null,
"e": 240,
"s": 218,
"text": "This is how it works:"
},
{
"code": null,
"e": 280,
"s": 240,
"text": "The switch expression is evaluated once"
},
{
"code": null,
"e": 349,
"s": 280,
"text": "The value of the expression is compared with the values of each case"
},
{
"code": null,
"e": 411,
"s": 349,
"text": "If there is a match, the associated block of code is executed"
},
{
"code": null,
"e": 482,
"s": 411,
"text": "The break and default keywords will be described later in this chapter"
},
{
"code": null,
"e": 555,
"s": 482,
"text": "The example below uses the weekday number to calculate the weekday name:"
},
{
"code": null,
"e": 1003,
"s": 555,
"text": "int day = 4;\nswitch (day) \n{\n case 1:\n Console.WriteLine(\"Monday\");\n break;\n case 2:\n Console.WriteLine(\"Tuesday\");\n break;\n case 3:\n Console.WriteLine(\"Wednesday\");\n break;\n case 4:\n Console.WriteLine(\"Thursday\");\n break;\n case 5:\n Console.WriteLine(\"Friday\");\n break;\n case 6:\n Console.WriteLine(\"Saturday\");\n break;\n case 7:\n Console.WriteLine(\"Sunday\");\n break;\n}\n// Outputs \"Thursday\" (day 4)\n"
},
{
"code": null,
"e": 1023,
"s": 1003,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1092,
"s": 1023,
"text": "When C# reaches a break \nkeyword, it breaks out of the switch block."
},
{
"code": null,
"e": 1170,
"s": 1092,
"text": "This will stop the execution of more code and case testing inside \nthe block."
},
{
"code": null,
"e": 1272,
"s": 1170,
"text": "When a match is found, and the job is done, it's time for a break. There is no need for more testing."
},
{
"code": null,
"e": 1398,
"s": 1272,
"text": "A break can save a lot of execution time because it \"ignores\" the execution \nof all the rest of the code in the switch block."
},
{
"code": null,
"e": 1489,
"s": 1398,
"text": "The default keyword is optional and specifies some code to run if there is no \ncase match:"
},
{
"code": null,
"e": 1778,
"s": 1489,
"text": "int day = 4;\nswitch (day) \n{\n case 6:\n Console.WriteLine(\"Today is Saturday.\");\n break;\n case 7:\n Console.WriteLine(\"Today is Sunday.\");\n break;\n default:\n Console.WriteLine(\"Looking forward to the Weekend.\");\n break;\n}\n// Outputs \"Looking forward to the Weekend.\"\n \n"
},
{
"code": null,
"e": 1798,
"s": 1778,
"text": "\nTry it Yourself »\n"
},
{
"code": null,
"e": 1867,
"s": 1798,
"text": "Insert the missing parts to complete the following switch statement."
},
{
"code": null,
"e": 1992,
"s": 1867,
"text": "int day = 2;\nswitch () \n{\n 1:\n Console.WriteLine(\"Monday\");\n break;\n 2:\n Console.WriteLine(\"Tuesday\");\n ;\n}\n"
},
{
"code": null,
"e": 2011,
"s": 1992,
"text": "Start the Exercise"
},
{
"code": null,
"e": 2044,
"s": 2011,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 2086,
"s": 2044,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2193,
"s": 2086,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2212,
"s": 2193,
"text": "[email protected]"
}
] |
Powershell - Read-Host Cmdlet | Read-Host cmdlet is used to read from the console.
In these example, we're see the Read-Host cmdlet in action.
In this example, we'll ask the user to pass an input and read the input into a variable.
$choice = Read-Host "Please put your choice"
Powershell will show a popup to enter the value. Once you enter the value, it is saved in $choice variable. Now print the variable.
$choice
You can see the value of variable.
1
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2085,
"s": 2034,
"text": "Read-Host cmdlet is used to read from the console."
},
{
"code": null,
"e": 2145,
"s": 2085,
"text": "In these example, we're see the Read-Host cmdlet in action."
},
{
"code": null,
"e": 2234,
"s": 2145,
"text": "In this example, we'll ask the user to pass an input and read the input into a variable."
},
{
"code": null,
"e": 2279,
"s": 2234,
"text": "$choice = Read-Host \"Please put your choice\""
},
{
"code": null,
"e": 2411,
"s": 2279,
"text": "Powershell will show a popup to enter the value. Once you enter the value, it is saved in $choice variable. Now print the variable."
},
{
"code": null,
"e": 2419,
"s": 2411,
"text": "$choice"
},
{
"code": null,
"e": 2454,
"s": 2419,
"text": "You can see the value of variable."
},
{
"code": null,
"e": 2457,
"s": 2454,
"text": "1\n"
},
{
"code": null,
"e": 2492,
"s": 2457,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2513,
"s": 2492,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2548,
"s": 2513,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2561,
"s": 2548,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2598,
"s": 2561,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2610,
"s": 2598,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2617,
"s": 2610,
"text": " Print"
},
{
"code": null,
"e": 2628,
"s": 2617,
"text": " Add Notes"
}
] |
Java Examples - Matching Phone Numbers | How to match phone numbers in a list?
Following example shows how to match phone numbers in a list to a particle pattern by using phone.matches(phoneNumberPattern) method.
public class MatchPhoneNumber {
public static void main(String args[]) {
isPhoneValid("1-999-585-4009");
isPhoneValid("999-585-4009");
isPhoneValid("1-585-4009");
isPhoneValid("585-4009");
isPhoneValid("1.999-585-4009");
isPhoneValid("999 585-4009");
isPhoneValid("1 585 4009");
isPhoneValid("111-Java2s");
}
public static boolean isPhoneValid(String phone) {
boolean retval = false;
String phoneNumberPattern = "(\\d-)?(\\d{3}-)?\\d{3}-\\d{4}";
retval = phone.matches(phoneNumberPattern);
String msg = "NO MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern;
if (retval) {
msg = " MATCH: pattern:" + phone + "\r\n regex: " + phoneNumberPattern;
}
System.out.println(msg + "\r\n");
return retval;
}
}
The above code sample will produce the following result.
MATCH: pattern:1-999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
MATCH: pattern:999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
MATCH: pattern:1-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:1.999-585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:999 585-4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:1 585 4009
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
NOMATCH: pattern:111-Java2s
regex: (\\d-)?(\\d{3}-)?\\d{3}-\\d{4}
The following is an example to verify phone number.
public class Main {
private static boolean isValid(String s) {
String regex = "\\d{2}-\\d{4}-\\d{6}";
return s.matches(regex);
}
public static void main(String[] args) {
System.out.println(isValid("91-9652-018244"));
}
}
The above code sample will produce the following result.
true
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2106,
"s": 2068,
"text": "How to match phone numbers in a list?"
},
{
"code": null,
"e": 2240,
"s": 2106,
"text": "Following example shows how to match phone numbers in a list to a particle pattern by using phone.matches(phoneNumberPattern) method."
},
{
"code": null,
"e": 3076,
"s": 2240,
"text": "public class MatchPhoneNumber {\n public static void main(String args[]) {\n isPhoneValid(\"1-999-585-4009\");\n isPhoneValid(\"999-585-4009\");\n isPhoneValid(\"1-585-4009\");\n isPhoneValid(\"585-4009\");\n isPhoneValid(\"1.999-585-4009\");\n isPhoneValid(\"999 585-4009\");\n isPhoneValid(\"1 585 4009\");\n isPhoneValid(\"111-Java2s\");\n }\n public static boolean isPhoneValid(String phone) {\n boolean retval = false;\n String phoneNumberPattern = \"(\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\";\n retval = phone.matches(phoneNumberPattern);\n String msg = \"NO MATCH: pattern:\" + phone + \"\\r\\n regex: \" + phoneNumberPattern;\n \n if (retval) {\n msg = \" MATCH: pattern:\" + phone + \"\\r\\n regex: \" + phoneNumberPattern;\n }\n System.out.println(msg + \"\\r\\n\");\n return retval;\n }\n}"
},
{
"code": null,
"e": 3133,
"s": 3076,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3621,
"s": 3133,
"text": "MATCH: pattern:1-999-585-4009\n\t regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\nMATCH: pattern:999-585-4009\n\t regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\nMATCH: pattern:1-585-4009\n\t regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\nNOMATCH: pattern:1.999-585-4009\n regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\nNOMATCH: pattern:999 585-4009\n regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\nNOMATCH: pattern:1 585 4009\n regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\nNOMATCH: pattern:111-Java2s\n regex: (\\\\d-)?(\\\\d{3}-)?\\\\d{3}-\\\\d{4}\n"
},
{
"code": null,
"e": 3673,
"s": 3621,
"text": "The following is an example to verify phone number."
},
{
"code": null,
"e": 3928,
"s": 3673,
"text": "public class Main { \n private static boolean isValid(String s) {\n String regex = \"\\\\d{2}-\\\\d{4}-\\\\d{6}\"; \n return s.matches(regex);\n } \n public static void main(String[] args) {\n System.out.println(isValid(\"91-9652-018244\"));\n } \n}"
},
{
"code": null,
"e": 3985,
"s": 3928,
"text": "The above code sample will produce the following result."
},
{
"code": null,
"e": 3991,
"s": 3985,
"text": "true\n"
},
{
"code": null,
"e": 3998,
"s": 3991,
"text": " Print"
},
{
"code": null,
"e": 4009,
"s": 3998,
"text": " Add Notes"
}
] |
Precision Handling in Java | Let us see how precisions are handled in Java −
Live Demo
import java.io.*;
import java.lang.*;
public class Demo{
public static void main(String[] args){
double my_val = 34.909;
System.out.println("The formatted value of 34.909 is ");
System.out.println(String.format("%.7f", my_val));
double my_val_2 = 12.56;
System.out.println("The formatted value of 12.56 is ");
System.out.println(String.format("%.9f", my_val_2));
}
}
The formatted value of 34.909 is
34.9090000
The formatted value of 12.56 is
12.560000000
A class named Demo contains the main function, where a double valued integer is declared, and it is
formatted by specifying the number that it should be formatted to. Similarly, another double
variable is defined, and formatted and printed on the screen. | [
{
"code": null,
"e": 1110,
"s": 1062,
"text": "Let us see how precisions are handled in Java −"
},
{
"code": null,
"e": 1121,
"s": 1110,
"text": " Live Demo"
},
{
"code": null,
"e": 1530,
"s": 1121,
"text": "import java.io.*;\nimport java.lang.*;\npublic class Demo{\n public static void main(String[] args){\n double my_val = 34.909;\n System.out.println(\"The formatted value of 34.909 is \");\n System.out.println(String.format(\"%.7f\", my_val));\n double my_val_2 = 12.56;\n System.out.println(\"The formatted value of 12.56 is \");\n System.out.println(String.format(\"%.9f\", my_val_2));\n }\n}"
},
{
"code": null,
"e": 1619,
"s": 1530,
"text": "The formatted value of 34.909 is\n34.9090000\nThe formatted value of 12.56 is\n12.560000000"
},
{
"code": null,
"e": 1874,
"s": 1619,
"text": "A class named Demo contains the main function, where a double valued integer is declared, and it is\nformatted by specifying the number that it should be formatted to. Similarly, another double\nvariable is defined, and formatted and printed on the screen."
}
] |
Unit Testing for C# Code | Unit testing is a key for C# code since it can help in maintaining code in the development process. It lets you know about the problems in the development cycle.
With Unit Testing, you can make the code reliable and reusable.
One of the fundamental principles of adopting unit testing is to follow a TDD (Test Driven Development) approach where we have to write tests case first, and then write the simple code that will make the test pass
For Unit testing, you need to work with Microsoft Testing tools, which is what we call MS Unit Test.
To create a Unit Test, go to Solution Explorer, right-click, go to New and click “New Project”.
Now select “Unit Test Project” −
Set a name for the Test and click Ok.
New Unit Test project is created.
Now right click on the new unit test and add the following reference −
Microsoft.VisualStudio.QualityTools.UnitTestFramework | [
{
"code": null,
"e": 1349,
"s": 1187,
"text": "Unit testing is a key for C# code since it can help in maintaining code in the development process. It lets you know about the problems in the development cycle."
},
{
"code": null,
"e": 1413,
"s": 1349,
"text": "With Unit Testing, you can make the code reliable and reusable."
},
{
"code": null,
"e": 1627,
"s": 1413,
"text": "One of the fundamental principles of adopting unit testing is to follow a TDD (Test Driven Development) approach where we have to write tests case first, and then write the simple code that will make the test pass"
},
{
"code": null,
"e": 1728,
"s": 1627,
"text": "For Unit testing, you need to work with Microsoft Testing tools, which is what we call MS Unit Test."
},
{
"code": null,
"e": 1824,
"s": 1728,
"text": "To create a Unit Test, go to Solution Explorer, right-click, go to New and click “New Project”."
},
{
"code": null,
"e": 1858,
"s": 1824,
"text": "Now select “Unit Test Project” − "
},
{
"code": null,
"e": 1896,
"s": 1858,
"text": "Set a name for the Test and click Ok."
},
{
"code": null,
"e": 1930,
"s": 1896,
"text": "New Unit Test project is created."
},
{
"code": null,
"e": 2002,
"s": 1930,
"text": "Now right click on the new unit test and add the following reference − "
},
{
"code": null,
"e": 2057,
"s": 2002,
"text": "Microsoft.VisualStudio.QualityTools.UnitTestFramework\n"
}
] |
How to Scrape Data From Local HTML Files using Python? | 21 Apr, 2021
BeautifulSoup module in Python allows us to scrape data from local HTML files. For some reason, website pages might get stored in a local (offline environment), and whenever in need, there may be requirements to get the data from them. Sometimes there may be a need to get data from multiple Locally stored HTML files too. Usually HTML files got the tags like <h1>, <h2>,...<p>, <div> tags etc., Using BeautifulSoup, we can scrap the contents and get the necessary details.
It can be installed by typing the below command in the terminal.
pip install beautifulsoup4
If there is an HTML file stored in one location, and we need to scrap the content via Python using BeautifulSoup, the lxml is a great API as it meant for parsing XML and HTML. It supports both one-step parsing and step-by-step parsing.
The Prettify() function in BeautifulSoup helps to view the tag nature and their nesting.
Example: Let’s create a sample HTML file.
Python3
# Necessary importsimport sysimport urllib.request # Save a reference to the original# standard outputoriginal_stdout = sys.stdout # as an example, taken my article list# published link page and stored in localwith urllib.request.urlopen('https://auth.geeksforgeeks.org/user/priyarajtt/articles') as webPageResponse: outputHtml = webPageResponse.read() # Scraped contents are placed in # samplehtml.html file and getting# used for next set of exampleswith open('samplehtml.html', 'w') as f: # Here the standard output is # written to the file that we # used above sys.stdout = f print(outputHtml) # Reset the standard output to its # original value sys.stdout = original_stdout
Output:
Now, use prettify() method to view tags and content in an easier way.
Python3
# Importing BeautifulSoup and # it is in the bs4 modulefrom bs4 import BeautifulSoup # Opening the html file. If the file# is present in different location, # exact location need to be mentionedHTMLFileToBeOpened = open("samplehtml.html", "r") # Reading the file and storing in a variablecontents = HTMLFileToBeOpened.read() # Creating a BeautifulSoup object and# specifying the parser beautifulSoupText = BeautifulSoup(contents, 'lxml') # Using the prettify method to modify the code# Prettify() function in BeautifulSoup helps# to view about the tag nature and their nestingprint(beautifulSoupText.body.prettify())
Output :
In this way can get HTML data. Now do some operations and some insightful in the data.
Example 1:
We can use find() methods and as HTML contents dynamically change, we may not be knowing the exact tag name. In that time, we can use findAll(True) to get the tag name first, and then we can do any kind of manipulation. For example, get the tag name and length of the tag
Python3
# Importing BeautifulSoup and it# is in the bs4 modulefrom bs4 import BeautifulSoup # Opening the html file. If the file# is present in different location, # exact location need to be mentionedHTMLFileToBeOpened = open("samplehtml.html", "r") # Reading the file and storing in a variablecontents = HTMLFileToBeOpened.read() # Creating a BeautifulSoup object and # specifying the parserbeautifulSoupText = BeautifulSoup(contents, 'lxml') # To get all the tags present in the html # and getting their lengthfor tag in beautifulSoupText.findAll(True): print(tag.name, " : ", len(beautifulSoupText.find(tag.name).text))
Output:
Example 2 :
Now, instead of scraping one HTML file, we want to do for all the HTML files present in that directory(there may be necessities for such cases as on daily basis, a particular directory may get filled with the online data and as a batch process, scraping has to be carried out).
We can use “os” module functionalities. Let us take the current directory all HTML files for our examples
So our task is to get all HTML files to get scrapped. In the below way, we can achieve. Entire folder HTML files got scraped one by one and their length of tags for all files are retrieved, and it is showcased in the attached video.
Python3
# necessary import for getting# directory and filenamesimport osfrom bs4 import BeautifulSoup # Get current working directorydirectory = os.getcwd() # for all the files present in that# directoryfor filename in os.listdir(directory): # check whether the file is having # the extension as html and it can # be done with endswith function if filename.endswith('.html'): # os.path.join() method in Python join # one or more path components which helps # to exactly get the file fname = os.path.join(directory, filename) print("Current file name ..", os.path.abspath(fname)) # open the file with open(fname, 'r') as file: beautifulSoupText = BeautifulSoup(file.read(), 'html.parser') # parse the html as you wish for tag in beautifulSoupText.findAll(True): print(tag.name, " : ", len(beautifulSoupText.find(tag.name).text))
Output:
Picked
Python BeautifulSoup
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python | os.path.join() method
Introduction To PYTHON
Python OOPs Concepts
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Create a directory in Python | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n21 Apr, 2021"
},
{
"code": null,
"e": 503,
"s": 28,
"text": "BeautifulSoup module in Python allows us to scrape data from local HTML files. For some reason, website pages might get stored in a local (offline environment), and whenever in need, there may be requirements to get the data from them. Sometimes there may be a need to get data from multiple Locally stored HTML files too. Usually HTML files got the tags like <h1>, <h2>,...<p>, <div> tags etc., Using BeautifulSoup, we can scrap the contents and get the necessary details. "
},
{
"code": null,
"e": 568,
"s": 503,
"text": "It can be installed by typing the below command in the terminal."
},
{
"code": null,
"e": 595,
"s": 568,
"text": "pip install beautifulsoup4"
},
{
"code": null,
"e": 832,
"s": 595,
"text": "If there is an HTML file stored in one location, and we need to scrap the content via Python using BeautifulSoup, the lxml is a great API as it meant for parsing XML and HTML. It supports both one-step parsing and step-by-step parsing. "
},
{
"code": null,
"e": 922,
"s": 832,
"text": "The Prettify() function in BeautifulSoup helps to view the tag nature and their nesting. "
},
{
"code": null,
"e": 964,
"s": 922,
"text": "Example: Let’s create a sample HTML file."
},
{
"code": null,
"e": 972,
"s": 964,
"text": "Python3"
},
{
"code": "# Necessary importsimport sysimport urllib.request # Save a reference to the original# standard outputoriginal_stdout = sys.stdout # as an example, taken my article list# published link page and stored in localwith urllib.request.urlopen('https://auth.geeksforgeeks.org/user/priyarajtt/articles') as webPageResponse: outputHtml = webPageResponse.read() # Scraped contents are placed in # samplehtml.html file and getting# used for next set of exampleswith open('samplehtml.html', 'w') as f: # Here the standard output is # written to the file that we # used above sys.stdout = f print(outputHtml) # Reset the standard output to its # original value sys.stdout = original_stdout",
"e": 1696,
"s": 972,
"text": null
},
{
"code": null,
"e": 1704,
"s": 1696,
"text": "Output:"
},
{
"code": null,
"e": 1774,
"s": 1704,
"text": "Now, use prettify() method to view tags and content in an easier way."
},
{
"code": null,
"e": 1782,
"s": 1774,
"text": "Python3"
},
{
"code": "# Importing BeautifulSoup and # it is in the bs4 modulefrom bs4 import BeautifulSoup # Opening the html file. If the file# is present in different location, # exact location need to be mentionedHTMLFileToBeOpened = open(\"samplehtml.html\", \"r\") # Reading the file and storing in a variablecontents = HTMLFileToBeOpened.read() # Creating a BeautifulSoup object and# specifying the parser beautifulSoupText = BeautifulSoup(contents, 'lxml') # Using the prettify method to modify the code# Prettify() function in BeautifulSoup helps# to view about the tag nature and their nestingprint(beautifulSoupText.body.prettify())",
"e": 2406,
"s": 1782,
"text": null
},
{
"code": null,
"e": 2416,
"s": 2406,
"text": "Output : "
},
{
"code": null,
"e": 2503,
"s": 2416,
"text": "In this way can get HTML data. Now do some operations and some insightful in the data."
},
{
"code": null,
"e": 2514,
"s": 2503,
"text": "Example 1:"
},
{
"code": null,
"e": 2786,
"s": 2514,
"text": "We can use find() methods and as HTML contents dynamically change, we may not be knowing the exact tag name. In that time, we can use findAll(True) to get the tag name first, and then we can do any kind of manipulation. For example, get the tag name and length of the tag"
},
{
"code": null,
"e": 2794,
"s": 2786,
"text": "Python3"
},
{
"code": "# Importing BeautifulSoup and it# is in the bs4 modulefrom bs4 import BeautifulSoup # Opening the html file. If the file# is present in different location, # exact location need to be mentionedHTMLFileToBeOpened = open(\"samplehtml.html\", \"r\") # Reading the file and storing in a variablecontents = HTMLFileToBeOpened.read() # Creating a BeautifulSoup object and # specifying the parserbeautifulSoupText = BeautifulSoup(contents, 'lxml') # To get all the tags present in the html # and getting their lengthfor tag in beautifulSoupText.findAll(True): print(tag.name, \" : \", len(beautifulSoupText.find(tag.name).text))",
"e": 3417,
"s": 2794,
"text": null
},
{
"code": null,
"e": 3425,
"s": 3417,
"text": "Output:"
},
{
"code": null,
"e": 3437,
"s": 3425,
"text": "Example 2 :"
},
{
"code": null,
"e": 3715,
"s": 3437,
"text": "Now, instead of scraping one HTML file, we want to do for all the HTML files present in that directory(there may be necessities for such cases as on daily basis, a particular directory may get filled with the online data and as a batch process, scraping has to be carried out)."
},
{
"code": null,
"e": 3821,
"s": 3715,
"text": "We can use “os” module functionalities. Let us take the current directory all HTML files for our examples"
},
{
"code": null,
"e": 4054,
"s": 3821,
"text": "So our task is to get all HTML files to get scrapped. In the below way, we can achieve. Entire folder HTML files got scraped one by one and their length of tags for all files are retrieved, and it is showcased in the attached video."
},
{
"code": null,
"e": 4062,
"s": 4054,
"text": "Python3"
},
{
"code": "# necessary import for getting# directory and filenamesimport osfrom bs4 import BeautifulSoup # Get current working directorydirectory = os.getcwd() # for all the files present in that# directoryfor filename in os.listdir(directory): # check whether the file is having # the extension as html and it can # be done with endswith function if filename.endswith('.html'): # os.path.join() method in Python join # one or more path components which helps # to exactly get the file fname = os.path.join(directory, filename) print(\"Current file name ..\", os.path.abspath(fname)) # open the file with open(fname, 'r') as file: beautifulSoupText = BeautifulSoup(file.read(), 'html.parser') # parse the html as you wish for tag in beautifulSoupText.findAll(True): print(tag.name, \" : \", len(beautifulSoupText.find(tag.name).text))",
"e": 5045,
"s": 4062,
"text": null
},
{
"code": null,
"e": 5054,
"s": 5045,
"text": "Output: "
},
{
"code": null,
"e": 5061,
"s": 5054,
"text": "Picked"
},
{
"code": null,
"e": 5082,
"s": 5061,
"text": "Python BeautifulSoup"
},
{
"code": null,
"e": 5089,
"s": 5082,
"text": "Python"
},
{
"code": null,
"e": 5187,
"s": 5089,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5219,
"s": 5187,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5246,
"s": 5219,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5277,
"s": 5246,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 5300,
"s": 5277,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 5321,
"s": 5300,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 5377,
"s": 5321,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 5419,
"s": 5377,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 5461,
"s": 5419,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 5500,
"s": 5461,
"text": "Python | Get unique values from a list"
}
] |
Pytest Plugins to Love ❤️. My top 5 and honorable 50 out of 600+... | by Martin Thoma | Towards Data Science | Pytest is extensible and has plenty of plugins. You don’t need to use any of them, but you might find some very useful. I love this because you have an easy time to get started with unit testing, while still finding amazing stuff when you’re more experienced 🤩
In this article, I’ll show you examples of plugins I use and the plugins I found while writing this article. You might want to cover the basics of unit testing first or refresh testing details like fixtures.
All plugins presented in this article can be installed via pip . Most of them are then already active. For example, when you install pytest-sugar via
pip install pytest-sugar
You can just execute pytest and the plugin will automatically work. Others need to be used more directly. For example, after installing pytest-timeout you need to specify the timeout parameter you want to use:
pytest --timeout=1
Don’t worry, I will explain those two plugins later 🙂
Searching on pypi.org for the trove classifier Framework :: Pytest , I found 668 packages. A stunning 1053 packages have “pytest” in the name. 461 packages have both, the name and the trove classifier.
I went through over 700 pytest-plugins for this article. I’ve jumped over plugins that consider themselves to be in planning, pre-alpha, or alpha stage. I’ve also skipped packages where I’ve seen a TODO in the readme or if the package had less than 10 stars on GitHub.
The packages I’ve found make pytest sparkle ✨, improve the speed 🏎, are specialized to specific packages, or just unique in their behavior ❄️
Last but not least, there are some plugins where I’m not sure if they are awesome or if they are a bad idea. Let’s jump right into it and have a look yourself!
Side note: Maybe you remember my side note on typo squatting? I found a fixable issue on PyPI while writing this article, hopefully improving security for the community🎉
The default output of pytest is already good, but some plugins make it amazing. pytest-sugar is one of those plugins❤
If those dots or checkmarks are too decent for you, givepytest-emoji and pytest-emoji-out a try 😃
The summary output now looks good, but the diffs between the expected value and the actual value can be improved. pytest-icdiff is a plugin I’ve only found while researching this article — and it was love at first sight 🥰❤
Very similar is pytest-clarity — be aware, that pytest-clarity is only active when you execute pytest -vv:
Once you're happy with the terminal output, you might think about getting reports in the browser. This could help once you have to have a look at many things, want to scroll and search. Then pytest-html is your friend. It generates reports like this one:
Now that we are happy with the output, we want to make it lightning fast!
Plugins can speed things up. For example, you can make pytest fail instantly with pytest-instafail instead of executing all remaining tests. For tests which might take a long time or even result in an infinite loop in case of errors, I use pytest-timeout ❤. That is especially helpful when you apply Mutation testing.
We also want to use our machine properly by using pytest-xdist . Install it, execute pytest -n autoand your tests run in parallel!pytest-parallelmight also be worth a shot.
The most extreme speedup is not to execute stuff you don’t need. pytest-picked executes tests that are related to unstaged files which can be way less than your complete test suite.
Going in a different direction, we want to make sure that the algorithms have some speed behavior. With pytest-benchmark , we can use the benchmark fixture to annotate parts of a test which we want to benchmark:
def test_argmax(benchmark): assert benchmark(mpu.math.argmax, [1, 2, 3]) == 2
Running pytest then also gives this output, where you can see three functions to which I’ve added a benchmark. Two of them test a factorization function. It should not be a surprise that factorizing 3072 takes longer than factorizing 1024, but it is always astonishing to me how quickly the numbers grow. The argmax of 3 examples is super quick, but factorization just needs way more computation:
Some plugins are unique and don’t fit in any of the other categories:
pytest-cov : Get a test coverage report 😍 ❤ I like to generate both, an HTML report and an output to the terminal. In some settings, an XML report is also helpful.
pytest-socket : Make certain that you don’t query anything non-local. Very nice ❤
pytest-randomly and pytest-rng: If you use random.random , then the outcome depends on the random seed. This plugin changes the seed.
pytest-random-order : Execute the tests in a random order, to make sure you see when a test leaves the system in a different state.
pytest-lazy-fixtures : Use fixtures in @pytest.mark.parametrize .
pytest-freezegun : Freeze time! This is one I’ve also mentioned in my patching article.
pytest-leaks : Find resource leaks. This requires a debug-built of Python!
pytest-flake8 : Run flake8 via pytest. I did that for a long time, but when I learned how to use Continuous Integration pipelines more effectively, I stopped it. You can still execute flake8 directly.
pytest-mypy and pytest-mccabe: Same story as for flake8. By the way, type annotations are awesome! I like to have those static code analysis tools in a linter step within the CI pipeline.
pytest-deadfixtures : Point out which fixtures are not used or duplicated.
The following plugins are only interesting to you if you work with the applications for which they are written. They usually provide fixtures/mocks.
pytest-cookie : Supports testing of cookiecutter templates.
pytest-plt and pytest-mpl: Provides fixtures for matplotlib.
pytest-responses : Provides fixtures for requests .
pytest-asyncio : Use it when you develop async functions.
pytest-qt : GUI development via Qt / PySide / PySide2.
pytest-djangoapp / pytest-djangoqueries: Exposes tools for Django application developers to facilitate test authoring, including settings override, template tag testing, and user creation.
pytest-flask and pytest-flask-sqlalchemy : Provides fixtures for running tests in transactions using Flask-SQLAlchemy.
pytest-seleniumbase / pytest-sbase / pytest-selenium
moto : Mocks for boto3 — AWS stuff. I don’t exactly love this one, but it is for sure the best you can do when you want to test code that uses S3.
pytest-aws : Testing AWS resource configurations
pytest-localstack : Create AWS integration tests via a Localstack Docker container
The following plugins sounded cool for me when I first read about them, but for various reasons, I’m uncertain if they are really a good idea:
pytest-check : Allows multiple failures per test. At first, I loved the idea. Then I realized that this might lead to worse tests as the tests start to do many things. On the other hand, you might want to test a “workflow” once — so not a unit test, but an integration test or even an end-to-end test. But then you would also need intermediate results.
pytest-docker-tools and pytest-docker-compose: I would just build the Docker image and execute the stuff in it.
pytest-mock : Provides a mocker fixture which is a thin-wrapper around the patching API provided by the mock package. It reduces boilerplate code by making mock a fixture.
pytest-spec , pytest-pspec , and pytest-testdox modify the pytest output. They show what is tested. The tests should be written in such a way that they represent the software specification — so the test is against a part of the specification.
pytest-recording : It should record network interactions via VCR.py, but I didn’t get it to work.
pytest-dependency allows you to specify which tests need to succeed for others to be able to succeed. Unit tests should be independent and dependent code should be mocked...maybe. I’m not certain about that.
pytest is the tool of choice to run tests in Python. While it has reasonable defaults, it’s extensive plugin system lets you customize it to make it even better.
I love pytest-sugar and pytest-icdiff , because they make the output of pytest easier to read. pytest-cov generates line- and branch coverage and thus is a valuable tool to find spots that need better tests. The next step is to run the tests. You really don’t want to accidentally hit the production environment. This is wherepytest-socket comes into play. It just blocks everything and reports it to you. The other type of issue are long-running tests that are potentially in infinite loops.pytest-timeout kills those tests after the specified amount of time.
There are so many other plugins; many add fixtures for specific packages which are typically hard to test. You should now have a good idea of the many possibilities added by pytest plugins — use them!
In this series, we already had:
Part 1: The basics of Unit Testing in Python
Part 2: Patching, Mocks and Dependency Injection
Part 3: How to test Flask applications with Databases, Templates and Protected Pages
Part 4: tox and nox
Part 5: Structuring Unit Tests
Part 6: CI-Pipelines
Part 7: Property-based Testing
Part 8: Mutation Testing
Part 9: Static Code Analysis — Linters, Type Checking, and Code Complexity
Part 10: Pytest Plugins to Love
Let me know if you’re interested in other topics around testing with Python. | [
{
"code": null,
"e": 308,
"s": 47,
"text": "Pytest is extensible and has plenty of plugins. You don’t need to use any of them, but you might find some very useful. I love this because you have an easy time to get started with unit testing, while still finding amazing stuff when you’re more experienced 🤩"
},
{
"code": null,
"e": 516,
"s": 308,
"text": "In this article, I’ll show you examples of plugins I use and the plugins I found while writing this article. You might want to cover the basics of unit testing first or refresh testing details like fixtures."
},
{
"code": null,
"e": 666,
"s": 516,
"text": "All plugins presented in this article can be installed via pip . Most of them are then already active. For example, when you install pytest-sugar via"
},
{
"code": null,
"e": 691,
"s": 666,
"text": "pip install pytest-sugar"
},
{
"code": null,
"e": 901,
"s": 691,
"text": "You can just execute pytest and the plugin will automatically work. Others need to be used more directly. For example, after installing pytest-timeout you need to specify the timeout parameter you want to use:"
},
{
"code": null,
"e": 920,
"s": 901,
"text": "pytest --timeout=1"
},
{
"code": null,
"e": 974,
"s": 920,
"text": "Don’t worry, I will explain those two plugins later 🙂"
},
{
"code": null,
"e": 1176,
"s": 974,
"text": "Searching on pypi.org for the trove classifier Framework :: Pytest , I found 668 packages. A stunning 1053 packages have “pytest” in the name. 461 packages have both, the name and the trove classifier."
},
{
"code": null,
"e": 1445,
"s": 1176,
"text": "I went through over 700 pytest-plugins for this article. I’ve jumped over plugins that consider themselves to be in planning, pre-alpha, or alpha stage. I’ve also skipped packages where I’ve seen a TODO in the readme or if the package had less than 10 stars on GitHub."
},
{
"code": null,
"e": 1587,
"s": 1445,
"text": "The packages I’ve found make pytest sparkle ✨, improve the speed 🏎, are specialized to specific packages, or just unique in their behavior ❄️"
},
{
"code": null,
"e": 1747,
"s": 1587,
"text": "Last but not least, there are some plugins where I’m not sure if they are awesome or if they are a bad idea. Let’s jump right into it and have a look yourself!"
},
{
"code": null,
"e": 1917,
"s": 1747,
"text": "Side note: Maybe you remember my side note on typo squatting? I found a fixable issue on PyPI while writing this article, hopefully improving security for the community🎉"
},
{
"code": null,
"e": 2035,
"s": 1917,
"text": "The default output of pytest is already good, but some plugins make it amazing. pytest-sugar is one of those plugins❤"
},
{
"code": null,
"e": 2133,
"s": 2035,
"text": "If those dots or checkmarks are too decent for you, givepytest-emoji and pytest-emoji-out a try 😃"
},
{
"code": null,
"e": 2356,
"s": 2133,
"text": "The summary output now looks good, but the diffs between the expected value and the actual value can be improved. pytest-icdiff is a plugin I’ve only found while researching this article — and it was love at first sight 🥰❤"
},
{
"code": null,
"e": 2463,
"s": 2356,
"text": "Very similar is pytest-clarity — be aware, that pytest-clarity is only active when you execute pytest -vv:"
},
{
"code": null,
"e": 2718,
"s": 2463,
"text": "Once you're happy with the terminal output, you might think about getting reports in the browser. This could help once you have to have a look at many things, want to scroll and search. Then pytest-html is your friend. It generates reports like this one:"
},
{
"code": null,
"e": 2792,
"s": 2718,
"text": "Now that we are happy with the output, we want to make it lightning fast!"
},
{
"code": null,
"e": 3110,
"s": 2792,
"text": "Plugins can speed things up. For example, you can make pytest fail instantly with pytest-instafail instead of executing all remaining tests. For tests which might take a long time or even result in an infinite loop in case of errors, I use pytest-timeout ❤. That is especially helpful when you apply Mutation testing."
},
{
"code": null,
"e": 3283,
"s": 3110,
"text": "We also want to use our machine properly by using pytest-xdist . Install it, execute pytest -n autoand your tests run in parallel!pytest-parallelmight also be worth a shot."
},
{
"code": null,
"e": 3465,
"s": 3283,
"text": "The most extreme speedup is not to execute stuff you don’t need. pytest-picked executes tests that are related to unstaged files which can be way less than your complete test suite."
},
{
"code": null,
"e": 3677,
"s": 3465,
"text": "Going in a different direction, we want to make sure that the algorithms have some speed behavior. With pytest-benchmark , we can use the benchmark fixture to annotate parts of a test which we want to benchmark:"
},
{
"code": null,
"e": 3758,
"s": 3677,
"text": "def test_argmax(benchmark): assert benchmark(mpu.math.argmax, [1, 2, 3]) == 2"
},
{
"code": null,
"e": 4155,
"s": 3758,
"text": "Running pytest then also gives this output, where you can see three functions to which I’ve added a benchmark. Two of them test a factorization function. It should not be a surprise that factorizing 3072 takes longer than factorizing 1024, but it is always astonishing to me how quickly the numbers grow. The argmax of 3 examples is super quick, but factorization just needs way more computation:"
},
{
"code": null,
"e": 4225,
"s": 4155,
"text": "Some plugins are unique and don’t fit in any of the other categories:"
},
{
"code": null,
"e": 4389,
"s": 4225,
"text": "pytest-cov : Get a test coverage report 😍 ❤ I like to generate both, an HTML report and an output to the terminal. In some settings, an XML report is also helpful."
},
{
"code": null,
"e": 4471,
"s": 4389,
"text": "pytest-socket : Make certain that you don’t query anything non-local. Very nice ❤"
},
{
"code": null,
"e": 4605,
"s": 4471,
"text": "pytest-randomly and pytest-rng: If you use random.random , then the outcome depends on the random seed. This plugin changes the seed."
},
{
"code": null,
"e": 4737,
"s": 4605,
"text": "pytest-random-order : Execute the tests in a random order, to make sure you see when a test leaves the system in a different state."
},
{
"code": null,
"e": 4803,
"s": 4737,
"text": "pytest-lazy-fixtures : Use fixtures in @pytest.mark.parametrize ."
},
{
"code": null,
"e": 4891,
"s": 4803,
"text": "pytest-freezegun : Freeze time! This is one I’ve also mentioned in my patching article."
},
{
"code": null,
"e": 4966,
"s": 4891,
"text": "pytest-leaks : Find resource leaks. This requires a debug-built of Python!"
},
{
"code": null,
"e": 5167,
"s": 4966,
"text": "pytest-flake8 : Run flake8 via pytest. I did that for a long time, but when I learned how to use Continuous Integration pipelines more effectively, I stopped it. You can still execute flake8 directly."
},
{
"code": null,
"e": 5355,
"s": 5167,
"text": "pytest-mypy and pytest-mccabe: Same story as for flake8. By the way, type annotations are awesome! I like to have those static code analysis tools in a linter step within the CI pipeline."
},
{
"code": null,
"e": 5430,
"s": 5355,
"text": "pytest-deadfixtures : Point out which fixtures are not used or duplicated."
},
{
"code": null,
"e": 5579,
"s": 5430,
"text": "The following plugins are only interesting to you if you work with the applications for which they are written. They usually provide fixtures/mocks."
},
{
"code": null,
"e": 5639,
"s": 5579,
"text": "pytest-cookie : Supports testing of cookiecutter templates."
},
{
"code": null,
"e": 5700,
"s": 5639,
"text": "pytest-plt and pytest-mpl: Provides fixtures for matplotlib."
},
{
"code": null,
"e": 5752,
"s": 5700,
"text": "pytest-responses : Provides fixtures for requests ."
},
{
"code": null,
"e": 5810,
"s": 5752,
"text": "pytest-asyncio : Use it when you develop async functions."
},
{
"code": null,
"e": 5865,
"s": 5810,
"text": "pytest-qt : GUI development via Qt / PySide / PySide2."
},
{
"code": null,
"e": 6054,
"s": 5865,
"text": "pytest-djangoapp / pytest-djangoqueries: Exposes tools for Django application developers to facilitate test authoring, including settings override, template tag testing, and user creation."
},
{
"code": null,
"e": 6173,
"s": 6054,
"text": "pytest-flask and pytest-flask-sqlalchemy : Provides fixtures for running tests in transactions using Flask-SQLAlchemy."
},
{
"code": null,
"e": 6226,
"s": 6173,
"text": "pytest-seleniumbase / pytest-sbase / pytest-selenium"
},
{
"code": null,
"e": 6373,
"s": 6226,
"text": "moto : Mocks for boto3 — AWS stuff. I don’t exactly love this one, but it is for sure the best you can do when you want to test code that uses S3."
},
{
"code": null,
"e": 6422,
"s": 6373,
"text": "pytest-aws : Testing AWS resource configurations"
},
{
"code": null,
"e": 6505,
"s": 6422,
"text": "pytest-localstack : Create AWS integration tests via a Localstack Docker container"
},
{
"code": null,
"e": 6648,
"s": 6505,
"text": "The following plugins sounded cool for me when I first read about them, but for various reasons, I’m uncertain if they are really a good idea:"
},
{
"code": null,
"e": 7001,
"s": 6648,
"text": "pytest-check : Allows multiple failures per test. At first, I loved the idea. Then I realized that this might lead to worse tests as the tests start to do many things. On the other hand, you might want to test a “workflow” once — so not a unit test, but an integration test or even an end-to-end test. But then you would also need intermediate results."
},
{
"code": null,
"e": 7113,
"s": 7001,
"text": "pytest-docker-tools and pytest-docker-compose: I would just build the Docker image and execute the stuff in it."
},
{
"code": null,
"e": 7285,
"s": 7113,
"text": "pytest-mock : Provides a mocker fixture which is a thin-wrapper around the patching API provided by the mock package. It reduces boilerplate code by making mock a fixture."
},
{
"code": null,
"e": 7528,
"s": 7285,
"text": "pytest-spec , pytest-pspec , and pytest-testdox modify the pytest output. They show what is tested. The tests should be written in such a way that they represent the software specification — so the test is against a part of the specification."
},
{
"code": null,
"e": 7626,
"s": 7528,
"text": "pytest-recording : It should record network interactions via VCR.py, but I didn’t get it to work."
},
{
"code": null,
"e": 7834,
"s": 7626,
"text": "pytest-dependency allows you to specify which tests need to succeed for others to be able to succeed. Unit tests should be independent and dependent code should be mocked...maybe. I’m not certain about that."
},
{
"code": null,
"e": 7996,
"s": 7834,
"text": "pytest is the tool of choice to run tests in Python. While it has reasonable defaults, it’s extensive plugin system lets you customize it to make it even better."
},
{
"code": null,
"e": 8557,
"s": 7996,
"text": "I love pytest-sugar and pytest-icdiff , because they make the output of pytest easier to read. pytest-cov generates line- and branch coverage and thus is a valuable tool to find spots that need better tests. The next step is to run the tests. You really don’t want to accidentally hit the production environment. This is wherepytest-socket comes into play. It just blocks everything and reports it to you. The other type of issue are long-running tests that are potentially in infinite loops.pytest-timeout kills those tests after the specified amount of time."
},
{
"code": null,
"e": 8758,
"s": 8557,
"text": "There are so many other plugins; many add fixtures for specific packages which are typically hard to test. You should now have a good idea of the many possibilities added by pytest plugins — use them!"
},
{
"code": null,
"e": 8790,
"s": 8758,
"text": "In this series, we already had:"
},
{
"code": null,
"e": 8835,
"s": 8790,
"text": "Part 1: The basics of Unit Testing in Python"
},
{
"code": null,
"e": 8884,
"s": 8835,
"text": "Part 2: Patching, Mocks and Dependency Injection"
},
{
"code": null,
"e": 8969,
"s": 8884,
"text": "Part 3: How to test Flask applications with Databases, Templates and Protected Pages"
},
{
"code": null,
"e": 8989,
"s": 8969,
"text": "Part 4: tox and nox"
},
{
"code": null,
"e": 9020,
"s": 8989,
"text": "Part 5: Structuring Unit Tests"
},
{
"code": null,
"e": 9041,
"s": 9020,
"text": "Part 6: CI-Pipelines"
},
{
"code": null,
"e": 9072,
"s": 9041,
"text": "Part 7: Property-based Testing"
},
{
"code": null,
"e": 9097,
"s": 9072,
"text": "Part 8: Mutation Testing"
},
{
"code": null,
"e": 9172,
"s": 9097,
"text": "Part 9: Static Code Analysis — Linters, Type Checking, and Code Complexity"
},
{
"code": null,
"e": 9204,
"s": 9172,
"text": "Part 10: Pytest Plugins to Love"
}
] |
Wand splice() function - Python - GeeksforGeeks | 10 Aug, 2021
The splice() function is an inbuilt function in the Python Wand ImageMagick library which is used to partition the image by splicing a width x height rectangle at (x, y) offset coordinate. The space inserted will be replaced by the available background color.
Syntax:
splice(width, height, x, y)
Parameters: This function accepts four parameters as mentioned above and defined below:
width: This parameter stores the width of the rectangle.
height: This parameter stores the height of the rectangle.
x: This parameter stores the offset on the x-axis.
y: This parameter stores the offset on the y-axis.
Return Value: This function returns the Wand ImageMagick object.
Original Image:
Example 1:
Python3
# Import library from Image from wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as splice: # Invoke splice function with height as 20, width as 20, x as 10, y as 10 splice.splice(20, 20, 10, 10) # Save the image splice.save(filename ='splice1.jpg')
Output:
Example 2:
Python3
# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke splice function with height as 10, width as 10, x as 15, y as 20 pic.splice(10, 10, 15, 20) # Save the image pic.save(filename ='splice2.jpg')
Output:
sagar0719kumar
sagartomar9927
Image-Processing
Python-wand
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Create a Pandas DataFrame from Lists
Box Plot in Python using Matplotlib
Python Dictionary
Bar Plot in Matplotlib
Enumerate() in Python
Python | Get dictionary keys as a list
Python | Convert set into a list
Ways to filter Pandas DataFrame by column values
Graph Plotting in Python | Set 1
Python - Call function from another file | [
{
"code": null,
"e": 24591,
"s": 24563,
"text": "\n10 Aug, 2021"
},
{
"code": null,
"e": 24852,
"s": 24591,
"text": "The splice() function is an inbuilt function in the Python Wand ImageMagick library which is used to partition the image by splicing a width x height rectangle at (x, y) offset coordinate. The space inserted will be replaced by the available background color. "
},
{
"code": null,
"e": 24860,
"s": 24852,
"text": "Syntax:"
},
{
"code": null,
"e": 24888,
"s": 24860,
"text": "splice(width, height, x, y)"
},
{
"code": null,
"e": 24978,
"s": 24888,
"text": "Parameters: This function accepts four parameters as mentioned above and defined below: "
},
{
"code": null,
"e": 25035,
"s": 24978,
"text": "width: This parameter stores the width of the rectangle."
},
{
"code": null,
"e": 25094,
"s": 25035,
"text": "height: This parameter stores the height of the rectangle."
},
{
"code": null,
"e": 25145,
"s": 25094,
"text": "x: This parameter stores the offset on the x-axis."
},
{
"code": null,
"e": 25196,
"s": 25145,
"text": "y: This parameter stores the offset on the y-axis."
},
{
"code": null,
"e": 25261,
"s": 25196,
"text": "Return Value: This function returns the Wand ImageMagick object."
},
{
"code": null,
"e": 25277,
"s": 25261,
"text": "Original Image:"
},
{
"code": null,
"e": 25290,
"s": 25277,
"text": "Example 1: "
},
{
"code": null,
"e": 25298,
"s": 25290,
"text": "Python3"
},
{
"code": "# Import library from Image from wand.image import Image # Import the imagewith Image(filename ='../geeksforgeeks.png') as image: # Clone the image in order to process with image.clone() as splice: # Invoke splice function with height as 20, width as 20, x as 10, y as 10 splice.splice(20, 20, 10, 10) # Save the image splice.save(filename ='splice1.jpg')",
"e": 25689,
"s": 25298,
"text": null
},
{
"code": null,
"e": 25699,
"s": 25689,
"text": "Output: "
},
{
"code": null,
"e": 25712,
"s": 25699,
"text": "Example 2: "
},
{
"code": null,
"e": 25720,
"s": 25712,
"text": "Python3"
},
{
"code": "# Import libraries from the wand from wand.image import Imagefrom wand.drawing import Drawingfrom wand.color import Color with Drawing() as draw: # Set Stroke color the circle to black draw.stroke_color = Color('black') # Set Width of the circle to 2 draw.stroke_width = 1 # Set the fill color to 'White (# FFFFFF)' draw.fill_color = Color('white') # Invoke Circle function with center at 50, 50 and radius 25 draw.circle((200, 200), # Center point (100, 100)) # Perimeter point # Set the font style draw.font = '../Helvetica.ttf' # Set the font size draw.font_size = 30 with Image(width = 400, height = 400, background = Color('# 45ff33')) as pic: # Set the text and its location draw.text(int(pic.width / 3), int(pic.height / 2), 'GeeksForGeeks !') # Draw the picture draw(pic) # Invoke splice function with height as 10, width as 10, x as 15, y as 20 pic.splice(10, 10, 15, 20) # Save the image pic.save(filename ='splice2.jpg')",
"e": 26775,
"s": 25720,
"text": null
},
{
"code": null,
"e": 26785,
"s": 26775,
"text": "Output: "
},
{
"code": null,
"e": 26802,
"s": 26787,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 26817,
"s": 26802,
"text": "sagartomar9927"
},
{
"code": null,
"e": 26834,
"s": 26817,
"text": "Image-Processing"
},
{
"code": null,
"e": 26846,
"s": 26834,
"text": "Python-wand"
},
{
"code": null,
"e": 26853,
"s": 26846,
"text": "Python"
},
{
"code": null,
"e": 26951,
"s": 26853,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26960,
"s": 26951,
"text": "Comments"
},
{
"code": null,
"e": 26973,
"s": 26960,
"text": "Old Comments"
},
{
"code": null,
"e": 27010,
"s": 26973,
"text": "Create a Pandas DataFrame from Lists"
},
{
"code": null,
"e": 27046,
"s": 27010,
"text": "Box Plot in Python using Matplotlib"
},
{
"code": null,
"e": 27064,
"s": 27046,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27087,
"s": 27064,
"text": "Bar Plot in Matplotlib"
},
{
"code": null,
"e": 27109,
"s": 27087,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27148,
"s": 27109,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27181,
"s": 27148,
"text": "Python | Convert set into a list"
},
{
"code": null,
"e": 27230,
"s": 27181,
"text": "Ways to filter Pandas DataFrame by column values"
},
{
"code": null,
"e": 27263,
"s": 27230,
"text": "Graph Plotting in Python | Set 1"
}
] |
GATE | GATE-CS-2007 | Question 64 - GeeksforGeeks | 28 Jun, 2021
Consider the following schedules involving two transactions. Which one of the following statements is TRUE?
(A) Both S1 and S2 are conflict serializable.(B) S1 is conflict serializable and S2 is not conflict serializable.(C) S1 is not conflict serializable and S2 is conflict serializable.(D) Both S1 and S2 are not conflict serializable.Answer: (C)Explanation:
S1 is not conflict serializable, but S2 is conflict serializable
Schedule S1
T1 T2
---------------------
r1(X)
r1(Y)
r2(X)
r2(Y)
w2(Y)
w1(X)
The schedule is neither conflict equivalent to T1T2, nor T2T1.
Schedule S2
T1 T2
---------------------
r1(X)
r2(X)
r2(Y)
w2(Y)
r1(Y)
w1(X)
The schedule is conflict equivalent to T2T1.
Quiz of this Question
GATE-CS-2007
GATE-GATE-CS-2007
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
GATE | GATE-IT-2004 | Question 66
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-3) | Question 65
GATE | GATE CS 2010 | Question 24
GATE | GATE CS 2011 | Question 7
GATE | GATE-IT-2004 | Question 71
GATE | GATE-CS-2004 | Question 3
GATE | GATE CS 2019 | Question 27
GATE | GATE CS 2012 | Question 54
GATE | GATE-CS-2016 (Set 1) | Question 65 | [
{
"code": null,
"e": 24524,
"s": 24496,
"text": "\n28 Jun, 2021"
},
{
"code": null,
"e": 24632,
"s": 24524,
"text": "Consider the following schedules involving two transactions. Which one of the following statements is TRUE?"
},
{
"code": null,
"e": 24886,
"s": 24632,
"text": "(A) Both S1 and S2 are conflict serializable.(B) S1 is conflict serializable and S2 is not conflict serializable.(C) S1 is not conflict serializable and S2 is conflict serializable.(D) Both S1 and S2 are not conflict serializable.Answer: (C)Explanation:"
},
{
"code": null,
"e": 25351,
"s": 24886,
"text": "S1 is not conflict serializable, but S2 is conflict serializable \n\nSchedule S1\n T1 T2\n---------------------\n r1(X)\n r1(Y)\n r2(X)\n r2(Y)\n w2(Y)\n w1(X)\nThe schedule is neither conflict equivalent to T1T2, nor T2T1.\n\nSchedule S2\n T1 T2\n---------------------\n r1(X)\n r2(X)\n r2(Y)\n w2(Y)\n r1(Y)\n w1(X)\nThe schedule is conflict equivalent to T2T1.\n"
},
{
"code": null,
"e": 25373,
"s": 25351,
"text": "Quiz of this Question"
},
{
"code": null,
"e": 25386,
"s": 25373,
"text": "GATE-CS-2007"
},
{
"code": null,
"e": 25404,
"s": 25386,
"text": "GATE-GATE-CS-2007"
},
{
"code": null,
"e": 25409,
"s": 25404,
"text": "GATE"
},
{
"code": null,
"e": 25507,
"s": 25409,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25541,
"s": 25507,
"text": "GATE | GATE-IT-2004 | Question 66"
},
{
"code": null,
"e": 25583,
"s": 25541,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25625,
"s": 25583,
"text": "GATE | GATE-CS-2014-(Set-3) | Question 65"
},
{
"code": null,
"e": 25659,
"s": 25625,
"text": "GATE | GATE CS 2010 | Question 24"
},
{
"code": null,
"e": 25692,
"s": 25659,
"text": "GATE | GATE CS 2011 | Question 7"
},
{
"code": null,
"e": 25726,
"s": 25692,
"text": "GATE | GATE-IT-2004 | Question 71"
},
{
"code": null,
"e": 25759,
"s": 25726,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25793,
"s": 25759,
"text": "GATE | GATE CS 2019 | Question 27"
},
{
"code": null,
"e": 25827,
"s": 25793,
"text": "GATE | GATE CS 2012 | Question 54"
}
] |
What is a reentrant function in C/C++? | Here we will see what is the reentrant function in C or C++. One function is said to be a reentrant function if there is a provision to interrupt that function in the course of execution, then service the ISR (Interrupt Service Routine) and then resume the task. This type of functions is used in different cases like, recursions, hardware interrupt handling.
For a reentrant function there should be some properties. These are listed below −
This type of function will not use any global or static variable. There are no restrictions, but it is generally not advised. This is because the interrupt may change the values of global variable, so after coming back from ISR the function may get some new value, and results will be different.
This type of function will not use any global or static variable. There are no restrictions, but it is generally not advised. This is because the interrupt may change the values of global variable, so after coming back from ISR the function may get some new value, and results will be different.
The reentrant function should not modify its own code. We need the action of the function should remain same throughout the code.
The reentrant function should not modify its own code. We need the action of the function should remain same throughout the code.
Another property is the reentrant function should not call any other non-reentrant function.
Another property is the reentrant function should not call any other non-reentrant function.
int x;
int my_function() {
return x * 10;
}
int my_second_function() {
return my_function() * 20;
}
Here these two functions are non-reentrant. The first one is using one global variable, so it is non-reentrant. The second one is calling one non-reentrant function, so these also is not reentrant function.
int my_function(int x) {
return x * 10;
}
int my_second_function(int x) {
return my_function(x) * 20;
}
Now these two functions are reentrant functions. | [
{
"code": null,
"e": 1422,
"s": 1062,
"text": "Here we will see what is the reentrant function in C or C++. One function is said to be a reentrant function if there is a provision to interrupt that function in the course of execution, then service the ISR (Interrupt Service Routine) and then resume the task. This type of functions is used in different cases like, recursions, hardware interrupt handling."
},
{
"code": null,
"e": 1505,
"s": 1422,
"text": "For a reentrant function there should be some properties. These are listed below −"
},
{
"code": null,
"e": 1801,
"s": 1505,
"text": "This type of function will not use any global or static variable. There are no restrictions, but it is generally not advised. This is because the interrupt may change the values of global variable, so after coming back from ISR the function may get some new value, and results will be different."
},
{
"code": null,
"e": 2097,
"s": 1801,
"text": "This type of function will not use any global or static variable. There are no restrictions, but it is generally not advised. This is because the interrupt may change the values of global variable, so after coming back from ISR the function may get some new value, and results will be different."
},
{
"code": null,
"e": 2227,
"s": 2097,
"text": "The reentrant function should not modify its own code. We need the action of the function should remain same throughout the code."
},
{
"code": null,
"e": 2357,
"s": 2227,
"text": "The reentrant function should not modify its own code. We need the action of the function should remain same throughout the code."
},
{
"code": null,
"e": 2450,
"s": 2357,
"text": "Another property is the reentrant function should not call any other non-reentrant function."
},
{
"code": null,
"e": 2543,
"s": 2450,
"text": "Another property is the reentrant function should not call any other non-reentrant function."
},
{
"code": null,
"e": 2649,
"s": 2543,
"text": "int x;\nint my_function() {\n return x * 10;\n}\nint my_second_function() {\n return my_function() * 20;\n}"
},
{
"code": null,
"e": 2856,
"s": 2649,
"text": "Here these two functions are non-reentrant. The first one is using one global variable, so it is non-reentrant. The second one is calling one non-reentrant function, so these also is not reentrant function."
},
{
"code": null,
"e": 2966,
"s": 2856,
"text": "int my_function(int x) {\n return x * 10;\n}\nint my_second_function(int x) {\n return my_function(x) * 20;\n}"
},
{
"code": null,
"e": 3015,
"s": 2966,
"text": "Now these two functions are reentrant functions."
}
] |
WebGL - Quick Guide | A few years back, Java applications – as a combination of applets and JOGL – were used to process 3D graphics on the Web by addressing the GPU (Graphical Processing Unit). As applets require a JVM to run, it became difficult to rely on Java applets. A few years later, people stopped using Java applets.
The Stage3D APIs provided by Adobe (Flash, AIR) offered GPU hardware accelerated architecture. Using these technologies, programmers could develop applications with 2D and 3D capabilities on web browsers as well as on IOS and Android platforms. Since Flash was a proprietary software, it was not used as web standard.
In March 2011, WebGL was released. It is an openware that can run without a JVM. It is completely controlled by the web browser.
The new release of HTML 5 has several features to support 3D graphics such as 2D Canvas, WebGL, SVG, 3D CSS transforms, and SMIL. In this tutorial, we will be covering the basics of WebGL.
OpenGL (Open Graphics Library) is a cross-language, cross-platform API for 2D and 3D graphics. It is a collection of commands. OpenGL4.5 is the latest version of OpenGL. The following table lists a set of technologies related to OpenGL.
Note − In WebGL, we use GLSL to write shaders.
WebGL (Web Graphics Library) is the new standard for 3D graphics on the Web, It is designed for the purpose of rendering 2D graphics and interactive 3D graphics. It is derived from OpenGL's ES 2.0 library which is a low-level 3D API for phones and other mobile devices. WebGL provides similar functionality of ES 2.0 (Embedded Systems) and performs well on modern 3D graphics hardware.
It is a JavaScript API that can be used with HTML5. WebGL code is written within the <canvas> tag of HTML5. It is a specification that allows Internet browsers access to Graphic Processing Units (GPUs) on those computers where they were used.
An American-Serbian software engineer named Vladimir Vukicevic did the foundation work and led the creation of WebGL
In 2007, Vladimir started working on an OpenGL prototype for Canvas element of the HTML document.
In 2007, Vladimir started working on an OpenGL prototype for Canvas element of the HTML document.
In March 2011, Kronos Group created WebGL.
In March 2011, Kronos Group created WebGL.
Rendering is the process of generating an image from a model using computer programs. In graphics, a virtual scene is described using information like geometry, viewpoint, texture, lighting, and shading, which is passed through a render program. The output of this render program will be a digital image.
There are two types of rendering −
Software Rendering − All the rendering calculations are done with the help of CPU.
Software Rendering − All the rendering calculations are done with the help of CPU.
Hardware Rendering − All the graphics computations are done by the GPU (Graphical processing unit).
Hardware Rendering − All the graphics computations are done by the GPU (Graphical processing unit).
Rendering can be done locally or remotely. If the image to be rendered is way too complex, then rendering is done remotely on a dedicated server having enough of hardware resources required to render complex scenes. It is also called as server-based rendering. Rendering can also be done locally by the CPU. It is called as client-based rendering.
WebGL follows a client-based rendering approach to render 3D scenes. All the processing required to obtain an image is performed locally using the client's graphics hardware.
According to NVIDIA, a GPU is "a single chip processor with integrated transform, lighting, triangle setup/clipping, and rendering engines capable of processing a minimum of 10 million polygons per second." Unlike multi-core processors with a few cores optimized for sequential processing, a GPU consists of thousands of smaller cores that process parallel workloads efficiently. Therefore, the GPU accelerates the creation of images in a frame buffer (a portion of ram which contains a complete frame data) intended for output to a display.
In GPU accelerated computing, the application is loaded into the CPU. Whenever it encounters a compute-intensive portion of the code, then that portion of code will be loaded and run on the GPU. It gives the system the ability to process graphics in an efficient way.
GPU will have a separate memory and it runs multiple copies of a small portion of the code at a time. The GPU processes all the data which is in its local memory, not the central memory. Therefore, the data that is needed to be processed by the GPU should be loaded/copied to the GPU memory and then be processed.
In the systems having the above architecture, the communication overhead between the CPU and GPU should be reduced to achieve faster processing of 3D programs. For this, we have to copy all the data and keep it on the GPU, instead of communicating with the GPU repeatedly.
The following tables show a list of browsers that support WebGL −
Here are the advantages of using WebGL −
JavaScript programming − WebGL applications are written in JavaScript. Using these applications, you can directly interact with other elements of the HTML Document. You can also use other JavaScript libraries (e.g. JQuery) and HTML technologies to enrich the WebGL application.
JavaScript programming − WebGL applications are written in JavaScript. Using these applications, you can directly interact with other elements of the HTML Document. You can also use other JavaScript libraries (e.g. JQuery) and HTML technologies to enrich the WebGL application.
Increasing support with mobile browsers − WebGL also supports Mobile browsers such as iOS safari, Android Browser, and Chrome for Android.
Increasing support with mobile browsers − WebGL also supports Mobile browsers such as iOS safari, Android Browser, and Chrome for Android.
Open source − WebGL is an open source. You can access the source code of the library and understand how it works and how it was developed.
Open source − WebGL is an open source. You can access the source code of the library and understand how it works and how it was developed.
No need for compilation − JavaScript is a half-programming and half-HTML component. To execute this script, there is no need to compile the file. Instead, you can directly open the file using any of the browsers and check the result. Since WebGL applications are developed using JavaScript, there is no need to compile WebGL applications as well.
No need for compilation − JavaScript is a half-programming and half-HTML component. To execute this script, there is no need to compile the file. Instead, you can directly open the file using any of the browsers and check the result. Since WebGL applications are developed using JavaScript, there is no need to compile WebGL applications as well.
Automatic memory management − JavaScript supports automatic memory management. There is no need for manual allocation of memory. WebGL inherits this feature of JavaScript.
Automatic memory management − JavaScript supports automatic memory management. There is no need for manual allocation of memory. WebGL inherits this feature of JavaScript.
Easy to set up − Since WebGL is integrated within HTML 5, there is no need for additional set up. To write a WebGL application, all that you need is a text editor and a web browser.
Easy to set up − Since WebGL is integrated within HTML 5, there is no need for additional set up. To write a WebGL application, all that you need is a text editor and a web browser.
There is no need to set a different environment for WebGL. The browsers supporting WebGL have their own in-built setup for WebGL.
To create graphical applications on the web, HTML-5 provides a rich set of features such as 2D Canvas, WebGL, SVG, 3D CSS transforms, and SMIL. To write WebGL applications, we use the existing canvas element of HTML-5. This chapter provides an overview of the HTML-5 2D canvas element.
HTML-5 <canvas> provides an easy and powerful option to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions, or do simple (and not so simple) animations.
Here is a simple <canvas> element having only two specific attributes width and height plus all the core HTML-5 attributes like id, name, and class.
The syntax of HTML canvas tag is given below. You have to mention the name of the canvas inside double quotations (“ ”).
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
The canvas tag has three attributes namely, id, width, and height.
Id − Id represents the identifier of the canvas element in the Document Object Model (DOM).
Id − Id represents the identifier of the canvas element in the Document Object Model (DOM).
Width − Width represents the width of the canvas.
Width − Width represents the width of the canvas.
Height − Height represents the height of the canvas.
Height − Height represents the height of the canvas.
These attributes determine the size of the canvas. If a programmer is not specifying them under the canvas tag, then browsers such as Firefox, Chrome, and Web Kit, by default, provide a canvas element of size 300 × 150.
The following code shows how to create a canvas. We have used CSS to give a colored border to the canvas.
<html>
<head>
<style>
#mycanvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
</body>
</html>
On executing, the above code will produce the following output −
The <canvas> is initially blank. To display something on the canvas element, we have to use a scripting language. This scripting language should access the rendering context and draw on it.
The canvas element has a DOM method called getContext(), which is used to obtain the rendering context and its drawing functions. This method takes one parameter, the type of context 2d.
The following code is to be written to get the required context. You can write this script inside the body tag as shown below.
<!DOCTYPE HTML>
<html>
<body>
<canvas id = "mycanvas" width = "600" height = "200"></canvas>
<script>
var canvas = document.getElementById('mycanvas');
var context = canvas.getContext('2d');
context.font = '20pt Calibri';
context.fillStyle = 'green';
context.fillText('Welcome to Tutorialspoint', 70, 70);
</script>
</body>
</html>
On executing, the above code will produce the following output −
For more example on HTML-5 2D Canvas, check out the following link HTML-5 Canvas.
HTML5 Canvas is also used to write WebGL applications. To create a WebGL rendering context on the canvas element, you should pass the string experimental-webgl, instead of 2d to the canvas.getContext() method. Some browsers support only 'webgl'.
<!DOCTYPE html>
<html>
<canvas id = 'my_canvas'></canvas>
<script>
var canvas = document.getElementById('my_canvas');
var gl = canvas.getContext('experimental-webgl');
gl.clearColor(0.9,0.9,0.8,1);
gl.clear(gl.COLOR_BUFFER_BIT);
</script>
</html>
On executing, the above code will produce the following output −
WebGL is mostly a low-level rasterization API rather than a 3D API. To draw an image using WebGL, you have to pass a vector representing the image. It then converts the given vector into pixel format using OpenGL SL and displays the image on the screen. Writing a WebGL application involves a set of steps which
we would be explaining in this chapter.
Just like any other 3D system, you will have x, y and z axes in WebGL, where the z axis signifies depth. The coordinates in WebGL are restricted to (1, 1, 1) and (-1, -1, - 1). It means − if you consider the screen projecting WebGL graphics as a cube, then one corner of the cube will be (1, 1, 1) and the opposite corner will be (-1, -1, -1). WebGL won’t display anything that is drawn beyond these boundaries.
The following diagram depicts the WebGL coordinate system. The z-axis signifies depth. A positive value of z indicates that the object is near the screen/viewer, whereas a negative value of z indicates that the object is away from the screen. Likewise, a positive value of x indicates that the object is to the right side of the screen and a negative value indicates the object is to the left side. Similarly, positive and negative values of y indicate whether the object is at the top or at the bottom portion of the screen.
After getting the WebGL context of the canvas object, you can start drawing graphical elements using WebGL API in JavaScript.
Here are some fundamental terms you need to know before starting with WebGL.
Generally, to draw objects such as a polygon, we mark the points on the plane and join them to form a desired polygon. A vertex is a point which defines the conjunction of the edges of a 3D object. It is represented by three floating point values each representing x, y, z axes respectively.
In the following example, we are drawing a triangle with the following vertices − (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.5).
Note − We have to store these vertices manually using JavaScript arrays and pass them to the WebGL rendering pipeline using vertex buffer.
In WebGL, numerical values are used to identify the vertices. These numerical values are known as indices. These indices are used to draw meshes in WebGL.
Note − Just like vertices, we store the indices using JavaScript arrays and pass them to WebGL rendering pipeline using index buffer.
Unlike OpenGL and JoGL, there are no predefined methods in WebGL to render the vertices directly. We have to store them manually using JavaScript arrays.
var vertices = [ 0.5, 0.5, 0.1,-0.5, 0.5,-0.5]
Buffers are the memory areas of WebGL that hold the data. There are various buffers namely, drawing buffer, frame buffer, vetex buffer, and index buffer. The vertex buffer and index buffer are used to describe and process the geometry of the model.
Vertex buffer objects store data about the vertices, while Index buffer objects store data about the indices. After storing the vertices into arrays, we pass them to WegGL graphics pipeline using these Buffer objects.
Frame buffer is a portion of graphics memory that hold the scene data. This buffer contains details such as width and height of the surface (in pixels), color of each pixel, depth and stencil buffers.
To draw 2D or 3D objects, the WebGL API provides two methods namely, drawArrays() and drawElements(). These two methods accept a parameter called mode using which you can select the object you want to draw. The options provided by this field are restricted to points, lines, and triangles.
To draw a 3D object using these two methods, we have to construct one or more primitive polygons using points, lines, or triangles. Thereafter, using those primitive polygons, we can form a mesh.
A 3D object drawn using primitive polygons is called a mesh. WebGL offers several ways to draw 3D graphical objects, however users normally prefer to draw a mesh.
In the following example, you can observe that we have drawn a square using two triangles→ {1, 2, 3} and {4, 1, 3}.
We normally use triangles to construct meshes. Since WebGL uses GPU accelerated computing, the information about these triangles should be transferred from CPU to GPU which takes a lot of communication overhead.
WebGL provides a solution to reduce the communication overhead. Since it uses ES SL (Embedded System Shader Language) that runs on GPU, we write all the required programs to draw graphical elements on the client system using shader programs (the programs which we write using OpenGL ES Shading Language / GLSL).
These shaders are the programs for GPU and the language used to write shader programs is GLSL. In these shaders, we define exactly how vertices, transformations, materials, lights, and camera interact with one another to create a particular image.
In short, it is a snippet that implements algorithms to get pixels for a mesh. We will discuss more about shaders in later chapters. There are two types of shaders − Vertex Shader and Fragment Shader.
Vertext shader is the program code called on every vertex. It is used to transform (move) the geometry (ex: triangle) from one place to another. It handles the data of each vertex (per-vertex data) such as vertex coordinates, normals, colors, and texture coordinates.
In the ES GL code of vertex shader, programmers have to define attributes to handle the data. These attributes point to a Vertex Buffer Object written in JavaScript.
The following tasks can be performed using vertex shaders −
Vertex transformation
Normal transformation and normalization
Texture coordinate generation
Texture coordinate transformation
Lighting
Color material application
A mesh is formed by multiple triangles, and the surface of each of the triangles is known as a fragment. Fragment shader is the code that runs on all pixels of every fragment. It is written to calculate and fill the color on individual pixels.
The following tasks can be performed using Fragment shaders −
Operations on interpolated values
Texture access
Texture application
Fog
Color sum
The full form of OpenGL ES SL is OpenGL Embedded System Shading Language. To handle the data in the shader programs, ES SL provides three types of variables. They are as follows −
Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices.
Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices.
Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color.
Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color.
Varyings − These variables are used to pass the data from the vertex shader to the fragment shader.
Varyings − These variables are used to pass the data from the vertex shader to the fragment shader.
With this much basics, we will now move on to discuss the Graphics Pipeline.
To render 3D graphics, we have to follow a sequence of steps. These steps are known as graphics pipeline or rendering pipeline. The following diagram depicts WebGL graphics pipeline.
In the following sections, we will discuss one by one the role of each step in the pipeline.
While developing WebGL applications, we write Shader language code to communicate with the GPU. JavaScript is used to write the control code of the program, which includes the following actions −
Initialize WebGL − JavaScript is used to initialize the WebGL context.
Initialize WebGL − JavaScript is used to initialize the WebGL context.
Create arrays − We create JavaScript arrays to hold the data of the geometry.
Create arrays − We create JavaScript arrays to hold the data of the geometry.
Buffer objects − We create buffer objects (vertex and index) by passing the arrays as parameters.
Buffer objects − We create buffer objects (vertex and index) by passing the arrays as parameters.
Shaders − We create, compile, and link the shaders using JavaScript.
Shaders − We create, compile, and link the shaders using JavaScript.
Attributes − We can create attributes, enable them, and associate them with buffer objects using JavaScript.
Attributes − We can create attributes, enable them, and associate them with buffer objects using JavaScript.
Uniforms − We can also associate the uniforms using JavaScript.
Uniforms − We can also associate the uniforms using JavaScript.
Transformation matrix − Using JavaScript, we can create transformation matrix.
Transformation matrix − Using JavaScript, we can create transformation matrix.
Initially we create the data for the required geometry and pass them to the shaders in the form of buffers. The attribute variable of the shader language points to the buffer objects, which are passed as inputs to the vertex shader.
When we start the rendering process by invoking the methods drawElements() and drawArray(), the vertex shader is executed for each vertex provided in the vertex buffer object. It calculates the position of each vertex of a primitive polygon and stores it in the varying gl_position. It also calculates the other attributes such as color, texture coordinates, and vertices that are normally associated with a vertex.
After calculating the position and other details of each vertex, the next phase is the primitive assembly stage. Here the triangles are assembled and passed to the rasterizer.
In the rasterization step, the pixels in the final image of the primitive are determined. It has two steps −
Culling − Initially the orientation (is it front or back facing?) of the polygon is determined. All those triangles with improper orientation that are not visible in view area are discarded. This process is called culling.
Culling − Initially the orientation (is it front or back facing?) of the polygon is determined. All those triangles with improper orientation that are not visible in view area are discarded. This process is called culling.
Clipping − If a triangle is partly outside the view area, then the part outside the view area is removed. This process is known as clipping.
Clipping − If a triangle is partly outside the view area, then the part outside the view area is removed. This process is known as clipping.
The fragment shader gets
data from the vertex shader in varying variables,
primitives from the rasterization stage, and then
calculates the color values for each pixel between the vertices.
The fragment shader stores the color values of every pixel in each fragment. These color values can be accessed during fragment operations, which we are going to discuss next.
Fragment operations are carried out after determining the color of each pixel in the primitive. These fragment operations may include the following −
Depth
Color buffer blend
Dithering
Once all the fragments are processed, a 2D image is formed and displayed on the screen. The frame buffer is the final destination of the rendering pipeline.
Frame buffer is a portion of graphics memory that hold the scene data. This buffer contains details such as width and height of the surface (in pixels), color of each pixel, and depth and stencil buffers.
We have discussed the basics of WebGL and the WebGL pipeline (a procedure followed to render Graphics applications). In this chapter, we are going to take a sample application to create a triangle using WebGL and observe the steps followed in the application.
WebGL application code is a combination of JavaScript and OpenGL Shader Language.
JavaScript is required to communicate with the CPU
OpenGL Shader Language is required to communicate with the GPU.
Let us now take a simple example to learn how to use WebGL to draw a simple triangle with 2D coordinates.
<!doctype html>
<html>
<body>
<canvas width = "300" height = "300" id = "my_Canvas"></canvas>
<script>
/* Step1: Prepare the canvas and get WebGL context */
var canvas = document.getElementById('my_Canvas');
var gl = canvas.getContext('experimental-webgl');
/* Step2: Define the geometry and store it in buffer objects */
var vertices = [-0.5, 0.5, -0.5, -0.5, 0.0, -0.5,];
// Create a new buffer object
var vertex_buffer = gl.createBuffer();
// Bind an empty array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertices data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/* Step3: Create and compile Shader programs */
// Vertex shader source code
var vertCode =
'attribute vec2 coordinates;' +
'void main(void) {' + ' gl_Position = vec4(coordinates,0.0, 1.0);' + '}';
//Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
//Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
//Compile the vertex shader
gl.compileShader(vertShader);
//Fragment shader source code
var fragCode = 'void main(void) {' + 'gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' + '}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragment shader
gl.compileShader(fragShader);
// Create a shader program object to store combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/* Step 4: Associate the shader programs to buffer objects */
//Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
//Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
//point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 0, 0);
//Enable the attribute
gl.enableVertexAttribArray(coord);
/* Step5: Drawing the required object (triangle) */
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
// Draw the triangle
gl.drawArrays(gl.TRIANGLES, 0, 3);
</script>
</body>
</html>
It will produce the following result −
If you observe the above program carefully, we have followed five sequential steps to draw a simple triangle using WebGL. The steps are as follows −
Step 1 − Prepare the canvas and get WebGL rendering context
We get the current HTML canvas object and obtain its WebGL rendering context.
Step 2 − Define the geometry and store it in buffer objects
We define the attributes of the geometry such as vertices, indices, color, etc., and store them in the JavaScript arrays. Then, we create one or more buffer objects and pass the arrays containing the data to the respective buffer object. In the example, we store the vertices of the triangle in a JavaScript array and pass this array to a vertex buffer object.
Step 3 − Create and compile Shader programs
We write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Step 4 − Associate the shader programs with buffer objects
We associate the buffer objects and the combined shader program.
Step 5 − Drawing the required object (triangle)
This step includes operations such as clearing the color, clearing the buffer bit, enabling the depth test, setting the view port, etc. Finally, you need to draw the required primitives using one of the methods − drawArrays() or drawElements().
All these steps are explained further in this tutorial.
To write a WebGL application, first step is to get the WebGL rendering context object. This object interacts with the WebGL drawing buffer and can call all the WebGL methods. The following operations are performed to obtain the WebGL context −
Create an HTML-5 canvas
Get the canvas ID
Obtain WebGL
In Chapter 5, we discussed how to create an HTML-5 canvas element. Within the body of the HTML-5 document, write a canvas, give it a name, and pass it as a parameter to the attribute id. You can define the dimensions of the canvas using the width and height attributes (optional).
The following example shows how to create a canvas element with the dimensions 500 × 500. We have created a border to the canvas using CSS for visibility. Copy and paste the following code in a file with the name my_canvas.html.
<!DOCTYPE HTML>
<html>
<head>
<style>
#mycanvas{border:1px solid blue;}
</style>
</head>
<body>
<canvas id = "mycanvas" width = "300" height = "300"></canvas>
</body>
</html>
It will produce the following result −
After creating the canvas, you have to get the WebGL context. The first thing to do to obtain a WebGL drawing context is to get the id of the current canvas element.
Canvas ID is acquired by calling the DOM (Document Object Model) method getElementById(). This method accepts a string value as parameter, so we pass the name of the current canvas to it.
For example, if the canvas name is my_canvas, then canvas ID is obtained as shown below−
var canvas = document.getElementById('my_Canvas');
To get the WebGLRenderingContext object (or WebGL Drawing context object or simply WebGL context), call the getContext() method of the current HTMLCanvasElement. The syntax of getContext() is as follows −
canvas.getContext(contextType, contextAttributes);
Pass the strings webgl or experimental-webgl as the contentType. The contextAttributes parameter is optional. (While proceeding with this step, make sure your browser implements WebGL version 1 (OpenGL ES 2.0)).
The following code snippet shows how to obtain the WebGL rendering context. Here gl is the reference variable to the obtained context object.
var canvas = document.getElementById('my_Canvas');
var gl = canvas.getContext('experimental-webgl');
The parameter WebGLContextAttributes is not mandatory. This parameter provides various options that accept Boolean values as listed below −
Alpha
If its value is true, it provides an alpha buffer to the canvas.
By default, its value is true.
depth
If its value is true, you will get a drawing buffer which contains a depth buffer of at least 16 bits.
By default, its value is true.
stencil
If its value is true, you will get a drawing buffer which contains a stencil buffer of at least 8 bits.
By default, its value is false.
antialias
If its value is true, you will get a drawing buffer which performs anti-aliasing.
By default, its value is true.
premultipliedAlpha
If its value is true, you will get a drawing buffer which contains colors with pre-multiplied alpha.
By default, its value is true.
preserveDrawingBuffer
If its value is true, the buffers will not be cleared and will preserve their values until cleared or overwritten by the author.
By default, its value is false.
The following code snippet shows how to create a WebGL context with a stencil buffer, which will not perform anti-aliasing.
var canvas = document.getElementById('canvas1');
var context = canvas.getContext('webgl', { antialias: false, stencil: true });
At the time of creating the WebGLRenderingContext, a drawing buffer is created. The Context object manages OpenGL state and renders to the drawing buffer.
It is the principal interface in WebGL. It represents the WebGL drawing context. This interface contains all the methods used to perform various tasks on the Drawing buffer. The attributes of this interface are given in the following table.
Canvas
This is a reference to the canvas element that created this context.
drawingBufferWidth
This attribute represents the actual width of the drawing buffer. It may differ from the width attribute of the HTMLCanvasElement.
drawingBufferHeight
This attribute represents the actual height of the drawing buffer. It may differ from the height attribute of the HTMLCanvasElement.
After obtaining the WebGL context, you have to define the geometry for the primitive (object you want to draw) and store it. In WebGL, we define the details of a geometry – for example, vertices, indices, color of the primitive – using JavaScript arrays. To pass these details to the shader programs, we have to create the buffer objects and store (attach) the JavaScript arrays containing the data in the respective buffers.
Note: Later, these buffer objects will be associated with the attributes of the shader program (vertex shader).
A 2D or 3D model drawn using vertices is called a mesh. Each facet in a mesh is called a polygon and a polygon is made of 3 or more vertices.
To draw models in the WebGL rendering context, you have to define the vertices and indices using JavaScript arrays. For example, if we want to create a triangle which lies on the coordinates {(5,5), (-5,5), (-5,-5)} as shown in the diagram, then you can create an array for the vertices as −
var vertices = [
0.5,0.5, //Vertex 1
0.5,-0.5, //Vertex 2
-0.5,-0.5, //Vertex 3
];
Similarly, you can create an array for the indices. Indices for the above triangle indices will be [0, 1, 2] and can be defined as −
var indices = [ 0,1,2 ]
For a better understanding of indices, consider more complex models like square. We can represent a square as a set of two triangles. If (0,3,1) and (3,1,2) are the two triangles using which we intend to draw a square, then the indices will be defined as −
var indices = [0,3,1,3,1,2];
Note −
For drawing primitives, WebGL provides the following two methods −
drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays.
drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays.
drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array.
drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array.
A buffer object is a mechanism provided by WebGL that indicates a memory area allocated in the system. In these buffer objects, you can store data of the model you want to draw, corresponding to vertices, indices, color, etc.
Using these buffer objects, you can pass multiple data to the shader program (vertex shader) through one of its attribute variables. Since these buffer objects reside in the GPU memory, they can be rendered directly, which in turn improves the performance.
To process geometry, there are two types of buffer objects. They are −
Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates.
Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates.
Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered.
Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered.
After defining the required geometry and storing them in JavaScript arrays, you need to pass these arrays to the buffer objects, from where the data will be passed to the shader programs. The following steps are to be followed to store data in the buffers.
Create an empty buffer.
Create an empty buffer.
Bind an appropriate array object to the empty buffer.
Bind an appropriate array object to the empty buffer.
Pass the data (vertices/indices) to the buffer using one of the typed arrays.
Pass the data (vertices/indices) to the buffer using one of the typed arrays.
Unbind the buffer (Optional).
Unbind the buffer (Optional).
To create an empty buffer object, WebGL provides a method called createBuffer(). This method returns a newly created buffer object, if the creation was successful; else it returns a null value in case of failure.
WebGL operates as a state machine. Once a buffer is created, any subsequent buffer operation will be executed on the current buffer until we unbound it. Use the following code to create a buffer −
var vertex_buffer = gl.createBuffer();
Note − gl is the reference variable to the current WebGL context.
After creating an empty buffer object, you need to bind an appropriate array buffer (target) to it. WebGL provides a method called bindBuffer() for this purpose.
The syntax of bindBuffer() method is as follows −
void bindBuffer (enum target, Object buffer)
This method accepts two parameters and they are discussed below.
target − The first variable is an enum value representing the type of the buffer we want to bind to the empty buffer. You have two predefined enum values as options for this parameter. They are −
ARRAY_BUFFER which represents vertex data.
ARRAY_BUFFER which represents vertex data.
ELEMENT_ARRAY_BUFFER which represents index data.
ELEMENT_ARRAY_BUFFER which represents index data.
Object buffer − The second one is the reference variable to the buffer object created in the previous step. The reference variable can be of a vertex buffer object or of an index buffer object.
The following code snippet shows how to use the bindBuffer() method.
//vertex buffer
var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
//Index buffer
var Index_Buffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
The next step is to pass the data (vertices/indices) to the buffer. Till now data is in the form of an array and before passing it to the buffer, we need to wrap it in one of the WebGL typed arrays. WebGL provides a method named bufferData() for this purpose.
The syntax of bufferData() method is as follows −
void bufferData (enum target, Object data, enum usage)
This method accepts three parameters and they are discussed below −
target − The first parameter is an enum value representing the type of the array buffer we used.The options for this parameter are −
ARRAY_BUFFER which represents vertex data.
ARRAY_BUFFER which represents vertex data.
ELEMENT_ARRAY_BUFFER which represents index data.
ELEMENT_ARRAY_BUFFER which represents index data.
Object data − The second parameter is the object value that contains the data to be written to the buffer object. Here we have to pass the data using typed arrays.
Usage − The third parameter of this method is an enum variable that specifies how to use the buffer object data (stored data) to draw shapes. There are three options for this parameter as listed below.
gl.STATIC_DRAW − Data will be specified once and used many times.
gl.STATIC_DRAW − Data will be specified once and used many times.
gl.STREAM_DRAW − Data will be specified once and used a few times.
gl.STREAM_DRAW − Data will be specified once and used a few times.
gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times.
gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times.
The following code snippet shows how to use the bufferData() method. Assume vertices and indices are the arrays holding the vertex and index data respectively.
//vertex buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
//Index buffer
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
WebGL provides a special type of array called typed arrays to transfer the data elements such as index vertex and texture. These typed arrays store large quantities of data and process them in native binary format which results in better performance. The typed arrays used by WebGL are Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, UInt32Array, Float32Array, and Float64Array.
Note
Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array.
Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array.
You can create typed arrays just like JavaScript arrays using new keyword.
You can create typed arrays just like JavaScript arrays using new keyword.
It is recommended that you unbind the buffers after using them. It can be done by passing a null value in place of the buffer object, as shown below.
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
WebGL provides the following methods to perform buffer operations −
void bindBuffer (enum target, Object buffer)
target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER
void bufferData(enum target, long size, enum usage)
target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER
usage − STATIC_DRAW, STREAM_DRAW, DYNAMIC_DRAW
void bufferData (enum target, Object data, enum usage)
target and usage − Same as for bufferData above
void bufferSubData(enum target, long offset, Object data)
target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER
any getBufferParameter(enum target, enum pname)
target − ARRAY_BUFFER, ELEMENT_ ARRAY_BUFFER
pname − BUFFER_SIZE, BUFFER_USAGE
Shaders are the programs that run on GPU. Shaders are written in OpenGL ES Shader Language (known as ES SL). ES SL has variables of its own, data types, qualifiers, built-in inputs and outputs.
The following table lists the basic data types provided by OpenGL ES SL.
void
Represents an empty value.
bool
Accepts true or false.
int
This is a signed integer data type.
float
This is a floating scalar data type.
vec2, vec3, vec4
n-component floating point vector
bvec2, bvec3, bvec4
Boolean vector
ivec2, ivec3, ivec4
signed integer vector
mat2, mat3, mat4
2x2, 3x3, 4x4 float matrix
sampler2D
Access a 2D texture
samplerCube
Access cube mapped texture
There are three main qualifiers in OpenGL ES SL −
attribute
This qualifier acts as a link between a vertex shader and OpenGL ES for per-vertex data. The value of this attribute changes for every execution of the vertex shader.
uniform
This qualifier links shader programs and the WebGL application. Unlike attribute qualifier, the values of uniforms do not change. Uniforms are read-only; you can use them with any basic data types, to declare a variable.
Example − uniform vec4 lightPosition;
varying
This qualifier forms a link between a vertex shader and fragment shader for interpolated data. It can be used with the following data types − float, vec2, vec3, vec4, mat2, mat3, mat4, or arrays.
Example − varying vec3 normal;
Vertex shader is a program code, which is called on every vertex. It transforms (move) the geometry (ex: triangle) from one place to other. It handles the data of each vertex (per-vertex data) such as vertex coordinates, normals, colors, and texture coordinates.
In the ES GL code of vertex shader, programmers have to define attributes to handle data. These attributes point to a Vertex Buffer Object written In JavaScript. The following tasks can be performed using vertex shaders along with vertex transformation −
Vertex transformation
Normal transformation and normalization
Texture coordinate generation
Texture coordinate transformation
Lighting
Color material application
OpenGL ES SL provides the following predefined variables for vertex shader −
highp vec4 gl_Position;
Holds the position of the vertex.
mediump float gl_PointSize;
Holds the transformed point size. The units for this variable are pixels.
Take a look at the following sample code of a vertex shader. It processes the vertices of a triangle.
attribute vec2 coordinates;
void main(void) {
gl_Position = vec4(coordinates, 0.0, 1.0);
};
If you observe the above code carefully, we have declared an attribute variable with the name coordinates. (This variable will be associated with the Vertex Buffer Object using the method getAttribLocation(). The attribute coordinates is passed as a parameter to this method along with the shader program object.)
In the second step of the given vertex shader program, the gl_position variable is defined.
gl_Position is the predefined variable which is available only in the vertex shader program. It contains the vertex position. In the above code, the coordinates attribute is passed in the form of a vector. As vertex shader is a per-vertex operation, the gl_position value is calculated for each vertex.
Later, the gl_position value is used by primitive assembly, clipping, culling, and other fixed functionality operations that operate on the primitives after the vertex processing is over.
We can write vertex shader programs for all possible operations of vertex shader, which we will discuss individually in this tutorial.
A mesh is formed by multiple triangles, and the surface of the each triangle is known as a fragment. A fragment shader is the code that runs on every pixel on each fragment. This is written to calculate and fill the color on individual pixels. The following tasks can be performed using fragment shaders −
Operations on interpolated values
Texture access
Texture application
Fog
Color sum
OpenGL ES SL provides the following predefined variables for fragment shader −
mediump vec4 gl_FragCoord;
Holds the fragment position within the frame buffer.
bool gl_FrontFacing;
Holds the fragment that belongs to a front-facing primitive.
mediump vec2 gl_PointCoord;
Holds the fragment position within a point (point rasterization only).
mediump vec4 gl_FragColor;
Holds the output fragment color value of the shader
mediump vec4 gl_FragData[n]
Holds the fragment color for color attachment n.
The following sample code of a fragment shader shows how to apply color to every pixel in a triangle.
void main(void) {
gl_FragColor = vec4(0, 0.8, 0, 1);
}
In the above code, the color value is stored in the variable gl.FragColor. The fragment shader program passes the output to the pipeline using fixed function variables; FragColor is one of them. This variable holds the color value of the pixels of the model.
Since shaders are independent programs, we can write them as a separate script and use in the application. Or, you can store them directly in string format, as shown below.
var vertCode =
'attribute vec2 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 0.0, 1.0);' +
'}';
Compilation involves following three steps −
Creating the shader object
Attaching the source code to the created shader object
Compiling the program
To create an empty shader, WebGL provides a method called createShader(). It creates and returns the shader object. Its syntax is as follows −
Object createShader (enum type)
As observed in the syntax, this method accepts a predefined enum value as parameter. We have two options for this −
gl.VERTEX_SHADER for creating vertex shader
gl.VERTEX_SHADER for creating vertex shader
gl.FRAGMENT_SHADER for creating fragment shader.
gl.FRAGMENT_SHADER for creating fragment shader.
You can attach the source code to the created shader object using the method shaderSource(). Its syntax is as follows −
void shaderSource(Object shader, string source)
This method accepts two parameters −
shader − You have to pass the created shader object as one parameter.
shader − You have to pass the created shader object as one parameter.
Source − You have to pass the shader program code in string format.
Source − You have to pass the shader program code in string format.
To compile the program, you have to use the method compileShader(). Its syntax is as follow −
compileShader(Object shader)
This method accepts the shader program object as a parameter. After creating a shader program object, attach the source code to it and pass that object to this method.
The following code snippet shows how to create and compile a vertex shader as well as a fragment shader to create a triangle.
// Vertex Shader
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'}';
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
// Fragment Shader
var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(0, 0.8, 0, 1);' +
'}';
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
After creating and compiling both the shader programs, you need to create a combined program containing both the shaders (vertex & fragment). The following steps need to be followed −
Create a program object
Attach both the shaders
Link both the shaders
Use the program
Create a program object by using the method createProgram(). It will return an empty program object. Here is its syntax −
createProgram();
Attach the shaders to the created program object using the method attachShader(). Its syntax is as follows −
attachShader(Object program, Object shader);
This method accepts two parameters −
Program − Pass the created empty program object as one parameter.
Program − Pass the created empty program object as one parameter.
Shader − Pass one of the compiled shaders programs (vertex shader, fragment shader)
Shader − Pass one of the compiled shaders programs (vertex shader, fragment shader)
Note − You need to attach both the shaders using this method.
Link the shaders using the method linkProgram(), by passing the program object to which you have attached the shaders. Its syntax is as follows −
linkProgram(shaderProgram);
WebGL provides a method called useProgram(). You need to pass the linked program to it. Its syntax is as follows −
useProgram(shaderProgram);
The following code snippet shows how to create, link, and use a combined shader program.
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
Each attribute in the vertex shader program points to a vertex buffer object. After creating the vertex buffer objects, programmers have to associate them with the attributes of the vertex shader program. Each attribute points to only one vertex buffer object from which they extract the data values, and then these attributes are passed to the shader program.
To associate the Vertex Buffer Objects with the attributes of the vertex shader program, you have to follow the steps given below −
Get the attribute location
Point the attribute to a vertex buffer object
Enable the attribute
WebGL provides a method called getAttribLocation() which returns the attribute location. Its syntax is as follows −
ulong getAttribLocation(Object program, string name)
This method accepts the vertex shader program object and the attribute values of the vertex shader program.
The following code snippet shows how to use this method.
var coordinatesVar = gl.getAttribLocation(shader_program, "coordinates");
Here, shader_program is the object of the shader program and coordinates is the attribute of the vertex shader program.
To assign the buffer object to the attribute variable, WebGL provides a method called vertexAttribPointer(). Here is the syntax of this method −
void vertexAttribPointer(location, int size, enum type, bool normalized, long stride, long offset)
This method accepts six parameters and they are discussed below.
Location − It specifies the storage location of an attribute variable. Under this option, you have to pass the value returned by the getAttribLocation() method.
Location − It specifies the storage location of an attribute variable. Under this option, you have to pass the value returned by the getAttribLocation() method.
Size − It specifies the number of components per vertex in the buffer object.
Size − It specifies the number of components per vertex in the buffer object.
Type − It specifies the type of data.
Type − It specifies the type of data.
Normalized − This is a Boolean value. If true, non-floating data is normalized to [0, 1]; else, it is normalized to [-1, 1].
Normalized − This is a Boolean value. If true, non-floating data is normalized to [0, 1]; else, it is normalized to [-1, 1].
Stride − It specifies the number of bytes between different vertex data elements, or zero for default stride.
Stride − It specifies the number of bytes between different vertex data elements, or zero for default stride.
Offset − It specifies the offset (in bytes) in a buffer object to indicate which byte the vertex data is stored from. If the data is stored from the beginning, offset is 0.
Offset − It specifies the offset (in bytes) in a buffer object to indicate which byte the vertex data is stored from. If the data is stored from the beginning, offset is 0.
The following snippet shows how to use vertexAttribPointer() in a program −
gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);
Activate the vertex shader attribute to access the buffer object in a vertex shader. For this operation, WebGL provides enableVertexAttribArray() method. This method accepts the location of the attribute as a parameter. Here is how to use this method in a program −
gl.enableVertexAttribArray(coordinatesVar);
After associating the buffers with the shaders, the final step is to draw the required primitives. WebGL provides two methods namely, drawArrays() and drawElements() to draw models.
drawArrays() is the method which is used to draw models using vertices. Here is its syntax −
void drawArrays(enum mode, int first, long count)
This method takes the following three parameters −
mode − In WebGL, models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES.
mode − In WebGL, models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES.
first − This option specifies the starting element in the enabled arrays. It cannot be a negative value.
first − This option specifies the starting element in the enabled arrays. It cannot be a negative value.
count − This option specifies the number of elements to be rendered.
count − This option specifies the number of elements to be rendered.
If you draw a model using drawArrays() method, then WebGL, while rendering the shapes, creates the geometry in the order in which the vertex coordinates are defined.
If you want to draw a single triangle using drawArray() method, then you have to pass three vertices and call the drawArrays() method, as shown below.
var vertices = [-0.5,-0.5, -0.25,0.5, 0.0,-0.5,];
gl.drawArrays(gl.TRIANGLES, 0, 3);
It will produce a triangle as shown below.
Suppose you want to draw contiguous triangles, then you have to pass the next three vertices in order in the vertex buffer and mention the number of elements to be rendered as 6.
var vertices = [-0.5,-0.5, -0.25,0.5, 0.0,-0.5, 0.0,-0.5, 0.25,0.5, 0.5,-0.5,];
gl.drawArrays(gl.TRIANGLES, 0, 6);
It will produce a contiguous triangle as shown below.
drawElements() is the method that is used to draw models using vertices and indices. Its syntax is as follows −
void drawElements(enum mode, long count, enum type, long offset)
This method takes the following four parameters −
mode − WebGL models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The list of possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES.
mode − WebGL models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The list of possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES.
count − This option specifies the number of elements to be rendered.
count − This option specifies the number of elements to be rendered.
type − This option specifies the data type of the indices which must be UNSIGNED_BYTE or UNSIGNED_SHORT.
type − This option specifies the data type of the indices which must be UNSIGNED_BYTE or UNSIGNED_SHORT.
offset − This option specifies the starting point for rendering. It is usually the first element (0).
offset − This option specifies the starting point for rendering. It is usually the first element (0).
If you draw a model using drawElements() method, then index buffer object should also be created along with the vertex buffer object. If you use this method, the vertex data will be processed once and used as many times as mentioned in the indices.
If you want to draw a single triangle using indices, you need to pass the indices along with vertices and call the drawElements() method as shown below.
var vertices = [ -0.5,-0.5,0.0, -0.25,0.5,0.0, 0.0,-0.5,0.0 ];
var indices = [0,1,2];
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
It will produce the following output −
If you want to draw contagious triangles using drawElements() method, simply add the other vertices and mention the indices for the remaining vertices.
var vertices = [
-0.5,-0.5,0.0,
-0.25,0.5,0.0,
0.0,-0.5,0.0,
0.25,0.5,0.0,
0.5,-0.5,0.0
];
var indices = [0,1,2,2,3,4];
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
It will produce the following output −
Before drawing a primitive, you need to perform a few operations, which are explained below.
First of all, you should clear the canvas, using clearColor() method. You can pass the RGBA values of a desired color as parameter to this method. Then WebGL clears the canvas and fills it with the specified color. Therefore, you can use this method for setting the background color.
Take a look at the following example. Here we are passing the RGBA value of gray color.
gl.clearColor(0.5, 0.5, .5, 1);
Enable the depth test using the enable() method, as shown below.
gl.enable(gl.DEPTH_TEST);
Clear the color as well as the depth buffer by using the clear() method, as shown below.
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
The view port represents a rectangular viewable area that contains the rendering results of the drawing buffer. You can set the dimensions of the view port using viewport() method. In the following code, the view port dimensions are set to the canvas dimensions.
gl.viewport(0,0,canvas.width,canvas.height);
We discussed earlier (in Chapter 5) how to follow a step-by-step process to draw a primitive. We have explained the process in five steps. You need to repeat these steps every time you draw a new shape. This chapter explains how to draw points with 3D coordinates in WebGL. Before moving further, let us take a relook at the five steps.
The following steps are required to create a WebGL application to draw points.
Step 1 − Prepare the Canvas and Get the WebGL Rendering Context
In this step, we obtain the WebGL Rendering context object using the method getContext().
Step 2 − Define the Geometry and Store it in the Buffer Objects
Since we are drawing three points, we define three vertices with 3D coordinates and store them in buffers.
var vertices = [
-0.5,0.5,0.0,
0.0,0.5,0.0,
-0.25,0.25,0.0,
];
Step 3 − Create and Compile the Shader Programs
In this step, you need to write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Vertex Shader − In the vertex shader of the given example, we define a vector attribute to store 3D coordinates, and assign it to the gl_position variable.
Vertex Shader − In the vertex shader of the given example, we define a vector attribute to store 3D coordinates, and assign it to the gl_position variable.
gl_pointsize is the variable used to assign a size to the point. We assign the point size as 10.
gl_pointsize is the variable used to assign a size to the point. We assign the point size as 10.
var vertCode = 'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'gl_PointSize = 10.0;'+
'}';
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable
var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';
Step 4 − Associate the Shader Programs to Buffer Objects
In this step, we associate the buffer objects with the shader program.
Step 5 − Drawing the Required Object
We use the method drawArrays() to draw points. Since the number of points we want to draw are is three, the count value is 3.
gl.drawArrays(gl.POINTS, 0, 3)
Here is the complete WebGL program to draw three points −
<!doctype html>
<html>
<body>
<canvas width = "570" height = "570" id = "my_Canvas"></canvas>
<script>
/*================Creating a canvas=================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*==========Defining and storing the geometry=======*/
var vertices = [
-0.5,0.5,0.0,
0.0,0.5,0.0,
-0.25,0.25,0.0,
];
// Create an empty buffer object to store the vertex buffer
var vertex_buffer = gl.createBuffer();
//Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*=========================Shaders========================*/
// vertex shader source code
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'gl_PointSize = 10.0;'+
'}';
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
// fragment shader source code
var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to store
// the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/*======== Associating shaders to buffer objects ========*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*============= Drawing the primitive ===============*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
// Draw the triangle
gl.drawArrays(gl.POINTS, 0, 3);
</script>
</body>
</html>
It will produce the following result −
In the previous chapter (Chapter 11), we discussed how to draw three points using WebGL. In Chapter 5, we took sample application to demonstrate how to draw a triangle. In both the examples, we have drawn the primitives using only vertices.
To draw more complex shapes/meshes, we pass the indices of a geometry too, along with the vertices, to the shaders. In this chapter, we will see how to draw a triangle using indices.
The following steps are required to create a WebGL application to draw a triangle.
Step 1 − Prepare the Canvas and Get WebGL Rendering Context
In this step, we obtain the WebGL Rendering context object using getContext().
Step 2 − Define the Geometry and Store it in Buffer Objects
Since we are drawing a triangle using indices, we have to pass the three vertices of the triangle, including the indices, and store them in the buffers.
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
];
indices = [0,1,2];
Step 3 − Create and Compile the Shader Programs
In this step, you need to write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position.
Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position.
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'}';
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable.
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable.
var fragCode = 'void main(void) {' +
' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +
'}';
Step 4 − Associate the Shader Programs to the Buffer Objects
In this step, we associate the buffer objects and the shader program.
Step 5 − Drawing the Required Object
Since we are drawing a triangle using indices, we will use drawElements(). To this method, we have to pass the number of indices. The value of the indices.length signifies the number of indices.
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
The following program code shows how to draw a triangle in WebGL using indices −
<!doctype html>
<html>
<body>
<canvas width = "570" height = "570" id = "my_Canvas"></canvas>
<script>
/*============== Creating a canvas ====================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*======== Defining and storing the geometry ===========*/
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
];
indices = [0,1,2];
// Create an empty buffer object to store vertex buffer
var vertex_buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// Create an empty buffer object to store Index buffer
var Index_Buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
/*================ Shaders ====================*/
// Vertex shader source code
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'}';
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
//fragment shader source code
var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to store
// the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both the programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/*======= Associating shaders to buffer objects =======*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Bind index buffer object
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*=========Drawing the triangle===========*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
// Draw the triangle
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
In the previous chapter (Chapter 12), we discussed how to draw a triangle using WebGL. In addition to triangles, WebGL supports various other drawing modes. This chapter explains the drawing modes supported by WebGL.
Let’s take a look at the syntax of the methods − drawElements() and draw Arrays().
void drawElements(enum mode, long count, enum type, long offset);
void drawArrays(enum mode, int first, long count);
If you clearly observe, both the methods accept a parameter mode. Using this parameter, the programmers can select the drawing mode in WebGL.
The drawing modes provided by WebGL are listed in the following table.
gl.POINTS
To draw a series of points.
gl.LINES
To draw a series of unconnected line segments (individual lines).
gl.LINE_STRIP
To draw a series of connected line segments.
gl.LINE_LOOP
To draw a series of connected line segments. It also joins the first and last vertices to form a loop.
gl.TRIANGLES
To draw a series of separate triangles.
gl.TRIANGLE_STRIP
To draw a series of connected triangles in strip fashion.
gl.TRIANGLE_FAN
To draw a series of connected triangles sharing the first vertex in a fan-like fashion.
The following example shows how to draw three parallel lines using gl.LINES.
<!doctype html>
<html>
<body>
<canvas width = "300" height = "300" id = "my_Canvas"></canvas>
<script>
/*======= Creating a canvas =========*/
var canvas = document.getElementById('my_Canvas');
var gl = canvas.getContext('experimental-webgl');
/*======= Defining and storing the geometry ======*/
var vertices = [
-0.7,-0.1,0,
-0.3,0.6,0,
-0.3,-0.3,0,
0.2,0.6,0,
0.3,-0.3,0,
0.7,0.6,0
]
// Create an empty buffer object
var vertex_buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*=================== Shaders ====================*/
// Vertex shader source code
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'}';
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
// Fragment shader source code
var fragCode =
'void main(void) {' +
'gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to store
// the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both the programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/*======= Associating shaders to buffer objects ======*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*============ Drawing the triangle =============*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color and depth buffer
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
// Draw the triangle
gl.drawArrays(gl.LINES, 0, 6);
// POINTS, LINE_STRIP, LINE_LOOP, LINES,
// TRIANGLE_STRIP,TRIANGLE_FAN, TRIANGLES
</script>
</body>
</html>
If you run this example, it will produce the following output −
In the above program, if you replace the mode of drawArrays() with one of the following drawing modes, it will produce different outputs each time.
In the previous chapter, we discussed the different drawing modes provided by WebGL. We can also use indices to draw primitives using one of these modes. To draw models in WebGL, we have to choose one of these primitives and draw the required mesh (i.e., a model formed using one or more primitives).
In this chapter, we will take an example to demonstrate how to draw a quadrilateral using WebGL.
The following steps are required to create a WebGL application to draw a quadrilateral.
Step 1 − Prepare the Canvas and Get the WebGL Rendering Context
In this step, we obtain the WebGL Rendering context object using getContext().
Step 2 − Define the Geometry and Store it in the Buffer Objects
A square can be drawn using two triangles. In this example, we provide the vertices for two triangles (with one common edge) and indices.
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
indices = [3,2,1,3,1,0];
Step 3 − Create and Compile the Shader Programs
In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position.
Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position.
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'}';
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable.
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable.
var fragCode = 'void main(void) {' +' gl_FragColor = vec4(0.5, 0.3, 0.0, 7.5);' +'}';
Step 4 − Associate the Shader Programs to Buffer Objects
In this step, we associate the buffer objects with the shader program.
Step 5 − Drawing the Required Object
Since we are drawing two triangles to form a quad, using indices, we will use the method drawElements(). To this method, we have to pass the number of indices. The value of indices.length gives the number of indices.
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
The following program shows how to create a WebGL application to draw a quadrilateral.
<!doctype html>
<html>
<body>
<canvas width = "570" height = "570" id = "my_Canvas"></canvas>
<script>
/*============ Creating a canvas =================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*========== Defining and storing the geometry =========*/
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
indices = [3,2,1,3,1,0];
// Create an empty buffer object to store vertex buffer
var vertex_buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// Create an empty buffer object to store Index buffer
var Index_Buffer = gl.createBuffer();
// Bind appropriate array buffer to it
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Pass the vertex data to the buffer
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
// Unbind the buffer
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
/*====================== Shaders =======================*/
// Vertex shader source code
var vertCode =
'attribute vec3 coordinates;' +
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'}';
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
// Fragment shader source code
var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to
// store the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both the programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/* ======= Associating shaders to buffer objects =======*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Bind index buffer object
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// Point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
/*============= Drawing the Quad ================*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
// Draw the triangle
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
In all our previous examples, we applied color to the object by assigning a desired color value to the gl_FragColor variable. In addition to that, we can define colors for each vertex − just like vertex coordinates and indices. This chapter takes an example to demonstrate how to apply colors to a quadrilateral using WebGL.
To apply colors, you have to define the colors for each vertex using the RGB values, in JavaScript array. You can assign the same values to all the vertices to have a unique color to the object. After defining the colors, you have to create a color buffer and store these values in it, and associate it to the vertex shader attributes.
In the vertex shader, along with the coordinates attribute (that holds the position of the vertices), we define an attribute and a varying to handle colors.
The color attribute holds the color value per vertex, and varying is the variable that is passed as an input to the fragment shader. Therefore, we have to assign the color value to varying.
In the fragment shader, the varying that holds the color value is assigned to gl_FragColor, which holds the final color of the object.
The following steps are required to create a WebGL application to draw a Quad and apply colors to it.
Step 1 − Prepare the Canvas and Get the WebGL Rendering Context
In this step, we obtain the WebGL Rendering context object using getContext().
Step 2 − Define the Geometry and Store it in the Buffer Objects
A square can be drawn using two triangles. Therefore, in this example, we provide the vertices for two triangles (with one common edge) and indices. Since we want to apply colors to it, a variable holding the color values is also defined and the color values for each (Red, Blue, Green, and Pink) are assigned to it.
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
var colors = [ 0,0,1, 1,0,0, 0,1,0, 1,0,1,];
indices = [3,2,1,3,1,0];
Step 3 − Create and Compile the Shader Programs
In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Vertex Shader − In the vertex shader of the program, we define vector attributes to store 3D coordinates (position), and the color of each vertex. A varing variable is declared to pass the color values from the vertex shader to the fragment shader. And finally, the value stored in the color attribute is assigned to varying.
Vertex Shader − In the vertex shader of the program, we define vector attributes to store 3D coordinates (position), and the color of each vertex. A varing variable is declared to pass the color values from the vertex shader to the fragment shader. And finally, the value stored in the color attribute is assigned to varying.
var vertCode = 'attribute vec3 coordinates;'+
'attribute vec3 color;'+
'varying vec3 vColor;'+
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'vColor = color;'+
'}';
Fragment Shader − In the fragment shader, we assign the varying to the gl_FragColor variable.
Fragment Shader − In the fragment shader, we assign the varying to the gl_FragColor variable.
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
Step 4 − Associate the Shader Programs with the Buffer Objects
In this step, we associate the buffer objects and the shader program.
Step 5 − Drawing the Required Object
Since we are drawing two triangles that will form a quad, using indices, we will use the method drawElements(). To this method, we have to pass the number of indices. The value of indices.length indicates the number of indices.
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
The following program demonstrates how to draw a quad using WebGL application and apply colors to it.
<!doctype html>
<html>
<body>
<canvas width = "300" height = "300" id = "my_Canvas"></canvas>
<script>
/*============= Creating a canvas ==================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*========== Defining and storing the geometry ==========*/
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
0.5,0.5,0.0
];
var colors = [0,0,1, 1,0,0, 0,1,0, 1,0,1,];
indices = [3,2,1,3,1,0];
// Create an empty buffer object and store vertex data
var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
// Create an empty buffer object and store Index data
var Index_Buffer = gl.createBuffer();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);
// Create an empty buffer object and store color data
var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
/*======================= Shaders =======================*/
// vertex shader source code
var vertCode = 'attribute vec3 coordinates;'+
'attribute vec3 color;'+
'varying vec3 vColor;'+
'void main(void) {' +
' gl_Position = vec4(coordinates, 1.0);' +
'vColor = color;'+
'}';
// Create a vertex shader object
var vertShader = gl.createShader(gl.VERTEX_SHADER);
// Attach vertex shader source code
gl.shaderSource(vertShader, vertCode);
// Compile the vertex shader
gl.compileShader(vertShader);
// fragment shader source code
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
// Create fragment shader object
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
// Attach fragment shader source code
gl.shaderSource(fragShader, fragCode);
// Compile the fragmentt shader
gl.compileShader(fragShader);
// Create a shader program object to
// store the combined shader program
var shaderProgram = gl.createProgram();
// Attach a vertex shader
gl.attachShader(shaderProgram, vertShader);
// Attach a fragment shader
gl.attachShader(shaderProgram, fragShader);
// Link both the programs
gl.linkProgram(shaderProgram);
// Use the combined shader program object
gl.useProgram(shaderProgram);
/* ======== Associating shaders to buffer objects =======*/
// Bind vertex buffer object
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
// Bind index buffer object
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);
// Get the attribute location
var coord = gl.getAttribLocation(shaderProgram, "coordinates");
// point an attribute to the currently bound VBO
gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);
// Enable the attribute
gl.enableVertexAttribArray(coord);
// bind the color buffer
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
// get the attribute location
var color = gl.getAttribLocation(shaderProgram, "color");
// point attribute to the volor buffer object
gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;
// enable the color attribute
gl.enableVertexAttribArray(color);
/*============Drawing the Quad====================*/
// Clear the canvas
gl.clearColor(0.5, 0.5, 0.5, 0.9);
// Enable the depth test
gl.enable(gl.DEPTH_TEST);
// Clear the color buffer bit
gl.clear(gl.COLOR_BUFFER_BIT);
// Set the view port
gl.viewport(0,0,canvas.width,canvas.height);
//Draw the triangle
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
So far, we discussed how to draw various shapes and apply colors in them using WebGL. Here, in this chapter, we will take an example to show how to translate a triangle.
Translation is one of the affine transformations provided by WebGL. Using translation, we can move a triangle (any object) on the xyz plane. Suppose we have a triangle [a, b, c] and we want to move the triangle to a position which is 5 units towards the positive X-axis and 3 units towards the positive Y-axis. Then the new vertices would be [a+5, b+3, c+0]. That means, to translate the triangle, we need to add the translation distances, say, tx, ty, tz to each vertex.
Since it is a per-vertex operation, we can carry it in the vertex shader program.
In the vertex shader, along with the attribute, coordinates (that hold the vertex positions), we define a uniform variable that holds the translation distances (x,y,z). Later, we add this uniform variable to the coordinates variable and assign the result to the gl_Position variable.
Note − Since vertex shader will be run on each vertex, all the vertices of the triangle will be translated.
The following steps are required to create a WebGL application to draw a triangle and then translate it to a new position.
Step 1 − Prepare the Canvas and Get the WebGL Rendering Context
In this step, we obtain the WebGL Rendering context object using getContext().
Step 2 − Define the Geometry and Store it in the Buffer Objects
Since we are drawing a triangle, we have to pass three vertices of the triangle, and store them in buffers.
var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ];
Step 3 − Create and Compile the Shader Programs
In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices.
Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices.
var vertCode =
'attribute vec4 coordinates;' +
'uniform vec4 translation;'+
'void main(void) {' +
' gl_Position = coordinates + translation;' +
'}';
Fragment Shader − In the fragment shader, we simply assign the fragment color to the variable gl_FragColor.
Fragment Shader − In the fragment shader, we simply assign the fragment color to the variable gl_FragColor.
var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';
Step 4 − Associate the Shader Programs to the Buffer Objects
In this step, we associate the buffer objects with the shader program.
Step 5 − Drawing the Required Object
Since we are drawing the triangle using indices, we will use the method drawArrays(). To this method, we have to pass the number of vertices /elements to be considered. Since we are drawing a triangle, we will pass 3 as a parameter.
gl.drawArrays(gl.TRIANGLES, 0, 3);
The following example show how to translate a triangle on xyz plane.
<!doctype html>
<html>
<body>
<canvas width = "300" height = "300" id = "my_Canvas"></canvas>
<script>
/*=================Creating a canvas=========================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*===========Defining and storing the geometry==============*/
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
];
//Create an empty buffer object and store vertex data
var vertex_buffer = gl.createBuffer();
//Create a new buffer
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
//bind it to the current buffer
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Pass the buffer data
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*========================Shaders============================*/
//vertex shader source code
var vertCode =
'attribute vec4 coordinates;' +
'uniform vec4 translation;'+
'void main(void) {' +
' gl_Position = coordinates + translation;' +
'}';
//Create a vertex shader program object and compile it
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
//fragment shader source code
var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';
//Create a fragment shader program object and compile it
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
//Create and use combiened shader program
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
/* ===========Associating shaders to buffer objects============*/
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coordinatesVar);
/* ==========translation======================================*/
var Tx = 0.5, Ty = 0.5, Tz = 0.0;
var translation = gl.getUniformLocation(shaderProgram, 'translation');
gl.uniform4f(translation, Tx, Ty, Tz, 0.0);
/*=================Drawing the riangle and transforming it========================*/
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0,0,canvas.width,canvas.height);
gl.drawArrays(gl.TRIANGLES, 0, 3);
</script>
</body>
</html>
If you run this example, it will produce the following output −
In this chapter, we will take an example to demonstrate how to modify the scale of a triangle using WebGL.
Scaling is nothing but increasing or decreasing the size of an object. For example, if a triangle has vertices of the size [a,b,c], then the triangle with the vertices [2a, 2b, 2c] will be double its size. Therefore, to scale a triangle, you have to multiply each vertices with the scaling factor. You can also scale a particular vertex.
To scale a triangle, in the vertex shader of the program, we create a uniform matrix and multiply the coordinate values with this matrix. Later, we pass a 4×4 diagonal matrix having the scaling factors of x,y,z coordinates in the diagonal positions (last diagonal position 1).
The following steps are required to create a WebGL application to scale a triangle.
Step 1 − Prepare the Canvas and Get the WebGL Rendering Context
In this step, we obtain the WebGL Rendering context object using getContext().
Step 2 − Define the Geometry and Store it in the Buffer Objects
Since we are drawing a triangle, we have to pass three vertices of the triangle, and store them in buffers.
var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ];
Step 3 − Create and Compile the Shader Programs
In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs.
Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform matrix to store the scaling factors, and finally, we multiply these two values and assign it to gl_position which holds the final position of the vertices.
Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform matrix to store the scaling factors, and finally, we multiply these two values and assign it to gl_position which holds the final position of the vertices.
var vertCode =
'attribute vec4 coordinates;' +
'uniform mat4 u_xformMatrix;' +
'void main(void) {' +
' gl_Position = u_xformMatrix * coordinates;' +
'}';
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable.
Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable.
var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';
Step 4 − Associate the Shader Programs with the Buffer Objects
In this step, we associate the buffer objects with the shader program.
Step 5 − Drawing the Required Object
Since we are drawing the triangle using indices, we use the drawArrays() method. To this method, we have to pass the number of vertices/elements to be considered. Since we are drawing a triangle, we will pass 3 as a parameter.
gl.drawArrays(gl.TRIANGLES, 0, 3);
The following example shows how to scale a triangle −
<!doctype html>
<html>
<body>
<canvas width = "300" height = "300" id = "my_Canvas"></canvas>
<script>
/*=================Creating a canvas=========================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*===========Defining and storing the geometry==============*/
var vertices = [
-0.5,0.5,0.0,
-0.5,-0.5,0.0,
0.5,-0.5,0.0,
];
//Create an empty buffer object and store vertex data
var vertex_buffer = gl.createBuffer();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
gl.bindBuffer(gl.ARRAY_BUFFER, null);
/*========================Shaders============================*/
//Vertex shader source code
var vertCode =
'attribute vec4 coordinates;' +
'uniform mat4 u_xformMatrix;' +
'void main(void) {' +
' gl_Position = u_xformMatrix * coordinates;' +
'}';
//Create a vertex shader program object and compile it
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
//fragment shader source code
var fragCode =
'void main(void) {' +
' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +
'}';
//Create a fragment shader program object and compile it
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
//Create and use combiened shader program
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
gl.useProgram(shaderProgram);
/*===================scaling==========================*/
var Sx = 1.0, Sy = 1.5, Sz = 1.0;
var xformMatrix = new Float32Array([
Sx, 0.0, 0.0, 0.0,
0.0, Sy, 0.0, 0.0,
0.0, 0.0, Sz, 0.0,
0.0, 0.0, 0.0, 1.0
]);
var u_xformMatrix = gl.getUniformLocation(shaderProgram, 'u_xformMatrix');
gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix);
/* ===========Associating shaders to buffer objects============*/
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var coordinatesVar = gl.getAttribLocation(shaderProgram, "coordinates");
gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);
gl.enableVertexAttribArray(coordinatesVar);
/*=================Drawing the Quad========================*/
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.enable(gl.DEPTH_TEST);
gl.clear(gl.COLOR_BUFFER_BIT);
gl.viewport(0,0,canvas.width,canvas.height);
gl.drawArrays(gl.TRIANGLES, 0, 3);
</script>
</body>
</html>
If you run this example, it will produce the following output −
In this chapter, we will take an example to demonstrate how to rotate a triangle using WebGL.
The following program shows how to rotate a triangle using WebGL.
<!doctype html>
<html>
<body>
<canvas width = "400" height = "400" id = "my_Canvas"></canvas>
<script>
/*=================Creating a canvas=========================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*===========Defining and storing the geometry==============*/
var vertices = [ -1,-1,-1, 1,-1,-1, 1, 1,-1 ];
var colors = [ 1,1,1, 1,1,1, 1,1,1 ];
var indices = [ 0,1,2 ];
//Create and store data into vertex buffer
var vertex_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
//Create and store data into color buffer
var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
//Create and store data into index buffer
var index_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
/*==========================Shaders=========================*/
var vertCode = 'attribute vec3 position;'+
'uniform mat4 Pmatrix;'+
'uniform mat4 Vmatrix;'+
'uniform mat4 Mmatrix;'+
'attribute vec3 color;'+//the color of the point
'varying vec3 vColor;'+
'void main(void) { '+//pre-built function
'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+
'vColor = color;'+
'}';
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
/*===========associating attributes to vertex shader ============*/
var Pmatrix = gl.getUniformLocation(shaderProgram, "Pmatrix");
var Vmatrix = gl.getUniformLocation(shaderProgram, "Vmatrix");
var Mmatrix = gl.getUniformLocation(shaderProgram, "Mmatrix");
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var position = gl.getAttribLocation(shaderProgram, "position");
gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ; //position
gl.enableVertexAttribArray(position);
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
var color = gl.getAttribLocation(shaderProgram, "color");
gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ; //color
gl.enableVertexAttribArray(color);
gl.useProgram(shaderProgram);
/*========================= MATRIX ========================= */
function get_projection(angle, a, zMin, zMax) {
var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5
return [
0.5/ang, 0 , 0, 0,
0, 0.5*a/ang, 0, 0,
0, 0, -(zMax+zMin)/(zMax-zMin), -1,
0, 0, (-2*zMax*zMin)/(zMax-zMin), 0
];
}
var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);
var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
//translating z
view_matrix[14] = view_matrix[14]-6; //zoom
/*=======================rotation========================*/
function rotateZ(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];
m[0] = c*m[0]-s*m[1];
m[4] = c*m[4]-s*m[5];
m[8] = c*m[8]-s*m[9];
m[1] = c*m[1]+s*mv0;
m[5] = c*m[5]+s*mv4;
m[9] = c*m[9]+s*mv8;
}
/*=================Drawing===========================*/
var time_old = 0;
var animate = function(time) {
var dt = time-time_old;
rotateZ(mov_matrix, dt*0.002);
time_old = time;
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);
gl.uniformMatrix4fv(Vmatrix, false, view_matrix);
gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
window.requestAnimationFrame(animate);
}
animate(0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
In this chapter, we will take an example to demonstrate how to draw a rotating 3D cube using WebGL.
The following program shows how to draw a rotating 3D cube −
<!doctype html>
<html>
<body>
<canvas width = "570" height = "570" id = "my_Canvas"></canvas>
<script>
/*============= Creating a canvas =================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*============ Defining and storing the geometry =========*/
var vertices = [
-1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,
-1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,
-1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,
1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,
-1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,
-1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1,
];
var colors = [
5,3,7, 5,3,7, 5,3,7, 5,3,7,
1,1,3, 1,1,3, 1,1,3, 1,1,3,
0,0,1, 0,0,1, 0,0,1, 0,0,1,
1,0,0, 1,0,0, 1,0,0, 1,0,0,
1,1,0, 1,1,0, 1,1,0, 1,1,0,
0,1,0, 0,1,0, 0,1,0, 0,1,0
];
var indices = [
0,1,2, 0,2,3, 4,5,6, 4,6,7,
8,9,10, 8,10,11, 12,13,14, 12,14,15,
16,17,18, 16,18,19, 20,21,22, 20,22,23
];
// Create and store data into vertex buffer
var vertex_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Create and store data into color buffer
var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// Create and store data into index buffer
var index_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
/*=================== Shaders =========================*/
var vertCode = 'attribute vec3 position;'+
'uniform mat4 Pmatrix;'+
'uniform mat4 Vmatrix;'+
'uniform mat4 Mmatrix;'+
'attribute vec3 color;'+//the color of the point
'varying vec3 vColor;'+
'void main(void) { '+//pre-built function
'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+
'vColor = color;'+
'}';
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
var shaderProgram = gl.createProgram();
gl.attachShader(shaderProgram, vertShader);
gl.attachShader(shaderProgram, fragShader);
gl.linkProgram(shaderProgram);
/* ====== Associating attributes to vertex shader =====*/
var Pmatrix = gl.getUniformLocation(shaderProgram, "Pmatrix");
var Vmatrix = gl.getUniformLocation(shaderProgram, "Vmatrix");
var Mmatrix = gl.getUniformLocation(shaderProgram, "Mmatrix");
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var position = gl.getAttribLocation(shaderProgram, "position");
gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ;
// Position
gl.enableVertexAttribArray(position);
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
var color = gl.getAttribLocation(shaderProgram, "color");
gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;
// Color
gl.enableVertexAttribArray(color);
gl.useProgram(shaderProgram);
/*==================== MATRIX =====================*/
function get_projection(angle, a, zMin, zMax) {
var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5
return [
0.5/ang, 0 , 0, 0,
0, 0.5*a/ang, 0, 0,
0, 0, -(zMax+zMin)/(zMax-zMin), -1,
0, 0, (-2*zMax*zMin)/(zMax-zMin), 0
];
}
var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);
var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];
// translating z
view_matrix[14] = view_matrix[14]-6;//zoom
/*==================== Rotation ====================*/
function rotateZ(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];
m[0] = c*m[0]-s*m[1];
m[4] = c*m[4]-s*m[5];
m[8] = c*m[8]-s*m[9];
m[1]=c*m[1]+s*mv0;
m[5]=c*m[5]+s*mv4;
m[9]=c*m[9]+s*mv8;
}
function rotateX(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv1 = m[1], mv5 = m[5], mv9 = m[9];
m[1] = m[1]*c-m[2]*s;
m[5] = m[5]*c-m[6]*s;
m[9] = m[9]*c-m[10]*s;
m[2] = m[2]*c+mv1*s;
m[6] = m[6]*c+mv5*s;
m[10] = m[10]*c+mv9*s;
}
function rotateY(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];
m[0] = c*m[0]+s*m[2];
m[4] = c*m[4]+s*m[6];
m[8] = c*m[8]+s*m[10];
m[2] = c*m[2]-s*mv0;
m[6] = c*m[6]-s*mv4;
m[10] = c*m[10]-s*mv8;
}
/*================= Drawing ===========================*/
var time_old = 0;
var animate = function(time) {
var dt = time-time_old;
rotateZ(mov_matrix, dt*0.005);//time
rotateY(mov_matrix, dt*0.002);
rotateX(mov_matrix, dt*0.003);
time_old = time;
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);
gl.uniformMatrix4fv(Vmatrix, false, view_matrix);
gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
window.requestAnimationFrame(animate);
}
animate(0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
In this chapter, we will take an example to demonstrate how to draw a 3D cube that can be rotated using mouse controls.
The following program shows how to rotate a cube using mouse controls −
<!doctype html>
<html>
<body>
<canvas width = "570" height = "570" id = "my_Canvas"></canvas>
<script>
/*============= Creating a canvas ======================*/
var canvas = document.getElementById('my_Canvas');
gl = canvas.getContext('experimental-webgl');
/*========== Defining and storing the geometry ==========*/
var vertices = [
-1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,
-1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,
-1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,
1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,
-1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,
-1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1,
];
var colors = [
5,3,7, 5,3,7, 5,3,7, 5,3,7,
1,1,3, 1,1,3, 1,1,3, 1,1,3,
0,0,1, 0,0,1, 0,0,1, 0,0,1,
1,0,0, 1,0,0, 1,0,0, 1,0,0,
1,1,0, 1,1,0, 1,1,0, 1,1,0,
0,1,0, 0,1,0, 0,1,0, 0,1,0
];
var indices = [
0,1,2, 0,2,3, 4,5,6, 4,6,7,
8,9,10, 8,10,11, 12,13,14, 12,14,15,
16,17,18, 16,18,19, 20,21,22, 20,22,23
];
// Create and store data into vertex buffer
var vertex_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);
// Create and store data into color buffer
var color_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);
// Create and store data into index buffer
var index_buffer = gl.createBuffer ();
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);
/*=================== SHADERS =================== */
var vertCode = 'attribute vec3 position;'+
'uniform mat4 Pmatrix;'+
'uniform mat4 Vmatrix;'+
'uniform mat4 Mmatrix;'+
'attribute vec3 color;'+//the color of the point
'varying vec3 vColor;'+
'void main(void) { '+//pre-built function
'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+
'vColor = color;'+
'}';
var fragCode = 'precision mediump float;'+
'varying vec3 vColor;'+
'void main(void) {'+
'gl_FragColor = vec4(vColor, 1.);'+
'}';
var vertShader = gl.createShader(gl.VERTEX_SHADER);
gl.shaderSource(vertShader, vertCode);
gl.compileShader(vertShader);
var fragShader = gl.createShader(gl.FRAGMENT_SHADER);
gl.shaderSource(fragShader, fragCode);
gl.compileShader(fragShader);
var shaderprogram = gl.createProgram();
gl.attachShader(shaderprogram, vertShader);
gl.attachShader(shaderprogram, fragShader);
gl.linkProgram(shaderprogram);
/*======== Associating attributes to vertex shader =====*/
var _Pmatrix = gl.getUniformLocation(shaderprogram, "Pmatrix");
var _Vmatrix = gl.getUniformLocation(shaderprogram, "Vmatrix");
var _Mmatrix = gl.getUniformLocation(shaderprogram, "Mmatrix");
gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);
var _position = gl.getAttribLocation(shaderprogram, "position");
gl.vertexAttribPointer(_position, 3, gl.FLOAT, false,0,0);
gl.enableVertexAttribArray(_position);
gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);
var _color = gl.getAttribLocation(shaderprogram, "color");
gl.vertexAttribPointer(_color, 3, gl.FLOAT, false,0,0) ;
gl.enableVertexAttribArray(_color);
gl.useProgram(shaderprogram);
/*==================== MATRIX ====================== */
function get_projection(angle, a, zMin, zMax) {
var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5
return [
0.5/ang, 0 , 0, 0,
0, 0.5*a/ang, 0, 0,
0, 0, -(zMax+zMin)/(zMax-zMin), -1,
0, 0, (-2*zMax*zMin)/(zMax-zMin), 0
];
}
var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);
var mo_matrix = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 ];
var view_matrix = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 ];
view_matrix[14] = view_matrix[14]-6;
/*================= Mouse events ======================*/
var AMORTIZATION = 0.95;
var drag = false;
var old_x, old_y;
var dX = 0, dY = 0;
var mouseDown = function(e) {
drag = true;
old_x = e.pageX, old_y = e.pageY;
e.preventDefault();
return false;
};
var mouseUp = function(e){
drag = false;
};
var mouseMove = function(e) {
if (!drag) return false;
dX = (e.pageX-old_x)*2*Math.PI/canvas.width,
dY = (e.pageY-old_y)*2*Math.PI/canvas.height;
THETA+= dX;
PHI+=dY;
old_x = e.pageX, old_y = e.pageY;
e.preventDefault();
};
canvas.addEventListener("mousedown", mouseDown, false);
canvas.addEventListener("mouseup", mouseUp, false);
canvas.addEventListener("mouseout", mouseUp, false);
canvas.addEventListener("mousemove", mouseMove, false);
/*=========================rotation================*/
function rotateX(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv1 = m[1], mv5 = m[5], mv9 = m[9];
m[1] = m[1]*c-m[2]*s;
m[5] = m[5]*c-m[6]*s;
m[9] = m[9]*c-m[10]*s;
m[2] = m[2]*c+mv1*s;
m[6] = m[6]*c+mv5*s;
m[10] = m[10]*c+mv9*s;
}
function rotateY(m, angle) {
var c = Math.cos(angle);
var s = Math.sin(angle);
var mv0 = m[0], mv4 = m[4], mv8 = m[8];
m[0] = c*m[0]+s*m[2];
m[4] = c*m[4]+s*m[6];
m[8] = c*m[8]+s*m[10];
m[2] = c*m[2]-s*mv0;
m[6] = c*m[6]-s*mv4;
m[10] = c*m[10]-s*mv8;
}
/*=================== Drawing =================== */
var THETA = 0,
PHI = 0;
var time_old = 0;
var animate = function(time) {
var dt = time-time_old;
if (!drag) {
dX *= AMORTIZATION, dY*=AMORTIZATION;
THETA+=dX, PHI+=dY;
}
//set model matrix to I4
mo_matrix[0] = 1, mo_matrix[1] = 0, mo_matrix[2] = 0,
mo_matrix[3] = 0,
mo_matrix[4] = 0, mo_matrix[5] = 1, mo_matrix[6] = 0,
mo_matrix[7] = 0,
mo_matrix[8] = 0, mo_matrix[9] = 0, mo_matrix[10] = 1,
mo_matrix[11] = 0,
mo_matrix[12] = 0, mo_matrix[13] = 0, mo_matrix[14] = 0,
mo_matrix[15] = 1;
rotateY(mo_matrix, THETA);
rotateX(mo_matrix, PHI);
time_old = time;
gl.enable(gl.DEPTH_TEST);
// gl.depthFunc(gl.LEQUAL);
gl.clearColor(0.5, 0.5, 0.5, 0.9);
gl.clearDepth(1.0);
gl.viewport(0.0, 0.0, canvas.width, canvas.height);
gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);
gl.uniformMatrix4fv(_Pmatrix, false, proj_matrix);
gl.uniformMatrix4fv(_Vmatrix, false, view_matrix);
gl.uniformMatrix4fv(_Mmatrix, false, mo_matrix);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);
gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);
window.requestAnimationFrame(animate);
}
animate(0);
</script>
</body>
</html>
If you run this example, it will produce the following output −
10 Lectures
1 hours
Frahaan Hussain
28 Lectures
4 hours
Frahaan Hussain
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2351,
"s": 2047,
"text": "A few years back, Java applications – as a combination of applets and JOGL – were used to process 3D graphics on the Web by addressing the GPU (Graphical Processing Unit). As applets require a JVM to run, it became difficult to rely on Java applets. A few years later, people stopped using Java applets."
},
{
"code": null,
"e": 2669,
"s": 2351,
"text": "The Stage3D APIs provided by Adobe (Flash, AIR) offered GPU hardware accelerated architecture. Using these technologies, programmers could develop applications with 2D and 3D capabilities on web browsers as well as on IOS and Android platforms. Since Flash was a proprietary software, it was not used as web standard."
},
{
"code": null,
"e": 2798,
"s": 2669,
"text": "In March 2011, WebGL was released. It is an openware that can run without a JVM. It is completely controlled by the web browser."
},
{
"code": null,
"e": 2987,
"s": 2798,
"text": "The new release of HTML 5 has several features to support 3D graphics such as 2D Canvas, WebGL, SVG, 3D CSS transforms, and SMIL. In this tutorial, we will be covering the basics of WebGL."
},
{
"code": null,
"e": 3224,
"s": 2987,
"text": "OpenGL (Open Graphics Library) is a cross-language, cross-platform API for 2D and 3D graphics. It is a collection of commands. OpenGL4.5 is the latest version of OpenGL. The following table lists a set of technologies related to OpenGL."
},
{
"code": null,
"e": 3271,
"s": 3224,
"text": "Note − In WebGL, we use GLSL to write shaders."
},
{
"code": null,
"e": 3657,
"s": 3271,
"text": "WebGL (Web Graphics Library) is the new standard for 3D graphics on the Web, It is designed for the purpose of rendering 2D graphics and interactive 3D graphics. It is derived from OpenGL's ES 2.0 library which is a low-level 3D API for phones and other mobile devices. WebGL provides similar functionality of ES 2.0 (Embedded Systems) and performs well on modern 3D graphics hardware."
},
{
"code": null,
"e": 3900,
"s": 3657,
"text": "It is a JavaScript API that can be used with HTML5. WebGL code is written within the <canvas> tag of HTML5. It is a specification that allows Internet browsers access to Graphic Processing Units (GPUs) on those computers where they were used."
},
{
"code": null,
"e": 4017,
"s": 3900,
"text": "An American-Serbian software engineer named Vladimir Vukicevic did the foundation work and led the creation of WebGL"
},
{
"code": null,
"e": 4115,
"s": 4017,
"text": "In 2007, Vladimir started working on an OpenGL prototype for Canvas element of the HTML document."
},
{
"code": null,
"e": 4213,
"s": 4115,
"text": "In 2007, Vladimir started working on an OpenGL prototype for Canvas element of the HTML document."
},
{
"code": null,
"e": 4256,
"s": 4213,
"text": "In March 2011, Kronos Group created WebGL."
},
{
"code": null,
"e": 4299,
"s": 4256,
"text": "In March 2011, Kronos Group created WebGL."
},
{
"code": null,
"e": 4604,
"s": 4299,
"text": "Rendering is the process of generating an image from a model using computer programs. In graphics, a virtual scene is described using information like geometry, viewpoint, texture, lighting, and shading, which is passed through a render program. The output of this render program will be a digital image."
},
{
"code": null,
"e": 4639,
"s": 4604,
"text": "There are two types of rendering −"
},
{
"code": null,
"e": 4722,
"s": 4639,
"text": "Software Rendering − All the rendering calculations are done with the help of CPU."
},
{
"code": null,
"e": 4805,
"s": 4722,
"text": "Software Rendering − All the rendering calculations are done with the help of CPU."
},
{
"code": null,
"e": 4905,
"s": 4805,
"text": "Hardware Rendering − All the graphics computations are done by the GPU (Graphical processing unit)."
},
{
"code": null,
"e": 5005,
"s": 4905,
"text": "Hardware Rendering − All the graphics computations are done by the GPU (Graphical processing unit)."
},
{
"code": null,
"e": 5353,
"s": 5005,
"text": "Rendering can be done locally or remotely. If the image to be rendered is way too complex, then rendering is done remotely on a dedicated server having enough of hardware resources required to render complex scenes. It is also called as server-based rendering. Rendering can also be done locally by the CPU. It is called as client-based rendering."
},
{
"code": null,
"e": 5528,
"s": 5353,
"text": "WebGL follows a client-based rendering approach to render 3D scenes. All the processing required to obtain an image is performed locally using the client's graphics hardware."
},
{
"code": null,
"e": 6070,
"s": 5528,
"text": "According to NVIDIA, a GPU is \"a single chip processor with integrated transform, lighting, triangle setup/clipping, and rendering engines capable of processing a minimum of 10 million polygons per second.\" Unlike multi-core processors with a few cores optimized for sequential processing, a GPU consists of thousands of smaller cores that process parallel workloads efficiently. Therefore, the GPU accelerates the creation of images in a frame buffer (a portion of ram which contains a complete frame data) intended for output to a display."
},
{
"code": null,
"e": 6338,
"s": 6070,
"text": "In GPU accelerated computing, the application is loaded into the CPU. Whenever it encounters a compute-intensive portion of the code, then that portion of code will be loaded and run on the GPU. It gives the system the ability to process graphics in an efficient way."
},
{
"code": null,
"e": 6652,
"s": 6338,
"text": "GPU will have a separate memory and it runs multiple copies of a small portion of the code at a time. The GPU processes all the data which is in its local memory, not the central memory. Therefore, the data that is needed to be processed by the GPU should be loaded/copied to the GPU memory and then be processed."
},
{
"code": null,
"e": 6925,
"s": 6652,
"text": "In the systems having the above architecture, the communication overhead between the CPU and GPU should be reduced to achieve faster processing of 3D programs. For this, we have to copy all the data and keep it on the GPU, instead of communicating with the GPU repeatedly."
},
{
"code": null,
"e": 6991,
"s": 6925,
"text": "The following tables show a list of browsers that support WebGL −"
},
{
"code": null,
"e": 7032,
"s": 6991,
"text": "Here are the advantages of using WebGL −"
},
{
"code": null,
"e": 7310,
"s": 7032,
"text": "JavaScript programming − WebGL applications are written in JavaScript. Using these applications, you can directly interact with other elements of the HTML Document. You can also use other JavaScript libraries (e.g. JQuery) and HTML technologies to enrich the WebGL application."
},
{
"code": null,
"e": 7588,
"s": 7310,
"text": "JavaScript programming − WebGL applications are written in JavaScript. Using these applications, you can directly interact with other elements of the HTML Document. You can also use other JavaScript libraries (e.g. JQuery) and HTML technologies to enrich the WebGL application."
},
{
"code": null,
"e": 7727,
"s": 7588,
"text": "Increasing support with mobile browsers − WebGL also supports Mobile browsers such as iOS safari, Android Browser, and Chrome for Android."
},
{
"code": null,
"e": 7866,
"s": 7727,
"text": "Increasing support with mobile browsers − WebGL also supports Mobile browsers such as iOS safari, Android Browser, and Chrome for Android."
},
{
"code": null,
"e": 8005,
"s": 7866,
"text": "Open source − WebGL is an open source. You can access the source code of the library and understand how it works and how it was developed."
},
{
"code": null,
"e": 8144,
"s": 8005,
"text": "Open source − WebGL is an open source. You can access the source code of the library and understand how it works and how it was developed."
},
{
"code": null,
"e": 8491,
"s": 8144,
"text": "No need for compilation − JavaScript is a half-programming and half-HTML component. To execute this script, there is no need to compile the file. Instead, you can directly open the file using any of the browsers and check the result. Since WebGL applications are developed using JavaScript, there is no need to compile WebGL applications as well."
},
{
"code": null,
"e": 8838,
"s": 8491,
"text": "No need for compilation − JavaScript is a half-programming and half-HTML component. To execute this script, there is no need to compile the file. Instead, you can directly open the file using any of the browsers and check the result. Since WebGL applications are developed using JavaScript, there is no need to compile WebGL applications as well."
},
{
"code": null,
"e": 9010,
"s": 8838,
"text": "Automatic memory management − JavaScript supports automatic memory management. There is no need for manual allocation of memory. WebGL inherits this feature of JavaScript."
},
{
"code": null,
"e": 9182,
"s": 9010,
"text": "Automatic memory management − JavaScript supports automatic memory management. There is no need for manual allocation of memory. WebGL inherits this feature of JavaScript."
},
{
"code": null,
"e": 9364,
"s": 9182,
"text": "Easy to set up − Since WebGL is integrated within HTML 5, there is no need for additional set up. To write a WebGL application, all that you need is a text editor and a web browser."
},
{
"code": null,
"e": 9546,
"s": 9364,
"text": "Easy to set up − Since WebGL is integrated within HTML 5, there is no need for additional set up. To write a WebGL application, all that you need is a text editor and a web browser."
},
{
"code": null,
"e": 9676,
"s": 9546,
"text": "There is no need to set a different environment for WebGL. The browsers supporting WebGL have their own in-built setup for WebGL."
},
{
"code": null,
"e": 9962,
"s": 9676,
"text": "To create graphical applications on the web, HTML-5 provides a rich set of features such as 2D Canvas, WebGL, SVG, 3D CSS transforms, and SMIL. To write WebGL applications, we use the existing canvas element of HTML-5. This chapter provides an overview of the HTML-5 2D canvas element."
},
{
"code": null,
"e": 10151,
"s": 9962,
"text": "HTML-5 <canvas> provides an easy and powerful option to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions, or do simple (and not so simple) animations."
},
{
"code": null,
"e": 10300,
"s": 10151,
"text": "Here is a simple <canvas> element having only two specific attributes width and height plus all the core HTML-5 attributes like id, name, and class."
},
{
"code": null,
"e": 10421,
"s": 10300,
"text": "The syntax of HTML canvas tag is given below. You have to mention the name of the canvas inside double quotations (“ ”)."
},
{
"code": null,
"e": 10485,
"s": 10421,
"text": "<canvas id = \"mycanvas\" width = \"100\" height = \"100\"></canvas>\n"
},
{
"code": null,
"e": 10552,
"s": 10485,
"text": "The canvas tag has three attributes namely, id, width, and height."
},
{
"code": null,
"e": 10644,
"s": 10552,
"text": "Id − Id represents the identifier of the canvas element in the Document Object Model (DOM)."
},
{
"code": null,
"e": 10736,
"s": 10644,
"text": "Id − Id represents the identifier of the canvas element in the Document Object Model (DOM)."
},
{
"code": null,
"e": 10786,
"s": 10736,
"text": "Width − Width represents the width of the canvas."
},
{
"code": null,
"e": 10836,
"s": 10786,
"text": "Width − Width represents the width of the canvas."
},
{
"code": null,
"e": 10889,
"s": 10836,
"text": "Height − Height represents the height of the canvas."
},
{
"code": null,
"e": 10942,
"s": 10889,
"text": "Height − Height represents the height of the canvas."
},
{
"code": null,
"e": 11162,
"s": 10942,
"text": "These attributes determine the size of the canvas. If a programmer is not specifying them under the canvas tag, then browsers such as Firefox, Chrome, and Web Kit, by default, provide a canvas element of size 300 × 150."
},
{
"code": null,
"e": 11268,
"s": 11162,
"text": "The following code shows how to create a canvas. We have used CSS to give a colored border to the canvas."
},
{
"code": null,
"e": 11465,
"s": 11268,
"text": "<html>\n <head>\n <style>\n #mycanvas{border:1px solid red;}\n </style>\n </head>\n <body>\n <canvas id = \"mycanvas\" width = \"100\" height = \"100\"></canvas>\n </body>\n</html>"
},
{
"code": null,
"e": 11530,
"s": 11465,
"text": "On executing, the above code will produce the following output −"
},
{
"code": null,
"e": 11720,
"s": 11530,
"text": "The <canvas> is initially blank. To display something on the canvas element, we have to use a scripting language. This scripting language should access the rendering context and draw on it."
},
{
"code": null,
"e": 11907,
"s": 11720,
"text": "The canvas element has a DOM method called getContext(), which is used to obtain the rendering context and its drawing functions. This method takes one parameter, the type of context 2d."
},
{
"code": null,
"e": 12034,
"s": 11907,
"text": "The following code is to be written to get the required context. You can write this script inside the body tag as shown below."
},
{
"code": null,
"e": 12440,
"s": 12034,
"text": "<!DOCTYPE HTML>\n<html>\n <body>\n <canvas id = \"mycanvas\" width = \"600\" height = \"200\"></canvas>\n\n <script>\n var canvas = document.getElementById('mycanvas');\n var context = canvas.getContext('2d');\n\t\t\t\n context.font = '20pt Calibri';\n context.fillStyle = 'green';\n context.fillText('Welcome to Tutorialspoint', 70, 70);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 12505,
"s": 12440,
"text": "On executing, the above code will produce the following output −"
},
{
"code": null,
"e": 12587,
"s": 12505,
"text": "For more example on HTML-5 2D Canvas, check out the following link HTML-5 Canvas."
},
{
"code": null,
"e": 12833,
"s": 12587,
"text": "HTML5 Canvas is also used to write WebGL applications. To create a WebGL rendering context on the canvas element, you should pass the string experimental-webgl, instead of 2d to the canvas.getContext() method. Some browsers support only 'webgl'."
},
{
"code": null,
"e": 13115,
"s": 12833,
"text": "<!DOCTYPE html>\n<html>\n <canvas id = 'my_canvas'></canvas>\n\t\n <script>\n var canvas = document.getElementById('my_canvas');\n var gl = canvas.getContext('experimental-webgl');\n gl.clearColor(0.9,0.9,0.8,1);\n gl.clear(gl.COLOR_BUFFER_BIT);\n </script>\n</html>"
},
{
"code": null,
"e": 13180,
"s": 13115,
"text": "On executing, the above code will produce the following output −"
},
{
"code": null,
"e": 13532,
"s": 13180,
"text": "WebGL is mostly a low-level rasterization API rather than a 3D API. To draw an image using WebGL, you have to pass a vector representing the image. It then converts the given vector into pixel format using OpenGL SL and displays the image on the screen. Writing a WebGL application involves a set of steps which\nwe would be explaining in this chapter."
},
{
"code": null,
"e": 13944,
"s": 13532,
"text": "Just like any other 3D system, you will have x, y and z axes in WebGL, where the z axis signifies depth. The coordinates in WebGL are restricted to (1, 1, 1) and (-1, -1, - 1). It means − if you consider the screen projecting WebGL graphics as a cube, then one corner of the cube will be (1, 1, 1) and the opposite corner will be (-1, -1, -1). WebGL won’t display anything that is drawn beyond these boundaries."
},
{
"code": null,
"e": 14470,
"s": 13944,
"text": "The following diagram depicts the WebGL coordinate system. The z-axis signifies depth. A positive value of z indicates that the object is near the screen/viewer, whereas a negative value of z indicates that the object is away from the screen. Likewise, a positive value of x indicates that the object is to the right side of the screen and a negative value indicates the object is to the left side. Similarly, positive and negative values of y indicate whether the object is at the top or at the bottom portion of the screen."
},
{
"code": null,
"e": 14596,
"s": 14470,
"text": "After getting the WebGL context of the canvas object, you can start drawing graphical elements using WebGL API in JavaScript."
},
{
"code": null,
"e": 14673,
"s": 14596,
"text": "Here are some fundamental terms you need to know before starting with WebGL."
},
{
"code": null,
"e": 14965,
"s": 14673,
"text": "Generally, to draw objects such as a polygon, we mark the points on the plane and join them to form a desired polygon. A vertex is a point which defines the conjunction of the edges of a 3D object. It is represented by three floating point values each representing x, y, z axes respectively."
},
{
"code": null,
"e": 15086,
"s": 14965,
"text": "In the following example, we are drawing a triangle with the following vertices − (0.5, 0.5), (-0.5, 0.5), (-0.5, -0.5)."
},
{
"code": null,
"e": 15225,
"s": 15086,
"text": "Note − We have to store these vertices manually using JavaScript arrays and pass them to the WebGL rendering pipeline using vertex buffer."
},
{
"code": null,
"e": 15380,
"s": 15225,
"text": "In WebGL, numerical values are used to identify the vertices. These numerical values are known as indices. These indices are used to draw meshes in WebGL."
},
{
"code": null,
"e": 15514,
"s": 15380,
"text": "Note − Just like vertices, we store the indices using JavaScript arrays and pass them to WebGL rendering pipeline using index buffer."
},
{
"code": null,
"e": 15668,
"s": 15514,
"text": "Unlike OpenGL and JoGL, there are no predefined methods in WebGL to render the vertices directly. We have to store them manually using JavaScript arrays."
},
{
"code": null,
"e": 15717,
"s": 15668,
"text": "var vertices = [ 0.5, 0.5, 0.1,-0.5, 0.5,-0.5] \n"
},
{
"code": null,
"e": 15966,
"s": 15717,
"text": "Buffers are the memory areas of WebGL that hold the data. There are various buffers namely, drawing buffer, frame buffer, vetex buffer, and index buffer. The vertex buffer and index buffer are used to describe and process the geometry of the model."
},
{
"code": null,
"e": 16184,
"s": 15966,
"text": "Vertex buffer objects store data about the vertices, while Index buffer objects store data about the indices. After storing the vertices into arrays, we pass them to WegGL graphics pipeline using these Buffer objects."
},
{
"code": null,
"e": 16385,
"s": 16184,
"text": "Frame buffer is a portion of graphics memory that hold the scene data. This buffer contains details such as width and height of the surface (in pixels), color of each pixel, depth and stencil buffers."
},
{
"code": null,
"e": 16675,
"s": 16385,
"text": "To draw 2D or 3D objects, the WebGL API provides two methods namely, drawArrays() and drawElements(). These two methods accept a parameter called mode using which you can select the object you want to draw. The options provided by this field are restricted to points, lines, and triangles."
},
{
"code": null,
"e": 16871,
"s": 16675,
"text": "To draw a 3D object using these two methods, we have to construct one or more primitive polygons using points, lines, or triangles. Thereafter, using those primitive polygons, we can form a mesh."
},
{
"code": null,
"e": 17034,
"s": 16871,
"text": "A 3D object drawn using primitive polygons is called a mesh. WebGL offers several ways to draw 3D graphical objects, however users normally prefer to draw a mesh."
},
{
"code": null,
"e": 17150,
"s": 17034,
"text": "In the following example, you can observe that we have drawn a square using two triangles→ {1, 2, 3} and {4, 1, 3}."
},
{
"code": null,
"e": 17362,
"s": 17150,
"text": "We normally use triangles to construct meshes. Since WebGL uses GPU accelerated computing, the information about these triangles should be transferred from CPU to GPU which takes a lot of communication overhead."
},
{
"code": null,
"e": 17674,
"s": 17362,
"text": "WebGL provides a solution to reduce the communication overhead. Since it uses ES SL (Embedded System Shader Language) that runs on GPU, we write all the required programs to draw graphical elements on the client system using shader programs (the programs which we write using OpenGL ES Shading Language / GLSL)."
},
{
"code": null,
"e": 17922,
"s": 17674,
"text": "These shaders are the programs for GPU and the language used to write shader programs is GLSL. In these shaders, we define exactly how vertices, transformations, materials, lights, and camera interact with one another to create a particular image."
},
{
"code": null,
"e": 18123,
"s": 17922,
"text": "In short, it is a snippet that implements algorithms to get pixels for a mesh. We will discuss more about shaders in later chapters. There are two types of shaders − Vertex Shader and Fragment Shader."
},
{
"code": null,
"e": 18391,
"s": 18123,
"text": "Vertext shader is the program code called on every vertex. It is used to transform (move) the geometry (ex: triangle) from one place to another. It handles the data of each vertex (per-vertex data) such as vertex coordinates, normals, colors, and texture coordinates."
},
{
"code": null,
"e": 18557,
"s": 18391,
"text": "In the ES GL code of vertex shader, programmers have to define attributes to handle the data. These attributes point to a Vertex Buffer Object written in JavaScript."
},
{
"code": null,
"e": 18617,
"s": 18557,
"text": "The following tasks can be performed using vertex shaders −"
},
{
"code": null,
"e": 18639,
"s": 18617,
"text": "Vertex transformation"
},
{
"code": null,
"e": 18679,
"s": 18639,
"text": "Normal transformation and normalization"
},
{
"code": null,
"e": 18709,
"s": 18679,
"text": "Texture coordinate generation"
},
{
"code": null,
"e": 18743,
"s": 18709,
"text": "Texture coordinate transformation"
},
{
"code": null,
"e": 18752,
"s": 18743,
"text": "Lighting"
},
{
"code": null,
"e": 18779,
"s": 18752,
"text": "Color material application"
},
{
"code": null,
"e": 19023,
"s": 18779,
"text": "A mesh is formed by multiple triangles, and the surface of each of the triangles is known as a fragment. Fragment shader is the code that runs on all pixels of every fragment. It is written to calculate and fill the color on individual pixels."
},
{
"code": null,
"e": 19085,
"s": 19023,
"text": "The following tasks can be performed using Fragment shaders −"
},
{
"code": null,
"e": 19119,
"s": 19085,
"text": "Operations on interpolated values"
},
{
"code": null,
"e": 19134,
"s": 19119,
"text": "Texture access"
},
{
"code": null,
"e": 19154,
"s": 19134,
"text": "Texture application"
},
{
"code": null,
"e": 19158,
"s": 19154,
"text": "Fog"
},
{
"code": null,
"e": 19168,
"s": 19158,
"text": "Color sum"
},
{
"code": null,
"e": 19348,
"s": 19168,
"text": "The full form of OpenGL ES SL is OpenGL Embedded System Shading Language. To handle the data in the shader programs, ES SL provides three types of variables. They are as follows −"
},
{
"code": null,
"e": 19597,
"s": 19348,
"text": "Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices."
},
{
"code": null,
"e": 19846,
"s": 19597,
"text": "Attributes − These variables hold the input values of the vertex shader program. Attributes point to the vertex buffer objects that contains per-vertex data. Each time the vertex shader is invoked, the attributes point to VBO of different vertices."
},
{
"code": null,
"e": 20002,
"s": 19846,
"text": "Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color."
},
{
"code": null,
"e": 20158,
"s": 20002,
"text": "Uniforms − These variables hold the input data that is common for both vertex and fragment shaders, such as light position, texture coordinates, and color."
},
{
"code": null,
"e": 20258,
"s": 20158,
"text": "Varyings − These variables are used to pass the data from the vertex shader to the fragment shader."
},
{
"code": null,
"e": 20358,
"s": 20258,
"text": "Varyings − These variables are used to pass the data from the vertex shader to the fragment shader."
},
{
"code": null,
"e": 20435,
"s": 20358,
"text": "With this much basics, we will now move on to discuss the Graphics Pipeline."
},
{
"code": null,
"e": 20618,
"s": 20435,
"text": "To render 3D graphics, we have to follow a sequence of steps. These steps are known as graphics pipeline or rendering pipeline. The following diagram depicts WebGL graphics pipeline."
},
{
"code": null,
"e": 20711,
"s": 20618,
"text": "In the following sections, we will discuss one by one the role of each step in the pipeline."
},
{
"code": null,
"e": 20907,
"s": 20711,
"text": "While developing WebGL applications, we write Shader language code to communicate with the GPU. JavaScript is used to write the control code of the program, which includes the following actions −"
},
{
"code": null,
"e": 20978,
"s": 20907,
"text": "Initialize WebGL − JavaScript is used to initialize the WebGL context."
},
{
"code": null,
"e": 21049,
"s": 20978,
"text": "Initialize WebGL − JavaScript is used to initialize the WebGL context."
},
{
"code": null,
"e": 21127,
"s": 21049,
"text": "Create arrays − We create JavaScript arrays to hold the data of the geometry."
},
{
"code": null,
"e": 21205,
"s": 21127,
"text": "Create arrays − We create JavaScript arrays to hold the data of the geometry."
},
{
"code": null,
"e": 21303,
"s": 21205,
"text": "Buffer objects − We create buffer objects (vertex and index) by passing the arrays as parameters."
},
{
"code": null,
"e": 21401,
"s": 21303,
"text": "Buffer objects − We create buffer objects (vertex and index) by passing the arrays as parameters."
},
{
"code": null,
"e": 21470,
"s": 21401,
"text": "Shaders − We create, compile, and link the shaders using JavaScript."
},
{
"code": null,
"e": 21539,
"s": 21470,
"text": "Shaders − We create, compile, and link the shaders using JavaScript."
},
{
"code": null,
"e": 21648,
"s": 21539,
"text": "Attributes − We can create attributes, enable them, and associate them with buffer objects using JavaScript."
},
{
"code": null,
"e": 21757,
"s": 21648,
"text": "Attributes − We can create attributes, enable them, and associate them with buffer objects using JavaScript."
},
{
"code": null,
"e": 21821,
"s": 21757,
"text": "Uniforms − We can also associate the uniforms using JavaScript."
},
{
"code": null,
"e": 21885,
"s": 21821,
"text": "Uniforms − We can also associate the uniforms using JavaScript."
},
{
"code": null,
"e": 21964,
"s": 21885,
"text": "Transformation matrix − Using JavaScript, we can create transformation matrix."
},
{
"code": null,
"e": 22043,
"s": 21964,
"text": "Transformation matrix − Using JavaScript, we can create transformation matrix."
},
{
"code": null,
"e": 22276,
"s": 22043,
"text": "Initially we create the data for the required geometry and pass them to the shaders in the form of buffers. The attribute variable of the shader language points to the buffer objects, which are passed as inputs to the vertex shader."
},
{
"code": null,
"e": 22692,
"s": 22276,
"text": "When we start the rendering process by invoking the methods drawElements() and drawArray(), the vertex shader is executed for each vertex provided in the vertex buffer object. It calculates the position of each vertex of a primitive polygon and stores it in the varying gl_position. It also calculates the other attributes such as color, texture coordinates, and vertices that are normally associated with a vertex."
},
{
"code": null,
"e": 22868,
"s": 22692,
"text": "After calculating the position and other details of each vertex, the next phase is the primitive assembly stage. Here the triangles are assembled and passed to the rasterizer."
},
{
"code": null,
"e": 22977,
"s": 22868,
"text": "In the rasterization step, the pixels in the final image of the primitive are determined. It has two steps −"
},
{
"code": null,
"e": 23200,
"s": 22977,
"text": "Culling − Initially the orientation (is it front or back facing?) of the polygon is determined. All those triangles with improper orientation that are not visible in view area are discarded. This process is called culling."
},
{
"code": null,
"e": 23423,
"s": 23200,
"text": "Culling − Initially the orientation (is it front or back facing?) of the polygon is determined. All those triangles with improper orientation that are not visible in view area are discarded. This process is called culling."
},
{
"code": null,
"e": 23564,
"s": 23423,
"text": "Clipping − If a triangle is partly outside the view area, then the part outside the view area is removed. This process is known as clipping."
},
{
"code": null,
"e": 23705,
"s": 23564,
"text": "Clipping − If a triangle is partly outside the view area, then the part outside the view area is removed. This process is known as clipping."
},
{
"code": null,
"e": 23730,
"s": 23705,
"text": "The fragment shader gets"
},
{
"code": null,
"e": 23780,
"s": 23730,
"text": "data from the vertex shader in varying variables,"
},
{
"code": null,
"e": 23830,
"s": 23780,
"text": "primitives from the rasterization stage, and then"
},
{
"code": null,
"e": 23895,
"s": 23830,
"text": "calculates the color values for each pixel between the vertices."
},
{
"code": null,
"e": 24071,
"s": 23895,
"text": "The fragment shader stores the color values of every pixel in each fragment. These color values can be accessed during fragment operations, which we are going to discuss next."
},
{
"code": null,
"e": 24221,
"s": 24071,
"text": "Fragment operations are carried out after determining the color of each pixel in the primitive. These fragment operations may include the following −"
},
{
"code": null,
"e": 24227,
"s": 24221,
"text": "Depth"
},
{
"code": null,
"e": 24246,
"s": 24227,
"text": "Color buffer blend"
},
{
"code": null,
"e": 24256,
"s": 24246,
"text": "Dithering"
},
{
"code": null,
"e": 24413,
"s": 24256,
"text": "Once all the fragments are processed, a 2D image is formed and displayed on the screen. The frame buffer is the final destination of the rendering pipeline."
},
{
"code": null,
"e": 24618,
"s": 24413,
"text": "Frame buffer is a portion of graphics memory that hold the scene data. This buffer contains details such as width and height of the surface (in pixels), color of each pixel, and depth and stencil buffers."
},
{
"code": null,
"e": 24878,
"s": 24618,
"text": "We have discussed the basics of WebGL and the WebGL pipeline (a procedure followed to render Graphics applications). In this chapter, we are going to take a sample application to create a triangle using WebGL and observe the steps followed in the application."
},
{
"code": null,
"e": 24960,
"s": 24878,
"text": "WebGL application code is a combination of JavaScript and OpenGL Shader Language."
},
{
"code": null,
"e": 25011,
"s": 24960,
"text": "JavaScript is required to communicate with the CPU"
},
{
"code": null,
"e": 25075,
"s": 25011,
"text": "OpenGL Shader Language is required to communicate with the GPU."
},
{
"code": null,
"e": 25181,
"s": 25075,
"text": "Let us now take a simple example to learn how to use WebGL to draw a simple triangle with 2D coordinates."
},
{
"code": null,
"e": 28425,
"s": 25181,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"300\" height = \"300\" id = \"my_Canvas\"></canvas>\n\t\t\n <script>\n /* Step1: Prepare the canvas and get WebGL context */\n\n var canvas = document.getElementById('my_Canvas');\n var gl = canvas.getContext('experimental-webgl');\n\n /* Step2: Define the geometry and store it in buffer objects */\n\n var vertices = [-0.5, 0.5, -0.5, -0.5, 0.0, -0.5,];\n\n // Create a new buffer object\n var vertex_buffer = gl.createBuffer();\n\n // Bind an empty array buffer to it\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n \n // Pass the vertices data to the buffer\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n /* Step3: Create and compile Shader programs */\n\n // Vertex shader source code\n var vertCode =\n 'attribute vec2 coordinates;' + \n 'void main(void) {' + ' gl_Position = vec4(coordinates,0.0, 1.0);' + '}';\n\n //Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n\n //Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n //Compile the vertex shader\n gl.compileShader(vertShader);\n\n //Fragment shader source code\n var fragCode = 'void main(void) {' + 'gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' + '}';\n\n // Create fragment shader object\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode);\n\n // Compile the fragment shader\n gl.compileShader(fragShader);\n\n // Create a shader program object to store combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader); \n \n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /* Step 4: Associate the shader programs to buffer objects */\n\n //Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n //Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n //point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 2, gl.FLOAT, false, 0, 0);\n\n //Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n /* Step5: Drawing the required object (triangle) */\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST); \n \n // Clear the color buffer bit\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n // Draw the triangle\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 28464,
"s": 28425,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 28613,
"s": 28464,
"text": "If you observe the above program carefully, we have followed five sequential steps to draw a simple triangle using WebGL. The steps are as follows −"
},
{
"code": null,
"e": 28673,
"s": 28613,
"text": "Step 1 − Prepare the canvas and get WebGL rendering context"
},
{
"code": null,
"e": 28751,
"s": 28673,
"text": "We get the current HTML canvas object and obtain its WebGL rendering context."
},
{
"code": null,
"e": 28811,
"s": 28751,
"text": "Step 2 − Define the geometry and store it in buffer objects"
},
{
"code": null,
"e": 29172,
"s": 28811,
"text": "We define the attributes of the geometry such as vertices, indices, color, etc., and store them in the JavaScript arrays. Then, we create one or more buffer objects and pass the arrays containing the data to the respective buffer object. In the example, we store the vertices of the triangle in a JavaScript array and pass this array to a vertex buffer object."
},
{
"code": null,
"e": 29216,
"s": 29172,
"text": "Step 3 − Create and compile Shader programs"
},
{
"code": null,
"e": 29344,
"s": 29216,
"text": "We write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 29403,
"s": 29344,
"text": "Step 4 − Associate the shader programs with buffer objects"
},
{
"code": null,
"e": 29468,
"s": 29403,
"text": "We associate the buffer objects and the combined shader program."
},
{
"code": null,
"e": 29516,
"s": 29468,
"text": "Step 5 − Drawing the required object (triangle)"
},
{
"code": null,
"e": 29761,
"s": 29516,
"text": "This step includes operations such as clearing the color, clearing the buffer bit, enabling the depth test, setting the view port, etc. Finally, you need to draw the required primitives using one of the methods − drawArrays() or drawElements()."
},
{
"code": null,
"e": 29817,
"s": 29761,
"text": "All these steps are explained further in this tutorial."
},
{
"code": null,
"e": 30061,
"s": 29817,
"text": "To write a WebGL application, first step is to get the WebGL rendering context object. This object interacts with the WebGL drawing buffer and can call all the WebGL methods. The following operations are performed to obtain the WebGL context −"
},
{
"code": null,
"e": 30085,
"s": 30061,
"text": "Create an HTML-5 canvas"
},
{
"code": null,
"e": 30103,
"s": 30085,
"text": "Get the canvas ID"
},
{
"code": null,
"e": 30116,
"s": 30103,
"text": "Obtain WebGL"
},
{
"code": null,
"e": 30397,
"s": 30116,
"text": "In Chapter 5, we discussed how to create an HTML-5 canvas element. Within the body of the HTML-5 document, write a canvas, give it a name, and pass it as a parameter to the attribute id. You can define the dimensions of the canvas using the width and height attributes (optional)."
},
{
"code": null,
"e": 30626,
"s": 30397,
"text": "The following example shows how to create a canvas element with the dimensions 500 × 500. We have created a border to the canvas using CSS for visibility. Copy and paste the following code in a file with the name my_canvas.html."
},
{
"code": null,
"e": 30840,
"s": 30626,
"text": "<!DOCTYPE HTML>\n<html>\n <head>\n <style>\n #mycanvas{border:1px solid blue;}\n </style>\n </head>\n <body>\n <canvas id = \"mycanvas\" width = \"300\" height = \"300\"></canvas>\n </body>\n</html>"
},
{
"code": null,
"e": 30879,
"s": 30840,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 31045,
"s": 30879,
"text": "After creating the canvas, you have to get the WebGL context. The first thing to do to obtain a WebGL drawing context is to get the id of the current canvas element."
},
{
"code": null,
"e": 31233,
"s": 31045,
"text": "Canvas ID is acquired by calling the DOM (Document Object Model) method getElementById(). This method accepts a string value as parameter, so we pass the name of the current canvas to it."
},
{
"code": null,
"e": 31322,
"s": 31233,
"text": "For example, if the canvas name is my_canvas, then canvas ID is obtained as shown below−"
},
{
"code": null,
"e": 31374,
"s": 31322,
"text": "var canvas = document.getElementById('my_Canvas');\n"
},
{
"code": null,
"e": 31579,
"s": 31374,
"text": "To get the WebGLRenderingContext object (or WebGL Drawing context object or simply WebGL context), call the getContext() method of the current HTMLCanvasElement. The syntax of getContext() is as follows −"
},
{
"code": null,
"e": 31631,
"s": 31579,
"text": "canvas.getContext(contextType, contextAttributes);\n"
},
{
"code": null,
"e": 31843,
"s": 31631,
"text": "Pass the strings webgl or experimental-webgl as the contentType. The contextAttributes parameter is optional. (While proceeding with this step, make sure your browser implements WebGL version 1 (OpenGL ES 2.0))."
},
{
"code": null,
"e": 31985,
"s": 31843,
"text": "The following code snippet shows how to obtain the WebGL rendering context. Here gl is the reference variable to the obtained context object."
},
{
"code": null,
"e": 32087,
"s": 31985,
"text": "var canvas = document.getElementById('my_Canvas');\nvar gl = canvas.getContext('experimental-webgl');\n"
},
{
"code": null,
"e": 32227,
"s": 32087,
"text": "The parameter WebGLContextAttributes is not mandatory. This parameter provides various options that accept Boolean values as listed below −"
},
{
"code": null,
"e": 32233,
"s": 32227,
"text": "Alpha"
},
{
"code": null,
"e": 32298,
"s": 32233,
"text": "If its value is true, it provides an alpha buffer to the canvas."
},
{
"code": null,
"e": 32329,
"s": 32298,
"text": "By default, its value is true."
},
{
"code": null,
"e": 32335,
"s": 32329,
"text": "depth"
},
{
"code": null,
"e": 32438,
"s": 32335,
"text": "If its value is true, you will get a drawing buffer which contains a depth buffer of at least 16 bits."
},
{
"code": null,
"e": 32469,
"s": 32438,
"text": "By default, its value is true."
},
{
"code": null,
"e": 32477,
"s": 32469,
"text": "stencil"
},
{
"code": null,
"e": 32581,
"s": 32477,
"text": "If its value is true, you will get a drawing buffer which contains a stencil buffer of at least 8 bits."
},
{
"code": null,
"e": 32613,
"s": 32581,
"text": "By default, its value is false."
},
{
"code": null,
"e": 32623,
"s": 32613,
"text": "antialias"
},
{
"code": null,
"e": 32705,
"s": 32623,
"text": "If its value is true, you will get a drawing buffer which performs anti-aliasing."
},
{
"code": null,
"e": 32736,
"s": 32705,
"text": "By default, its value is true."
},
{
"code": null,
"e": 32755,
"s": 32736,
"text": "premultipliedAlpha"
},
{
"code": null,
"e": 32856,
"s": 32755,
"text": "If its value is true, you will get a drawing buffer which contains colors with pre-multiplied alpha."
},
{
"code": null,
"e": 32887,
"s": 32856,
"text": "By default, its value is true."
},
{
"code": null,
"e": 32909,
"s": 32887,
"text": "preserveDrawingBuffer"
},
{
"code": null,
"e": 33038,
"s": 32909,
"text": "If its value is true, the buffers will not be cleared and will preserve their values until cleared or overwritten by the author."
},
{
"code": null,
"e": 33070,
"s": 33038,
"text": "By default, its value is false."
},
{
"code": null,
"e": 33194,
"s": 33070,
"text": "The following code snippet shows how to create a WebGL context with a stencil buffer, which will not perform anti-aliasing."
},
{
"code": null,
"e": 33323,
"s": 33194,
"text": "var canvas = document.getElementById('canvas1');\nvar context = canvas.getContext('webgl', { antialias: false, stencil: true });\n"
},
{
"code": null,
"e": 33478,
"s": 33323,
"text": "At the time of creating the WebGLRenderingContext, a drawing buffer is created. The Context object manages OpenGL state and renders to the drawing buffer."
},
{
"code": null,
"e": 33719,
"s": 33478,
"text": "It is the principal interface in WebGL. It represents the WebGL drawing context. This interface contains all the methods used to perform various tasks on the Drawing buffer. The attributes of this interface are given in the following table."
},
{
"code": null,
"e": 33726,
"s": 33719,
"text": "Canvas"
},
{
"code": null,
"e": 33795,
"s": 33726,
"text": "This is a reference to the canvas element that created this context."
},
{
"code": null,
"e": 33814,
"s": 33795,
"text": "drawingBufferWidth"
},
{
"code": null,
"e": 33945,
"s": 33814,
"text": "This attribute represents the actual width of the drawing buffer. It may differ from the width attribute of the HTMLCanvasElement."
},
{
"code": null,
"e": 33965,
"s": 33945,
"text": "drawingBufferHeight"
},
{
"code": null,
"e": 34098,
"s": 33965,
"text": "This attribute represents the actual height of the drawing buffer. It may differ from the height attribute of the HTMLCanvasElement."
},
{
"code": null,
"e": 34524,
"s": 34098,
"text": "After obtaining the WebGL context, you have to define the geometry for the primitive (object you want to draw) and store it. In WebGL, we define the details of a geometry – for example, vertices, indices, color of the primitive – using JavaScript arrays. To pass these details to the shader programs, we have to create the buffer objects and store (attach) the JavaScript arrays containing the data in the respective buffers."
},
{
"code": null,
"e": 34636,
"s": 34524,
"text": "Note: Later, these buffer objects will be associated with the attributes of the shader program (vertex shader)."
},
{
"code": null,
"e": 34778,
"s": 34636,
"text": "A 2D or 3D model drawn using vertices is called a mesh. Each facet in a mesh is called a polygon and a polygon is made of 3 or more vertices."
},
{
"code": null,
"e": 35070,
"s": 34778,
"text": "To draw models in the WebGL rendering context, you have to define the vertices and indices using JavaScript arrays. For example, if we want to create a triangle which lies on the coordinates {(5,5), (-5,5), (-5,-5)} as shown in the diagram, then you can create an array for the vertices as −"
},
{
"code": null,
"e": 35170,
"s": 35070,
"text": "var vertices = [\n 0.5,0.5, //Vertex 1\n 0.5,-0.5, //Vertex 2\n -0.5,-0.5, //Vertex 3\n]; \n"
},
{
"code": null,
"e": 35303,
"s": 35170,
"text": "Similarly, you can create an array for the indices. Indices for the above triangle indices will be [0, 1, 2] and can be defined as −"
},
{
"code": null,
"e": 35328,
"s": 35303,
"text": "var indices = [ 0,1,2 ]\n"
},
{
"code": null,
"e": 35585,
"s": 35328,
"text": "For a better understanding of indices, consider more complex models like square. We can represent a square as a set of two triangles. If (0,3,1) and (3,1,2) are the two triangles using which we intend to draw a square, then the indices will be defined as −"
},
{
"code": null,
"e": 35615,
"s": 35585,
"text": "var indices = [0,3,1,3,1,2];\n"
},
{
"code": null,
"e": 35622,
"s": 35615,
"text": "Note −"
},
{
"code": null,
"e": 35689,
"s": 35622,
"text": "For drawing primitives, WebGL provides the following two methods −"
},
{
"code": null,
"e": 35792,
"s": 35689,
"text": "drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays."
},
{
"code": null,
"e": 35895,
"s": 35792,
"text": "drawArrays() − While using this method, we pass the vertices of the primitive using JavaScript arrays."
},
{
"code": null,
"e": 36012,
"s": 35895,
"text": "drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array."
},
{
"code": null,
"e": 36129,
"s": 36012,
"text": "drawElements() − While using this method, we pass both vertices and indices of the primitive using JavaScript array."
},
{
"code": null,
"e": 36355,
"s": 36129,
"text": "A buffer object is a mechanism provided by WebGL that indicates a memory area allocated in the system. In these buffer objects, you can store data of the model you want to draw, corresponding to vertices, indices, color, etc."
},
{
"code": null,
"e": 36612,
"s": 36355,
"text": "Using these buffer objects, you can pass multiple data to the shader program (vertex shader) through one of its attribute variables. Since these buffer objects reside in the GPU memory, they can be rendered directly, which in turn improves the performance."
},
{
"code": null,
"e": 36683,
"s": 36612,
"text": "To process geometry, there are two types of buffer objects. They are −"
},
{
"code": null,
"e": 36951,
"s": 36683,
"text": "Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates."
},
{
"code": null,
"e": 37219,
"s": 36951,
"text": "Vertex buffer object (VBO) − It holds the per-vertex data of the graphical model that is going to be rendered. We use vertex buffer objects in WebGL to store and process the data regarding vertices such as vertex coordinates, normals, colors, and texture coordinates."
},
{
"code": null,
"e": 37335,
"s": 37219,
"text": "Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered."
},
{
"code": null,
"e": 37451,
"s": 37335,
"text": "Index buffer objects (IBO) − It holds the indices (index data) of the graphical model that is going to be rendered."
},
{
"code": null,
"e": 37708,
"s": 37451,
"text": "After defining the required geometry and storing them in JavaScript arrays, you need to pass these arrays to the buffer objects, from where the data will be passed to the shader programs. The following steps are to be followed to store data in the buffers."
},
{
"code": null,
"e": 37732,
"s": 37708,
"text": "Create an empty buffer."
},
{
"code": null,
"e": 37756,
"s": 37732,
"text": "Create an empty buffer."
},
{
"code": null,
"e": 37810,
"s": 37756,
"text": "Bind an appropriate array object to the empty buffer."
},
{
"code": null,
"e": 37864,
"s": 37810,
"text": "Bind an appropriate array object to the empty buffer."
},
{
"code": null,
"e": 37942,
"s": 37864,
"text": "Pass the data (vertices/indices) to the buffer using one of the typed arrays."
},
{
"code": null,
"e": 38020,
"s": 37942,
"text": "Pass the data (vertices/indices) to the buffer using one of the typed arrays."
},
{
"code": null,
"e": 38050,
"s": 38020,
"text": "Unbind the buffer (Optional)."
},
{
"code": null,
"e": 38080,
"s": 38050,
"text": "Unbind the buffer (Optional)."
},
{
"code": null,
"e": 38293,
"s": 38080,
"text": "To create an empty buffer object, WebGL provides a method called createBuffer(). This method returns a newly created buffer object, if the creation was successful; else it returns a null value in case of failure."
},
{
"code": null,
"e": 38490,
"s": 38293,
"text": "WebGL operates as a state machine. Once a buffer is created, any subsequent buffer operation will be executed on the current buffer until we unbound it. Use the following code to create a buffer −"
},
{
"code": null,
"e": 38530,
"s": 38490,
"text": "var vertex_buffer = gl.createBuffer();\n"
},
{
"code": null,
"e": 38596,
"s": 38530,
"text": "Note − gl is the reference variable to the current WebGL context."
},
{
"code": null,
"e": 38758,
"s": 38596,
"text": "After creating an empty buffer object, you need to bind an appropriate array buffer (target) to it. WebGL provides a method called bindBuffer() for this purpose."
},
{
"code": null,
"e": 38808,
"s": 38758,
"text": "The syntax of bindBuffer() method is as follows −"
},
{
"code": null,
"e": 38854,
"s": 38808,
"text": "void bindBuffer (enum target, Object buffer)\n"
},
{
"code": null,
"e": 38919,
"s": 38854,
"text": "This method accepts two parameters and they are discussed below."
},
{
"code": null,
"e": 39115,
"s": 38919,
"text": "target − The first variable is an enum value representing the type of the buffer we want to bind to the empty buffer. You have two predefined enum values as options for this parameter. They are −"
},
{
"code": null,
"e": 39158,
"s": 39115,
"text": "ARRAY_BUFFER which represents vertex data."
},
{
"code": null,
"e": 39201,
"s": 39158,
"text": "ARRAY_BUFFER which represents vertex data."
},
{
"code": null,
"e": 39251,
"s": 39201,
"text": "ELEMENT_ARRAY_BUFFER which represents index data."
},
{
"code": null,
"e": 39301,
"s": 39251,
"text": "ELEMENT_ARRAY_BUFFER which represents index data."
},
{
"code": null,
"e": 39495,
"s": 39301,
"text": "Object buffer − The second one is the reference variable to the buffer object created in the previous step. The reference variable can be of a vertex buffer object or of an index buffer object."
},
{
"code": null,
"e": 39564,
"s": 39495,
"text": "The following code snippet shows how to use the bindBuffer() method."
},
{
"code": null,
"e": 39775,
"s": 39564,
"text": "//vertex buffer\nvar vertex_buffer = gl.createBuffer();\ngl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n//Index buffer\nvar Index_Buffer = gl.createBuffer();\ngl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n"
},
{
"code": null,
"e": 40036,
"s": 39775,
"text": "The next step is to pass the data (vertices/indices) to the buffer. Till now data is in the form of an array and before passing it to the buffer, we need to wrap it in one of the WebGL typed arrays. WebGL provides a method named bufferData() for this purpose."
},
{
"code": null,
"e": 40086,
"s": 40036,
"text": "The syntax of bufferData() method is as follows −"
},
{
"code": null,
"e": 40142,
"s": 40086,
"text": "void bufferData (enum target, Object data, enum usage)\n"
},
{
"code": null,
"e": 40210,
"s": 40142,
"text": "This method accepts three parameters and they are discussed below −"
},
{
"code": null,
"e": 40343,
"s": 40210,
"text": "target − The first parameter is an enum value representing the type of the array buffer we used.The options for this parameter are −"
},
{
"code": null,
"e": 40386,
"s": 40343,
"text": "ARRAY_BUFFER which represents vertex data."
},
{
"code": null,
"e": 40429,
"s": 40386,
"text": "ARRAY_BUFFER which represents vertex data."
},
{
"code": null,
"e": 40479,
"s": 40429,
"text": "ELEMENT_ARRAY_BUFFER which represents index data."
},
{
"code": null,
"e": 40529,
"s": 40479,
"text": "ELEMENT_ARRAY_BUFFER which represents index data."
},
{
"code": null,
"e": 40693,
"s": 40529,
"text": "Object data − The second parameter is the object value that contains the data to be written to the buffer object. Here we have to pass the data using typed arrays."
},
{
"code": null,
"e": 40895,
"s": 40693,
"text": "Usage − The third parameter of this method is an enum variable that specifies how to use the buffer object data (stored data) to draw shapes. There are three options for this parameter as listed below."
},
{
"code": null,
"e": 40961,
"s": 40895,
"text": "gl.STATIC_DRAW − Data will be specified once and used many times."
},
{
"code": null,
"e": 41027,
"s": 40961,
"text": "gl.STATIC_DRAW − Data will be specified once and used many times."
},
{
"code": null,
"e": 41094,
"s": 41027,
"text": "gl.STREAM_DRAW − Data will be specified once and used a few times."
},
{
"code": null,
"e": 41161,
"s": 41094,
"text": "gl.STREAM_DRAW − Data will be specified once and used a few times."
},
{
"code": null,
"e": 41234,
"s": 41161,
"text": "gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times."
},
{
"code": null,
"e": 41307,
"s": 41234,
"text": "gl.DYNAMIC_DRAW − Data will be specified repeatedly and used many times."
},
{
"code": null,
"e": 41467,
"s": 41307,
"text": "The following code snippet shows how to use the bufferData() method. Assume vertices and indices are the arrays holding the vertex and index data respectively."
},
{
"code": null,
"e": 41658,
"s": 41467,
"text": "//vertex buffer\ngl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n//Index buffer\ngl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n"
},
{
"code": null,
"e": 42049,
"s": 41658,
"text": "WebGL provides a special type of array called typed arrays to transfer the data elements such as index vertex and texture. These typed arrays store large quantities of data and process them in native binary format which results in better performance. The typed arrays used by WebGL are Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, UInt32Array, Float32Array, and Float64Array."
},
{
"code": null,
"e": 42054,
"s": 42049,
"text": "Note"
},
{
"code": null,
"e": 42156,
"s": 42054,
"text": "Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array."
},
{
"code": null,
"e": 42258,
"s": 42156,
"text": "Generally, for storing vertex data, we use Float32Array; and to store index data, we use Uint16Array."
},
{
"code": null,
"e": 42333,
"s": 42258,
"text": "You can create typed arrays just like JavaScript arrays using new keyword."
},
{
"code": null,
"e": 42408,
"s": 42333,
"text": "You can create typed arrays just like JavaScript arrays using new keyword."
},
{
"code": null,
"e": 42558,
"s": 42408,
"text": "It is recommended that you unbind the buffers after using them. It can be done by passing a null value in place of the buffer object, as shown below."
},
{
"code": null,
"e": 42605,
"s": 42558,
"text": "gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n"
},
{
"code": null,
"e": 42673,
"s": 42605,
"text": "WebGL provides the following methods to perform buffer operations −"
},
{
"code": null,
"e": 42718,
"s": 42673,
"text": "void bindBuffer (enum target, Object buffer)"
},
{
"code": null,
"e": 42762,
"s": 42718,
"text": "target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER"
},
{
"code": null,
"e": 42814,
"s": 42762,
"text": "void bufferData(enum target, long size, enum usage)"
},
{
"code": null,
"e": 42858,
"s": 42814,
"text": "target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER"
},
{
"code": null,
"e": 42905,
"s": 42858,
"text": "usage − STATIC_DRAW, STREAM_DRAW, DYNAMIC_DRAW"
},
{
"code": null,
"e": 42960,
"s": 42905,
"text": "void bufferData (enum target, Object data, enum usage)"
},
{
"code": null,
"e": 43008,
"s": 42960,
"text": "target and usage − Same as for bufferData above"
},
{
"code": null,
"e": 43066,
"s": 43008,
"text": "void bufferSubData(enum target, long offset, Object data)"
},
{
"code": null,
"e": 43110,
"s": 43066,
"text": "target − ARRAY_BUFFER, ELEMENT_ARRAY_BUFFER"
},
{
"code": null,
"e": 43158,
"s": 43110,
"text": "any getBufferParameter(enum target, enum pname)"
},
{
"code": null,
"e": 43203,
"s": 43158,
"text": "target − ARRAY_BUFFER, ELEMENT_ ARRAY_BUFFER"
},
{
"code": null,
"e": 43237,
"s": 43203,
"text": "pname − BUFFER_SIZE, BUFFER_USAGE"
},
{
"code": null,
"e": 43431,
"s": 43237,
"text": "Shaders are the programs that run on GPU. Shaders are written in OpenGL ES Shader Language (known as ES SL). ES SL has variables of its own, data types, qualifiers, built-in inputs and outputs."
},
{
"code": null,
"e": 43504,
"s": 43431,
"text": "The following table lists the basic data types provided by OpenGL ES SL."
},
{
"code": null,
"e": 43509,
"s": 43504,
"text": "void"
},
{
"code": null,
"e": 43536,
"s": 43509,
"text": "Represents an empty value."
},
{
"code": null,
"e": 43541,
"s": 43536,
"text": "bool"
},
{
"code": null,
"e": 43564,
"s": 43541,
"text": "Accepts true or false."
},
{
"code": null,
"e": 43568,
"s": 43564,
"text": "int"
},
{
"code": null,
"e": 43604,
"s": 43568,
"text": "This is a signed integer data type."
},
{
"code": null,
"e": 43610,
"s": 43604,
"text": "float"
},
{
"code": null,
"e": 43647,
"s": 43610,
"text": "This is a floating scalar data type."
},
{
"code": null,
"e": 43664,
"s": 43647,
"text": "vec2, vec3, vec4"
},
{
"code": null,
"e": 43698,
"s": 43664,
"text": "n-component floating point vector"
},
{
"code": null,
"e": 43718,
"s": 43698,
"text": "bvec2, bvec3, bvec4"
},
{
"code": null,
"e": 43733,
"s": 43718,
"text": "Boolean vector"
},
{
"code": null,
"e": 43753,
"s": 43733,
"text": "ivec2, ivec3, ivec4"
},
{
"code": null,
"e": 43775,
"s": 43753,
"text": "signed integer vector"
},
{
"code": null,
"e": 43792,
"s": 43775,
"text": "mat2, mat3, mat4"
},
{
"code": null,
"e": 43819,
"s": 43792,
"text": "2x2, 3x3, 4x4 float matrix"
},
{
"code": null,
"e": 43829,
"s": 43819,
"text": "sampler2D"
},
{
"code": null,
"e": 43849,
"s": 43829,
"text": "Access a 2D texture"
},
{
"code": null,
"e": 43861,
"s": 43849,
"text": "samplerCube"
},
{
"code": null,
"e": 43888,
"s": 43861,
"text": "Access cube mapped texture"
},
{
"code": null,
"e": 43938,
"s": 43888,
"text": "There are three main qualifiers in OpenGL ES SL −"
},
{
"code": null,
"e": 43948,
"s": 43938,
"text": "attribute"
},
{
"code": null,
"e": 44115,
"s": 43948,
"text": "This qualifier acts as a link between a vertex shader and OpenGL ES for per-vertex data. The value of this attribute changes for every execution of the vertex shader."
},
{
"code": null,
"e": 44123,
"s": 44115,
"text": "uniform"
},
{
"code": null,
"e": 44344,
"s": 44123,
"text": "This qualifier links shader programs and the WebGL application. Unlike attribute qualifier, the values of uniforms do not change. Uniforms are read-only; you can use them with any basic data types, to declare a variable."
},
{
"code": null,
"e": 44382,
"s": 44344,
"text": "Example − uniform vec4 lightPosition;"
},
{
"code": null,
"e": 44390,
"s": 44382,
"text": "varying"
},
{
"code": null,
"e": 44586,
"s": 44390,
"text": "This qualifier forms a link between a vertex shader and fragment shader for interpolated data. It can be used with the following data types − float, vec2, vec3, vec4, mat2, mat3, mat4, or arrays."
},
{
"code": null,
"e": 44617,
"s": 44586,
"text": "Example − varying vec3 normal;"
},
{
"code": null,
"e": 44880,
"s": 44617,
"text": "Vertex shader is a program code, which is called on every vertex. It transforms (move) the geometry (ex: triangle) from one place to other. It handles the data of each vertex (per-vertex data) such as vertex coordinates, normals, colors, and texture coordinates."
},
{
"code": null,
"e": 45135,
"s": 44880,
"text": "In the ES GL code of vertex shader, programmers have to define attributes to handle data. These attributes point to a Vertex Buffer Object written In JavaScript. The following tasks can be performed using vertex shaders along with vertex transformation −"
},
{
"code": null,
"e": 45157,
"s": 45135,
"text": "Vertex transformation"
},
{
"code": null,
"e": 45197,
"s": 45157,
"text": "Normal transformation and normalization"
},
{
"code": null,
"e": 45227,
"s": 45197,
"text": "Texture coordinate generation"
},
{
"code": null,
"e": 45261,
"s": 45227,
"text": "Texture coordinate transformation"
},
{
"code": null,
"e": 45270,
"s": 45261,
"text": "Lighting"
},
{
"code": null,
"e": 45297,
"s": 45270,
"text": "Color material application"
},
{
"code": null,
"e": 45374,
"s": 45297,
"text": "OpenGL ES SL provides the following predefined variables for vertex shader −"
},
{
"code": null,
"e": 45398,
"s": 45374,
"text": "highp vec4 gl_Position;"
},
{
"code": null,
"e": 45432,
"s": 45398,
"text": "Holds the position of the vertex."
},
{
"code": null,
"e": 45460,
"s": 45432,
"text": "mediump float gl_PointSize;"
},
{
"code": null,
"e": 45534,
"s": 45460,
"text": "Holds the transformed point size. The units for this variable are pixels."
},
{
"code": null,
"e": 45636,
"s": 45534,
"text": "Take a look at the following sample code of a vertex shader. It processes the vertices of a triangle."
},
{
"code": null,
"e": 45732,
"s": 45636,
"text": "attribute vec2 coordinates;\n\nvoid main(void) {\n gl_Position = vec4(coordinates, 0.0, 1.0);\n};"
},
{
"code": null,
"e": 46046,
"s": 45732,
"text": "If you observe the above code carefully, we have declared an attribute variable with the name coordinates. (This variable will be associated with the Vertex Buffer Object using the method getAttribLocation(). The attribute coordinates is passed as a parameter to this method along with the shader program object.)"
},
{
"code": null,
"e": 46138,
"s": 46046,
"text": "In the second step of the given vertex shader program, the gl_position variable is defined."
},
{
"code": null,
"e": 46441,
"s": 46138,
"text": "gl_Position is the predefined variable which is available only in the vertex shader program. It contains the vertex position. In the above code, the coordinates attribute is passed in the form of a vector. As vertex shader is a per-vertex operation, the gl_position value is calculated for each vertex."
},
{
"code": null,
"e": 46629,
"s": 46441,
"text": "Later, the gl_position value is used by primitive assembly, clipping, culling, and other fixed functionality operations that operate on the primitives after the vertex processing is over."
},
{
"code": null,
"e": 46764,
"s": 46629,
"text": "We can write vertex shader programs for all possible operations of vertex shader, which we will discuss individually in this tutorial."
},
{
"code": null,
"e": 47070,
"s": 46764,
"text": "A mesh is formed by multiple triangles, and the surface of the each triangle is known as a fragment. A fragment shader is the code that runs on every pixel on each fragment. This is written to calculate and fill the color on individual pixels. The following tasks can be performed using fragment shaders −"
},
{
"code": null,
"e": 47104,
"s": 47070,
"text": "Operations on interpolated values"
},
{
"code": null,
"e": 47119,
"s": 47104,
"text": "Texture access"
},
{
"code": null,
"e": 47139,
"s": 47119,
"text": "Texture application"
},
{
"code": null,
"e": 47143,
"s": 47139,
"text": "Fog"
},
{
"code": null,
"e": 47153,
"s": 47143,
"text": "Color sum"
},
{
"code": null,
"e": 47232,
"s": 47153,
"text": "OpenGL ES SL provides the following predefined variables for fragment shader −"
},
{
"code": null,
"e": 47259,
"s": 47232,
"text": "mediump vec4 gl_FragCoord;"
},
{
"code": null,
"e": 47312,
"s": 47259,
"text": "Holds the fragment position within the frame buffer."
},
{
"code": null,
"e": 47333,
"s": 47312,
"text": "bool gl_FrontFacing;"
},
{
"code": null,
"e": 47394,
"s": 47333,
"text": "Holds the fragment that belongs to a front-facing primitive."
},
{
"code": null,
"e": 47422,
"s": 47394,
"text": "mediump vec2 gl_PointCoord;"
},
{
"code": null,
"e": 47493,
"s": 47422,
"text": "Holds the fragment position within a point (point rasterization only)."
},
{
"code": null,
"e": 47520,
"s": 47493,
"text": "mediump vec4 gl_FragColor;"
},
{
"code": null,
"e": 47572,
"s": 47520,
"text": "Holds the output fragment color value of the shader"
},
{
"code": null,
"e": 47600,
"s": 47572,
"text": "mediump vec4 gl_FragData[n]"
},
{
"code": null,
"e": 47649,
"s": 47600,
"text": "Holds the fragment color for color attachment n."
},
{
"code": null,
"e": 47751,
"s": 47649,
"text": "The following sample code of a fragment shader shows how to apply color to every pixel in a triangle."
},
{
"code": null,
"e": 47809,
"s": 47751,
"text": "void main(void) {\n gl_FragColor = vec4(0, 0.8, 0, 1);\n}"
},
{
"code": null,
"e": 48068,
"s": 47809,
"text": "In the above code, the color value is stored in the variable gl.FragColor. The fragment shader program passes the output to the pipeline using fixed function variables; FragColor is one of them. This variable holds the color value of the pixels of the model."
},
{
"code": null,
"e": 48241,
"s": 48068,
"text": "Since shaders are independent programs, we can write them as a separate script and use in the application. Or, you can store them directly in string format, as shown below."
},
{
"code": null,
"e": 48380,
"s": 48241,
"text": "var vertCode =\n 'attribute vec2 coordinates;' +\n\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 0.0, 1.0);' +\n '}';"
},
{
"code": null,
"e": 48425,
"s": 48380,
"text": "Compilation involves following three steps −"
},
{
"code": null,
"e": 48452,
"s": 48425,
"text": "Creating the shader object"
},
{
"code": null,
"e": 48507,
"s": 48452,
"text": "Attaching the source code to the created shader object"
},
{
"code": null,
"e": 48529,
"s": 48507,
"text": "Compiling the program"
},
{
"code": null,
"e": 48672,
"s": 48529,
"text": "To create an empty shader, WebGL provides a method called createShader(). It creates and returns the shader object. Its syntax is as follows −"
},
{
"code": null,
"e": 48705,
"s": 48672,
"text": "Object createShader (enum type)\n"
},
{
"code": null,
"e": 48821,
"s": 48705,
"text": "As observed in the syntax, this method accepts a predefined enum value as parameter. We have two options for this −"
},
{
"code": null,
"e": 48865,
"s": 48821,
"text": "gl.VERTEX_SHADER for creating vertex shader"
},
{
"code": null,
"e": 48909,
"s": 48865,
"text": "gl.VERTEX_SHADER for creating vertex shader"
},
{
"code": null,
"e": 48958,
"s": 48909,
"text": "gl.FRAGMENT_SHADER for creating fragment shader."
},
{
"code": null,
"e": 49007,
"s": 48958,
"text": "gl.FRAGMENT_SHADER for creating fragment shader."
},
{
"code": null,
"e": 49127,
"s": 49007,
"text": "You can attach the source code to the created shader object using the method shaderSource(). Its syntax is as follows −"
},
{
"code": null,
"e": 49176,
"s": 49127,
"text": "void shaderSource(Object shader, string source)\n"
},
{
"code": null,
"e": 49213,
"s": 49176,
"text": "This method accepts two parameters −"
},
{
"code": null,
"e": 49283,
"s": 49213,
"text": "shader − You have to pass the created shader object as one parameter."
},
{
"code": null,
"e": 49353,
"s": 49283,
"text": "shader − You have to pass the created shader object as one parameter."
},
{
"code": null,
"e": 49421,
"s": 49353,
"text": "Source − You have to pass the shader program code in string format."
},
{
"code": null,
"e": 49489,
"s": 49421,
"text": "Source − You have to pass the shader program code in string format."
},
{
"code": null,
"e": 49583,
"s": 49489,
"text": "To compile the program, you have to use the method compileShader(). Its syntax is as follow −"
},
{
"code": null,
"e": 49613,
"s": 49583,
"text": "compileShader(Object shader)\n"
},
{
"code": null,
"e": 49781,
"s": 49613,
"text": "This method accepts the shader program object as a parameter. After creating a shader program object, attach the source code to it and pass that object to this method."
},
{
"code": null,
"e": 49907,
"s": 49781,
"text": "The following code snippet shows how to create and compile a vertex shader as well as a fragment shader to create a triangle."
},
{
"code": null,
"e": 50419,
"s": 49907,
"text": "// Vertex Shader\nvar vertCode =\n 'attribute vec3 coordinates;' +\n\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n\nvar vertShader = gl.createShader(gl.VERTEX_SHADER);\ngl.shaderSource(vertShader, vertCode);\ngl.compileShader(vertShader);\n \n// Fragment Shader\nvar fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0, 0.8, 0, 1);' +\n '}';\n\nvar fragShader = gl.createShader(gl.FRAGMENT_SHADER);\ngl.shaderSource(fragShader, fragCode);\ngl.compileShader(fragShader);"
},
{
"code": null,
"e": 50603,
"s": 50419,
"text": "After creating and compiling both the shader programs, you need to create a combined program containing both the shaders (vertex & fragment). The following steps need to be followed −"
},
{
"code": null,
"e": 50627,
"s": 50603,
"text": "Create a program object"
},
{
"code": null,
"e": 50651,
"s": 50627,
"text": "Attach both the shaders"
},
{
"code": null,
"e": 50673,
"s": 50651,
"text": "Link both the shaders"
},
{
"code": null,
"e": 50689,
"s": 50673,
"text": "Use the program"
},
{
"code": null,
"e": 50811,
"s": 50689,
"text": "Create a program object by using the method createProgram(). It will return an empty program object. Here is its syntax −"
},
{
"code": null,
"e": 50829,
"s": 50811,
"text": "createProgram();\n"
},
{
"code": null,
"e": 50938,
"s": 50829,
"text": "Attach the shaders to the created program object using the method attachShader(). Its syntax is as follows −"
},
{
"code": null,
"e": 50984,
"s": 50938,
"text": "attachShader(Object program, Object shader);\n"
},
{
"code": null,
"e": 51021,
"s": 50984,
"text": "This method accepts two parameters −"
},
{
"code": null,
"e": 51087,
"s": 51021,
"text": "Program − Pass the created empty program object as one parameter."
},
{
"code": null,
"e": 51153,
"s": 51087,
"text": "Program − Pass the created empty program object as one parameter."
},
{
"code": null,
"e": 51237,
"s": 51153,
"text": "Shader − Pass one of the compiled shaders programs (vertex shader, fragment shader)"
},
{
"code": null,
"e": 51321,
"s": 51237,
"text": "Shader − Pass one of the compiled shaders programs (vertex shader, fragment shader)"
},
{
"code": null,
"e": 51383,
"s": 51321,
"text": "Note − You need to attach both the shaders using this method."
},
{
"code": null,
"e": 51529,
"s": 51383,
"text": "Link the shaders using the method linkProgram(), by passing the program object to which you have attached the shaders. Its syntax is as follows −"
},
{
"code": null,
"e": 51558,
"s": 51529,
"text": "linkProgram(shaderProgram);\n"
},
{
"code": null,
"e": 51673,
"s": 51558,
"text": "WebGL provides a method called useProgram(). You need to pass the linked program to it. Its syntax is as follows −"
},
{
"code": null,
"e": 51701,
"s": 51673,
"text": "useProgram(shaderProgram);\n"
},
{
"code": null,
"e": 51790,
"s": 51701,
"text": "The following code snippet shows how to create, link, and use a combined shader program."
},
{
"code": null,
"e": 51981,
"s": 51790,
"text": "var shaderProgram = gl.createProgram();\ngl.attachShader(shaderProgram, vertShader);\ngl.attachShader(shaderProgram, fragShader);\ngl.linkProgram(shaderProgram);\ngl.useProgram(shaderProgram); \n"
},
{
"code": null,
"e": 52342,
"s": 51981,
"text": "Each attribute in the vertex shader program points to a vertex buffer object. After creating the vertex buffer objects, programmers have to associate them with the attributes of the vertex shader program. Each attribute points to only one vertex buffer object from which they extract the data values, and then these attributes are passed to the shader program."
},
{
"code": null,
"e": 52474,
"s": 52342,
"text": "To associate the Vertex Buffer Objects with the attributes of the vertex shader program, you have to follow the steps given below −"
},
{
"code": null,
"e": 52501,
"s": 52474,
"text": "Get the attribute location"
},
{
"code": null,
"e": 52547,
"s": 52501,
"text": "Point the attribute to a vertex buffer object"
},
{
"code": null,
"e": 52568,
"s": 52547,
"text": "Enable the attribute"
},
{
"code": null,
"e": 52684,
"s": 52568,
"text": "WebGL provides a method called getAttribLocation() which returns the attribute location. Its syntax is as follows −"
},
{
"code": null,
"e": 52738,
"s": 52684,
"text": "ulong getAttribLocation(Object program, string name)\n"
},
{
"code": null,
"e": 52846,
"s": 52738,
"text": "This method accepts the vertex shader program object and the attribute values of the vertex shader program."
},
{
"code": null,
"e": 52903,
"s": 52846,
"text": "The following code snippet shows how to use this method."
},
{
"code": null,
"e": 52979,
"s": 52903,
"text": "var coordinatesVar = gl.getAttribLocation(shader_program, \"coordinates\"); \n"
},
{
"code": null,
"e": 53099,
"s": 52979,
"text": "Here, shader_program is the object of the shader program and coordinates is the attribute of the vertex shader program."
},
{
"code": null,
"e": 53244,
"s": 53099,
"text": "To assign the buffer object to the attribute variable, WebGL provides a method called vertexAttribPointer(). Here is the syntax of this method −"
},
{
"code": null,
"e": 53344,
"s": 53244,
"text": "void vertexAttribPointer(location, int size, enum type, bool normalized, long stride, long offset)\n"
},
{
"code": null,
"e": 53409,
"s": 53344,
"text": "This method accepts six parameters and they are discussed below."
},
{
"code": null,
"e": 53570,
"s": 53409,
"text": "Location − It specifies the storage location of an attribute variable. Under this option, you have to pass the value returned by the getAttribLocation() method."
},
{
"code": null,
"e": 53731,
"s": 53570,
"text": "Location − It specifies the storage location of an attribute variable. Under this option, you have to pass the value returned by the getAttribLocation() method."
},
{
"code": null,
"e": 53809,
"s": 53731,
"text": "Size − It specifies the number of components per vertex in the buffer object."
},
{
"code": null,
"e": 53887,
"s": 53809,
"text": "Size − It specifies the number of components per vertex in the buffer object."
},
{
"code": null,
"e": 53925,
"s": 53887,
"text": "Type − It specifies the type of data."
},
{
"code": null,
"e": 53963,
"s": 53925,
"text": "Type − It specifies the type of data."
},
{
"code": null,
"e": 54088,
"s": 53963,
"text": "Normalized − This is a Boolean value. If true, non-floating data is normalized to [0, 1]; else, it is normalized to [-1, 1]."
},
{
"code": null,
"e": 54213,
"s": 54088,
"text": "Normalized − This is a Boolean value. If true, non-floating data is normalized to [0, 1]; else, it is normalized to [-1, 1]."
},
{
"code": null,
"e": 54323,
"s": 54213,
"text": "Stride − It specifies the number of bytes between different vertex data elements, or zero for default stride."
},
{
"code": null,
"e": 54433,
"s": 54323,
"text": "Stride − It specifies the number of bytes between different vertex data elements, or zero for default stride."
},
{
"code": null,
"e": 54606,
"s": 54433,
"text": "Offset − It specifies the offset (in bytes) in a buffer object to indicate which byte the vertex data is stored from. If the data is stored from the beginning, offset is 0."
},
{
"code": null,
"e": 54779,
"s": 54606,
"text": "Offset − It specifies the offset (in bytes) in a buffer object to indicate which byte the vertex data is stored from. If the data is stored from the beginning, offset is 0."
},
{
"code": null,
"e": 54855,
"s": 54779,
"text": "The following snippet shows how to use vertexAttribPointer() in a program −"
},
{
"code": null,
"e": 54922,
"s": 54855,
"text": "gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0);\n"
},
{
"code": null,
"e": 55188,
"s": 54922,
"text": "Activate the vertex shader attribute to access the buffer object in a vertex shader. For this operation, WebGL provides enableVertexAttribArray() method. This method accepts the location of the attribute as a parameter. Here is how to use this method in a program −"
},
{
"code": null,
"e": 55234,
"s": 55188,
"text": "gl.enableVertexAttribArray(coordinatesVar); \n"
},
{
"code": null,
"e": 55416,
"s": 55234,
"text": "After associating the buffers with the shaders, the final step is to draw the required primitives. WebGL provides two methods namely, drawArrays() and drawElements() to draw models."
},
{
"code": null,
"e": 55509,
"s": 55416,
"text": "drawArrays() is the method which is used to draw models using vertices. Here is its syntax −"
},
{
"code": null,
"e": 55560,
"s": 55509,
"text": "void drawArrays(enum mode, int first, long count)\n"
},
{
"code": null,
"e": 55611,
"s": 55560,
"text": "This method takes the following three parameters −"
},
{
"code": null,
"e": 55899,
"s": 55611,
"text": "mode − In WebGL, models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES."
},
{
"code": null,
"e": 56187,
"s": 55899,
"text": "mode − In WebGL, models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES."
},
{
"code": null,
"e": 56292,
"s": 56187,
"text": "first − This option specifies the starting element in the enabled arrays. It cannot be a negative value."
},
{
"code": null,
"e": 56397,
"s": 56292,
"text": "first − This option specifies the starting element in the enabled arrays. It cannot be a negative value."
},
{
"code": null,
"e": 56466,
"s": 56397,
"text": "count − This option specifies the number of elements to be rendered."
},
{
"code": null,
"e": 56535,
"s": 56466,
"text": "count − This option specifies the number of elements to be rendered."
},
{
"code": null,
"e": 56701,
"s": 56535,
"text": "If you draw a model using drawArrays() method, then WebGL, while rendering the shapes, creates the geometry in the order in which the vertex coordinates are defined."
},
{
"code": null,
"e": 56852,
"s": 56701,
"text": "If you want to draw a single triangle using drawArray() method, then you have to pass three vertices and call the drawArrays() method, as shown below."
},
{
"code": null,
"e": 56938,
"s": 56852,
"text": "var vertices = [-0.5,-0.5, -0.25,0.5, 0.0,-0.5,];\ngl.drawArrays(gl.TRIANGLES, 0, 3);\n"
},
{
"code": null,
"e": 56981,
"s": 56938,
"text": "It will produce a triangle as shown below."
},
{
"code": null,
"e": 57160,
"s": 56981,
"text": "Suppose you want to draw contiguous triangles, then you have to pass the next three vertices in order in the vertex buffer and mention the number of elements to be rendered as 6."
},
{
"code": null,
"e": 57276,
"s": 57160,
"text": "var vertices = [-0.5,-0.5, -0.25,0.5, 0.0,-0.5, 0.0,-0.5, 0.25,0.5, 0.5,-0.5,];\ngl.drawArrays(gl.TRIANGLES, 0, 6);\n"
},
{
"code": null,
"e": 57330,
"s": 57276,
"text": "It will produce a contiguous triangle as shown below."
},
{
"code": null,
"e": 57442,
"s": 57330,
"text": "drawElements() is the method that is used to draw models using vertices and indices. Its syntax is as follows −"
},
{
"code": null,
"e": 57508,
"s": 57442,
"text": "void drawElements(enum mode, long count, enum type, long offset)\n"
},
{
"code": null,
"e": 57558,
"s": 57508,
"text": "This method takes the following four parameters −"
},
{
"code": null,
"e": 57850,
"s": 57558,
"text": "mode − WebGL models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The list of possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES."
},
{
"code": null,
"e": 58142,
"s": 57850,
"text": "mode − WebGL models are drawn using primitive types. Using mode, programmers have to choose one of the primitive types provided by WebGL. The list of possible values for this option are − gl.POINTS, gl.LINE_STRIP, gl.LINE_LOOP, gl.LINES, gl.TRIANGLE_STRIP, gl.TRIANGLE_FAN, and gl.TRIANGLES."
},
{
"code": null,
"e": 58211,
"s": 58142,
"text": "count − This option specifies the number of elements to be rendered."
},
{
"code": null,
"e": 58280,
"s": 58211,
"text": "count − This option specifies the number of elements to be rendered."
},
{
"code": null,
"e": 58385,
"s": 58280,
"text": "type − This option specifies the data type of the indices which must be UNSIGNED_BYTE or UNSIGNED_SHORT."
},
{
"code": null,
"e": 58490,
"s": 58385,
"text": "type − This option specifies the data type of the indices which must be UNSIGNED_BYTE or UNSIGNED_SHORT."
},
{
"code": null,
"e": 58592,
"s": 58490,
"text": "offset − This option specifies the starting point for rendering. It is usually the first element (0)."
},
{
"code": null,
"e": 58694,
"s": 58592,
"text": "offset − This option specifies the starting point for rendering. It is usually the first element (0)."
},
{
"code": null,
"e": 58943,
"s": 58694,
"text": "If you draw a model using drawElements() method, then index buffer object should also be created along with the vertex buffer object. If you use this method, the vertex data will be processed once and used as many times as mentioned in the indices."
},
{
"code": null,
"e": 59096,
"s": 58943,
"text": "If you want to draw a single triangle using indices, you need to pass the indices along with vertices and call the drawElements() method as shown below."
},
{
"code": null,
"e": 59251,
"s": 59096,
"text": "var vertices = [ -0.5,-0.5,0.0, -0.25,0.5,0.0, 0.0,-0.5,0.0 ];\nvar indices = [0,1,2];\n\ngl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);"
},
{
"code": null,
"e": 59290,
"s": 59251,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 59442,
"s": 59290,
"text": "If you want to draw contagious triangles using drawElements() method, simply add the other vertices and mention the indices for the remaining vertices."
},
{
"code": null,
"e": 59648,
"s": 59442,
"text": "var vertices = [\n -0.5,-0.5,0.0,\n -0.25,0.5,0.0,\n 0.0,-0.5,0.0,\n 0.25,0.5,0.0,\n 0.5,-0.5,0.0 \n];\n\nvar indices = [0,1,2,2,3,4];\n\ngl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);"
},
{
"code": null,
"e": 59687,
"s": 59648,
"text": "It will produce the following output −"
},
{
"code": null,
"e": 59780,
"s": 59687,
"text": "Before drawing a primitive, you need to perform a few operations, which are explained below."
},
{
"code": null,
"e": 60064,
"s": 59780,
"text": "First of all, you should clear the canvas, using clearColor() method. You can pass the RGBA values of a desired color as parameter to this method. Then WebGL clears the canvas and fills it with the specified color. Therefore, you can use this method for setting the background color."
},
{
"code": null,
"e": 60152,
"s": 60064,
"text": "Take a look at the following example. Here we are passing the RGBA value of gray color."
},
{
"code": null,
"e": 60185,
"s": 60152,
"text": "gl.clearColor(0.5, 0.5, .5, 1);\n"
},
{
"code": null,
"e": 60250,
"s": 60185,
"text": "Enable the depth test using the enable() method, as shown below."
},
{
"code": null,
"e": 60278,
"s": 60250,
"text": "gl.enable(gl.DEPTH_TEST); \n"
},
{
"code": null,
"e": 60367,
"s": 60278,
"text": "Clear the color as well as the depth buffer by using the clear() method, as shown below."
},
{
"code": null,
"e": 60421,
"s": 60367,
"text": "gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n"
},
{
"code": null,
"e": 60684,
"s": 60421,
"text": "The view port represents a rectangular viewable area that contains the rendering results of the drawing buffer. You can set the dimensions of the view port using viewport() method. In the following code, the view port dimensions are set to the canvas dimensions."
},
{
"code": null,
"e": 60730,
"s": 60684,
"text": "gl.viewport(0,0,canvas.width,canvas.height);\n"
},
{
"code": null,
"e": 61067,
"s": 60730,
"text": "We discussed earlier (in Chapter 5) how to follow a step-by-step process to draw a primitive. We have explained the process in five steps. You need to repeat these steps every time you draw a new shape. This chapter explains how to draw points with 3D coordinates in WebGL. Before moving further, let us take a relook at the five steps."
},
{
"code": null,
"e": 61146,
"s": 61067,
"text": "The following steps are required to create a WebGL application to draw points."
},
{
"code": null,
"e": 61210,
"s": 61146,
"text": "Step 1 − Prepare the Canvas and Get the WebGL Rendering Context"
},
{
"code": null,
"e": 61300,
"s": 61210,
"text": "In this step, we obtain the WebGL Rendering context object using the method getContext()."
},
{
"code": null,
"e": 61364,
"s": 61300,
"text": "Step 2 − Define the Geometry and Store it in the Buffer Objects"
},
{
"code": null,
"e": 61471,
"s": 61364,
"text": "Since we are drawing three points, we define three vertices with 3D coordinates and store them in buffers."
},
{
"code": null,
"e": 61545,
"s": 61471,
"text": "var vertices = [\n -0.5,0.5,0.0,\n 0.0,0.5,0.0,\n -0.25,0.25,0.0, \n];\n"
},
{
"code": null,
"e": 61593,
"s": 61545,
"text": "Step 3 − Create and Compile the Shader Programs"
},
{
"code": null,
"e": 61744,
"s": 61593,
"text": "In this step, you need to write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 61900,
"s": 61744,
"text": "Vertex Shader − In the vertex shader of the given example, we define a vector attribute to store 3D coordinates, and assign it to the gl_position variable."
},
{
"code": null,
"e": 62056,
"s": 61900,
"text": "Vertex Shader − In the vertex shader of the given example, we define a vector attribute to store 3D coordinates, and assign it to the gl_position variable."
},
{
"code": null,
"e": 62153,
"s": 62056,
"text": "gl_pointsize is the variable used to assign a size to the point. We assign the point size as 10."
},
{
"code": null,
"e": 62250,
"s": 62153,
"text": "gl_pointsize is the variable used to assign a size to the point. We assign the point size as 10."
},
{
"code": null,
"e": 62411,
"s": 62250,
"text": "var vertCode = 'attribute vec3 coordinates;' +\n\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n 'gl_PointSize = 10.0;'+\n '}';\n"
},
{
"code": null,
"e": 62518,
"s": 62411,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable"
},
{
"code": null,
"e": 62625,
"s": 62518,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable"
},
{
"code": null,
"e": 62708,
"s": 62625,
"text": "var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';\n"
},
{
"code": null,
"e": 62765,
"s": 62708,
"text": "Step 4 − Associate the Shader Programs to Buffer Objects"
},
{
"code": null,
"e": 62836,
"s": 62765,
"text": "In this step, we associate the buffer objects with the shader program."
},
{
"code": null,
"e": 62873,
"s": 62836,
"text": "Step 5 − Drawing the Required Object"
},
{
"code": null,
"e": 62999,
"s": 62873,
"text": "We use the method drawArrays() to draw points. Since the number of points we want to draw are is three, the count value is 3."
},
{
"code": null,
"e": 63031,
"s": 62999,
"text": "gl.drawArrays(gl.POINTS, 0, 3)\n"
},
{
"code": null,
"e": 63089,
"s": 63031,
"text": "Here is the complete WebGL program to draw three points −"
},
{
"code": null,
"e": 66536,
"s": 63089,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*================Creating a canvas=================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl'); \n\n /*==========Defining and storing the geometry=======*/\n\n var vertices = [\n -0.5,0.5,0.0,\n 0.0,0.5,0.0,\n -0.25,0.25,0.0, \n ];\n\n // Create an empty buffer object to store the vertex buffer\n var vertex_buffer = gl.createBuffer();\n\n //Bind appropriate array buffer to it\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Pass the vertex data to the buffer\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n /*=========================Shaders========================*/\n\n // vertex shader source code\n var vertCode =\n 'attribute vec3 coordinates;' +\n\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n 'gl_PointSize = 10.0;'+\n '}';\n\n // Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n \n // Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n // Compile the vertex shader\n gl.compileShader(vertShader);\n\n // fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n\n // Create fragment shader object\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode);\n\n // Compile the fragmentt shader\n gl.compileShader(fragShader);\n \n // Create a shader program object to store\n // the combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader); \n\n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /*======== Associating shaders to buffer objects ========*/\n\n // Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n // Point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);\n\n // Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n /*============= Drawing the primitive ===============*/\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST);\n \n // Clear the color buffer bit\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n // Draw the triangle\n gl.drawArrays(gl.POINTS, 0, 3);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 66575,
"s": 66536,
"text": "It will produce the following result −"
},
{
"code": null,
"e": 66816,
"s": 66575,
"text": "In the previous chapter (Chapter 11), we discussed how to draw three points using WebGL. In Chapter 5, we took sample application to demonstrate how to draw a triangle. In both the examples, we have drawn the primitives using only vertices."
},
{
"code": null,
"e": 66999,
"s": 66816,
"text": "To draw more complex shapes/meshes, we pass the indices of a geometry too, along with the vertices, to the shaders. In this chapter, we will see how to draw a triangle using indices."
},
{
"code": null,
"e": 67082,
"s": 66999,
"text": "The following steps are required to create a WebGL application to draw a triangle."
},
{
"code": null,
"e": 67142,
"s": 67082,
"text": "Step 1 − Prepare the Canvas and Get WebGL Rendering Context"
},
{
"code": null,
"e": 67221,
"s": 67142,
"text": "In this step, we obtain the WebGL Rendering context object using getContext()."
},
{
"code": null,
"e": 67281,
"s": 67221,
"text": "Step 2 − Define the Geometry and Store it in Buffer Objects"
},
{
"code": null,
"e": 67434,
"s": 67281,
"text": "Since we are drawing a triangle using indices, we have to pass the three vertices of the triangle, including the indices, and store them in the buffers."
},
{
"code": null,
"e": 67530,
"s": 67434,
"text": "var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0, \n];\n\t\nindices = [0,1,2]; \n"
},
{
"code": null,
"e": 67578,
"s": 67530,
"text": "Step 3 − Create and Compile the Shader Programs"
},
{
"code": null,
"e": 67729,
"s": 67578,
"text": "In this step, you need to write vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 67867,
"s": 67729,
"text": "Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position."
},
{
"code": null,
"e": 68005,
"s": 67867,
"text": "Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position."
},
{
"code": null,
"e": 68140,
"s": 68005,
"text": "var vertCode =\n 'attribute vec3 coordinates;' +\n\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n"
},
{
"code": null,
"e": 68248,
"s": 68140,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable."
},
{
"code": null,
"e": 68356,
"s": 68248,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable."
},
{
"code": null,
"e": 68444,
"s": 68356,
"text": "var fragCode = 'void main(void) {' +\n ' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +\n'}';\n"
},
{
"code": null,
"e": 68505,
"s": 68444,
"text": "Step 4 − Associate the Shader Programs to the Buffer Objects"
},
{
"code": null,
"e": 68575,
"s": 68505,
"text": "In this step, we associate the buffer objects and the shader program."
},
{
"code": null,
"e": 68612,
"s": 68575,
"text": "Step 5 − Drawing the Required Object"
},
{
"code": null,
"e": 68807,
"s": 68612,
"text": "Since we are drawing a triangle using indices, we will use drawElements(). To this method, we have to pass the number of indices. The value of the indices.length signifies the number of indices."
},
{
"code": null,
"e": 68876,
"s": 68807,
"text": "gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n"
},
{
"code": null,
"e": 68957,
"s": 68876,
"text": "The following program code shows how to draw a triangle in WebGL using indices −"
},
{
"code": null,
"e": 73051,
"s": 68957,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============== Creating a canvas ====================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n \n /*======== Defining and storing the geometry ===========*/\n\n var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0, \n ];\n \n indices = [0,1,2];\n \n // Create an empty buffer object to store vertex buffer\n var vertex_buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n \n // Pass the vertex data to the buffer\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n // Create an empty buffer object to store Index buffer\n var Index_Buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n\n // Pass the vertex data to the buffer\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n \n // Unbind the buffer\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n\n /*================ Shaders ====================*/\n \n // Vertex shader source code\n var vertCode =\n 'attribute vec3 coordinates;' +\n\t\t\t\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n \n // Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n\n // Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n // Compile the vertex shader\n gl.compileShader(vertShader);\n\n //fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n \n // Create fragment shader object\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode); \n \n // Compile the fragmentt shader\n gl.compileShader(fragShader);\n\n // Create a shader program object to store\n // the combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader);\n\n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both the programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /*======= Associating shaders to buffer objects =======*/\n\n // Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Bind index buffer object\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n \n // Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n // Point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0); \n \n // Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n /*=========Drawing the triangle===========*/\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST);\n\n // Clear the color buffer bit\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n // Draw the triangle\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 73115,
"s": 73051,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 73332,
"s": 73115,
"text": "In the previous chapter (Chapter 12), we discussed how to draw a triangle using WebGL. In addition to triangles, WebGL supports various other drawing modes. This chapter explains the drawing modes supported by WebGL."
},
{
"code": null,
"e": 73415,
"s": 73332,
"text": "Let’s take a look at the syntax of the methods − drawElements() and draw Arrays()."
},
{
"code": null,
"e": 73534,
"s": 73415,
"text": "void drawElements(enum mode, long count, enum type, long offset);\n\nvoid drawArrays(enum mode, int first, long count);\n"
},
{
"code": null,
"e": 73676,
"s": 73534,
"text": "If you clearly observe, both the methods accept a parameter mode. Using this parameter, the programmers can select the drawing mode in WebGL."
},
{
"code": null,
"e": 73747,
"s": 73676,
"text": "The drawing modes provided by WebGL are listed in the following table."
},
{
"code": null,
"e": 73757,
"s": 73747,
"text": "gl.POINTS"
},
{
"code": null,
"e": 73785,
"s": 73757,
"text": "To draw a series of points."
},
{
"code": null,
"e": 73794,
"s": 73785,
"text": "gl.LINES"
},
{
"code": null,
"e": 73860,
"s": 73794,
"text": "To draw a series of unconnected line segments (individual lines)."
},
{
"code": null,
"e": 73874,
"s": 73860,
"text": "gl.LINE_STRIP"
},
{
"code": null,
"e": 73919,
"s": 73874,
"text": "To draw a series of connected line segments."
},
{
"code": null,
"e": 73932,
"s": 73919,
"text": "gl.LINE_LOOP"
},
{
"code": null,
"e": 74035,
"s": 73932,
"text": "To draw a series of connected line segments. It also joins the first and last vertices to form a loop."
},
{
"code": null,
"e": 74048,
"s": 74035,
"text": "gl.TRIANGLES"
},
{
"code": null,
"e": 74088,
"s": 74048,
"text": "To draw a series of separate triangles."
},
{
"code": null,
"e": 74106,
"s": 74088,
"text": "gl.TRIANGLE_STRIP"
},
{
"code": null,
"e": 74164,
"s": 74106,
"text": "To draw a series of connected triangles in strip fashion."
},
{
"code": null,
"e": 74180,
"s": 74164,
"text": "gl.TRIANGLE_FAN"
},
{
"code": null,
"e": 74268,
"s": 74180,
"text": "To draw a series of connected triangles sharing the first vertex in a fan-like fashion."
},
{
"code": null,
"e": 74345,
"s": 74268,
"text": "The following example shows how to draw three parallel lines using gl.LINES."
},
{
"code": null,
"e": 77879,
"s": 74345,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"300\" height = \"300\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*======= Creating a canvas =========*/\n\n var canvas = document.getElementById('my_Canvas');\n var gl = canvas.getContext('experimental-webgl');\n\n /*======= Defining and storing the geometry ======*/\n\n var vertices = [\n -0.7,-0.1,0,\n -0.3,0.6,0,\n -0.3,-0.3,0,\n 0.2,0.6,0,\n 0.3,-0.3,0,\n 0.7,0.6,0 \n ]\n\n // Create an empty buffer object\n var vertex_buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n \n // Pass the vertex data to the buffer\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n /*=================== Shaders ====================*/\n\n // Vertex shader source code\n var vertCode =\n 'attribute vec3 coordinates;' +\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n\n // Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n\n // Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n // Compile the vertex shader\n gl.compileShader(vertShader);\n\n // Fragment shader source code\n var fragCode =\n 'void main(void) {' +\n 'gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n\n // Create fragment shader object\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode);\n\n // Compile the fragmentt shader\n gl.compileShader(fragShader);\n\n // Create a shader program object to store\n // the combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader);\n\n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both the programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /*======= Associating shaders to buffer objects ======*/\n\n // Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n // Point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);\n\n // Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n /*============ Drawing the triangle =============*/\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST);\n\n // Clear the color and depth buffer\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n // Draw the triangle\n gl.drawArrays(gl.LINES, 0, 6);\n\n // POINTS, LINE_STRIP, LINE_LOOP, LINES,\n // TRIANGLE_STRIP,TRIANGLE_FAN, TRIANGLES\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 77943,
"s": 77879,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 78091,
"s": 77943,
"text": "In the above program, if you replace the mode of drawArrays() with one of the following drawing modes, it will produce different outputs each time."
},
{
"code": null,
"e": 78392,
"s": 78091,
"text": "In the previous chapter, we discussed the different drawing modes provided by WebGL. We can also use indices to draw primitives using one of these modes. To draw models in WebGL, we have to choose one of these primitives and draw the required mesh (i.e., a model formed using one or more primitives)."
},
{
"code": null,
"e": 78489,
"s": 78392,
"text": "In this chapter, we will take an example to demonstrate how to draw a quadrilateral using WebGL."
},
{
"code": null,
"e": 78577,
"s": 78489,
"text": "The following steps are required to create a WebGL application to draw a quadrilateral."
},
{
"code": null,
"e": 78641,
"s": 78577,
"text": "Step 1 − Prepare the Canvas and Get the WebGL Rendering Context"
},
{
"code": null,
"e": 78720,
"s": 78641,
"text": "In this step, we obtain the WebGL Rendering context object using getContext()."
},
{
"code": null,
"e": 78784,
"s": 78720,
"text": "Step 2 − Define the Geometry and Store it in the Buffer Objects"
},
{
"code": null,
"e": 78922,
"s": 78784,
"text": "A square can be drawn using two triangles. In this example, we provide the vertices for two triangles (with one common edge) and indices."
},
{
"code": null,
"e": 79038,
"s": 78922,
"text": "var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0,\n 0.5,0.5,0.0 \n];\n\nindices = [3,2,1,3,1,0]; \n"
},
{
"code": null,
"e": 79086,
"s": 79038,
"text": "Step 3 − Create and Compile the Shader Programs"
},
{
"code": null,
"e": 79241,
"s": 79086,
"text": "In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 79379,
"s": 79241,
"text": "Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position."
},
{
"code": null,
"e": 79517,
"s": 79379,
"text": "Vertex Shader − In the vertex shader of the program, we define the vector attribute to store 3D coordinates and assign it to gl_position."
},
{
"code": null,
"e": 79650,
"s": 79517,
"text": "var vertCode =\n 'attribute vec3 coordinates;' +\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n"
},
{
"code": null,
"e": 79758,
"s": 79650,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable."
},
{
"code": null,
"e": 79866,
"s": 79758,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable."
},
{
"code": null,
"e": 79953,
"s": 79866,
"text": "var fragCode = 'void main(void) {' +' gl_FragColor = vec4(0.5, 0.3, 0.0, 7.5);' +'}';\n"
},
{
"code": null,
"e": 80010,
"s": 79953,
"text": "Step 4 − Associate the Shader Programs to Buffer Objects"
},
{
"code": null,
"e": 80081,
"s": 80010,
"text": "In this step, we associate the buffer objects with the shader program."
},
{
"code": null,
"e": 80118,
"s": 80081,
"text": "Step 5 − Drawing the Required Object"
},
{
"code": null,
"e": 80335,
"s": 80118,
"text": "Since we are drawing two triangles to form a quad, using indices, we will use the method drawElements(). To this method, we have to pass the number of indices. The value of indices.length gives the number of indices."
},
{
"code": null,
"e": 80404,
"s": 80335,
"text": "gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n"
},
{
"code": null,
"e": 80491,
"s": 80404,
"text": "The following program shows how to create a WebGL application to draw a quadrilateral."
},
{
"code": null,
"e": 84533,
"s": 80491,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============ Creating a canvas =================*/\n \n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n \n /*========== Defining and storing the geometry =========*/\n\n var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0,\n 0.5,0.5,0.0 \n ];\n\n indices = [3,2,1,3,1,0];\n\n // Create an empty buffer object to store vertex buffer\n var vertex_buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Pass the vertex data to the buffer\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n // Create an empty buffer object to store Index buffer\n var Index_Buffer = gl.createBuffer();\n\n // Bind appropriate array buffer to it\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n\n // Pass the vertex data to the buffer\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n // Unbind the buffer\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n\n /*====================== Shaders =======================*/\n\n // Vertex shader source code\n var vertCode =\n 'attribute vec3 coordinates;' +\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n '}';\n\n // Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n\n // Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n // Compile the vertex shader\n gl.compileShader(vertShader);\n\n // Fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n\n // Create fragment shader object \n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode);\n\n // Compile the fragmentt shader\n gl.compileShader(fragShader);\n\n // Create a shader program object to\n // store the combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader);\n\n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both the programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /* ======= Associating shaders to buffer objects =======*/\n\n // Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Bind index buffer object\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer); \n\n // Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n // Point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);\n\n // Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n /*============= Drawing the Quad ================*/\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST);\n\n // Clear the color buffer bit\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n // Draw the triangle\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 84597,
"s": 84533,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 84922,
"s": 84597,
"text": "In all our previous examples, we applied color to the object by assigning a desired color value to the gl_FragColor variable. In addition to that, we can define colors for each vertex − just like vertex coordinates and indices. This chapter takes an example to demonstrate how to apply colors to a quadrilateral using WebGL."
},
{
"code": null,
"e": 85258,
"s": 84922,
"text": "To apply colors, you have to define the colors for each vertex using the RGB values, in JavaScript array. You can assign the same values to all the vertices to have a unique color to the object. After defining the colors, you have to create a color buffer and store these values in it, and associate it to the vertex shader attributes."
},
{
"code": null,
"e": 85415,
"s": 85258,
"text": "In the vertex shader, along with the coordinates attribute (that holds the position of the vertices), we define an attribute and a varying to handle colors."
},
{
"code": null,
"e": 85605,
"s": 85415,
"text": "The color attribute holds the color value per vertex, and varying is the variable that is passed as an input to the fragment shader. Therefore, we have to assign the color value to varying."
},
{
"code": null,
"e": 85740,
"s": 85605,
"text": "In the fragment shader, the varying that holds the color value is assigned to gl_FragColor, which holds the final color of the object."
},
{
"code": null,
"e": 85842,
"s": 85740,
"text": "The following steps are required to create a WebGL application to draw a Quad and apply colors to it."
},
{
"code": null,
"e": 85906,
"s": 85842,
"text": "Step 1 − Prepare the Canvas and Get the WebGL Rendering Context"
},
{
"code": null,
"e": 85985,
"s": 85906,
"text": "In this step, we obtain the WebGL Rendering context object using getContext()."
},
{
"code": null,
"e": 86049,
"s": 85985,
"text": "Step 2 − Define the Geometry and Store it in the Buffer Objects"
},
{
"code": null,
"e": 86366,
"s": 86049,
"text": "A square can be drawn using two triangles. Therefore, in this example, we provide the vertices for two triangles (with one common edge) and indices. Since we want to apply colors to it, a variable holding the color values is also defined and the color values for each (Red, Blue, Green, and Pink) are assigned to it."
},
{
"code": null,
"e": 86528,
"s": 86366,
"text": "var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0, \n 0.5,-0.5,0.0,\n 0.5,0.5,0.0 \n];\n\nvar colors = [ 0,0,1, 1,0,0, 0,1,0, 1,0,1,];\nindices = [3,2,1,3,1,0]; \n"
},
{
"code": null,
"e": 86576,
"s": 86528,
"text": "Step 3 − Create and Compile the Shader Programs"
},
{
"code": null,
"e": 86731,
"s": 86576,
"text": "In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 87057,
"s": 86731,
"text": "Vertex Shader − In the vertex shader of the program, we define vector attributes to store 3D coordinates (position), and the color of each vertex. A varing variable is declared to pass the color values from the vertex shader to the fragment shader. And finally, the value stored in the color attribute is assigned to varying."
},
{
"code": null,
"e": 87383,
"s": 87057,
"text": "Vertex Shader − In the vertex shader of the program, we define vector attributes to store 3D coordinates (position), and the color of each vertex. A varing variable is declared to pass the color values from the vertex shader to the fragment shader. And finally, the value stored in the color attribute is assigned to varying."
},
{
"code": null,
"e": 87594,
"s": 87383,
"text": "var vertCode = 'attribute vec3 coordinates;'+\n 'attribute vec3 color;'+\n 'varying vec3 vColor;'+\n\t\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n 'vColor = color;'+\n '}';\n"
},
{
"code": null,
"e": 87688,
"s": 87594,
"text": "Fragment Shader − In the fragment shader, we assign the varying to the gl_FragColor variable."
},
{
"code": null,
"e": 87782,
"s": 87688,
"text": "Fragment Shader − In the fragment shader, we assign the varying to the gl_FragColor variable."
},
{
"code": null,
"e": 87927,
"s": 87782,
"text": "var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n"
},
{
"code": null,
"e": 87990,
"s": 87927,
"text": "Step 4 − Associate the Shader Programs with the Buffer Objects"
},
{
"code": null,
"e": 88060,
"s": 87990,
"text": "In this step, we associate the buffer objects and the shader program."
},
{
"code": null,
"e": 88097,
"s": 88060,
"text": "Step 5 − Drawing the Required Object"
},
{
"code": null,
"e": 88325,
"s": 88097,
"text": "Since we are drawing two triangles that will form a quad, using indices, we will use the method drawElements(). To this method, we have to pass the number of indices. The value of indices.length indicates the number of indices."
},
{
"code": null,
"e": 88394,
"s": 88325,
"text": "gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n"
},
{
"code": null,
"e": 88496,
"s": 88394,
"text": "The following program demonstrates how to draw a quad using WebGL application and apply colors to it."
},
{
"code": null,
"e": 93192,
"s": 88496,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"300\" height = \"300\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============= Creating a canvas ==================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n \n /*========== Defining and storing the geometry ==========*/\n\n var vertices = [\n -0.5,0.5,0.0,\n -0.5,-0.5,0.0,\n 0.5,-0.5,0.0,\n 0.5,0.5,0.0\n ];\n\n var colors = [0,0,1, 1,0,0, 0,1,0, 1,0,1,];\n \n indices = [3,2,1,3,1,0];\n \n // Create an empty buffer object and store vertex data\n var vertex_buffer = gl.createBuffer();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n gl.bindBuffer(gl.ARRAY_BUFFER, null);\n\n // Create an empty buffer object and store Index data\n var Index_Buffer = gl.createBuffer();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, null);\n\n // Create an empty buffer object and store color data\n var color_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n /*======================= Shaders =======================*/\n \n // vertex shader source code\n var vertCode = 'attribute vec3 coordinates;'+\n 'attribute vec3 color;'+\n 'varying vec3 vColor;'+\n 'void main(void) {' +\n ' gl_Position = vec4(coordinates, 1.0);' +\n 'vColor = color;'+\n '}';\n \n // Create a vertex shader object\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n\n // Attach vertex shader source code\n gl.shaderSource(vertShader, vertCode);\n\n // Compile the vertex shader\n gl.compileShader(vertShader);\n\n\n // fragment shader source code\n var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n \n // Create fragment shader object\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n\n // Attach fragment shader source code\n gl.shaderSource(fragShader, fragCode);\n\n // Compile the fragmentt shader\n gl.compileShader(fragShader);\n\n // Create a shader program object to\n // store the combined shader program\n var shaderProgram = gl.createProgram();\n\n // Attach a vertex shader\n gl.attachShader(shaderProgram, vertShader);\n\n // Attach a fragment shader\n gl.attachShader(shaderProgram, fragShader);\n\n // Link both the programs\n gl.linkProgram(shaderProgram);\n\n // Use the combined shader program object\n gl.useProgram(shaderProgram);\n\n /* ======== Associating shaders to buffer objects =======*/\n\n // Bind vertex buffer object\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n // Bind index buffer object\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, Index_Buffer);\n\n // Get the attribute location\n var coord = gl.getAttribLocation(shaderProgram, \"coordinates\");\n\n // point an attribute to the currently bound VBO\n gl.vertexAttribPointer(coord, 3, gl.FLOAT, false, 0, 0);\n\n // Enable the attribute\n gl.enableVertexAttribArray(coord);\n\n // bind the color buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n \n // get the attribute location\n var color = gl.getAttribLocation(shaderProgram, \"color\");\n \n // point attribute to the volor buffer object\n gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;\n \n // enable the color attribute\n gl.enableVertexAttribArray(color);\n\n /*============Drawing the Quad====================*/\n\n // Clear the canvas\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n\n // Enable the depth test\n gl.enable(gl.DEPTH_TEST);\n\n // Clear the color buffer bit\n gl.clear(gl.COLOR_BUFFER_BIT);\n\n // Set the view port\n gl.viewport(0,0,canvas.width,canvas.height);\n\n //Draw the triangle\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT,0);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 93256,
"s": 93192,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 93426,
"s": 93256,
"text": "So far, we discussed how to draw various shapes and apply colors in them using WebGL. Here, in this chapter, we will take an example to show how to translate a triangle."
},
{
"code": null,
"e": 93898,
"s": 93426,
"text": "Translation is one of the affine transformations provided by WebGL. Using translation, we can move a triangle (any object) on the xyz plane. Suppose we have a triangle [a, b, c] and we want to move the triangle to a position which is 5 units towards the positive X-axis and 3 units towards the positive Y-axis. Then the new vertices would be [a+5, b+3, c+0]. That means, to translate the triangle, we need to add the translation distances, say, tx, ty, tz to each vertex."
},
{
"code": null,
"e": 93980,
"s": 93898,
"text": "Since it is a per-vertex operation, we can carry it in the vertex shader program."
},
{
"code": null,
"e": 94264,
"s": 93980,
"text": "In the vertex shader, along with the attribute, coordinates (that hold the vertex positions), we define a uniform variable that holds the translation distances (x,y,z). Later, we add this uniform variable to the coordinates variable and assign the result to the gl_Position variable."
},
{
"code": null,
"e": 94372,
"s": 94264,
"text": "Note − Since vertex shader will be run on each vertex, all the vertices of the triangle will be translated."
},
{
"code": null,
"e": 94495,
"s": 94372,
"text": "The following steps are required to create a WebGL application to draw a triangle and then translate it to a new position."
},
{
"code": null,
"e": 94559,
"s": 94495,
"text": "Step 1 − Prepare the Canvas and Get the WebGL Rendering Context"
},
{
"code": null,
"e": 94638,
"s": 94559,
"text": "In this step, we obtain the WebGL Rendering context object using getContext()."
},
{
"code": null,
"e": 94702,
"s": 94638,
"text": "Step 2 − Define the Geometry and Store it in the Buffer Objects"
},
{
"code": null,
"e": 94810,
"s": 94702,
"text": "Since we are drawing a triangle, we have to pass three vertices of the triangle, and store them in buffers."
},
{
"code": null,
"e": 94874,
"s": 94810,
"text": "var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ];\n"
},
{
"code": null,
"e": 94922,
"s": 94874,
"text": "Step 3 − Create and Compile the Shader Programs"
},
{
"code": null,
"e": 95077,
"s": 94922,
"text": "In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 95378,
"s": 95077,
"text": "Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices."
},
{
"code": null,
"e": 95679,
"s": 95378,
"text": "Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform variable to store the translation distances, and finally, we add these two values and assign it to gl_position which holds the final position of the vertices."
},
{
"code": null,
"e": 95847,
"s": 95679,
"text": "var vertCode =\n 'attribute vec4 coordinates;' +\n 'uniform vec4 translation;'+\n 'void main(void) {' +\n ' gl_Position = coordinates + translation;' +\n '}';\n"
},
{
"code": null,
"e": 95955,
"s": 95847,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the variable gl_FragColor."
},
{
"code": null,
"e": 96063,
"s": 95955,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the variable gl_FragColor."
},
{
"code": null,
"e": 96146,
"s": 96063,
"text": "var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';\n"
},
{
"code": null,
"e": 96207,
"s": 96146,
"text": "Step 4 − Associate the Shader Programs to the Buffer Objects"
},
{
"code": null,
"e": 96278,
"s": 96207,
"text": "In this step, we associate the buffer objects with the shader program."
},
{
"code": null,
"e": 96315,
"s": 96278,
"text": "Step 5 − Drawing the Required Object"
},
{
"code": null,
"e": 96548,
"s": 96315,
"text": "Since we are drawing the triangle using indices, we will use the method drawArrays(). To this method, we have to pass the number of vertices /elements to be considered. Since we are drawing a triangle, we will pass 3 as a parameter."
},
{
"code": null,
"e": 96584,
"s": 96548,
"text": "gl.drawArrays(gl.TRIANGLES, 0, 3);\n"
},
{
"code": null,
"e": 96653,
"s": 96584,
"text": "The following example show how to translate a triangle on xyz plane."
},
{
"code": null,
"e": 99913,
"s": 96653,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"300\" height = \"300\" id = \"my_Canvas\"></canvas>\n \n <script>\n /*=================Creating a canvas=========================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl'); \n \n /*===========Defining and storing the geometry==============*/\n var vertices = [\n -0.5,0.5,0.0, \t\n -0.5,-0.5,0.0, \t\n 0.5,-0.5,0.0, \n ];\n \n //Create an empty buffer object and store vertex data \n var vertex_buffer = gl.createBuffer(); \n\t\t\t\n //Create a new buffer\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); \n\t\t\t\n //bind it to the current buffer\t\t\t\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); \n\t\t\t\n // Pass the buffer data\n gl.bindBuffer(gl.ARRAY_BUFFER, null); \n \n /*========================Shaders============================*/\n \n //vertex shader source code \n var vertCode =\n 'attribute vec4 coordinates;' + \n 'uniform vec4 translation;'+\n 'void main(void) {' +\n ' gl_Position = coordinates + translation;' +\n '}';\n \n //Create a vertex shader program object and compile it \n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n \n \n //fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n\n //Create a fragment shader program object and compile it \n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n \n //Create and use combiened shader program\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n \n gl.useProgram(shaderProgram);\n \n /* ===========Associating shaders to buffer objects============*/\n \n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); \n var coordinatesVar = gl.getAttribLocation(shaderProgram, \"coordinates\");\n gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0); \n gl.enableVertexAttribArray(coordinatesVar); \n \n /* ==========translation======================================*/\n var Tx = 0.5, Ty = 0.5, Tz = 0.0;\n var translation = gl.getUniformLocation(shaderProgram, 'translation');\n gl.uniform4f(translation, Tx, Ty, Tz, 0.0);\n \n /*=================Drawing the riangle and transforming it========================*/ \n\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.enable(gl.DEPTH_TEST);\n \n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.viewport(0,0,canvas.width,canvas.height);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n </script>\n </body>\n </html>"
},
{
"code": null,
"e": 99977,
"s": 99913,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 100084,
"s": 99977,
"text": "In this chapter, we will take an example to demonstrate how to modify the scale of a triangle using WebGL."
},
{
"code": null,
"e": 100422,
"s": 100084,
"text": "Scaling is nothing but increasing or decreasing the size of an object. For example, if a triangle has vertices of the size [a,b,c], then the triangle with the vertices [2a, 2b, 2c] will be double its size. Therefore, to scale a triangle, you have to multiply each vertices with the scaling factor. You can also scale a particular vertex."
},
{
"code": null,
"e": 100699,
"s": 100422,
"text": "To scale a triangle, in the vertex shader of the program, we create a uniform matrix and multiply the coordinate values with this matrix. Later, we pass a 4×4 diagonal matrix having the scaling factors of x,y,z coordinates in the diagonal positions (last diagonal position 1)."
},
{
"code": null,
"e": 100783,
"s": 100699,
"text": "The following steps are required to create a WebGL application to scale a triangle."
},
{
"code": null,
"e": 100847,
"s": 100783,
"text": "Step 1 − Prepare the Canvas and Get the WebGL Rendering Context"
},
{
"code": null,
"e": 100926,
"s": 100847,
"text": "In this step, we obtain the WebGL Rendering context object using getContext()."
},
{
"code": null,
"e": 100990,
"s": 100926,
"text": "Step 2 − Define the Geometry and Store it in the Buffer Objects"
},
{
"code": null,
"e": 101098,
"s": 100990,
"text": "Since we are drawing a triangle, we have to pass three vertices of the triangle, and store them in buffers."
},
{
"code": null,
"e": 101162,
"s": 101098,
"text": "var vertices = [ -0.5,0.5,0.0, -0.5,-0.5,0.0, 0.5,-0.5,0.0, ];\n"
},
{
"code": null,
"e": 101210,
"s": 101162,
"text": "Step 3 − Create and Compile the Shader Programs"
},
{
"code": null,
"e": 101365,
"s": 101210,
"text": "In this step, you need to write the vertex shader and fragment shader programs, compile them, and create a combined program by linking these two programs."
},
{
"code": null,
"e": 101663,
"s": 101365,
"text": "Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform matrix to store the scaling factors, and finally, we multiply these two values and assign it to gl_position which holds the final position of the vertices."
},
{
"code": null,
"e": 101961,
"s": 101663,
"text": "Vertex Shader − In the vertex shader of the program, we define a vector attribute to store 3D coordinates. Along with it, we define a uniform matrix to store the scaling factors, and finally, we multiply these two values and assign it to gl_position which holds the final position of the vertices."
},
{
"code": null,
"e": 102134,
"s": 101961,
"text": "var vertCode =\n 'attribute vec4 coordinates;' +\n 'uniform mat4 u_xformMatrix;' +\n 'void main(void) {' +\n ' gl_Position = u_xformMatrix * coordinates;' +\n '}';\n"
},
{
"code": null,
"e": 102242,
"s": 102134,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable."
},
{
"code": null,
"e": 102350,
"s": 102242,
"text": "Fragment Shader − In the fragment shader, we simply assign the fragment color to the gl_FragColor variable."
},
{
"code": null,
"e": 102433,
"s": 102350,
"text": "var fragCode = 'void main(void) {' +' gl_FragColor = vec4(1, 0.5, 0.0, 1);' +'}';\n"
},
{
"code": null,
"e": 102496,
"s": 102433,
"text": "Step 4 − Associate the Shader Programs with the Buffer Objects"
},
{
"code": null,
"e": 102567,
"s": 102496,
"text": "In this step, we associate the buffer objects with the shader program."
},
{
"code": null,
"e": 102604,
"s": 102567,
"text": "Step 5 − Drawing the Required Object"
},
{
"code": null,
"e": 102831,
"s": 102604,
"text": "Since we are drawing the triangle using indices, we use the drawArrays() method. To this method, we have to pass the number of vertices/elements to be considered. Since we are drawing a triangle, we will pass 3 as a parameter."
},
{
"code": null,
"e": 102867,
"s": 102831,
"text": "gl.drawArrays(gl.TRIANGLES, 0, 3);\n"
},
{
"code": null,
"e": 102921,
"s": 102867,
"text": "The following example shows how to scale a triangle −"
},
{
"code": null,
"e": 106237,
"s": 102921,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"300\" height = \"300\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*=================Creating a canvas=========================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl'); \n\n /*===========Defining and storing the geometry==============*/\n var vertices = [\n -0.5,0.5,0.0, \t\n -0.5,-0.5,0.0, \t\n 0.5,-0.5,0.0, \n ];\n\n //Create an empty buffer object and store vertex data\n\n var vertex_buffer = gl.createBuffer(); \n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); \n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW); \n gl.bindBuffer(gl.ARRAY_BUFFER, null); \n\n /*========================Shaders============================*/\n\n //Vertex shader source code\n var vertCode =\n 'attribute vec4 coordinates;' + \n 'uniform mat4 u_xformMatrix;' +\n 'void main(void) {' +\n ' gl_Position = u_xformMatrix * coordinates;' +\n '}';\n\n //Create a vertex shader program object and compile it \n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n\n //fragment shader source code\n var fragCode =\n 'void main(void) {' +\n ' gl_FragColor = vec4(0.0, 0.0, 0.0, 0.1);' +\n '}';\n\n //Create a fragment shader program object and compile it \n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n\n //Create and use combiened shader program\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n\n gl.useProgram(shaderProgram); \n\n /*===================scaling==========================*/\n\n var Sx = 1.0, Sy = 1.5, Sz = 1.0;\n var xformMatrix = new Float32Array([\n Sx, 0.0, 0.0, 0.0,\n 0.0, Sy, 0.0, 0.0,\n 0.0, 0.0, Sz, 0.0,\n 0.0, 0.0, 0.0, 1.0 \n ]);\n\n var u_xformMatrix = gl.getUniformLocation(shaderProgram, 'u_xformMatrix');\n gl.uniformMatrix4fv(u_xformMatrix, false, xformMatrix);\n\n /* ===========Associating shaders to buffer objects============*/\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer); \n\n var coordinatesVar = gl.getAttribLocation(shaderProgram, \"coordinates\"); \n gl.vertexAttribPointer(coordinatesVar, 3, gl.FLOAT, false, 0, 0); \n gl.enableVertexAttribArray(coordinatesVar);\n\n /*=================Drawing the Quad========================*/ \n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.enable(gl.DEPTH_TEST);\n\n gl.clear(gl.COLOR_BUFFER_BIT);\n gl.viewport(0,0,canvas.width,canvas.height);\n gl.drawArrays(gl.TRIANGLES, 0, 3);\n </script>\n </body>\n</html> "
},
{
"code": null,
"e": 106301,
"s": 106237,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 106395,
"s": 106301,
"text": "In this chapter, we will take an example to demonstrate how to rotate a triangle using WebGL."
},
{
"code": null,
"e": 106461,
"s": 106395,
"text": "The following program shows how to rotate a triangle using WebGL."
},
{
"code": null,
"e": 111880,
"s": 106461,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"400\" height = \"400\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*=================Creating a canvas=========================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n\n /*===========Defining and storing the geometry==============*/\n\n var vertices = [ -1,-1,-1, 1,-1,-1, 1, 1,-1 ];\n var colors = [ 1,1,1, 1,1,1, 1,1,1 ];\n var indices = [ 0,1,2 ];\n\n //Create and store data into vertex buffer\n var vertex_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n //Create and store data into color buffer\n var color_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n //Create and store data into index buffer\n var index_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n /*==========================Shaders=========================*/\n\n var vertCode = 'attribute vec3 position;'+\n 'uniform mat4 Pmatrix;'+\n 'uniform mat4 Vmatrix;'+\n 'uniform mat4 Mmatrix;'+\n 'attribute vec3 color;'+//the color of the point\n 'varying vec3 vColor;'+\n\n 'void main(void) { '+//pre-built function\n 'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+\n 'vColor = color;'+\n '}';\n\n var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n\n /*===========associating attributes to vertex shader ============*/\n\n var Pmatrix = gl.getUniformLocation(shaderProgram, \"Pmatrix\");\n var Vmatrix = gl.getUniformLocation(shaderProgram, \"Vmatrix\");\n var Mmatrix = gl.getUniformLocation(shaderProgram, \"Mmatrix\");\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n\n var position = gl.getAttribLocation(shaderProgram, \"position\");\n gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ; //position\n gl.enableVertexAttribArray(position);\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n\n var color = gl.getAttribLocation(shaderProgram, \"color\");\n gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ; //color\n gl.enableVertexAttribArray(color);\n gl.useProgram(shaderProgram);\n\n /*========================= MATRIX ========================= */\n\n function get_projection(angle, a, zMin, zMax) {\n var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5\n return [\n 0.5/ang, 0 , 0, 0,\n 0, 0.5*a/ang, 0, 0,\n 0, 0, -(zMax+zMin)/(zMax-zMin), -1,\n 0, 0, (-2*zMax*zMin)/(zMax-zMin), 0\n ];\n }\n\n var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);\n var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n\n //translating z\n view_matrix[14] = view_matrix[14]-6; //zoom\n\n /*=======================rotation========================*/\n function rotateZ(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8]; \n\n m[0] = c*m[0]-s*m[1];\n m[4] = c*m[4]-s*m[5];\n m[8] = c*m[8]-s*m[9];\n m[1] = c*m[1]+s*mv0;\n m[5] = c*m[5]+s*mv4;\n m[9] = c*m[9]+s*mv8;\n }\n\n /*=================Drawing===========================*/\n\n var time_old = 0;\n var animate = function(time) {\n var dt = time-time_old;\n rotateZ(mov_matrix, dt*0.002);\n time_old = time;\n\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.clearDepth(1.0);\n gl.viewport(0.0, 0.0, canvas.width, canvas.height);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);\n gl.uniformMatrix4fv(Vmatrix, false, view_matrix);\n gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);\n window.requestAnimationFrame(animate);\n }\n animate(0);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 111944,
"s": 111880,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 112044,
"s": 111944,
"text": "In this chapter, we will take an example to demonstrate how to draw a rotating 3D cube using WebGL."
},
{
"code": null,
"e": 112105,
"s": 112044,
"text": "The following program shows how to draw a rotating 3D cube −"
},
{
"code": null,
"e": 119018,
"s": 112105,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============= Creating a canvas =================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n\n /*============ Defining and storing the geometry =========*/\n\n var vertices = [\n -1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,\n -1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,\n -1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,\n 1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,\n -1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,\n -1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1, \n ];\n\n var colors = [\n 5,3,7, 5,3,7, 5,3,7, 5,3,7,\n 1,1,3, 1,1,3, 1,1,3, 1,1,3,\n 0,0,1, 0,0,1, 0,0,1, 0,0,1,\n 1,0,0, 1,0,0, 1,0,0, 1,0,0,\n 1,1,0, 1,1,0, 1,1,0, 1,1,0,\n 0,1,0, 0,1,0, 0,1,0, 0,1,0\n ];\n\n var indices = [\n 0,1,2, 0,2,3, 4,5,6, 4,6,7,\n 8,9,10, 8,10,11, 12,13,14, 12,14,15,\n 16,17,18, 16,18,19, 20,21,22, 20,22,23 \n ];\n\n // Create and store data into vertex buffer\n var vertex_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Create and store data into color buffer\n var color_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n // Create and store data into index buffer\n var index_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n /*=================== Shaders =========================*/\n\n var vertCode = 'attribute vec3 position;'+\n 'uniform mat4 Pmatrix;'+\n 'uniform mat4 Vmatrix;'+\n 'uniform mat4 Mmatrix;'+\n 'attribute vec3 color;'+//the color of the point\n 'varying vec3 vColor;'+\n\n 'void main(void) { '+//pre-built function\n 'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+\n 'vColor = color;'+\n '}';\n\n var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n\n var shaderProgram = gl.createProgram();\n gl.attachShader(shaderProgram, vertShader);\n gl.attachShader(shaderProgram, fragShader);\n gl.linkProgram(shaderProgram);\n\n /* ====== Associating attributes to vertex shader =====*/\n var Pmatrix = gl.getUniformLocation(shaderProgram, \"Pmatrix\");\n var Vmatrix = gl.getUniformLocation(shaderProgram, \"Vmatrix\");\n var Mmatrix = gl.getUniformLocation(shaderProgram, \"Mmatrix\");\n\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n var position = gl.getAttribLocation(shaderProgram, \"position\");\n gl.vertexAttribPointer(position, 3, gl.FLOAT, false,0,0) ;\n\n // Position\n gl.enableVertexAttribArray(position);\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n var color = gl.getAttribLocation(shaderProgram, \"color\");\n gl.vertexAttribPointer(color, 3, gl.FLOAT, false,0,0) ;\n\n // Color\n gl.enableVertexAttribArray(color);\n gl.useProgram(shaderProgram);\n\n /*==================== MATRIX =====================*/\n\n function get_projection(angle, a, zMin, zMax) {\n var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5\n return [\n 0.5/ang, 0 , 0, 0,\n 0, 0.5*a/ang, 0, 0,\n 0, 0, -(zMax+zMin)/(zMax-zMin), -1,\n 0, 0, (-2*zMax*zMin)/(zMax-zMin), 0 \n ];\n }\n\n var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);\n\n var mov_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n var view_matrix = [1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1];\n\n // translating z\n view_matrix[14] = view_matrix[14]-6;//zoom\n\n /*==================== Rotation ====================*/\n\n function rotateZ(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8];\n\n m[0] = c*m[0]-s*m[1];\n m[4] = c*m[4]-s*m[5];\n m[8] = c*m[8]-s*m[9];\n\n m[1]=c*m[1]+s*mv0;\n m[5]=c*m[5]+s*mv4;\n m[9]=c*m[9]+s*mv8;\n }\n\n function rotateX(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv1 = m[1], mv5 = m[5], mv9 = m[9];\n\n m[1] = m[1]*c-m[2]*s;\n m[5] = m[5]*c-m[6]*s;\n m[9] = m[9]*c-m[10]*s;\n\n m[2] = m[2]*c+mv1*s;\n m[6] = m[6]*c+mv5*s;\n m[10] = m[10]*c+mv9*s;\n }\n\n function rotateY(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8];\n\n m[0] = c*m[0]+s*m[2];\n m[4] = c*m[4]+s*m[6];\n m[8] = c*m[8]+s*m[10];\n\n m[2] = c*m[2]-s*mv0;\n m[6] = c*m[6]-s*mv4;\n m[10] = c*m[10]-s*mv8;\n }\n\n /*================= Drawing ===========================*/\n var time_old = 0;\n\n var animate = function(time) {\n\n var dt = time-time_old;\n rotateZ(mov_matrix, dt*0.005);//time\n rotateY(mov_matrix, dt*0.002);\n rotateX(mov_matrix, dt*0.003);\n time_old = time;\n\n gl.enable(gl.DEPTH_TEST);\n gl.depthFunc(gl.LEQUAL);\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.clearDepth(1.0);\n\n gl.viewport(0.0, 0.0, canvas.width, canvas.height);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n gl.uniformMatrix4fv(Pmatrix, false, proj_matrix);\n gl.uniformMatrix4fv(Vmatrix, false, view_matrix);\n gl.uniformMatrix4fv(Mmatrix, false, mov_matrix);\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);\n\n window.requestAnimationFrame(animate);\n }\n animate(0);\n </script>\n </body>\n</html>"
},
{
"code": null,
"e": 119082,
"s": 119018,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 119202,
"s": 119082,
"text": "In this chapter, we will take an example to demonstrate how to draw a 3D cube that can be rotated using mouse controls."
},
{
"code": null,
"e": 119274,
"s": 119202,
"text": "The following program shows how to rotate a cube using mouse controls −"
},
{
"code": null,
"e": 127319,
"s": 119274,
"text": "<!doctype html>\n<html>\n <body>\n <canvas width = \"570\" height = \"570\" id = \"my_Canvas\"></canvas>\n\n <script>\n /*============= Creating a canvas ======================*/\n var canvas = document.getElementById('my_Canvas');\n gl = canvas.getContext('experimental-webgl');\n\n /*========== Defining and storing the geometry ==========*/\n\n var vertices = [\n -1,-1,-1, 1,-1,-1, 1, 1,-1, -1, 1,-1,\n -1,-1, 1, 1,-1, 1, 1, 1, 1, -1, 1, 1,\n -1,-1,-1, -1, 1,-1, -1, 1, 1, -1,-1, 1,\n 1,-1,-1, 1, 1,-1, 1, 1, 1, 1,-1, 1,\n -1,-1,-1, -1,-1, 1, 1,-1, 1, 1,-1,-1,\n -1, 1,-1, -1, 1, 1, 1, 1, 1, 1, 1,-1, \n ];\n\n var colors = [\n 5,3,7, 5,3,7, 5,3,7, 5,3,7,\n 1,1,3, 1,1,3, 1,1,3, 1,1,3,\n 0,0,1, 0,0,1, 0,0,1, 0,0,1,\n 1,0,0, 1,0,0, 1,0,0, 1,0,0,\n 1,1,0, 1,1,0, 1,1,0, 1,1,0,\n 0,1,0, 0,1,0, 0,1,0, 0,1,0 \n ];\n\n var indices = [\n 0,1,2, 0,2,3, 4,5,6, 4,6,7,\n 8,9,10, 8,10,11, 12,13,14, 12,14,15,\n 16,17,18, 16,18,19, 20,21,22, 20,22,23 \n ];\n\n // Create and store data into vertex buffer\n var vertex_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(vertices), gl.STATIC_DRAW);\n\n // Create and store data into color buffer\n var color_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n gl.bufferData(gl.ARRAY_BUFFER, new Float32Array(colors), gl.STATIC_DRAW);\n\n // Create and store data into index buffer\n var index_buffer = gl.createBuffer ();\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.bufferData(gl.ELEMENT_ARRAY_BUFFER, new Uint16Array(indices), gl.STATIC_DRAW);\n\n /*=================== SHADERS =================== */\n\n var vertCode = 'attribute vec3 position;'+\n 'uniform mat4 Pmatrix;'+\n 'uniform mat4 Vmatrix;'+\n 'uniform mat4 Mmatrix;'+\n 'attribute vec3 color;'+//the color of the point\n 'varying vec3 vColor;'+\n 'void main(void) { '+//pre-built function\n 'gl_Position = Pmatrix*Vmatrix*Mmatrix*vec4(position, 1.);'+\n 'vColor = color;'+\n '}';\n\n var fragCode = 'precision mediump float;'+\n 'varying vec3 vColor;'+\n 'void main(void) {'+\n 'gl_FragColor = vec4(vColor, 1.);'+\n '}';\n\n var vertShader = gl.createShader(gl.VERTEX_SHADER);\n gl.shaderSource(vertShader, vertCode);\n gl.compileShader(vertShader);\n\n var fragShader = gl.createShader(gl.FRAGMENT_SHADER);\n gl.shaderSource(fragShader, fragCode);\n gl.compileShader(fragShader);\n\n var shaderprogram = gl.createProgram();\n gl.attachShader(shaderprogram, vertShader);\n gl.attachShader(shaderprogram, fragShader);\n gl.linkProgram(shaderprogram);\n\n /*======== Associating attributes to vertex shader =====*/\n var _Pmatrix = gl.getUniformLocation(shaderprogram, \"Pmatrix\");\n var _Vmatrix = gl.getUniformLocation(shaderprogram, \"Vmatrix\");\n var _Mmatrix = gl.getUniformLocation(shaderprogram, \"Mmatrix\");\n\n gl.bindBuffer(gl.ARRAY_BUFFER, vertex_buffer);\n var _position = gl.getAttribLocation(shaderprogram, \"position\");\n gl.vertexAttribPointer(_position, 3, gl.FLOAT, false,0,0);\n gl.enableVertexAttribArray(_position);\n\n gl.bindBuffer(gl.ARRAY_BUFFER, color_buffer);\n var _color = gl.getAttribLocation(shaderprogram, \"color\");\n gl.vertexAttribPointer(_color, 3, gl.FLOAT, false,0,0) ;\n gl.enableVertexAttribArray(_color);\n gl.useProgram(shaderprogram);\n\n /*==================== MATRIX ====================== */\n\n function get_projection(angle, a, zMin, zMax) {\n var ang = Math.tan((angle*.5)*Math.PI/180);//angle*.5\n return [\n 0.5/ang, 0 , 0, 0,\n 0, 0.5*a/ang, 0, 0,\n 0, 0, -(zMax+zMin)/(zMax-zMin), -1,\n 0, 0, (-2*zMax*zMin)/(zMax-zMin), 0 \n\t\t\t ];\n }\n\n var proj_matrix = get_projection(40, canvas.width/canvas.height, 1, 100);\n var mo_matrix = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 ];\n var view_matrix = [ 1,0,0,0, 0,1,0,0, 0,0,1,0, 0,0,0,1 ];\n\n view_matrix[14] = view_matrix[14]-6;\n\n /*================= Mouse events ======================*/\n\n var AMORTIZATION = 0.95;\n var drag = false;\n var old_x, old_y;\n var dX = 0, dY = 0;\n\n var mouseDown = function(e) {\n drag = true;\n old_x = e.pageX, old_y = e.pageY;\n e.preventDefault();\n return false;\n };\n\n var mouseUp = function(e){\n drag = false;\n };\n\n var mouseMove = function(e) {\n if (!drag) return false;\n dX = (e.pageX-old_x)*2*Math.PI/canvas.width,\n dY = (e.pageY-old_y)*2*Math.PI/canvas.height;\n THETA+= dX;\n PHI+=dY;\n old_x = e.pageX, old_y = e.pageY;\n e.preventDefault();\n };\n\n canvas.addEventListener(\"mousedown\", mouseDown, false);\n canvas.addEventListener(\"mouseup\", mouseUp, false);\n canvas.addEventListener(\"mouseout\", mouseUp, false);\n canvas.addEventListener(\"mousemove\", mouseMove, false);\n\n /*=========================rotation================*/\n\n function rotateX(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv1 = m[1], mv5 = m[5], mv9 = m[9];\n\n m[1] = m[1]*c-m[2]*s;\n m[5] = m[5]*c-m[6]*s;\n m[9] = m[9]*c-m[10]*s;\n\n m[2] = m[2]*c+mv1*s;\n m[6] = m[6]*c+mv5*s;\n m[10] = m[10]*c+mv9*s;\n }\n\n function rotateY(m, angle) {\n var c = Math.cos(angle);\n var s = Math.sin(angle);\n var mv0 = m[0], mv4 = m[4], mv8 = m[8];\n\n m[0] = c*m[0]+s*m[2];\n m[4] = c*m[4]+s*m[6];\n m[8] = c*m[8]+s*m[10];\n\n m[2] = c*m[2]-s*mv0;\n m[6] = c*m[6]-s*mv4;\n m[10] = c*m[10]-s*mv8;\n }\n\n /*=================== Drawing =================== */\n\n var THETA = 0,\n PHI = 0;\n var time_old = 0;\n\n var animate = function(time) {\n var dt = time-time_old;\n\n if (!drag) {\n dX *= AMORTIZATION, dY*=AMORTIZATION;\n THETA+=dX, PHI+=dY;\n }\n\n //set model matrix to I4\n\n mo_matrix[0] = 1, mo_matrix[1] = 0, mo_matrix[2] = 0,\n mo_matrix[3] = 0,\n\n mo_matrix[4] = 0, mo_matrix[5] = 1, mo_matrix[6] = 0,\n mo_matrix[7] = 0,\n\n mo_matrix[8] = 0, mo_matrix[9] = 0, mo_matrix[10] = 1,\n mo_matrix[11] = 0,\n\n mo_matrix[12] = 0, mo_matrix[13] = 0, mo_matrix[14] = 0,\n mo_matrix[15] = 1;\n\n rotateY(mo_matrix, THETA);\n rotateX(mo_matrix, PHI);\n\n time_old = time; \n gl.enable(gl.DEPTH_TEST);\n\n // gl.depthFunc(gl.LEQUAL);\n\n gl.clearColor(0.5, 0.5, 0.5, 0.9);\n gl.clearDepth(1.0);\n gl.viewport(0.0, 0.0, canvas.width, canvas.height);\n gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT);\n\n gl.uniformMatrix4fv(_Pmatrix, false, proj_matrix);\n gl.uniformMatrix4fv(_Vmatrix, false, view_matrix);\n gl.uniformMatrix4fv(_Mmatrix, false, mo_matrix);\n\n gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER, index_buffer);\n gl.drawElements(gl.TRIANGLES, indices.length, gl.UNSIGNED_SHORT, 0);\n\n window.requestAnimationFrame(animate);\n }\n animate(0);\n </script>\n </body>\n</html> "
},
{
"code": null,
"e": 127383,
"s": 127319,
"text": "If you run this example, it will produce the following output −"
},
{
"code": null,
"e": 127416,
"s": 127383,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 127433,
"s": 127416,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 127466,
"s": 127433,
"text": "\n 28 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 127483,
"s": 127466,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 127490,
"s": 127483,
"text": " Print"
},
{
"code": null,
"e": 127501,
"s": 127490,
"text": " Add Notes"
}
] |
GATE | GATE CS 2020 | Question 48 - GeeksforGeeks | 26 May, 2021
An organization requires a range of IP address to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign an address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. Which of the following address spaces are potential candidates from which the ISP can allot any one of the organization ?
I. 202.61.84.0 / 21
II. 202.61.104.0 / 21
III. 202.61.64.0 / 21
IV. 202.61.144.0 / 21
(A) I and II only(B) II and III only(C) III and IV only(D) I and IV onlyAnswer: (B)Explanation: Subnet Mask for given IP address:
202.61.0.0/17
⇒ 11111111 11111111 10000000 00000000
⇒ 255.255.128.0
Now, since we need 1500 hosts, so, bits for host address,
= ceiling (log2 (1500))
= ceiling (10.55)
= 11 bits for host address
So, last 11 bits will for in host addresses:
00000000.00000000 → 00000111.11111111 (0.0 → 7.255)
00001000.00000000 → 00010000.00000000 (8.0 - 15.255)
00001111.11111111 → 00010111.11111111 (16.0 - 23.255)
Sequence is 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120.
Hence 64 and 104 is present in sequence so it is the possible IP addresses.
So option (B) is correct.Quiz of this Question
GATE
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
GATE | GATE-CS-2016 (Set 2) | Question 48
GATE | GATE-CS-2014-(Set-1) | Question 30
GATE | GATE-CS-2001 | Question 23
GATE | GATE-CS-2015 (Set 1) | Question 65
GATE | GATE CS 2010 | Question 45
GATE | GATE-CS-2004 | Question 3
GATE | GATE-CS-2015 (Set 3) | Question 65
C++ Program to count Vowels in a string using Pointer
GATE | GATE CS 2012 | Question 40
GATE | GATE-CS-2001 | Question 48 | [
{
"code": null,
"e": 24083,
"s": 24055,
"text": "\n26 May, 2021"
},
{
"code": null,
"e": 24628,
"s": 24083,
"text": "An organization requires a range of IP address to assign one to each of its 1500 computers. The organization has approached an Internet Service Provider (ISP) for this task. The ISP uses CIDR and serves the requests from the available IP address space 202.61.0.0/17. The ISP wants to assign an address space to the organization which will minimize the number of routing entries in the ISP’s router using route aggregation. Which of the following address spaces are potential candidates from which the ISP can allot any one of the organization ?"
},
{
"code": null,
"e": 24715,
"s": 24628,
"text": "I. 202.61.84.0 / 21\nII. 202.61.104.0 / 21\nIII. 202.61.64.0 / 21\nIV. 202.61.144.0 / 21 "
},
{
"code": null,
"e": 24845,
"s": 24715,
"text": "(A) I and II only(B) II and III only(C) III and IV only(D) I and IV onlyAnswer: (B)Explanation: Subnet Mask for given IP address:"
},
{
"code": null,
"e": 24915,
"s": 24845,
"text": "202.61.0.0/17 \n⇒ 11111111 11111111 10000000 00000000\n⇒ 255.255.128.0 "
},
{
"code": null,
"e": 24973,
"s": 24915,
"text": "Now, since we need 1500 hosts, so, bits for host address,"
},
{
"code": null,
"e": 25045,
"s": 24973,
"text": "= ceiling (log2 (1500)) \n= ceiling (10.55) \n= 11 bits for host address "
},
{
"code": null,
"e": 25090,
"s": 25045,
"text": "So, last 11 bits will for in host addresses:"
},
{
"code": null,
"e": 25254,
"s": 25090,
"text": "00000000.00000000 → 00000111.11111111 (0.0 → 7.255)\n\n00001000.00000000 → 00010000.00000000 (8.0 - 15.255)\n\n00001111.11111111 → 00010111.11111111 (16.0 - 23.255) "
},
{
"code": null,
"e": 25327,
"s": 25254,
"text": "Sequence is 0, 8, 16, 24, 32, 40, 48, 56, 64, 72, 80, 96, 104, 112, 120."
},
{
"code": null,
"e": 25403,
"s": 25327,
"text": "Hence 64 and 104 is present in sequence so it is the possible IP addresses."
},
{
"code": null,
"e": 25450,
"s": 25403,
"text": "So option (B) is correct.Quiz of this Question"
},
{
"code": null,
"e": 25455,
"s": 25450,
"text": "GATE"
},
{
"code": null,
"e": 25553,
"s": 25455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25562,
"s": 25553,
"text": "Comments"
},
{
"code": null,
"e": 25575,
"s": 25562,
"text": "Old Comments"
},
{
"code": null,
"e": 25617,
"s": 25575,
"text": "GATE | GATE-CS-2016 (Set 2) | Question 48"
},
{
"code": null,
"e": 25659,
"s": 25617,
"text": "GATE | GATE-CS-2014-(Set-1) | Question 30"
},
{
"code": null,
"e": 25693,
"s": 25659,
"text": "GATE | GATE-CS-2001 | Question 23"
},
{
"code": null,
"e": 25735,
"s": 25693,
"text": "GATE | GATE-CS-2015 (Set 1) | Question 65"
},
{
"code": null,
"e": 25769,
"s": 25735,
"text": "GATE | GATE CS 2010 | Question 45"
},
{
"code": null,
"e": 25802,
"s": 25769,
"text": "GATE | GATE-CS-2004 | Question 3"
},
{
"code": null,
"e": 25844,
"s": 25802,
"text": "GATE | GATE-CS-2015 (Set 3) | Question 65"
},
{
"code": null,
"e": 25898,
"s": 25844,
"text": "C++ Program to count Vowels in a string using Pointer"
},
{
"code": null,
"e": 25932,
"s": 25898,
"text": "GATE | GATE CS 2012 | Question 40"
}
] |
Alternative for <blink> tag - GeeksforGeeks | 04 Jan, 2022
In this article we will learn about the alternatives of the blink tag of HTML. The blink tag doesn’t have any alternative HTML tag but the same effect can be alternatively created with the help of CSS
Example:
In this example we will be using CSS animations to get the blink-effect
html
<!DOCTYPE html><html> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>Geeksforgeeks</title> <style type="text/css"> /* Minor Styling optional */ .blinky{ margin: auto; width: 200px; height: 200px; background: cyan; text-align: center; font-size: 24px; /* for support in Safari 4.0 - 8.0 */ -webkit-animation: 1.5s linear infinite blinky-effect; animation: 1.5s linear infinite blinky-effect; } /* for support in Safari 4.0 - 8.0 */ @-webkit-keyframes blinky-effect { 0% { visibility: hidden; } 50% { visibility: hidden; } 100% { visibility: visible; } } @keyframes blinky-effect { 0% { visibility: hidden; } 50% { visibility: hidden; } 100% { visibility: visible; } } </style> </head> <body> <div class="blinky"> This div is going to blink </div> </body></html>
Output:
Blink-Effect using CSS animations.
Advantages of the CSS approach over the blink tag
In general the blink tag should not be used as it is a obsolete feature and can be removed in further updates. In order to learn more about CSS animations refer this article: CSS Animations
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
surindertarika1234
avtarkumar719
HTML-Misc
Picked
HTML
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Types of CSS (Cascading Style Sheet)
HTML | <img> align Attribute
Form validation using HTML and JavaScript
HTML Introduction
How to Upload Image into Database and Display it using PHP ?
Express.js express.Router() Function
Installation of Node.js on Linux
Convert a string to an integer in JavaScript
Top 10 Angular Libraries For Web Developers
How to create footer to stay at the bottom of a Web page? | [
{
"code": null,
"e": 23989,
"s": 23961,
"text": "\n04 Jan, 2022"
},
{
"code": null,
"e": 24190,
"s": 23989,
"text": "In this article we will learn about the alternatives of the blink tag of HTML. The blink tag doesn’t have any alternative HTML tag but the same effect can be alternatively created with the help of CSS"
},
{
"code": null,
"e": 24199,
"s": 24190,
"text": "Example:"
},
{
"code": null,
"e": 24271,
"s": 24199,
"text": "In this example we will be using CSS animations to get the blink-effect"
},
{
"code": null,
"e": 24276,
"s": 24271,
"text": "html"
},
{
"code": "<!DOCTYPE html><html> <head> <meta http-equiv=\"content-type\" content=\"text/html; charset=utf-8\" /> <title>Geeksforgeeks</title> <style type=\"text/css\"> /* Minor Styling optional */ .blinky{ margin: auto; width: 200px; height: 200px; background: cyan; text-align: center; font-size: 24px; /* for support in Safari 4.0 - 8.0 */ -webkit-animation: 1.5s linear infinite blinky-effect; animation: 1.5s linear infinite blinky-effect; } /* for support in Safari 4.0 - 8.0 */ @-webkit-keyframes blinky-effect { 0% { visibility: hidden; } 50% { visibility: hidden; } 100% { visibility: visible; } } @keyframes blinky-effect { 0% { visibility: hidden; } 50% { visibility: hidden; } 100% { visibility: visible; } } </style> </head> <body> <div class=\"blinky\"> This div is going to blink </div> </body></html>",
"e": 25691,
"s": 24276,
"text": null
},
{
"code": null,
"e": 25699,
"s": 25691,
"text": "Output:"
},
{
"code": null,
"e": 25734,
"s": 25699,
"text": "Blink-Effect using CSS animations."
},
{
"code": null,
"e": 25786,
"s": 25734,
"text": "Advantages of the CSS approach over the blink tag "
},
{
"code": null,
"e": 25978,
"s": 25788,
"text": "In general the blink tag should not be used as it is a obsolete feature and can be removed in further updates. In order to learn more about CSS animations refer this article: CSS Animations"
},
{
"code": null,
"e": 26117,
"s": 25980,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 26136,
"s": 26117,
"text": "surindertarika1234"
},
{
"code": null,
"e": 26150,
"s": 26136,
"text": "avtarkumar719"
},
{
"code": null,
"e": 26160,
"s": 26150,
"text": "HTML-Misc"
},
{
"code": null,
"e": 26167,
"s": 26160,
"text": "Picked"
},
{
"code": null,
"e": 26172,
"s": 26167,
"text": "HTML"
},
{
"code": null,
"e": 26189,
"s": 26172,
"text": "Web Technologies"
},
{
"code": null,
"e": 26194,
"s": 26189,
"text": "HTML"
},
{
"code": null,
"e": 26292,
"s": 26194,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 26301,
"s": 26292,
"text": "Comments"
},
{
"code": null,
"e": 26314,
"s": 26301,
"text": "Old Comments"
},
{
"code": null,
"e": 26351,
"s": 26314,
"text": "Types of CSS (Cascading Style Sheet)"
},
{
"code": null,
"e": 26380,
"s": 26351,
"text": "HTML | <img> align Attribute"
},
{
"code": null,
"e": 26422,
"s": 26380,
"text": "Form validation using HTML and JavaScript"
},
{
"code": null,
"e": 26440,
"s": 26422,
"text": "HTML Introduction"
},
{
"code": null,
"e": 26501,
"s": 26440,
"text": "How to Upload Image into Database and Display it using PHP ?"
},
{
"code": null,
"e": 26538,
"s": 26501,
"text": "Express.js express.Router() Function"
},
{
"code": null,
"e": 26571,
"s": 26538,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 26616,
"s": 26571,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 26660,
"s": 26616,
"text": "Top 10 Angular Libraries For Web Developers"
}
] |
You Should Start Using FastAPI Now | by Tivadar Danka | Towards Data Science | Python has always been a popular choice for developing lightweight web apps, thanks to the awesome frameworks like Flask, Django, Falcon and many others. Due to Python’s position as the number one language for machine learning, it is particularly convenient for packaging models and exposing them as a service.
For many years, Flask was the number one tool for the job, but in case you haven’t heard, there is a new challenger in town. FastAPI is a relatively new web framework for Python, taking inspiration from its predecessors, perfecting them and fixing many of their flaws. Built on top of Starlette, it brings a ton of awesome features to the table.
It has gained significant traction recently, and after spending the last 8 months working with it every day, I can confidently say that the hype is justified. If you haven’t tried it yet, I would like to give you five reasons to give it a shot.
All web frameworks need to balance between functionality and giving freedom for the developer. Django is powerful yet very opinionated. On the other hand, Flask is low level enough to provide a large degree of freedom, but a lot is left for the user to do. FastAPI is more on the Flask side of the spectrum, but it manages to strike a healthier balance.
To give you an example, let’s see how an endpoint is defined in FastAPI.
For defining the schema, it uses Pydantic, which is another awesome Python library, used for data validation. This is simple to do here, yet so much is happening in the background. The responsibility to validate the input is delegated to FastAPI. If the request is not right, for instance the email field contains an int, an appropriate error code will be returned, instead of the app breaking down with the dreaded Internal Server Error (500). And it is practically free.
This simple example app can be served with uvicorn:
uvicorn main:app
Now the app is ready to accept requests. In this case, a request would look like
curl -X POST "http://localhost:8000/login" -H "accept: application/json" -H "Content-Type: application/json" -d "{\"email\":\"string\",\"password\":\"string\"}"
The icing on the cake is that it automatically generates the documentation according to the OpenAPI using the interactive Swagger UI.
One of the biggest disadvantage of Python WSGI web frameworks compared to the ones in Node.js or Go was the inability to handle requests asynchronously. Since the introduction of ASGI, this is no longer an issue, and FastAPI is taking full advantage of this. All you have to do is simply declare the endpoints with the async keyword like this:
FastAPI has a really cool way to manage dependencies. Although it is not forced on the developer, it is strongly encouraged to use the built-in injection system to handle dependencies in your endpoints.
To give an example, let’s write an endpoint, where users can post comments to certain articles.
FastAPI automatically evaluates the get_database function at runtime when the endpoint is called, so you can use the return value as you wish. There are (at least) two good reasons for this.
You can override the dependencies globally by modifying the app.dependency_overrides dictionary. This can make testing a breeze, since you can mock objects easily.The dependency (which is the get_database in our case) can perform more sophisticated checks, allowing you to separate them from business logic. This greatly simplifies things. For instance, user authentication can be easily implemented with this.
You can override the dependencies globally by modifying the app.dependency_overrides dictionary. This can make testing a breeze, since you can mock objects easily.
The dependency (which is the get_database in our case) can perform more sophisticated checks, allowing you to separate them from business logic. This greatly simplifies things. For instance, user authentication can be easily implemented with this.
SQL, MongoDB, Redis, or whatever you choose, FastAPI doesn’t force your hand to build your application around it. If you have ever tried to work with MongoDB using Django, you know how painful it can be. With FastAPI, you don’t need to go the extra mile, adding a database to your stack is as simple as possible. (Or to be more precise, the amount of work to be done will be determined by the database you choose, not by the complications added by the web framework.)
But really, look at this beauty.
Voila! I can see you typing
pip install fastapi
into your terminal already.
When you are working with a complex data model, REST can be a serious hindrance. It is definitely not fun when a tiny change in the frontend requires to update the schema for an endpoint. GraphQL shines in these situations. Although GraphQL support is not unique among Python web frameworks, Graphene and FastAPI work together seamlessly. No need to install any extensions like graphene_django for Django, it just works natively.
Of course, a great framework cannot truly shine without an equally great documentation. Django, Flask and all the others excel in this aspect, but FastAPI is on par with them. Of course, since it is much younger, there are no books written about it yet, but it is just a matter of time.
If you would like to see FastAPI in action, I have just the perfect guide for you! I have written a detailed tutorial, where you can deploy your machine learning model using Docker, Docker Compose and GitHub Actions!
towardsdatascience.com
To summarize, whether you are looking for a fast and lightweight framework to serve your deep learning models or something more complex, FastAPI delivers. If you haven’t tried it yet, I strongly encourage you to do so. I am pretty sure you’ll stick with it.
If you love taking machine learning concepts apart and understanding what makes them tick, we have a lot in common. Check out my blog, where I frequently publish technical posts like this! | [
{
"code": null,
"e": 358,
"s": 47,
"text": "Python has always been a popular choice for developing lightweight web apps, thanks to the awesome frameworks like Flask, Django, Falcon and many others. Due to Python’s position as the number one language for machine learning, it is particularly convenient for packaging models and exposing them as a service."
},
{
"code": null,
"e": 704,
"s": 358,
"text": "For many years, Flask was the number one tool for the job, but in case you haven’t heard, there is a new challenger in town. FastAPI is a relatively new web framework for Python, taking inspiration from its predecessors, perfecting them and fixing many of their flaws. Built on top of Starlette, it brings a ton of awesome features to the table."
},
{
"code": null,
"e": 949,
"s": 704,
"text": "It has gained significant traction recently, and after spending the last 8 months working with it every day, I can confidently say that the hype is justified. If you haven’t tried it yet, I would like to give you five reasons to give it a shot."
},
{
"code": null,
"e": 1303,
"s": 949,
"text": "All web frameworks need to balance between functionality and giving freedom for the developer. Django is powerful yet very opinionated. On the other hand, Flask is low level enough to provide a large degree of freedom, but a lot is left for the user to do. FastAPI is more on the Flask side of the spectrum, but it manages to strike a healthier balance."
},
{
"code": null,
"e": 1376,
"s": 1303,
"text": "To give you an example, let’s see how an endpoint is defined in FastAPI."
},
{
"code": null,
"e": 1849,
"s": 1376,
"text": "For defining the schema, it uses Pydantic, which is another awesome Python library, used for data validation. This is simple to do here, yet so much is happening in the background. The responsibility to validate the input is delegated to FastAPI. If the request is not right, for instance the email field contains an int, an appropriate error code will be returned, instead of the app breaking down with the dreaded Internal Server Error (500). And it is practically free."
},
{
"code": null,
"e": 1901,
"s": 1849,
"text": "This simple example app can be served with uvicorn:"
},
{
"code": null,
"e": 1918,
"s": 1901,
"text": "uvicorn main:app"
},
{
"code": null,
"e": 1999,
"s": 1918,
"text": "Now the app is ready to accept requests. In this case, a request would look like"
},
{
"code": null,
"e": 2162,
"s": 1999,
"text": "curl -X POST \"http://localhost:8000/login\" -H \"accept: application/json\" -H \"Content-Type: application/json\" -d \"{\\\"email\\\":\\\"string\\\",\\\"password\\\":\\\"string\\\"}\""
},
{
"code": null,
"e": 2296,
"s": 2162,
"text": "The icing on the cake is that it automatically generates the documentation according to the OpenAPI using the interactive Swagger UI."
},
{
"code": null,
"e": 2640,
"s": 2296,
"text": "One of the biggest disadvantage of Python WSGI web frameworks compared to the ones in Node.js or Go was the inability to handle requests asynchronously. Since the introduction of ASGI, this is no longer an issue, and FastAPI is taking full advantage of this. All you have to do is simply declare the endpoints with the async keyword like this:"
},
{
"code": null,
"e": 2843,
"s": 2640,
"text": "FastAPI has a really cool way to manage dependencies. Although it is not forced on the developer, it is strongly encouraged to use the built-in injection system to handle dependencies in your endpoints."
},
{
"code": null,
"e": 2939,
"s": 2843,
"text": "To give an example, let’s write an endpoint, where users can post comments to certain articles."
},
{
"code": null,
"e": 3130,
"s": 2939,
"text": "FastAPI automatically evaluates the get_database function at runtime when the endpoint is called, so you can use the return value as you wish. There are (at least) two good reasons for this."
},
{
"code": null,
"e": 3541,
"s": 3130,
"text": "You can override the dependencies globally by modifying the app.dependency_overrides dictionary. This can make testing a breeze, since you can mock objects easily.The dependency (which is the get_database in our case) can perform more sophisticated checks, allowing you to separate them from business logic. This greatly simplifies things. For instance, user authentication can be easily implemented with this."
},
{
"code": null,
"e": 3705,
"s": 3541,
"text": "You can override the dependencies globally by modifying the app.dependency_overrides dictionary. This can make testing a breeze, since you can mock objects easily."
},
{
"code": null,
"e": 3953,
"s": 3705,
"text": "The dependency (which is the get_database in our case) can perform more sophisticated checks, allowing you to separate them from business logic. This greatly simplifies things. For instance, user authentication can be easily implemented with this."
},
{
"code": null,
"e": 4421,
"s": 3953,
"text": "SQL, MongoDB, Redis, or whatever you choose, FastAPI doesn’t force your hand to build your application around it. If you have ever tried to work with MongoDB using Django, you know how painful it can be. With FastAPI, you don’t need to go the extra mile, adding a database to your stack is as simple as possible. (Or to be more precise, the amount of work to be done will be determined by the database you choose, not by the complications added by the web framework.)"
},
{
"code": null,
"e": 4454,
"s": 4421,
"text": "But really, look at this beauty."
},
{
"code": null,
"e": 4482,
"s": 4454,
"text": "Voila! I can see you typing"
},
{
"code": null,
"e": 4502,
"s": 4482,
"text": "pip install fastapi"
},
{
"code": null,
"e": 4530,
"s": 4502,
"text": "into your terminal already."
},
{
"code": null,
"e": 4960,
"s": 4530,
"text": "When you are working with a complex data model, REST can be a serious hindrance. It is definitely not fun when a tiny change in the frontend requires to update the schema for an endpoint. GraphQL shines in these situations. Although GraphQL support is not unique among Python web frameworks, Graphene and FastAPI work together seamlessly. No need to install any extensions like graphene_django for Django, it just works natively."
},
{
"code": null,
"e": 5247,
"s": 4960,
"text": "Of course, a great framework cannot truly shine without an equally great documentation. Django, Flask and all the others excel in this aspect, but FastAPI is on par with them. Of course, since it is much younger, there are no books written about it yet, but it is just a matter of time."
},
{
"code": null,
"e": 5464,
"s": 5247,
"text": "If you would like to see FastAPI in action, I have just the perfect guide for you! I have written a detailed tutorial, where you can deploy your machine learning model using Docker, Docker Compose and GitHub Actions!"
},
{
"code": null,
"e": 5487,
"s": 5464,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 5745,
"s": 5487,
"text": "To summarize, whether you are looking for a fast and lightweight framework to serve your deep learning models or something more complex, FastAPI delivers. If you haven’t tried it yet, I strongly encourage you to do so. I am pretty sure you’ll stick with it."
}
] |
Increase or decrease the size of a font with CSS | The font-size property is used to increase or decrease the font size. The font-size property is used to control the size of fonts. Possible values could be xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, size in pixels or in %.
<html>
<head>
</head>
<body>
<p style = "font-size:15px;">This font size is 15 pixels</p>
<p style = "font-size:small;">This font size is small</p>
<p style = "font-size:large;">This font size is large</p>
</body>
</html> | [
{
"code": null,
"e": 1319,
"s": 1062,
"text": "The font-size property is used to increase or decrease the font size. The font-size property is used to control the size of fonts. Possible values could be xx-small, x-small, small, medium, large, x-large, xx-large, smaller, larger, size in pixels or in %."
},
{
"code": null,
"e": 1571,
"s": 1319,
"text": "<html>\n <head>\n </head>\n <body>\n <p style = \"font-size:15px;\">This font size is 15 pixels</p>\n <p style = \"font-size:small;\">This font size is small</p>\n <p style = \"font-size:large;\">This font size is large</p>\n </body>\n</html>"
}
] |
Dynamically Add/Delete HTML Table Rows Using Javascript | Theory of Computation
In this article, you will learn how to create a simple user interface where a user can add or delete multiple table rows in a form dynamically using Javascript.
Sometimes, there may be a requirement for the user to add multiple repeated row's fields in a form. We cannot assume how many fields we should provide on the webpage. Like, we need to provide some employees details. There is no surety of how many employee details, may be later we have to delete some. Let's discuss how we can achieve these tasks. In this post, we will write code to add or remove the entire row with there input fields dynamically using Javascript. We will provide two buttons, the first button to add new rows to the table and the second to remove rows.
As we know, Javascript is a dynamic language. It means it can control, access and manipulate the HTML elements dynamically on the client side. We can easily add and remove HTML elements in a web page using Javascript. In this article, we will provide you with a simple way to add or remove HTML table rows with there fields dynamically. The below code has an HTML form and two javascript functions addRows() and deleteRows() to add and delete the table rows respectively.
<html>
<head>
<title>Onclick increase Table Rows</title>
<script type="text/javascript">
function addRows(){
var table = document.getElementById('emptbl');
var rowCount = table.rows.length;
var cellCount = table.rows[0].cells.length;
var row = table.insertRow(rowCount);
for(var i =0; i <= cellCount; i++){
var cell = 'cell'+i;
cell = row.insertCell(i);
var copycel = document.getElementById('col'+i).innerHTML;
cell.innerHTML=copycel;
if(i == 3){
var radioinput = document.getElementById('col3').getElementsByTagName('input');
for(var j = 0; j <= radioinput.length; j++) {
if(radioinput[j].type == 'radio') {
var rownum = rowCount;
radioinput[j].name = 'gender['+rownum+']';
}
}
}
}
}
function deleteRows(){
var table = document.getElementById('emptbl');
var rowCount = table.rows.length;
if(rowCount > '2'){
var row = table.deleteRow(rowCount-1);
rowCount--;
}
else{
alert('There should be atleast one row');
}
}
</script>
</head>
<body>
<form action="#" method="post">
<table id="emptbl">
<tr>
<th>Employee Name</th>
<th>Phone</th>
<th>Department</th>
<th>Gender</th>
</tr>
<tr>
<td id="col0"><input type="text" name="empname[]" value="" /></td>
<td id="col1"><input type="text" name="phone[]" value="" /></td>
<td id="col2">
<select name="department[]" id="dept">
<option value="0">Select Department</option>
<option value="1">Sales</option>
<option value="2">IT</option>
<option value="3">Warehouse</option>
</select>
</td>
<td id="col3">
<input type="radio" name="gender[0]" value="male" />Male
<input type="radio" name="gender[1]" value="female" />Female
</td>
</tr>
</table>
<table>
<tr>
<td><input type="button" value="Add Row" onclick="addRows()" /></td>
<td><input type="button" value="Delete Row" onclick="deleteRows()" /></td>
<td><input type="submit" value="Submit" /></td>
</tr>
</table>
</form>
</body>
</html>
In the above code, we have taken a form element with three buttons to Add Row, Delete Row and Submit form data. Within the form element, we have taken a table to display the form input data. To perform dynamic operations on the table using Javascript, we have given an id 'emptbl' to the table.
These are the step-by-step code explanations on how a new row is dynamically created when user clicks on the 'Add Row' button.
addRows() - Within the head section, we have created a Javascript function name addRows() that is responsible for adding a new table row with input fields. For this, first we got the table element with table id and stored in a javascript variable table.
var table = document.getElementById('emptbl');
Next, we stored the number of <tr> element using the Javascript property rows.length in a variable rowCount and rows[0].cells.length property returns number of <td> elements of first row.
var rowCount = table.rows.length;
var cellCount = table.rows[0].cells.length;
Next, we have created an empty row using Javascript property insertRow().
var row = table.insertRow(rowCount);
Next, we have dynamically generated the cells within the empty row using a for loop and taken the innerHTML of the old cell with cell index and paste it in the new one.
for(var i =0; i <= cellCount; i++){
}
These are the step-by-step code explanations on how an existing row is dynamically deleted when a user clicks the 'Delete Row' button.
deleteRows() - Within the head section after addRows() function, we have created other Javascript function name deleteRows() that is responsible to delete existing table row with input fields. For this, first we got the table element with table id and stored in a variable table.
Next, we stored the number of <tr> element using property rows.length in a variable rowCount.
var rowCount = table.rows.length;
Next, using the IF Else statement, we have checked whether the number of table rows is greater than one or not.
if(rowCount > '2'){
}
If it is TRUE, then it deletes one row with the Javascript property deleteRow() and decrement the number of rows by one.
var row = table.deleteRow(rowCount-1);
rowCount--;
We hope this code helps someone. You can implement this easily with minor edits. During implementation, please take care of table id and columns id.
Download and open PDF file using Ajax
Javascript window location
How to reverse a number in Javascript
How to reverse string in Javascript
PHP script to read email inbox How to retrieve data from database without refreshing page Print specific part of webpage Store Emoji character in MySQL using PHP PHP Display PDF file from Database Jquery ajax loop through data Dynamically add/remove rows in html table using jquery Submit form without page refresh using javascript PHP Form Validation Tutorial Google reCAPTCHA v3 PHP example Select/deselect all checkboxes using Javascript
Javascript speech recognition example
Image popup on page load using HTML and jQuery
jQuery File upload progress bar with file size validation | [
{
"code": null,
"e": 112,
"s": 90,
"text": "Theory of Computation"
},
{
"code": null,
"e": 273,
"s": 112,
"text": "In this article, you will learn how to create a simple user interface where a user can add or delete multiple table rows in a form dynamically using Javascript."
},
{
"code": null,
"e": 846,
"s": 273,
"text": "Sometimes, there may be a requirement for the user to add multiple repeated row's fields in a form. We cannot assume how many fields we should provide on the webpage. Like, we need to provide some employees details. There is no surety of how many employee details, may be later we have to delete some. Let's discuss how we can achieve these tasks. In this post, we will write code to add or remove the entire row with there input fields dynamically using Javascript. We will provide two buttons, the first button to add new rows to the table and the second to remove rows."
},
{
"code": null,
"e": 1318,
"s": 846,
"text": "As we know, Javascript is a dynamic language. It means it can control, access and manipulate the HTML elements dynamically on the client side. We can easily add and remove HTML elements in a web page using Javascript. In this article, we will provide you with a simple way to add or remove HTML table rows with there fields dynamically. The below code has an HTML form and two javascript functions addRows() and deleteRows() to add and delete the table rows respectively."
},
{
"code": null,
"e": 3342,
"s": 1318,
"text": "<html>\n<head>\n<title>Onclick increase Table Rows</title>\n<script type=\"text/javascript\">\nfunction addRows(){ \n\tvar table = document.getElementById('emptbl');\n\tvar rowCount = table.rows.length;\n\tvar cellCount = table.rows[0].cells.length; \n\tvar row = table.insertRow(rowCount);\n\tfor(var i =0; i <= cellCount; i++){\n\t\tvar cell = 'cell'+i;\n\t\tcell = row.insertCell(i);\n\t\tvar copycel = document.getElementById('col'+i).innerHTML;\n\t\tcell.innerHTML=copycel;\n\t\tif(i == 3){ \n\t\t\tvar radioinput = document.getElementById('col3').getElementsByTagName('input'); \n\t\t\tfor(var j = 0; j <= radioinput.length; j++) { \n\t\t\t\tif(radioinput[j].type == 'radio') { \n\t\t\t\t\tvar rownum = rowCount;\n\t\t\t\t\tradioinput[j].name = 'gender['+rownum+']';\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n}\nfunction deleteRows(){\n\tvar table = document.getElementById('emptbl');\n\tvar rowCount = table.rows.length;\n\tif(rowCount > '2'){\n\t\tvar row = table.deleteRow(rowCount-1);\n\t\trowCount--;\n\t}\n\telse{\n\t\talert('There should be atleast one row');\n\t}\n}\n</script>\n</head>\n<body>\n<form action=\"#\" method=\"post\"> \n\t<table id=\"emptbl\">\n\t\t<tr>\n\t\t\t<th>Employee Name</th>\n\t\t\t<th>Phone</th>\n\t\t\t<th>Department</th> \n\t\t\t<th>Gender</th> \n\t\t</tr> \n\t\t<tr> \n\t\t\t<td id=\"col0\"><input type=\"text\" name=\"empname[]\" value=\"\" /></td> \n\t\t\t<td id=\"col1\"><input type=\"text\" name=\"phone[]\" value=\"\" /></td> \n\t\t\t<td id=\"col2\"> \n\t\t\t<select name=\"department[]\" id=\"dept\"> \n\t\t\t<option value=\"0\">Select Department</option> \n\t\t\t<option value=\"1\">Sales</option>\n\t\t\t<option value=\"2\">IT</option>\n\t\t\t<option value=\"3\">Warehouse</option>\n\t\t\t</select> \n\t\t </td> \n\t\t <td id=\"col3\"> \n\t\t\t<input type=\"radio\" name=\"gender[0]\" value=\"male\" />Male \n\t\t\t<input type=\"radio\" name=\"gender[1]\" value=\"female\" />Female \n\t\t </td> \n\t\t</tr> \n\t</table> \n\t<table> \n\t\t<tr> \n\t\t\t<td><input type=\"button\" value=\"Add Row\" onclick=\"addRows()\" /></td> \n\t\t\t<td><input type=\"button\" value=\"Delete Row\" onclick=\"deleteRows()\" /></td> \n\t\t\t<td><input type=\"submit\" value=\"Submit\" /></td> \n\t\t</tr> \n\t</table> \n </form> \n</body> \n</html>\n"
},
{
"code": null,
"e": 3637,
"s": 3342,
"text": "In the above code, we have taken a form element with three buttons to Add Row, Delete Row and Submit form data. Within the form element, we have taken a table to display the form input data. To perform dynamic operations on the table using Javascript, we have given an id 'emptbl' to the table."
},
{
"code": null,
"e": 3764,
"s": 3637,
"text": "These are the step-by-step code explanations on how a new row is dynamically created when user clicks on the 'Add Row' button."
},
{
"code": null,
"e": 4018,
"s": 3764,
"text": "addRows() - Within the head section, we have created a Javascript function name addRows() that is responsible for adding a new table row with input fields. For this, first we got the table element with table id and stored in a javascript variable table."
},
{
"code": null,
"e": 4065,
"s": 4018,
"text": "var table = document.getElementById('emptbl');"
},
{
"code": null,
"e": 4253,
"s": 4065,
"text": "Next, we stored the number of <tr> element using the Javascript property rows.length in a variable rowCount and rows[0].cells.length property returns number of <td> elements of first row."
},
{
"code": null,
"e": 4331,
"s": 4253,
"text": "var rowCount = table.rows.length;\nvar cellCount = table.rows[0].cells.length;"
},
{
"code": null,
"e": 4405,
"s": 4331,
"text": "Next, we have created an empty row using Javascript property insertRow()."
},
{
"code": null,
"e": 4442,
"s": 4405,
"text": "var row = table.insertRow(rowCount);"
},
{
"code": null,
"e": 4611,
"s": 4442,
"text": "Next, we have dynamically generated the cells within the empty row using a for loop and taken the innerHTML of the old cell with cell index and paste it in the new one."
},
{
"code": null,
"e": 4650,
"s": 4611,
"text": "for(var i =0; i <= cellCount; i++){\n\n}"
},
{
"code": null,
"e": 4785,
"s": 4650,
"text": "These are the step-by-step code explanations on how an existing row is dynamically deleted when a user clicks the 'Delete Row' button."
},
{
"code": null,
"e": 5065,
"s": 4785,
"text": "deleteRows() - Within the head section after addRows() function, we have created other Javascript function name deleteRows() that is responsible to delete existing table row with input fields. For this, first we got the table element with table id and stored in a variable table."
},
{
"code": null,
"e": 5159,
"s": 5065,
"text": "Next, we stored the number of <tr> element using property rows.length in a variable rowCount."
},
{
"code": null,
"e": 5193,
"s": 5159,
"text": "var rowCount = table.rows.length;"
},
{
"code": null,
"e": 5305,
"s": 5193,
"text": "Next, using the IF Else statement, we have checked whether the number of table rows is greater than one or not."
},
{
"code": null,
"e": 5328,
"s": 5305,
"text": "if(rowCount > '2'){\n\n}"
},
{
"code": null,
"e": 5449,
"s": 5328,
"text": "If it is TRUE, then it deletes one row with the Javascript property deleteRow() and decrement the number of rows by one."
},
{
"code": null,
"e": 5500,
"s": 5449,
"text": "var row = table.deleteRow(rowCount-1);\nrowCount--;"
},
{
"code": null,
"e": 5649,
"s": 5500,
"text": "We hope this code helps someone. You can implement this easily with minor edits. During implementation, please take care of table id and columns id."
}
] |
Program to find whether a string is alphanumeric. | Any word that contains numbers and letters is known as alphanumeric. The following regular expression matches the combination of numbers and letters.
"^[a-zA-Z0-9]+$";
The matches method of the String class accepts a regular expression (in the form of a String) and matches it with the current string in case the match this method returns true else it returns false.
Therefore, to find whether a particular string contains alpha-numeric values −
Get the string.
Invoke the match method on it bypassing the above mentioned regular expression.
Retrieve the result.
import java.util.Scanner;
public class AlphanumericString {
public static void main(String args[]) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.next();
String regex = "^[a-zA-Z0-9]+$";
boolean result = input.matches(regex);
if(result) {
System.out.println("Given string is alpha numeric");
} else {
System.out.println("Given string is not alpha numeric");
}
}
}
Enter input string:
abc123*
Given string is not alpha numeric
You can also compile a regular expression and match it with a particular string using the classes and methods (APIs) of the java.util.regex package. The following program is written using these APIs and it verifies whether a given string is alpha-numeric.
import java.util.Scanner;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Test {
public static void main( String args[] ) {
Scanner sc = new Scanner(System.in);
System.out.println("Enter input string: ");
String input = sc.nextLine();
String regex = "^[a-zA-Z0-9]+$";
String data[] = input.split(" ");
//Creating a pattern object
Pattern pattern = Pattern.compile(regex);
for (String ele : data){
//creating a matcher object
Matcher matcher = pattern.matcher(ele);
if(matcher.matches()) {
System.out.println("The word "+ele+": is alpha numeric");
} else {
System.out.println("The word "+ele+": is not alpha numeric");
}
}
}
}
Enter input string:
hello* this$ is sample text
The word hello*: is not alpha numeric
The word this$: is not alpha numeric
The word is: is alpha numeric
The word sample: is alpha numeric
The word text: is alpha numeric | [
{
"code": null,
"e": 1212,
"s": 1062,
"text": "Any word that contains numbers and letters is known as alphanumeric. The following regular expression matches the combination of numbers and letters."
},
{
"code": null,
"e": 1230,
"s": 1212,
"text": "\"^[a-zA-Z0-9]+$\";"
},
{
"code": null,
"e": 1429,
"s": 1230,
"text": "The matches method of the String class accepts a regular expression (in the form of a String) and matches it with the current string in case the match this method returns true else it returns false."
},
{
"code": null,
"e": 1508,
"s": 1429,
"text": "Therefore, to find whether a particular string contains alpha-numeric values −"
},
{
"code": null,
"e": 1524,
"s": 1508,
"text": "Get the string."
},
{
"code": null,
"e": 1604,
"s": 1524,
"text": "Invoke the match method on it bypassing the above mentioned regular expression."
},
{
"code": null,
"e": 1625,
"s": 1604,
"text": "Retrieve the result."
},
{
"code": null,
"e": 2115,
"s": 1625,
"text": "import java.util.Scanner;\npublic class AlphanumericString {\n public static void main(String args[]) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string: \");\n String input = sc.next();\n String regex = \"^[a-zA-Z0-9]+$\";\n boolean result = input.matches(regex);\n if(result) {\n System.out.println(\"Given string is alpha numeric\");\n } else {\n System.out.println(\"Given string is not alpha numeric\");\n }\n }\n}"
},
{
"code": null,
"e": 2177,
"s": 2115,
"text": "Enter input string:\nabc123*\nGiven string is not alpha numeric"
},
{
"code": null,
"e": 2433,
"s": 2177,
"text": "You can also compile a regular expression and match it with a particular string using the classes and methods (APIs) of the java.util.regex package. The following program is written using these APIs and it verifies whether a given string is alpha-numeric."
},
{
"code": null,
"e": 3217,
"s": 2433,
"text": "import java.util.Scanner;\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\npublic class Test {\n public static void main( String args[] ) {\n Scanner sc = new Scanner(System.in);\n System.out.println(\"Enter input string: \");\n String input = sc.nextLine();\n String regex = \"^[a-zA-Z0-9]+$\";\n String data[] = input.split(\" \");\n //Creating a pattern object\n Pattern pattern = Pattern.compile(regex);\n for (String ele : data){\n //creating a matcher object\n Matcher matcher = pattern.matcher(ele);\n if(matcher.matches()) {\n System.out.println(\"The word \"+ele+\": is alpha numeric\");\n } else {\n System.out.println(\"The word \"+ele+\": is not alpha numeric\");\n }\n }\n }\n}"
},
{
"code": null,
"e": 3436,
"s": 3217,
"text": "Enter input string:\nhello* this$ is sample text\nThe word hello*: is not alpha numeric\nThe word this$: is not alpha numeric\nThe word is: is alpha numeric\nThe word sample: is alpha numeric\nThe word text: is alpha numeric"
}
] |
Ruby | Enumerable each_cons() function - GeeksforGeeks | 05 Dec, 2019
The each_cons() of enumerable is an inbuilt method in Ruby iterates for consecutive N elements starting from each element every time. If no block is given, it returns the enumerator.
Syntax: enu.each_cons(N) { |obj| block }
Parameters: The function takes the block which is used to check the condition and N which specifies the number of consecutive elements to take.
Return Value: It returns the elements iterative consecutive for each element.
Example 1:
# Ruby program for each_cons method in Enumerable # Initializeenu = (1.. 5) # returns each element enu.each_cons(2){|obj| p obj}
Output:
[1, 2]
[2, 3]
[3, 4]
[4, 5]
Example 2:
# Ruby program for each_cons method in Enumerable # Initializeenu = (1..10) # returns each element enu.each_cons(4)
Output:
Enumerator: 1..10:each_cons(4)
Ruby Collections
Ruby Enumerable-class
Ruby-Methods
Ruby
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Ruby | Enumerator each_with_index function
How to Make a Custom Array of Hashes in Ruby?
Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1
Ruby | String concat Method
Ruby | pop() function
Ruby For Beginners
Ruby | String empty? Method
Ruby | Array shift() function
Ruby | Enumerable sum() function
Ruby | Class Method and Variables | [
{
"code": null,
"e": 23595,
"s": 23567,
"text": "\n05 Dec, 2019"
},
{
"code": null,
"e": 23778,
"s": 23595,
"text": "The each_cons() of enumerable is an inbuilt method in Ruby iterates for consecutive N elements starting from each element every time. If no block is given, it returns the enumerator."
},
{
"code": null,
"e": 23819,
"s": 23778,
"text": "Syntax: enu.each_cons(N) { |obj| block }"
},
{
"code": null,
"e": 23963,
"s": 23819,
"text": "Parameters: The function takes the block which is used to check the condition and N which specifies the number of consecutive elements to take."
},
{
"code": null,
"e": 24041,
"s": 23963,
"text": "Return Value: It returns the elements iterative consecutive for each element."
},
{
"code": null,
"e": 24052,
"s": 24041,
"text": "Example 1:"
},
{
"code": "# Ruby program for each_cons method in Enumerable # Initializeenu = (1.. 5) # returns each element enu.each_cons(2){|obj| p obj}",
"e": 24183,
"s": 24052,
"text": null
},
{
"code": null,
"e": 24191,
"s": 24183,
"text": "Output:"
},
{
"code": null,
"e": 24220,
"s": 24191,
"text": "[1, 2]\n[2, 3]\n[3, 4]\n[4, 5]\n"
},
{
"code": null,
"e": 24231,
"s": 24220,
"text": "Example 2:"
},
{
"code": "# Ruby program for each_cons method in Enumerable # Initializeenu = (1..10) # returns each element enu.each_cons(4)",
"e": 24349,
"s": 24231,
"text": null
},
{
"code": null,
"e": 24357,
"s": 24349,
"text": "Output:"
},
{
"code": null,
"e": 24389,
"s": 24357,
"text": "Enumerator: 1..10:each_cons(4)\n"
},
{
"code": null,
"e": 24406,
"s": 24389,
"text": "Ruby Collections"
},
{
"code": null,
"e": 24428,
"s": 24406,
"text": "Ruby Enumerable-class"
},
{
"code": null,
"e": 24441,
"s": 24428,
"text": "Ruby-Methods"
},
{
"code": null,
"e": 24446,
"s": 24441,
"text": "Ruby"
},
{
"code": null,
"e": 24544,
"s": 24446,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 24553,
"s": 24544,
"text": "Comments"
},
{
"code": null,
"e": 24566,
"s": 24553,
"text": "Old Comments"
},
{
"code": null,
"e": 24609,
"s": 24566,
"text": "Ruby | Enumerator each_with_index function"
},
{
"code": null,
"e": 24655,
"s": 24609,
"text": "How to Make a Custom Array of Hashes in Ruby?"
},
{
"code": null,
"e": 24723,
"s": 24655,
"text": "Ruby | Decision Making (if, if-else, if-else-if, ternary) | Set - 1"
},
{
"code": null,
"e": 24751,
"s": 24723,
"text": "Ruby | String concat Method"
},
{
"code": null,
"e": 24773,
"s": 24751,
"text": "Ruby | pop() function"
},
{
"code": null,
"e": 24792,
"s": 24773,
"text": "Ruby For Beginners"
},
{
"code": null,
"e": 24820,
"s": 24792,
"text": "Ruby | String empty? Method"
},
{
"code": null,
"e": 24850,
"s": 24820,
"text": "Ruby | Array shift() function"
},
{
"code": null,
"e": 24883,
"s": 24850,
"text": "Ruby | Enumerable sum() function"
}
] |
Create empty dataframe in Pandas - GeeksforGeeks | 28 Jul, 2020
The Pandas Dataframe is a structure that has data in the 2D format and labels with it. DataFrames are widely used in data science, machine learning, and other such places. DataFrames are the same as SQL tables or Excel sheets but these are faster in use.Empty DataFrame could be created with the help of pandas.DataFrame() as shown in below example:
Syntax: pandas.Dataframe()
Return: Return a Dataframe object.
Code:
Python3
# import pandas libraryimport pandas as pd # create an empty dataframemy_df = pd.DataFrame() # show the dataframemy_df
Output:
The above output does not show anything lets us insert some heading to the DataFrame.
Code:
Python3
# import pandas libraryimport pandas as pd # column name list col_names = ['A', 'B', 'C'] # create an empty dataframe# with columnsmy_df = pd.DataFrame(columns = col_names) # show the dataframemy_df
Output:
The empty dataframe showing only headings.
Now let’s Insert some records in a dataframe.Code:
Python3
# import pandas libraryimport pandas as pd # create a dataframemy_df = pd.DataFrame({'A': ['114', '345', '157788', '5626'], 'B': ['shirt', 'trousers', 'tie', 'belt'], 'C': [1200, 1500, 600, 352]}) # show the dataframemy_df
Output:
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Python Classes and Objects
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n28 Jul, 2020"
},
{
"code": null,
"e": 24251,
"s": 23901,
"text": "The Pandas Dataframe is a structure that has data in the 2D format and labels with it. DataFrames are widely used in data science, machine learning, and other such places. DataFrames are the same as SQL tables or Excel sheets but these are faster in use.Empty DataFrame could be created with the help of pandas.DataFrame() as shown in below example:"
},
{
"code": null,
"e": 24278,
"s": 24251,
"text": "Syntax: pandas.Dataframe()"
},
{
"code": null,
"e": 24313,
"s": 24278,
"text": "Return: Return a Dataframe object."
},
{
"code": null,
"e": 24319,
"s": 24313,
"text": "Code:"
},
{
"code": null,
"e": 24327,
"s": 24319,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create an empty dataframemy_df = pd.DataFrame() # show the dataframemy_df",
"e": 24449,
"s": 24327,
"text": null
},
{
"code": null,
"e": 24457,
"s": 24449,
"text": "Output:"
},
{
"code": null,
"e": 24543,
"s": 24457,
"text": "The above output does not show anything lets us insert some heading to the DataFrame."
},
{
"code": null,
"e": 24549,
"s": 24543,
"text": "Code:"
},
{
"code": null,
"e": 24557,
"s": 24549,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # column name list col_names = ['A', 'B', 'C'] # create an empty dataframe# with columnsmy_df = pd.DataFrame(columns = col_names) # show the dataframemy_df",
"e": 24761,
"s": 24557,
"text": null
},
{
"code": null,
"e": 24769,
"s": 24761,
"text": "Output:"
},
{
"code": null,
"e": 24812,
"s": 24769,
"text": "The empty dataframe showing only headings."
},
{
"code": null,
"e": 24863,
"s": 24812,
"text": "Now let’s Insert some records in a dataframe.Code:"
},
{
"code": null,
"e": 24871,
"s": 24863,
"text": "Python3"
},
{
"code": "# import pandas libraryimport pandas as pd # create a dataframemy_df = pd.DataFrame({'A': ['114', '345', '157788', '5626'], 'B': ['shirt', 'trousers', 'tie', 'belt'], 'C': [1200, 1500, 600, 352]}) # show the dataframemy_df",
"e": 25219,
"s": 24871,
"text": null
},
{
"code": null,
"e": 25227,
"s": 25219,
"text": "Output:"
},
{
"code": null,
"e": 25253,
"s": 25229,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 25267,
"s": 25253,
"text": "Python-pandas"
},
{
"code": null,
"e": 25274,
"s": 25267,
"text": "Python"
},
{
"code": null,
"e": 25372,
"s": 25274,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25381,
"s": 25372,
"text": "Comments"
},
{
"code": null,
"e": 25394,
"s": 25381,
"text": "Old Comments"
},
{
"code": null,
"e": 25426,
"s": 25394,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25482,
"s": 25426,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25524,
"s": 25482,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25566,
"s": 25524,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25602,
"s": 25566,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25641,
"s": 25602,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25663,
"s": 25641,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25694,
"s": 25663,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 25721,
"s": 25694,
"text": "Python Classes and Objects"
}
] |
Add headers inside the dropdown menu in Bootstrap | To add headers inside the dropdown menu, use the .dropdown-header class in Boostrap. The .dropdown-menu class is used to add a dropdown menu.
You can try to run the following code to implement the dropdown-header class in Bootstrap −
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 = "container">
<h2>Beverages</h2>
<p>The following are the beverages available in India:</p>
<div class = "dropdown">
<button class = "btn btn-primary dropdown-toggle" type = "button" data-toggle="dropdown">Beverages
<span class = "caret"></span></button>
<ul class = "dropdown-menu">
<li class = "dropdown-header">Energy Drinks</li>
<li><a href = "#">Gatorade</a></li>
<li><a href = "#">Sting</a></li>
<li><a href = "#">Red Bull</a></li>
<li class = "dropdown-header">Sof Drinks</li>
<li><a href = "#">Pepsi</a></li>
<li><a href = "#">Coca Cola</a></li>
</ul>
</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1204,
"s": 1062,
"text": "To add headers inside the dropdown menu, use the .dropdown-header class in Boostrap. The .dropdown-menu class is used to add a dropdown menu."
},
{
"code": null,
"e": 1296,
"s": 1204,
"text": "You can try to run the following code to implement the dropdown-header class in Bootstrap −"
},
{
"code": null,
"e": 1306,
"s": 1296,
"text": "Live Demo"
},
{
"code": null,
"e": 2397,
"s": 1306,
"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 = \"container\">\n <h2>Beverages</h2>\n <p>The following are the beverages available in India:</p>\n <div class = \"dropdown\">\n <button class = \"btn btn-primary dropdown-toggle\" type = \"button\" data-toggle=\"dropdown\">Beverages\n <span class = \"caret\"></span></button>\n <ul class = \"dropdown-menu\">\n <li class = \"dropdown-header\">Energy Drinks</li>\n <li><a href = \"#\">Gatorade</a></li>\n <li><a href = \"#\">Sting</a></li>\n <li><a href = \"#\">Red Bull</a></li>\n <li class = \"dropdown-header\">Sof Drinks</li>\n <li><a href = \"#\">Pepsi</a></li>\n <li><a href = \"#\">Coca Cola</a></li>\n </ul>\n </div>\n </div>\n </body>\n</html>"
}
] |
Count of Numbers in a Range where digit d occurs exactly K times - GeeksforGeeks | 15 Jun, 2021
Given two positive integers L and R which represents a range and two more positive integers d and K. The task is to find the count of numbers in the range where digit d occurs exactly K times.Examples:
Input: L = 11, R = 100, d = 2, k = 1 Output: 17 Required numbers are 12, 20, 21, 23, 24, 25, 26, 27, 28, 29, 32, 42, 52, 62, 72, 82 and 92.Input: L = 95, R = 1005, d = 0, k = 2 Output: 14
Prerequisites : Digit DP
Approach: Firstly, if we are able to count the required numbers upto R i.e. in the range [0, R], we can easily reach our answer in the range [L, R] by solving for from zero to R and then subtracting the answer we get after solving for from zero to L – 1. Now, we need to define the DP states. DP States:
Since we can consider our number as a sequence of digits, one state is the position at which we are currently in. This position can have values from 0 to 18 if we are dealing with the numbers upto 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9.
Second state is the count which defines the number of times, we have placed digit d so far.
Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, maximum limit of digit we can place is digit at current position in R.
Last state is also boolean variable nonz which helps to consider the situation if are any leading zeroes in the number we are building, we don’t need to count them.
In the final recursive call, when we are at the last position if the count of digit d is equal to K, return 1 otherwise return 0.Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// CPP Program to find the count of// numbers in a range where digit d// occurs exactly K times#include <bits/stdc++.h>using namespace std; const int M = 20; // states - position, count, tight, nonzint dp[M][M][2][2]; // d is required digit and K is occurrenceint d, K; // This function returns the count of// required numbers from 0 to numint count(int pos, int cnt, int tight, int nonz, vector<int> num){ // Last position if (pos == num.size()) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos][cnt][tight][nonz] != -1) return dp[pos][cnt][tight][nonz]; int ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight ? 9 : num[pos]); for (int dig = 0; dig <= limit; dig++) { int currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (!d && nonz)) currCnt++; } int currTight = tight; // At this position, number becomes // smaller if (dig < num[pos]) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, nonz || (dig != 0), num); } return dp[pos][cnt][tight][nonz] = ans;} // Function to convert x into its digit vector and uses// count() function to return the required countint solve(int x){ vector<int> num; while (x) { num.push_back(x % 10); x /= 10; } reverse(num.begin(), num.end()); // Initialize dp memset(dp, -1, sizeof(dp)); return count(0, 0, 0, 0, num);} // Driver Code to test above functionsint main(){ int L = 11, R = 100; d = 2, K = 1; cout << solve(R) - solve(L - 1) << endl; return 0;}
// Java Program to find the count of// numbers in a range where digit d// occurs exactly K timesimport java.util.*;class Solution{static final int M = 20; // states - position, count, tight, nonzstatic int dp[][][][]= new int[M][M][2][2]; // d is required digit and K is occurrencestatic int d, K; // This function returns the count of// required numbers from 0 to numstatic int count(int pos, int cnt, int tight, int nonz, Vector<Integer> num){ // Last position if (pos == num.size()) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos][cnt][tight][nonz] != -1) return dp[pos][cnt][tight][nonz]; int ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = ((tight !=0)? 9 : num.get(pos)); for (int dig = 0; dig <= limit; dig++) { int currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (d==0 && nonz!=0)) currCnt++; } int currTight = tight; // At this position, number becomes // smaller if (dig < num.get(pos)) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, (dig != 0?1:0), num); } return dp[pos][cnt][tight][nonz] = ans;} // Function to convert x into its digit vector and uses// count() function to return the required countstatic int solve(int x){ Vector<Integer> num= new Vector<Integer>(); while (x!=0) { num.add(x % 10); x /= 10; } Collections.reverse(num); // Initialize dp for(int i=0;i<M;i++) for(int j=0;j<M;j++) for(int k=0;k<2;k++) for(int l=0;l<2;l++) dp[i][j][k][l]=-1; return count(0, 0, 0, 0, num);} // Driver Code to test above functionspublic static void main(String args[]){ int L = 11, R = 100; d = 2; K = 1; System.out.print( solve(R) - solve(L - 1) );} }//contributed by Arnab Kundu
# Python Program to find the count of# numbers in a range where digit d# occurs exactly K timesM = 20 # states - position, count, tight, nonzdp = [] # d is required digit and K is occurrenced, K = None, None # This function returns the count of# required numbers from 0 to numdef count(pos, cnt, tight, nonz, num: list): # Last position if pos == len(num): if cnt == K: return 1 return 0 # If this result is already computed # simply return it if dp[pos][cnt][tight][nonz] != -1: return dp[pos][cnt][tight][nonz] ans = 0 # Maximum limit upto which we can place # digit. If tight is 1, means number has # already become smaller so we can place # any digit, otherwise num[pos] limit = 9 if tight else num[pos] for dig in range(limit + 1): currCnt = cnt # Nonz is true if we placed a non # zero digit at the starting of # the number if dig == d: if d != 0 or not d and nonz: currCnt += 1 currTight = tight # At this position, number becomes # smaller if dig < num[pos]: currTight = 1 # Next recursive call, also set nonz # to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, (nonz or dig != 0), num) dp[pos][cnt][tight][nonz] = ans return dp[pos][cnt][tight][nonz] # Function to convert x into its digit vector and uses# count() function to return the required countdef solve(x): global dp, K, d num = [] while x: num.append(x % 10) x //= 10 num.reverse() # Initialize dp dp = [[[[-1, -1] for i in range(2)] for j in range(M)] for k in range(M)] return count(0, 0, 0, 0, num) # Driver Codeif __name__ == "__main__": L = 11 R = 100 d = 2 K = 1 print(solve(R) - solve(L - 1)) # This code is contributed by# sanjeev2552
// C# Program to find the count of// numbers in a range where digit d// occurs exactly K timesusing System;using System.Collections.Generic; class GFG{ static readonly int M = 20; // states - position, count, tight, nonz static int [,,,]dp= new int[M, M, 2, 2]; // d is required digit and K is occurrence static int d, K; // This function returns the count of // required numbers from 0 to num static int count(int pos, int cnt, int tight, int nonz, List<int> num) { // Last position if (pos == num.Count) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos, cnt, tight, nonz] != -1) return dp[pos, cnt, tight, nonz]; int ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = ((tight != 0) ? 9 : num[pos]); for (int dig = 0; dig <= limit; dig++) { int currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (d == 0 && nonz != 0)) currCnt++; } int currTight = tight; // At this position, number becomes // smaller if (dig < num[pos]) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, (dig != 0 ? 1 : 0), num); } return dp[pos, cnt, tight, nonz] = ans; } // Function to convert x into its // digit vector and uses count() // function to return the required count static int solve(int x) { List<int> num = new List<int>(); while (x != 0) { num.Add(x % 10); x /= 10; } num.Reverse(); // Initialize dp for(int i = 0; i < M; i++) for(int j = 0; j < M; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 2; l++) dp[i, j, k, l]=-1; return count(0, 0, 0, 0, num); } // Driver Code public static void Main() { int L = 11, R = 100; d = 2; K = 1; Console.Write( solve(R) - solve(L - 1) ); }} // This code is contributed by Rajput-JI
<script> // JavaScript Program to find the count of// numbers in a range where digit d// occurs exactly K times var M = 20; // states - position, count, tight, nonzvar dp = Array.from(Array(M), ()=>Array(M)); // d is required digit and K is occurrencevar d, K; // This function returns the count of// required numbers from 0 to numfunction count( pos, cnt, tight, nonz, num){ // Last position if (pos == num.length) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos][cnt][tight][nonz] != -1) return dp[pos][cnt][tight][nonz]; var ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] var limit = (tight ? 9 : num[pos]); for (var dig = 0; dig <= limit; dig++) { var currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (!d && nonz)) currCnt++; } var currTight = tight; // At this position, number becomes // smaller if (dig < num[pos]) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, nonz || (dig != 0?1:0), num); } return dp[pos][cnt][tight][nonz] = ans;} // Function to convert x into its digit vector and uses// count() function to return the required countfunction solve(x){ var num = []; while (x) { num.push(x % 10); x = parseInt(x/10); } num.reverse(); for(var i =0; i<M; i++) for(var j =0; j<M; j++) dp[i][j] = Array.from(Array(2), ()=>Array(2).fill(-1)) return count(0, 0, 0, 0, num);} // Driver Code to test above functionsvar L = 11, R = 100;d = 2, K = 1;document.write( solve(R) - solve(L - 1)); </script>
17
andrew1234
Rajput-Ji
nidhi_biet
sanjeev2552
rutvik_56
digit-DP
Technical Scripter 2018
Algorithms
Combinatorial
Competitive Programming
Dynamic Programming
Mathematical
Dynamic Programming
Mathematical
Combinatorial
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SCAN (Elevator) Disk Scheduling Algorithms
Program for SSTF disk scheduling algorithm
Rail Fence Cipher - Encryption and Decryption
Quadratic Probing in Hashing
Write a program to print all permutations of a given string
Permutation and Combination in Python
itertools.combinations() module in Python to print all possible combinations
Factorial of a large number | [
{
"code": null,
"e": 24702,
"s": 24674,
"text": "\n15 Jun, 2021"
},
{
"code": null,
"e": 24906,
"s": 24702,
"text": "Given two positive integers L and R which represents a range and two more positive integers d and K. The task is to find the count of numbers in the range where digit d occurs exactly K times.Examples: "
},
{
"code": null,
"e": 25096,
"s": 24906,
"text": "Input: L = 11, R = 100, d = 2, k = 1 Output: 17 Required numbers are 12, 20, 21, 23, 24, 25, 26, 27, 28, 29, 32, 42, 52, 62, 72, 82 and 92.Input: L = 95, R = 1005, d = 0, k = 2 Output: 14 "
},
{
"code": null,
"e": 25122,
"s": 25096,
"text": "Prerequisites : Digit DP "
},
{
"code": null,
"e": 25428,
"s": 25122,
"text": "Approach: Firstly, if we are able to count the required numbers upto R i.e. in the range [0, R], we can easily reach our answer in the range [L, R] by solving for from zero to R and then subtracting the answer we get after solving for from zero to L – 1. Now, we need to define the DP states. DP States: "
},
{
"code": null,
"e": 25735,
"s": 25428,
"text": "Since we can consider our number as a sequence of digits, one state is the position at which we are currently in. This position can have values from 0 to 18 if we are dealing with the numbers upto 1018. In each recursive call, we try to build the sequence from left to right by placing a digit from 0 to 9."
},
{
"code": null,
"e": 25828,
"s": 25735,
"text": "Second state is the count which defines the number of times, we have placed digit d so far. "
},
{
"code": null,
"e": 26138,
"s": 25828,
"text": "Another state is the boolean variable tight which tells the number we are trying to build has already become smaller than R so that in the upcoming recursive calls we can place any digit from 0 to 9. If the number has not become smaller, maximum limit of digit we can place is digit at current position in R. "
},
{
"code": null,
"e": 26303,
"s": 26138,
"text": "Last state is also boolean variable nonz which helps to consider the situation if are any leading zeroes in the number we are building, we don’t need to count them."
},
{
"code": null,
"e": 26485,
"s": 26303,
"text": "In the final recursive call, when we are at the last position if the count of digit d is equal to K, return 1 otherwise return 0.Below is the implementation of the above approach: "
},
{
"code": null,
"e": 26489,
"s": 26485,
"text": "C++"
},
{
"code": null,
"e": 26494,
"s": 26489,
"text": "Java"
},
{
"code": null,
"e": 26502,
"s": 26494,
"text": "Python3"
},
{
"code": null,
"e": 26505,
"s": 26502,
"text": "C#"
},
{
"code": null,
"e": 26516,
"s": 26505,
"text": "Javascript"
},
{
"code": "// CPP Program to find the count of// numbers in a range where digit d// occurs exactly K times#include <bits/stdc++.h>using namespace std; const int M = 20; // states - position, count, tight, nonzint dp[M][M][2][2]; // d is required digit and K is occurrenceint d, K; // This function returns the count of// required numbers from 0 to numint count(int pos, int cnt, int tight, int nonz, vector<int> num){ // Last position if (pos == num.size()) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos][cnt][tight][nonz] != -1) return dp[pos][cnt][tight][nonz]; int ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = (tight ? 9 : num[pos]); for (int dig = 0; dig <= limit; dig++) { int currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (!d && nonz)) currCnt++; } int currTight = tight; // At this position, number becomes // smaller if (dig < num[pos]) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, nonz || (dig != 0), num); } return dp[pos][cnt][tight][nonz] = ans;} // Function to convert x into its digit vector and uses// count() function to return the required countint solve(int x){ vector<int> num; while (x) { num.push_back(x % 10); x /= 10; } reverse(num.begin(), num.end()); // Initialize dp memset(dp, -1, sizeof(dp)); return count(0, 0, 0, 0, num);} // Driver Code to test above functionsint main(){ int L = 11, R = 100; d = 2, K = 1; cout << solve(R) - solve(L - 1) << endl; return 0;}",
"e": 28549,
"s": 26516,
"text": null
},
{
"code": "// Java Program to find the count of// numbers in a range where digit d// occurs exactly K timesimport java.util.*;class Solution{static final int M = 20; // states - position, count, tight, nonzstatic int dp[][][][]= new int[M][M][2][2]; // d is required digit and K is occurrencestatic int d, K; // This function returns the count of// required numbers from 0 to numstatic int count(int pos, int cnt, int tight, int nonz, Vector<Integer> num){ // Last position if (pos == num.size()) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos][cnt][tight][nonz] != -1) return dp[pos][cnt][tight][nonz]; int ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = ((tight !=0)? 9 : num.get(pos)); for (int dig = 0; dig <= limit; dig++) { int currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (d==0 && nonz!=0)) currCnt++; } int currTight = tight; // At this position, number becomes // smaller if (dig < num.get(pos)) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, (dig != 0?1:0), num); } return dp[pos][cnt][tight][nonz] = ans;} // Function to convert x into its digit vector and uses// count() function to return the required countstatic int solve(int x){ Vector<Integer> num= new Vector<Integer>(); while (x!=0) { num.add(x % 10); x /= 10; } Collections.reverse(num); // Initialize dp for(int i=0;i<M;i++) for(int j=0;j<M;j++) for(int k=0;k<2;k++) for(int l=0;l<2;l++) dp[i][j][k][l]=-1; return count(0, 0, 0, 0, num);} // Driver Code to test above functionspublic static void main(String args[]){ int L = 11, R = 100; d = 2; K = 1; System.out.print( solve(R) - solve(L - 1) );} }//contributed by Arnab Kundu",
"e": 30849,
"s": 28549,
"text": null
},
{
"code": "# Python Program to find the count of# numbers in a range where digit d# occurs exactly K timesM = 20 # states - position, count, tight, nonzdp = [] # d is required digit and K is occurrenced, K = None, None # This function returns the count of# required numbers from 0 to numdef count(pos, cnt, tight, nonz, num: list): # Last position if pos == len(num): if cnt == K: return 1 return 0 # If this result is already computed # simply return it if dp[pos][cnt][tight][nonz] != -1: return dp[pos][cnt][tight][nonz] ans = 0 # Maximum limit upto which we can place # digit. If tight is 1, means number has # already become smaller so we can place # any digit, otherwise num[pos] limit = 9 if tight else num[pos] for dig in range(limit + 1): currCnt = cnt # Nonz is true if we placed a non # zero digit at the starting of # the number if dig == d: if d != 0 or not d and nonz: currCnt += 1 currTight = tight # At this position, number becomes # smaller if dig < num[pos]: currTight = 1 # Next recursive call, also set nonz # to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, (nonz or dig != 0), num) dp[pos][cnt][tight][nonz] = ans return dp[pos][cnt][tight][nonz] # Function to convert x into its digit vector and uses# count() function to return the required countdef solve(x): global dp, K, d num = [] while x: num.append(x % 10) x //= 10 num.reverse() # Initialize dp dp = [[[[-1, -1] for i in range(2)] for j in range(M)] for k in range(M)] return count(0, 0, 0, 0, num) # Driver Codeif __name__ == \"__main__\": L = 11 R = 100 d = 2 K = 1 print(solve(R) - solve(L - 1)) # This code is contributed by# sanjeev2552",
"e": 32773,
"s": 30849,
"text": null
},
{
"code": "// C# Program to find the count of// numbers in a range where digit d// occurs exactly K timesusing System;using System.Collections.Generic; class GFG{ static readonly int M = 20; // states - position, count, tight, nonz static int [,,,]dp= new int[M, M, 2, 2]; // d is required digit and K is occurrence static int d, K; // This function returns the count of // required numbers from 0 to num static int count(int pos, int cnt, int tight, int nonz, List<int> num) { // Last position if (pos == num.Count) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos, cnt, tight, nonz] != -1) return dp[pos, cnt, tight, nonz]; int ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] int limit = ((tight != 0) ? 9 : num[pos]); for (int dig = 0; dig <= limit; dig++) { int currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (d == 0 && nonz != 0)) currCnt++; } int currTight = tight; // At this position, number becomes // smaller if (dig < num[pos]) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, (dig != 0 ? 1 : 0), num); } return dp[pos, cnt, tight, nonz] = ans; } // Function to convert x into its // digit vector and uses count() // function to return the required count static int solve(int x) { List<int> num = new List<int>(); while (x != 0) { num.Add(x % 10); x /= 10; } num.Reverse(); // Initialize dp for(int i = 0; i < M; i++) for(int j = 0; j < M; j++) for(int k = 0; k < 2; k++) for(int l = 0; l < 2; l++) dp[i, j, k, l]=-1; return count(0, 0, 0, 0, num); } // Driver Code public static void Main() { int L = 11, R = 100; d = 2; K = 1; Console.Write( solve(R) - solve(L - 1) ); }} // This code is contributed by Rajput-JI",
"e": 35374,
"s": 32773,
"text": null
},
{
"code": "<script> // JavaScript Program to find the count of// numbers in a range where digit d// occurs exactly K times var M = 20; // states - position, count, tight, nonzvar dp = Array.from(Array(M), ()=>Array(M)); // d is required digit and K is occurrencevar d, K; // This function returns the count of// required numbers from 0 to numfunction count( pos, cnt, tight, nonz, num){ // Last position if (pos == num.length) { if (cnt == K) return 1; return 0; } // If this result is already computed // simply return it if (dp[pos][cnt][tight][nonz] != -1) return dp[pos][cnt][tight][nonz]; var ans = 0; // Maximum limit upto which we can place // digit. If tight is 1, means number has // already become smaller so we can place // any digit, otherwise num[pos] var limit = (tight ? 9 : num[pos]); for (var dig = 0; dig <= limit; dig++) { var currCnt = cnt; // Nonz is true if we placed a non // zero digit at the starting of // the number if (dig == d) { if (d != 0 || (!d && nonz)) currCnt++; } var currTight = tight; // At this position, number becomes // smaller if (dig < num[pos]) currTight = 1; // Next recursive call, also set nonz // to 1 if current digit is non zero ans += count(pos + 1, currCnt, currTight, nonz || (dig != 0?1:0), num); } return dp[pos][cnt][tight][nonz] = ans;} // Function to convert x into its digit vector and uses// count() function to return the required countfunction solve(x){ var num = []; while (x) { num.push(x % 10); x = parseInt(x/10); } num.reverse(); for(var i =0; i<M; i++) for(var j =0; j<M; j++) dp[i][j] = Array.from(Array(2), ()=>Array(2).fill(-1)) return count(0, 0, 0, 0, num);} // Driver Code to test above functionsvar L = 11, R = 100;d = 2, K = 1;document.write( solve(R) - solve(L - 1)); </script>",
"e": 37405,
"s": 35374,
"text": null
},
{
"code": null,
"e": 37408,
"s": 37405,
"text": "17"
},
{
"code": null,
"e": 37421,
"s": 37410,
"text": "andrew1234"
},
{
"code": null,
"e": 37431,
"s": 37421,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 37442,
"s": 37431,
"text": "nidhi_biet"
},
{
"code": null,
"e": 37454,
"s": 37442,
"text": "sanjeev2552"
},
{
"code": null,
"e": 37464,
"s": 37454,
"text": "rutvik_56"
},
{
"code": null,
"e": 37473,
"s": 37464,
"text": "digit-DP"
},
{
"code": null,
"e": 37497,
"s": 37473,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 37508,
"s": 37497,
"text": "Algorithms"
},
{
"code": null,
"e": 37522,
"s": 37508,
"text": "Combinatorial"
},
{
"code": null,
"e": 37546,
"s": 37522,
"text": "Competitive Programming"
},
{
"code": null,
"e": 37566,
"s": 37546,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37579,
"s": 37566,
"text": "Mathematical"
},
{
"code": null,
"e": 37599,
"s": 37579,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 37612,
"s": 37599,
"text": "Mathematical"
},
{
"code": null,
"e": 37626,
"s": 37612,
"text": "Combinatorial"
},
{
"code": null,
"e": 37637,
"s": 37626,
"text": "Algorithms"
},
{
"code": null,
"e": 37735,
"s": 37637,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37760,
"s": 37735,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 37803,
"s": 37760,
"text": "SCAN (Elevator) Disk Scheduling Algorithms"
},
{
"code": null,
"e": 37846,
"s": 37803,
"text": "Program for SSTF disk scheduling algorithm"
},
{
"code": null,
"e": 37892,
"s": 37846,
"text": "Rail Fence Cipher - Encryption and Decryption"
},
{
"code": null,
"e": 37921,
"s": 37892,
"text": "Quadratic Probing in Hashing"
},
{
"code": null,
"e": 37981,
"s": 37921,
"text": "Write a program to print all permutations of a given string"
},
{
"code": null,
"e": 38019,
"s": 37981,
"text": "Permutation and Combination in Python"
},
{
"code": null,
"e": 38096,
"s": 38019,
"text": "itertools.combinations() module in Python to print all possible combinations"
}
] |
Assigning arrays in Java. | While creating variables first of all we will declare them, initialize them, assign/re-assign values to them.
Similarly, while creating arrays −
You can declare an array just like a variable −
You can declare an array just like a variable −
int myArray[];
You can create an array just like an object using the new keyword −
You can create an array just like an object using the new keyword −
myArray = new int[5];
You can initialize the array by assigning values to all the elements one by one using the index −
You can initialize the array by assigning values to all the elements one by one using the index −
myArray [0] = 101;
myArray [1] = 102;
When we assign primitive values of one type to a variable of other (datatype) implicitly they are converted.
But, when you try to assign a higher datatype to lower, at the time of compilation you will get an error saying “incompatible types: possible lossy conversion”
Therefore while assigning values to the elements of an array you can assign any value which will be cast implicitly.
public class ArrayExample {
public static void main(String args[]){
//Declaring an array
int[] myArray = new int[5];
//Assigning values to the array
myArray[0] = 2020;
myArray[1] = 'h';
byte by = 4;
myArray[2] = by;
short sh = 8;
myArray[3] = sh;
myArray[4] = 465;
System.out.println(Arrays.toString(myArray));
}
}
[2020, 104, 4, 8, 465]
But, if you try to assign incompatible types (higher types) to a variable a compile-time error will be generated saying “possible lossy conversion”.
Live Demo
import java.util.Arrays;
public class ArrayExample {
public static void main(String args[]){
//Declaring an array
int[] myArray = new int[5];
//Assigning values to the array
myArray[0] = 2020;
myArray[1] = 'h';
byte by = 4;
myArray[2] = by;
short sh = 8;
myArray[3] = 152L;
myArray[4] = 465;
System.out.println(Arrays.toString(myArray));
}
}
ArrayExample.java:12: error: incompatible types: possible lossy conversion from
long to int
myArray[3] = 152L;
^
1 error
If you have an array of objects while assigning values to the elements of it, you need to make sure that the objects you assign should be of the same or, a subtype of the class (which is the type of the array).
Live Demo
import java.util.Arrays;
public class ArrayExample {
public static void main(String args[]){
//Declaring an array
Number[] num = new Number[5];
//Assigning values to the array
num[0] = 2020;
num[1] = 125L;
num[2] = 2545.F;
num[3] = 152L;
num[4] = 465;
System.out.println(Arrays.toString(num));
}
}
[2020, 125, 2545.0, 152, 465]
But to an array of objects if you assign a value which is neither the declared type nor its subtype a compile-time error will be generated.
Live Demo
import java.util.Arrays;
public class ArrayExample {
public static void main(String args[]){
//Declaring an array
Number[] num = new Number[5];
//Assigning values to the array
num[0] = 2020;
num[1] = 125L;
num[2] = 2545.F;
num[3] = 152L;
num[4] = "hello";
System.out.println(Arrays.toString(num));
}
}
ArrayExample.java:11: error: incompatible types: String cannot be converted to N
umber
num[4] = "hello";
^
1 error
If you have created an array of objects of an interface type you need to make sure that the values, you assign to the elements of the array are the objects of the class that implements the said interface. | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "While creating variables first of all we will declare them, initialize them, assign/re-assign values to them."
},
{
"code": null,
"e": 1207,
"s": 1172,
"text": "Similarly, while creating arrays −"
},
{
"code": null,
"e": 1255,
"s": 1207,
"text": "You can declare an array just like a variable −"
},
{
"code": null,
"e": 1303,
"s": 1255,
"text": "You can declare an array just like a variable −"
},
{
"code": null,
"e": 1318,
"s": 1303,
"text": "int myArray[];"
},
{
"code": null,
"e": 1386,
"s": 1318,
"text": "You can create an array just like an object using the new keyword −"
},
{
"code": null,
"e": 1454,
"s": 1386,
"text": "You can create an array just like an object using the new keyword −"
},
{
"code": null,
"e": 1476,
"s": 1454,
"text": "myArray = new int[5];"
},
{
"code": null,
"e": 1574,
"s": 1476,
"text": "You can initialize the array by assigning values to all the elements one by one using the index −"
},
{
"code": null,
"e": 1672,
"s": 1574,
"text": "You can initialize the array by assigning values to all the elements one by one using the index −"
},
{
"code": null,
"e": 1710,
"s": 1672,
"text": "myArray [0] = 101;\nmyArray [1] = 102;"
},
{
"code": null,
"e": 1819,
"s": 1710,
"text": "When we assign primitive values of one type to a variable of other (datatype) implicitly they are converted."
},
{
"code": null,
"e": 1979,
"s": 1819,
"text": "But, when you try to assign a higher datatype to lower, at the time of compilation you will get an error saying “incompatible types: possible lossy conversion”"
},
{
"code": null,
"e": 2096,
"s": 1979,
"text": "Therefore while assigning values to the elements of an array you can assign any value which will be cast implicitly."
},
{
"code": null,
"e": 2483,
"s": 2096,
"text": "public class ArrayExample {\n public static void main(String args[]){\n //Declaring an array\n int[] myArray = new int[5];\n //Assigning values to the array\n myArray[0] = 2020;\n myArray[1] = 'h';\n byte by = 4;\n myArray[2] = by;\n short sh = 8;\n myArray[3] = sh;\n myArray[4] = 465;\n System.out.println(Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 2506,
"s": 2483,
"text": "[2020, 104, 4, 8, 465]"
},
{
"code": null,
"e": 2655,
"s": 2506,
"text": "But, if you try to assign incompatible types (higher types) to a variable a compile-time error will be generated saying “possible lossy conversion”."
},
{
"code": null,
"e": 2666,
"s": 2655,
"text": " Live Demo"
},
{
"code": null,
"e": 3080,
"s": 2666,
"text": "import java.util.Arrays;\npublic class ArrayExample {\n public static void main(String args[]){\n //Declaring an array\n int[] myArray = new int[5];\n //Assigning values to the array\n myArray[0] = 2020;\n myArray[1] = 'h';\n byte by = 4;\n myArray[2] = by;\n short sh = 8;\n myArray[3] = 152L;\n myArray[4] = 465;\n System.out.println(Arrays.toString(myArray));\n }\n}"
},
{
"code": null,
"e": 3222,
"s": 3080,
"text": "ArrayExample.java:12: error: incompatible types: possible lossy conversion from\nlong to int\n myArray[3] = 152L;\n ^\n1 error"
},
{
"code": null,
"e": 3433,
"s": 3222,
"text": "If you have an array of objects while assigning values to the elements of it, you need to make sure that the objects you assign should be of the same or, a subtype of the class (which is the type of the array)."
},
{
"code": null,
"e": 3444,
"s": 3433,
"text": " Live Demo"
},
{
"code": null,
"e": 3802,
"s": 3444,
"text": "import java.util.Arrays;\npublic class ArrayExample {\n public static void main(String args[]){\n //Declaring an array\n Number[] num = new Number[5];\n //Assigning values to the array\n num[0] = 2020;\n num[1] = 125L;\n num[2] = 2545.F;\n num[3] = 152L;\n num[4] = 465;\n System.out.println(Arrays.toString(num));\n }\n}"
},
{
"code": null,
"e": 3832,
"s": 3802,
"text": "[2020, 125, 2545.0, 152, 465]"
},
{
"code": null,
"e": 3972,
"s": 3832,
"text": "But to an array of objects if you assign a value which is neither the declared type nor its subtype a compile-time error will be generated."
},
{
"code": null,
"e": 3983,
"s": 3972,
"text": " Live Demo"
},
{
"code": null,
"e": 4345,
"s": 3983,
"text": "import java.util.Arrays;\npublic class ArrayExample {\n public static void main(String args[]){\n //Declaring an array\n Number[] num = new Number[5];\n //Assigning values to the array\n num[0] = 2020;\n num[1] = 125L;\n num[2] = 2545.F;\n num[3] = 152L;\n num[4] = \"hello\";\n System.out.println(Arrays.toString(num));\n }\n}"
},
{
"code": null,
"e": 4475,
"s": 4345,
"text": "ArrayExample.java:11: error: incompatible types: String cannot be converted to N\number\n num[4] = \"hello\";\n ^\n1 error"
},
{
"code": null,
"e": 4680,
"s": 4475,
"text": "If you have created an array of objects of an interface type you need to make sure that the values, you assign to the elements of the array are the objects of the class that implements the said interface."
}
] |
How to find the device driver version using PowerShell? | To find the device driver version using PowerShell, we need to use the class win32_PnpSignedDriver of the WMI object. For example,
Get-WmiObject win32_PnpSignedDriver
Or if you are using PowerShell core (PowerShell 6.0 or later), you can use the CIM Instance command. For example,
Get-CimInstance win32_PnpSignedDriver
To filter out the Drivers against their versions, use the below command to filter.
gwmi win32_PnpSignedDriver | Select Description, DriverVersion
ACPI x64-based PC 6.2.9200.16384
UMBus Root Bus Enumerator 6.2.9200.16384
WAN Miniport (IPv6) 6.2.9200.16384
Composite Bus Enumerator 6.2.9200.16384
WAN Miniport (IKEv2) 6.2.9200.16384
WAN Miniport (SSTP) 6.2.9200.16384
WAN Miniport (IP) 6.2.9200.16384
To search for the Specific driver with its name,
gwmi win32_PnpSignedDriver | where{$_.Description -eq "WAN Miniport (IPv6)"} | Select Description, DriverVersion
To search for the specific driver using wildcard character,
gwmi win32_PnpSignedDriver | where{$_.Description -like "Vmware*"} | Select Description, DriverVersion
To get the list of drivers on the remote computer use -ComputerName parameter in the WMI or CIM instance command as shown below.
gwmi win32_PnpSignedDriver -ComputerName Computer1 | [
{
"code": null,
"e": 1193,
"s": 1062,
"text": "To find the device driver version using PowerShell, we need to use the class win32_PnpSignedDriver of the WMI object. For example,"
},
{
"code": null,
"e": 1229,
"s": 1193,
"text": "Get-WmiObject win32_PnpSignedDriver"
},
{
"code": null,
"e": 1343,
"s": 1229,
"text": "Or if you are using PowerShell core (PowerShell 6.0 or later), you can use the CIM Instance command. For example,"
},
{
"code": null,
"e": 1381,
"s": 1343,
"text": "Get-CimInstance win32_PnpSignedDriver"
},
{
"code": null,
"e": 1464,
"s": 1381,
"text": "To filter out the Drivers against their versions, use the below command to filter."
},
{
"code": null,
"e": 1527,
"s": 1464,
"text": "gwmi win32_PnpSignedDriver | Select Description, DriverVersion"
},
{
"code": null,
"e": 1887,
"s": 1527,
"text": "ACPI x64-based PC 6.2.9200.16384 \nUMBus Root Bus Enumerator 6.2.9200.16384 \nWAN Miniport (IPv6) 6.2.9200.16384 \nComposite Bus Enumerator 6.2.9200.16384 \nWAN Miniport (IKEv2) 6.2.9200.16384 \nWAN Miniport (SSTP) 6.2.9200.16384 \nWAN Miniport (IP) 6.2.9200.16384"
},
{
"code": null,
"e": 1936,
"s": 1887,
"text": "To search for the Specific driver with its name,"
},
{
"code": null,
"e": 2049,
"s": 1936,
"text": "gwmi win32_PnpSignedDriver | where{$_.Description -eq \"WAN Miniport (IPv6)\"} | Select Description, DriverVersion"
},
{
"code": null,
"e": 2109,
"s": 2049,
"text": "To search for the specific driver using wildcard character,"
},
{
"code": null,
"e": 2212,
"s": 2109,
"text": "gwmi win32_PnpSignedDriver | where{$_.Description -like \"Vmware*\"} | Select Description, DriverVersion"
},
{
"code": null,
"e": 2341,
"s": 2212,
"text": "To get the list of drivers on the remote computer use -ComputerName parameter in the WMI or CIM instance command as shown below."
},
{
"code": null,
"e": 2393,
"s": 2341,
"text": "gwmi win32_PnpSignedDriver -ComputerName Computer1\n"
}
] |
A detailed guide to PyTorch’s nn.Transformer() module. | by Daniel Melchor | Towards Data Science | I have recently been getting more involved in the world of machine learning. When I’ve had a problem understanding a complex issue or coding a neural network, the internet has seemed to have all the answers: from a simple linear regression to complex convolutional networks. At least that is what I thought...
Once I began getting better at this Deep Learning thing, I stumbled upon the all-glorious transformer. The original paper: “Attention is all you need”, proposed an innovative way to construct neural networks. No more convolutions! The paper proposes an encoder-decoder neural network made up of repeated encoder and decoder blocks. The structure is the following:
The left block is the encoder, and the right block is the decoder. If you don’t understand the parts of this model yet, I highly recommend going over Harvard’s “The Annotated Transformer” guide where they code the transformer model in PyTorch from scratch. I will not be covering important concepts like “multi-head attention” or “feed-forward layers” in this tutorial, so you should know them before you continue reading. If you have already taken a look at the code from scratch, you are probably wondering if you are going to have to copy-paste that code all over the place for every project you make. Thankfully, no. Modern python libraries like PyTorch and Tensorflow already include easily accessible transformer models through an import. However, there is more to it than just importing the model and plugging it in. Today I will explain how to use and tune PyTorch nn.Transformer() module. I personally struggled trying to find information about how to implement, train, and infer from it, so I decided to create my own guide for all of you.
To start, we need to import PyTorch and some other libraries we are going to be using:
Now, let’s take a closer look at the transformer module. I recommend starting by reading over PyTorch’s documentation about it. As they explain, there are no mandatory parameters. The module comes with the “Attention is all you need” model hyperparameters. To use it, let’s begin by creating a simple PyTorch model. I will only change some of the default parameters so our model doesn’t take unnecessarily long to train. I made those parameters part of our class:
The transformer blocks don’t care about the order of the input sequence. This, of course, is a problem. Saying “I ate a pizza with pineapple” is not the same as saying “a pineapple ate I with pizza”. Thankfully, we have a solution: positional encoding. This is a way to “give importance” to elements depending on their position. A detailed explanation of how it works can be found here, but a quick explanation is that we create a vector for each element representing its position with regard to every other element in the sequence. Positional encoding follows this very complicated-looking formula which, in practice, we won’t really need to understand:
For the sake of organization and reusability, let’s create a separate class for the positional encoding layer (it looks hard but it is really just the formula, dropout, and a residual connection):
Now that we have the only layer not included in PyTorch, we are ready to finish our model. Before adding the positional encoding, we need an embedding layer so that each element in our sequences is converted into a vector we can manipulate (instead of a fixed integer). We will also need a final linear layer so that we can convert the model’s output into the dimensions of our desired output. The final model should look something like this:
I know... It looks very intimidating, but if you understand what each part does, it is actually a pretty simple model to implement.
You may recall there was a special block in the model structure called “masked multi-head attention”:
So... what is masking? Before I can explain it to you, let’s quickly recapitulate what is going on with our tensors when we feed them into our model. First, we embed and encode (positional encoding) our source tensor. Then, our source tensor is encoded into an unintelligible encoded tensor that we feed into our decoder with our embedded and encoded (positionally) target vector. For our model to learn, we can’t just show it the whole target tensor! This would just give him the answer straight up.
The solution to this is a masking tensor. This tensor is made up of size (sequence length x sequence length) since for every element in the sequence, we show the model one more element. This matrix will be added to our target vector, so the matrix will be made up of zeros in the positions where the transformer can have access to the elements, and minus infinity where it can’t. An illustrated explanation might help you a bit more:
In case you didn’t know, tensors are matrices that can be stored in a GPU, and since they are matrices, all dimensions must have elements of the same size. Of course, this won’t happen when treating with tasks like NLP or different-sized images. Therefore, we use the so-called “special tokens”. These tokens allow our model to know where the start of the sentence is (<SOS>), where the end of the sentence is (<EOS>) and what elements are just there to fill up the remaining space so that our matrices have the sam sequence size (<PAD>). These tokens must also be converted into their corresponding integer id (In our example they will be 2, 3, and 4 respectively). Padding a sequence looks something like this:
To tell our model that these tokens should be irrelevant, we use a binary matrix where there is a True value on the positions where the padding token is and False where it isn’t:
To create the two masking matrices we talked about, we need to extend our transformer model. If you know a bit of NumPy, you will have no problem understanding what these methods do. If you can’t understand it, I recommend opening a Jupyter notebook and going step by step to understand what they do.
The full extended model looks like this (note the change in the forward method as well):
For the sake of this project, I am going to create a set of fake data we can use to train our model. This data will be made up of sequences like:
1, 1, 1, 1, 1, 1, 1, 1 → 1, 1, 1, 1, 1, 1, 1, 1
0, 0, 0, 0, 0, 0, 0, 0 → 0, 0, 0, 0, 0, 0, 0, 0
1, 0, 1, 0, 1, 0, 1, 0 → 1, 0, 1, 0, 1, 0, 1, 0
0, 1, 0, 1, 0, 1, 0, 1 → 0, 1, 0, 1, 0, 1, 0, 1
Feel free to skip to the next section if you aren’t interested in the data creation part.
I won’t bother explaining what these functions do since they are pretty easy to understand with basic NumPy knowledge. I’ll create all the sentences of size 8 so I don’t need padding, and I’ll organize them randomly into batches of size 16:
Now that we have data to work with, we can get to training our model. Let’s begin by creating an instance of our model, loss function, and optimizer. We will use the Stochastic Gradient Descent optimizer, the Cross-Entropy Loss function, and a learning rate of 0.01. I will also use my graphics card for this training since it will take less time, but it is not necessary.
An important concept we need to understand before continuing is that the target tensor we give as an input to the transformer must be shifted by one to the right (compared to the target output tensor). In other words, the tensor we want to give the model for training must have one extra element at the beginning and one less element at the end, and the tensor we compute the loss function with must be shifted in the other direction. This is so that if we give the model an element during inference, it gives us the next one.
Now that we have grasped this concept, let’s get to coding! The training loop is a standard training loop except:
The target tensor is passed to the model during the prediction
A target mask is generated to hide the next words
A padding mask might be generated and passed to the model as well
The validation loop is exactly the same as our training loop except we don’t read or update gradients:
In this example, I am training the model for 10 epochs. To simplify the training I created a fit function that calls the train and validation loop every epoch and prints the loss:
This produces the following out
Training and validating model------------------------- Epoch 1 -------------------------Training loss: 0.5878Validation loss: 0.4172------------------------- Epoch 2 -------------------------Training loss: 0.4384Validation loss: 0.3981------------------------- Epoch 3 -------------------------Training loss: 0.4155Validation loss: 0.3852------------------------- Epoch 4 -------------------------Training loss: 0.4003Validation loss: 0.3700------------------------- Epoch 5 -------------------------Training loss: 0.3842Validation loss: 0.3443------------------------- Epoch 6 -------------------------Training loss: 0.3592Validation loss: 0.3069------------------------- Epoch 7 -------------------------Training loss: 0.3291Validation loss: 0.2652------------------------- Epoch 8 -------------------------Training loss: 0.2956Validation loss: 0.2195------------------------- Epoch 9 -------------------------Training loss: 0.2684Validation loss: 0.1947------------------------- Epoch 10 ------------------------- Training loss: 0.2501Validation loss: 0.1930
After training we obtain the following losses per epoch:
As we can see, our model seems to have learned something. It is time to check if it has, but... how do we check it? We don’t have target tensors for data we have never seen. Here is where shifting our input target and output target tensor has an effect. As we saw before, our model learned to predict the next token when given an element. Therefore, we should be able to give our model the input tensor and the start token, and it should give us back the next element. If when the model predicts a token, we concatenate it with our previous input, we should slowly be able to add words to our output until our model predicts the <EOS> token.
Here is the code for that process:
The output of running this code is:
Example 0Input: [0, 0, 0, 0, 0, 0, 0, 0]Continuation: [0, 0, 0, 0, 0, 0, 0, 0, 0]Example 1Input: [1, 1, 1, 1, 1, 1, 1, 1]Continuation: [1, 1, 1, 1, 1, 1, 1, 1, 1]Example 2Input: [1, 0, 1, 0, 1, 0, 1, 0]Continuation: [1, 0, 1, 0, 1, 0, 1, 0]Example 3Input: [0, 1, 0, 1, 0, 1, 0, 1]Continuation: [1, 0, 1, 0, 1, 0, 1, 0]Example 4Input: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]Continuation: [0, 1, 0, 1, 0, 1, 0, 1, 0]Example 5Input: [0, 1]Continuation: [0, 1, 0, 1, 0, 1, 0]
So the model has indeed gotten the gist of our sequences, but it still makes some mistakes when trying to predict the continuation. For example, in “Example 4”, the model should predict a 1 as the first token, since the ending of the input is a 0. We can also see how during inference our sentences don’t need to have the same length, and the outputs will also not have the same length (see “Example 5”).
I believe this article can help a lot of beginner/intermediate machine learning developers learn how to work with transformer models in PyTorch, and, since the structure is the same in other languages, this tutorial is probably also useful for other frameworks like Tensorflow (hopefully).
If you have any suggestions or find any bugs feel free to leave a comment and I will fix it ASAP.
Full Colab Notebook: https://drive.google.com/file/d/15gyTrsd-OU6YZVyjwis48ysrXFPEcv9r/view?usp=sharing | [
{
"code": null,
"e": 481,
"s": 171,
"text": "I have recently been getting more involved in the world of machine learning. When I’ve had a problem understanding a complex issue or coding a neural network, the internet has seemed to have all the answers: from a simple linear regression to complex convolutional networks. At least that is what I thought..."
},
{
"code": null,
"e": 845,
"s": 481,
"text": "Once I began getting better at this Deep Learning thing, I stumbled upon the all-glorious transformer. The original paper: “Attention is all you need”, proposed an innovative way to construct neural networks. No more convolutions! The paper proposes an encoder-decoder neural network made up of repeated encoder and decoder blocks. The structure is the following:"
},
{
"code": null,
"e": 1895,
"s": 845,
"text": "The left block is the encoder, and the right block is the decoder. If you don’t understand the parts of this model yet, I highly recommend going over Harvard’s “The Annotated Transformer” guide where they code the transformer model in PyTorch from scratch. I will not be covering important concepts like “multi-head attention” or “feed-forward layers” in this tutorial, so you should know them before you continue reading. If you have already taken a look at the code from scratch, you are probably wondering if you are going to have to copy-paste that code all over the place for every project you make. Thankfully, no. Modern python libraries like PyTorch and Tensorflow already include easily accessible transformer models through an import. However, there is more to it than just importing the model and plugging it in. Today I will explain how to use and tune PyTorch nn.Transformer() module. I personally struggled trying to find information about how to implement, train, and infer from it, so I decided to create my own guide for all of you."
},
{
"code": null,
"e": 1982,
"s": 1895,
"text": "To start, we need to import PyTorch and some other libraries we are going to be using:"
},
{
"code": null,
"e": 2446,
"s": 1982,
"text": "Now, let’s take a closer look at the transformer module. I recommend starting by reading over PyTorch’s documentation about it. As they explain, there are no mandatory parameters. The module comes with the “Attention is all you need” model hyperparameters. To use it, let’s begin by creating a simple PyTorch model. I will only change some of the default parameters so our model doesn’t take unnecessarily long to train. I made those parameters part of our class:"
},
{
"code": null,
"e": 3101,
"s": 2446,
"text": "The transformer blocks don’t care about the order of the input sequence. This, of course, is a problem. Saying “I ate a pizza with pineapple” is not the same as saying “a pineapple ate I with pizza”. Thankfully, we have a solution: positional encoding. This is a way to “give importance” to elements depending on their position. A detailed explanation of how it works can be found here, but a quick explanation is that we create a vector for each element representing its position with regard to every other element in the sequence. Positional encoding follows this very complicated-looking formula which, in practice, we won’t really need to understand:"
},
{
"code": null,
"e": 3298,
"s": 3101,
"text": "For the sake of organization and reusability, let’s create a separate class for the positional encoding layer (it looks hard but it is really just the formula, dropout, and a residual connection):"
},
{
"code": null,
"e": 3741,
"s": 3298,
"text": "Now that we have the only layer not included in PyTorch, we are ready to finish our model. Before adding the positional encoding, we need an embedding layer so that each element in our sequences is converted into a vector we can manipulate (instead of a fixed integer). We will also need a final linear layer so that we can convert the model’s output into the dimensions of our desired output. The final model should look something like this:"
},
{
"code": null,
"e": 3873,
"s": 3741,
"text": "I know... It looks very intimidating, but if you understand what each part does, it is actually a pretty simple model to implement."
},
{
"code": null,
"e": 3975,
"s": 3873,
"text": "You may recall there was a special block in the model structure called “masked multi-head attention”:"
},
{
"code": null,
"e": 4476,
"s": 3975,
"text": "So... what is masking? Before I can explain it to you, let’s quickly recapitulate what is going on with our tensors when we feed them into our model. First, we embed and encode (positional encoding) our source tensor. Then, our source tensor is encoded into an unintelligible encoded tensor that we feed into our decoder with our embedded and encoded (positionally) target vector. For our model to learn, we can’t just show it the whole target tensor! This would just give him the answer straight up."
},
{
"code": null,
"e": 4910,
"s": 4476,
"text": "The solution to this is a masking tensor. This tensor is made up of size (sequence length x sequence length) since for every element in the sequence, we show the model one more element. This matrix will be added to our target vector, so the matrix will be made up of zeros in the positions where the transformer can have access to the elements, and minus infinity where it can’t. An illustrated explanation might help you a bit more:"
},
{
"code": null,
"e": 5623,
"s": 4910,
"text": "In case you didn’t know, tensors are matrices that can be stored in a GPU, and since they are matrices, all dimensions must have elements of the same size. Of course, this won’t happen when treating with tasks like NLP or different-sized images. Therefore, we use the so-called “special tokens”. These tokens allow our model to know where the start of the sentence is (<SOS>), where the end of the sentence is (<EOS>) and what elements are just there to fill up the remaining space so that our matrices have the sam sequence size (<PAD>). These tokens must also be converted into their corresponding integer id (In our example they will be 2, 3, and 4 respectively). Padding a sequence looks something like this:"
},
{
"code": null,
"e": 5802,
"s": 5623,
"text": "To tell our model that these tokens should be irrelevant, we use a binary matrix where there is a True value on the positions where the padding token is and False where it isn’t:"
},
{
"code": null,
"e": 6103,
"s": 5802,
"text": "To create the two masking matrices we talked about, we need to extend our transformer model. If you know a bit of NumPy, you will have no problem understanding what these methods do. If you can’t understand it, I recommend opening a Jupyter notebook and going step by step to understand what they do."
},
{
"code": null,
"e": 6192,
"s": 6103,
"text": "The full extended model looks like this (note the change in the forward method as well):"
},
{
"code": null,
"e": 6338,
"s": 6192,
"text": "For the sake of this project, I am going to create a set of fake data we can use to train our model. This data will be made up of sequences like:"
},
{
"code": null,
"e": 6386,
"s": 6338,
"text": "1, 1, 1, 1, 1, 1, 1, 1 → 1, 1, 1, 1, 1, 1, 1, 1"
},
{
"code": null,
"e": 6434,
"s": 6386,
"text": "0, 0, 0, 0, 0, 0, 0, 0 → 0, 0, 0, 0, 0, 0, 0, 0"
},
{
"code": null,
"e": 6482,
"s": 6434,
"text": "1, 0, 1, 0, 1, 0, 1, 0 → 1, 0, 1, 0, 1, 0, 1, 0"
},
{
"code": null,
"e": 6530,
"s": 6482,
"text": "0, 1, 0, 1, 0, 1, 0, 1 → 0, 1, 0, 1, 0, 1, 0, 1"
},
{
"code": null,
"e": 6620,
"s": 6530,
"text": "Feel free to skip to the next section if you aren’t interested in the data creation part."
},
{
"code": null,
"e": 6861,
"s": 6620,
"text": "I won’t bother explaining what these functions do since they are pretty easy to understand with basic NumPy knowledge. I’ll create all the sentences of size 8 so I don’t need padding, and I’ll organize them randomly into batches of size 16:"
},
{
"code": null,
"e": 7234,
"s": 6861,
"text": "Now that we have data to work with, we can get to training our model. Let’s begin by creating an instance of our model, loss function, and optimizer. We will use the Stochastic Gradient Descent optimizer, the Cross-Entropy Loss function, and a learning rate of 0.01. I will also use my graphics card for this training since it will take less time, but it is not necessary."
},
{
"code": null,
"e": 7761,
"s": 7234,
"text": "An important concept we need to understand before continuing is that the target tensor we give as an input to the transformer must be shifted by one to the right (compared to the target output tensor). In other words, the tensor we want to give the model for training must have one extra element at the beginning and one less element at the end, and the tensor we compute the loss function with must be shifted in the other direction. This is so that if we give the model an element during inference, it gives us the next one."
},
{
"code": null,
"e": 7875,
"s": 7761,
"text": "Now that we have grasped this concept, let’s get to coding! The training loop is a standard training loop except:"
},
{
"code": null,
"e": 7938,
"s": 7875,
"text": "The target tensor is passed to the model during the prediction"
},
{
"code": null,
"e": 7988,
"s": 7938,
"text": "A target mask is generated to hide the next words"
},
{
"code": null,
"e": 8054,
"s": 7988,
"text": "A padding mask might be generated and passed to the model as well"
},
{
"code": null,
"e": 8157,
"s": 8054,
"text": "The validation loop is exactly the same as our training loop except we don’t read or update gradients:"
},
{
"code": null,
"e": 8337,
"s": 8157,
"text": "In this example, I am training the model for 10 epochs. To simplify the training I created a fit function that calls the train and validation loop every epoch and prints the loss:"
},
{
"code": null,
"e": 8369,
"s": 8337,
"text": "This produces the following out"
},
{
"code": null,
"e": 9431,
"s": 8369,
"text": "Training and validating model------------------------- Epoch 1 -------------------------Training loss: 0.5878Validation loss: 0.4172------------------------- Epoch 2 -------------------------Training loss: 0.4384Validation loss: 0.3981------------------------- Epoch 3 -------------------------Training loss: 0.4155Validation loss: 0.3852------------------------- Epoch 4 -------------------------Training loss: 0.4003Validation loss: 0.3700------------------------- Epoch 5 -------------------------Training loss: 0.3842Validation loss: 0.3443------------------------- Epoch 6 -------------------------Training loss: 0.3592Validation loss: 0.3069------------------------- Epoch 7 -------------------------Training loss: 0.3291Validation loss: 0.2652------------------------- Epoch 8 -------------------------Training loss: 0.2956Validation loss: 0.2195------------------------- Epoch 9 -------------------------Training loss: 0.2684Validation loss: 0.1947------------------------- Epoch 10 ------------------------- Training loss: 0.2501Validation loss: 0.1930"
},
{
"code": null,
"e": 9488,
"s": 9431,
"text": "After training we obtain the following losses per epoch:"
},
{
"code": null,
"e": 10130,
"s": 9488,
"text": "As we can see, our model seems to have learned something. It is time to check if it has, but... how do we check it? We don’t have target tensors for data we have never seen. Here is where shifting our input target and output target tensor has an effect. As we saw before, our model learned to predict the next token when given an element. Therefore, we should be able to give our model the input tensor and the start token, and it should give us back the next element. If when the model predicts a token, we concatenate it with our previous input, we should slowly be able to add words to our output until our model predicts the <EOS> token."
},
{
"code": null,
"e": 10165,
"s": 10130,
"text": "Here is the code for that process:"
},
{
"code": null,
"e": 10201,
"s": 10165,
"text": "The output of running this code is:"
},
{
"code": null,
"e": 10667,
"s": 10201,
"text": "Example 0Input: [0, 0, 0, 0, 0, 0, 0, 0]Continuation: [0, 0, 0, 0, 0, 0, 0, 0, 0]Example 1Input: [1, 1, 1, 1, 1, 1, 1, 1]Continuation: [1, 1, 1, 1, 1, 1, 1, 1, 1]Example 2Input: [1, 0, 1, 0, 1, 0, 1, 0]Continuation: [1, 0, 1, 0, 1, 0, 1, 0]Example 3Input: [0, 1, 0, 1, 0, 1, 0, 1]Continuation: [1, 0, 1, 0, 1, 0, 1, 0]Example 4Input: [0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0]Continuation: [0, 1, 0, 1, 0, 1, 0, 1, 0]Example 5Input: [0, 1]Continuation: [0, 1, 0, 1, 0, 1, 0]"
},
{
"code": null,
"e": 11072,
"s": 10667,
"text": "So the model has indeed gotten the gist of our sequences, but it still makes some mistakes when trying to predict the continuation. For example, in “Example 4”, the model should predict a 1 as the first token, since the ending of the input is a 0. We can also see how during inference our sentences don’t need to have the same length, and the outputs will also not have the same length (see “Example 5”)."
},
{
"code": null,
"e": 11362,
"s": 11072,
"text": "I believe this article can help a lot of beginner/intermediate machine learning developers learn how to work with transformer models in PyTorch, and, since the structure is the same in other languages, this tutorial is probably also useful for other frameworks like Tensorflow (hopefully)."
},
{
"code": null,
"e": 11460,
"s": 11362,
"text": "If you have any suggestions or find any bugs feel free to leave a comment and I will fix it ASAP."
}
] |
Kivy – Python Framework for Mobile App development | 20 Aug, 2020
Kivy is a free and open-source Python library used for developing mobile applications and other multitouch application software with a Natural User Interface.
Installation
We can download the latest version of Kivy from here. After opening the link you can choose your Platform and follow the instructions specific for your platform.
Installation using PyCharm
We will open PyCharm and Create a New Project and Name it as “Tutorial”(Project Name), we can Name as we want.We will Right click on “Tutorial”(Project Name) and create a new Directory Named as FirstApp.Inside this FirstApp We will create a Python file named as Main.To install Kivy follow:Goto File->Settings->Project:Tutorial(Project Name).Under Project: Tutorial(Project Name), Click on Project Interpreter.Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:Installing Kivy DependenciesSimilarly Click on the following dependencies to install them :kivy-deps.anglekivy-deps.glewkivy-deps.gstreamerkivy-deps.sdl2Example 1 : Printing Welcome Message on Kivy App# import the modulesfrom kivy.app import Appfrom kivy.uix.label import Label # defining the Base Class of our first Kivy Appclass MyApp(App): def build(self): # initializing a Label with text ‘Hello World’ and return its instance return Label(text = 'welcome to GeeksforGeeks') if __name__ == '__main__': # MyApp is initialized and its run() method called MyApp().run()Output :Example 2 : Creating Login Screen# importing the modulesfrom kivy.app import Appfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.label import Labelfrom kivy.uix.textinput import TextInput # this class is used as a Base for our # Root Widget which is LoginScreen class LoginScreen(GridLayout): # overriding the method __init__() so as to # add widgets and to define their behavior def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # GridLayout managing its children in two columns # and add a Label and a TextInput for the Email id and password self.cols = 2 self.add_widget(Label(text = 'Email id')) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = 'password')) self.password = TextInput(password = True, multiline = False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': # MyApp is initialized and # its run() method called MyApp().run()Output :My Personal Notes
arrow_drop_upSave
We will open PyCharm and Create a New Project and Name it as “Tutorial”(Project Name), we can Name as we want.
We will Right click on “Tutorial”(Project Name) and create a new Directory Named as FirstApp.
Inside this FirstApp We will create a Python file named as Main.
To install Kivy follow:Goto File->Settings->Project:Tutorial(Project Name).Under Project: Tutorial(Project Name), Click on Project Interpreter.Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:Installing Kivy DependenciesSimilarly Click on the following dependencies to install them :kivy-deps.anglekivy-deps.glewkivy-deps.gstreamerkivy-deps.sdl2Example 1 : Printing Welcome Message on Kivy App# import the modulesfrom kivy.app import Appfrom kivy.uix.label import Label # defining the Base Class of our first Kivy Appclass MyApp(App): def build(self): # initializing a Label with text ‘Hello World’ and return its instance return Label(text = 'welcome to GeeksforGeeks') if __name__ == '__main__': # MyApp is initialized and its run() method called MyApp().run()Output :Example 2 : Creating Login Screen# importing the modulesfrom kivy.app import Appfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.label import Labelfrom kivy.uix.textinput import TextInput # this class is used as a Base for our # Root Widget which is LoginScreen class LoginScreen(GridLayout): # overriding the method __init__() so as to # add widgets and to define their behavior def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # GridLayout managing its children in two columns # and add a Label and a TextInput for the Email id and password self.cols = 2 self.add_widget(Label(text = 'Email id')) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = 'password')) self.password = TextInput(password = True, multiline = False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': # MyApp is initialized and # its run() method called MyApp().run()Output :My Personal Notes
arrow_drop_upSave
To install Kivy follow:
Goto File->Settings->Project:Tutorial(Project Name).Under Project: Tutorial(Project Name), Click on Project Interpreter.Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:
Goto File->Settings->Project:Tutorial(Project Name).
Under Project: Tutorial(Project Name), Click on Project Interpreter.
Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:
Installing Kivy Dependencies
Similarly Click on the following dependencies to install them :
kivy-deps.angle
kivy-deps.glew
kivy-deps.gstreamer
kivy-deps.sdl2
Example 1 : Printing Welcome Message on Kivy App
# import the modulesfrom kivy.app import Appfrom kivy.uix.label import Label # defining the Base Class of our first Kivy Appclass MyApp(App): def build(self): # initializing a Label with text ‘Hello World’ and return its instance return Label(text = 'welcome to GeeksforGeeks') if __name__ == '__main__': # MyApp is initialized and its run() method called MyApp().run()
Output :
Example 2 : Creating Login Screen
# importing the modulesfrom kivy.app import Appfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.label import Labelfrom kivy.uix.textinput import TextInput # this class is used as a Base for our # Root Widget which is LoginScreen class LoginScreen(GridLayout): # overriding the method __init__() so as to # add widgets and to define their behavior def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # GridLayout managing its children in two columns # and add a Label and a TextInput for the Email id and password self.cols = 2 self.add_widget(Label(text = 'Email id')) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = 'password')) self.password = TextInput(password = True, multiline = False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': # MyApp is initialized and # its run() method called MyApp().run()
Output :
Python-kivy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Python Classes and Objects
Python OOPs Concepts
Introduction To PYTHON
Python | os.path.join() method
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Aug, 2020"
},
{
"code": null,
"e": 211,
"s": 52,
"text": "Kivy is a free and open-source Python library used for developing mobile applications and other multitouch application software with a Natural User Interface."
},
{
"code": null,
"e": 224,
"s": 211,
"text": "Installation"
},
{
"code": null,
"e": 386,
"s": 224,
"text": "We can download the latest version of Kivy from here. After opening the link you can choose your Platform and follow the instructions specific for your platform."
},
{
"code": null,
"e": 413,
"s": 386,
"text": "Installation using PyCharm"
},
{
"code": null,
"e": 2677,
"s": 413,
"text": "We will open PyCharm and Create a New Project and Name it as “Tutorial”(Project Name), we can Name as we want.We will Right click on “Tutorial”(Project Name) and create a new Directory Named as FirstApp.Inside this FirstApp We will create a Python file named as Main.To install Kivy follow:Goto File->Settings->Project:Tutorial(Project Name).Under Project: Tutorial(Project Name), Click on Project Interpreter.Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:Installing Kivy DependenciesSimilarly Click on the following dependencies to install them :kivy-deps.anglekivy-deps.glewkivy-deps.gstreamerkivy-deps.sdl2Example 1 : Printing Welcome Message on Kivy App# import the modulesfrom kivy.app import Appfrom kivy.uix.label import Label # defining the Base Class of our first Kivy Appclass MyApp(App): def build(self): # initializing a Label with text ‘Hello World’ and return its instance return Label(text = 'welcome to GeeksforGeeks') if __name__ == '__main__': # MyApp is initialized and its run() method called MyApp().run()Output :Example 2 : Creating Login Screen# importing the modulesfrom kivy.app import Appfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.label import Labelfrom kivy.uix.textinput import TextInput # this class is used as a Base for our # Root Widget which is LoginScreen class LoginScreen(GridLayout): # overriding the method __init__() so as to # add widgets and to define their behavior def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # GridLayout managing its children in two columns # and add a Label and a TextInput for the Email id and password self.cols = 2 self.add_widget(Label(text = 'Email id')) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = 'password')) self.password = TextInput(password = True, multiline = False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': # MyApp is initialized and # its run() method called MyApp().run()Output :My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 2788,
"s": 2677,
"text": "We will open PyCharm and Create a New Project and Name it as “Tutorial”(Project Name), we can Name as we want."
},
{
"code": null,
"e": 2882,
"s": 2788,
"text": "We will Right click on “Tutorial”(Project Name) and create a new Directory Named as FirstApp."
},
{
"code": null,
"e": 2947,
"s": 2882,
"text": "Inside this FirstApp We will create a Python file named as Main."
},
{
"code": null,
"e": 4944,
"s": 2947,
"text": "To install Kivy follow:Goto File->Settings->Project:Tutorial(Project Name).Under Project: Tutorial(Project Name), Click on Project Interpreter.Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:Installing Kivy DependenciesSimilarly Click on the following dependencies to install them :kivy-deps.anglekivy-deps.glewkivy-deps.gstreamerkivy-deps.sdl2Example 1 : Printing Welcome Message on Kivy App# import the modulesfrom kivy.app import Appfrom kivy.uix.label import Label # defining the Base Class of our first Kivy Appclass MyApp(App): def build(self): # initializing a Label with text ‘Hello World’ and return its instance return Label(text = 'welcome to GeeksforGeeks') if __name__ == '__main__': # MyApp is initialized and its run() method called MyApp().run()Output :Example 2 : Creating Login Screen# importing the modulesfrom kivy.app import Appfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.label import Labelfrom kivy.uix.textinput import TextInput # this class is used as a Base for our # Root Widget which is LoginScreen class LoginScreen(GridLayout): # overriding the method __init__() so as to # add widgets and to define their behavior def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # GridLayout managing its children in two columns # and add a Label and a TextInput for the Email id and password self.cols = 2 self.add_widget(Label(text = 'Email id')) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = 'password')) self.password = TextInput(password = True, multiline = False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': # MyApp is initialized and # its run() method called MyApp().run()Output :My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 4968,
"s": 4944,
"text": "To install Kivy follow:"
},
{
"code": null,
"e": 5179,
"s": 4968,
"text": "Goto File->Settings->Project:Tutorial(Project Name).Under Project: Tutorial(Project Name), Click on Project Interpreter.Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:"
},
{
"code": null,
"e": 5232,
"s": 5179,
"text": "Goto File->Settings->Project:Tutorial(Project Name)."
},
{
"code": null,
"e": 5301,
"s": 5232,
"text": "Under Project: Tutorial(Project Name), Click on Project Interpreter."
},
{
"code": null,
"e": 5392,
"s": 5301,
"text": "Then Click on ‘+’ Sign on top right and Search for Kivy you will see the following Screen:"
},
{
"code": null,
"e": 5421,
"s": 5392,
"text": "Installing Kivy Dependencies"
},
{
"code": null,
"e": 5485,
"s": 5421,
"text": "Similarly Click on the following dependencies to install them :"
},
{
"code": null,
"e": 5501,
"s": 5485,
"text": "kivy-deps.angle"
},
{
"code": null,
"e": 5516,
"s": 5501,
"text": "kivy-deps.glew"
},
{
"code": null,
"e": 5536,
"s": 5516,
"text": "kivy-deps.gstreamer"
},
{
"code": null,
"e": 5551,
"s": 5536,
"text": "kivy-deps.sdl2"
},
{
"code": null,
"e": 5600,
"s": 5551,
"text": "Example 1 : Printing Welcome Message on Kivy App"
},
{
"code": "# import the modulesfrom kivy.app import Appfrom kivy.uix.label import Label # defining the Base Class of our first Kivy Appclass MyApp(App): def build(self): # initializing a Label with text ‘Hello World’ and return its instance return Label(text = 'welcome to GeeksforGeeks') if __name__ == '__main__': # MyApp is initialized and its run() method called MyApp().run()",
"e": 6009,
"s": 5600,
"text": null
},
{
"code": null,
"e": 6018,
"s": 6009,
"text": "Output :"
},
{
"code": null,
"e": 6052,
"s": 6018,
"text": "Example 2 : Creating Login Screen"
},
{
"code": "# importing the modulesfrom kivy.app import Appfrom kivy.uix.gridlayout import GridLayoutfrom kivy.uix.label import Labelfrom kivy.uix.textinput import TextInput # this class is used as a Base for our # Root Widget which is LoginScreen class LoginScreen(GridLayout): # overriding the method __init__() so as to # add widgets and to define their behavior def __init__(self, **kwargs): super(LoginScreen, self).__init__(**kwargs) # GridLayout managing its children in two columns # and add a Label and a TextInput for the Email id and password self.cols = 2 self.add_widget(Label(text = 'Email id')) self.username = TextInput(multiline = False) self.add_widget(self.username) self.add_widget(Label(text = 'password')) self.password = TextInput(password = True, multiline = False) self.add_widget(self.password) class MyApp(App): def build(self): return LoginScreen() if __name__ == '__main__': # MyApp is initialized and # its run() method called MyApp().run()",
"e": 7123,
"s": 6052,
"text": null
},
{
"code": null,
"e": 7132,
"s": 7123,
"text": "Output :"
},
{
"code": null,
"e": 7144,
"s": 7132,
"text": "Python-kivy"
},
{
"code": null,
"e": 7151,
"s": 7144,
"text": "Python"
},
{
"code": null,
"e": 7249,
"s": 7151,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 7281,
"s": 7249,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 7308,
"s": 7281,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 7329,
"s": 7308,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 7352,
"s": 7329,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 7383,
"s": 7352,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 7439,
"s": 7383,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 7481,
"s": 7439,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 7523,
"s": 7481,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 7562,
"s": 7523,
"text": "Python | Get unique values from a list"
}
] |
How to Update Contents of a Table using JDBC Connection? | 08 Dec, 2020
JDBC (Java Database Connectivity) is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend( for storing data).
1. Create Database: You can create a database using SQLyog and create some tables in it and fill data inside it in order to update the contents of a table. Here, for example, the name of my database is hotelman, and table names are cuslogin and adminlogin. We will be taking cuslogin table as an example.
2. Create Connection: Open Netbeans and create a new package. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java.
Java
// Java program to create a connection to a database import java.sql.*; public class connection { // Connection instance Connection con = null; public static Connection connectDB() { try { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection( "jdbc:mysql://localhost:3306/hotelman", "root", "1234"); // here,root is the username and 1234 is the // password,you can set your own username and // password. return con; } catch (SQLException e) { System.out.println(e); } }}
3. Update Contents In a Table: Let’s suppose we want to update the customer name from cuslogin table whose id is 2.
Initialize a string with the SQL query as follows
String sql="update cuslogin set name='GFG' where id=2";
Initialize the below objects of Connection class, PreparedStatement class(needed for jdbc), and connect with the database as follows
Connection con=null;
PreparedStatement p=null;
con=connection.connectDB();
Now, add the SQL query given above, inside prepareStatement and execute it as follows
p =con.prepareStatement(sql);
p.execute();
Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for updating the name of the customer whose id is 2, from table cuslogin.
Note: both the file’s viz result.java and connection.java should be inside the same package, else the program won’t give the desired output!!
Java
// Java Program to Update contents in a table import java.sql.*;public class result { public static void main(String[] args) { Connection con = null; PreparedStatement p = null; con = connection.connectDB(); try { String sql = "update cuslogin set name='GFG' where id=2"; p = con.prepareStatement(sql); p.execute(); } catch (SQLException e) { System.out.println(e); } }}
After running the result.java, the output can be seen in SQLyog as follows:
We can see, the customer whose id is 2, now has the name GFG.
JDBC
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n08 Dec, 2020"
},
{
"code": null,
"e": 303,
"s": 28,
"text": "JDBC (Java Database Connectivity) is basically a standard API(application interface) between the java programming language and various databases like Oracle, SQL, PostgreSQL, etc. It connects the front end(for interacting with the users) with the backend( for storing data)."
},
{
"code": null,
"e": 608,
"s": 303,
"text": "1. Create Database: You can create a database using SQLyog and create some tables in it and fill data inside it in order to update the contents of a table. Here, for example, the name of my database is hotelman, and table names are cuslogin and adminlogin. We will be taking cuslogin table as an example."
},
{
"code": null,
"e": 801,
"s": 608,
"text": "2. Create Connection: Open Netbeans and create a new package. Inside the package, open a new java file and type the below code for JDBC connectivity and save the filename with connection.java."
},
{
"code": null,
"e": 806,
"s": 801,
"text": "Java"
},
{
"code": "// Java program to create a connection to a database import java.sql.*; public class connection { // Connection instance Connection con = null; public static Connection connectDB() { try { Class.forName(\"com.mysql.jdbc.Driver\"); Connection con = DriverManager.getConnection( \"jdbc:mysql://localhost:3306/hotelman\", \"root\", \"1234\"); // here,root is the username and 1234 is the // password,you can set your own username and // password. return con; } catch (SQLException e) { System.out.println(e); } }}",
"e": 1481,
"s": 806,
"text": null
},
{
"code": null,
"e": 1598,
"s": 1481,
"text": "3. Update Contents In a Table: Let’s suppose we want to update the customer name from cuslogin table whose id is 2."
},
{
"code": null,
"e": 1648,
"s": 1598,
"text": "Initialize a string with the SQL query as follows"
},
{
"code": null,
"e": 1705,
"s": 1648,
"text": "String sql=\"update cuslogin set name='GFG' where id=2\";"
},
{
"code": null,
"e": 1840,
"s": 1705,
"text": "Initialize the below objects of Connection class, PreparedStatement class(needed for jdbc), and connect with the database as follows "
},
{
"code": null,
"e": 1915,
"s": 1840,
"text": "Connection con=null;\nPreparedStatement p=null;\ncon=connection.connectDB();"
},
{
"code": null,
"e": 2001,
"s": 1915,
"text": "Now, add the SQL query given above, inside prepareStatement and execute it as follows"
},
{
"code": null,
"e": 2044,
"s": 2001,
"text": "p =con.prepareStatement(sql);\np.execute();"
},
{
"code": null,
"e": 2224,
"s": 2044,
"text": "Open a new java file (here, its result.java) inside the same package and type the full code (shown below) for updating the name of the customer whose id is 2, from table cuslogin."
},
{
"code": null,
"e": 2366,
"s": 2224,
"text": "Note: both the file’s viz result.java and connection.java should be inside the same package, else the program won’t give the desired output!!"
},
{
"code": null,
"e": 2371,
"s": 2366,
"text": "Java"
},
{
"code": "// Java Program to Update contents in a table import java.sql.*;public class result { public static void main(String[] args) { Connection con = null; PreparedStatement p = null; con = connection.connectDB(); try { String sql = \"update cuslogin set name='GFG' where id=2\"; p = con.prepareStatement(sql); p.execute(); } catch (SQLException e) { System.out.println(e); } }}",
"e": 2862,
"s": 2371,
"text": null
},
{
"code": null,
"e": 2938,
"s": 2862,
"text": "After running the result.java, the output can be seen in SQLyog as follows:"
},
{
"code": null,
"e": 3000,
"s": 2938,
"text": "We can see, the customer whose id is 2, now has the name GFG."
},
{
"code": null,
"e": 3005,
"s": 3000,
"text": "JDBC"
},
{
"code": null,
"e": 3012,
"s": 3005,
"text": "Picked"
},
{
"code": null,
"e": 3036,
"s": 3012,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3041,
"s": 3036,
"text": "Java"
},
{
"code": null,
"e": 3055,
"s": 3041,
"text": "Java Programs"
},
{
"code": null,
"e": 3074,
"s": 3055,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3079,
"s": 3074,
"text": "Java"
}
] |
Rename all file names in your directory using Python | 15 Aug, 2021
Given multiple files in a directory having different names, the task is to rename all those files in sorted order. We can use OS module in order to do this operation. The OS module in Python provides functions for interacting with the operating system and provides a portable way of using operating system-dependent functionality. We can go to the current working directory using os.getcwd() method and rename the files with os.rame() method.
Below is the Python implementation :
Python3
# Python program to rename all file# names in your directoryimport os os.chdir('D:\\Geeksforgeeks')print(os.getcwd()) for count, f in enumerate(os.listdir()): f_name, f_ext = os.path.splitext(f) f_name = "geek" + str(count) new_name = f'{f_name}{f_ext}' os.rename(f, new_name)
Output:
Shivam_k
miguelrodrigo249
Python OS-file-module
Python os-module-programs
python-os-module
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n15 Aug, 2021"
},
{
"code": null,
"e": 473,
"s": 28,
"text": "Given multiple files in a directory having different names, the task is to rename all those files in sorted order. We can use OS module in order to do this operation. The OS module in Python provides functions for interacting with the operating system and provides a portable way of using operating system-dependent functionality. We can go to the current working directory using os.getcwd() method and rename the files with os.rame() method. "
},
{
"code": null,
"e": 511,
"s": 473,
"text": "Below is the Python implementation : "
},
{
"code": null,
"e": 519,
"s": 511,
"text": "Python3"
},
{
"code": "# Python program to rename all file# names in your directoryimport os os.chdir('D:\\\\Geeksforgeeks')print(os.getcwd()) for count, f in enumerate(os.listdir()): f_name, f_ext = os.path.splitext(f) f_name = \"geek\" + str(count) new_name = f'{f_name}{f_ext}' os.rename(f, new_name)",
"e": 809,
"s": 519,
"text": null
},
{
"code": null,
"e": 819,
"s": 809,
"text": "Output: "
},
{
"code": null,
"e": 830,
"s": 821,
"text": "Shivam_k"
},
{
"code": null,
"e": 847,
"s": 830,
"text": "miguelrodrigo249"
},
{
"code": null,
"e": 869,
"s": 847,
"text": "Python OS-file-module"
},
{
"code": null,
"e": 895,
"s": 869,
"text": "Python os-module-programs"
},
{
"code": null,
"e": 912,
"s": 895,
"text": "python-os-module"
},
{
"code": null,
"e": 919,
"s": 912,
"text": "Python"
},
{
"code": null,
"e": 935,
"s": 919,
"text": "Python Programs"
}
] |
Python | Convert string tuples to list tuples | 18 Oct, 2019
Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to list of tuples. This kind of problem can have it’s occurrence in data science domain. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using eval() + list comprehensionThis problem can be easily performed as one liner using the inbuilt function of eval(), which performs this task of string to tuple conversion and list comprehension.
# Python3 code to demonstrate working of# Converting string tuples to list tuples # using list comprehension + eval() # Initializing list test_list = ["('gfg', 1)", "('is', 2)", "('best', 3)"] # printing original list print("The original list is : " + str(test_list)) # Converting string tuples to list tuples # using list comprehension + eval()res = [eval(ele) for ele in test_list] # printing resultprint("The list tuple after conversion : " + str(res))
The original list is : ["('gfg', 1)", "('is', 2)", "('best', 3)"]
The list tuple after conversion : [('gfg', 1), ('is', 2), ('best', 3)]
Method #2 : Using eval() + map()This task can also be performed using combination of above functions. The task performed by list comprehension above can be performed using map() in this method.
# Python3 code to demonstrate working of# Converting string tuples to list tuples # using map() + eval() # Initializing list test_list = ["('gfg', 1)", "('is', 2)", "('best', 3)"] # printing original list print("The original list is : " + str(test_list)) # Converting string tuples to list tuples # using map() + eval()res = list(map(eval, test_list)) # printing resultprint("The list tuple after conversion : " + str(res))
The original list is : ["('gfg', 1)", "('is', 2)", "('best', 3)"]
The list tuple after conversion : [('gfg', 1), ('is', 2), ('best', 3)]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n18 Oct, 2019"
},
{
"code": null,
"e": 343,
"s": 28,
"text": "Sometimes, while working with Python we can have a problem in which we have a list of records in form of tuples in stringified form and we desire to convert them to list of tuples. This kind of problem can have it’s occurrence in data science domain. Let’s discuss certain ways in which this task can be performed."
},
{
"code": null,
"e": 555,
"s": 343,
"text": "Method #1 : Using eval() + list comprehensionThis problem can be easily performed as one liner using the inbuilt function of eval(), which performs this task of string to tuple conversion and list comprehension."
},
{
"code": "# Python3 code to demonstrate working of# Converting string tuples to list tuples # using list comprehension + eval() # Initializing list test_list = [\"('gfg', 1)\", \"('is', 2)\", \"('best', 3)\"] # printing original list print(\"The original list is : \" + str(test_list)) # Converting string tuples to list tuples # using list comprehension + eval()res = [eval(ele) for ele in test_list] # printing resultprint(\"The list tuple after conversion : \" + str(res))",
"e": 1015,
"s": 555,
"text": null
},
{
"code": null,
"e": 1153,
"s": 1015,
"text": "The original list is : [\"('gfg', 1)\", \"('is', 2)\", \"('best', 3)\"]\nThe list tuple after conversion : [('gfg', 1), ('is', 2), ('best', 3)]\n"
},
{
"code": null,
"e": 1349,
"s": 1155,
"text": "Method #2 : Using eval() + map()This task can also be performed using combination of above functions. The task performed by list comprehension above can be performed using map() in this method."
},
{
"code": "# Python3 code to demonstrate working of# Converting string tuples to list tuples # using map() + eval() # Initializing list test_list = [\"('gfg', 1)\", \"('is', 2)\", \"('best', 3)\"] # printing original list print(\"The original list is : \" + str(test_list)) # Converting string tuples to list tuples # using map() + eval()res = list(map(eval, test_list)) # printing resultprint(\"The list tuple after conversion : \" + str(res))",
"e": 1777,
"s": 1349,
"text": null
},
{
"code": null,
"e": 1915,
"s": 1777,
"text": "The original list is : [\"('gfg', 1)\", \"('is', 2)\", \"('best', 3)\"]\nThe list tuple after conversion : [('gfg', 1), ('is', 2), ('best', 3)]\n"
},
{
"code": null,
"e": 1936,
"s": 1915,
"text": "Python list-programs"
},
{
"code": null,
"e": 1943,
"s": 1936,
"text": "Python"
},
{
"code": null,
"e": 1959,
"s": 1943,
"text": "Python Programs"
}
] |
Maximum array from two given arrays keeping order same | 22 Jun, 2021
Given two same-sized arrays A[] and B[] (both arrays contain distinct elements individually but may have some common elements), the task is to form a third (or result) array of the same size. The resulting array should have maximum n elements from both arrays. It should have chosen elements of A[] first, then chosen elements of B[] in the same order as they appear in original arrays. If there are common elements, then only one element should be present in res[] and priority should be given to A[].
Examples:
Input : A[] = [ 9 7 2 3 6 ]
B[] = [ 7 4 8 0 1 ]
Output : res[] = [9 7 6 4 8]
res[] has maximum n elements of both A[]
and B[] such that elements of A[] appear
first (in same order), then elements of B[].
Also 7 is common and priority is given to
A's 7.
Input : A[] = [ 6 7 5 3 ]
B[] = [ 5 6 2 9 ]
Output : res[] = [ 6 7 5 9 ]
1) Create copies of both arrays and sort the copies in decreasing order. 2) Use a hash to pick unique n maximum elements of both arrays, giving priority to A[]. 3) Initialize result array as empty. 4) Traverse through A[], copy those elements of A[] that are present in the hash. This is done to keep the order of elements the same. 5) Repeat step 4 for B[]. This time we only consider those elements that are not present in A[] (Do not appear twice in the hash).
Below is the implementation of the above idea.
C++
Java
Python3
C#
Javascript
// Make a set of maximum elements from two// arrays A[] and B[]#include <bits/stdc++.h>using namespace std; void maximizeTheFirstArray(int A[], int B[], int n){ // Create copies of A[] and B[] and sort // the copies in descending order. vector<int> temp1(A, A+n); vector<int> temp2(B, B+n); sort(temp1.begin(), temp1.end(), greater<int>()); sort(temp2.begin(), temp2.end(), greater<int>()); // Put maximum n distinct elements of // both sorted arrays in a map. unordered_map<int, int> m; int i = 0, j = 0; while (m.size() < n) { if (temp1[i] >= temp2[j]) { m[temp1[i]]++; i++; } else { m[temp2[j]]++; j++; } } // Copy elements of A[] to that // are present in hash m. vector<int> res; for (int i = 0; i < n; i++) if (m.find(A[i]) != m.end()) res.push_back(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (int i = 0; i < n; i++) if (m.find(B[i]) != m.end() && m[B[i]] == 1) res.push_back(B[i]); // print result for (int i = 0; i < n; i++) cout << res[i] << " ";} // driver programint main(){ int A[] = { 9, 7, 2, 3, 6 }; int B[] = { 7, 4, 8, 0, 1 }; int n = sizeof(A) / sizeof(A[0]); maximizeTheFirstArray(A, B, n); return 0;}
// Make a set of maximum elements from two// arrays A[] and B[]import java.io.*;import java.util.*;class GFG{ static void maximizeTheFirstArray(int[] A, int[] B,int n) { // Create copies of A[] and B[] and sort // the copies in descending order. ArrayList<Integer> temp1 = new ArrayList<Integer>(); ArrayList<Integer> temp2 = new ArrayList<Integer>(); for(int i : A) { temp1.add(i); } for(int i:B) { temp2.add(i); } Collections.sort(temp1, Collections.reverseOrder()); Collections.sort(temp2, Collections.reverseOrder()); // Put maximum n distinct elements of // both sorted arrays in a map. Map<Integer,Integer> m = new HashMap<>(); int i = 0, j = 0; while (m.size() < n) { if (temp1.get(i) >= temp2.get(j)) { if(m.containsKey(temp1.get(i))) { m.put(temp1.get(i), m.get(temp1.get(i)) + 1); } else { m.put(temp1.get(i), 1); } i++; } else { if(m.containsKey(temp2.get(j))) { m.put(temp2.get(j), m.get(temp2.get(j)) + 1); } else { m.put(temp2.get(j), 1); } j++; } } // Copy elements of A[] to that // are present in hash m. ArrayList<Integer> res = new ArrayList<Integer>(); for (i = 0; i < n; i++) if (m.containsKey(A[i])) res.add(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (i = 0; i < n; i++) if (m.containsKey(B[i]) && m.get(B[i]) == 1) res.add(B[i]); // print result for (i = 0; i < n; i++) System.out.print(res.get(i)+" "); } // Driver program public static void main (String[] args) { int A[] = { 9, 7, 2, 3, 6 }; int B[] = { 7, 4, 8, 0, 1 }; int n = A.length; maximizeTheFirstArray(A, B, n); }} // This code is contributed by rag2127
# Python3 program to implement the# above approach# Make a set of maximum elements# from two arrays A[] and B[]from collections import defaultdict def maximizeTheFirstArray(A, B, n): # Create copies of A[] and B[] # and sort the copies in # descending order. temp1 = A.copy() temp2 = B.copy() temp1.sort(reverse = True) temp2.sort(reverse = True) # Put maximum n distinct # elements of both sorted # arrays in a map. m = defaultdict(int) i = 0 j = 0; while (len(m) < n): if (temp1[i] >= temp2[j]): m[temp1[i]] += 1 i += 1 else: m[temp2[j]] += 1 j += 1 # Copy elements of A[] to that # are present in hash m. res = [] for i in range (n): if (A[i] in m): res.append(A[i]) # Copy elements of B[] to that # are present in hash m. This time # we also check if the element did # not appear twice. for i in range (n): if (B[i] in m and m[B[i]] == 1): res.append(B[i]) # Print result for i in range (n): print (res[i], end = " ") # Driver codeif __name__ == "__main__": A = [9, 7, 2, 3, 6] B = [7, 4, 8, 0, 1] n = len(A) maximizeTheFirstArray(A, B, n); # This code is contributed by Chitranayal
// Make a set of maximum elements from two// arrays A[] and B[]using System;using System.Collections.Generic; class GFG{ static void maximizeTheFirstArray(int[] A, int[] B, int n){ // Create copies of A[] and B[] and sort // the copies in descending order. List<int> temp1 = new List<int>(); List<int> temp2 = new List<int>(); foreach(int i in A) { temp1.Add(i); } foreach(int i in B) { temp2.Add(i); } temp1.Sort(); temp1.Reverse(); temp2.Sort(); temp2.Reverse(); // Put maximum n distinct elements of // both sorted arrays in a map. Dictionary<int, int> m = new Dictionary<int, int>(); int I = 0, j = 0; while (m.Count < n) { if (temp1[I] >= temp2[j]) { if (m.ContainsKey(temp1[I])) { m[temp1[I]]++; } else { m.Add(temp1[I], 1); } I++; } else { if (m.ContainsKey(temp2[j])) { m[temp2[j]]++; } else { m.Add(temp2[j], 1); } j++; } } // Copy elements of A[] to that // are present in hash m. List<int> res = new List<int>(); for(int i = 0; i < n; i++) if (m.ContainsKey(A[i])) res.Add(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for(int i = 0; i < n; i++) if (m.ContainsKey(B[i]) && m[B[i]] == 1) res.Add(B[i]); // print result for(int i = 0; i < n; i++) Console.Write(res[i] + " ");} // Driver Codestatic public void Main(){ int[] A = { 9, 7, 2, 3, 6 }; int[] B = { 7, 4, 8, 0, 1 }; int n = A.Length; maximizeTheFirstArray(A, B, n);}} // This code is contributed by avanitrachhadiya2155
<script>// Make a set of maximum elements from two// arrays A[] and B[]function maximizeTheFirstArray(A, B, n){ // Create copies of A[] and B[] and sort // the copies in descending order. let temp1 = new Array(); let temp2 = new Array(); for (let i of A) { temp1.push(i); } for (let i of B) { temp2.push(i); } temp1.sort((a, b) => a - b).reverse(); temp2.sort((a, b) => a - b).reverse(); // set maximum n distinct elements of // both sorted arrays in a map. let m = new Map(); let i = 0, j = 0; while (m.size < n) { if (temp1[i] >= temp2[j]) { if (m.has(temp1[i])) { m.set(temp1[i], m.get(temp1[i]) + 1); } else { m.set(temp1[i], 1); } i++; } else { if (m.has(temp2[j])) { m.set(temp2[j], m.get(temp2[j]) + 1); } else { m.set(temp2[j], 1); } j++; } } // Copy elements of A[] to that // are present in hash m. let res = new Array(); for (i = 0; i < n; i++) if (m.has(A[i])) res.push(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (i = 0; i < n; i++) if (m.has(B[i]) && m.get(B[i]) == 1) res.push(B[i]); // print result for (i = 0; i < n; i++) document.write(res[i] + " ");} // Driver programlet A = [9, 7, 2, 3, 6];let B = [7, 4, 8, 0, 1];let n = A.length;maximizeTheFirstArray(A, B, n); // This code is contributed by gfgking </script>
Output:
9 7 6 4 8
Time complexity: O(n Log n)
ukasp
rag2127
avanitrachhadiya2155
gfgking
cpp-unordered_map
cpp-vector
Arrays
Hash
Sorting
Arrays
Hash
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n22 Jun, 2021"
},
{
"code": null,
"e": 557,
"s": 54,
"text": "Given two same-sized arrays A[] and B[] (both arrays contain distinct elements individually but may have some common elements), the task is to form a third (or result) array of the same size. The resulting array should have maximum n elements from both arrays. It should have chosen elements of A[] first, then chosen elements of B[] in the same order as they appear in original arrays. If there are common elements, then only one element should be present in res[] and priority should be given to A[]."
},
{
"code": null,
"e": 569,
"s": 557,
"text": "Examples: "
},
{
"code": null,
"e": 920,
"s": 569,
"text": "Input : A[] = [ 9 7 2 3 6 ]\n B[] = [ 7 4 8 0 1 ]\nOutput : res[] = [9 7 6 4 8]\nres[] has maximum n elements of both A[] \nand B[] such that elements of A[] appear\nfirst (in same order), then elements of B[].\nAlso 7 is common and priority is given to\nA's 7.\n\nInput : A[] = [ 6 7 5 3 ]\n B[] = [ 5 6 2 9 ] \nOutput : res[] = [ 6 7 5 9 ]"
},
{
"code": null,
"e": 1384,
"s": 920,
"text": "1) Create copies of both arrays and sort the copies in decreasing order. 2) Use a hash to pick unique n maximum elements of both arrays, giving priority to A[]. 3) Initialize result array as empty. 4) Traverse through A[], copy those elements of A[] that are present in the hash. This is done to keep the order of elements the same. 5) Repeat step 4 for B[]. This time we only consider those elements that are not present in A[] (Do not appear twice in the hash)."
},
{
"code": null,
"e": 1432,
"s": 1384,
"text": "Below is the implementation of the above idea. "
},
{
"code": null,
"e": 1436,
"s": 1432,
"text": "C++"
},
{
"code": null,
"e": 1441,
"s": 1436,
"text": "Java"
},
{
"code": null,
"e": 1449,
"s": 1441,
"text": "Python3"
},
{
"code": null,
"e": 1452,
"s": 1449,
"text": "C#"
},
{
"code": null,
"e": 1463,
"s": 1452,
"text": "Javascript"
},
{
"code": "// Make a set of maximum elements from two// arrays A[] and B[]#include <bits/stdc++.h>using namespace std; void maximizeTheFirstArray(int A[], int B[], int n){ // Create copies of A[] and B[] and sort // the copies in descending order. vector<int> temp1(A, A+n); vector<int> temp2(B, B+n); sort(temp1.begin(), temp1.end(), greater<int>()); sort(temp2.begin(), temp2.end(), greater<int>()); // Put maximum n distinct elements of // both sorted arrays in a map. unordered_map<int, int> m; int i = 0, j = 0; while (m.size() < n) { if (temp1[i] >= temp2[j]) { m[temp1[i]]++; i++; } else { m[temp2[j]]++; j++; } } // Copy elements of A[] to that // are present in hash m. vector<int> res; for (int i = 0; i < n; i++) if (m.find(A[i]) != m.end()) res.push_back(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (int i = 0; i < n; i++) if (m.find(B[i]) != m.end() && m[B[i]] == 1) res.push_back(B[i]); // print result for (int i = 0; i < n; i++) cout << res[i] << \" \";} // driver programint main(){ int A[] = { 9, 7, 2, 3, 6 }; int B[] = { 7, 4, 8, 0, 1 }; int n = sizeof(A) / sizeof(A[0]); maximizeTheFirstArray(A, B, n); return 0;}",
"e": 2947,
"s": 1463,
"text": null
},
{
"code": "// Make a set of maximum elements from two// arrays A[] and B[]import java.io.*;import java.util.*;class GFG{ static void maximizeTheFirstArray(int[] A, int[] B,int n) { // Create copies of A[] and B[] and sort // the copies in descending order. ArrayList<Integer> temp1 = new ArrayList<Integer>(); ArrayList<Integer> temp2 = new ArrayList<Integer>(); for(int i : A) { temp1.add(i); } for(int i:B) { temp2.add(i); } Collections.sort(temp1, Collections.reverseOrder()); Collections.sort(temp2, Collections.reverseOrder()); // Put maximum n distinct elements of // both sorted arrays in a map. Map<Integer,Integer> m = new HashMap<>(); int i = 0, j = 0; while (m.size() < n) { if (temp1.get(i) >= temp2.get(j)) { if(m.containsKey(temp1.get(i))) { m.put(temp1.get(i), m.get(temp1.get(i)) + 1); } else { m.put(temp1.get(i), 1); } i++; } else { if(m.containsKey(temp2.get(j))) { m.put(temp2.get(j), m.get(temp2.get(j)) + 1); } else { m.put(temp2.get(j), 1); } j++; } } // Copy elements of A[] to that // are present in hash m. ArrayList<Integer> res = new ArrayList<Integer>(); for (i = 0; i < n; i++) if (m.containsKey(A[i])) res.add(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (i = 0; i < n; i++) if (m.containsKey(B[i]) && m.get(B[i]) == 1) res.add(B[i]); // print result for (i = 0; i < n; i++) System.out.print(res.get(i)+\" \"); } // Driver program public static void main (String[] args) { int A[] = { 9, 7, 2, 3, 6 }; int B[] = { 7, 4, 8, 0, 1 }; int n = A.length; maximizeTheFirstArray(A, B, n); }} // This code is contributed by rag2127",
"e": 5330,
"s": 2947,
"text": null
},
{
"code": "# Python3 program to implement the# above approach# Make a set of maximum elements# from two arrays A[] and B[]from collections import defaultdict def maximizeTheFirstArray(A, B, n): # Create copies of A[] and B[] # and sort the copies in # descending order. temp1 = A.copy() temp2 = B.copy() temp1.sort(reverse = True) temp2.sort(reverse = True) # Put maximum n distinct # elements of both sorted # arrays in a map. m = defaultdict(int) i = 0 j = 0; while (len(m) < n): if (temp1[i] >= temp2[j]): m[temp1[i]] += 1 i += 1 else: m[temp2[j]] += 1 j += 1 # Copy elements of A[] to that # are present in hash m. res = [] for i in range (n): if (A[i] in m): res.append(A[i]) # Copy elements of B[] to that # are present in hash m. This time # we also check if the element did # not appear twice. for i in range (n): if (B[i] in m and m[B[i]] == 1): res.append(B[i]) # Print result for i in range (n): print (res[i], end = \" \") # Driver codeif __name__ == \"__main__\": A = [9, 7, 2, 3, 6] B = [7, 4, 8, 0, 1] n = len(A) maximizeTheFirstArray(A, B, n); # This code is contributed by Chitranayal",
"e": 6643,
"s": 5330,
"text": null
},
{
"code": "// Make a set of maximum elements from two// arrays A[] and B[]using System;using System.Collections.Generic; class GFG{ static void maximizeTheFirstArray(int[] A, int[] B, int n){ // Create copies of A[] and B[] and sort // the copies in descending order. List<int> temp1 = new List<int>(); List<int> temp2 = new List<int>(); foreach(int i in A) { temp1.Add(i); } foreach(int i in B) { temp2.Add(i); } temp1.Sort(); temp1.Reverse(); temp2.Sort(); temp2.Reverse(); // Put maximum n distinct elements of // both sorted arrays in a map. Dictionary<int, int> m = new Dictionary<int, int>(); int I = 0, j = 0; while (m.Count < n) { if (temp1[I] >= temp2[j]) { if (m.ContainsKey(temp1[I])) { m[temp1[I]]++; } else { m.Add(temp1[I], 1); } I++; } else { if (m.ContainsKey(temp2[j])) { m[temp2[j]]++; } else { m.Add(temp2[j], 1); } j++; } } // Copy elements of A[] to that // are present in hash m. List<int> res = new List<int>(); for(int i = 0; i < n; i++) if (m.ContainsKey(A[i])) res.Add(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for(int i = 0; i < n; i++) if (m.ContainsKey(B[i]) && m[B[i]] == 1) res.Add(B[i]); // print result for(int i = 0; i < n; i++) Console.Write(res[i] + \" \");} // Driver Codestatic public void Main(){ int[] A = { 9, 7, 2, 3, 6 }; int[] B = { 7, 4, 8, 0, 1 }; int n = A.Length; maximizeTheFirstArray(A, B, n);}} // This code is contributed by avanitrachhadiya2155",
"e": 8664,
"s": 6643,
"text": null
},
{
"code": "<script>// Make a set of maximum elements from two// arrays A[] and B[]function maximizeTheFirstArray(A, B, n){ // Create copies of A[] and B[] and sort // the copies in descending order. let temp1 = new Array(); let temp2 = new Array(); for (let i of A) { temp1.push(i); } for (let i of B) { temp2.push(i); } temp1.sort((a, b) => a - b).reverse(); temp2.sort((a, b) => a - b).reverse(); // set maximum n distinct elements of // both sorted arrays in a map. let m = new Map(); let i = 0, j = 0; while (m.size < n) { if (temp1[i] >= temp2[j]) { if (m.has(temp1[i])) { m.set(temp1[i], m.get(temp1[i]) + 1); } else { m.set(temp1[i], 1); } i++; } else { if (m.has(temp2[j])) { m.set(temp2[j], m.get(temp2[j]) + 1); } else { m.set(temp2[j], 1); } j++; } } // Copy elements of A[] to that // are present in hash m. let res = new Array(); for (i = 0; i < n; i++) if (m.has(A[i])) res.push(A[i]); // Copy elements of B[] to that // are present in hash m. This time // we also check if the element did // not appear twice. for (i = 0; i < n; i++) if (m.has(B[i]) && m.get(B[i]) == 1) res.push(B[i]); // print result for (i = 0; i < n; i++) document.write(res[i] + \" \");} // Driver programlet A = [9, 7, 2, 3, 6];let B = [7, 4, 8, 0, 1];let n = A.length;maximizeTheFirstArray(A, B, n); // This code is contributed by gfgking </script>",
"e": 10337,
"s": 8664,
"text": null
},
{
"code": null,
"e": 10346,
"s": 10337,
"text": "Output: "
},
{
"code": null,
"e": 10358,
"s": 10346,
"text": " 9 7 6 4 8 "
},
{
"code": null,
"e": 10386,
"s": 10358,
"text": "Time complexity: O(n Log n)"
},
{
"code": null,
"e": 10392,
"s": 10386,
"text": "ukasp"
},
{
"code": null,
"e": 10400,
"s": 10392,
"text": "rag2127"
},
{
"code": null,
"e": 10421,
"s": 10400,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 10429,
"s": 10421,
"text": "gfgking"
},
{
"code": null,
"e": 10447,
"s": 10429,
"text": "cpp-unordered_map"
},
{
"code": null,
"e": 10458,
"s": 10447,
"text": "cpp-vector"
},
{
"code": null,
"e": 10465,
"s": 10458,
"text": "Arrays"
},
{
"code": null,
"e": 10470,
"s": 10465,
"text": "Hash"
},
{
"code": null,
"e": 10478,
"s": 10470,
"text": "Sorting"
},
{
"code": null,
"e": 10485,
"s": 10478,
"text": "Arrays"
},
{
"code": null,
"e": 10490,
"s": 10485,
"text": "Hash"
},
{
"code": null,
"e": 10498,
"s": 10490,
"text": "Sorting"
}
] |
How to auto like all the comments on a facebook post using JavaScript ? | 07 Aug, 2020
In this article, we are going to learn how to like all the comments on a Facebook post automatically. Many times we want to like all the comments of friends on our post or on any other’s post, so this script helps us to save our time and effort by automatically liking all the comments on the post.
Approach:
Make a variable comments that points to an array of all the comment on the post.Run a loop to iterate all the comments.Now we check if the comment is not already liked.Then click on the like button of that comment.
Make a variable comments that points to an array of all the comment on the post.
Run a loop to iterate all the comments.
Now we check if the comment is not already liked.
Then click on the like button of that comment.
Below are the steps:
Go to facebook page using m.facebook.com
Sign in and open any post.
Open developer mode in Chrome by pressing Ctrl+Shift+I
Navigate to the console.
Now, run the below script.var comments =document.getElementsByClassName("touchable _2b0a");for(var i=0;i<comments.length;i++){ if(comments[i].style.color != "rgb(32, 120, 244)") { comments[i].click(); }}
var comments =document.getElementsByClassName("touchable _2b0a");for(var i=0;i<comments.length;i++){ if(comments[i].style.color != "rgb(32, 120, 244)") { comments[i].click(); }}
Output:
Output
Note: Please ensure that there is a stable internet connection available so that the script runs smoothly. Also ensure to visit facebook with m.facebook.com not www.facebook.com because this script works on mobile version of facebook only.
This tutorial is for educational purpose only, please don’t use it for disturbing anyone or any unethical way.
JavaScript-Misc
GBlog
JavaScript
TechTips
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!
Geek Streak - 24 Days POTD Challenge
What is Hashing | A Complete Tutorial
How To Switch From A Service-Based To A Product-Based Company?
Roadmap to Learn JavaScript For Beginners
Difference between var, let and const keywords in JavaScript
Remove elements from a JavaScript Array
Differences between Functional Components and Class Components in React
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n07 Aug, 2020"
},
{
"code": null,
"e": 351,
"s": 52,
"text": "In this article, we are going to learn how to like all the comments on a Facebook post automatically. Many times we want to like all the comments of friends on our post or on any other’s post, so this script helps us to save our time and effort by automatically liking all the comments on the post."
},
{
"code": null,
"e": 361,
"s": 351,
"text": "Approach:"
},
{
"code": null,
"e": 576,
"s": 361,
"text": "Make a variable comments that points to an array of all the comment on the post.Run a loop to iterate all the comments.Now we check if the comment is not already liked.Then click on the like button of that comment."
},
{
"code": null,
"e": 657,
"s": 576,
"text": "Make a variable comments that points to an array of all the comment on the post."
},
{
"code": null,
"e": 697,
"s": 657,
"text": "Run a loop to iterate all the comments."
},
{
"code": null,
"e": 747,
"s": 697,
"text": "Now we check if the comment is not already liked."
},
{
"code": null,
"e": 794,
"s": 747,
"text": "Then click on the like button of that comment."
},
{
"code": null,
"e": 815,
"s": 794,
"text": "Below are the steps:"
},
{
"code": null,
"e": 856,
"s": 815,
"text": "Go to facebook page using m.facebook.com"
},
{
"code": null,
"e": 883,
"s": 856,
"text": "Sign in and open any post."
},
{
"code": null,
"e": 938,
"s": 883,
"text": "Open developer mode in Chrome by pressing Ctrl+Shift+I"
},
{
"code": null,
"e": 963,
"s": 938,
"text": "Navigate to the console."
},
{
"code": null,
"e": 1183,
"s": 963,
"text": "Now, run the below script.var comments =document.getElementsByClassName(\"touchable _2b0a\");for(var i=0;i<comments.length;i++){ if(comments[i].style.color != \"rgb(32, 120, 244)\") { comments[i].click(); }}"
},
{
"code": "var comments =document.getElementsByClassName(\"touchable _2b0a\");for(var i=0;i<comments.length;i++){ if(comments[i].style.color != \"rgb(32, 120, 244)\") { comments[i].click(); }}",
"e": 1377,
"s": 1183,
"text": null
},
{
"code": null,
"e": 1385,
"s": 1377,
"text": "Output:"
},
{
"code": null,
"e": 1392,
"s": 1385,
"text": "Output"
},
{
"code": null,
"e": 1632,
"s": 1392,
"text": "Note: Please ensure that there is a stable internet connection available so that the script runs smoothly. Also ensure to visit facebook with m.facebook.com not www.facebook.com because this script works on mobile version of facebook only."
},
{
"code": null,
"e": 1743,
"s": 1632,
"text": "This tutorial is for educational purpose only, please don’t use it for disturbing anyone or any unethical way."
},
{
"code": null,
"e": 1759,
"s": 1743,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 1765,
"s": 1759,
"text": "GBlog"
},
{
"code": null,
"e": 1776,
"s": 1765,
"text": "JavaScript"
},
{
"code": null,
"e": 1785,
"s": 1776,
"text": "TechTips"
},
{
"code": null,
"e": 1802,
"s": 1785,
"text": "Web Technologies"
},
{
"code": null,
"e": 1829,
"s": 1802,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 1927,
"s": 1829,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1952,
"s": 1927,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 2007,
"s": 1952,
"text": "GEEK-O-LYMPICS 2022 - May The Geeks Force Be With You!"
},
{
"code": null,
"e": 2044,
"s": 2007,
"text": "Geek Streak - 24 Days POTD Challenge"
},
{
"code": null,
"e": 2082,
"s": 2044,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 2145,
"s": 2082,
"text": "How To Switch From A Service-Based To A Product-Based Company?"
},
{
"code": null,
"e": 2187,
"s": 2145,
"text": "Roadmap to Learn JavaScript For Beginners"
},
{
"code": null,
"e": 2248,
"s": 2187,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 2288,
"s": 2248,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 2360,
"s": 2288,
"text": "Differences between Functional Components and Class Components in React"
}
] |
Java Program to Reverse a List | 21 Oct, 2021
Reversing a list means after reversing the list, the first element should be swapped with the last element, the second element should be swapped with the second last element, and so on till the middle element and the resultant list is the reversed list.
Example:
Input:
"PLATFORM", "LEARNING", "BEST", "THE", "IS", "GFG"
Output:
Reverse order of given List :-
[GFG, IS, THE, BEST, LEARNING, PLATFORM]
We can mainly reverse the list by three ways:
RecursivelyUsing Collections.reverse()Using List.add() and List.remove methods
Recursively
Using Collections.reverse()
Using List.add() and List.remove methods
Method 1: Using Recursion
The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function.
Java
// Java Program to Reverse a List recursively import java.io.*;import java.util.*; class GFG { public static <T> void revlist(List<T> list) { // base condition when the list size is 0 if (list.size() <= 1 || list == null) return; T value = list.remove(0); // call the recursive function to reverse // the list after removing the first element revlist(list); // now after the rest of the list has been // reversed by the upper recursive call, // add the first value at the end list.add(value); } public static void main(String[] args) { System.out.println( "Reverse order of given List :- "); List<String> gfg = new ArrayList<>( Arrays.asList("PLATFORM", "LEARNING", "BEST", "THE", "IS", "GFG")); revlist(gfg); System.out.println(gfg); }}
Reverse order of given List :-
[GFG, IS, THE, BEST, LEARNING, PLATFORM]
Method 2: Using Collections.reverse()
java.util.Collections.reverse() method is a java.util.Collections class method. It reverses the order of elements in a list passed as an argument.
Java
// Java program to reverse the list// using Collections.reverse() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> number = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); System.out.println( "Reverse order of given List :- "); // the number list will be reversed using this method Collections.reverse(number); System.out.println(number); }}
Reverse order of given List :-
[8, 7, 6, 5, 4, 3, 2, 1]
Method 3: Using List.add() + List.remove()
The List.add() method of List interface is used to append the specified element in argument to the end of the list.
The List.remove() method of List interface is used to remove the specified element in argument from the list.
Java
// Java program to reverse the list using List.add()// and List.remove() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> number = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); System.out.println( "Reverse order of given List :- "); for (int k = 0, j = number.size() - 1; k < j; k++) { number.add(k, number.remove(j)); } System.out.println(number); }}
Reverse order of given List :-
[8, 7, 6, 5, 4, 3, 2, 1]
arorakashish0911
prachisoda1234
Java-Collections
java-list
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Java-Collections
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Oct, 2021"
},
{
"code": null,
"e": 308,
"s": 54,
"text": "Reversing a list means after reversing the list, the first element should be swapped with the last element, the second element should be swapped with the second last element, and so on till the middle element and the resultant list is the reversed list."
},
{
"code": null,
"e": 317,
"s": 308,
"text": "Example:"
},
{
"code": null,
"e": 457,
"s": 317,
"text": "Input:\n\"PLATFORM\", \"LEARNING\", \"BEST\", \"THE\", \"IS\", \"GFG\"\nOutput:\nReverse order of given List :- \n[GFG, IS, THE, BEST, LEARNING, PLATFORM]"
},
{
"code": null,
"e": 503,
"s": 457,
"text": "We can mainly reverse the list by three ways:"
},
{
"code": null,
"e": 582,
"s": 503,
"text": "RecursivelyUsing Collections.reverse()Using List.add() and List.remove methods"
},
{
"code": null,
"e": 594,
"s": 582,
"text": "Recursively"
},
{
"code": null,
"e": 622,
"s": 594,
"text": "Using Collections.reverse()"
},
{
"code": null,
"e": 663,
"s": 622,
"text": "Using List.add() and List.remove methods"
},
{
"code": null,
"e": 689,
"s": 663,
"text": "Method 1: Using Recursion"
},
{
"code": null,
"e": 842,
"s": 689,
"text": "The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. "
},
{
"code": null,
"e": 847,
"s": 842,
"text": "Java"
},
{
"code": "// Java Program to Reverse a List recursively import java.io.*;import java.util.*; class GFG { public static <T> void revlist(List<T> list) { // base condition when the list size is 0 if (list.size() <= 1 || list == null) return; T value = list.remove(0); // call the recursive function to reverse // the list after removing the first element revlist(list); // now after the rest of the list has been // reversed by the upper recursive call, // add the first value at the end list.add(value); } public static void main(String[] args) { System.out.println( \"Reverse order of given List :- \"); List<String> gfg = new ArrayList<>( Arrays.asList(\"PLATFORM\", \"LEARNING\", \"BEST\", \"THE\", \"IS\", \"GFG\")); revlist(gfg); System.out.println(gfg); }}",
"e": 1754,
"s": 847,
"text": null
},
{
"code": null,
"e": 1827,
"s": 1754,
"text": "Reverse order of given List :- \n[GFG, IS, THE, BEST, LEARNING, PLATFORM]"
},
{
"code": null,
"e": 1865,
"s": 1827,
"text": "Method 2: Using Collections.reverse()"
},
{
"code": null,
"e": 2012,
"s": 1865,
"text": "java.util.Collections.reverse() method is a java.util.Collections class method. It reverses the order of elements in a list passed as an argument."
},
{
"code": null,
"e": 2017,
"s": 2012,
"text": "Java"
},
{
"code": "// Java program to reverse the list// using Collections.reverse() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> number = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); System.out.println( \"Reverse order of given List :- \"); // the number list will be reversed using this method Collections.reverse(number); System.out.println(number); }}",
"e": 2511,
"s": 2017,
"text": null
},
{
"code": null,
"e": 2568,
"s": 2511,
"text": "Reverse order of given List :- \n[8, 7, 6, 5, 4, 3, 2, 1]"
},
{
"code": null,
"e": 2611,
"s": 2568,
"text": "Method 3: Using List.add() + List.remove()"
},
{
"code": null,
"e": 2727,
"s": 2611,
"text": "The List.add() method of List interface is used to append the specified element in argument to the end of the list."
},
{
"code": null,
"e": 2837,
"s": 2727,
"text": "The List.remove() method of List interface is used to remove the specified element in argument from the list."
},
{
"code": null,
"e": 2842,
"s": 2837,
"text": "Java"
},
{
"code": "// Java program to reverse the list using List.add()// and List.remove() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { List<Integer> number = new ArrayList<>( Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8)); System.out.println( \"Reverse order of given List :- \"); for (int k = 0, j = number.size() - 1; k < j; k++) { number.add(k, number.remove(j)); } System.out.println(number); }}",
"e": 3361,
"s": 2842,
"text": null
},
{
"code": null,
"e": 3418,
"s": 3361,
"text": "Reverse order of given List :- \n[8, 7, 6, 5, 4, 3, 2, 1]"
},
{
"code": null,
"e": 3435,
"s": 3418,
"text": "arorakashish0911"
},
{
"code": null,
"e": 3450,
"s": 3435,
"text": "prachisoda1234"
},
{
"code": null,
"e": 3467,
"s": 3450,
"text": "Java-Collections"
},
{
"code": null,
"e": 3477,
"s": 3467,
"text": "java-list"
},
{
"code": null,
"e": 3484,
"s": 3477,
"text": "Picked"
},
{
"code": null,
"e": 3508,
"s": 3484,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 3513,
"s": 3508,
"text": "Java"
},
{
"code": null,
"e": 3527,
"s": 3513,
"text": "Java Programs"
},
{
"code": null,
"e": 3546,
"s": 3527,
"text": "Technical Scripter"
},
{
"code": null,
"e": 3551,
"s": 3546,
"text": "Java"
},
{
"code": null,
"e": 3568,
"s": 3551,
"text": "Java-Collections"
}
] |
PyQt5 - Auto Adjusting Progress Bar size - GeeksforGeeks | 22 Apr, 2020
In this article we will see how to adjust the size of progress bar. Adjusting size means setting the size of progress bar as much as it is needed, nor too big nor to small, just the size which can comprise all the text in it. In order to do this we will use adjustSize method.
Note : Adjusting size will set the minimum required size. It doesn’t depend on the text added using setFormat method.
Syntax : bar.adjustSize()
Argument : It takes no argument.
Action performed : It will adjust the size according to the need.
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 100, 20, 50) # setting the value bar.setValue(100) # setting alignment to center bar.setAlignment(Qt.AlignCenter) # adjusting the size of the progress bar bar.adjustSize() App = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Python | Pandas dataframe.groupby()
Defaultdict in Python
Python | Get unique values from a list
Python Classes and Objects
Python | os.path.join() method
Create a directory in Python | [
{
"code": null,
"e": 23901,
"s": 23873,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 24178,
"s": 23901,
"text": "In this article we will see how to adjust the size of progress bar. Adjusting size means setting the size of progress bar as much as it is needed, nor too big nor to small, just the size which can comprise all the text in it. In order to do this we will use adjustSize method."
},
{
"code": null,
"e": 24296,
"s": 24178,
"text": "Note : Adjusting size will set the minimum required size. It doesn’t depend on the text added using setFormat method."
},
{
"code": null,
"e": 24322,
"s": 24296,
"text": "Syntax : bar.adjustSize()"
},
{
"code": null,
"e": 24355,
"s": 24322,
"text": "Argument : It takes no argument."
},
{
"code": null,
"e": 24421,
"s": 24355,
"text": "Action performed : It will adjust the size according to the need."
},
{
"code": null,
"e": 24450,
"s": 24421,
"text": "Below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating progress bar bar = QProgressBar(self) # setting geometry to progress bar bar.setGeometry(200, 100, 20, 50) # setting the value bar.setValue(100) # setting alignment to center bar.setAlignment(Qt.AlignCenter) # adjusting the size of the progress bar bar.adjustSize() App = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 25456,
"s": 24450,
"text": null
},
{
"code": null,
"e": 25465,
"s": 25456,
"text": "Output :"
},
{
"code": null,
"e": 25476,
"s": 25465,
"text": "Python-gui"
},
{
"code": null,
"e": 25488,
"s": 25476,
"text": "Python-PyQt"
},
{
"code": null,
"e": 25495,
"s": 25488,
"text": "Python"
},
{
"code": null,
"e": 25593,
"s": 25495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25602,
"s": 25593,
"text": "Comments"
},
{
"code": null,
"e": 25615,
"s": 25602,
"text": "Old Comments"
},
{
"code": null,
"e": 25647,
"s": 25615,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 25703,
"s": 25647,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 25745,
"s": 25703,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 25787,
"s": 25745,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 25823,
"s": 25787,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 25845,
"s": 25823,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 25884,
"s": 25845,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 25911,
"s": 25884,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 25942,
"s": 25911,
"text": "Python | os.path.join() method"
}
] |
How do you throw an Exception without breaking a for loop in java? | Whenever an exception occurred in a loop the control gets out of the loop, by handling the exception the statements after the catch block in the method will get executed. But, the loop breaks.
Live Demo
public class ExceptionInLoop{
public static void sampleMethod(){
String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
try {
for(int i=0; i<=10; i++) {
System.out.println(str[i]);
System.out.println(i);
}
}catch (ArrayIndexOutOfBoundsException ex){
System.out.println("Exception occurred");
}
System.out.println("hello");
}
public static void main(String args[]) {
sampleMethod();
}
}
Mango
0
Apple
1
Banana
2
Grapes
3
Oranges
4
Exception occurred
Hello
One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception.
If you have try catch within the loop it gets executed completely inspite of exceptions.
Live Demo
public class ExceptionInLoop{
public static void print(String str) {
System.out.println(str);
}
public static void sampleMethod()throws ArrayIndexOutOfBoundsException {
String str[] = {"Mango", "Apple", "Banana", "Grapes", "Oranges"};
for(int i=0; i<=10; i++) {
try {
print(str[i]);
System.out.println(i);
} catch(Exception e){
System.out.println(i);
}
}
}
public static void main(String args[]) {
try{
sampleMethod();
}catch(ArrayIndexOutOfBoundsException e) {
System.out.println("");
}
}
}
Mango
0
Apple
1
Banana
2
Grapes
3
Oranges
4
5
6
7
8
9
10 | [
{
"code": null,
"e": 1255,
"s": 1062,
"text": "Whenever an exception occurred in a loop the control gets out of the loop, by handling the exception the statements after the catch block in the method will get executed. But, the loop breaks."
},
{
"code": null,
"e": 1266,
"s": 1255,
"text": " Live Demo"
},
{
"code": null,
"e": 1783,
"s": 1266,
"text": "public class ExceptionInLoop{\n public static void sampleMethod(){\n String str[] = {\"Mango\", \"Apple\", \"Banana\", \"Grapes\", \"Oranges\"};\n try {\n for(int i=0; i<=10; i++) {\n System.out.println(str[i]);\n System.out.println(i);\n }\n }catch (ArrayIndexOutOfBoundsException ex){\n System.out.println(\"Exception occurred\");\n }\n System.out.println(\"hello\");\n }\n public static void main(String args[]) {\n sampleMethod();\n }\n}"
},
{
"code": null,
"e": 1852,
"s": 1783,
"text": "Mango\n0\nApple\n1\nBanana\n2\nGrapes\n3\nOranges\n4\nException occurred\nHello"
},
{
"code": null,
"e": 1989,
"s": 1852,
"text": "One way to execute the loop without breaking is to move the code that causes the exception to another method that handles the exception."
},
{
"code": null,
"e": 2078,
"s": 1989,
"text": "If you have try catch within the loop it gets executed completely inspite of exceptions."
},
{
"code": null,
"e": 2089,
"s": 2078,
"text": " Live Demo"
},
{
"code": null,
"e": 2737,
"s": 2089,
"text": "public class ExceptionInLoop{\n public static void print(String str) {\n System.out.println(str);\n }\n public static void sampleMethod()throws ArrayIndexOutOfBoundsException {\n String str[] = {\"Mango\", \"Apple\", \"Banana\", \"Grapes\", \"Oranges\"};\n for(int i=0; i<=10; i++) {\n try {\n print(str[i]);\n System.out.println(i);\n } catch(Exception e){\n System.out.println(i);\n }\n }\n }\n public static void main(String args[]) {\n try{\n sampleMethod();\n }catch(ArrayIndexOutOfBoundsException e) {\n System.out.println(\"\");\n }\n }\n}"
},
{
"code": null,
"e": 2794,
"s": 2737,
"text": "Mango\n0\nApple\n1\nBanana\n2\nGrapes\n3\nOranges\n4\n5\n6\n7\n8\n9\n10"
}
] |
Animate transform-origin property with CSS Animation | To implement animation on the transform-origin property with CSS, you can try to run the following code
Live Demo
<!DOCTYPE html>
<html>
<head>
<style>
#demo1 {
position: relative;
height: 300px;
width: 400px;
border: 2px solid black;
margin: 100px;
padding: 5px;
}
#demo2 {
padding: 30px;
position: absolute;
border: 1px solid black;
background-color: orange;
transform: rotate(45deg);
transform-origin: 30% 10%;
animation: mymove 3s infinite;
}
@keyframes mymove {
30% {
transform-origin: 0 0 0;
}
}
</style>
</head>
<body>
<h1>CSS transform-origin property</h1>
<div id = "demo1">
<div id="demo2">Demo</div>
</div>
</body>
</html> | [
{
"code": null,
"e": 1166,
"s": 1062,
"text": "To implement animation on the transform-origin property with CSS, you can try to run the following code"
},
{
"code": null,
"e": 1176,
"s": 1166,
"text": "Live Demo"
},
{
"code": null,
"e": 1996,
"s": 1176,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <style>\n #demo1 {\n position: relative;\n height: 300px;\n width: 400px;\n border: 2px solid black;\n margin: 100px;\n padding: 5px;\n }\n #demo2 {\n padding: 30px;\n position: absolute;\n border: 1px solid black;\n background-color: orange;\n transform: rotate(45deg);\n transform-origin: 30% 10%;\n animation: mymove 3s infinite;\n }\n @keyframes mymove {\n 30% {\n transform-origin: 0 0 0;\n }\n }\n </style>\n </head>\n <body>\n <h1>CSS transform-origin property</h1>\n <div id = \"demo1\">\n <div id=\"demo2\">Demo</div>\n </div>\n </body>\n</html>"
}
] |
How to create Definition Lists in HTML5? | Use the <dl> tag to add definition lists. The HTML <dl> tag is used for declaring a definition list. This tag is used within <dd> tag. A definition list is similar to other lists but in a definition list, each list item contains two entries; a term and a description.
You can try to run the following code to create Definition Lists in HTML5 −
<!DOCTYPE html>
<html>
<head>
<title>HTML dl Tag</title>
</head>
<body>
<dl>
<dt>Definition List</dt>
<dd>A list of terms and their definitions/descriptions.</dd>
<dt>C++</dt>
<dd>C++ tutorial.</dd>
<dt>Java</dt>
<dd>Java tutorial.</dd>
</dl>
</body>
</html> | [
{
"code": null,
"e": 1330,
"s": 1062,
"text": "Use the <dl> tag to add definition lists. The HTML <dl> tag is used for declaring a definition list. This tag is used within <dd> tag. A definition list is similar to other lists but in a definition list, each list item contains two entries; a term and a description."
},
{
"code": null,
"e": 1406,
"s": 1330,
"text": "You can try to run the following code to create Definition Lists in HTML5 −"
},
{
"code": null,
"e": 1731,
"s": 1406,
"text": "<!DOCTYPE html>\n<html>\n <head>\n <title>HTML dl Tag</title>\n </head>\n <body>\n <dl>\n <dt>Definition List</dt>\n <dd>A list of terms and their definitions/descriptions.</dd>\n <dt>C++</dt>\n <dd>C++ tutorial.</dd>\n <dt>Java</dt>\n <dd>Java tutorial.</dd>\n </dl>\n </body>\n</html>"
}
] |
AI-Powered Code Completion in JupyterLab | by Robert Ritz | Towards Data Science | As a data scientist, you almost surely use a form of Jupyter Notebooks. Hopefully, you have moved over to the goodness of JupyterLab with its integrated sidebar, tabs, and more. When it first launched in 2018, JupyterLab was great but felt it was missing some things.
Now you can add a visual debugger and there is even a library called nbdev that allows you to author full Python packages and push them to PyPI. JupyterLab has become a complete IDE for data scientists. But one thing was still sub-optimal until recently, code completions.
Trying to use the built-in code completion in JupyterLab gets you something like this:
Kite, a company that makes code completion software for a variety of languages and IDE’s, recently launched Kite for JupyterLab. Now you can get something like this:
Simplify your life with logical autocompletion. It runs locally and doesn’t send your code to the cloud.
It isn’t perfect, and it certainly doesn’t read your mind. It IS a good upgrade for the default code completion though.
Kite for JupyterLab brings you one step closer to a full notebook based IDE.
Installing Kite for JupyterLab is fairly painless.
First, install Kite for Desktop. You can get the installer here. Versions are available for Windows, Mac, and Linux.Make sure your JupyterLab is version 2.2 or later. This is a pretty recent version of JupyterLab so you may need to upgrade with your install with conda or pip.Install the JupyterLab extension. You will need NodeJS installed just like for your other extensions.
First, install Kite for Desktop. You can get the installer here. Versions are available for Windows, Mac, and Linux.
Make sure your JupyterLab is version 2.2 or later. This is a pretty recent version of JupyterLab so you may need to upgrade with your install with conda or pip.
Install the JupyterLab extension. You will need NodeJS installed just like for your other extensions.
pip install jupyter-kitejupyter labextension install "@kiteco/jupyterlab-kite"
I’ve only used Kite for JupyterLab for about a week now. It’s not groundbreaking, but it certainly makes my coding experience that much better. Completions are noticeably faster than the native completions as well.
I’m using the free version of Kite, and the completions take place 100% locally. The best suggestion for me isn’t always at the top, but it’s usually in the top 5. As data scientists, we use LOTS of methods, and this is a nice way to get reminders when needed.
Happy coding!
Thanks for reading. You can find more about me here. Consider subscribing to get notifications when I publish. If you would like to directly support my articles you can use my referral link to sign up to become a Medium member. | [
{
"code": null,
"e": 440,
"s": 172,
"text": "As a data scientist, you almost surely use a form of Jupyter Notebooks. Hopefully, you have moved over to the goodness of JupyterLab with its integrated sidebar, tabs, and more. When it first launched in 2018, JupyterLab was great but felt it was missing some things."
},
{
"code": null,
"e": 713,
"s": 440,
"text": "Now you can add a visual debugger and there is even a library called nbdev that allows you to author full Python packages and push them to PyPI. JupyterLab has become a complete IDE for data scientists. But one thing was still sub-optimal until recently, code completions."
},
{
"code": null,
"e": 800,
"s": 713,
"text": "Trying to use the built-in code completion in JupyterLab gets you something like this:"
},
{
"code": null,
"e": 966,
"s": 800,
"text": "Kite, a company that makes code completion software for a variety of languages and IDE’s, recently launched Kite for JupyterLab. Now you can get something like this:"
},
{
"code": null,
"e": 1071,
"s": 966,
"text": "Simplify your life with logical autocompletion. It runs locally and doesn’t send your code to the cloud."
},
{
"code": null,
"e": 1191,
"s": 1071,
"text": "It isn’t perfect, and it certainly doesn’t read your mind. It IS a good upgrade for the default code completion though."
},
{
"code": null,
"e": 1268,
"s": 1191,
"text": "Kite for JupyterLab brings you one step closer to a full notebook based IDE."
},
{
"code": null,
"e": 1319,
"s": 1268,
"text": "Installing Kite for JupyterLab is fairly painless."
},
{
"code": null,
"e": 1697,
"s": 1319,
"text": "First, install Kite for Desktop. You can get the installer here. Versions are available for Windows, Mac, and Linux.Make sure your JupyterLab is version 2.2 or later. This is a pretty recent version of JupyterLab so you may need to upgrade with your install with conda or pip.Install the JupyterLab extension. You will need NodeJS installed just like for your other extensions."
},
{
"code": null,
"e": 1814,
"s": 1697,
"text": "First, install Kite for Desktop. You can get the installer here. Versions are available for Windows, Mac, and Linux."
},
{
"code": null,
"e": 1975,
"s": 1814,
"text": "Make sure your JupyterLab is version 2.2 or later. This is a pretty recent version of JupyterLab so you may need to upgrade with your install with conda or pip."
},
{
"code": null,
"e": 2077,
"s": 1975,
"text": "Install the JupyterLab extension. You will need NodeJS installed just like for your other extensions."
},
{
"code": null,
"e": 2156,
"s": 2077,
"text": "pip install jupyter-kitejupyter labextension install \"@kiteco/jupyterlab-kite\""
},
{
"code": null,
"e": 2371,
"s": 2156,
"text": "I’ve only used Kite for JupyterLab for about a week now. It’s not groundbreaking, but it certainly makes my coding experience that much better. Completions are noticeably faster than the native completions as well."
},
{
"code": null,
"e": 2632,
"s": 2371,
"text": "I’m using the free version of Kite, and the completions take place 100% locally. The best suggestion for me isn’t always at the top, but it’s usually in the top 5. As data scientists, we use LOTS of methods, and this is a nice way to get reminders when needed."
},
{
"code": null,
"e": 2646,
"s": 2632,
"text": "Happy coding!"
}
] |
Convert Dashes to CamelCase in PHP | Following is the code to convert dashes to CamelCase in PHP −
Sample input − this-is-a-test-string
Sample output − thisIsATestString
Note − There is no need to use regex or callbacks. It can be achieved using ucwords.
function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
$str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));
if (!$capitalizeFirstCharacter) {
$str[0] = strtolower($str[0]);
}
return $str;
}
echo dashToCamelCase('this-is-a-string');
For PHP version>=5.3, the below code can be used −
function dashToCamelCase($string, $capitalizeFirstCharacter = false) {
$str = str_replace('-', '', ucwords($string, '-'));
if (!$capitalizeFirstCharacter) {
$str = lcfirst($str);
}
return $str;
echo dashToCamelCase('this-is-a-test-string');
The 'lcfirst' function needs to be used instead of 'strtolower'. | [
{
"code": null,
"e": 1124,
"s": 1062,
"text": "Following is the code to convert dashes to CamelCase in PHP −"
},
{
"code": null,
"e": 1161,
"s": 1124,
"text": "Sample input − this-is-a-test-string"
},
{
"code": null,
"e": 1195,
"s": 1161,
"text": "Sample output − thisIsATestString"
},
{
"code": null,
"e": 1280,
"s": 1195,
"text": "Note − There is no need to use regex or callbacks. It can be achieved using ucwords."
},
{
"code": null,
"e": 1563,
"s": 1280,
"text": "function dashToCamelCase($string, $capitalizeFirstCharacter = false) {\n $str = str_replace(' ', '', ucwords(str_replace('-', ' ', $string)));\n if (!$capitalizeFirstCharacter) {\n $str[0] = strtolower($str[0]);\n }\n return $str;\n}\necho dashToCamelCase('this-is-a-string');"
},
{
"code": null,
"e": 1614,
"s": 1563,
"text": "For PHP version>=5.3, the below code can be used −"
},
{
"code": null,
"e": 1873,
"s": 1614,
"text": "function dashToCamelCase($string, $capitalizeFirstCharacter = false) {\n $str = str_replace('-', '', ucwords($string, '-'));\n if (!$capitalizeFirstCharacter) {\n $str = lcfirst($str);\n }\n return $str;\necho dashToCamelCase('this-is-a-test-string');"
},
{
"code": null,
"e": 1938,
"s": 1873,
"text": "The 'lcfirst' function needs to be used instead of 'strtolower'."
}
] |
Specify a path for a file or a directory in Java | The path for a file can be obtained using the method java.io.File.getPath(). This method returns the abstract pathname in the form of a pathname string and it requires no parameters.
A program that demonstrates this is given as follows −
Live Demo
import java.io.File;
public class Demo {
public static void main(String[] args) {
File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
System.out.println("Path = " + file.getPath());
}
}
The output of the above program is as follows −
Path = C:/jdk11.0.2/demo1.java
Now let us understand the above program.
The path name of the file is printed using the method getPath(). A code snippet that demonstrates this is given as follows −
File file = new File("C:" + File.separator + "jdk11.0.2" + File.separator, "demo1.java");
System.out.println("Path = " + file.getPath()); | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "The path for a file can be obtained using the method java.io.File.getPath(). This method returns the abstract pathname in the form of a pathname string and it requires no parameters."
},
{
"code": null,
"e": 1300,
"s": 1245,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1311,
"s": 1300,
"text": " Live Demo"
},
{
"code": null,
"e": 1553,
"s": 1311,
"text": "import java.io.File;\npublic class Demo {\n public static void main(String[] args) {\n File file = new File(\"C:\" + File.separator + \"jdk11.0.2\" + File.separator, \"demo1.java\");\n System.out.println(\"Path = \" + file.getPath());\n }\n}"
},
{
"code": null,
"e": 1601,
"s": 1553,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 1632,
"s": 1601,
"text": "Path = C:/jdk11.0.2/demo1.java"
},
{
"code": null,
"e": 1673,
"s": 1632,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1798,
"s": 1673,
"text": "The path name of the file is printed using the method getPath(). A code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1936,
"s": 1798,
"text": "File file = new File(\"C:\" + File.separator + \"jdk11.0.2\" + File.separator, \"demo1.java\");\nSystem.out.println(\"Path = \" + file.getPath());"
}
] |
How to delete registry key value (property) using PowerShell? | To delete the registry key value using PowerShell, we can use the Remove-ItemProperty command. Suppose we have the registry NodeSoftware and its Property is AppSecurity. We need to delete its key using the Remove-ItemProperty command.
PS C:\> Get-Item HKLM:\SOFTWARE\NodeSoftware
Hive: HKEY_LOCAL_MACHINE\SOFTWARE
Name Property
---- --------
NodeSoftware AppSecurity : 1
To delete the registry key,
PS C:\>Remove-ItemProperty HKLM:\SOFTWARE\NodeSoftware\ -Name AppSecurity -Force -Verbose
VERBOSE: Performing the operation "Remove Property" on target "Item: HKEY_LOCAL_MACHINE\SOFTWARE\NodeSoftware\ Property: AppSecurity".
You can also delete property by setting the location. For example,
PS C:\> Set-Location HKLM:\SOFTWARE\NodeSoftware
PS HKLM:\SOFTWARE\NodeSoftware> Remove-ItemProperty -Path . -Name AppSecurity -Force -Verbose
To remove Item property using Pipeline,
Get-Item HKLM:\SOFTWARE\NodeSoftware | Remove-ItemProperty -Name AppSecurity -Force -Verbose | [
{
"code": null,
"e": 1297,
"s": 1062,
"text": "To delete the registry key value using PowerShell, we can use the Remove-ItemProperty command. Suppose we have the registry NodeSoftware and its Property is AppSecurity. We need to delete its key using the Remove-ItemProperty command."
},
{
"code": null,
"e": 1442,
"s": 1297,
"text": "PS C:\\> Get-Item HKLM:\\SOFTWARE\\NodeSoftware\nHive: HKEY_LOCAL_MACHINE\\SOFTWARE\nName Property\n---- --------\nNodeSoftware AppSecurity : 1"
},
{
"code": null,
"e": 1470,
"s": 1442,
"text": "To delete the registry key,"
},
{
"code": null,
"e": 1695,
"s": 1470,
"text": "PS C:\\>Remove-ItemProperty HKLM:\\SOFTWARE\\NodeSoftware\\ -Name AppSecurity -Force -Verbose\nVERBOSE: Performing the operation \"Remove Property\" on target \"Item: HKEY_LOCAL_MACHINE\\SOFTWARE\\NodeSoftware\\ Property: AppSecurity\"."
},
{
"code": null,
"e": 1762,
"s": 1695,
"text": "You can also delete property by setting the location. For example,"
},
{
"code": null,
"e": 1905,
"s": 1762,
"text": "PS C:\\> Set-Location HKLM:\\SOFTWARE\\NodeSoftware\nPS HKLM:\\SOFTWARE\\NodeSoftware> Remove-ItemProperty -Path . -Name AppSecurity -Force -Verbose"
},
{
"code": null,
"e": 1945,
"s": 1905,
"text": "To remove Item property using Pipeline,"
},
{
"code": null,
"e": 2038,
"s": 1945,
"text": "Get-Item HKLM:\\SOFTWARE\\NodeSoftware | Remove-ItemProperty -Name AppSecurity -Force -Verbose"
}
] |
INDEX-MATCH — An upgrade on VLOOKUP functions | by Anmol Bansal | Towards Data Science | In a previous article, we discussed about how and when to use VLOOKUP functions and what are the issues that we might face while using them. This article, on the other hand, will take you to a journey to understand an upgraded version of VLOOKUP. This upgrade is a combination of two functions in spreadsheets — INDEX and MATCH. Let us try and understand the working of INDEX-MATCH through the following example.
As always, let us take an example from our favorite data source — Kaggle. The following screenshot is a small subset of the Netflix data which consists of TV shows and movies available on Netflix as of 2019.
This dataset consists of different shows and movies along with their unique show_id, country we are considering, date when the show was added and the year when the entity was released. It also contains rating of the show/movie, duration and title of the content piece.
Consider now that we want to create a search method where the user can select a title and we display information to the user regarding that title. This search method would look something like this:
The user can input any title in the above example and we will try and find the type and rating of the title mentioned from the database. One of the simpler solutions to this is through VLOOKUP. We can easily find the rating of the title through it. Although, we would need to change the structure of the table to get the type of the title since VLOOKUP can only look to the right of the search value. Let’s see how can INDEX and MATCH formulas help us in solving this problem.
INDEX formula in spreadsheets look something like this:
INDEX helps us in finding the content of the cell. It takes 3 inputs.
Reference: The table in which we want to find the value.
Row: The number of rows from the beginning of the reference table where the value lies. This is an optional value. If no value is supplied, it will take the first row as the value.
Column: The number of columns from the beginning of the reference table where the value lies. This is an optional value. If no value is supplied, it will take the first column as the value.
To find the type of the title ‘Carrie Pilby’ in our table, we apply the following formula:
=INDEX(A1:H23,12,2)
We select the complete table as reference, we find that this movie title is in the 12th row and we know that the type of the title is stored in 2nd column of the reference table. This will give the result as ‘Movie’ which is absolutely correct!
But did you notice any problems with this? We actually had to count the row number and the column number to get 12 and 2 as the parameters in the formula. This isn’t easy, is it? Let’s find out if there is any other way in the world which can help us in easing this process.
MATCH formula in spreadsheets look something like this:
MATCH helps us in finding the relative position of the content in our table. It takes 3 inputs.
Search Key: The value that we want to find.
Range: The row/column in which the value is situated. Note that range can only take a row or a column, but not both.
Search Type: For all practical purpose, we set this value as zero. This indicates that we are finding the exact value. This is an optional term which takes the value as 1 by default.
MATCH essentially gives us the row number or the column number of where the search term lies. Isn’t this the missing part of the INDEX puzzle we encountered earlier? We needed an easier way to find the row and column number of the search item, rather than counting it manually. And MATCH gives you exactly that!
The above explanation now allows us to join the INDEX and MATCH formulas together and get the information we require with the minimum amount of hassle. Here is how a general INDEX-MATCH formula would look like:
=INDEX(reference, MATCH(search_key, row, 0), MATCH(search_key, column, 0))
In the above formula, we provide a reference table to the INDEX, which is basically the data table where all the information is. Next, the first MATCH formula provides the row index of the search term and the second MATCH provides the column index of the search term. Finally, the combination of these two will provide the row and column index to the INDEX formula and we’ll get our desired result! Let’s try it out in our Netflix example.
The above formula selects the entire table in first parameter of INDEX. Then it searches for the movie title mentioned in K1 through MATCH formula in the entire row of content titles, which is C1:C23. This will return whatever row number the title ‘Carrie Pilby’ is in. In the second MATCH, it searches for J2, which is the parameter that we want to find, in this case Type. This will return whatever column the column name ‘Type’ is in. And together it will provide the correct result i.e. Movie.
Similarly, here is the formula for how to match rating in the table for the given content title.
Often there will be comparisons on which formula to use to find the values of a given content. Although VLOOKUP is simpler to understand and provides an easy application, the INDEX-MATCH combination is a powerful match which provides the following advantages:
You can use INDEX-MATCH to find a value against multiple criteria. In the above examples, we found Type and Rating with content name criteria and parameter criteria. This wouldn’t have been easy to achieve in VLOOKUP.VLOOKUP finds a match on the left and returns any value to the right of the search item. On the other hand, INDEX-MATCH can look both ways. In the above example, type was on the left of title and rating on the right, still it managed to find both the results correctly.
You can use INDEX-MATCH to find a value against multiple criteria. In the above examples, we found Type and Rating with content name criteria and parameter criteria. This wouldn’t have been easy to achieve in VLOOKUP.
VLOOKUP finds a match on the left and returns any value to the right of the search item. On the other hand, INDEX-MATCH can look both ways. In the above example, type was on the left of title and rating on the right, still it managed to find both the results correctly.
Understanding INDEX-MATCH adds an extremely versatile tool in your spreadsheet armory. INDEX-MATCH along with the knowledge of Pivot Tables can really help you to improve your analytical skills. Let me know in comments if this was a helpful piece of content! | [
{
"code": null,
"e": 585,
"s": 172,
"text": "In a previous article, we discussed about how and when to use VLOOKUP functions and what are the issues that we might face while using them. This article, on the other hand, will take you to a journey to understand an upgraded version of VLOOKUP. This upgrade is a combination of two functions in spreadsheets — INDEX and MATCH. Let us try and understand the working of INDEX-MATCH through the following example."
},
{
"code": null,
"e": 793,
"s": 585,
"text": "As always, let us take an example from our favorite data source — Kaggle. The following screenshot is a small subset of the Netflix data which consists of TV shows and movies available on Netflix as of 2019."
},
{
"code": null,
"e": 1062,
"s": 793,
"text": "This dataset consists of different shows and movies along with their unique show_id, country we are considering, date when the show was added and the year when the entity was released. It also contains rating of the show/movie, duration and title of the content piece."
},
{
"code": null,
"e": 1260,
"s": 1062,
"text": "Consider now that we want to create a search method where the user can select a title and we display information to the user regarding that title. This search method would look something like this:"
},
{
"code": null,
"e": 1737,
"s": 1260,
"text": "The user can input any title in the above example and we will try and find the type and rating of the title mentioned from the database. One of the simpler solutions to this is through VLOOKUP. We can easily find the rating of the title through it. Although, we would need to change the structure of the table to get the type of the title since VLOOKUP can only look to the right of the search value. Let’s see how can INDEX and MATCH formulas help us in solving this problem."
},
{
"code": null,
"e": 1793,
"s": 1737,
"text": "INDEX formula in spreadsheets look something like this:"
},
{
"code": null,
"e": 1863,
"s": 1793,
"text": "INDEX helps us in finding the content of the cell. It takes 3 inputs."
},
{
"code": null,
"e": 1920,
"s": 1863,
"text": "Reference: The table in which we want to find the value."
},
{
"code": null,
"e": 2101,
"s": 1920,
"text": "Row: The number of rows from the beginning of the reference table where the value lies. This is an optional value. If no value is supplied, it will take the first row as the value."
},
{
"code": null,
"e": 2291,
"s": 2101,
"text": "Column: The number of columns from the beginning of the reference table where the value lies. This is an optional value. If no value is supplied, it will take the first column as the value."
},
{
"code": null,
"e": 2382,
"s": 2291,
"text": "To find the type of the title ‘Carrie Pilby’ in our table, we apply the following formula:"
},
{
"code": null,
"e": 2402,
"s": 2382,
"text": "=INDEX(A1:H23,12,2)"
},
{
"code": null,
"e": 2647,
"s": 2402,
"text": "We select the complete table as reference, we find that this movie title is in the 12th row and we know that the type of the title is stored in 2nd column of the reference table. This will give the result as ‘Movie’ which is absolutely correct!"
},
{
"code": null,
"e": 2922,
"s": 2647,
"text": "But did you notice any problems with this? We actually had to count the row number and the column number to get 12 and 2 as the parameters in the formula. This isn’t easy, is it? Let’s find out if there is any other way in the world which can help us in easing this process."
},
{
"code": null,
"e": 2978,
"s": 2922,
"text": "MATCH formula in spreadsheets look something like this:"
},
{
"code": null,
"e": 3074,
"s": 2978,
"text": "MATCH helps us in finding the relative position of the content in our table. It takes 3 inputs."
},
{
"code": null,
"e": 3118,
"s": 3074,
"text": "Search Key: The value that we want to find."
},
{
"code": null,
"e": 3235,
"s": 3118,
"text": "Range: The row/column in which the value is situated. Note that range can only take a row or a column, but not both."
},
{
"code": null,
"e": 3418,
"s": 3235,
"text": "Search Type: For all practical purpose, we set this value as zero. This indicates that we are finding the exact value. This is an optional term which takes the value as 1 by default."
},
{
"code": null,
"e": 3730,
"s": 3418,
"text": "MATCH essentially gives us the row number or the column number of where the search term lies. Isn’t this the missing part of the INDEX puzzle we encountered earlier? We needed an easier way to find the row and column number of the search item, rather than counting it manually. And MATCH gives you exactly that!"
},
{
"code": null,
"e": 3941,
"s": 3730,
"text": "The above explanation now allows us to join the INDEX and MATCH formulas together and get the information we require with the minimum amount of hassle. Here is how a general INDEX-MATCH formula would look like:"
},
{
"code": null,
"e": 4016,
"s": 3941,
"text": "=INDEX(reference, MATCH(search_key, row, 0), MATCH(search_key, column, 0))"
},
{
"code": null,
"e": 4456,
"s": 4016,
"text": "In the above formula, we provide a reference table to the INDEX, which is basically the data table where all the information is. Next, the first MATCH formula provides the row index of the search term and the second MATCH provides the column index of the search term. Finally, the combination of these two will provide the row and column index to the INDEX formula and we’ll get our desired result! Let’s try it out in our Netflix example."
},
{
"code": null,
"e": 4954,
"s": 4456,
"text": "The above formula selects the entire table in first parameter of INDEX. Then it searches for the movie title mentioned in K1 through MATCH formula in the entire row of content titles, which is C1:C23. This will return whatever row number the title ‘Carrie Pilby’ is in. In the second MATCH, it searches for J2, which is the parameter that we want to find, in this case Type. This will return whatever column the column name ‘Type’ is in. And together it will provide the correct result i.e. Movie."
},
{
"code": null,
"e": 5051,
"s": 4954,
"text": "Similarly, here is the formula for how to match rating in the table for the given content title."
},
{
"code": null,
"e": 5311,
"s": 5051,
"text": "Often there will be comparisons on which formula to use to find the values of a given content. Although VLOOKUP is simpler to understand and provides an easy application, the INDEX-MATCH combination is a powerful match which provides the following advantages:"
},
{
"code": null,
"e": 5798,
"s": 5311,
"text": "You can use INDEX-MATCH to find a value against multiple criteria. In the above examples, we found Type and Rating with content name criteria and parameter criteria. This wouldn’t have been easy to achieve in VLOOKUP.VLOOKUP finds a match on the left and returns any value to the right of the search item. On the other hand, INDEX-MATCH can look both ways. In the above example, type was on the left of title and rating on the right, still it managed to find both the results correctly."
},
{
"code": null,
"e": 6016,
"s": 5798,
"text": "You can use INDEX-MATCH to find a value against multiple criteria. In the above examples, we found Type and Rating with content name criteria and parameter criteria. This wouldn’t have been easy to achieve in VLOOKUP."
},
{
"code": null,
"e": 6286,
"s": 6016,
"text": "VLOOKUP finds a match on the left and returns any value to the right of the search item. On the other hand, INDEX-MATCH can look both ways. In the above example, type was on the left of title and rating on the right, still it managed to find both the results correctly."
}
] |
Check if count of divisors is even or odd in Python | Suppose we have a number n, we have to find its total number of divisors are even or odd.
So, if the input is like n = 75, then the output will be Even, as the divisors are [1, 3, 5, 15, 25, 75].
To solve this we shall follow one simple and efficient approach. We have observed that when a number is perfect square then only it has odd number of divisors. So if the number is not perfect square then it will have even divisors. So here we will only check whether the number is perfect square or not and based on this we can return "odd" or "even" as output.
To solve this, we will follow these steps −
if n < 1 is non-zero, thenreturn
return
sqrt := square root of n
if sqrt*sqrt is same as n, thenreturn 'Odd'
return 'Odd'
otherwise,return 'Even'
return 'Even'
Let us see the following implementation to get better understanding −
Live Demo
def solve(n):
if n < 1:
return
sqrt = n**0.5
if sqrt*sqrt == n:
return 'Odd'
else:
return 'Even'
n = 75
print(solve(n))
75
Even | [
{
"code": null,
"e": 1152,
"s": 1062,
"text": "Suppose we have a number n, we have to find its total number of divisors are even or odd."
},
{
"code": null,
"e": 1258,
"s": 1152,
"text": "So, if the input is like n = 75, then the output will be Even, as the divisors are [1, 3, 5, 15, 25, 75]."
},
{
"code": null,
"e": 1620,
"s": 1258,
"text": "To solve this we shall follow one simple and efficient approach. We have observed that when a number is perfect square then only it has odd number of divisors. So if the number is not perfect square then it will have even divisors. So here we will only check whether the number is perfect square or not and based on this we can return \"odd\" or \"even\" as output."
},
{
"code": null,
"e": 1664,
"s": 1620,
"text": "To solve this, we will follow these steps −"
},
{
"code": null,
"e": 1697,
"s": 1664,
"text": "if n < 1 is non-zero, thenreturn"
},
{
"code": null,
"e": 1704,
"s": 1697,
"text": "return"
},
{
"code": null,
"e": 1729,
"s": 1704,
"text": "sqrt := square root of n"
},
{
"code": null,
"e": 1773,
"s": 1729,
"text": "if sqrt*sqrt is same as n, thenreturn 'Odd'"
},
{
"code": null,
"e": 1786,
"s": 1773,
"text": "return 'Odd'"
},
{
"code": null,
"e": 1810,
"s": 1786,
"text": "otherwise,return 'Even'"
},
{
"code": null,
"e": 1824,
"s": 1810,
"text": "return 'Even'"
},
{
"code": null,
"e": 1894,
"s": 1824,
"text": "Let us see the following implementation to get better understanding −"
},
{
"code": null,
"e": 1905,
"s": 1894,
"text": " Live Demo"
},
{
"code": null,
"e": 2055,
"s": 1905,
"text": "def solve(n):\n if n < 1:\n return\n sqrt = n**0.5\n if sqrt*sqrt == n:\n return 'Odd'\n else:\n return 'Even'\nn = 75\nprint(solve(n))"
},
{
"code": null,
"e": 2058,
"s": 2055,
"text": "75"
},
{
"code": null,
"e": 2063,
"s": 2058,
"text": "Even"
}
] |
Android Project folder Structure - GeeksforGeeks | 02 Mar, 2022
Android Studio is the official IDE (Integrated Development Environment) developed by JetBrains community which is freely provided by Google for android app development.After completing the setup of Android Architecture we can create android application in the studio. We need to create new project for each sample application and we should understand the folder structure. It looks like this:
The android project contains different types of app modules, source code files, and resource files. We will explore all the folders and files in the android app.
Manifests FolderJava Folderres (Resources) FolderDrawable FolderLayout FolderMipmap FolderValues FolderGradle Scripts
Manifests Folder
Java Folder
res (Resources) FolderDrawable FolderLayout FolderMipmap FolderValues Folder
Drawable Folder
Layout Folder
Mipmap Folder
Values Folder
Gradle Scripts
Manifests folder contains AndroidManifest.xml for our creating the android application. This file contains information about our application such as android version, metadata, states package for Kotlin file and other application components. It acts as an intermediator between android OS and our application.Following is the mainfests folder structure in android application.
AndroidManifest.xml
XML
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http:// schemas.android.com/apk/res/android" package="com.geeksforgeeks.myapplication"> <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>
Java folder contains all the java and Kotlin source code (.java) files that we create during the app development, including other Test files. If we create any new project using Kotlin, by default the class file MainActivity.kt file will create automatically under the package name “com.geeksforgeeks.myfirstkotlinapp” like as shown below.
MainActivity.kt
Kotlin
package com.geeksforgeeks.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}
The resource folder is the most important folder because it contains all the non-code sources like images, XML layouts, UI strings for our android application.
It contains the different types of images used for the development of the application. We need to add all the images in a drawable folder for the application development.
The layout folder contains all XML layout files which we used to define the user interface of our application. It contains the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http:// schemas.android.com/apk/res/android" xmlns:app="http:// schemas.android.com/apk/res-auto" xmlns:tools="http:// schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintLeft_toLeftOf="parent" app:layout_constraintRight_toRightOf="parent" app:layout_constraintTop_toTopOf="parent" /> </androidx.constraintlayout.widget.ConstraintLayout>
This folder contains launcher.xml files to define icons that are used to show on the home screen. It contains different density types of icons depending upon the size of the device such as hdpi, mdpi, xhdpi.
Values folder contains a number of XML files like strings, dimensions, colors and styles definitions. One of the most important file is strings.xml file which contains the resources.
XML
<resources> <string name="app_name">NameOfTheApplication</string> <string name="checked">Checked</string> <string name="unchecked">Unchecked</string></resources>
Gradle means automated build system and it contains number of files which are used to define a build configuration which can be apply to all modules in our application. In build.gradle (Project) there are buildscripts and in build.gradle (Module) plugins and implementations are used to build configurations that can be applied to all our application modules.
ayushpandey3july
rkbhola5
Android-Studio
Kotlin Android
Android
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Create and Add Data to SQLite Database in Android?
Broadcast Receiver in Android With Example
Services in Android with Example
Content Providers in Android with Example
Android RecyclerView in Kotlin
Flutter - Custom Bottom Navigation Bar
Navigation Drawer in Android
How to View and Locate SQLite Database in Android Studio?
Android Projects - From Basic to Advanced Level
How to Update Gradle in Android Studio? | [
{
"code": null,
"e": 24664,
"s": 24636,
"text": "\n02 Mar, 2022"
},
{
"code": null,
"e": 25058,
"s": 24664,
"text": "Android Studio is the official IDE (Integrated Development Environment) developed by JetBrains community which is freely provided by Google for android app development.After completing the setup of Android Architecture we can create android application in the studio. We need to create new project for each sample application and we should understand the folder structure. It looks like this: "
},
{
"code": null,
"e": 25222,
"s": 25058,
"text": "The android project contains different types of app modules, source code files, and resource files. We will explore all the folders and files in the android app. "
},
{
"code": null,
"e": 25340,
"s": 25222,
"text": "Manifests FolderJava Folderres (Resources) FolderDrawable FolderLayout FolderMipmap FolderValues FolderGradle Scripts"
},
{
"code": null,
"e": 25357,
"s": 25340,
"text": "Manifests Folder"
},
{
"code": null,
"e": 25369,
"s": 25357,
"text": "Java Folder"
},
{
"code": null,
"e": 25446,
"s": 25369,
"text": "res (Resources) FolderDrawable FolderLayout FolderMipmap FolderValues Folder"
},
{
"code": null,
"e": 25462,
"s": 25446,
"text": "Drawable Folder"
},
{
"code": null,
"e": 25476,
"s": 25462,
"text": "Layout Folder"
},
{
"code": null,
"e": 25490,
"s": 25476,
"text": "Mipmap Folder"
},
{
"code": null,
"e": 25504,
"s": 25490,
"text": "Values Folder"
},
{
"code": null,
"e": 25519,
"s": 25504,
"text": "Gradle Scripts"
},
{
"code": null,
"e": 25899,
"s": 25521,
"text": "Manifests folder contains AndroidManifest.xml for our creating the android application. This file contains information about our application such as android version, metadata, states package for Kotlin file and other application components. It acts as an intermediator between android OS and our application.Following is the mainfests folder structure in android application. "
},
{
"code": null,
"e": 25921,
"s": 25899,
"text": "AndroidManifest.xml "
},
{
"code": null,
"e": 25925,
"s": 25921,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http:// schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.myapplication\"> <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>",
"e": 26638,
"s": 25925,
"text": null
},
{
"code": null,
"e": 26979,
"s": 26638,
"text": "Java folder contains all the java and Kotlin source code (.java) files that we create during the app development, including other Test files. If we create any new project using Kotlin, by default the class file MainActivity.kt file will create automatically under the package name “com.geeksforgeeks.myfirstkotlinapp” like as shown below. "
},
{
"code": null,
"e": 26997,
"s": 26979,
"text": "MainActivity.kt "
},
{
"code": null,
"e": 27004,
"s": 26997,
"text": "Kotlin"
},
{
"code": "package com.geeksforgeeks.myapplication import androidx.appcompat.app.AppCompatActivity import android.os.Bundle class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) }}",
"e": 27329,
"s": 27004,
"text": null
},
{
"code": null,
"e": 27491,
"s": 27329,
"text": "The resource folder is the most important folder because it contains all the non-code sources like images, XML layouts, UI strings for our android application. "
},
{
"code": null,
"e": 27665,
"s": 27493,
"text": "It contains the different types of images used for the development of the application. We need to add all the images in a drawable folder for the application development. "
},
{
"code": null,
"e": 27817,
"s": 27665,
"text": "The layout folder contains all XML layout files which we used to define the user interface of our application. It contains the activity_main.xml file. "
},
{
"code": null,
"e": 27821,
"s": 27817,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http:// schemas.android.com/apk/res/android\" xmlns:app=\"http:// schemas.android.com/apk/res-auto\" xmlns:tools=\"http:// schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <TextView android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Hello World!\" app:layout_constraintBottom_toBottomOf=\"parent\" app:layout_constraintLeft_toLeftOf=\"parent\" app:layout_constraintRight_toRightOf=\"parent\" app:layout_constraintTop_toTopOf=\"parent\" /> </androidx.constraintlayout.widget.ConstraintLayout>",
"e": 28595,
"s": 27821,
"text": null
},
{
"code": null,
"e": 28804,
"s": 28595,
"text": "This folder contains launcher.xml files to define icons that are used to show on the home screen. It contains different density types of icons depending upon the size of the device such as hdpi, mdpi, xhdpi. "
},
{
"code": null,
"e": 28989,
"s": 28804,
"text": "Values folder contains a number of XML files like strings, dimensions, colors and styles definitions. One of the most important file is strings.xml file which contains the resources. "
},
{
"code": null,
"e": 28993,
"s": 28989,
"text": "XML"
},
{
"code": "<resources> <string name=\"app_name\">NameOfTheApplication</string> <string name=\"checked\">Checked</string> <string name=\"unchecked\">Unchecked</string></resources>",
"e": 29164,
"s": 28993,
"text": null
},
{
"code": null,
"e": 29525,
"s": 29164,
"text": "Gradle means automated build system and it contains number of files which are used to define a build configuration which can be apply to all modules in our application. In build.gradle (Project) there are buildscripts and in build.gradle (Module) plugins and implementations are used to build configurations that can be applied to all our application modules. "
},
{
"code": null,
"e": 29544,
"s": 29527,
"text": "ayushpandey3july"
},
{
"code": null,
"e": 29553,
"s": 29544,
"text": "rkbhola5"
},
{
"code": null,
"e": 29568,
"s": 29553,
"text": "Android-Studio"
},
{
"code": null,
"e": 29583,
"s": 29568,
"text": "Kotlin Android"
},
{
"code": null,
"e": 29591,
"s": 29583,
"text": "Android"
},
{
"code": null,
"e": 29599,
"s": 29591,
"text": "Android"
},
{
"code": null,
"e": 29697,
"s": 29599,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29755,
"s": 29697,
"text": "How to Create and Add Data to SQLite Database in Android?"
},
{
"code": null,
"e": 29798,
"s": 29755,
"text": "Broadcast Receiver in Android With Example"
},
{
"code": null,
"e": 29831,
"s": 29798,
"text": "Services in Android with Example"
},
{
"code": null,
"e": 29873,
"s": 29831,
"text": "Content Providers in Android with Example"
},
{
"code": null,
"e": 29904,
"s": 29873,
"text": "Android RecyclerView in Kotlin"
},
{
"code": null,
"e": 29943,
"s": 29904,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 29972,
"s": 29943,
"text": "Navigation Drawer in Android"
},
{
"code": null,
"e": 30030,
"s": 29972,
"text": "How to View and Locate SQLite Database in Android Studio?"
},
{
"code": null,
"e": 30078,
"s": 30030,
"text": "Android Projects - From Basic to Advanced Level"
}
] |
java.util.regex.Pattern.quote() Method | The java.util.regex.Pattern.quote(String s) method returns a literal pattern String for the specified String.
Following is the declaration for java.util.regex.Pattern.quote(String s) method.
public static String quote(String s)
s − The string to be literalized.
s − The string to be literalized.
A literal string replacement.
The following example shows the usage of java.util.regex.Pattern.quote(String s) method.
package com.tutorialspoint;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternDemo {
private static String REGEX = "dog$";
private static String INPUT = "The dog$ says meow " + "All dog$ say meow.";
private static String REPLACE = "cat";
public static void main(String[] args) {
Pattern pattern = Pattern.compile(Pattern.quote(REGEX));
// get a matcher object
Matcher matcher = pattern.matcher(INPUT);
INPUT = matcher.replaceAll(REPLACE);
System.out.println(INPUT);
}
}
Let us compile and run the above program, this will produce the following result −
The cat says meow All cat say meow.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2234,
"s": 2124,
"text": "The java.util.regex.Pattern.quote(String s) method returns a literal pattern String for the specified String."
},
{
"code": null,
"e": 2315,
"s": 2234,
"text": "Following is the declaration for java.util.regex.Pattern.quote(String s) method."
},
{
"code": null,
"e": 2353,
"s": 2315,
"text": "public static String quote(String s)\n"
},
{
"code": null,
"e": 2387,
"s": 2353,
"text": "s − The string to be literalized."
},
{
"code": null,
"e": 2421,
"s": 2387,
"text": "s − The string to be literalized."
},
{
"code": null,
"e": 2451,
"s": 2421,
"text": "A literal string replacement."
},
{
"code": null,
"e": 2540,
"s": 2451,
"text": "The following example shows the usage of java.util.regex.Pattern.quote(String s) method."
},
{
"code": null,
"e": 3100,
"s": 2540,
"text": "package com.tutorialspoint;\n\nimport java.util.regex.Matcher;\nimport java.util.regex.Pattern;\n\npublic class PatternDemo {\n private static String REGEX = \"dog$\";\n private static String INPUT = \"The dog$ says meow \" + \"All dog$ say meow.\";\n private static String REPLACE = \"cat\";\n\n public static void main(String[] args) {\n Pattern pattern = Pattern.compile(Pattern.quote(REGEX));\n \n // get a matcher object\n Matcher matcher = pattern.matcher(INPUT); \n INPUT = matcher.replaceAll(REPLACE);\n System.out.println(INPUT);\n }\n}"
},
{
"code": null,
"e": 3183,
"s": 3100,
"text": "Let us compile and run the above program, this will produce the following result −"
},
{
"code": null,
"e": 3220,
"s": 3183,
"text": "The cat says meow All cat say meow.\n"
},
{
"code": null,
"e": 3227,
"s": 3220,
"text": " Print"
},
{
"code": null,
"e": 3238,
"s": 3227,
"text": " Add Notes"
}
] |
Puppet - Environment Conf | In Puppet, all environments have the environment.conf file. This file can override several default settings whenever the master is serving any of the nodes or all the nodes assigned to that particular environment.
In Puppet, for all the environments which are defined, environment.conf file is located at the top level of its home environment, very next to the manifest and modules directors. Considering an example, if your environment is in default directories (Vipin/testing/environment), then test environment’s config file is located at Vipin/testing/environments/test/environment.conf.
# /etc/testingdir/code/environments/test/environment.conf
# Puppet Enterprise requires $basemodulepath; see note below under modulepath".
modulepath = site:dist:modules:$basemodulepath
# Use our custom script to get a git commit for the current state of the code:
config_version = get_environment_commit.sh
All the configuration files in Puppet uses the same INI-like format in the same way. environment.conf file follow the same INI-like format as others do like puppet.conf file. The only difference between environment.conf and puppet.conf is environment.conf file cannot contain the [main] section. All settings in the environment.conf file must be outside any config section.
Most of the allowed settings accept file path or list of path as the value. If any of the paths are relevant path, they start without a leading slash or drive letter – they will be mostly resolved relative to that environment’s main directory.
Environment.conf settings file is capable of using values of other settings as variable. There are multiple useful variables which could be interpolated into the environment.conf file. Here is a list of few important variables −
$basemodulepath − Useful for including directories in the module path settings. Puppet enterprise user should usually include this value of modulepath since the Puppet engine uses module in the basemodulepath.
$basemodulepath − Useful for including directories in the module path settings. Puppet enterprise user should usually include this value of modulepath since the Puppet engine uses module in the basemodulepath.
$environment − Useful as a command line argument to your config_version script. You can interpolate this variable only in the config_version setting.
$environment − Useful as a command line argument to your config_version script. You can interpolate this variable only in the config_version setting.
$codedir − Useful for locating files.
$codedir − Useful for locating files.
By default, Puppet environment.conf file is only allowed to override four settings in the configuration as listed.
Modulepath
Manifest
Config_version
Environment_timeout
This is one of the key settings in environment.conf file. All the directors defined in modulepath are by default loaded by Puppet. This is the path location from where Puppet loads its modules. One needs to explicitly set this up. If this above setting is not set, the default modulepath of any environment in Puppet will be −
<MODULES DIRECTORY FROM ENVIRONMENT>:$basemodulepath
This is used to define the main manifest file, which Puppet master will use while booting up and compiling the catalog out of the defined manifest which is going to be used to configure the environment. In this, we can define a single file, a list of files, or even a directory consisting of multiple manifest files which needs to be evaluated and compiled in a defined alphabetical sequence.
One needs to explicitly define this setting in the environment.conf file. If not, then Puppet will use environments default manifest directory as its main manifest.
Config_version can be defined as a definite version used to identify catalogs and events. When Puppet compiles any manifest file by default, it adds a config version to the generated catalogs as well as to the reports which gets generated when the Puppet master applies any defined catalog on Puppet nodes. Puppet runs a script to perform all the above steps and uses all the generated output as Config_version.
It is used to get the details about the amount of time which Puppet should use to load data for a given environment. If the value is defined in puppet.conf file, then these values will override the default timeout value.
[master]
manifest = $confdir/environments/$environment/manifests/site.pp
modulepath = $confdir/environments/$environment/modules
In the above code $confdir is the path of the directory, where environment configuration files are located. $environment is the name of the environment for which the configuration is being done.
# The environment configuration file
# The main manifest directory or file where Puppet starts to evaluate code
# This is the default value. Works with just a site.pp file or any other
manifest = manifests/
# The directories added to the module path, looked in first match first used order:
# modules - Directory for external modules, populated by r10k based on Puppetfile
# $basemodulepath - As from: puppet config print basemodulepath
modulepath = site:modules:$basemodulepath
# Set the cache timeout for this environment.
# This overrides what is set directly in puppet.conf for the whole Puppet server
# environment_timeout = unlimited
# With caching you need to flush the cache whenever new Puppet code is deployed
# This can also be done manually running: bin/puppet_flush_environment_cache.sh
# To disable catalog caching:
environment_timeout = 0
# Here we pass to one in the control repo the Puppet environment (and git branch)
# to get title and essential info of the last git commit
config_version = 'bin/config_script.sh $environment'
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2387,
"s": 2173,
"text": "In Puppet, all environments have the environment.conf file. This file can override several default settings whenever the master is serving any of the nodes or all the nodes assigned to that particular environment."
},
{
"code": null,
"e": 2765,
"s": 2387,
"text": "In Puppet, for all the environments which are defined, environment.conf file is located at the top level of its home environment, very next to the manifest and modules directors. Considering an example, if your environment is in default directories (Vipin/testing/environment), then test environment’s config file is located at Vipin/testing/environments/test/environment.conf."
},
{
"code": null,
"e": 3080,
"s": 2765,
"text": "# /etc/testingdir/code/environments/test/environment.conf \n# Puppet Enterprise requires $basemodulepath; see note below under modulepath\". \nmodulepath = site:dist:modules:$basemodulepath \n# Use our custom script to get a git commit for the current state of the code: \nconfig_version = get_environment_commit.sh \n"
},
{
"code": null,
"e": 3454,
"s": 3080,
"text": "All the configuration files in Puppet uses the same INI-like format in the same way. environment.conf file follow the same INI-like format as others do like puppet.conf file. The only difference between environment.conf and puppet.conf is environment.conf file cannot contain the [main] section. All settings in the environment.conf file must be outside any config section."
},
{
"code": null,
"e": 3698,
"s": 3454,
"text": "Most of the allowed settings accept file path or list of path as the value. If any of the paths are relevant path, they start without a leading slash or drive letter – they will be mostly resolved relative to that environment’s main directory."
},
{
"code": null,
"e": 3927,
"s": 3698,
"text": "Environment.conf settings file is capable of using values of other settings as variable. There are multiple useful variables which could be interpolated into the environment.conf file. Here is a list of few important variables −"
},
{
"code": null,
"e": 4137,
"s": 3927,
"text": "$basemodulepath − Useful for including directories in the module path settings. Puppet enterprise user should usually include this value of modulepath since the Puppet engine uses module in the basemodulepath."
},
{
"code": null,
"e": 4347,
"s": 4137,
"text": "$basemodulepath − Useful for including directories in the module path settings. Puppet enterprise user should usually include this value of modulepath since the Puppet engine uses module in the basemodulepath."
},
{
"code": null,
"e": 4497,
"s": 4347,
"text": "$environment − Useful as a command line argument to your config_version script. You can interpolate this variable only in the config_version setting."
},
{
"code": null,
"e": 4647,
"s": 4497,
"text": "$environment − Useful as a command line argument to your config_version script. You can interpolate this variable only in the config_version setting."
},
{
"code": null,
"e": 4685,
"s": 4647,
"text": "$codedir − Useful for locating files."
},
{
"code": null,
"e": 4723,
"s": 4685,
"text": "$codedir − Useful for locating files."
},
{
"code": null,
"e": 4838,
"s": 4723,
"text": "By default, Puppet environment.conf file is only allowed to override four settings in the configuration as listed."
},
{
"code": null,
"e": 4849,
"s": 4838,
"text": "Modulepath"
},
{
"code": null,
"e": 4858,
"s": 4849,
"text": "Manifest"
},
{
"code": null,
"e": 4873,
"s": 4858,
"text": "Config_version"
},
{
"code": null,
"e": 4893,
"s": 4873,
"text": "Environment_timeout"
},
{
"code": null,
"e": 5220,
"s": 4893,
"text": "This is one of the key settings in environment.conf file. All the directors defined in modulepath are by default loaded by Puppet. This is the path location from where Puppet loads its modules. One needs to explicitly set this up. If this above setting is not set, the default modulepath of any environment in Puppet will be −"
},
{
"code": null,
"e": 5275,
"s": 5220,
"text": "<MODULES DIRECTORY FROM ENVIRONMENT>:$basemodulepath \n"
},
{
"code": null,
"e": 5668,
"s": 5275,
"text": "This is used to define the main manifest file, which Puppet master will use while booting up and compiling the catalog out of the defined manifest which is going to be used to configure the environment. In this, we can define a single file, a list of files, or even a directory consisting of multiple manifest files which needs to be evaluated and compiled in a defined alphabetical sequence."
},
{
"code": null,
"e": 5833,
"s": 5668,
"text": "One needs to explicitly define this setting in the environment.conf file. If not, then Puppet will use environments default manifest directory as its main manifest."
},
{
"code": null,
"e": 6245,
"s": 5833,
"text": "Config_version can be defined as a definite version used to identify catalogs and events. When Puppet compiles any manifest file by default, it adds a config version to the generated catalogs as well as to the reports which gets generated when the Puppet master applies any defined catalog on Puppet nodes. Puppet runs a script to perform all the above steps and uses all the generated output as Config_version."
},
{
"code": null,
"e": 6466,
"s": 6245,
"text": "It is used to get the details about the amount of time which Puppet should use to load data for a given environment. If the value is defined in puppet.conf file, then these values will override the default timeout value."
},
{
"code": null,
"e": 6606,
"s": 6466,
"text": "[master] \n manifest = $confdir/environments/$environment/manifests/site.pp \n modulepath = $confdir/environments/$environment/modules\n"
},
{
"code": null,
"e": 6801,
"s": 6606,
"text": "In the above code $confdir is the path of the directory, where environment configuration files are located. $environment is the name of the environment for which the configuration is being done."
},
{
"code": null,
"e": 7881,
"s": 6801,
"text": "# The environment configuration file \n# The main manifest directory or file where Puppet starts to evaluate code \n# This is the default value. Works with just a site.pp file or any other \nmanifest = manifests/ \n# The directories added to the module path, looked in first match first used order: \n# modules - Directory for external modules, populated by r10k based on Puppetfile \n# $basemodulepath - As from: puppet config print basemodulepath \nmodulepath = site:modules:$basemodulepath \n# Set the cache timeout for this environment. \n# This overrides what is set directly in puppet.conf for the whole Puppet server \n# environment_timeout = unlimited \n# With caching you need to flush the cache whenever new Puppet code is deployed \n# This can also be done manually running: bin/puppet_flush_environment_cache.sh \n# To disable catalog caching: \nenvironment_timeout = 0 \n# Here we pass to one in the control repo the Puppet environment (and git branch) \n# to get title and essential info of the last git commit\nconfig_version = 'bin/config_script.sh $environment' \n"
},
{
"code": null,
"e": 7888,
"s": 7881,
"text": " Print"
},
{
"code": null,
"e": 7899,
"s": 7888,
"text": " Add Notes"
}
] |
Write a program in Java to find the missing positive number in a given array of unsorted integers | Let’s suppose we have given an array of unsorted integers. The task is to find the positive missing number which is not present in the given array in the range [0 to n]. For example,
Input-1 −
N = 9
arr = [0,2,5,9,1,7,4,3,6]
Output −
8
Explanation − In the given unsorted array, ‘8’ is the only positive integer that is missing, thus the output is ‘8’.
Input-2 −
N = 1
arr = [0]
Output −
1
Explanation − In the given array, ‘1’ is the only one positive integer which is missing, thus the output is ‘1’.
There are several approaches to solve this particular problem. However, we can solve this problem in linear time O(n) and constant space O(1).
Since we know that our array is of size n and it contains exactly elements in the range of [0 to n]. So, if we do XOR operation of each of the elements and its index with ‘n’, then we can find the resultant number as a unique number that is missing from the array.
Take Input of N size of the array with elements in the range [0 to n].
Take Input of N size of the array with elements in the range [0 to n].
An integer function findMissingNumber(int arr[], int size) takes an array and its size as input and returns the missing number.
An integer function findMissingNumber(int arr[], int size) takes an array and its size as input and returns the missing number.
Let’s take n as a missing number to perform XOR operation.
Let’s take n as a missing number to perform XOR operation.
Iterate over all the array elements and perform XOR operation with each of the array elements and its indexes with respect to missing number, i.e., n
Iterate over all the array elements and perform XOR operation with each of the array elements and its indexes with respect to missing number, i.e., n
Now return the missing number.
Now return the missing number.
public class Solution {
public static int findMissingNumber(int arr[], int size){
int missing_no= size;
for(int i=0;i<size;i++){
missing_no^= i^arr[i];
}
return missing_no;
}
public static void main(String[] args){
int arr[] = {0,4,2,1,6,3};
int n = arr.length;
int a=findMissingNumber(arr, n);
System.out.println(a);
}
}
Running the above code will generate the output as,
5
In the given array {0,4,2,1,6,3}, ‘5’ is missing, thus we will return 5. | [
{
"code": null,
"e": 1245,
"s": 1062,
"text": "Let’s suppose we have given an array of unsorted integers. The task is to find the positive missing number which is not present in the given array in the range [0 to n]. For example,"
},
{
"code": null,
"e": 1255,
"s": 1245,
"text": "Input-1 −"
},
{
"code": null,
"e": 1287,
"s": 1255,
"text": "N = 9\narr = [0,2,5,9,1,7,4,3,6]"
},
{
"code": null,
"e": 1296,
"s": 1287,
"text": "Output −"
},
{
"code": null,
"e": 1298,
"s": 1296,
"text": "8"
},
{
"code": null,
"e": 1415,
"s": 1298,
"text": "Explanation − In the given unsorted array, ‘8’ is the only positive integer that is missing, thus the output is ‘8’."
},
{
"code": null,
"e": 1425,
"s": 1415,
"text": "Input-2 −"
},
{
"code": null,
"e": 1441,
"s": 1425,
"text": "N = 1\narr = [0]"
},
{
"code": null,
"e": 1450,
"s": 1441,
"text": "Output −"
},
{
"code": null,
"e": 1452,
"s": 1450,
"text": "1"
},
{
"code": null,
"e": 1565,
"s": 1452,
"text": "Explanation − In the given array, ‘1’ is the only one positive integer which is missing, thus the output is ‘1’."
},
{
"code": null,
"e": 1708,
"s": 1565,
"text": "There are several approaches to solve this particular problem. However, we can solve this problem in linear time O(n) and constant space O(1)."
},
{
"code": null,
"e": 1973,
"s": 1708,
"text": "Since we know that our array is of size n and it contains exactly elements in the range of [0 to n]. So, if we do XOR operation of each of the elements and its index with ‘n’, then we can find the resultant number as a unique number that is missing from the array."
},
{
"code": null,
"e": 2044,
"s": 1973,
"text": "Take Input of N size of the array with elements in the range [0 to n]."
},
{
"code": null,
"e": 2115,
"s": 2044,
"text": "Take Input of N size of the array with elements in the range [0 to n]."
},
{
"code": null,
"e": 2243,
"s": 2115,
"text": "An integer function findMissingNumber(int arr[], int size) takes an array and its size as input and returns the missing number."
},
{
"code": null,
"e": 2371,
"s": 2243,
"text": "An integer function findMissingNumber(int arr[], int size) takes an array and its size as input and returns the missing number."
},
{
"code": null,
"e": 2430,
"s": 2371,
"text": "Let’s take n as a missing number to perform XOR operation."
},
{
"code": null,
"e": 2489,
"s": 2430,
"text": "Let’s take n as a missing number to perform XOR operation."
},
{
"code": null,
"e": 2639,
"s": 2489,
"text": "Iterate over all the array elements and perform XOR operation with each of the array elements and its indexes with respect to missing number, i.e., n"
},
{
"code": null,
"e": 2789,
"s": 2639,
"text": "Iterate over all the array elements and perform XOR operation with each of the array elements and its indexes with respect to missing number, i.e., n"
},
{
"code": null,
"e": 2820,
"s": 2789,
"text": "Now return the missing number."
},
{
"code": null,
"e": 2851,
"s": 2820,
"text": "Now return the missing number."
},
{
"code": null,
"e": 3242,
"s": 2851,
"text": "public class Solution {\n public static int findMissingNumber(int arr[], int size){\n int missing_no= size;\n for(int i=0;i<size;i++){\n missing_no^= i^arr[i];\n }\n return missing_no;\n }\n public static void main(String[] args){\n int arr[] = {0,4,2,1,6,3};\n int n = arr.length;\n int a=findMissingNumber(arr, n);\n System.out.println(a);\n }\n}"
},
{
"code": null,
"e": 3294,
"s": 3242,
"text": "Running the above code will generate the output as,"
},
{
"code": null,
"e": 3296,
"s": 3294,
"text": "5"
},
{
"code": null,
"e": 3369,
"s": 3296,
"text": "In the given array {0,4,2,1,6,3}, ‘5’ is missing, thus we will return 5."
}
] |
isalnum() function in C Language | The function isalnum() is used to check that the character is alphanumeric or not. It returns non-zero value, if the character is alphanumeric means letter or number otherwise, returns zero. It is declared in “ctype.h” header file.
Here is the syntax of isalnum() in C language,
int isalnum(int character);
Here,
character − The character which is to be checked.
Here is an example of isalnum() in C language,
Live Demo
#include<stdio.h>
#include<ctype.h>
int main() {
char val1 = 's';
char val2 = '8';
char val3 = '$';
if(isalnum(val1))
printf("The character is alphanumeric\n");
else
printf("The character is not alphanumeric\n");
if(isalnum(val2))
printf("The character is alphanumeric\n");
else
printf("The character is not alphanumeric");
if(isalnum(val3))
printf("The character is alphanumeric\n");
else
printf("The character is not alphanumeric");
return 0;
}
The character is alphanumeric
The character is alphanumeric
The character is not alphanumeric
In the above program, three variables of char type are declared and initialized with the values. These variables are checked that these values are alphanumeric or not by using isalnum() function.
if(isalnum(val1))
printf("The character is alphanumeric\n");
else
printf("The character is not alphanumeric\n"); | [
{
"code": null,
"e": 1294,
"s": 1062,
"text": "The function isalnum() is used to check that the character is alphanumeric or not. It returns non-zero value, if the character is alphanumeric means letter or number otherwise, returns zero. It is declared in “ctype.h” header file."
},
{
"code": null,
"e": 1341,
"s": 1294,
"text": "Here is the syntax of isalnum() in C language,"
},
{
"code": null,
"e": 1369,
"s": 1341,
"text": "int isalnum(int character);"
},
{
"code": null,
"e": 1375,
"s": 1369,
"text": "Here,"
},
{
"code": null,
"e": 1425,
"s": 1375,
"text": "character − The character which is to be checked."
},
{
"code": null,
"e": 1472,
"s": 1425,
"text": "Here is an example of isalnum() in C language,"
},
{
"code": null,
"e": 1483,
"s": 1472,
"text": " Live Demo"
},
{
"code": null,
"e": 1978,
"s": 1483,
"text": "#include<stdio.h>\n#include<ctype.h>\nint main() {\n char val1 = 's';\n char val2 = '8';\n char val3 = '$';\n if(isalnum(val1))\n printf(\"The character is alphanumeric\\n\");\n else\n printf(\"The character is not alphanumeric\\n\");\n if(isalnum(val2))\n printf(\"The character is alphanumeric\\n\");\n else\n printf(\"The character is not alphanumeric\");\n if(isalnum(val3))\n printf(\"The character is alphanumeric\\n\");\n else\n printf(\"The character is not alphanumeric\");\n return 0;\n}"
},
{
"code": null,
"e": 2072,
"s": 1978,
"text": "The character is alphanumeric\nThe character is alphanumeric\nThe character is not alphanumeric"
},
{
"code": null,
"e": 2268,
"s": 2072,
"text": "In the above program, three variables of char type are declared and initialized with the values. These variables are checked that these values are alphanumeric or not by using isalnum() function."
},
{
"code": null,
"e": 2381,
"s": 2268,
"text": "if(isalnum(val1))\nprintf(\"The character is alphanumeric\\n\");\nelse\nprintf(\"The character is not alphanumeric\\n\");"
}
] |
Print structured MySQL SELECT at command prompt | To print, the syntax is as follows −
mysql -uroot -t -e "your Select Query " -p
To implement the above syntax, let us open the command prompt −
Now, reach the MySQL bin −
Let us implement the above syntax to easily print structured SQL select. Following is the query −
This will produce the following output − | [
{
"code": null,
"e": 1099,
"s": 1062,
"text": "To print, the syntax is as follows −"
},
{
"code": null,
"e": 1143,
"s": 1099,
"text": "mysql -uroot -t -e \"your Select Query \" -p"
},
{
"code": null,
"e": 1207,
"s": 1143,
"text": "To implement the above syntax, let us open the command prompt −"
},
{
"code": null,
"e": 1234,
"s": 1207,
"text": "Now, reach the MySQL bin −"
},
{
"code": null,
"e": 1332,
"s": 1234,
"text": "Let us implement the above syntax to easily print structured SQL select. Following is the query −"
},
{
"code": null,
"e": 1373,
"s": 1332,
"text": "This will produce the following output −"
}
] |
Subsets and Splits