title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
How to convert python tuple into a two-dimensional table?
If you have a numeric library like numpy available, you should use the reshape method to reshape the tuple to a multidimensional array. import numpy data = numpy.array(range(1,10)) data.reshape([3,3]) print(data) This will give the output − array([[1, 2, 3], [4, 5, 6], [7, 8, 9]]) If you prefer to do it in pure python, you can use a list comprehension − data = tuple(range(1, 10)) table = tuple(data[n:n+3] for n in xrange(0,len(data),3)) print(table) This will give the output − ((1, 2, 3), (4, 5, 6), (7, 8, 9))
[ { "code": null, "e": 1199, "s": 1062, "text": "If you have a numeric library like numpy available, you should use the reshape method to reshape the tuple to a multidimensional array. " }, { "code": null, "e": 1276, "s": 1199, "text": "import numpy\ndata = numpy.array(range(1,10))\ndata.reshape([3,3])\nprint(data)" }, { "code": null, "e": 1304, "s": 1276, "text": "This will give the output −" }, { "code": null, "e": 1359, "s": 1304, "text": "array([[1, 2, 3],\n [4, 5, 6],\n [7, 8, 9]])" }, { "code": null, "e": 1433, "s": 1359, "text": "If you prefer to do it in pure python, you can use a list comprehension −" }, { "code": null, "e": 1531, "s": 1433, "text": "data = tuple(range(1, 10))\ntable = tuple(data[n:n+3] for n in xrange(0,len(data),3))\nprint(table)" }, { "code": null, "e": 1559, "s": 1531, "text": "This will give the output −" }, { "code": null, "e": 1593, "s": 1559, "text": "((1, 2, 3), (4, 5, 6), (7, 8, 9))" } ]
Python Environment Setup for Deep Learning on Windows 10 | by Tamim Mirza | Towards Data Science
A detailed introduction on how to get started with Deep Learning starting with enabling an environment suited to it on the Microsoft Windows 10. The frameworks to be installed will be Keras API with Google’s TensorFlow GPU version as the back end engine. This guide is the same procedure I had utilized during my own deep learning project and it has served me well. The purpose of this guide is to accumulate all necessary and updated information in one place rather than searching all over Google. Let’s get started. This guide has been updated to the release of TensorFlow 2.1 What is Deep Learning?PC Hardware SetupPC Software SetupPython InterpreterPython IDE What is Deep Learning? PC Hardware Setup PC Software Setup Python Interpreter Python IDE Deep learning is a subset of machine learning that utilizes multi-layered artificial neural networks to deliver state-of-the-art accuracy in tasks such as object detection, speech recognition, language translation and others. Deep learning differs from traditional machine learning techniques in that they can automatically learn representations from data such as images, video or text, without introducing hand-coded rules or human domain knowledge. Their highly flexible architectures can learn directly from raw data and can increase their predictive accuracy when provided with more data. To perform deep learning on any data set, the software/program requires a computer system powerful enough to handle the computing power necessary. So the following minimum specs are required: 1) Central Processing Unit (CPU) — Intel Core i5 6th Generation processor or higher. An AMD equivalent processor will also be optimal. 2) RAM — 8 GB minimum, 16 GB or higher is recommended. 3) Graphics Processing Unit (GPU) — NVIDIA GeForce GTX 940 or higher. AMD GPUs are not able to perform deep learning regardless. NVIDIA CUDA-enabled GPUs for deep learning 4) Operating System — Microsoft Windows 10 (64-bit recommended) Pro or Home. I recommend updating Windows 10 to the latest version before proceeding forward. Note: In case of laptops, the ideal option would be to purchase a gaming laptop from any vendor deemed suitable such as ASUS, Lenovo Legion, Acer Predator, Alienware, etc. Now to perform deep learning we are going to use a method known as GPU computing which directs complex mathematical computations to the GPU rather than the CPU which significantly reduces the overall computation time. To do so we install several components in the following order: Visual Studio is crucial for the installation of the next two components. I recommend Visual Studio 2019 (since I use it) as its performance supersedes all of it’s predecessors and installation has never been easier nor faster than ever before. But there is a range that you can use any VS version from 2012 to 2019. Download Visual Studio 2019 Download Visual Studio 2017 and older If you have Visual Studio 2019 installed then you have to update it to version 16.4 or higher. New installations of VS 2019 are updated by default. After installing Visual Studio 2019 (or 2017 as it is similar to 2019) then please ensure that “Desktop Development with C++” workload is installed along with the following components: MSVC v142 — VS 2019 C++ x64/x86 build tools (v14.24)Windows 10 SDK (Any version) MSVC v142 — VS 2019 C++ x64/x86 build tools (v14.24) Windows 10 SDK (Any version) This tool is designed to update your NVIDIA GPU drivers and it is far easier to do it like this and it is highly recommended to be installed if you have an NVIDIA GPU Download NVIDIA GeForce Experience Install it and you will need to create an account in order to use it. You should see a screen like this In the red box you can see a button labeled “Check for Updates”. The automatic update function is not reliable so manually check for updates before proceeding to download the next software. If your driver is updated then great you can move on. If not then please update it although CUDA Toolkit comes bundled with drivers but it is recommended to do it from here as they only carry the minimum drivers requirement at the time of release (since its possible you are using this a certain time after the release date). This software component is what is required to enable the GPU to be capable for GPU computing. We will download version 10.0 as that is the compatible version with the frameworks that we will be installing. Note: TensorFlow 2.1 is compatible with CUDA Toolkit 10.1 only. Download CUDA Toolkit 10.1 Official Windows Installation Documentation for CUDA 10.1 Next you need to go into the samples folder in your CUDA installation where it, if you chose the default path during installation, is at: C:\ProgramData\NVIDIA Corporation\CUDA Samples\v10.1\1_Utilities\deviceQuery and select the VS Solution appropriate to the VS version installed on your system and run it on your installed version of Visual Studio. If you have Visual Studio 2017 then run the Visual Studio solution for VS 2017. At the of the result from running the solution you should have attained With the installation verified you need to add CUDA Toolkit to the Path environment which is done through the following method: Step #1 Step #2 Step #3 Step #4 Step #5 C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\binC:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\include Download NVIDIA cuDNN You need to sign up for an NVIDIA Developer account in order to download it which is free and not that much a bother. Download cuDNN 7.6.X for CUDA 10.1. Once downloaded, unzip it and you will have 3 files and then do: a) Copy <installpath>\cuda\bin\cudnn64_7.dll to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\bin. b) Copy <installpath>\cuda\ include\cudnn.h to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\include. c) Copy <installpath>\cuda\lib\x64\cudnn.lib to C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v10.1\lib\x64. Once completed your GPU is now ready to perform GPU computing. Now that we have our GPU configured, it is time to install our python interpreter which we will go with Anaconda. It is deemed far better to use than the traditional python installation and will operate much better. There are two variations of this interpreter that we can install called Anaconda and Miniconda. To choose which one to go with refer the following guide (taken from official documentation): Choose Anaconda if you: Are new to conda or Python Like the convenience of having Python and over 150 scientific packages automatically installed at once Have the time and disk space (a few minutes and 5 GB), and/or Don’t want to install each of the packages you want to use individually. Choose Miniconda if you: Do not mind installing each of the packages you want to use individually. Do not have time or disk space to install over 150 packages at once, and/or Just want fast access to Python and the conda commands, and wish to sort out the other programs later. I use Miniconda myself. Anaconda is bloated. Many of the packages are never used and could still be easily installed if and when needed. Note: It is recommended (but not necessary) to download the Python 3 versions of your choice interpreter since Python 2 is reaching it’s end-of-life. Click to download Anaconda Click to download Miniconda Once you have installed your choice interpreter, it time to install the required packages. Open Anaconda Prompt and type in the command: conda update conda For Anaconda-only users, after you type in the above command, next type in: conda update anaconda Do NOT close Anaconda prompt just yet. Note: TensorFlow supports Python 3.5, 3.6 and 3.7 on Windows 10. Although TensorFlow 2.1 will be the final version of TensorFlow that will support Python 2 (regardless of OS). Now it is time to create our environment, we can do this through Anaconda Prompt easily (in this case we will be creating a Python 3.7 environment named TensorFlow-GPU): conda create -n TensorFlow-GPU python=3.7 And we have successfully created the new environment. Do NOT close Anaconda prompt just yet. Now we begin to installed tensorflow GPU version and to do that we first activate our newly created environment. Simply type in: conda activate TensorFlow-GPU Next we install TensorFlow 2.1 (The base package tensorflow already contains support for CPU and GPU and will configure according to the system): pip install tensorflow The pip version is officially supported while the conda version is community supported. Google recommends to install the pip version. TensorFlow version 1.13 and onwards come with Keras pre-installed and built with TensorFlow and so it exempts the users from installing a separate Keras package. Now to test the environment, invoke the command: python Then type in: >>import tensorflow as tf If this is the result you get: >>import tensorflow as tf>> Then it means that the installation was successful. Now we move on to the IDE. You may close the prompt. Both of the following are great in debugging, linting and smart autocompleting Python code with lightning fast speeds and precision. Visual Studio Code installed with these necessary extensions.PyCharm: The Python IDE for Professional Developers. Visual Studio Code installed with these necessary extensions. PyCharm: The Python IDE for Professional Developers. With that you are ready to begin your journey into machine learning and beyond.
[ { "code": null, "e": 301, "s": 46, "text": "A detailed introduction on how to get started with Deep Learning starting with enabling an environment suited to it on the Microsoft Windows 10. The frameworks to be installed will be Keras API with Google’s TensorFlow GPU version as the back end engine." }, { "code": null, "e": 545, "s": 301, "text": "This guide is the same procedure I had utilized during my own deep learning project and it has served me well. The purpose of this guide is to accumulate all necessary and updated information in one place rather than searching all over Google." }, { "code": null, "e": 564, "s": 545, "text": "Let’s get started." }, { "code": null, "e": 625, "s": 564, "text": "This guide has been updated to the release of TensorFlow 2.1" }, { "code": null, "e": 710, "s": 625, "text": "What is Deep Learning?PC Hardware SetupPC Software SetupPython InterpreterPython IDE" }, { "code": null, "e": 733, "s": 710, "text": "What is Deep Learning?" }, { "code": null, "e": 751, "s": 733, "text": "PC Hardware Setup" }, { "code": null, "e": 769, "s": 751, "text": "PC Software Setup" }, { "code": null, "e": 788, "s": 769, "text": "Python Interpreter" }, { "code": null, "e": 799, "s": 788, "text": "Python IDE" }, { "code": null, "e": 1025, "s": 799, "text": "Deep learning is a subset of machine learning that utilizes multi-layered artificial neural networks to deliver state-of-the-art accuracy in tasks such as object detection, speech recognition, language translation and others." }, { "code": null, "e": 1392, "s": 1025, "text": "Deep learning differs from traditional machine learning techniques in that they can automatically learn representations from data such as images, video or text, without introducing hand-coded rules or human domain knowledge. Their highly flexible architectures can learn directly from raw data and can increase their predictive accuracy when provided with more data." }, { "code": null, "e": 1584, "s": 1392, "text": "To perform deep learning on any data set, the software/program requires a computer system powerful enough to handle the computing power necessary. So the following minimum specs are required:" }, { "code": null, "e": 1719, "s": 1584, "text": "1) Central Processing Unit (CPU) — Intel Core i5 6th Generation processor or higher. An AMD equivalent processor will also be optimal." }, { "code": null, "e": 1774, "s": 1719, "text": "2) RAM — 8 GB minimum, 16 GB or higher is recommended." }, { "code": null, "e": 1903, "s": 1774, "text": "3) Graphics Processing Unit (GPU) — NVIDIA GeForce GTX 940 or higher. AMD GPUs are not able to perform deep learning regardless." }, { "code": null, "e": 1946, "s": 1903, "text": "NVIDIA CUDA-enabled GPUs for deep learning" }, { "code": null, "e": 2104, "s": 1946, "text": "4) Operating System — Microsoft Windows 10 (64-bit recommended) Pro or Home. I recommend updating Windows 10 to the latest version before proceeding forward." }, { "code": null, "e": 2276, "s": 2104, "text": "Note: In case of laptops, the ideal option would be to purchase a gaming laptop from any vendor deemed suitable such as ASUS, Lenovo Legion, Acer Predator, Alienware, etc." }, { "code": null, "e": 2557, "s": 2276, "text": "Now to perform deep learning we are going to use a method known as GPU computing which directs complex mathematical computations to the GPU rather than the CPU which significantly reduces the overall computation time. To do so we install several components in the following order:" }, { "code": null, "e": 2874, "s": 2557, "text": "Visual Studio is crucial for the installation of the next two components. I recommend Visual Studio 2019 (since I use it) as its performance supersedes all of it’s predecessors and installation has never been easier nor faster than ever before. But there is a range that you can use any VS version from 2012 to 2019." }, { "code": null, "e": 2902, "s": 2874, "text": "Download Visual Studio 2019" }, { "code": null, "e": 2940, "s": 2902, "text": "Download Visual Studio 2017 and older" }, { "code": null, "e": 3088, "s": 2940, "text": "If you have Visual Studio 2019 installed then you have to update it to version 16.4 or higher. New installations of VS 2019 are updated by default." }, { "code": null, "e": 3273, "s": 3088, "text": "After installing Visual Studio 2019 (or 2017 as it is similar to 2019) then please ensure that “Desktop Development with C++” workload is installed along with the following components:" }, { "code": null, "e": 3354, "s": 3273, "text": "MSVC v142 — VS 2019 C++ x64/x86 build tools (v14.24)Windows 10 SDK (Any version)" }, { "code": null, "e": 3407, "s": 3354, "text": "MSVC v142 — VS 2019 C++ x64/x86 build tools (v14.24)" }, { "code": null, "e": 3436, "s": 3407, "text": "Windows 10 SDK (Any version)" }, { "code": null, "e": 3603, "s": 3436, "text": "This tool is designed to update your NVIDIA GPU drivers and it is far easier to do it like this and it is highly recommended to be installed if you have an NVIDIA GPU" }, { "code": null, "e": 3638, "s": 3603, "text": "Download NVIDIA GeForce Experience" }, { "code": null, "e": 3742, "s": 3638, "text": "Install it and you will need to create an account in order to use it. You should see a screen like this" }, { "code": null, "e": 3932, "s": 3742, "text": "In the red box you can see a button labeled “Check for Updates”. The automatic update function is not reliable so manually check for updates before proceeding to download the next software." }, { "code": null, "e": 4258, "s": 3932, "text": "If your driver is updated then great you can move on. If not then please update it although CUDA Toolkit comes bundled with drivers but it is recommended to do it from here as they only carry the minimum drivers requirement at the time of release (since its possible you are using this a certain time after the release date)." }, { "code": null, "e": 4465, "s": 4258, "text": "This software component is what is required to enable the GPU to be capable for GPU computing. We will download version 10.0 as that is the compatible version with the frameworks that we will be installing." }, { "code": null, "e": 4529, "s": 4465, "text": "Note: TensorFlow 2.1 is compatible with CUDA Toolkit 10.1 only." }, { "code": null, "e": 4556, "s": 4529, "text": "Download CUDA Toolkit 10.1" }, { "code": null, "e": 4614, "s": 4556, "text": "Official Windows Installation Documentation for CUDA 10.1" }, { "code": null, "e": 4752, "s": 4614, "text": "Next you need to go into the samples folder in your CUDA installation where it, if you chose the default path during installation, is at:" }, { "code": null, "e": 4829, "s": 4752, "text": "C:\\ProgramData\\NVIDIA Corporation\\CUDA Samples\\v10.1\\1_Utilities\\deviceQuery" }, { "code": null, "e": 5118, "s": 4829, "text": "and select the VS Solution appropriate to the VS version installed on your system and run it on your installed version of Visual Studio. If you have Visual Studio 2017 then run the Visual Studio solution for VS 2017. At the of the result from running the solution you should have attained" }, { "code": null, "e": 5246, "s": 5118, "text": "With the installation verified you need to add CUDA Toolkit to the Path environment which is done through the following method:" }, { "code": null, "e": 5254, "s": 5246, "text": "Step #1" }, { "code": null, "e": 5262, "s": 5254, "text": "Step #2" }, { "code": null, "e": 5270, "s": 5262, "text": "Step #3" }, { "code": null, "e": 5278, "s": 5270, "text": "Step #4" }, { "code": null, "e": 5286, "s": 5278, "text": "Step #5" }, { "code": null, "e": 5475, "s": 5286, "text": "C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\binC:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\lib\\x64C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\include" }, { "code": null, "e": 5497, "s": 5475, "text": "Download NVIDIA cuDNN" }, { "code": null, "e": 5651, "s": 5497, "text": "You need to sign up for an NVIDIA Developer account in order to download it which is free and not that much a bother. Download cuDNN 7.6.X for CUDA 10.1." }, { "code": null, "e": 5716, "s": 5651, "text": "Once downloaded, unzip it and you will have 3 files and then do:" }, { "code": null, "e": 5826, "s": 5716, "text": "a) Copy <installpath>\\cuda\\bin\\cudnn64_7.dll to C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\bin." }, { "code": null, "e": 5939, "s": 5826, "text": "b) Copy <installpath>\\cuda\\ include\\cudnn.h to C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\include." }, { "code": null, "e": 6053, "s": 5939, "text": "c) Copy <installpath>\\cuda\\lib\\x64\\cudnn.lib to C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v10.1\\lib\\x64." }, { "code": null, "e": 6116, "s": 6053, "text": "Once completed your GPU is now ready to perform GPU computing." }, { "code": null, "e": 6332, "s": 6116, "text": "Now that we have our GPU configured, it is time to install our python interpreter which we will go with Anaconda. It is deemed far better to use than the traditional python installation and will operate much better." }, { "code": null, "e": 6522, "s": 6332, "text": "There are two variations of this interpreter that we can install called Anaconda and Miniconda. To choose which one to go with refer the following guide (taken from official documentation):" }, { "code": null, "e": 6546, "s": 6522, "text": "Choose Anaconda if you:" }, { "code": null, "e": 6573, "s": 6546, "text": "Are new to conda or Python" }, { "code": null, "e": 6676, "s": 6573, "text": "Like the convenience of having Python and over 150 scientific packages automatically installed at once" }, { "code": null, "e": 6738, "s": 6676, "text": "Have the time and disk space (a few minutes and 5 GB), and/or" }, { "code": null, "e": 6811, "s": 6738, "text": "Don’t want to install each of the packages you want to use individually." }, { "code": null, "e": 6836, "s": 6811, "text": "Choose Miniconda if you:" }, { "code": null, "e": 6910, "s": 6836, "text": "Do not mind installing each of the packages you want to use individually." }, { "code": null, "e": 6986, "s": 6910, "text": "Do not have time or disk space to install over 150 packages at once, and/or" }, { "code": null, "e": 7089, "s": 6986, "text": "Just want fast access to Python and the conda commands, and wish to sort out the other programs later." }, { "code": null, "e": 7226, "s": 7089, "text": "I use Miniconda myself. Anaconda is bloated. Many of the packages are never used and could still be easily installed if and when needed." }, { "code": null, "e": 7376, "s": 7226, "text": "Note: It is recommended (but not necessary) to download the Python 3 versions of your choice interpreter since Python 2 is reaching it’s end-of-life." }, { "code": null, "e": 7403, "s": 7376, "text": "Click to download Anaconda" }, { "code": null, "e": 7431, "s": 7403, "text": "Click to download Miniconda" }, { "code": null, "e": 7568, "s": 7431, "text": "Once you have installed your choice interpreter, it time to install the required packages. Open Anaconda Prompt and type in the command:" }, { "code": null, "e": 7587, "s": 7568, "text": "conda update conda" }, { "code": null, "e": 7663, "s": 7587, "text": "For Anaconda-only users, after you type in the above command, next type in:" }, { "code": null, "e": 7685, "s": 7663, "text": "conda update anaconda" }, { "code": null, "e": 7724, "s": 7685, "text": "Do NOT close Anaconda prompt just yet." }, { "code": null, "e": 7900, "s": 7724, "text": "Note: TensorFlow supports Python 3.5, 3.6 and 3.7 on Windows 10. Although TensorFlow 2.1 will be the final version of TensorFlow that will support Python 2 (regardless of OS)." }, { "code": null, "e": 8070, "s": 7900, "text": "Now it is time to create our environment, we can do this through Anaconda Prompt easily (in this case we will be creating a Python 3.7 environment named TensorFlow-GPU):" }, { "code": null, "e": 8112, "s": 8070, "text": "conda create -n TensorFlow-GPU python=3.7" }, { "code": null, "e": 8166, "s": 8112, "text": "And we have successfully created the new environment." }, { "code": null, "e": 8205, "s": 8166, "text": "Do NOT close Anaconda prompt just yet." }, { "code": null, "e": 8334, "s": 8205, "text": "Now we begin to installed tensorflow GPU version and to do that we first activate our newly created environment. Simply type in:" }, { "code": null, "e": 8364, "s": 8334, "text": "conda activate TensorFlow-GPU" }, { "code": null, "e": 8510, "s": 8364, "text": "Next we install TensorFlow 2.1 (The base package tensorflow already contains support for CPU and GPU and will configure according to the system):" }, { "code": null, "e": 8533, "s": 8510, "text": "pip install tensorflow" }, { "code": null, "e": 8667, "s": 8533, "text": "The pip version is officially supported while the conda version is community supported. Google recommends to install the pip version." }, { "code": null, "e": 8829, "s": 8667, "text": "TensorFlow version 1.13 and onwards come with Keras pre-installed and built with TensorFlow and so it exempts the users from installing a separate Keras package." }, { "code": null, "e": 8878, "s": 8829, "text": "Now to test the environment, invoke the command:" }, { "code": null, "e": 8885, "s": 8878, "text": "python" }, { "code": null, "e": 8899, "s": 8885, "text": "Then type in:" }, { "code": null, "e": 8925, "s": 8899, "text": ">>import tensorflow as tf" }, { "code": null, "e": 8956, "s": 8925, "text": "If this is the result you get:" }, { "code": null, "e": 8984, "s": 8956, "text": ">>import tensorflow as tf>>" }, { "code": null, "e": 9089, "s": 8984, "text": "Then it means that the installation was successful. Now we move on to the IDE. You may close the prompt." }, { "code": null, "e": 9222, "s": 9089, "text": "Both of the following are great in debugging, linting and smart autocompleting Python code with lightning fast speeds and precision." }, { "code": null, "e": 9336, "s": 9222, "text": "Visual Studio Code installed with these necessary extensions.PyCharm: The Python IDE for Professional Developers." }, { "code": null, "e": 9398, "s": 9336, "text": "Visual Studio Code installed with these necessary extensions." }, { "code": null, "e": 9451, "s": 9398, "text": "PyCharm: The Python IDE for Professional Developers." } ]
How to handle frame in Selenium WebDriver using java?
We can handle frames in Selenium webdriver. A frame is identified with <frame> tag in the html document. A frame is used to insert an HTML document inside another HTML document. To work with frames, we should first understand switching between frames and identify the frame to which we want to move. There are multiple ways to switch to frames − switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0. switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0. Syntax − driver.switchTo().frame(1), we shall switch to the frame with index 1. switchTo().frame(name) - The frame id or name is passed as an argument to switch to. switchTo().frame(name) - The frame id or name is passed as an argument to switch to. Syntax − driver.switchTo().frame("fname"), we shall switch to the frame with name fname. switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to. switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to. Syntax − driver.switchTo().frame(n), we shall switch to the frame with webelement n. switchTo().defaultContent() – To switch back to the main page from the frame. switchTo().defaultContent() – To switch back to the main page from the frame. Syntax − driver.switchTo().defaultContent() Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class Framehandling{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); String url = "https://the-internet.herokuapp.com/frames"; driver.get(url); driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS); // identify element driver.findElement(By.linkText("Nested Frames")).click(); // switch to frame with frame name and identify inside element driver.switchTo().frame("frame-bottom"); WebElement l = driver.findElement(By.cssSelector("body")); System.out.println("Bottom frame text: " +l.getText()); // switch to main page driver.switchTo().defaultContent(); driver.quit(); } }
[ { "code": null, "e": 1240, "s": 1062, "text": "We can handle frames in Selenium webdriver. A frame is identified with <frame> tag in the html document. A frame is used to insert an HTML document inside another HTML document." }, { "code": null, "e": 1408, "s": 1240, "text": "To work with frames, we should first understand switching between frames and identify the frame to which we want to move. There are multiple ways to switch to frames −" }, { "code": null, "e": 1519, "s": 1408, "text": "switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0." }, { "code": null, "e": 1630, "s": 1519, "text": "switchTo().frame(n) - The index of frame is passed as an argument to switch to. The frame index starts from 0." }, { "code": null, "e": 1639, "s": 1630, "text": "Syntax −" }, { "code": null, "e": 1710, "s": 1639, "text": "driver.switchTo().frame(1), we shall switch to the frame with index 1." }, { "code": null, "e": 1795, "s": 1710, "text": "switchTo().frame(name) - The frame id or name is passed as an argument to switch to." }, { "code": null, "e": 1880, "s": 1795, "text": "switchTo().frame(name) - The frame id or name is passed as an argument to switch to." }, { "code": null, "e": 1889, "s": 1880, "text": "Syntax −" }, { "code": null, "e": 1969, "s": 1889, "text": "driver.switchTo().frame(\"fname\"), we shall switch to the frame with name fname." }, { "code": null, "e": 2061, "s": 1969, "text": "switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to." }, { "code": null, "e": 2153, "s": 2061, "text": "switchTo.frame(webelement n) - The frame web element is passed as an argument to switch to." }, { "code": null, "e": 2162, "s": 2153, "text": "Syntax −" }, { "code": null, "e": 2238, "s": 2162, "text": "driver.switchTo().frame(n), we shall switch to the frame with webelement n." }, { "code": null, "e": 2316, "s": 2238, "text": "switchTo().defaultContent() – To switch back to the main page from the frame." }, { "code": null, "e": 2394, "s": 2316, "text": "switchTo().defaultContent() – To switch back to the main page from the frame." }, { "code": null, "e": 2403, "s": 2394, "text": "Syntax −" }, { "code": null, "e": 2438, "s": 2403, "text": "driver.switchTo().defaultContent()" }, { "code": null, "e": 2459, "s": 2438, "text": "Code Implementation." }, { "code": null, "e": 3467, "s": 2459, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class Framehandling{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n String url = \"https://the-internet.herokuapp.com/frames\";\n driver.get(url);\n driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);\n // identify element\n driver.findElement(By.linkText(\"Nested Frames\")).click();\n // switch to frame with frame name and identify inside element\n driver.switchTo().frame(\"frame-bottom\");\n WebElement l = driver.findElement(By.cssSelector(\"body\"));\n System.out.println(\"Bottom frame text: \" +l.getText());\n // switch to main page\n driver.switchTo().defaultContent();\n driver.quit();\n }\n}" } ]
Java ResultSet beforeFirst() method with example
When we execute certain SQL queries (SELECT query in general) they return tabular data. The java.sql.ResultSet interface represents such tabular data returned by the SQL statements. i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general). The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row. The beforeFirst() method of the ResultSet interface moves the pointer of the current (ResultSet) object to the default position (before first), from the current position. Statement stmt = con.createStatement(); ResultSet rs = stmt.executeQuery("Select * from MyPlayers"); Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: CREATE TABLE MyPlayers( ID INT, First_Name VARCHAR(255), Last_Name VARCHAR(255), Date_Of_Birth date, Place_Of_Birth VARCHAR(255), Country VARCHAR(255), PRIMARY KEY (ID) ); Now, we will insert 7 records in MyPlayers table using INSERT statements: insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India'); insert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica'); insert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka'); insert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India'); insert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India'); insert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India'); insert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England'); Following JDBC program establishes connection with the database, retrieves the contents of the table MyPlayers into a ResultSet object, prints its contents, moves the cursor to the default position (before first row) and, prints the contents of the table again. import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; public class ResultSet_beforeFirst { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String mysqlUrl = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(mysqlUrl, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from MyPlayers"; //Executing the query ResultSet rs = stmt.executeQuery(query); System.out.println("Contents of the MyPlayers table: "); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("First_Name")+", "); System.out.print("Age: "+rs.getString("Last_Name")+", "); System.out.print("Salary: "+rs.getDate("Date_Of_Birth")+", "); System.out.print("Country: "+rs.getString("Place_Of_Birth")+", "); System.out.print("Address: "+rs.getString("Country")); System.out.println(); } System.out.println(); //Moving cursor to the default position (before first row). rs.beforeFirst(); System.out.println("Printing the contents of the table again"); while(rs.next()) { System.out.print("ID: "+rs.getInt("ID")+", "); System.out.print("Name: "+rs.getString("First_Name")+", "); System.out.print("Age: "+rs.getString("Last_Name")+", "); System.out.print("Salary: "+rs.getDate("Date_Of_Birth")+", "); System.out.print("Country: "+rs.getString("Place_Of_Birth")+", "); System.out.print("Address: "+rs.getString("Country")); System.out.println(); } } } Connection established...... Contents of the MyPlayers table: ID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India ID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica ID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka ID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India ID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India ID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India ID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England ID: 8, Name: Ryan, Age: McLaren, Salary: 1983-02-09, Country: Kumberly, Address: null printing the contents of the table again ID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India ID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica ID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka ID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India ID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India ID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India ID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England ID: 8, Name: Ryan, Age: McLaren, Salary: 1983-02-09, Country: Kumberly, Address: null
[ { "code": null, "e": 1150, "s": 1062, "text": "When we execute certain SQL queries (SELECT query in general) they return tabular data." }, { "code": null, "e": 1244, "s": 1150, "text": "The java.sql.ResultSet interface represents such tabular data returned by the SQL statements." }, { "code": null, "e": 1434, "s": 1244, "text": "i.e. the ResultSet object holds the tabular data returned by the methods that execute the statements which quires the database (executeQuery() method of the Statement interface in general)." }, { "code": null, "e": 1563, "s": 1434, "text": "The ResultSet object has a cursor/pointer which points to the current row. Initially this cursor is positioned before first row." }, { "code": null, "e": 1734, "s": 1563, "text": "The beforeFirst() method of the ResultSet interface moves the pointer of the current (ResultSet) object to the default position (before first), from the current position." }, { "code": null, "e": 1835, "s": 1734, "text": "Statement stmt = con.createStatement();\nResultSet rs = stmt.executeQuery(\"Select * from MyPlayers\");" }, { "code": null, "e": 1935, "s": 1835, "text": "Let us create a table with name MyPlayers in MySQL database using CREATE statement as shown below: " }, { "code": null, "e": 2128, "s": 1935, "text": "CREATE TABLE MyPlayers(\n ID INT,\n First_Name VARCHAR(255),\n Last_Name VARCHAR(255),\n Date_Of_Birth date,\n Place_Of_Birth VARCHAR(255),\n Country VARCHAR(255),\n PRIMARY KEY (ID)\n);" }, { "code": null, "e": 2202, "s": 2128, "text": "Now, we will insert 7 records in MyPlayers table using INSERT statements:" }, { "code": null, "e": 2864, "s": 2202, "text": "insert into MyPlayers values(1, 'Shikhar', 'Dhawan', DATE('1981-12-05'), 'Delhi', 'India');\ninsert into MyPlayers values(2, 'Jonathan', 'Trott', DATE('1981-04-22'), 'CapeTown', 'SouthAfrica');\ninsert into MyPlayers values(3, 'Kumara', 'Sangakkara', DATE('1977-10-27'), 'Matale', 'Srilanka');\ninsert into MyPlayers values(4, 'Virat', 'Kohli', DATE('1988-11-05'), 'Delhi', 'India');\ninsert into MyPlayers values(5, 'Rohit', 'Sharma', DATE('1987-04-30'), 'Nagpur', 'India');\ninsert into MyPlayers values(6, 'Ravindra', 'Jadeja', DATE('1988-12-06'), 'Nagpur', 'India');\ninsert into MyPlayers values(7, 'James', 'Anderson', DATE('1982-06-30'), 'Burnley', 'England');" }, { "code": null, "e": 3126, "s": 2864, "text": "Following JDBC program establishes connection with the database, retrieves the contents of the table MyPlayers into a ResultSet object, prints its contents, moves the cursor to the default position (before first row) and, prints the contents of the table again." }, { "code": null, "e": 5126, "s": 3126, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.ResultSet;\nimport java.sql.SQLException;\nimport java.sql.Statement;\npublic class ResultSet_beforeFirst {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String mysqlUrl = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(mysqlUrl, \"root\", \"password\");\n System.out.println(\"Connection established......\");\n //Creating the Statement\n Statement stmt = con.createStatement();\n //Query to retrieve records\n String query = \"Select * from MyPlayers\";\n //Executing the query\n ResultSet rs = stmt.executeQuery(query);\n System.out.println(\"Contents of the MyPlayers table: \");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"First_Name\")+\", \");\n System.out.print(\"Age: \"+rs.getString(\"Last_Name\")+\", \");\n System.out.print(\"Salary: \"+rs.getDate(\"Date_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Country\"));\n System.out.println();\n }\n System.out.println();\n //Moving cursor to the default position (before first row).\n rs.beforeFirst();\n System.out.println(\"Printing the contents of the table again\");\n while(rs.next()) {\n System.out.print(\"ID: \"+rs.getInt(\"ID\")+\", \");\n System.out.print(\"Name: \"+rs.getString(\"First_Name\")+\", \");\n System.out.print(\"Age: \"+rs.getString(\"Last_Name\")+\", \");\n System.out.print(\"Salary: \"+rs.getDate(\"Date_Of_Birth\")+\", \");\n System.out.print(\"Country: \"+rs.getString(\"Place_Of_Birth\")+\", \");\n System.out.print(\"Address: \"+rs.getString(\"Country\"));\n System.out.println();\n }\n }\n}" }, { "code": null, "e": 6645, "s": 5126, "text": "Connection established......\nContents of the MyPlayers table:\nID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India\nID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica\nID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka\nID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India\nID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India\nID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India\nID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England\nID: 8, Name: Ryan, Age: McLaren, Salary: 1983-02-09, Country: Kumberly, Address: null\nprinting the contents of the table again\nID: 1, Name: Shikhar, Age: Dhawan, Salary: 1981-12-05, Country: Delhi, Address: India\nID: 2, Name: Jonathan, Age: Trott, Salary: 1981-04-22, Country: CapeTown, Address: SouthAfrica\nID: 3, Name: Kumara, Age: Sangakkara, Salary: 1977-10-27, Country: Matale, Address: Srilanka\nID: 4, Name: Virat, Age: Kohli, Salary: 1988-11-05, Country: Mumbai, Address: India\nID: 5, Name: Rohit, Age: Sharma, Salary: 1987-04-30, Country: Nagpur, Address: India\nID: 6, Name: Ravindra, Age: Jadeja, Salary: 1988-12-06, Country: Nagpur, Address: India\nID: 7, Name: James, Age: Anderson, Salary: 1982-06-30, Country: Burnley , Address: England\nID: 8, Name: Ryan, Age: McLaren, Salary: 1983-02-09, Country: Kumberly, Address: null" } ]
Git - Stash Operation
Suppose you are implementing a new feature for your product. Your code is in progress and suddenly a customer escalation comes. Because of this, you have to keep aside your new feature work for a few hours. You cannot commit your partial code and also cannot throw away your changes. So you need some temporary space, where you can store your partial changes and later on commit it. In Git, the stash operation takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time. [jerry@CentOS project]$ git status -s M string.c ?? string Now, you want to switch branches for customer escalation, but you don’t want to commit what you’ve been working on yet; so you’ll stash the changes. To push a new stash onto your stack, run the git stash command. [jerry@CentOS project]$ git stash Saved working directory and index state WIP on master: e86f062 Added my_strcpy function HEAD is now at e86f062 Added my_strcpy function Now, your working directory is clean and all the changes are saved on a stack. Let us verify it with the git status command. [jerry@CentOS project]$ git status -s ?? string Now you can safely switch the branch and work elsewhere. We can view a list of stashed changes by using the git stash list command. [jerry@CentOS project]$ git stash list stash@{0}: WIP on master: e86f062 Added my_strcpy function Suppose you have resolved the customer escalation and you are back on your new feature looking for your half-done code, just execute the git stash pop command, to remove the changes from the stack and place them in the current working directory. [jerry@CentOS project]$ git status -s ?? string [jerry@CentOS project]$ git stash pop The above command will produce the following result: # On branch master # Changed but not updated: # (use "git add ..." to update what will be committed) # (use "git checkout -- ..." to discard changes in working directory) # # modified: string.c # # Untracked files: # (use "git add ..." to include in what will be committed) # # string no changes added to commit (use "git add" and/or "git commit -a") Dropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4) [jerry@CentOS project]$ git status -s M string.c ?? string 251 Lectures 35.5 hours Gowthami Swarna 23 Lectures 2 hours Asif Hussain 15 Lectures 1.5 hours Abhilash Nelson 125 Lectures 9 hours John Shea 13 Lectures 2.5 hours Raghu Pandey 13 Lectures 3 hours Sebastian Sulinski Print Add Notes Bookmark this page
[ { "code": null, "e": 2428, "s": 2045, "text": "Suppose you are implementing a new feature for your product. Your code is in progress and suddenly a customer escalation comes. Because of this, you have to keep aside your new feature work for a few hours. You cannot commit your partial code and also cannot throw away your changes. So you need some temporary space, where you can store your partial changes and later on commit it." }, { "code": null, "e": 2589, "s": 2428, "text": "In Git, the stash operation takes your modified tracked files, stages changes, and saves them on a stack of unfinished changes that you can reapply at any time." }, { "code": null, "e": 2649, "s": 2589, "text": "[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n" }, { "code": null, "e": 2862, "s": 2649, "text": "Now, you want to switch branches for customer escalation, but you don’t want to commit what you’ve been working on yet; so you’ll stash the changes. To push a new stash onto your stack, run the git stash command." }, { "code": null, "e": 3033, "s": 2862, "text": "[jerry@CentOS project]$ git stash\nSaved working directory and index state WIP on master: e86f062 Added my_strcpy function\nHEAD is now at e86f062 Added my_strcpy function\n" }, { "code": null, "e": 3158, "s": 3033, "text": "Now, your working directory is clean and all the changes are saved on a stack. Let us verify it with the git status command." }, { "code": null, "e": 3207, "s": 3158, "text": "[jerry@CentOS project]$ git status -s\n?? string\n" }, { "code": null, "e": 3339, "s": 3207, "text": "Now you can safely switch the branch and work elsewhere. We can view a list of stashed changes by using the git stash list command." }, { "code": null, "e": 3438, "s": 3339, "text": "[jerry@CentOS project]$ git stash list\nstash@{0}: WIP on master: e86f062 Added my_strcpy function\n" }, { "code": null, "e": 3684, "s": 3438, "text": "Suppose you have resolved the customer escalation and you are back on your new feature looking for your half-done code, just execute the git stash pop command, to remove the changes from the stack and place them in the current working directory." }, { "code": null, "e": 3772, "s": 3684, "text": "[jerry@CentOS project]$ git status -s\n?? string\n\n[jerry@CentOS project]$ git stash pop\n" }, { "code": null, "e": 3825, "s": 3772, "text": "The above command will produce the following result:" }, { "code": null, "e": 4303, "s": 3825, "text": "# On branch master\n# Changed but not updated:\n# (use \"git add ...\" to update what will be committed)\n# (use \"git checkout -- ...\" to discard changes in working directory)\n#\n#\nmodified: string.c\n#\n# Untracked files:\n# (use \"git add ...\" to include in what will be committed)\n#\n#\nstring\nno changes added to commit (use \"git add\" and/or \"git commit -a\")\nDropped refs/stash@{0} (36f79dfedae4ac20e2e8558830154bd6315e72d4)\n\n[jerry@CentOS project]$ git status -s\nM string.c\n?? string\n" }, { "code": null, "e": 4340, "s": 4303, "text": "\n 251 Lectures \n 35.5 hours \n" }, { "code": null, "e": 4357, "s": 4340, "text": " Gowthami Swarna" }, { "code": null, "e": 4390, "s": 4357, "text": "\n 23 Lectures \n 2 hours \n" }, { "code": null, "e": 4404, "s": 4390, "text": " Asif Hussain" }, { "code": null, "e": 4439, "s": 4404, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 4456, "s": 4439, "text": " Abhilash Nelson" }, { "code": null, "e": 4490, "s": 4456, "text": "\n 125 Lectures \n 9 hours \n" }, { "code": null, "e": 4501, "s": 4490, "text": " John Shea" }, { "code": null, "e": 4536, "s": 4501, "text": "\n 13 Lectures \n 2.5 hours \n" }, { "code": null, "e": 4550, "s": 4536, "text": " Raghu Pandey" }, { "code": null, "e": 4583, "s": 4550, "text": "\n 13 Lectures \n 3 hours \n" }, { "code": null, "e": 4603, "s": 4583, "text": " Sebastian Sulinski" }, { "code": null, "e": 4610, "s": 4603, "text": " Print" }, { "code": null, "e": 4621, "s": 4610, "text": " Add Notes" } ]
C program to store the car information using dynamic linked list.
Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes. Node has two parts which are as follows − Data Link The types of linked lists in C programming language are as follows − Single / Singly linked lists Double / Doubly linked lists Circular single linked list Circular double linked list Refer an algorithm given below for storing the car information by using the dynamic linked list. Step 1 − Declare structure variables. Step 2 − Declare Function definition to display. Step 3 − Allocate dynamic memory allocation to variable. Step 4 − Use do while loop to enter the car information. Step 5 − Call display function goto step 2. Following is the C program for storing the car information by using the dynamic linked list − Live Demo #include<stdio.h> #include<stdlib.h> #include<string.h> struct node{ char model[10],color[10]; int year; struct node *next; }; struct node *temp,*head; void display(struct node *head){ temp=head; while(temp!=NULL){ if(temp->year>2010 && (strcmp("yellow",temp->color)==0)) printf(" %s \t\t %s \t\t %d",temp->model,temp->color,temp->year); temp=temp->next; printf("\n"); } } int main(){ int n; char option,enter; head=(struct node *)malloc(sizeof(struct node)); temp=head; do{ printf("\nenter car model: "); scanf("%s",temp->model); printf("enter car color: "); scanf("%s",temp->color); printf("enter car year: "); scanf("%d",&temp->year); printf("\nDo you want continue Y(es) | N(o) : "); scanf("%c",&enter); scanf("%c",&option); if (option!='N'){ temp->next=(struct node *)malloc(sizeof(struct node)); temp=temp->next; } else { temp->next=NULL; } }while(option!='N'); display(head); return 0; } When the above program is executed, it produces the following output − enter car model: I20 enter car color: white enter car year: 2016 Do you want continue Y(es) | N(o) : Y enter car model: verna enter car color: red enter car year: 2018 Do you want continue Y(es) | N(o) : Y enter car model: creta enter car color: Maroon enter car year: 2010 Do you want continue Y(es) | N(o) : N
[ { "code": null, "e": 1171, "s": 1062, "text": "Linked lists use dynamic memory allocation i.e. they grow and shrink accordingly. It is collection of nodes." }, { "code": null, "e": 1213, "s": 1171, "text": "Node has two parts which are as follows −" }, { "code": null, "e": 1218, "s": 1213, "text": "Data" }, { "code": null, "e": 1223, "s": 1218, "text": "Link" }, { "code": null, "e": 1292, "s": 1223, "text": "The types of linked lists in C programming language are as follows −" }, { "code": null, "e": 1321, "s": 1292, "text": "Single / Singly linked lists" }, { "code": null, "e": 1350, "s": 1321, "text": "Double / Doubly linked lists" }, { "code": null, "e": 1378, "s": 1350, "text": "Circular single linked list" }, { "code": null, "e": 1406, "s": 1378, "text": "Circular double linked list" }, { "code": null, "e": 1503, "s": 1406, "text": "Refer an algorithm given below for storing the car information by using the dynamic linked list." }, { "code": null, "e": 1541, "s": 1503, "text": "Step 1 − Declare structure variables." }, { "code": null, "e": 1590, "s": 1541, "text": "Step 2 − Declare Function definition to display." }, { "code": null, "e": 1647, "s": 1590, "text": "Step 3 − Allocate dynamic memory allocation to variable." }, { "code": null, "e": 1704, "s": 1647, "text": "Step 4 − Use do while loop to enter the car information." }, { "code": null, "e": 1748, "s": 1704, "text": "Step 5 − Call display function goto step 2." }, { "code": null, "e": 1842, "s": 1748, "text": "Following is the C program for storing the car information by using the dynamic linked list −" }, { "code": null, "e": 1853, "s": 1842, "text": " Live Demo" }, { "code": null, "e": 2913, "s": 1853, "text": "#include<stdio.h>\n#include<stdlib.h>\n#include<string.h>\nstruct node{\n char model[10],color[10];\n int year;\n struct node *next;\n};\nstruct node *temp,*head;\nvoid display(struct node *head){\n temp=head;\n while(temp!=NULL){\n if(temp->year>2010 && (strcmp(\"yellow\",temp->color)==0))\n printf(\" %s \\t\\t %s \\t\\t %d\",temp->model,temp->color,temp->year);\n temp=temp->next;\n printf(\"\\n\");\n }\n}\nint main(){\n int n;\n char option,enter;\n head=(struct node *)malloc(sizeof(struct node));\n temp=head;\n do{\n printf(\"\\nenter car model: \");\n scanf(\"%s\",temp->model);\n printf(\"enter car color: \");\n scanf(\"%s\",temp->color);\n printf(\"enter car year: \");\n scanf(\"%d\",&temp->year);\n printf(\"\\nDo you want continue Y(es) | N(o) : \");\n scanf(\"%c\",&enter);\n scanf(\"%c\",&option);\n if (option!='N'){\n temp->next=(struct node *)malloc(sizeof(struct node));\n temp=temp->next;\n } else {\n temp->next=NULL;\n }\n }while(option!='N');\n display(head);\n return 0;\n}" }, { "code": null, "e": 2984, "s": 2913, "text": "When the above program is executed, it produces the following output −" }, { "code": null, "e": 3296, "s": 2984, "text": "enter car model: I20\nenter car color: white\nenter car year: 2016\nDo you want continue Y(es) | N(o) : Y\nenter car model: verna\nenter car color: red\nenter car year: 2018\nDo you want continue Y(es) | N(o) : Y\nenter car model: creta\nenter car color: Maroon\nenter car year: 2010\nDo you want continue Y(es) | N(o) : N" } ]
numpy.pad() function in Python
01 Oct, 2020 numpy.pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy.pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width. Syntax: numpy.pad(array, pad_width, mode=’constant’, **kwargs) Parameters : array: the array to pad pad_width: This parameter defines the number of values that are padded to the edges of each axis.mode : str or function(optional) **kwargs: allows you to pass keyword variable length of argument to a function. It is used when we want to handle the named argument in a function. Return:A padded array of rank equal to an array with shape increased according to pad_width. Example 1: Python3 # Python program to explain# working of numpy.pad() functionimport numpy as np arr = [1, 3, 2, 5, 4] # padding array using CONSTANT modepad_arr = np.pad(arr, (3, 2), 'constant', constant_values=(6, 4)) print(pad_arr) Output: [6 6 6 1 3 2 5 4 4 4] Example 2: Python3 # Python program to explain# working of numpy.pad() functionimport numpy as np arr = [1, 3, 2, 5, 4] # padding array using 'linear_ramp' modepad_arr = np.pad(arr, (3, 2), 'linear_ramp', end_values=(-4, 5)) print(pad_arr) Output: [-4 -2 -1 1 3 2 5 4 4 5] Example 3: Python3 # Python program to explain# working of numpy.pad() functionimport numpy as np arr = [1, 3, 9, 5, 4] # padding array using 'maximum' modepad_arr = np.pad(arr, (3,), 'maximum') print(pad_arr) Output: [9 9 9 1 3 9 5 4 9 9 9] Example 4: Python3 # Python program to explain# working of numpy.pad() functionimport numpy as np arr = [[1, 3],[5, 8]] # padding array using 'minimum' modepad_arr = np.pad(arr, (3,), 'minimum') print(pad_arr) Output: [[1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [5 5 5 5 8 5 5 5] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1] [1 1 1 1 3 1 1 1]] Python numpy-arrayCreation Python-numpy 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 Oct, 2020" }, { "code": null, "e": 327, "s": 53, "text": "numpy.pad() function is used to pad the Numpy arrays. Sometimes there is a need to perform padding in Numpy arrays, then numPy.pad() function is used. The function returns the padded array of rank equal to the given array and the shape will increase according to pad_width." }, { "code": null, "e": 391, "s": 327, "text": "Syntax: numpy.pad(array, pad_width, mode=’constant’, **kwargs) " }, { "code": null, "e": 404, "s": 391, "text": "Parameters :" }, { "code": null, "e": 428, "s": 404, "text": "array: the array to pad" }, { "code": null, "e": 558, "s": 428, "text": "pad_width: This parameter defines the number of values that are padded to the edges of each axis.mode : str or function(optional)" }, { "code": null, "e": 706, "s": 558, "text": "**kwargs: allows you to pass keyword variable length of argument to a function. It is used when we want to handle the named argument in a function." }, { "code": null, "e": 799, "s": 706, "text": "Return:A padded array of rank equal to an array with shape increased according to pad_width." }, { "code": null, "e": 810, "s": 799, "text": "Example 1:" }, { "code": null, "e": 818, "s": 810, "text": "Python3" }, { "code": "# Python program to explain# working of numpy.pad() functionimport numpy as np arr = [1, 3, 2, 5, 4] # padding array using CONSTANT modepad_arr = np.pad(arr, (3, 2), 'constant', constant_values=(6, 4)) print(pad_arr)", "e": 1057, "s": 818, "text": null }, { "code": null, "e": 1065, "s": 1057, "text": "Output:" }, { "code": null, "e": 1088, "s": 1065, "text": "[6 6 6 1 3 2 5 4 4 4]\n" }, { "code": null, "e": 1099, "s": 1088, "text": "Example 2:" }, { "code": null, "e": 1107, "s": 1099, "text": "Python3" }, { "code": "# Python program to explain# working of numpy.pad() functionimport numpy as np arr = [1, 3, 2, 5, 4] # padding array using 'linear_ramp' modepad_arr = np.pad(arr, (3, 2), 'linear_ramp', end_values=(-4, 5)) print(pad_arr)", "e": 1353, "s": 1107, "text": null }, { "code": null, "e": 1361, "s": 1353, "text": "Output:" }, { "code": null, "e": 1394, "s": 1361, "text": "[-4 -2 -1 1 3 2 5 4 4 5]\n" }, { "code": null, "e": 1405, "s": 1394, "text": "Example 3:" }, { "code": null, "e": 1413, "s": 1405, "text": "Python3" }, { "code": "# Python program to explain# working of numpy.pad() functionimport numpy as np arr = [1, 3, 9, 5, 4] # padding array using 'maximum' modepad_arr = np.pad(arr, (3,), 'maximum') print(pad_arr)", "e": 1609, "s": 1413, "text": null }, { "code": null, "e": 1617, "s": 1609, "text": "Output:" }, { "code": null, "e": 1642, "s": 1617, "text": "[9 9 9 1 3 9 5 4 9 9 9]\n" }, { "code": null, "e": 1653, "s": 1642, "text": "Example 4:" }, { "code": null, "e": 1661, "s": 1653, "text": "Python3" }, { "code": "# Python program to explain# working of numpy.pad() functionimport numpy as np arr = [[1, 3],[5, 8]] # padding array using 'minimum' modepad_arr = np.pad(arr, (3,), 'minimum') print(pad_arr)", "e": 1865, "s": 1661, "text": null }, { "code": null, "e": 1873, "s": 1865, "text": "Output:" }, { "code": null, "e": 2020, "s": 1873, "text": "[[1 1 1 1 3 1 1 1]\n[1 1 1 1 3 1 1 1]\n[1 1 1 1 3 1 1 1]\n[1 1 1 1 3 1 1 1]\n[5 5 5 5 8 5 5 5]\n[1 1 1 1 3 1 1 1]\n[1 1 1 1 3 1 1 1]\n[1 1 1 1 3 1 1 1]]\n" }, { "code": null, "e": 2047, "s": 2020, "text": "Python numpy-arrayCreation" }, { "code": null, "e": 2060, "s": 2047, "text": "Python-numpy" }, { "code": null, "e": 2067, "s": 2060, "text": "Python" } ]
Python – Split String on all punctuations
02 Sep, 2020 Given a String, Split the String on all the punctuations. Input : test_str = ‘geeksforgeeks! is-best’Output : [‘geeksforgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]Explanation : Splits on ‘!’ and ‘-‘. Input : test_str = ‘geek-sfo, rgeeks! is-best’Output : [‘geek’, ‘-‘, ‘sfo’, ‘, ‘, ‘rgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]Explanation : Splits on ‘!’, ‘, ‘ and ‘-‘. Method : Using regex + findall() This is one way in which this problem can be solved. In this, we construct appropriate regex and task of segregating and split is done by findall(). Python3 # Python3 code to demonstrate working of # Split String on all punctuations# using regex + findall()import re # initializing stringtest_str = 'geeksforgeeks ! is-best, for @geeks' # printing original Stringprint("The original string is : " + str(test_str)) # using findall() to get all regex matches. res = re.findall( r'\w+|[^\s\w]+', test_str) # printing result print("The converted string : " + str(res)) The original string is : geeksforgeeks! is-best, for @geeks The converted string : ['geeksforgeeks', '!', 'is', '-', 'best', ', ', 'for', '@', 'geeks'] Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Sep, 2020" }, { "code": null, "e": 86, "s": 28, "text": "Given a String, Split the String on all the punctuations." }, { "code": null, "e": 216, "s": 86, "text": "Input : test_str = ‘geeksforgeeks! is-best’Output : [‘geeksforgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]Explanation : Splits on ‘!’ and ‘-‘." }, { "code": null, "e": 374, "s": 216, "text": "Input : test_str = ‘geek-sfo, rgeeks! is-best’Output : [‘geek’, ‘-‘, ‘sfo’, ‘, ‘, ‘rgeeks’, ‘!’, ‘is’, ‘-‘, ‘best’]Explanation : Splits on ‘!’, ‘, ‘ and ‘-‘." }, { "code": null, "e": 407, "s": 374, "text": "Method : Using regex + findall()" }, { "code": null, "e": 556, "s": 407, "text": "This is one way in which this problem can be solved. In this, we construct appropriate regex and task of segregating and split is done by findall()." }, { "code": null, "e": 564, "s": 556, "text": "Python3" }, { "code": "# Python3 code to demonstrate working of # Split String on all punctuations# using regex + findall()import re # initializing stringtest_str = 'geeksforgeeks ! is-best, for @geeks' # printing original Stringprint(\"The original string is : \" + str(test_str)) # using findall() to get all regex matches. res = re.findall( r'\\w+|[^\\s\\w]+', test_str) # printing result print(\"The converted string : \" + str(res)) ", "e": 977, "s": 564, "text": null }, { "code": null, "e": 1130, "s": 977, "text": "The original string is : geeksforgeeks! is-best, for @geeks\nThe converted string : ['geeksforgeeks', '!', 'is', '-', 'best', ', ', 'for', '@', 'geeks']\n" }, { "code": null, "e": 1153, "s": 1130, "text": "Python string-programs" }, { "code": null, "e": 1160, "s": 1153, "text": "Python" }, { "code": null, "e": 1176, "s": 1160, "text": "Python Programs" }, { "code": null, "e": 1274, "s": 1176, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1306, "s": 1274, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1333, "s": 1306, "text": "Python Classes and Objects" }, { "code": null, "e": 1354, "s": 1333, "text": "Python OOPs Concepts" }, { "code": null, "e": 1377, "s": 1354, "text": "Introduction To PYTHON" }, { "code": null, "e": 1433, "s": 1377, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 1455, "s": 1433, "text": "Defaultdict in Python" }, { "code": null, "e": 1494, "s": 1455, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1532, "s": 1494, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1569, "s": 1532, "text": "Python Program for Fibonacci numbers" } ]
Python | Combine two dictionary adding values for common keys
31 Mar, 2022 Given two dictionary, the task is to combine the dictionaries such that we get the added values for common keys in resultant dictionary. Example: Input: dict1 = {'a': 12, 'for': 25, 'c': 9} dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} Output: {'for': 325, 'Geeks': 100, 'geek': 200} Let’s see some of the methods to do the task. Method #1: Naive method Python3 # Python program to combine two dictionary# adding values for common keys# initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # adding the values with common keyfor key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass print(dict2) {'for': 325, 'Geeks': 100, 'geek': 200} Method #2: Using collections.Counter() Python3 # Python program to combine two dictionary# adding values for common keysfrom collections import Counter # initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # adding the values with common key Cdict = Counter(dict1) + Counter(dict2)print(Cdict) Counter({'for': 325, 'geek': 200, 'Geeks': 100, 'a': 12, 'c': 9}) Method #3: Using itertools.chain() Python3 # Python program to combine two dictionary# adding values for common keysimport itertoolsimport collections # initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # using defaultdictCdict = collections.defaultdict(int) # iterating key, val with chain()for key, val in itertools.chain(dict1.items(), dict2.items()): Cdict[key] += val print(dict(Cdict)) {'for': 325, 'a': 12, 'geek': 200, 'Geeks': 100, 'c': 9} Method #4: Using functools.reduce and dict comprehension Python3 #Here is another way to combine dictionaies and#sum values of common keys (runs fast): from functools import reduce # creating three dictionaries in a listdict_seq = [ {'a': 1, 'b': 2, 'c': 3}, {'a':10, 'b': 20}, {'b': 100},] print(reduce(lambda d1,d2: {k: d1.get(k,0)+d2.get(k,0)for k in set(d1)|set(d2)}, dict_seq)) Output: {'a': 11, 'b': 122, 'c': 3} mberest sagartomar9927 Marketing Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python | Convert string dictionary to dictionary
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Mar, 2022" }, { "code": null, "e": 202, "s": 54, "text": "Given two dictionary, the task is to combine the dictionaries such that we get the added values for common keys in resultant dictionary. Example: " }, { "code": null, "e": 350, "s": 202, "text": "Input: dict1 = {'a': 12, 'for': 25, 'c': 9}\n dict2 = {'Geeks': 100, 'geek': 200, 'for': 300}\n\nOutput: {'for': 325, 'Geeks': 100, 'geek': 200}" }, { "code": null, "e": 421, "s": 350, "text": "Let’s see some of the methods to do the task. Method #1: Naive method " }, { "code": null, "e": 429, "s": 421, "text": "Python3" }, { "code": "# Python program to combine two dictionary# adding values for common keys# initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # adding the values with common keyfor key in dict2: if key in dict1: dict2[key] = dict2[key] + dict1[key] else: pass print(dict2)", "e": 777, "s": 429, "text": null }, { "code": null, "e": 817, "s": 777, "text": "{'for': 325, 'Geeks': 100, 'geek': 200}" }, { "code": null, "e": 860, "s": 819, "text": " Method #2: Using collections.Counter() " }, { "code": null, "e": 868, "s": 860, "text": "Python3" }, { "code": "# Python program to combine two dictionary# adding values for common keysfrom collections import Counter # initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # adding the values with common key Cdict = Counter(dict1) + Counter(dict2)print(Cdict)", "e": 1185, "s": 868, "text": null }, { "code": null, "e": 1251, "s": 1185, "text": "Counter({'for': 325, 'geek': 200, 'Geeks': 100, 'a': 12, 'c': 9})" }, { "code": null, "e": 1290, "s": 1253, "text": " Method #3: Using itertools.chain() " }, { "code": null, "e": 1298, "s": 1290, "text": "Python3" }, { "code": "# Python program to combine two dictionary# adding values for common keysimport itertoolsimport collections # initializing two dictionariesdict1 = {'a': 12, 'for': 25, 'c': 9}dict2 = {'Geeks': 100, 'geek': 200, 'for': 300} # using defaultdictCdict = collections.defaultdict(int) # iterating key, val with chain()for key, val in itertools.chain(dict1.items(), dict2.items()): Cdict[key] += val print(dict(Cdict))", "e": 1717, "s": 1298, "text": null }, { "code": null, "e": 1774, "s": 1717, "text": "{'for': 325, 'a': 12, 'geek': 200, 'Geeks': 100, 'c': 9}" }, { "code": null, "e": 1835, "s": 1776, "text": " Method #4: Using functools.reduce and dict comprehension" }, { "code": null, "e": 1843, "s": 1835, "text": "Python3" }, { "code": "#Here is another way to combine dictionaies and#sum values of common keys (runs fast): from functools import reduce # creating three dictionaries in a listdict_seq = [ {'a': 1, 'b': 2, 'c': 3}, {'a':10, 'b': 20}, {'b': 100},] print(reduce(lambda d1,d2: {k: d1.get(k,0)+d2.get(k,0)for k in set(d1)|set(d2)}, dict_seq))", "e": 2165, "s": 1843, "text": null }, { "code": null, "e": 2173, "s": 2165, "text": "Output:" }, { "code": null, "e": 2201, "s": 2173, "text": "{'a': 11, 'b': 122, 'c': 3}" }, { "code": null, "e": 2209, "s": 2201, "text": "mberest" }, { "code": null, "e": 2224, "s": 2209, "text": "sagartomar9927" }, { "code": null, "e": 2234, "s": 2224, "text": "Marketing" }, { "code": null, "e": 2261, "s": 2234, "text": "Python dictionary-programs" }, { "code": null, "e": 2268, "s": 2261, "text": "Python" }, { "code": null, "e": 2284, "s": 2268, "text": "Python Programs" }, { "code": null, "e": 2382, "s": 2284, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2414, "s": 2382, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2441, "s": 2414, "text": "Python Classes and Objects" }, { "code": null, "e": 2462, "s": 2441, "text": "Python OOPs Concepts" }, { "code": null, "e": 2485, "s": 2462, "text": "Introduction To PYTHON" }, { "code": null, "e": 2541, "s": 2485, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2563, "s": 2541, "text": "Defaultdict in Python" }, { "code": null, "e": 2602, "s": 2563, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2640, "s": 2602, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 2677, "s": 2640, "text": "Python Program for Fibonacci numbers" } ]
Wrapper Classes in Java
06 Aug, 2020 A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object. Need of Wrapper Classes They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).The classes in java.util package handles only objects and hence wrapper classes help in this case also.Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.An object is needed to support synchronization in multithreading. They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value). The classes in java.util package handles only objects and hence wrapper classes help in this case also. Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types. An object is needed to support synchronization in multithreading. Primitive Data types and their Corresponding Wrapper class Autoboxing and Unboxing Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.Example: // Java program to demonstrate Autoboxing import java.util.ArrayList;class Autoboxing{ public static void main(String[] args) { char ch = 'a'; // Autoboxing- primitive to Character object conversion Character a = ch; ArrayList<Integer> arrayList = new ArrayList<Integer>(); // Autoboxing because ArrayList stores only objects arrayList.add(25); // printing the values from object System.out.println(arrayList.get(0)); }} Output: 25 Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc. // Java program to demonstrate Unboxingimport java.util.ArrayList; class Unboxing{ public static void main(String[] args) { Character ch = 'a'; // unboxing - Character object to primitive conversion char a = ch; ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(24); // unboxing because get method returns an Integer object int num = arrayList.get(0); // printing the values from primitive data types System.out.println(num); }} Output: 24 Implementation // Java program to demonstrate Wrapping and UnWrapping// in Java Classesclass WrappingUnwrapping{ public static void main(String args[]) { // byte data type byte a = 1; // wrapping around Byte object Byte byteobj = new Byte(a); // int data type int b = 10; //wrapping around Integer object Integer intobj = new Integer(b); // float data type float c = 18.6f; // wrapping around Float object Float floatobj = new Float(c); // double data type double d = 250.5; // Wrapping around Double object Double doubleobj = new Double(d); // char data type char e='a'; // wrapping around Character object Character charobj=e; // printing the values from objects System.out.println("Values of Wrapper objects (printing as objects)"); System.out.println("Byte object byteobj: " + byteobj); System.out.println("Integer object intobj: " + intobj); System.out.println("Float object floatobj: " + floatobj); System.out.println("Double object doubleobj: " + doubleobj); System.out.println("Character object charobj: " + charobj); // objects to data types (retrieving data types from objects) // unwrapping objects to primitive data types byte bv = byteobj; int iv = intobj; float fv = floatobj; double dv = doubleobj; char cv = charobj; // printing the values from data types System.out.println("Unwrapped values (printing as data types)"); System.out.println("byte value, bv: " + bv); System.out.println("int value, iv: " + iv); System.out.println("float value, fv: " + fv); System.out.println("double value, dv: " + dv); System.out.println("char value, cv: " + cv); }} Output: Values of Wrapper objects (printing as objects) Byte object byteobj: 1 Integer object intobj: 10 Float object floatobj: 18.6 Double object doubleobj: 250.5 Character object charobj: a Unwrapped values (printing as data types) byte value, bv: 1 int value, iv: 10 float value, fv: 18.6 double value, dv: 250.5 char value, cv: a Related Article :Comparison of Autoboxed Integer objects in Java This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. PasinduSiriwardana java-wrapper-class Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Split() String method in Java with examples Arrays.sort() in Java with examples Reverse a string in Java How to iterate any Map in Java Stream In Java Singleton Class in Java Initialize an ArrayList in Java Initializing a List in Java Generics in Java Java Programming Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n06 Aug, 2020" }, { "code": null, "e": 328, "s": 54, "text": "A Wrapper class is a class whose object wraps or contains primitive data types. When we create an object to a wrapper class, it contains a field and in this field, we can store primitive data types. In other words, we can wrap a primitive value into a wrapper class object." }, { "code": null, "e": 352, "s": 328, "text": "Need of Wrapper Classes" }, { "code": null, "e": 826, "s": 352, "text": "They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value).The classes in java.util package handles only objects and hence wrapper classes help in this case also.Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types.An object is needed to support synchronization in multithreading." }, { "code": null, "e": 996, "s": 826, "text": "They convert primitive data types into objects. Objects are needed if we wish to modify the arguments passed into a method (because primitive types are passed by value)." }, { "code": null, "e": 1100, "s": 996, "text": "The classes in java.util package handles only objects and hence wrapper classes help in this case also." }, { "code": null, "e": 1237, "s": 1100, "text": "Data structures in the Collection framework, such as ArrayList and Vector, store only objects (reference types) and not primitive types." }, { "code": null, "e": 1303, "s": 1237, "text": "An object is needed to support synchronization in multithreading." }, { "code": null, "e": 1362, "s": 1303, "text": "Primitive Data types and their Corresponding Wrapper class" }, { "code": null, "e": 1386, "s": 1362, "text": "Autoboxing and Unboxing" }, { "code": null, "e": 1603, "s": 1386, "text": "Autoboxing: Automatic conversion of primitive types to the object of their corresponding wrapper classes is known as autoboxing. For example – conversion of int to Integer, long to Long, double to Double etc.Example:" }, { "code": "// Java program to demonstrate Autoboxing import java.util.ArrayList;class Autoboxing{ public static void main(String[] args) { char ch = 'a'; // Autoboxing- primitive to Character object conversion Character a = ch; ArrayList<Integer> arrayList = new ArrayList<Integer>(); // Autoboxing because ArrayList stores only objects arrayList.add(25); // printing the values from object System.out.println(arrayList.get(0)); }}", "e": 2098, "s": 1603, "text": null }, { "code": null, "e": 2106, "s": 2098, "text": "Output:" }, { "code": null, "e": 2109, "s": 2106, "text": "25" }, { "code": null, "e": 2358, "s": 2109, "text": "Unboxing: It is just the reverse process of autoboxing. Automatically converting an object of a wrapper class to its corresponding primitive type is known as unboxing. For example – conversion of Integer to int, Long to long, Double to double, etc." }, { "code": "// Java program to demonstrate Unboxingimport java.util.ArrayList; class Unboxing{ public static void main(String[] args) { Character ch = 'a'; // unboxing - Character object to primitive conversion char a = ch; ArrayList<Integer> arrayList = new ArrayList<Integer>(); arrayList.add(24); // unboxing because get method returns an Integer object int num = arrayList.get(0); // printing the values from primitive data types System.out.println(num); }}", "e": 2889, "s": 2358, "text": null }, { "code": null, "e": 2897, "s": 2889, "text": "Output:" }, { "code": null, "e": 2900, "s": 2897, "text": "24" }, { "code": null, "e": 2915, "s": 2900, "text": "Implementation" }, { "code": "// Java program to demonstrate Wrapping and UnWrapping// in Java Classesclass WrappingUnwrapping{ public static void main(String args[]) { // byte data type byte a = 1; // wrapping around Byte object Byte byteobj = new Byte(a); // int data type int b = 10; //wrapping around Integer object Integer intobj = new Integer(b); // float data type float c = 18.6f; // wrapping around Float object Float floatobj = new Float(c); // double data type double d = 250.5; // Wrapping around Double object Double doubleobj = new Double(d); // char data type char e='a'; // wrapping around Character object Character charobj=e; // printing the values from objects System.out.println(\"Values of Wrapper objects (printing as objects)\"); System.out.println(\"Byte object byteobj: \" + byteobj); System.out.println(\"Integer object intobj: \" + intobj); System.out.println(\"Float object floatobj: \" + floatobj); System.out.println(\"Double object doubleobj: \" + doubleobj); System.out.println(\"Character object charobj: \" + charobj); // objects to data types (retrieving data types from objects) // unwrapping objects to primitive data types byte bv = byteobj; int iv = intobj; float fv = floatobj; double dv = doubleobj; char cv = charobj; // printing the values from data types System.out.println(\"Unwrapped values (printing as data types)\"); System.out.println(\"byte value, bv: \" + bv); System.out.println(\"int value, iv: \" + iv); System.out.println(\"float value, fv: \" + fv); System.out.println(\"double value, dv: \" + dv); System.out.println(\"char value, cv: \" + cv); }}", "e": 4794, "s": 2915, "text": null }, { "code": null, "e": 4802, "s": 4794, "text": "Output:" }, { "code": null, "e": 5133, "s": 4802, "text": "Values of Wrapper objects (printing as objects)\nByte object byteobj: 1\nInteger object intobj: 10\nFloat object floatobj: 18.6\nDouble object doubleobj: 250.5\nCharacter object charobj: a\nUnwrapped values (printing as data types)\nbyte value, bv: 1\nint value, iv: 10\nfloat value, fv: 18.6\ndouble value, dv: 250.5\nchar value, cv: a\n" }, { "code": null, "e": 5198, "s": 5133, "text": "Related Article :Comparison of Autoboxed Integer objects in Java" }, { "code": null, "e": 5500, "s": 5198, "text": "This article is contributed by Nishant Sharma. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 5625, "s": 5500, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 5644, "s": 5625, "text": "PasinduSiriwardana" }, { "code": null, "e": 5663, "s": 5644, "text": "java-wrapper-class" }, { "code": null, "e": 5668, "s": 5663, "text": "Java" }, { "code": null, "e": 5673, "s": 5668, "text": "Java" }, { "code": null, "e": 5771, "s": 5673, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5815, "s": 5771, "text": "Split() String method in Java with examples" }, { "code": null, "e": 5851, "s": 5815, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 5876, "s": 5851, "text": "Reverse a string in Java" }, { "code": null, "e": 5907, "s": 5876, "text": "How to iterate any Map in Java" }, { "code": null, "e": 5922, "s": 5907, "text": "Stream In Java" }, { "code": null, "e": 5946, "s": 5922, "text": "Singleton Class in Java" }, { "code": null, "e": 5978, "s": 5946, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 6006, "s": 5978, "text": "Initializing a List in Java" }, { "code": null, "e": 6023, "s": 6006, "text": "Generics in Java" } ]
Phishing Attack
29 Dec, 2020 Phishing is a type of cybersecurity attack that attempts to obtain data that are sensitive like Username, Password, and more. It attacks the user through mail, text, or direct messages. Now the attachment sends by the attacker is opened by the user because the user thinks that the email, text, messages came from a trusted source. It is a type of Social Engineering Attack. For Example, The user may find some messages like the lottery winner. When the user clicks on the attachment the malicious code activates that can access sensitive information details. Or if the user clicks on the link that was sent in the attachment they may be redirected to a different website that will ask for the login credentials of the bank. Types of Phishing Attack : Spear Phishing –This attack is used to target any specific organization or an individual for unauthorized access. These types of attacks are not initiated by any random hacker, but these attacks are initiated by someone who seeks information related to financial gain or some important information. Just like the phishing attack spear-phishing also comes from a trusted source. This type of attack is much successful. It is considered to be one of the most successful methods as both of the attacks(that is phishing and spear-phishing) is an online attack on users.Clone Phishing –This attack is actually based on copying the email messages that were sent from a trusted source. Now the hackers alter the information by adding a link that redirects the user to a malicious or fake website. Now, this is sent to a large number of users and the person who initiated it watches who clicks on the attachment that was sent as a mail. This spreads through the contacts of the user who has clicked on the attachment.Catphishing –It is a type of social engineering attack that plays with the emotions of a person and exploits them to gain money and information. They target them through dating sites. It is a type of engineering threat.Voice Phishing –Some attacks require to direct the user through fake websites, but some attacks do not require a fake website. This type of attack is sometimes referred to as vishing. Someone who is using the method of vishing, use modern caller id spoofing to convince the victim that the call is from a trusted source. They also use IVR to make it difficult for the legal authorities to trace, block, monitor. It is used to steal credit card numbers or some confidential data of the user. This type of phishing can cause more harm.SMS phishing –These attacks are used to make the user revealing account information. This attack is also similar to the phishing attack used by cybercriminals to steal credit card details or sensitive information, by making it look like it came from a trusted organization. Cybercriminals use text messages to get personal information by trying to redirect them to a fake website. This fake website looks like that it is an original website. Spear Phishing –This attack is used to target any specific organization or an individual for unauthorized access. These types of attacks are not initiated by any random hacker, but these attacks are initiated by someone who seeks information related to financial gain or some important information. Just like the phishing attack spear-phishing also comes from a trusted source. This type of attack is much successful. It is considered to be one of the most successful methods as both of the attacks(that is phishing and spear-phishing) is an online attack on users. Clone Phishing –This attack is actually based on copying the email messages that were sent from a trusted source. Now the hackers alter the information by adding a link that redirects the user to a malicious or fake website. Now, this is sent to a large number of users and the person who initiated it watches who clicks on the attachment that was sent as a mail. This spreads through the contacts of the user who has clicked on the attachment. Catphishing –It is a type of social engineering attack that plays with the emotions of a person and exploits them to gain money and information. They target them through dating sites. It is a type of engineering threat. Voice Phishing –Some attacks require to direct the user through fake websites, but some attacks do not require a fake website. This type of attack is sometimes referred to as vishing. Someone who is using the method of vishing, use modern caller id spoofing to convince the victim that the call is from a trusted source. They also use IVR to make it difficult for the legal authorities to trace, block, monitor. It is used to steal credit card numbers or some confidential data of the user. This type of phishing can cause more harm. SMS phishing –These attacks are used to make the user revealing account information. This attack is also similar to the phishing attack used by cybercriminals to steal credit card details or sensitive information, by making it look like it came from a trusted organization. Cybercriminals use text messages to get personal information by trying to redirect them to a fake website. This fake website looks like that it is an original website. As android phones or smartphones are mostly used by the user, cybercriminals use this opportunity to perform this type of attack. Because they don’t have to go through the trouble of breaking firewalls and then accessing the system of the user to steal data. Symptoms of the phishing : It may request the user to share personal details like the login credentials related to the bank and more. It redirects to a website if the user clicks on the link that was sent in the email. If they are redirected to a website it may want some information related to the credit card or banking details of the user. Preventive measures of phishing : Do not try to open any suspicious email attachments. Do not try to open any link which may seem suspicious. Do not try to provide any sensitive information like personal information or banking information via email, text, or messages. Always the user should have an antivirus to make sure the system is affected by the system or not. Information-Security Computer Networks Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Wireless Application Protocol GSM in Wireless Communication Secure Socket Layer (SSL) Mobile Internet Protocol (or Mobile IP) Advanced Encryption Standard (AES) Introduction of Mobile Ad hoc Network (MANET) Difference between MANET and VANET Difference between FDMA, TDMA and CDMA Cryptography and its Types Dynamic Host Configuration Protocol (DHCP)
[ { "code": null, "e": 52, "s": 24, "text": "\n29 Dec, 2020" }, { "code": null, "e": 777, "s": 52, "text": "Phishing is a type of cybersecurity attack that attempts to obtain data that are sensitive like Username, Password, and more. It attacks the user through mail, text, or direct messages. Now the attachment sends by the attacker is opened by the user because the user thinks that the email, text, messages came from a trusted source. It is a type of Social Engineering Attack. For Example, The user may find some messages like the lottery winner. When the user clicks on the attachment the malicious code activates that can access sensitive information details. Or if the user clicks on the link that was sent in the attachment they may be redirected to a different website that will ask for the login credentials of the bank." }, { "code": null, "e": 804, "s": 777, "text": "Types of Phishing Attack :" }, { "code": null, "e": 3007, "s": 804, "text": "Spear Phishing –This attack is used to target any specific organization or an individual for unauthorized access. These types of attacks are not initiated by any random hacker, but these attacks are initiated by someone who seeks information related to financial gain or some important information. Just like the phishing attack spear-phishing also comes from a trusted source. This type of attack is much successful. It is considered to be one of the most successful methods as both of the attacks(that is phishing and spear-phishing) is an online attack on users.Clone Phishing –This attack is actually based on copying the email messages that were sent from a trusted source. Now the hackers alter the information by adding a link that redirects the user to a malicious or fake website. Now, this is sent to a large number of users and the person who initiated it watches who clicks on the attachment that was sent as a mail. This spreads through the contacts of the user who has clicked on the attachment.Catphishing –It is a type of social engineering attack that plays with the emotions of a person and exploits them to gain money and information. They target them through dating sites. It is a type of engineering threat.Voice Phishing –Some attacks require to direct the user through fake websites, but some attacks do not require a fake website. This type of attack is sometimes referred to as vishing. Someone who is using the method of vishing, use modern caller id spoofing to convince the victim that the call is from a trusted source. They also use IVR to make it difficult for the legal authorities to trace, block, monitor. It is used to steal credit card numbers or some confidential data of the user. This type of phishing can cause more harm.SMS phishing –These attacks are used to make the user revealing account information. This attack is also similar to the phishing attack used by cybercriminals to steal credit card details or sensitive information, by making it look like it came from a trusted organization. Cybercriminals use text messages to get personal information by trying to redirect them to a fake website. This fake website looks like that it is an original website." }, { "code": null, "e": 3573, "s": 3007, "text": "Spear Phishing –This attack is used to target any specific organization or an individual for unauthorized access. These types of attacks are not initiated by any random hacker, but these attacks are initiated by someone who seeks information related to financial gain or some important information. Just like the phishing attack spear-phishing also comes from a trusted source. This type of attack is much successful. It is considered to be one of the most successful methods as both of the attacks(that is phishing and spear-phishing) is an online attack on users." }, { "code": null, "e": 4018, "s": 3573, "text": "Clone Phishing –This attack is actually based on copying the email messages that were sent from a trusted source. Now the hackers alter the information by adding a link that redirects the user to a malicious or fake website. Now, this is sent to a large number of users and the person who initiated it watches who clicks on the attachment that was sent as a mail. This spreads through the contacts of the user who has clicked on the attachment." }, { "code": null, "e": 4238, "s": 4018, "text": "Catphishing –It is a type of social engineering attack that plays with the emotions of a person and exploits them to gain money and information. They target them through dating sites. It is a type of engineering threat." }, { "code": null, "e": 4772, "s": 4238, "text": "Voice Phishing –Some attacks require to direct the user through fake websites, but some attacks do not require a fake website. This type of attack is sometimes referred to as vishing. Someone who is using the method of vishing, use modern caller id spoofing to convince the victim that the call is from a trusted source. They also use IVR to make it difficult for the legal authorities to trace, block, monitor. It is used to steal credit card numbers or some confidential data of the user. This type of phishing can cause more harm." }, { "code": null, "e": 5214, "s": 4772, "text": "SMS phishing –These attacks are used to make the user revealing account information. This attack is also similar to the phishing attack used by cybercriminals to steal credit card details or sensitive information, by making it look like it came from a trusted organization. Cybercriminals use text messages to get personal information by trying to redirect them to a fake website. This fake website looks like that it is an original website." }, { "code": null, "e": 5473, "s": 5214, "text": "As android phones or smartphones are mostly used by the user, cybercriminals use this opportunity to perform this type of attack. Because they don’t have to go through the trouble of breaking firewalls and then accessing the system of the user to steal data." }, { "code": null, "e": 5500, "s": 5473, "text": "Symptoms of the phishing :" }, { "code": null, "e": 5607, "s": 5500, "text": "It may request the user to share personal details like the login credentials related to the bank and more." }, { "code": null, "e": 5692, "s": 5607, "text": "It redirects to a website if the user clicks on the link that was sent in the email." }, { "code": null, "e": 5816, "s": 5692, "text": "If they are redirected to a website it may want some information related to the credit card or banking details of the user." }, { "code": null, "e": 5850, "s": 5816, "text": "Preventive measures of phishing :" }, { "code": null, "e": 5903, "s": 5850, "text": "Do not try to open any suspicious email attachments." }, { "code": null, "e": 5958, "s": 5903, "text": "Do not try to open any link which may seem suspicious." }, { "code": null, "e": 6085, "s": 5958, "text": "Do not try to provide any sensitive information like personal information or banking information via email, text, or messages." }, { "code": null, "e": 6184, "s": 6085, "text": "Always the user should have an antivirus to make sure the system is affected by the system or not." }, { "code": null, "e": 6205, "s": 6184, "text": "Information-Security" }, { "code": null, "e": 6223, "s": 6205, "text": "Computer Networks" }, { "code": null, "e": 6241, "s": 6223, "text": "Computer Networks" }, { "code": null, "e": 6339, "s": 6241, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 6369, "s": 6339, "text": "Wireless Application Protocol" }, { "code": null, "e": 6399, "s": 6369, "text": "GSM in Wireless Communication" }, { "code": null, "e": 6425, "s": 6399, "text": "Secure Socket Layer (SSL)" }, { "code": null, "e": 6465, "s": 6425, "text": "Mobile Internet Protocol (or Mobile IP)" }, { "code": null, "e": 6500, "s": 6465, "text": "Advanced Encryption Standard (AES)" }, { "code": null, "e": 6546, "s": 6500, "text": "Introduction of Mobile Ad hoc Network (MANET)" }, { "code": null, "e": 6581, "s": 6546, "text": "Difference between MANET and VANET" }, { "code": null, "e": 6620, "s": 6581, "text": "Difference between FDMA, TDMA and CDMA" }, { "code": null, "e": 6647, "s": 6620, "text": "Cryptography and its Types" } ]
Python – Group Similar keys in dictionary
22 Apr, 2020 Sometimes while working with dictionary data, we can have problems in which we need to perform grouping based on substring of keys and reform the data grouped on similar keys. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed. Method #1 : Using loopThis is brute way in which we perform this task. In this, we check for element using conditional statement and insert the keys according to substring presence. # Python3 code to demonstrate working of # Group Similar keys in dictionary# Using loop # initializing Dictionarytest_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3, 'gfg2' : 9, 'is2' : 8, 'best2' : 7, 'gfg3' : 10, 'is3' : 5, 'best3' : 6} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Group Similar keys in dictionary# Using loopres = []res1, res2, res3 = {}, {}, {}for key, value in test_dict.items(): if 'gfg' in key: res1[key] = value elif 'is' in key: res2[key] = value elif 'best' in key: res3[key] = value res.append(res1)res.append(res2)res.append(res3) # printing result print("The grouped similar keys are : " + str(res)) The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}] Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. In this, we group the substring to keys using dictionary comprehension. # Python3 code to demonstrate working of # Group Similar keys in dictionary# Using dictionary comprehension # initializing Dictionarytest_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3, 'gfg2' : 9, 'is2' : 8, 'best2' : 7, 'gfg3' : 10, 'is3' : 5, 'best3' : 6} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # Group Similar keys in dictionary# Using dictionaryres = []res1 = {key : val for key, val in test_dict.items() if 'gfg' in key}res2 = {key : val for key, val in test_dict.items() if 'is' in key}res3 = {key : val for key, val in test_dict.items() if 'best' in key}res.append(res1)res.append(res2)res.append(res3) # printing result print("The grouped similar keys are : " + str(res)) The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}] Python dictionary-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Apr, 2020" }, { "code": null, "e": 316, "s": 28, "text": "Sometimes while working with dictionary data, we can have problems in which we need to perform grouping based on substring of keys and reform the data grouped on similar keys. This can have application in data preprocessing. Lets discuss certain ways in which this task can be performed." }, { "code": null, "e": 498, "s": 316, "text": "Method #1 : Using loopThis is brute way in which we perform this task. In this, we check for element using conditional statement and insert the keys according to substring presence." }, { "code": "# Python3 code to demonstrate working of # Group Similar keys in dictionary# Using loop # initializing Dictionarytest_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3, 'gfg2' : 9, 'is2' : 8, 'best2' : 7, 'gfg3' : 10, 'is3' : 5, 'best3' : 6} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Group Similar keys in dictionary# Using loopres = []res1, res2, res3 = {}, {}, {}for key, value in test_dict.items(): if 'gfg' in key: res1[key] = value elif 'is' in key: res2[key] = value elif 'best' in key: res3[key] = value res.append(res1)res.append(res2)res.append(res3) # printing result print(\"The grouped similar keys are : \" + str(res)) ", "e": 1208, "s": 498, "text": null }, { "code": null, "e": 1475, "s": 1208, "text": "The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}]" }, { "code": null, "e": 1652, "s": 1477, "text": "Method #2 : Using dictionary comprehensionThis is yet another way in which this task can be performed. In this, we group the substring to keys using dictionary comprehension." }, { "code": "# Python3 code to demonstrate working of # Group Similar keys in dictionary# Using dictionary comprehension # initializing Dictionarytest_dict = {'gfg1' : 1, 'is1' : 2, 'best1' : 3, 'gfg2' : 9, 'is2' : 8, 'best2' : 7, 'gfg3' : 10, 'is3' : 5, 'best3' : 6} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # Group Similar keys in dictionary# Using dictionaryres = []res1 = {key : val for key, val in test_dict.items() if 'gfg' in key}res2 = {key : val for key, val in test_dict.items() if 'is' in key}res3 = {key : val for key, val in test_dict.items() if 'best' in key}res.append(res1)res.append(res2)res.append(res3) # printing result print(\"The grouped similar keys are : \" + str(res)) ", "e": 2404, "s": 1652, "text": null }, { "code": null, "e": 2671, "s": 2404, "text": "The original dictionary is : {‘best2’: 7, ‘best3’: 6, ‘is2’: 8, ‘is3’: 5, ‘best1’: 3, ‘gfg1’: 1, ‘gfg3’: 10, ‘is1’: 2, ‘gfg2’: 9}The grouped similar keys are : [{‘gfg3’: 10, ‘gfg2’: 9, ‘gfg1’: 1}, {‘is2’: 8, ‘is3’: 5, ‘is1’: 2}, {‘best3’: 6, ‘best1’: 3, ‘best2’: 7}]" }, { "code": null, "e": 2698, "s": 2671, "text": "Python dictionary-programs" }, { "code": null, "e": 2705, "s": 2698, "text": "Python" }, { "code": null, "e": 2721, "s": 2705, "text": "Python Programs" }, { "code": null, "e": 2819, "s": 2721, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2837, "s": 2819, "text": "Python Dictionary" }, { "code": null, "e": 2879, "s": 2837, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2901, "s": 2879, "text": "Enumerate() in Python" }, { "code": null, "e": 2936, "s": 2901, "text": "Read a file line by line in Python" }, { "code": null, "e": 2968, "s": 2936, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3011, "s": 2968, "text": "Python program to convert a list to string" }, { "code": null, "e": 3033, "s": 3011, "text": "Defaultdict in Python" }, { "code": null, "e": 3072, "s": 3033, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 3110, "s": 3072, "text": "Python | Convert a list to dictionary" } ]
HTML | onload Event Attribute
08 Aug, 2021 This attribute works when an object has been loaded. This attribute mostly used within the <body> element to execute a script. It can be used with other elements as well. This attribute is used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.Supported Tags: <body> <frame> <frameset> <iframe> <img> <input type=”image”> <link> <script> <style> Syntax: <element onload = "script"> Attribute Value: This attribute contains single value script and it runs when onload event triggered. This attribute is associated with many HTML elements.Example 1: html <!DOCTYPE html><html> <head> <title>onload event attribute</title> <script> function Function() { alert("Page is loaded"); } </script> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body onload="Function()"> <h1>GeeksforGeeks</h1> <h2>onload event attribute</h2> </body></html> Output: Example 2: html <!DOCTYPE html><html> <head> <title>onload event attribute</title> </head> <body> <img src="https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png" onload="loadImage()" width="500" height="132"> <script> function loadImage() { alert("Image loaded successfully"); } </script> </body></html> Output: Supported Browsers: The browser supported by onload attribute are listed below: Chrome Internet Explorer Firefox Safari Opera hritikbhatnagar2182 HTML-Attributes CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n08 Aug, 2021" }, { "code": null, "e": 390, "s": 53, "text": "This attribute works when an object has been loaded. This attribute mostly used within the <body> element to execute a script. It can be used with other elements as well. This attribute is used to check the visitor’s browser type and browser version, and load the proper version of the web page based on the information.Supported Tags: " }, { "code": null, "e": 397, "s": 390, "text": "<body>" }, { "code": null, "e": 405, "s": 397, "text": "<frame>" }, { "code": null, "e": 416, "s": 405, "text": "<frameset>" }, { "code": null, "e": 425, "s": 416, "text": "<iframe>" }, { "code": null, "e": 431, "s": 425, "text": "<img>" }, { "code": null, "e": 452, "s": 431, "text": "<input type=”image”>" }, { "code": null, "e": 459, "s": 452, "text": "<link>" }, { "code": null, "e": 468, "s": 459, "text": "<script>" }, { "code": null, "e": 476, "s": 468, "text": "<style>" }, { "code": null, "e": 486, "s": 476, "text": "Syntax: " }, { "code": null, "e": 514, "s": 486, "text": "<element onload = \"script\">" }, { "code": null, "e": 682, "s": 514, "text": "Attribute Value: This attribute contains single value script and it runs when onload event triggered. This attribute is associated with many HTML elements.Example 1: " }, { "code": null, "e": 687, "s": 682, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>onload event attribute</title> <script> function Function() { alert(\"Page is loaded\"); } </script> <style> body { text-align:center; } h1 { color:green; } </style> </head> <body onload=\"Function()\"> <h1>GeeksforGeeks</h1> <h2>onload event attribute</h2> </body></html>", "e": 1152, "s": 687, "text": null }, { "code": null, "e": 1162, "s": 1152, "text": "Output: " }, { "code": null, "e": 1175, "s": 1162, "text": "Example 2: " }, { "code": null, "e": 1180, "s": 1175, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>onload event attribute</title> </head> <body> <img src=\"https://media.geeksforgeeks.org/wp-content/uploads/geeksforgeeks-9.png\" onload=\"loadImage()\" width=\"500\" height=\"132\"> <script> function loadImage() { alert(\"Image loaded successfully\"); } </script> </body></html> ", "e": 1589, "s": 1180, "text": null }, { "code": null, "e": 1599, "s": 1589, "text": "Output: " }, { "code": null, "e": 1681, "s": 1599, "text": "Supported Browsers: The browser supported by onload attribute are listed below: " }, { "code": null, "e": 1688, "s": 1681, "text": "Chrome" }, { "code": null, "e": 1706, "s": 1688, "text": "Internet Explorer" }, { "code": null, "e": 1714, "s": 1706, "text": "Firefox" }, { "code": null, "e": 1721, "s": 1714, "text": "Safari" }, { "code": null, "e": 1727, "s": 1721, "text": "Opera" }, { "code": null, "e": 1749, "s": 1729, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1765, "s": 1749, "text": "HTML-Attributes" }, { "code": null, "e": 1769, "s": 1765, "text": "CSS" }, { "code": null, "e": 1774, "s": 1769, "text": "HTML" }, { "code": null, "e": 1791, "s": 1774, "text": "Web Technologies" }, { "code": null, "e": 1796, "s": 1791, "text": "HTML" } ]
WebGL - Modes of Drawing
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.
[ { "code": null, "e": 2398, "s": 2181, "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": 2481, "s": 2398, "text": "Let’s take a look at the syntax of the methods − drawElements() and draw Arrays()." }, { "code": null, "e": 2600, "s": 2481, "text": "void drawElements(enum mode, long count, enum type, long offset);\n\nvoid drawArrays(enum mode, int first, long count);\n" }, { "code": null, "e": 2742, "s": 2600, "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": 2813, "s": 2742, "text": "The drawing modes provided by WebGL are listed in the following table." }, { "code": null, "e": 2823, "s": 2813, "text": "gl.POINTS" }, { "code": null, "e": 2851, "s": 2823, "text": "To draw a series of points." }, { "code": null, "e": 2860, "s": 2851, "text": "gl.LINES" }, { "code": null, "e": 2926, "s": 2860, "text": "To draw a series of unconnected line segments (individual lines)." }, { "code": null, "e": 2940, "s": 2926, "text": "gl.LINE_STRIP" }, { "code": null, "e": 2985, "s": 2940, "text": "To draw a series of connected line segments." }, { "code": null, "e": 2998, "s": 2985, "text": "gl.LINE_LOOP" }, { "code": null, "e": 3101, "s": 2998, "text": "To draw a series of connected line segments. It also joins the first and last vertices to form a loop." }, { "code": null, "e": 3114, "s": 3101, "text": "gl.TRIANGLES" }, { "code": null, "e": 3154, "s": 3114, "text": "To draw a series of separate triangles." }, { "code": null, "e": 3172, "s": 3154, "text": "gl.TRIANGLE_STRIP" }, { "code": null, "e": 3230, "s": 3172, "text": "To draw a series of connected triangles in strip fashion." }, { "code": null, "e": 3246, "s": 3230, "text": "gl.TRIANGLE_FAN" }, { "code": null, "e": 3334, "s": 3246, "text": "To draw a series of connected triangles sharing the first vertex in a fan-like fashion." }, { "code": null, "e": 3411, "s": 3334, "text": "The following example shows how to draw three parallel lines using gl.LINES." }, { "code": null, "e": 6945, "s": 3411, "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": 7009, "s": 6945, "text": "If you run this example, it will produce the following output −" } ]
Python @staticmethod
21 Nov, 2019 There can be some functionality that relates to the class, but does not require any instance(s) to do some work, static methods can be used in such cases. A static method is a method which is bound to the class and not the object of the class. It can’t access or modify class state. It is present in a class because it makes sense for the method to be present in class. A static method does not receive an implicit first argument. Syntax: class C(object): @staticmethod def fun(arg1, arg2, ...): ... Returns: a static method for function fun. When function decorated with @staticmethod is called, we don’t pass an instance of the class to it as it is normally done with methods. It means that the function is put inside the class but it cannot access the instance of that class. Example #1: # Python program to # demonstrate static methods class Maths(): @staticmethod def addNum(num1, num2): return num1 + num2 # Driver's codeif __name__ == "__main__": # Calling method of class # without creating instance res = Maths.addNum(1, 2) print("The result is", res) Output: The result is 3 Example #2: # Python program to# demonstrate static methods class Person: def __init__(self, name, age): self.name = name self.age = age # a static method to check if a Person is adult or not. @staticmethod def isAdult(age): return age > 18 # Driver's codeif __name__ == "__main__": res = Person.isAdult(12) print('Is person adult:', res) res = Person.isAdult(22) print('\nIs person adult:', res) Output: Is person adult: False Is person adult: True Python-OOP Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Nov, 2019" }, { "code": null, "e": 483, "s": 52, "text": "There can be some functionality that relates to the class, but does not require any instance(s) to do some work, static methods can be used in such cases. A static method is a method which is bound to the class and not the object of the class. It can’t access or modify class state. It is present in a class because it makes sense for the method to be present in class. A static method does not receive an implicit first argument." }, { "code": null, "e": 614, "s": 483, "text": "Syntax:\n\nclass C(object):\n @staticmethod\n def fun(arg1, arg2, ...):\n ...\n\nReturns: a static method for function fun.\n" }, { "code": null, "e": 850, "s": 614, "text": "When function decorated with @staticmethod is called, we don’t pass an instance of the class to it as it is normally done with methods. It means that the function is put inside the class but it cannot access the instance of that class." }, { "code": null, "e": 862, "s": 850, "text": "Example #1:" }, { "code": "# Python program to # demonstrate static methods class Maths(): @staticmethod def addNum(num1, num2): return num1 + num2 # Driver's codeif __name__ == \"__main__\": # Calling method of class # without creating instance res = Maths.addNum(1, 2) print(\"The result is\", res)", "e": 1179, "s": 862, "text": null }, { "code": null, "e": 1187, "s": 1179, "text": "Output:" }, { "code": null, "e": 1204, "s": 1187, "text": "The result is 3\n" }, { "code": null, "e": 1216, "s": 1204, "text": "Example #2:" }, { "code": "# Python program to# demonstrate static methods class Person: def __init__(self, name, age): self.name = name self.age = age # a static method to check if a Person is adult or not. @staticmethod def isAdult(age): return age > 18 # Driver's codeif __name__ == \"__main__\": res = Person.isAdult(12) print('Is person adult:', res) res = Person.isAdult(22) print('\\nIs person adult:', res)", "e": 1676, "s": 1216, "text": null }, { "code": null, "e": 1684, "s": 1676, "text": "Output:" }, { "code": null, "e": 1731, "s": 1684, "text": "Is person adult: False\n\nIs person adult: True\n" }, { "code": null, "e": 1742, "s": 1731, "text": "Python-OOP" }, { "code": null, "e": 1749, "s": 1742, "text": "Python" }, { "code": null, "e": 1847, "s": 1749, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1865, "s": 1847, "text": "Python Dictionary" }, { "code": null, "e": 1907, "s": 1865, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1929, "s": 1907, "text": "Enumerate() in Python" }, { "code": null, "e": 1964, "s": 1929, "text": "Read a file line by line in Python" }, { "code": null, "e": 1990, "s": 1964, "text": "Python String | replace()" }, { "code": null, "e": 2022, "s": 1990, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2051, "s": 2022, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2078, "s": 2051, "text": "Python Classes and Objects" }, { "code": null, "e": 2108, "s": 2078, "text": "Iterate over a list in Python" } ]
Launch Website URL shortcut using Python
14 Sep, 2021 In this article, we are going to launch favorite websites using shortcuts, for this, we will use Python’s sqlite3 and webbrowser modules to launch your favorite websites using shortcuts. Both sqlite3 and webbrowser are a part of the python standard library, so we don’t need to install anything separately. The best part about this is that because we are using a database to store the websites and their shortcuts, your favorite websites will remain saved in the database even if we close the terminal or shut down the PC. So you don’t need to add your favorite websites to the database every time you execute the script. We create a new database if it does not already exist and connect it to our database. We create different functions to fetch data from the database, open a website, add a new website to the database, and remove a website from the database We call a while loop so that our program can listen to the user’s commands until they quit We ask for a response from the user to perform a specific task Python3 import webbrowser import sqlite3 # connecting to sqlite and creating# an actual databaseconn = sqlite3.connect("favorites.db") c = conn.cursor() c.execute("""CREATE TABLE IF NOT EXISTS favorites (title TEXT, url TEXT)""") # Created a table named favorites# (if it didn't already existed).# Then inserted the headers title # (which takes text as input)# and url (which takes text as input)def get_data(): """ Used to extract data from our database """ c.execute('''SELECT * FROM favorites''') results = c.fetchall() return results def get_fav(titl): """ Used to extract the favorite website """ c.execute('''SELECT * FROM favorites WHERE title=?''', (titl, )) return c.fetchone() def add_fav(titl, url): """ Used to add a new favorite website """ c.execute("""INSERT INTO favorites (title, url) VALUES (?, ?)""", (titl, url)) conn.commit() def remove_fav(titl): """ Used to remove a favorite website from the database """ c.execute('''DELETE FROM favorites WHERE title=?''', (titl, )) conn.commit() # A loop to listen to commands from the userwhile True: print() # printing each statement like # this to keep the code clean print("Press v to visit a favorite,", end=" ") print("ls for list,", end=" ") print("add to add a new item,", end=" ") print("rm to delete,", end=" ") print("q to quit:", end=" ") # taking input command from the user response = input("") if response.lower() == "v": shortcut = input("Enter the shortcut for the website: ") record = get_fav(shortcut) try: # opening the selected website in the browser webbrowser.open(record[1]) except TypeError: # if we don't have the shortcut # in the database, print this: print('This shortcut does not exist in the database') elif response.lower() == "ls": # printing the items in the database print(get_data()) elif response.lower() == "add": # adding a new website to the database destination = input( "Enter URL for the shortcut (Example -> https://xyz.com): ") # adding the shortcut to the above website in # the database shortcut = input("Enter the shortcut for the URL: ") add_fav(shortcut, destination) elif response.lower() == "rm": # removing an item from the database shortcut = input( "Enter the shortcut for the URL you want to remove: ") remove_fav(shortcut) print("Removed Successfully") elif response.lower() == "q": break else: print("Enter a valid command") Output: Code Execution Blogathon-2021 Python-SQLite python-utility Blogathon Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Import JSON Data into SQL Server? SQL Query to Convert Datetime to Date Python program to convert XML to Dictionary Scrape LinkedIn Using Selenium And Beautiful Soup in Python Modes of DMA Transfer Read JSON file using Python Python map() function Adding new column to existing DataFrame in Pandas Python Dictionary How to get column names in Pandas dataframe
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Sep, 2021" }, { "code": null, "e": 241, "s": 54, "text": "In this article, we are going to launch favorite websites using shortcuts, for this, we will use Python’s sqlite3 and webbrowser modules to launch your favorite websites using shortcuts." }, { "code": null, "e": 362, "s": 241, "text": "Both sqlite3 and webbrowser are a part of the python standard library, so we don’t need to install anything separately. " }, { "code": null, "e": 677, "s": 362, "text": "The best part about this is that because we are using a database to store the websites and their shortcuts, your favorite websites will remain saved in the database even if we close the terminal or shut down the PC. So you don’t need to add your favorite websites to the database every time you execute the script." }, { "code": null, "e": 763, "s": 677, "text": "We create a new database if it does not already exist and connect it to our database." }, { "code": null, "e": 916, "s": 763, "text": "We create different functions to fetch data from the database, open a website, add a new website to the database, and remove a website from the database" }, { "code": null, "e": 1007, "s": 916, "text": "We call a while loop so that our program can listen to the user’s commands until they quit" }, { "code": null, "e": 1070, "s": 1007, "text": "We ask for a response from the user to perform a specific task" }, { "code": null, "e": 1078, "s": 1070, "text": "Python3" }, { "code": "import webbrowser import sqlite3 # connecting to sqlite and creating# an actual databaseconn = sqlite3.connect(\"favorites.db\") c = conn.cursor() c.execute(\"\"\"CREATE TABLE IF NOT EXISTS favorites (title TEXT, url TEXT)\"\"\") # Created a table named favorites# (if it didn't already existed).# Then inserted the headers title # (which takes text as input)# and url (which takes text as input)def get_data(): \"\"\" Used to extract data from our database \"\"\" c.execute('''SELECT * FROM favorites''') results = c.fetchall() return results def get_fav(titl): \"\"\" Used to extract the favorite website \"\"\" c.execute('''SELECT * FROM favorites WHERE title=?''', (titl, )) return c.fetchone() def add_fav(titl, url): \"\"\" Used to add a new favorite website \"\"\" c.execute(\"\"\"INSERT INTO favorites (title, url) VALUES (?, ?)\"\"\", (titl, url)) conn.commit() def remove_fav(titl): \"\"\" Used to remove a favorite website from the database \"\"\" c.execute('''DELETE FROM favorites WHERE title=?''', (titl, )) conn.commit() # A loop to listen to commands from the userwhile True: print() # printing each statement like # this to keep the code clean print(\"Press v to visit a favorite,\", end=\" \") print(\"ls for list,\", end=\" \") print(\"add to add a new item,\", end=\" \") print(\"rm to delete,\", end=\" \") print(\"q to quit:\", end=\" \") # taking input command from the user response = input(\"\") if response.lower() == \"v\": shortcut = input(\"Enter the shortcut for the website: \") record = get_fav(shortcut) try: # opening the selected website in the browser webbrowser.open(record[1]) except TypeError: # if we don't have the shortcut # in the database, print this: print('This shortcut does not exist in the database') elif response.lower() == \"ls\": # printing the items in the database print(get_data()) elif response.lower() == \"add\": # adding a new website to the database destination = input( \"Enter URL for the shortcut (Example -> https://xyz.com): \") # adding the shortcut to the above website in # the database shortcut = input(\"Enter the shortcut for the URL: \") add_fav(shortcut, destination) elif response.lower() == \"rm\": # removing an item from the database shortcut = input( \"Enter the shortcut for the URL you want to remove: \") remove_fav(shortcut) print(\"Removed Successfully\") elif response.lower() == \"q\": break else: print(\"Enter a valid command\")", "e": 3853, "s": 1078, "text": null }, { "code": null, "e": 3861, "s": 3853, "text": "Output:" }, { "code": null, "e": 3876, "s": 3861, "text": "Code Execution" }, { "code": null, "e": 3891, "s": 3876, "text": "Blogathon-2021" }, { "code": null, "e": 3905, "s": 3891, "text": "Python-SQLite" }, { "code": null, "e": 3920, "s": 3905, "text": "python-utility" }, { "code": null, "e": 3930, "s": 3920, "text": "Blogathon" }, { "code": null, "e": 3937, "s": 3930, "text": "Python" }, { "code": null, "e": 4035, "s": 3937, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4076, "s": 4035, "text": "How to Import JSON Data into SQL Server?" }, { "code": null, "e": 4114, "s": 4076, "text": "SQL Query to Convert Datetime to Date" }, { "code": null, "e": 4158, "s": 4114, "text": "Python program to convert XML to Dictionary" }, { "code": null, "e": 4218, "s": 4158, "text": "Scrape LinkedIn Using Selenium And Beautiful Soup in Python" }, { "code": null, "e": 4240, "s": 4218, "text": "Modes of DMA Transfer" }, { "code": null, "e": 4268, "s": 4240, "text": "Read JSON file using Python" }, { "code": null, "e": 4290, "s": 4268, "text": "Python map() function" }, { "code": null, "e": 4340, "s": 4290, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 4358, "s": 4340, "text": "Python Dictionary" } ]
SQL - INTERSECT Clause
The SQL INTERSECT clause/operator is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. This means INTERSECT returns only common rows returned by the two SELECT statements. Just as with the UNION operator, the same rules apply when using the INTERSECT operator. MySQL does not support the INTERSECT operator. The basic syntax of INTERSECT is as follows. SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] INTERSECT SELECT column1 [, column2 ] FROM table1 [, table2 ] [WHERE condition] Here, the given condition could be any given expression based on your requirement. Consider the following two tables. Table 1 − CUSTOMERS Table is as follows +----+----------+-----+-----------+----------+ | ID | NAME | AGE | ADDRESS | SALARY | +----+----------+-----+-----------+----------+ | 1 | Ramesh | 32 | Ahmedabad | 2000.00 | | 2 | Khilan | 25 | Delhi | 1500.00 | | 3 | kaushik | 23 | Kota | 2000.00 | | 4 | Chaitali | 25 | Mumbai | 6500.00 | | 5 | Hardik | 27 | Bhopal | 8500.00 | | 6 | Komal | 22 | MP | 4500.00 | | 7 | Muffy | 24 | Indore | 10000.00 | +----+----------+-----+-----------+----------+ Table 2 − ORDERS Table is as follows. +-----+---------------------+-------------+--------+ |OID | DATE | CUSTOMER_ID | AMOUNT | +-----+---------------------+-------------+--------+ | 102 | 2009-10-08 00:00:00 | 3 | 3000 | | 100 | 2009-10-08 00:00:00 | 3 | 1500 | | 101 | 2009-11-20 00:00:00 | 2 | 1560 | | 103 | 2008-05-20 00:00:00 | 4 | 2060 | +-----+---------------------+-------------+--------+ Now, let us join these two tables in our SELECT statement as follows. SQL> SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS LEFT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID INTERSECT SELECT ID, NAME, AMOUNT, DATE FROM CUSTOMERS RIGHT JOIN ORDERS ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID; This would produce the following result. +------+---------+--------+---------------------+ | ID | NAME | AMOUNT | DATE | +------+---------+--------+---------------------+ | 3 | kaushik | 3000 | 2009-10-08 00:00:00 | | 3 | kaushik | 1500 | 2009-10-08 00:00:00 | | 2 | Ramesh | 1560 | 2009-11-20 00:00:00 | | 4 | kaushik | 2060 | 2008-05-20 00:00:00 |
[ { "code": null, "e": 2862, "s": 2587, "text": "The SQL INTERSECT clause/operator is used to combine two SELECT statements, but returns rows only from the first SELECT statement that are identical to a row in the second SELECT statement. This means INTERSECT returns only common rows returned by the two SELECT statements." }, { "code": null, "e": 2998, "s": 2862, "text": "Just as with the UNION operator, the same rules apply when using the INTERSECT operator. MySQL does not support the INTERSECT operator." }, { "code": null, "e": 3043, "s": 2998, "text": "The basic syntax of INTERSECT is as follows." }, { "code": null, "e": 3196, "s": 3043, "text": "SELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n\nINTERSECT\n\nSELECT column1 [, column2 ]\nFROM table1 [, table2 ]\n[WHERE condition]\n" }, { "code": null, "e": 3279, "s": 3196, "text": "Here, the given condition could be any given expression based on your requirement." }, { "code": null, "e": 3314, "s": 3279, "text": "Consider the following two tables." }, { "code": null, "e": 3354, "s": 3314, "text": "Table 1 − CUSTOMERS Table is as follows" }, { "code": null, "e": 3871, "s": 3354, "text": "+----+----------+-----+-----------+----------+\n| ID | NAME | AGE | ADDRESS | SALARY |\n+----+----------+-----+-----------+----------+\n| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |\n| 2 | Khilan | 25 | Delhi | 1500.00 |\n| 3 | kaushik | 23 | Kota | 2000.00 |\n| 4 | Chaitali | 25 | Mumbai | 6500.00 |\n| 5 | Hardik | 27 | Bhopal | 8500.00 |\n| 6 | Komal | 22 | MP | 4500.00 |\n| 7 | Muffy | 24 | Indore | 10000.00 |\n+----+----------+-----+-----------+----------+" }, { "code": null, "e": 3909, "s": 3871, "text": "Table 2 − ORDERS Table is as follows." }, { "code": null, "e": 4333, "s": 3909, "text": "+-----+---------------------+-------------+--------+\n|OID | DATE | CUSTOMER_ID | AMOUNT |\n+-----+---------------------+-------------+--------+\n| 102 | 2009-10-08 00:00:00 | 3 | 3000 |\n| 100 | 2009-10-08 00:00:00 | 3 | 1500 |\n| 101 | 2009-11-20 00:00:00 | 2 | 1560 |\n| 103 | 2008-05-20 00:00:00 | 4 | 2060 |\n+-----+---------------------+-------------+--------+" }, { "code": null, "e": 4403, "s": 4333, "text": "Now, let us join these two tables in our SELECT statement as follows." }, { "code": null, "e": 4641, "s": 4403, "text": "SQL> SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n LEFT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID\nINTERSECT\n SELECT ID, NAME, AMOUNT, DATE\n FROM CUSTOMERS\n RIGHT JOIN ORDERS\n ON CUSTOMERS.ID = ORDERS.CUSTOMER_ID;" }, { "code": null, "e": 4682, "s": 4641, "text": "This would produce the following result." } ]
subfinder Tool in Linux
25 Jan, 2021 subfinder is a subdomain enumeration tool written in the Go programming language. Subfinder is used for discovering passive subdomains of websites by using digital sources like Censys, Chaos, Recon.dev, Shodan, Spyse, Virustotal, and many other passive online sources. Subfinder is widely used by Ethical Hackers and Bug bounty hunters in the Information gathering Phase which is also known as Reconnaissance. As subfinder is a Go tool you need to have the Go language package installed before installing subfinder. 1. From Source(Recommended) All you need to do is open your terminal and paste this one line of code and press enter. GO111MODULE=on go get -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder From Source 2. From Binary Firstly download the release suitable for your OS from https://github.com/projectdiscovery/subfinder/releases/ and then unzip the folder and move the subfinder binary file to /usr/local/bin/ and you are good to go # download release from https://github.com/projectdiscovery/subfinder/releases/ tar -xzvf subfinder-linux-amd64.tar.gz mv subfinder /usr/local/bin/ subfinder -h 3. From Github Clone https://github.com/projectdiscovery/subfinder.git repository and change directory to subfinder/v2/cmd/subfinder and then type go build . (don’t forget to put a ‘.’ at the end ) now move the subfinder binary file to /usr/local/bin and subfinder is ready to use. git clone https://github.com/projectdiscovery/subfinder.git cd subfinder/v2/cmd/subfinder go build . mv subfinder /usr/local/bin/ subfinder -h From Github Retrieving the Subfinder list of attributes subfinder -h Here we will find out subdomains of the domain geeksforgeeks.org and setting a concurrency of 50. I got around 73 subdomains for geeksforgeeks.org in 4 seconds 71 milliseconds. subfinder -d geeksforgeeks.org -silent -t 50 Example usage of subfinder Pros of subfinder over sublist3r: As subfinder is a Go Tool and sublist3r is a python tool and Go Language is faster than python and also Go language’s approach to concurrency is very easy to work with. Also, subfinder also provides various options that sublist3r doesn’t. Cyber-security Information-Security Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. tar command in Linux with examples curl command in Linux with Examples 'crontab' in Linux with Examples TCP Server-Client implementation in C Conditional Statements | Shell Script Tail command in Linux with examples UDP Server-Client implementation in C Docker - COPY Instruction scp command in Linux with Examples diff command in Linux with examples
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Jan, 2021" }, { "code": null, "e": 438, "s": 28, "text": "subfinder is a subdomain enumeration tool written in the Go programming language. Subfinder is used for discovering passive subdomains of websites by using digital sources like Censys, Chaos, Recon.dev, Shodan, Spyse, Virustotal, and many other passive online sources. Subfinder is widely used by Ethical Hackers and Bug bounty hunters in the Information gathering Phase which is also known as Reconnaissance." }, { "code": null, "e": 544, "s": 438, "text": "As subfinder is a Go tool you need to have the Go language package installed before installing subfinder." }, { "code": null, "e": 572, "s": 544, "text": "1. From Source(Recommended)" }, { "code": null, "e": 662, "s": 572, "text": "All you need to do is open your terminal and paste this one line of code and press enter." }, { "code": null, "e": 742, "s": 662, "text": "GO111MODULE=on go get -v github.com/projectdiscovery/subfinder/v2/cmd/subfinder" }, { "code": null, "e": 754, "s": 742, "text": "From Source" }, { "code": null, "e": 769, "s": 754, "text": "2. From Binary" }, { "code": null, "e": 983, "s": 769, "text": "Firstly download the release suitable for your OS from https://github.com/projectdiscovery/subfinder/releases/ and then unzip the folder and move the subfinder binary file to /usr/local/bin/ and you are good to go" }, { "code": null, "e": 1144, "s": 983, "text": "# download release from https://github.com/projectdiscovery/subfinder/releases/\ntar -xzvf subfinder-linux-amd64.tar.gz\nmv subfinder /usr/local/bin/\nsubfinder -h" }, { "code": null, "e": 1159, "s": 1144, "text": "3. From Github" }, { "code": null, "e": 1426, "s": 1159, "text": "Clone https://github.com/projectdiscovery/subfinder.git repository and change directory to subfinder/v2/cmd/subfinder and then type go build . (don’t forget to put a ‘.’ at the end ) now move the subfinder binary file to /usr/local/bin and subfinder is ready to use." }, { "code": null, "e": 1569, "s": 1426, "text": "git clone https://github.com/projectdiscovery/subfinder.git\ncd subfinder/v2/cmd/subfinder\ngo build .\nmv subfinder /usr/local/bin/\nsubfinder -h" }, { "code": null, "e": 1581, "s": 1569, "text": "From Github" }, { "code": null, "e": 1625, "s": 1581, "text": "Retrieving the Subfinder list of attributes" }, { "code": null, "e": 1639, "s": 1625, "text": "subfinder -h " }, { "code": null, "e": 1816, "s": 1639, "text": "Here we will find out subdomains of the domain geeksforgeeks.org and setting a concurrency of 50. I got around 73 subdomains for geeksforgeeks.org in 4 seconds 71 milliseconds." }, { "code": null, "e": 1861, "s": 1816, "text": "subfinder -d geeksforgeeks.org -silent -t 50" }, { "code": null, "e": 1888, "s": 1861, "text": "Example usage of subfinder" }, { "code": null, "e": 2161, "s": 1888, "text": "Pros of subfinder over sublist3r: As subfinder is a Go Tool and sublist3r is a python tool and Go Language is faster than python and also Go language’s approach to concurrency is very easy to work with. Also, subfinder also provides various options that sublist3r doesn’t." }, { "code": null, "e": 2176, "s": 2161, "text": "Cyber-security" }, { "code": null, "e": 2197, "s": 2176, "text": "Information-Security" }, { "code": null, "e": 2208, "s": 2197, "text": "Linux-Unix" }, { "code": null, "e": 2306, "s": 2208, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2341, "s": 2306, "text": "tar command in Linux with examples" }, { "code": null, "e": 2377, "s": 2341, "text": "curl command in Linux with Examples" }, { "code": null, "e": 2410, "s": 2377, "text": "'crontab' in Linux with Examples" }, { "code": null, "e": 2448, "s": 2410, "text": "TCP Server-Client implementation in C" }, { "code": null, "e": 2486, "s": 2448, "text": "Conditional Statements | Shell Script" }, { "code": null, "e": 2522, "s": 2486, "text": "Tail command in Linux with examples" }, { "code": null, "e": 2560, "s": 2522, "text": "UDP Server-Client implementation in C" }, { "code": null, "e": 2586, "s": 2560, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2621, "s": 2586, "text": "scp command in Linux with Examples" } ]
Python – Measure time taken by program to execute
26 May, 2020 This article aims to show how to measure the time taken by the program to execute. Calculating time helps to optimize your Python script to perform better. Approach #1 :A simple solution to it is to use time module to get the current time. The following steps calculate the running time of a program or section of a program. Store the starting time before the first line of the program executes. Store the ending time after the last line of the program executes. Print the difference between start time and end time. Code #1 : # Code to Measure time taken by program to execute.import time # store starting timebegin = time.time() # program body starts for i in range(5): print("GeeksForGeeks")# program body ends time.sleep(1)# store end timeend = time.time() # total time takenprint(f"Total runtime of the program is {end - begin}") GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks GeeksForGeeks Total runtime of the program is 1.0010437965393066 Approach #2 : Using Timeit module # importing the required module import timeit # code snippet to be executed only once mysetup = "from math import sqrt" # code snippet whose execution time is to be measured mycode = ''' def example(): mylist = [] for x in range(100): mylist.append(sqrt(x)) ''' # timeit statement print timeit.timeit(setup = mysetup, stmt = mycode, number = 10000) Output: 0.00119590759277 Note: Output may vary depending on the system or server load. To read more about Timeit modulule, refer – Timeit in Python with Examples python-utility Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 May, 2020" }, { "code": null, "e": 208, "s": 52, "text": "This article aims to show how to measure the time taken by the program to execute. Calculating time helps to optimize your Python script to perform better." }, { "code": null, "e": 377, "s": 208, "text": "Approach #1 :A simple solution to it is to use time module to get the current time. The following steps calculate the running time of a program or section of a program." }, { "code": null, "e": 448, "s": 377, "text": "Store the starting time before the first line of the program executes." }, { "code": null, "e": 515, "s": 448, "text": "Store the ending time after the last line of the program executes." }, { "code": null, "e": 569, "s": 515, "text": "Print the difference between start time and end time." }, { "code": null, "e": 579, "s": 569, "text": "Code #1 :" }, { "code": "# Code to Measure time taken by program to execute.import time # store starting timebegin = time.time() # program body starts for i in range(5): print(\"GeeksForGeeks\")# program body ends time.sleep(1)# store end timeend = time.time() # total time takenprint(f\"Total runtime of the program is {end - begin}\")", "e": 895, "s": 579, "text": null }, { "code": null, "e": 1017, "s": 895, "text": "GeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nGeeksForGeeks\nTotal runtime of the program is 1.0010437965393066\n" }, { "code": null, "e": 1052, "s": 1017, "text": " Approach #2 : Using Timeit module" }, { "code": "# importing the required module import timeit # code snippet to be executed only once mysetup = \"from math import sqrt\" # code snippet whose execution time is to be measured mycode = ''' def example(): mylist = [] for x in range(100): mylist.append(sqrt(x)) ''' # timeit statement print timeit.timeit(setup = mysetup, stmt = mycode, number = 10000) ", "e": 1462, "s": 1052, "text": null }, { "code": null, "e": 1470, "s": 1462, "text": "Output:" }, { "code": null, "e": 1487, "s": 1470, "text": "0.00119590759277" }, { "code": null, "e": 1549, "s": 1487, "text": "Note: Output may vary depending on the system or server load." }, { "code": null, "e": 1624, "s": 1549, "text": "To read more about Timeit modulule, refer – Timeit in Python with Examples" }, { "code": null, "e": 1639, "s": 1624, "text": "python-utility" }, { "code": null, "e": 1646, "s": 1639, "text": "Python" }, { "code": null, "e": 1662, "s": 1646, "text": "Python Programs" } ]
Math.round() function in JavaScript
The round() function of the Math object accepts a floating point random number and returns its nearest integer value. If the given number is x.5 or more this function returns the next number (x+1) If the given number is x.4 or less this function returns the previous number (x-1). If the given number itself is an integer this function returns the same. Its Syntax is as follows Math.round(); Live Demo <html> <head> <title>JavaScript Example</title> </head> <body> <script type="text/javascript"> var result = Math.round(2541.542); document.write("Rounded value of the given number: "+result); </script> </body> </html> Rounded value of the given number: 2542
[ { "code": null, "e": 1305, "s": 1187, "text": "The round() function of the Math object accepts a floating point random number and returns its nearest integer value." }, { "code": null, "e": 1384, "s": 1305, "text": "If the given number is x.5 or more this function returns the next number (x+1)" }, { "code": null, "e": 1468, "s": 1384, "text": "If the given number is x.4 or less this function returns the previous number (x-1)." }, { "code": null, "e": 1541, "s": 1468, "text": "If the given number itself is an integer this function returns the same." }, { "code": null, "e": 1566, "s": 1541, "text": "Its Syntax is as follows" }, { "code": null, "e": 1580, "s": 1566, "text": "Math.round();" }, { "code": null, "e": 1591, "s": 1580, "text": " Live Demo" }, { "code": null, "e": 1830, "s": 1591, "text": "<html>\n<head>\n <title>JavaScript Example</title>\n</head>\n<body>\n <script type=\"text/javascript\">\n var result = Math.round(2541.542);\n document.write(\"Rounded value of the given number: \"+result);\n </script>\n</body>\n</html>" }, { "code": null, "e": 1870, "s": 1830, "text": "Rounded value of the given number: 2542" } ]
Clone a Directed Acyclic Graph
27 Jan, 2022 A directed acyclic graph (DAG) is a graph which doesn’t contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them. Examples: Input : 0 - - - > 1 - - - -> 4 | / \ ^ | / \ | | / \ | | / \ | | / \ | | / \ | v v v | 2 - - - - - - - - -> 3 Output : Printing the output of the cloned graph gives: 0-1 1-2 2-3 3-4 1-3 1-4 0-2 To clone a DAG without storing the graph itself within a hash (or dictionary in Python). To clone, it we basically do a depth-first traversal of the nodes, taking original node’s value and initializing new neighboring nodes with the same value, recursively doing, till the original graph is fully traversed. Below is the recursive approach to cloning a DAG (in Python). We make use of dynamic lists in Python, append operation to this list happens in constant time, hence, fast and efficient initialization of the graph. C++14 Java Python3 // C++ program to clone a directed acyclic graph.#include <bits/stdc++.h>using namespace std; // Class to create a new graph nodeclass Node{ public: int key; vector<Node *> adj; // key is the value of the node // adj will be holding a dynamic // list of all Node type neighboring // nodes Node(int key) { this->key = key; }}; // Function to print a graph,// depth-wise, recursivelyvoid printGraph(Node *startNode, vector<bool> &visited){ // Visit only those nodes who have any // neighboring nodes to be traversed if (!startNode->adj.empty()) { // Loop through the neighboring nodes // of this node. If source node not already // visited, print edge from source to // neighboring nodes. After visiting all // neighbors of source node, mark its visited // flag to true for(auto i : startNode->adj) { if (!visited[startNode->key]) { cout << "edge " << startNode << "-" << i << ":" << startNode->key << "-" << i->key << endl; if (!visited[i->key]) { printGraph(i, visited); visited[i->key] = true; } } } }} // Function to clone a graph. To do this, we// start reading the original graph depth-wise,// recursively. If we encounter an unvisited// node in original graph, we initialize a// new instance of Node for cloned graph with// key of original nodeNode *cloneGraph(Node *oldSource, Node *newSource, vector<bool> &visited){ Node *clone = NULL; if (!visited[oldSource->key] && !oldSource->adj.empty()) { for(auto old : oldSource->adj) { // Below check is for backtracking, so new // nodes don't get initialized everytime if (clone == NULL || (clone != NULL && clone->key != old->key)) clone = new Node(old->key); newSource->adj.push_back(clone); cloneGraph(old, clone, visited); // Once, all neighbors for that particular node // are created in cloned graph, code backtracks // and exits from that node, mark the node as // visited in original graph, and traverse the // next unvisited visited[old->key] = true; } } return newSource;} // Driver Codeint main(){ Node *n0 = new Node(0); Node *n1 = new Node(1); Node *n2 = new Node(2); Node *n3 = new Node(3); Node *n4 = new Node(4); n0->adj.push_back(n1); n0->adj.push_back(n2); n1->adj.push_back(n2); n1->adj.push_back(n3); n1->adj.push_back(n4); n2->adj.push_back(n3); n3->adj.push_back(n4); // Flag to check if a node is already visited. // Stops indefinite looping during recursion vector<bool> visited(5, false); cout << "Graph Before Cloning:-\n"; printGraph(n0, visited); visited = { false, false, false, false, false }; cout << "\nGraph Before Starts:-\n"; Node *clonedGraphHead = cloneGraph( n0, new Node(n0->key), visited); cout << "Cloning Process Completes.\n"; visited = { false, false, false, false, false }; cout << "\nGraph After Cloning:-\n"; printGraph(clonedGraphHead, visited); return 0;} // This code is contributed by sanjeev2552 // Java program to clone a directed acyclic graph.import java.util.*; class GFG{ // Class to create a new graph nodestatic class Node{ int key; ArrayList<Node> adj = new ArrayList<Node>(); // key is the value of the node // adj will be holding a dynamic // list of all Node type neighboring // nodes Node(int key) { this.key = key; }} // Function to print a graph,// depth-wise, recursivelystatic void printGraph(Node startNode, boolean[] visited){ // Visit only those nodes who have any // neighboring nodes to be traversed if (!startNode.adj.isEmpty()) { // Loop through the neighboring nodes // of this node. If source node not already // visited, print edge from source to // neighboring nodes. After visiting all // neighbors of source node, mark its visited // flag to true for(Node i : startNode.adj) { if (!visited[startNode.key]) { System.out.println("edge " + startNode + "-" + i + ":" + startNode.key + "-" + i.key); if (!visited[i.key]) { printGraph(i, visited); visited[i.key] = true; } } } }} // Function to clone a graph. To do this, we// start reading the original graph depth-wise,// recursively. If we encounter an unvisited// node in original graph, we initialize a// new instance of Node for cloned graph with// key of original nodestatic Node cloneGraph(Node oldSource, Node newSource, boolean[] visited){ Node clone = null; if (!visited[oldSource.key] && !oldSource.adj.isEmpty()) { for(Node old : oldSource.adj) { // Below check is for backtracking, so new // nodes don't get initialized everytime if (clone == null || (clone != null && clone.key != old.key)) clone = new Node(old.key); newSource.adj.add(clone); cloneGraph(old, clone, visited); // Once, all neighbors for that particular node // are created in cloned graph, code backtracks // and exits from that node, mark the node as // visited in original graph, and traverse the // next unvisited visited[old.key] = true; } } return newSource;} // Driver Codepublic static void main(String[] args){ Node n0 = new Node(0); Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); n0.adj.add(n1); n0.adj.add(n2); n1.adj.add(n2); n1.adj.add(n3); n1.adj.add(n4); n2.adj.add(n3); n3.adj.add(n4); // Flag to check if a node is already visited. // Stops indefinite looping during recursion boolean visited[] = new boolean[5]; System.out.println("Graph Before Cloning:-"); printGraph(n0, visited); Arrays.fill(visited, false); System.out.println("\nCloning Process Starts"); Node clonedGraphHead = cloneGraph( n0, new Node(n0.key), visited); System.out.println("Cloning Process Completes."); Arrays.fill(visited, false); System.out.println("\nGraph After Cloning:-"); printGraph(clonedGraphHead, visited);}} // This code is contributed by adityapande88 # Python program to clone a directed acyclic graph. # Class to create a new graph nodeclass Node(): # key is the value of the node # adj will be holding a dynamic # list of all Node type neighboring # nodes def __init__(self, key = None, adj = None): self.key = key self.adj = adj # Function to print a graph, depth-wise, recursivelydef printGraph(startNode, visited): # Visit only those nodes who have any # neighboring nodes to be traversed if startNode.adj is not None: # Loop through the neighboring nodes # of this node. If source node not already # visited, print edge from source to # neighboring nodes. After visiting all # neighbors of source node, mark its visited # flag to true for i in startNode.adj: if visited[startNode.key] == False : print("edge %s-%s:%s-%s"%(hex(id(startNode)), hex(id(i)), startNode.key, i.key)) if visited[i.key] == False: printGraph(i, visited) visited[i.key] = True # Function to clone a graph. To do this, we start# reading the original graph depth-wise, recursively# If we encounter an unvisited node in original graph,# we initialize a new instance of Node for# cloned graph with key of original nodedef cloneGraph(oldSource, newSource, visited): clone = None if visited[oldSource.key] is False and oldSource.adj is not None: for old in oldSource.adj: # Below check is for backtracking, so new # nodes don't get initialized everytime if clone is None or(clone is not None and clone.key != old.key): clone = Node(old.key, []) newSource.adj.append(clone) cloneGraph(old, clone, visited) # Once, all neighbors for that particular node # are created in cloned graph, code backtracks # and exits from that node, mark the node as # visited in original graph, and traverse the # next unvisited visited[old.key] = True return newSource # Creating DAG to be cloned# In Python, we can do as many assignments of# variables in one single line by using commasn0, n1, n2 = Node(0, []), Node(1, []), Node(2, [])n3, n4 = Node(3, []), Node(4)n0.adj.append(n1)n0.adj.append(n2)n1.adj.append(n2)n1.adj.append(n3)n1.adj.append(n4)n2.adj.append(n3)n3.adj.append(n4) # flag to check if a node is already visited.# Stops indefinite looping during recursionvisited = [False]* (5)print("Graph Before Cloning:-")printGraph(n0, visited) visited = [False]* (5)print("\nCloning Process Starts")clonedGraphHead = cloneGraph(n0, Node(n0.key, []), visited)print("Cloning Process Completes.") visited = [False]*(5)print("\nGraph After Cloning:-")printGraph(clonedGraphHead, visited) Output: Graph Before Cloning:- edge 0x7fa03dd43878-0x7fa03dd43908:0-1 edge 0x7fa03dd43908-0x7fa03dd43950:1-2 edge 0x7fa03dd43950-0x7fa03dd43998:2-3 edge 0x7fa03dd43998-0x7fa03dd439e0:3-4 edge 0x7fa03dd43908-0x7fa03dd43998:1-3 edge 0x7fa03dd43908-0x7fa03dd439e0:1-4 edge 0x7fa03dd43878-0x7fa03dd43950:0-2 Cloning Process Starts Cloning Process Completes. Graph After Cloning:- edge 0x7fa03dd43a28-0x7fa03dd43a70:0-1 edge 0x7fa03dd43a70-0x7fa03dd43ab8:1-2 edge 0x7fa03dd43ab8-0x7fa03dd43b00:2-3 edge 0x7fa03dd43b00-0x7fa03dd43b48:3-4 edge 0x7fa03dd43a70-0x7fa03dd43b90:1-3 edge 0x7fa03dd43a70-0x7fa03dd43bd8:1-4 edge 0x7fa03dd43a28-0x7fa03dd43c20:0-2 Creating the DAG by appending adjacent edges to the vertex happens in O(1) time. Cloning of the graph takes O(E+V) time. This article is contributed by Raveena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. sanjeev2552 adityapande88 surinderdawra388 amartyaghoshgfg DFS graph-cycle Graph DFS Graph Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n27 Jan, 2022" }, { "code": null, "e": 275, "s": 54, "text": "A directed acyclic graph (DAG) is a graph which doesn’t contain a cycle and has directed edges. We are given a DAG, we need to clone it, i.e., create another graph that has copy of its vertices and edges connecting them." }, { "code": null, "e": 287, "s": 275, "text": "Examples: " }, { "code": null, "e": 598, "s": 287, "text": "Input :\n \n0 - - - > 1 - - - -> 4\n| / \\ ^ \n| / \\ | \n| / \\ |\n| / \\ | \n| / \\ |\n| / \\ |\nv v v |\n2 - - - - - - - - -> 3\n\n\nOutput : Printing the output of the cloned graph gives: \n0-1\n1-2\n2-3\n3-4\n1-3\n1-4\n0-2" }, { "code": null, "e": 1119, "s": 598, "text": "To clone a DAG without storing the graph itself within a hash (or dictionary in Python). To clone, it we basically do a depth-first traversal of the nodes, taking original node’s value and initializing new neighboring nodes with the same value, recursively doing, till the original graph is fully traversed. Below is the recursive approach to cloning a DAG (in Python). We make use of dynamic lists in Python, append operation to this list happens in constant time, hence, fast and efficient initialization of the graph." }, { "code": null, "e": 1125, "s": 1119, "text": "C++14" }, { "code": null, "e": 1130, "s": 1125, "text": "Java" }, { "code": null, "e": 1138, "s": 1130, "text": "Python3" }, { "code": "// C++ program to clone a directed acyclic graph.#include <bits/stdc++.h>using namespace std; // Class to create a new graph nodeclass Node{ public: int key; vector<Node *> adj; // key is the value of the node // adj will be holding a dynamic // list of all Node type neighboring // nodes Node(int key) { this->key = key; }}; // Function to print a graph,// depth-wise, recursivelyvoid printGraph(Node *startNode, vector<bool> &visited){ // Visit only those nodes who have any // neighboring nodes to be traversed if (!startNode->adj.empty()) { // Loop through the neighboring nodes // of this node. If source node not already // visited, print edge from source to // neighboring nodes. After visiting all // neighbors of source node, mark its visited // flag to true for(auto i : startNode->adj) { if (!visited[startNode->key]) { cout << \"edge \" << startNode << \"-\" << i << \":\" << startNode->key << \"-\" << i->key << endl; if (!visited[i->key]) { printGraph(i, visited); visited[i->key] = true; } } } }} // Function to clone a graph. To do this, we// start reading the original graph depth-wise,// recursively. If we encounter an unvisited// node in original graph, we initialize a// new instance of Node for cloned graph with// key of original nodeNode *cloneGraph(Node *oldSource, Node *newSource, vector<bool> &visited){ Node *clone = NULL; if (!visited[oldSource->key] && !oldSource->adj.empty()) { for(auto old : oldSource->adj) { // Below check is for backtracking, so new // nodes don't get initialized everytime if (clone == NULL || (clone != NULL && clone->key != old->key)) clone = new Node(old->key); newSource->adj.push_back(clone); cloneGraph(old, clone, visited); // Once, all neighbors for that particular node // are created in cloned graph, code backtracks // and exits from that node, mark the node as // visited in original graph, and traverse the // next unvisited visited[old->key] = true; } } return newSource;} // Driver Codeint main(){ Node *n0 = new Node(0); Node *n1 = new Node(1); Node *n2 = new Node(2); Node *n3 = new Node(3); Node *n4 = new Node(4); n0->adj.push_back(n1); n0->adj.push_back(n2); n1->adj.push_back(n2); n1->adj.push_back(n3); n1->adj.push_back(n4); n2->adj.push_back(n3); n3->adj.push_back(n4); // Flag to check if a node is already visited. // Stops indefinite looping during recursion vector<bool> visited(5, false); cout << \"Graph Before Cloning:-\\n\"; printGraph(n0, visited); visited = { false, false, false, false, false }; cout << \"\\nGraph Before Starts:-\\n\"; Node *clonedGraphHead = cloneGraph( n0, new Node(n0->key), visited); cout << \"Cloning Process Completes.\\n\"; visited = { false, false, false, false, false }; cout << \"\\nGraph After Cloning:-\\n\"; printGraph(clonedGraphHead, visited); return 0;} // This code is contributed by sanjeev2552", "e": 4735, "s": 1138, "text": null }, { "code": "// Java program to clone a directed acyclic graph.import java.util.*; class GFG{ // Class to create a new graph nodestatic class Node{ int key; ArrayList<Node> adj = new ArrayList<Node>(); // key is the value of the node // adj will be holding a dynamic // list of all Node type neighboring // nodes Node(int key) { this.key = key; }} // Function to print a graph,// depth-wise, recursivelystatic void printGraph(Node startNode, boolean[] visited){ // Visit only those nodes who have any // neighboring nodes to be traversed if (!startNode.adj.isEmpty()) { // Loop through the neighboring nodes // of this node. If source node not already // visited, print edge from source to // neighboring nodes. After visiting all // neighbors of source node, mark its visited // flag to true for(Node i : startNode.adj) { if (!visited[startNode.key]) { System.out.println(\"edge \" + startNode + \"-\" + i + \":\" + startNode.key + \"-\" + i.key); if (!visited[i.key]) { printGraph(i, visited); visited[i.key] = true; } } } }} // Function to clone a graph. To do this, we// start reading the original graph depth-wise,// recursively. If we encounter an unvisited// node in original graph, we initialize a// new instance of Node for cloned graph with// key of original nodestatic Node cloneGraph(Node oldSource, Node newSource, boolean[] visited){ Node clone = null; if (!visited[oldSource.key] && !oldSource.adj.isEmpty()) { for(Node old : oldSource.adj) { // Below check is for backtracking, so new // nodes don't get initialized everytime if (clone == null || (clone != null && clone.key != old.key)) clone = new Node(old.key); newSource.adj.add(clone); cloneGraph(old, clone, visited); // Once, all neighbors for that particular node // are created in cloned graph, code backtracks // and exits from that node, mark the node as // visited in original graph, and traverse the // next unvisited visited[old.key] = true; } } return newSource;} // Driver Codepublic static void main(String[] args){ Node n0 = new Node(0); Node n1 = new Node(1); Node n2 = new Node(2); Node n3 = new Node(3); Node n4 = new Node(4); n0.adj.add(n1); n0.adj.add(n2); n1.adj.add(n2); n1.adj.add(n3); n1.adj.add(n4); n2.adj.add(n3); n3.adj.add(n4); // Flag to check if a node is already visited. // Stops indefinite looping during recursion boolean visited[] = new boolean[5]; System.out.println(\"Graph Before Cloning:-\"); printGraph(n0, visited); Arrays.fill(visited, false); System.out.println(\"\\nCloning Process Starts\"); Node clonedGraphHead = cloneGraph( n0, new Node(n0.key), visited); System.out.println(\"Cloning Process Completes.\"); Arrays.fill(visited, false); System.out.println(\"\\nGraph After Cloning:-\"); printGraph(clonedGraphHead, visited);}} // This code is contributed by adityapande88", "e": 8250, "s": 4735, "text": null }, { "code": "# Python program to clone a directed acyclic graph. # Class to create a new graph nodeclass Node(): # key is the value of the node # adj will be holding a dynamic # list of all Node type neighboring # nodes def __init__(self, key = None, adj = None): self.key = key self.adj = adj # Function to print a graph, depth-wise, recursivelydef printGraph(startNode, visited): # Visit only those nodes who have any # neighboring nodes to be traversed if startNode.adj is not None: # Loop through the neighboring nodes # of this node. If source node not already # visited, print edge from source to # neighboring nodes. After visiting all # neighbors of source node, mark its visited # flag to true for i in startNode.adj: if visited[startNode.key] == False : print(\"edge %s-%s:%s-%s\"%(hex(id(startNode)), hex(id(i)), startNode.key, i.key)) if visited[i.key] == False: printGraph(i, visited) visited[i.key] = True # Function to clone a graph. To do this, we start# reading the original graph depth-wise, recursively# If we encounter an unvisited node in original graph,# we initialize a new instance of Node for# cloned graph with key of original nodedef cloneGraph(oldSource, newSource, visited): clone = None if visited[oldSource.key] is False and oldSource.adj is not None: for old in oldSource.adj: # Below check is for backtracking, so new # nodes don't get initialized everytime if clone is None or(clone is not None and clone.key != old.key): clone = Node(old.key, []) newSource.adj.append(clone) cloneGraph(old, clone, visited) # Once, all neighbors for that particular node # are created in cloned graph, code backtracks # and exits from that node, mark the node as # visited in original graph, and traverse the # next unvisited visited[old.key] = True return newSource # Creating DAG to be cloned# In Python, we can do as many assignments of# variables in one single line by using commasn0, n1, n2 = Node(0, []), Node(1, []), Node(2, [])n3, n4 = Node(3, []), Node(4)n0.adj.append(n1)n0.adj.append(n2)n1.adj.append(n2)n1.adj.append(n3)n1.adj.append(n4)n2.adj.append(n3)n3.adj.append(n4) # flag to check if a node is already visited.# Stops indefinite looping during recursionvisited = [False]* (5)print(\"Graph Before Cloning:-\")printGraph(n0, visited) visited = [False]* (5)print(\"\\nCloning Process Starts\")clonedGraphHead = cloneGraph(n0, Node(n0.key, []), visited)print(\"Cloning Process Completes.\") visited = [False]*(5)print(\"\\nGraph After Cloning:-\")printGraph(clonedGraphHead, visited)", "e": 11065, "s": 8250, "text": null }, { "code": null, "e": 11074, "s": 11065, "text": "Output: " }, { "code": null, "e": 11717, "s": 11074, "text": "Graph Before Cloning:-\nedge 0x7fa03dd43878-0x7fa03dd43908:0-1\nedge 0x7fa03dd43908-0x7fa03dd43950:1-2\nedge 0x7fa03dd43950-0x7fa03dd43998:2-3\nedge 0x7fa03dd43998-0x7fa03dd439e0:3-4\nedge 0x7fa03dd43908-0x7fa03dd43998:1-3\nedge 0x7fa03dd43908-0x7fa03dd439e0:1-4\nedge 0x7fa03dd43878-0x7fa03dd43950:0-2\n\nCloning Process Starts\nCloning Process Completes.\n\nGraph After Cloning:-\nedge 0x7fa03dd43a28-0x7fa03dd43a70:0-1\nedge 0x7fa03dd43a70-0x7fa03dd43ab8:1-2\nedge 0x7fa03dd43ab8-0x7fa03dd43b00:2-3\nedge 0x7fa03dd43b00-0x7fa03dd43b48:3-4\nedge 0x7fa03dd43a70-0x7fa03dd43b90:1-3\nedge 0x7fa03dd43a70-0x7fa03dd43bd8:1-4\nedge 0x7fa03dd43a28-0x7fa03dd43c20:0-2" }, { "code": null, "e": 11839, "s": 11717, "text": "Creating the DAG by appending adjacent edges to the vertex happens in O(1) time. Cloning of the graph takes O(E+V) time. " }, { "code": null, "e": 12255, "s": 11839, "text": "This article is contributed by Raveena. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 12269, "s": 12257, "text": "sanjeev2552" }, { "code": null, "e": 12283, "s": 12269, "text": "adityapande88" }, { "code": null, "e": 12300, "s": 12283, "text": "surinderdawra388" }, { "code": null, "e": 12316, "s": 12300, "text": "amartyaghoshgfg" }, { "code": null, "e": 12320, "s": 12316, "text": "DFS" }, { "code": null, "e": 12332, "s": 12320, "text": "graph-cycle" }, { "code": null, "e": 12338, "s": 12332, "text": "Graph" }, { "code": null, "e": 12342, "s": 12338, "text": "DFS" }, { "code": null, "e": 12348, "s": 12342, "text": "Graph" } ]
TextField – Django Models
12 Feb, 2020 TextField is a large text field for large-sized text. TextField is generally used for storing paragraphs and all other text data. The default form widget for this field is TextArea. Syntax – field_name = models.TextField( **options) Illustration of TextField 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 models.py file of geeks app. from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.TextField() 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 when we run makemigrations command from the terminal, Python manage.py makemigrations A new folder named migrations would be created in geeks directory with a file named 0001_initial.py # Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.TextField( )), ], ), ] Now run, Python manage.py migrate Thus, an geeks_field TextField is created when you run migrations on the project. It is a field to store small- to large-sized strings. TextField is used for storing large text in the database. One can store paragraphs, data, etc. To store smaller text like First_name, Last_name, CharField should be used. Let us create an instance of the TextField we created and check if it is working. # importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field ="GfG is the best")geek_object.save() Now let’s check it in admin server. We have created an instance of GeeksModel. Field Options 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 null = True to TextField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an TextField can use. NaveenArora Django-models Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 53, "s": 25, "text": "\n12 Feb, 2020" }, { "code": null, "e": 235, "s": 53, "text": "TextField is a large text field for large-sized text. TextField is generally used for storing paragraphs and all other text data. The default form widget for this field is TextArea." }, { "code": null, "e": 244, "s": 235, "text": "Syntax –" }, { "code": null, "e": 286, "s": 244, "text": "field_name = models.TextField( **options)" }, { "code": null, "e": 396, "s": 286, "text": "Illustration of TextField using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 483, "s": 396, "text": "Refer to the following articles to check how to create a project and an app in Django." }, { "code": null, "e": 534, "s": 483, "text": "How to Create a Basic Project using MVT in Django?" }, { "code": null, "e": 567, "s": 534, "text": "How to Create an App in Django ?" }, { "code": null, "e": 626, "s": 567, "text": "Enter the following code into models.py file of geeks app." }, { "code": "from django.db import modelsfrom django.db.models import Model# Create your models here. class GeeksModel(Model): geeks_field = models.TextField()", "e": 777, "s": 626, "text": null }, { "code": null, "e": 813, "s": 777, "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": 1051, "s": 813, "text": null }, { "code": null, "e": 1109, "s": 1051, "text": "Now when we run makemigrations command from the terminal," }, { "code": null, "e": 1141, "s": 1109, "text": "Python manage.py makemigrations" }, { "code": null, "e": 1241, "s": 1141, "text": "A new folder named migrations would be created in geeks directory with a file named 0001_initial.py" }, { "code": "# Generated by Django 2.2.5 on 2019-09-25 06:00 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name ='GeeksModel', fields =[ ('id', models.AutoField( auto_created = True, primary_key = True, serialize = False, verbose_name ='ID' )), ('geeks_field', models.TextField( )), ], ), ]", "e": 1861, "s": 1241, "text": null }, { "code": null, "e": 1870, "s": 1861, "text": "Now run," }, { "code": null, "e": 1895, "s": 1870, "text": "Python manage.py migrate" }, { "code": null, "e": 2031, "s": 1895, "text": "Thus, an geeks_field TextField is created when you run migrations on the project. It is a field to store small- to large-sized strings." }, { "code": null, "e": 2284, "s": 2031, "text": "TextField is used for storing large text in the database. One can store paragraphs, data, etc. To store smaller text like First_name, Last_name, CharField should be used. Let us create an instance of the TextField we created and check if it is working." }, { "code": "# importing the model# from geeks appfrom geeks.models import GeeksModel # creating a instance of # GeeksModelgeek_object = GeeksModel.objects.create(geeks_field =\"GfG is the best\")geek_object.save()", "e": 2485, "s": 2284, "text": null }, { "code": null, "e": 2564, "s": 2485, "text": "Now let’s check it in admin server. We have created an instance of GeeksModel." }, { "code": null, "e": 2910, "s": 2564, "text": "Field Options 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 null = True to TextField will enable it to store empty values for that table in relational database.Here are the field options and attributes that an TextField can use." }, { "code": null, "e": 2922, "s": 2910, "text": "NaveenArora" }, { "code": null, "e": 2936, "s": 2922, "text": "Django-models" }, { "code": null, "e": 2950, "s": 2936, "text": "Python Django" }, { "code": null, "e": 2957, "s": 2950, "text": "Python" }, { "code": null, "e": 3055, "s": 2957, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3073, "s": 3055, "text": "Python Dictionary" }, { "code": null, "e": 3115, "s": 3073, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3137, "s": 3115, "text": "Enumerate() in Python" }, { "code": null, "e": 3172, "s": 3137, "text": "Read a file line by line in Python" }, { "code": null, "e": 3198, "s": 3172, "text": "Python String | replace()" }, { "code": null, "e": 3230, "s": 3198, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3259, "s": 3230, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3286, "s": 3259, "text": "Python Classes and Objects" }, { "code": null, "e": 3316, "s": 3286, "text": "Iterate over a list in Python" } ]
C# | Dictionary Class
01 Sep, 2021 The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System.Collections.Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1) because the Dictionary class is implemented as a hash table. Every key in a Dictionary <TKey, TValue> must be unique according to the dictionary’s equality comparer. Note: A key cannot be null, but a value can be if the value type TValue is a reference type. Parameters: TKey : Denotes the type of the keys in the dictionary. TValue : Denotes the type of the values in the dictionary. Since the Dictionary<TKey, TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair <TKey, TValue> of the key type and the value type. Constructors Example: C# // C# code to create a Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("1", "C"); myDict.Add("2", "C++"); myDict.Add("3", "Java"); myDict.Add("4", "Python"); myDict.Add("5", "C#"); myDict.Add("6", "HTML"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); // Displaying the key/value pairs in myDict Console.WriteLine("\nThe key/value pairs"+ " in myDict are : "); foreach(KeyValuePair<string, string> kvp in myDict) { Console.WriteLine("Key = {0}, Value = {1}", kvp.Key, kvp.Value); } }} Total key/value pairs in myDict are : 6 The key/value pairs in myDict are : Key = 1, Value = C Key = 2, Value = C++ Key = 3, Value = Java Key = 4, Value = Python Key = 5, Value = C# Key = 6, Value = HTML Properties Example 1: C# // C# code to get the keys// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("1", "C"); myDict.Add("2", "C++"); myDict.Add("3", "Java"); myDict.Add("4", "Python"); myDict.Add("5", "C#"); myDict.Add("6", "HTML"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); // To get the keys alone, use the Keys property. Dictionary<string, string>.KeyCollection keyColl = myDict.Keys; // The elements of the KeyCollection // are strongly typed with the type // that was specified for dictionary keys. foreach(string s in keyColl) { Console.WriteLine("Key = {0}", s); } }} Total key/value pairs in myDict are : 6 Key = 1 Key = 2 Key = 3 Key = 4 Key = 5 Key = 6 Example 2: C# // C# code to get the values// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("1", "C"); myDict.Add("2", "C++"); myDict.Add("3", "Java"); myDict.Add("4", "Python"); myDict.Add("5", "C#"); myDict.Add("6", "HTML"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs"+ " in myDict are : " + myDict.Count); // To get the values alone, use the Values property. Dictionary<string, string>.ValueCollection valueColl = myDict.Values; // The elements of the ValueCollection // are strongly typed with the type // that was specified for dictionary values. foreach(string s in valueColl) { Console.WriteLine("Value = {0}", s); } }} Total key/value pairs in myDict are : 6 Value = C Value = C++ Value = Java Value = Python Value = C# Value = HTML Methods Example 1: C# // C# code to remove all entries// from Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("1", "C"); myDict.Add("2", "C++"); myDict.Add("3", "Java"); myDict.Add("4", "Python"); myDict.Add("5", "C#"); myDict.Add("6", "HTML"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); myDict.Clear(); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs in "+ "myDict after Clear() operation are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 Total key/value pairs in myDict after Clear() operation are : 0 Example 2: C# // C# code to remove the entry with// the specified key from the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add("1", "C"); myDict.Add("2", "C++"); myDict.Add("3", "Java"); myDict.Add("4", "Python"); myDict.Add("5", "C#"); myDict.Add("6", "HTML"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs "+ "in myDict are : " + myDict.Count); // Remove the entry with the // specified key from the Dictionary myDict.Remove("Russia"); // To get count of key/value pairs in myDict Console.WriteLine("Total key/value pairs in"+ " myDict after Remove() operation are : " + myDict.Count); }} Total key/value pairs in myDict are : 6 Total key/value pairs in myDict after Remove() operation are : 6 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2 mosheborisute CSharp Dictionary Class CSharp-Generic-Namespace C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Sep, 2021" }, { "code": null, "e": 591, "s": 28, "text": "The Dictionary<TKey, TValue> Class in C# is a collection of Keys and Values. It is a generic collection class in the System.Collections.Generic namespace. The Dictionary <TKey, TValue> generic class provides a mapping from a set of keys to a set of values. Each addition to the dictionary consists of a value and its associated key. Retrieving a value by using its key is very fast, close to O(1) because the Dictionary class is implemented as a hash table. Every key in a Dictionary <TKey, TValue> must be unique according to the dictionary’s equality comparer." }, { "code": null, "e": 684, "s": 591, "text": "Note: A key cannot be null, but a value can be if the value type TValue is a reference type." }, { "code": null, "e": 698, "s": 684, "text": "Parameters: " }, { "code": null, "e": 753, "s": 698, "text": "TKey : Denotes the type of the keys in the dictionary." }, { "code": null, "e": 812, "s": 753, "text": "TValue : Denotes the type of the values in the dictionary." }, { "code": null, "e": 1050, "s": 812, "text": "Since the Dictionary<TKey, TValue> is a collection of keys and values, the element type is not the type of the key or the type of the value. Instead, the element type is a KeyValuePair <TKey, TValue> of the key type and the value type. " }, { "code": null, "e": 1063, "s": 1050, "text": "Constructors" }, { "code": null, "e": 1072, "s": 1063, "text": "Example:" }, { "code": null, "e": 1075, "s": 1072, "text": "C#" }, { "code": "// C# code to create a Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"1\", \"C\"); myDict.Add(\"2\", \"C++\"); myDict.Add(\"3\", \"Java\"); myDict.Add(\"4\", \"Python\"); myDict.Add(\"5\", \"C#\"); myDict.Add(\"6\", \"HTML\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); // Displaying the key/value pairs in myDict Console.WriteLine(\"\\nThe key/value pairs\"+ \" in myDict are : \"); foreach(KeyValuePair<string, string> kvp in myDict) { Console.WriteLine(\"Key = {0}, Value = {1}\", kvp.Key, kvp.Value); } }}", "e": 2105, "s": 1075, "text": null }, { "code": null, "e": 2311, "s": 2105, "text": "Total key/value pairs in myDict are : 6\n\nThe key/value pairs in myDict are : \nKey = 1, Value = C\nKey = 2, Value = C++\nKey = 3, Value = Java\nKey = 4, Value = Python\nKey = 5, Value = C#\nKey = 6, Value = HTML" }, { "code": null, "e": 2324, "s": 2313, "text": "Properties" }, { "code": null, "e": 2335, "s": 2324, "text": "Example 1:" }, { "code": null, "e": 2338, "s": 2335, "text": "C#" }, { "code": "// C# code to get the keys// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"1\", \"C\"); myDict.Add(\"2\", \"C++\"); myDict.Add(\"3\", \"Java\"); myDict.Add(\"4\", \"Python\"); myDict.Add(\"5\", \"C#\"); myDict.Add(\"6\", \"HTML\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); // To get the keys alone, use the Keys property. Dictionary<string, string>.KeyCollection keyColl = myDict.Keys; // The elements of the KeyCollection // are strongly typed with the type // that was specified for dictionary keys. foreach(string s in keyColl) { Console.WriteLine(\"Key = {0}\", s); } }}", "e": 3459, "s": 2338, "text": null }, { "code": null, "e": 3547, "s": 3459, "text": "Total key/value pairs in myDict are : 6\nKey = 1\nKey = 2\nKey = 3\nKey = 4\nKey = 5\nKey = 6" }, { "code": null, "e": 3560, "s": 3549, "text": "Example 2:" }, { "code": null, "e": 3563, "s": 3560, "text": "C#" }, { "code": "// C# code to get the values// in the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"1\", \"C\"); myDict.Add(\"2\", \"C++\"); myDict.Add(\"3\", \"Java\"); myDict.Add(\"4\", \"Python\"); myDict.Add(\"5\", \"C#\"); myDict.Add(\"6\", \"HTML\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs\"+ \" in myDict are : \" + myDict.Count); // To get the values alone, use the Values property. Dictionary<string, string>.ValueCollection valueColl = myDict.Values; // The elements of the ValueCollection // are strongly typed with the type // that was specified for dictionary values. foreach(string s in valueColl) { Console.WriteLine(\"Value = {0}\", s); } }}", "e": 4707, "s": 3563, "text": null }, { "code": null, "e": 4821, "s": 4707, "text": "Total key/value pairs in myDict are : 6\nValue = C\nValue = C++\nValue = Java\nValue = Python\nValue = C#\nValue = HTML" }, { "code": null, "e": 4831, "s": 4823, "text": "Methods" }, { "code": null, "e": 4842, "s": 4831, "text": "Example 1:" }, { "code": null, "e": 4845, "s": 4842, "text": "C#" }, { "code": "// C# code to remove all entries// from Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"1\", \"C\"); myDict.Add(\"2\", \"C++\"); myDict.Add(\"3\", \"Java\"); myDict.Add(\"4\", \"Python\"); myDict.Add(\"5\", \"C#\"); myDict.Add(\"6\", \"HTML\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); myDict.Clear(); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs in \"+ \"myDict after Clear() operation are : \" + myDict.Count); }}", "e": 5801, "s": 4845, "text": null }, { "code": null, "e": 5905, "s": 5801, "text": "Total key/value pairs in myDict are : 6\nTotal key/value pairs in myDict after Clear() operation are : 0" }, { "code": null, "e": 5918, "s": 5907, "text": "Example 2:" }, { "code": null, "e": 5921, "s": 5918, "text": "C#" }, { "code": "// C# code to remove the entry with// the specified key from the Dictionaryusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Create a new dictionary of // strings, with string keys. Dictionary<string, string> myDict = new Dictionary<string, string>(); // Adding key/value pairs in myDict myDict.Add(\"1\", \"C\"); myDict.Add(\"2\", \"C++\"); myDict.Add(\"3\", \"Java\"); myDict.Add(\"4\", \"Python\"); myDict.Add(\"5\", \"C#\"); myDict.Add(\"6\", \"HTML\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs \"+ \"in myDict are : \" + myDict.Count); // Remove the entry with the // specified key from the Dictionary myDict.Remove(\"Russia\"); // To get count of key/value pairs in myDict Console.WriteLine(\"Total key/value pairs in\"+ \" myDict after Remove() operation are : \" + myDict.Count); }}", "e": 6986, "s": 5921, "text": null }, { "code": null, "e": 7091, "s": 6986, "text": "Total key/value pairs in myDict are : 6\nTotal key/value pairs in myDict after Remove() operation are : 6" }, { "code": null, "e": 7105, "s": 7093, "text": "Reference: " }, { "code": null, "e": 7213, "s": 7105, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.dictionary-2?view=netframework-4.7.2" }, { "code": null, "e": 7229, "s": 7215, "text": "mosheborisute" }, { "code": null, "e": 7253, "s": 7229, "text": "CSharp Dictionary Class" }, { "code": null, "e": 7278, "s": 7253, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 7281, "s": 7278, "text": "C#" } ]
LinkedHashSet in Java with Examples
04 Mar, 2022 The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted. The Hierarchy of LinkedHashSet is as follows: Parameters: The type of elements maintained by this set All Implemented Interfaces are as listed below: Serializable Cloneable, Iterable<E> Collection<E> Set<E> Syntax: Declaration public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable Contains unique elements only like HashSet. It extends the HashSet class and implements the Set interface. Maintains insertion order. 1. LinkedHashSet(): This constructor is used to create a default HashSet LinkedHashSet<E> hs = new LinkedHashSet<E>(); 2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C. LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c); 3. LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the integer mentioned in the parameter. LinkedHashSet<E> hs = new LinkedHashSet<E>(int size); 4. LinkedHashSet(int capacity, float fillRatio): Can be used to initialize both the capacity and the fill ratio, also called the load capacity of the LinkedHashSet with the arguments mentioned in the parameter. When the number of elements exceeds the capacity of the hash set is multiplied with the fill ratio thus expanding the capacity of the LinkedHashSet. LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity, int fillRatio); Example: Java // Java Program to Illustrate LinkedHashSet // Importing required classesimport java.util.LinkedHashSet; // Main class// LinkedHashSetExamplepublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinkedHashSet of string type LinkedHashSet<String> linkedset = new LinkedHashSet<String>(); // Adding element to LinkedHashSet // using add() method linkedset.add("A"); linkedset.add("B"); linkedset.add("C"); linkedset.add("D"); // Note: This will not add new element // as A already exists linkedset.add("A"); linkedset.add("E"); // Getting size of LinkedHashSet // using size() method System.out.println("Size of LinkedHashSet = " + linkedset.size()); System.out.println("Original LinkedHashSet:" + linkedset); // Removing existing entry from above Set // using remove() method System.out.println("Removing D from LinkedHashSet: " + linkedset.remove("D")); // Removing existing entry from above Set // that does not exist in Set System.out.println( "Trying to Remove Z which is not " + "present: " + linkedset.remove("Z")); // Checking for element whether it is present inside // Set or not using contains() method System.out.println("Checking if A is present=" + linkedset.contains("A")); // Noew lastly printing the updated LinkedHashMap System.out.println("Updated LinkedHashSet: " + linkedset); }} Size of LinkedHashSet = 5 Original LinkedHashSet:[A, B, C, D, E] Removing D from LinkedHashSet: true Trying to Remove Z which is not present: false Checking if A is present=true Updated LinkedHashSet: [A, B, C, E] Let’s see how to perform a few frequently used operations on the LinkedHashSet. Operation 1: Adding Elements In order to add an element to the LinkedHashSet, we can use the add() method. This is different from HashSet because in HashSet, the insertion order is not retained but is retained in the LinkedHashSet. Example: Java // Java Program to Add Elements to LinkedHashSet // Importing required classesimport java.io.*;import java.util.*; // Main class// AddingElementsToLinkedHashSetclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinkedHashSet LinkedHashSet<String> hs = new LinkedHashSet<String>(); // Adding elements to above Set // using add() method // Note: Insertion order is maintained hs.add("Geek"); hs.add("For"); hs.add("Geeks"); // Printing elements of Set System.out.println("LinkedHashSet : " + hs); }} LinkedHashSet : [Geek, For, Geeks] Operation 2: Removing Elements The values can be removed from the LinkedHashSet using the remove() method. Example: Java // Java program to Remove Elements from LinkedHashSet // Importing required classesimport java.io.*;import java.util.*; // Main class// RemoveElementsFromLinkedHashSetclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinekdhashSet of string type LinkedHashSet<String> hs = new LinkedHashSet<String>(); // Adding elements to above Set // using add() method hs.add("Geek"); hs.add("For"); hs.add("Geeks"); hs.add("A"); hs.add("B"); hs.add("Z"); // Printing all above elements to the console System.out.println("Initial HashSet " + hs); // Removing the element from above Set hs.remove("B"); // Again removing the element System.out.println("After removing element " + hs); // Returning false if the element is not present System.out.println(hs.remove("AC")); }} Initial HashSet [Geek, For, Geeks, A, B, Z] After removing element [Geek, For, Geeks, A, Z] false Operation 3: Iterating through LinkedHashSet Iterate through the elements of LinkedHashSet using the iterator() method. The most famous one is to use the enhanced for loop. Example: Java // Java Program to Illustrate Iterating over LinkedHashSet // Importing required classesimport java.io.*;import java.util.*; // Main class// IteratingLinkedHashSetclass GFG { // Main driver method public static void main(String[] args) { // Instantiate an object of Set // Since LinkedHashSet implements Set // Set points to LinkedHashSet Set<String> hs = new LinkedHashSet<String>(); // Adding elements to above Set // using add() method hs.add("Geek"); hs.add("For"); hs.add("Geeks"); hs.add("A"); hs.add("B"); hs.add("Z"); // Iterating though the LinkedHashSet // using iterators Iterator itr = hs.iterator(); while (itr.hasNext()) System.out.print(itr.next() + ", "); // New line System.out.println(); // Using enhanced for loop for iteration for (String s : hs) System.out.print(s + ", "); System.out.println(); }} Geek, For, Geeks, A, B, Z, Geek, For, Geeks, A, B, Z, Here, E is the type of element stored. METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION METHOD DESCRIPTION removeIf(Predicate<? super E> filter) METHOD DESCRIPTION METHOD DESCRIPTION forEach(Consumer<? super T> action) Following is the difference between LinkedHashMap and LinkedHashSet: Note: Keeping the insertion order in both LinkedHashmap and LinkedHashset have additional associated costs, both in terms of spending additional CPU cycles and needing more memory. If you do not need the insertion order maintained, it is recommended to use the lighter-weight HashSet and HashMap instead. This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks’s main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Chinmoy Lenka Akanksha_Rai Ganeshchowdharysadanala solankimayank simmytarika5 Java - util package Java-Collections java-hashset java-LinkedHashSet Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Mar, 2022" }, { "code": null, "e": 520, "s": 52, "text": "The LinkedHashSet is an ordered version of HashSet that maintains a doubly-linked List across all elements. When the iteration order is needed to be maintained this class is used. When iterating through a HashSet the order is unpredictable, while a LinkedHashSet lets us iterate through the elements in the order in which they were inserted. When cycling through LinkedHashSet using an iterator, the elements will be returned in the order in which they were inserted." }, { "code": null, "e": 566, "s": 520, "text": "The Hierarchy of LinkedHashSet is as follows:" }, { "code": null, "e": 622, "s": 566, "text": "Parameters: The type of elements maintained by this set" }, { "code": null, "e": 727, "s": 622, "text": "All Implemented Interfaces are as listed below:\nSerializable\nCloneable,\nIterable<E>\nCollection<E>\nSet<E>" }, { "code": null, "e": 748, "s": 727, "text": "Syntax: Declaration " }, { "code": null, "e": 840, "s": 748, "text": "public class LinkedHashSet<E> extends HashSet<E> implements Set<E>, Cloneable, Serializable" }, { "code": null, "e": 947, "s": 840, "text": "Contains unique elements only like HashSet. It extends the HashSet class and implements the Set interface." }, { "code": null, "e": 974, "s": 947, "text": "Maintains insertion order." }, { "code": null, "e": 1047, "s": 974, "text": "1. LinkedHashSet(): This constructor is used to create a default HashSet" }, { "code": null, "e": 1093, "s": 1047, "text": "LinkedHashSet<E> hs = new LinkedHashSet<E>();" }, { "code": null, "e": 1197, "s": 1093, "text": "2. LinkedHashSet(Collection C): Used in initializing the HashSet with the elements of the collection C." }, { "code": null, "e": 1255, "s": 1197, "text": "LinkedHashSet<E> hs = new LinkedHashSet<E>(Collection c);" }, { "code": null, "e": 1377, "s": 1255, "text": "3. LinkedHashSet(int size): Used to initialize the size of the LinkedHashSet with the integer mentioned in the parameter." }, { "code": null, "e": 1431, "s": 1377, "text": "LinkedHashSet<E> hs = new LinkedHashSet<E>(int size);" }, { "code": null, "e": 1791, "s": 1431, "text": "4. LinkedHashSet(int capacity, float fillRatio): Can be used to initialize both the capacity and the fill ratio, also called the load capacity of the LinkedHashSet with the arguments mentioned in the parameter. When the number of elements exceeds the capacity of the hash set is multiplied with the fill ratio thus expanding the capacity of the LinkedHashSet." }, { "code": null, "e": 1864, "s": 1791, "text": "LinkedHashSet<E> hs = new LinkedHashSet<E>(int capacity, int fillRatio);" }, { "code": null, "e": 1873, "s": 1864, "text": "Example:" }, { "code": null, "e": 1878, "s": 1873, "text": "Java" }, { "code": "// Java Program to Illustrate LinkedHashSet // Importing required classesimport java.util.LinkedHashSet; // Main class// LinkedHashSetExamplepublic class GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinkedHashSet of string type LinkedHashSet<String> linkedset = new LinkedHashSet<String>(); // Adding element to LinkedHashSet // using add() method linkedset.add(\"A\"); linkedset.add(\"B\"); linkedset.add(\"C\"); linkedset.add(\"D\"); // Note: This will not add new element // as A already exists linkedset.add(\"A\"); linkedset.add(\"E\"); // Getting size of LinkedHashSet // using size() method System.out.println(\"Size of LinkedHashSet = \" + linkedset.size()); System.out.println(\"Original LinkedHashSet:\" + linkedset); // Removing existing entry from above Set // using remove() method System.out.println(\"Removing D from LinkedHashSet: \" + linkedset.remove(\"D\")); // Removing existing entry from above Set // that does not exist in Set System.out.println( \"Trying to Remove Z which is not \" + \"present: \" + linkedset.remove(\"Z\")); // Checking for element whether it is present inside // Set or not using contains() method System.out.println(\"Checking if A is present=\" + linkedset.contains(\"A\")); // Noew lastly printing the updated LinkedHashMap System.out.println(\"Updated LinkedHashSet: \" + linkedset); }}", "e": 3600, "s": 1878, "text": null }, { "code": null, "e": 3814, "s": 3600, "text": "Size of LinkedHashSet = 5\nOriginal LinkedHashSet:[A, B, C, D, E]\nRemoving D from LinkedHashSet: true\nTrying to Remove Z which is not present: false\nChecking if A is present=true\nUpdated LinkedHashSet: [A, B, C, E]" }, { "code": null, "e": 3894, "s": 3814, "text": "Let’s see how to perform a few frequently used operations on the LinkedHashSet." }, { "code": null, "e": 3923, "s": 3894, "text": "Operation 1: Adding Elements" }, { "code": null, "e": 4126, "s": 3923, "text": "In order to add an element to the LinkedHashSet, we can use the add() method. This is different from HashSet because in HashSet, the insertion order is not retained but is retained in the LinkedHashSet." }, { "code": null, "e": 4135, "s": 4126, "text": "Example:" }, { "code": null, "e": 4140, "s": 4135, "text": "Java" }, { "code": "// Java Program to Add Elements to LinkedHashSet // Importing required classesimport java.io.*;import java.util.*; // Main class// AddingElementsToLinkedHashSetclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinkedHashSet LinkedHashSet<String> hs = new LinkedHashSet<String>(); // Adding elements to above Set // using add() method // Note: Insertion order is maintained hs.add(\"Geek\"); hs.add(\"For\"); hs.add(\"Geeks\"); // Printing elements of Set System.out.println(\"LinkedHashSet : \" + hs); }}", "e": 4770, "s": 4140, "text": null }, { "code": null, "e": 4805, "s": 4770, "text": "LinkedHashSet : [Geek, For, Geeks]" }, { "code": null, "e": 4836, "s": 4805, "text": "Operation 2: Removing Elements" }, { "code": null, "e": 4912, "s": 4836, "text": "The values can be removed from the LinkedHashSet using the remove() method." }, { "code": null, "e": 4921, "s": 4912, "text": "Example:" }, { "code": null, "e": 4926, "s": 4921, "text": "Java" }, { "code": "// Java program to Remove Elements from LinkedHashSet // Importing required classesimport java.io.*;import java.util.*; // Main class// RemoveElementsFromLinkedHashSetclass GFG { // Main driver method public static void main(String[] args) { // Creating an empty LinekdhashSet of string type LinkedHashSet<String> hs = new LinkedHashSet<String>(); // Adding elements to above Set // using add() method hs.add(\"Geek\"); hs.add(\"For\"); hs.add(\"Geeks\"); hs.add(\"A\"); hs.add(\"B\"); hs.add(\"Z\"); // Printing all above elements to the console System.out.println(\"Initial HashSet \" + hs); // Removing the element from above Set hs.remove(\"B\"); // Again removing the element System.out.println(\"After removing element \" + hs); // Returning false if the element is not present System.out.println(hs.remove(\"AC\")); }}", "e": 5888, "s": 4926, "text": null }, { "code": null, "e": 5986, "s": 5888, "text": "Initial HashSet [Geek, For, Geeks, A, B, Z]\nAfter removing element [Geek, For, Geeks, A, Z]\nfalse" }, { "code": null, "e": 6031, "s": 5986, "text": "Operation 3: Iterating through LinkedHashSet" }, { "code": null, "e": 6160, "s": 6031, "text": "Iterate through the elements of LinkedHashSet using the iterator() method. The most famous one is to use the enhanced for loop." }, { "code": null, "e": 6169, "s": 6160, "text": "Example:" }, { "code": null, "e": 6174, "s": 6169, "text": "Java" }, { "code": "// Java Program to Illustrate Iterating over LinkedHashSet // Importing required classesimport java.io.*;import java.util.*; // Main class// IteratingLinkedHashSetclass GFG { // Main driver method public static void main(String[] args) { // Instantiate an object of Set // Since LinkedHashSet implements Set // Set points to LinkedHashSet Set<String> hs = new LinkedHashSet<String>(); // Adding elements to above Set // using add() method hs.add(\"Geek\"); hs.add(\"For\"); hs.add(\"Geeks\"); hs.add(\"A\"); hs.add(\"B\"); hs.add(\"Z\"); // Iterating though the LinkedHashSet // using iterators Iterator itr = hs.iterator(); while (itr.hasNext()) System.out.print(itr.next() + \", \"); // New line System.out.println(); // Using enhanced for loop for iteration for (String s : hs) System.out.print(s + \", \"); System.out.println(); }}", "e": 7182, "s": 6174, "text": null }, { "code": null, "e": 7238, "s": 7182, "text": "Geek, For, Geeks, A, B, Z, \nGeek, For, Geeks, A, B, Z, " }, { "code": null, "e": 7277, "s": 7238, "text": "Here, E is the type of element stored." }, { "code": null, "e": 7284, "s": 7277, "text": "METHOD" }, { "code": null, "e": 7296, "s": 7284, "text": "DESCRIPTION" }, { "code": null, "e": 7303, "s": 7296, "text": "METHOD" }, { "code": null, "e": 7315, "s": 7303, "text": "DESCRIPTION" }, { "code": null, "e": 7322, "s": 7315, "text": "METHOD" }, { "code": null, "e": 7334, "s": 7322, "text": "DESCRIPTION" }, { "code": null, "e": 7341, "s": 7334, "text": "METHOD" }, { "code": null, "e": 7353, "s": 7341, "text": "DESCRIPTION" }, { "code": null, "e": 7381, "s": 7353, "text": "removeIf(Predicate<? super " }, { "code": null, "e": 7392, "s": 7381, "text": "E> filter)" }, { "code": null, "e": 7399, "s": 7392, "text": "METHOD" }, { "code": null, "e": 7411, "s": 7399, "text": "DESCRIPTION" }, { "code": null, "e": 7418, "s": 7411, "text": "METHOD" }, { "code": null, "e": 7430, "s": 7418, "text": "DESCRIPTION" }, { "code": null, "e": 7455, "s": 7430, "text": "forEach(Consumer<? super" }, { "code": null, "e": 7467, "s": 7455, "text": " T> action)" }, { "code": null, "e": 7536, "s": 7467, "text": "Following is the difference between LinkedHashMap and LinkedHashSet:" }, { "code": null, "e": 7841, "s": 7536, "text": "Note: Keeping the insertion order in both LinkedHashmap and LinkedHashset have additional associated costs, both in terms of spending additional CPU cycles and needing more memory. If you do not need the insertion order maintained, it is recommended to use the lighter-weight HashSet and HashMap instead." }, { "code": null, "e": 8266, "s": 7841, "text": "This article is contributed by Pratik Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks’s main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 8280, "s": 8266, "text": "Chinmoy Lenka" }, { "code": null, "e": 8293, "s": 8280, "text": "Akanksha_Rai" }, { "code": null, "e": 8317, "s": 8293, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 8331, "s": 8317, "text": "solankimayank" }, { "code": null, "e": 8344, "s": 8331, "text": "simmytarika5" }, { "code": null, "e": 8364, "s": 8344, "text": "Java - util package" }, { "code": null, "e": 8381, "s": 8364, "text": "Java-Collections" }, { "code": null, "e": 8394, "s": 8381, "text": "java-hashset" }, { "code": null, "e": 8413, "s": 8394, "text": "java-LinkedHashSet" }, { "code": null, "e": 8418, "s": 8413, "text": "Java" }, { "code": null, "e": 8423, "s": 8418, "text": "Java" }, { "code": null, "e": 8440, "s": 8423, "text": "Java-Collections" } ]
How to convert a PDF document to a preview image in PHP?
22 Sep, 2021 Converting a PDF document into a set of images may not sound that fun, but it can have a few applications. As the content from images cannot be copied that easily, the conversion makes the document strictly ‘read-only’ and brings an extra layer of protection from plagiarism. The images may also come in handy when you need some ready-made slides for your quick office presentations or for embedding them into your reports and blogs.In this post, however, we will limit ourselves to a much smaller example, that is to generate an image preview from a given PDF document. “Why previews?”, you may ask. Well, one may need it for his library management system, her online e-book retail store or just for some insane weekend programming challenge. Where do you think you can use this concept into your project? Do let me know in the comments.Now implementing the complete conversion algorithm from scratch is not feasible, so we will stick to the 3rd party libraries to ease our task. The methods that I found appealing in this scenario are based on the following tools: Ghostscript: It is a command line utility available for all three major platforms, viz. Windows, Linux and Mac, that interprets PostSript and PDF files. You can read more about it on its official site. ImageMagick: It is a free and open-source software suite for displaying, converting, and editing raster image and vector image files. It is available for majority of mainstream programming languages, including PHP. Here’s the standard documentation for a quick overview. For using Ghostscript into your project, start with its installation. If you are on windows, download the executable from its download page.Linux users can install Ghostscript directly through their default package managers; # RPM based distros, Fedora 26/27/28 $ sudo dnf install ghostscript Verify the installation via this command, $ gs --version After installation, move to the directory containing the PDF file and run the following command. $ gs -dSAFER -dBATCH -sDEVICE=jpeg \ -dTextAlphaBits=4 -dGraphicsAlphaBits=4 \ -dFirstPage=1 -dLastPage=1 -r300 \ -sOutputFile=preview.jpg input.pdf This will generate an image of the first page from the document. Let us understand what it actually does; -sDEVICE: sets the output file format of the image. -sTEXTVAL, -sGRAPHICVAL: sets the anti-aliasing for the resultant image. Allowed values are 1, 2 and 4. -r{NUM}: sets the resolution (in dpi) of the image. -sFirstPage, -sLastPage: set the first and the last page of the document that has to be rendered. -sOutputFile: sets the name of the output file. input.pdf: it is the actual pdf document that is used for conversion. Now for using this command in PHP, we call exec() function. For ex: php <?php exec( "ls -l", $output_str, $return_val ); foreach ( $output_str as $line ) { echo $line . "\n";} ?>; This example, on Linux, will execute ls command and list all the directories and files onto the console.We can use this concept and execute ghostscript command from our PHP code. Here’s how I have done it; php <?php function is_pdf ( $file ) { $file_content = file_get_contents( $file ); if ( preg_match( "/^%PDF-[0-1]\.[0-9]+/", $file_content ) ) { return true; } else { return false; }} function create_preview ( $file ) { $output_format = "jpeg"; $antialiasing = "4"; $preview_page = "1"; $resolution = "300"; $output_file = "preview.jpg"; $exec_command = "gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=" . $output_format . " "; $exec_command .= "-dTextAlphaBits=". $antialiasing . " -dGraphicsAlphaBits=" . $antialiasing . " "; $exec_command .= "-dFirstPage=" . $preview_page . " -dLastPage=" . $preview_page . " "; $exec_command .= "-r" . $resolution . " "; $exec_command .= "-sOutputFile=" . $output_file . " '" . $file . "'"; echo "Executing command...\n"; exec( $exec_command, $command_output, $return_val ); foreach( $command_output as $line ) { echo $line . "\n"; } if ( !$return_val ) { echo "Preview created successfully!!\n"; } else { echo "Error while creating the preview.\n"; }} function __main__() { global $argv; $input_file = $argv[1]; if ( is_pdf( $input_file ) ) { // Create preview for the pdf create_preview( $input_file ); } else { echo "The input file " . $input_file . " is not a valid PDF document.\n"; }} __main__(); ?> The execution starts from __main__() which takes PDF file at command line. It checks whether the input file is valid PDF or not. If valid, it executes the ghostscript command over the input file. Output: $ php pdf_preview.php input.pdf Executing command... GPL Ghostscript 9.22 (2017-10-04) Copyright (C) 2017 Artifex Software, Inc. All rights reserved. This software comes with NO WARRANTY: see the file PUBLIC for details. Processing pages 1 through 1. Page 1 Preview created successfully!! As usual, we will start with installing ImageMagick binaries into the system. Start with the dependencies; $ sudo dnf install gcc php-devel php-pear After that, install ImageMagick; $ sudo dnf install ImageMagick ImageMagick-devel Then install the PHP wrapper classes; $ sudo pecl install imagick $ sudo bash -c "echo "extension=imagick.so" > /etc/php.d/imagick.ini" If you are planning to use it on LAMP architecture, consider restarting the Apache Web server; $ sudo service httpd restart Now that our system is ready, we can use ImageMagick into our example project. The basic functionality of the script remains the same. All you have to do is to replace the content of the create_preview() function with the following code. php function create_preview ( $file ) { $output_format = "jpeg"; $preview_page = "1"; $resolution = "300"; $output_file = "imagick_preview.jpg"; echo "Fetching preview...\n"; $img_data = new Imagick(); $img_data->setResolution( $resolution, $resolution ); $img_data->readImage( $file . "[" . ($preview_page - 1) . "]" ); $img_data->setImageFormat( $output_format ); file_put_contents( $output_file, $img_data, FILE_USE_INCLUDE_PATH );} The code is self-explanatory. We are defining an instance of Imagick type and setting various parameters like resolution, file format, etc. The PDF page you want to render is mentioned as an array index after the file name. For ex: First page: input.pdf[0] Second page: input.pdf[1] . . . Nth page: input.pdf[N - 1] Output: $ php pdf_preview.php input.pdf Fetching preview... Some of you might be wondering why to use this method over the previous one. Well, I found the ImageMagick one pretty consistent with the PHP code. A command line in programming does not look that good and sometimes becomes notorious to understand. However, with the same set of configurations, Ghostscript produced smaller image files than the ones rendered by ImageMagick. I am not sure if that is because of some optimization issues, but the difference is not of that big concern. The choice of one over the other is merely based on your own taste.So this is how you create a preview for a given PDF document. I hope you have learned something new from this post. Which method would you prefer? Have any suggestions for further improvements? Feel free to mention them in the comments. anikakapoor Picked Technical Scripter 2018 PHP Technical Scripter Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Insert Form Data into Database using PHP ? How to convert array to string in PHP ? How to Upload Image into Database and Display it using PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP 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 Sep, 2021" }, { "code": null, "e": 1097, "s": 28, "text": "Converting a PDF document into a set of images may not sound that fun, but it can have a few applications. As the content from images cannot be copied that easily, the conversion makes the document strictly ‘read-only’ and brings an extra layer of protection from plagiarism. The images may also come in handy when you need some ready-made slides for your quick office presentations or for embedding them into your reports and blogs.In this post, however, we will limit ourselves to a much smaller example, that is to generate an image preview from a given PDF document. “Why previews?”, you may ask. Well, one may need it for his library management system, her online e-book retail store or just for some insane weekend programming challenge. Where do you think you can use this concept into your project? Do let me know in the comments.Now implementing the complete conversion algorithm from scratch is not feasible, so we will stick to the 3rd party libraries to ease our task. The methods that I found appealing in this scenario are based on the following tools: " }, { "code": null, "e": 1299, "s": 1097, "text": "Ghostscript: It is a command line utility available for all three major platforms, viz. Windows, Linux and Mac, that interprets PostSript and PDF files. You can read more about it on its official site." }, { "code": null, "e": 1570, "s": 1299, "text": "ImageMagick: It is a free and open-source software suite for displaying, converting, and editing raster image and vector image files. It is available for majority of mainstream programming languages, including PHP. Here’s the standard documentation for a quick overview." }, { "code": null, "e": 1799, "s": 1572, "text": "For using Ghostscript into your project, start with its installation. If you are on windows, download the executable from its download page.Linux users can install Ghostscript directly through their default package managers; " }, { "code": null, "e": 1867, "s": 1799, "text": "# RPM based distros, Fedora 26/27/28\n$ sudo dnf install ghostscript" }, { "code": null, "e": 1911, "s": 1867, "text": "Verify the installation via this command, " }, { "code": null, "e": 1926, "s": 1911, "text": "$ gs --version" }, { "code": null, "e": 2025, "s": 1926, "text": "After installation, move to the directory containing the PDF file and run the following command. " }, { "code": null, "e": 2175, "s": 2025, "text": "$ gs -dSAFER -dBATCH -sDEVICE=jpeg \\\n-dTextAlphaBits=4 -dGraphicsAlphaBits=4 \\ \n-dFirstPage=1 -dLastPage=1 -r300 \\\n-sOutputFile=preview.jpg input.pdf" }, { "code": null, "e": 2283, "s": 2175, "text": "This will generate an image of the first page from the document. Let us understand what it actually does; " }, { "code": null, "e": 2335, "s": 2283, "text": "-sDEVICE: sets the output file format of the image." }, { "code": null, "e": 2439, "s": 2335, "text": "-sTEXTVAL, -sGRAPHICVAL: sets the anti-aliasing for the resultant image. Allowed values are 1, 2 and 4." }, { "code": null, "e": 2491, "s": 2439, "text": "-r{NUM}: sets the resolution (in dpi) of the image." }, { "code": null, "e": 2589, "s": 2491, "text": "-sFirstPage, -sLastPage: set the first and the last page of the document that has to be rendered." }, { "code": null, "e": 2637, "s": 2589, "text": "-sOutputFile: sets the name of the output file." }, { "code": null, "e": 2707, "s": 2637, "text": "input.pdf: it is the actual pdf document that is used for conversion." }, { "code": null, "e": 2777, "s": 2707, "text": "Now for using this command in PHP, we call exec() function. For ex: " }, { "code": null, "e": 2781, "s": 2777, "text": "php" }, { "code": "<?php exec( \"ls -l\", $output_str, $return_val ); foreach ( $output_str as $line ) { echo $line . \"\\n\";} ?>;", "e": 2892, "s": 2781, "text": null }, { "code": null, "e": 3099, "s": 2892, "text": "This example, on Linux, will execute ls command and list all the directories and files onto the console.We can use this concept and execute ghostscript command from our PHP code. Here’s how I have done it; " }, { "code": null, "e": 3103, "s": 3099, "text": "php" }, { "code": "<?php function is_pdf ( $file ) { $file_content = file_get_contents( $file ); if ( preg_match( \"/^%PDF-[0-1]\\.[0-9]+/\", $file_content ) ) { return true; } else { return false; }} function create_preview ( $file ) { $output_format = \"jpeg\"; $antialiasing = \"4\"; $preview_page = \"1\"; $resolution = \"300\"; $output_file = \"preview.jpg\"; $exec_command = \"gs -dSAFER -dBATCH -dNOPAUSE -sDEVICE=\" . $output_format . \" \"; $exec_command .= \"-dTextAlphaBits=\". $antialiasing . \" -dGraphicsAlphaBits=\" . $antialiasing . \" \"; $exec_command .= \"-dFirstPage=\" . $preview_page . \" -dLastPage=\" . $preview_page . \" \"; $exec_command .= \"-r\" . $resolution . \" \"; $exec_command .= \"-sOutputFile=\" . $output_file . \" '\" . $file . \"'\"; echo \"Executing command...\\n\"; exec( $exec_command, $command_output, $return_val ); foreach( $command_output as $line ) { echo $line . \"\\n\"; } if ( !$return_val ) { echo \"Preview created successfully!!\\n\"; } else { echo \"Error while creating the preview.\\n\"; }} function __main__() { global $argv; $input_file = $argv[1]; if ( is_pdf( $input_file ) ) { // Create preview for the pdf create_preview( $input_file ); } else { echo \"The input file \" . $input_file . \" is not a valid PDF document.\\n\"; }} __main__(); ?>", "e": 4495, "s": 3103, "text": null }, { "code": null, "e": 4701, "s": 4495, "text": "The execution starts from __main__() which takes PDF file at command line. It checks whether the input file is valid PDF or not. If valid, it executes the ghostscript command over the input file. Output: " }, { "code": null, "e": 4991, "s": 4701, "text": "$ php pdf_preview.php input.pdf\nExecuting command...\nGPL Ghostscript 9.22 (2017-10-04)\nCopyright (C) 2017 Artifex Software, Inc. All rights reserved.\nThis software comes with NO WARRANTY: see the file PUBLIC for details.\nProcessing pages 1 through 1.\nPage 1\nPreview created successfully!!" }, { "code": null, "e": 5102, "s": 4993, "text": "As usual, we will start with installing ImageMagick binaries into the system. Start with the dependencies; " }, { "code": null, "e": 5144, "s": 5102, "text": "$ sudo dnf install gcc php-devel php-pear" }, { "code": null, "e": 5179, "s": 5144, "text": "After that, install ImageMagick; " }, { "code": null, "e": 5228, "s": 5179, "text": "$ sudo dnf install ImageMagick ImageMagick-devel" }, { "code": null, "e": 5268, "s": 5228, "text": "Then install the PHP wrapper classes; " }, { "code": null, "e": 5366, "s": 5268, "text": "$ sudo pecl install imagick\n$ sudo bash -c \"echo \"extension=imagick.so\" > /etc/php.d/imagick.ini\"" }, { "code": null, "e": 5463, "s": 5366, "text": "If you are planning to use it on LAMP architecture, consider restarting the Apache Web server; " }, { "code": null, "e": 5492, "s": 5463, "text": "$ sudo service httpd restart" }, { "code": null, "e": 5732, "s": 5492, "text": "Now that our system is ready, we can use ImageMagick into our example project. The basic functionality of the script remains the same. All you have to do is to replace the content of the create_preview() function with the following code. " }, { "code": null, "e": 5736, "s": 5732, "text": "php" }, { "code": "function create_preview ( $file ) { $output_format = \"jpeg\"; $preview_page = \"1\"; $resolution = \"300\"; $output_file = \"imagick_preview.jpg\"; echo \"Fetching preview...\\n\"; $img_data = new Imagick(); $img_data->setResolution( $resolution, $resolution ); $img_data->readImage( $file . \"[\" . ($preview_page - 1) . \"]\" ); $img_data->setImageFormat( $output_format ); file_put_contents( $output_file, $img_data, FILE_USE_INCLUDE_PATH );}", "e": 6200, "s": 5736, "text": null }, { "code": null, "e": 6434, "s": 6200, "text": "The code is self-explanatory. We are defining an instance of Imagick type and setting various parameters like resolution, file format, etc. The PDF page you want to render is mentioned as an array index after the file name. For ex: " }, { "code": null, "e": 6518, "s": 6434, "text": "First page: input.pdf[0]\nSecond page: input.pdf[1]\n.\n.\n.\nNth page: input.pdf[N - 1]" }, { "code": null, "e": 6528, "s": 6518, "text": "Output: " }, { "code": null, "e": 6580, "s": 6528, "text": "$ php pdf_preview.php input.pdf\nFetching preview..." }, { "code": null, "e": 7369, "s": 6580, "text": "Some of you might be wondering why to use this method over the previous one. Well, I found the ImageMagick one pretty consistent with the PHP code. A command line in programming does not look that good and sometimes becomes notorious to understand. However, with the same set of configurations, Ghostscript produced smaller image files than the ones rendered by ImageMagick. I am not sure if that is because of some optimization issues, but the difference is not of that big concern. The choice of one over the other is merely based on your own taste.So this is how you create a preview for a given PDF document. I hope you have learned something new from this post. Which method would you prefer? Have any suggestions for further improvements? Feel free to mention them in the comments. " }, { "code": null, "e": 7383, "s": 7371, "text": "anikakapoor" }, { "code": null, "e": 7390, "s": 7383, "text": "Picked" }, { "code": null, "e": 7414, "s": 7390, "text": "Technical Scripter 2018" }, { "code": null, "e": 7418, "s": 7414, "text": "PHP" }, { "code": null, "e": 7437, "s": 7418, "text": "Technical Scripter" }, { "code": null, "e": 7454, "s": 7437, "text": "Web Technologies" }, { "code": null, "e": 7458, "s": 7454, "text": "PHP" }, { "code": null, "e": 7556, "s": 7458, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7606, "s": 7556, "text": "How to Insert Form Data into Database using PHP ?" }, { "code": null, "e": 7646, "s": 7606, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 7707, "s": 7646, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 7752, "s": 7707, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 7779, "s": 7752, "text": "Comparing two dates in PHP" }, { "code": null, "e": 7812, "s": 7779, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 7874, "s": 7812, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 7935, "s": 7874, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 7985, "s": 7935, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Prune-and-Search | A Complexity Analysis Overview
19 Jul, 2021 The word “prune” means to reduce something by removing things that are not necessary. So, Prune-and-Search is an excellent algorithmic paradigm for solving various optimization problems. This approach was first suggested by Nimrod Megiddo in 1983. This approach always consists of several iterations. At each iteration, it discards a fraction, say f, of input data and then invokes the same algorithm recursively on the remaining data to solve the problem. The main idea of this approach is to reduce the search space by pruning a fraction of the input elements and recurse on the remaining valid input elements. After some iterations, the size of input data will become so small that it can be solved by the brute-force method in constant time c’. Time Complexity Analysis for such algorithms: Let the time required in each iteration be O(n^k) where- n = size of input data k is some constant. Let f = fraction of data be removed in each iteration. Recursively, the above approach can be written as- T(n) = T((1-f)n) + O(n^k)We have,T(n) <= T((1-f)n) + c*n^k for very large value of n.<= T((1-f)^2 * n) + c*n^k +c*((1-f)^k)*n^k..<= c’ + c*n^k + c*((1-f)^k)n^k + c*((1-f)^2k)n^k + ..... + c*((1-f)^pk)n^k= c’ + c*n^k(1 + (1-f)^k + (1-f)^2k + ..... + (1-f)^pk).Since (1-f) < 1, as n tends to very large numberTherefore, T(n) = O(n^k). It shows that the time complexity of the whole process is of the same order as the time complexity of prune-and-search in each iteration. This approach can be used to analyze the algorithms of many known problems like Binary Search, finding Kth largest/smallest element from an unsorted array(The Selection Problem), 1-center problem(Smallest Enclosing Circle), solving linear programming in two variables, and so on. Examples: 1. Binary Search: As we know that this technique is applied on a sorted list of data for searching the index of a particular value(say ‘val‘), in the given list. For this, we go to the middle element and compare it with val. If the middle element is equal to val then, we return this middle element. Otherwise, we prune one-half of the data and the same technique is used for the remaining elements. For detailed implementation see this.Time Complexity Analysis: In each step, since it is comparing val with only the middle element, so complexity for this step will be O(1) let say it c (any constant). And half of the list is removed, so T(n) = T(n/2) + O(1) if n>=2 Otherwise T(n) = O(1) = c. In simple terms,T(n) = T(n/2) + c= T(n/4) + c + c= T(n/8) + c + c + c.....= T(1) + c + ... + c + c= k times c where k will be a constant.Since half of input is discarded in each iteration, so the value of k will be at most log(n) in worst cases. Therefore, worst case complexity of Binary Search will beT(n) = O(log(n)). 2. The Selection Problem: Given an unordered list of n elements, the task is to find the Kth smallest element from the list. The first very basic approach is to sort the given list in ascending order and directly pick the value at the Kth index. So, sorting will take O(n*log(n)) time in general and O(1) for retrieving the Kth index value. Therefore, overall T(n) = O(n*log(n)) for this approach. The second approach is to use the QuickSelect method i.e Prune-and-Search technique. The basic idea of this prune-and-search selection algorithm is to determine a fraction that will not contain the Kth element and discard that fraction of elements from the next iterations. We know that in order to have an O(n) algorithm, we must have a method that is capable of pruning away a fraction of elements in O(n) time in each iteration. Let P be an element of the list that can partition the given list into two parts, say S1 and S2, such that S1 contains all elements less than or equal to P and S2 contains all elements greater than P. Now we can say that If |S1| == K, then S1[k] will be the Kth smallest element.If |S1| > K, then the Kth element must be present in S1. So discard the second part S2 and recurse on S1 with the same algorithm.Otherwise, the Kth element must be in S2. So discard S1 and recurse on S2 for (K-|S1|)th element in S2. If |S1| == K, then S1[k] will be the Kth smallest element. If |S1| > K, then the Kth element must be present in S1. So discard the second part S2 and recurse on S1 with the same algorithm. Otherwise, the Kth element must be in S2. So discard S1 and recurse on S2 for (K-|S1|)th element in S2. The key point here is how to select P such that we can always discard a fraction of S, no matter whether we are pruning S1 or S2. The answer is P should be the median of list S. Again, finding median is the special case of this problem where K=n/2. But median can be calculated by some other way more efficiently using the following algorithm: Divide the list into n/5 sublists each containing at most 5 elements.Now we can sort each sublist and find their median in constant time.Again find the median of all medians recursively until size becomes at most 5. The obtained median will be a perfect pivot to be used in the Quick Selection Algorithm.[Note that Insertion sort will be a better choice for sorting the smaller sublists of size 5.] Divide the list into n/5 sublists each containing at most 5 elements. Now we can sort each sublist and find their median in constant time. Again find the median of all medians recursively until size becomes at most 5. The obtained median will be a perfect pivot to be used in the Quick Selection Algorithm.[Note that Insertion sort will be a better choice for sorting the smaller sublists of size 5.] Why only 5? Splitting the list into a size of 5 assumes a worst-case split of 70-30. At least half of the medians are greater than the median of medians, so half of the n/5 blocks have at least 3 elements which give 3n/10 split that implies the other partition is 7n/10 in the worst case i.e. T(n) = T(n/5) + T(7n/10) + O(n). Since (n/5 + 7n/10) < 1, so T(n) = O(n) in worst case. Let P be the median of medians which can be represented as- |1''1''1''1''1| 1 1 1 1 |2 2 2 2 2| 2 2 2 2 |3__3__3__3_|P|'3''3''3''3| 4 4 4 4 |4 4 4 4 4| 5 5 5 5 |5__5__5__5__5| As shown here, at least one-fourth of the elements in S are less than or equal to P and at least one-fourth of elements of S is greater than or equal to P. Thus, if we choose P in this way, we can always prune away at least one-fourth of elements during each iteration. Hence, splitting S into sublists of size 5 will be an efficient way to find the median of medians. Now we can state the algorithm as- Prune-and-Search Algorithm to find Kth smallest elementInput: A set S of n elements and K.Output: The Kth smallest element in S.Approach:Step-1: If |S| <= 5, apply any Brute Force method.Step-2: Divide S into n/5 sublists each containing at most 5 elements.Step-3: Sort each sublists(Insertion sort will be better one to apply).Step-4: Recursively find P as median of medians of each sublists.Step-5: Partition S into S1 and S2 such that S1 contains all elements less than or equal to P and S2 contains all elements greater than P.Step-6: Now there can be three cases asa) if |S1| == K, then S1[k] will be the Kth smallest element.b) if |S1| > K, then Kth element must be present in S1. So discard the second part s2 and recurse on s1 with same algorithm.c) Otherwise Kth element must be in S2. So discard S1 and recurse on S2 for (K-|S1|)th element in S2. For detailed code and implementation, visit K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst-Case Linear Time) Complexity Analysis: Since each sub-list contains 5 elements so sorting them will take a constant amount of time. Thus, steps 2, 3, and 5 can be done in O(n) time, and step 4 needs T(n/5) time as we are using the same algorithm recursively to find the median of n/5 medians. Since we are pruning at least n/4 elements in each iteration, so 3n/4 elements are remaining after each iteration in the worst case. Hence, T(n) = T(3n/4) + T(n/5) + O(n). Let T(n) = a0 + a1*n + a2*(n^2) + .... where a1 != 0.we haveT(3n/4) = a0 + (3/4)a1*n + (9/16)a2*(n^2) + ....T(n/5) = a0 + (1/5)a1*n + (1/25)a2*(n^2) + ....T((3n/4) + (n/5)) = T(19n/20) = a0 + (19/20)a1*n + (361/400)a2*(n^2) + ....Thus, T(3n/4) + T(n/5) <= a0 + T(19n/20).Therefore,T(n) = T(3n/4) + T(n/5) + O(n)<= T(19n/20) + cn.Applying the initially obtained formula for general case to this inequality,we will get T(n) = O(n). Thus, we have a worst-case linear time algorithm for solving the selection problem based on the Prune-and-Search technique. Similarly, we can apply these types of strategies to solve Linear Programming with two variables and the Smallest Enclosing Circle Problems. time complexity Algorithms Analysis Searching Searching Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. DSA Sheet by Love Babbar SDE SHEET - A Complete Guide for SDE Preparation Top 50 Array Coding Problems for Interviews Difference between BFS and DFS Recursion Analysis of Algorithms | Set 1 (Asymptotic Analysis) Understanding Time Complexity with Simple Examples Time Complexity and Space Complexity Practice Questions on Time Complexity Analysis Analysis of Algorithms | Set 2 (Worst, Average and Best Cases)
[ { "code": null, "e": 28, "s": 0, "text": "\n19 Jul, 2021" }, { "code": null, "e": 485, "s": 28, "text": "The word “prune” means to reduce something by removing things that are not necessary. So, Prune-and-Search is an excellent algorithmic paradigm for solving various optimization problems. This approach was first suggested by Nimrod Megiddo in 1983. This approach always consists of several iterations. At each iteration, it discards a fraction, say f, of input data and then invokes the same algorithm recursively on the remaining data to solve the problem." }, { "code": null, "e": 778, "s": 485, "text": "The main idea of this approach is to reduce the search space by pruning a fraction of the input elements and recurse on the remaining valid input elements. After some iterations, the size of input data will become so small that it can be solved by the brute-force method in constant time c’. " }, { "code": null, "e": 881, "s": 778, "text": "Time Complexity Analysis for such algorithms: Let the time required in each iteration be O(n^k) where-" }, { "code": null, "e": 926, "s": 881, "text": "n = size of input data \nk is some constant. " }, { "code": null, "e": 1033, "s": 926, "text": "Let f = fraction of data be removed in each iteration. Recursively, the above approach can be written as- " }, { "code": null, "e": 1366, "s": 1033, "text": "T(n) = T((1-f)n) + O(n^k)We have,T(n) <= T((1-f)n) + c*n^k for very large value of n.<= T((1-f)^2 * n) + c*n^k +c*((1-f)^k)*n^k..<= c’ + c*n^k + c*((1-f)^k)n^k + c*((1-f)^2k)n^k + ..... + c*((1-f)^pk)n^k= c’ + c*n^k(1 + (1-f)^k + (1-f)^2k + ..... + (1-f)^pk).Since (1-f) < 1, as n tends to very large numberTherefore, T(n) = O(n^k)." }, { "code": null, "e": 1785, "s": 1366, "text": "It shows that the time complexity of the whole process is of the same order as the time complexity of prune-and-search in each iteration. This approach can be used to analyze the algorithms of many known problems like Binary Search, finding Kth largest/smallest element from an unsorted array(The Selection Problem), 1-center problem(Smallest Enclosing Circle), solving linear programming in two variables, and so on. " }, { "code": null, "e": 1796, "s": 1785, "text": "Examples: " }, { "code": null, "e": 2492, "s": 1796, "text": "1. Binary Search: As we know that this technique is applied on a sorted list of data for searching the index of a particular value(say ‘val‘), in the given list. For this, we go to the middle element and compare it with val. If the middle element is equal to val then, we return this middle element. Otherwise, we prune one-half of the data and the same technique is used for the remaining elements. For detailed implementation see this.Time Complexity Analysis: In each step, since it is comparing val with only the middle element, so complexity for this step will be O(1) let say it c (any constant). And half of the list is removed, so T(n) = T(n/2) + O(1) if n>=2 Otherwise T(n) = O(1) = c. " }, { "code": null, "e": 2813, "s": 2492, "text": "In simple terms,T(n) = T(n/2) + c= T(n/4) + c + c= T(n/8) + c + c + c.....= T(1) + c + ... + c + c= k times c where k will be a constant.Since half of input is discarded in each iteration, so the value of k will be at most log(n) in worst cases. Therefore, worst case complexity of Binary Search will beT(n) = O(log(n))." }, { "code": null, "e": 3864, "s": 2813, "text": "2. The Selection Problem: Given an unordered list of n elements, the task is to find the Kth smallest element from the list. The first very basic approach is to sort the given list in ascending order and directly pick the value at the Kth index. So, sorting will take O(n*log(n)) time in general and O(1) for retrieving the Kth index value. Therefore, overall T(n) = O(n*log(n)) for this approach. The second approach is to use the QuickSelect method i.e Prune-and-Search technique. The basic idea of this prune-and-search selection algorithm is to determine a fraction that will not contain the Kth element and discard that fraction of elements from the next iterations. We know that in order to have an O(n) algorithm, we must have a method that is capable of pruning away a fraction of elements in O(n) time in each iteration. Let P be an element of the list that can partition the given list into two parts, say S1 and S2, such that S1 contains all elements less than or equal to P and S2 contains all elements greater than P. Now we can say that" }, { "code": null, "e": 4155, "s": 3864, "text": "If |S1| == K, then S1[k] will be the Kth smallest element.If |S1| > K, then the Kth element must be present in S1. So discard the second part S2 and recurse on S1 with the same algorithm.Otherwise, the Kth element must be in S2. So discard S1 and recurse on S2 for (K-|S1|)th element in S2." }, { "code": null, "e": 4214, "s": 4155, "text": "If |S1| == K, then S1[k] will be the Kth smallest element." }, { "code": null, "e": 4344, "s": 4214, "text": "If |S1| > K, then the Kth element must be present in S1. So discard the second part S2 and recurse on S1 with the same algorithm." }, { "code": null, "e": 4448, "s": 4344, "text": "Otherwise, the Kth element must be in S2. So discard S1 and recurse on S2 for (K-|S1|)th element in S2." }, { "code": null, "e": 4792, "s": 4448, "text": "The key point here is how to select P such that we can always discard a fraction of S, no matter whether we are pruning S1 or S2. The answer is P should be the median of list S. Again, finding median is the special case of this problem where K=n/2. But median can be calculated by some other way more efficiently using the following algorithm:" }, { "code": null, "e": 5191, "s": 4792, "text": "Divide the list into n/5 sublists each containing at most 5 elements.Now we can sort each sublist and find their median in constant time.Again find the median of all medians recursively until size becomes at most 5. The obtained median will be a perfect pivot to be used in the Quick Selection Algorithm.[Note that Insertion sort will be a better choice for sorting the smaller sublists of size 5.]" }, { "code": null, "e": 5261, "s": 5191, "text": "Divide the list into n/5 sublists each containing at most 5 elements." }, { "code": null, "e": 5330, "s": 5261, "text": "Now we can sort each sublist and find their median in constant time." }, { "code": null, "e": 5592, "s": 5330, "text": "Again find the median of all medians recursively until size becomes at most 5. The obtained median will be a perfect pivot to be used in the Quick Selection Algorithm.[Note that Insertion sort will be a better choice for sorting the smaller sublists of size 5.]" }, { "code": null, "e": 6034, "s": 5592, "text": "Why only 5? Splitting the list into a size of 5 assumes a worst-case split of 70-30. At least half of the medians are greater than the median of medians, so half of the n/5 blocks have at least 3 elements which give 3n/10 split that implies the other partition is 7n/10 in the worst case i.e. T(n) = T(n/5) + T(7n/10) + O(n). Since (n/5 + 7n/10) < 1, so T(n) = O(n) in worst case. Let P be the median of medians which can be represented as- " }, { "code": null, "e": 6173, "s": 6034, "text": "|1''1''1''1''1| 1 1 1 1\n|2 2 2 2 2| 2 2 2 2\n|3__3__3__3_|P|'3''3''3''3|\n 4 4 4 4 |4 4 4 4 4| \n 5 5 5 5 |5__5__5__5__5|" }, { "code": null, "e": 6578, "s": 6173, "text": "As shown here, at least one-fourth of the elements in S are less than or equal to P and at least one-fourth of elements of S is greater than or equal to P. Thus, if we choose P in this way, we can always prune away at least one-fourth of elements during each iteration. Hence, splitting S into sublists of size 5 will be an efficient way to find the median of medians. Now we can state the algorithm as- " }, { "code": null, "e": 7435, "s": 6578, "text": "Prune-and-Search Algorithm to find Kth smallest elementInput: A set S of n elements and K.Output: The Kth smallest element in S.Approach:Step-1: If |S| <= 5, apply any Brute Force method.Step-2: Divide S into n/5 sublists each containing at most 5 elements.Step-3: Sort each sublists(Insertion sort will be better one to apply).Step-4: Recursively find P as median of medians of each sublists.Step-5: Partition S into S1 and S2 such that S1 contains all elements less than or equal to P and S2 contains all elements greater than P.Step-6: Now there can be three cases asa) if |S1| == K, then S1[k] will be the Kth smallest element.b) if |S1| > K, then Kth element must be present in S1. So discard the second part s2 and recurse on s1 with same algorithm.c) Otherwise Kth element must be in S2. So discard S1 and recurse on S2 for (K-|S1|)th element in S2." }, { "code": null, "e": 7561, "s": 7435, "text": "For detailed code and implementation, visit K’th Smallest/Largest Element in Unsorted Array | Set 3 (Worst-Case Linear Time) " }, { "code": null, "e": 8010, "s": 7561, "text": "Complexity Analysis: Since each sub-list contains 5 elements so sorting them will take a constant amount of time. Thus, steps 2, 3, and 5 can be done in O(n) time, and step 4 needs T(n/5) time as we are using the same algorithm recursively to find the median of n/5 medians. Since we are pruning at least n/4 elements in each iteration, so 3n/4 elements are remaining after each iteration in the worst case. Hence, T(n) = T(3n/4) + T(n/5) + O(n). " }, { "code": null, "e": 8440, "s": 8010, "text": "Let T(n) = a0 + a1*n + a2*(n^2) + .... where a1 != 0.we haveT(3n/4) = a0 + (3/4)a1*n + (9/16)a2*(n^2) + ....T(n/5) = a0 + (1/5)a1*n + (1/25)a2*(n^2) + ....T((3n/4) + (n/5)) = T(19n/20) = a0 + (19/20)a1*n + (361/400)a2*(n^2) + ....Thus, T(3n/4) + T(n/5) <= a0 + T(19n/20).Therefore,T(n) = T(3n/4) + T(n/5) + O(n)<= T(19n/20) + cn.Applying the initially obtained formula for general case to this inequality,we will get T(n) = O(n)." }, { "code": null, "e": 8706, "s": 8440, "text": "Thus, we have a worst-case linear time algorithm for solving the selection problem based on the Prune-and-Search technique. Similarly, we can apply these types of strategies to solve Linear Programming with two variables and the Smallest Enclosing Circle Problems. " }, { "code": null, "e": 8722, "s": 8706, "text": "time complexity" }, { "code": null, "e": 8733, "s": 8722, "text": "Algorithms" }, { "code": null, "e": 8742, "s": 8733, "text": "Analysis" }, { "code": null, "e": 8752, "s": 8742, "text": "Searching" }, { "code": null, "e": 8762, "s": 8752, "text": "Searching" }, { "code": null, "e": 8773, "s": 8762, "text": "Algorithms" }, { "code": null, "e": 8871, "s": 8773, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8896, "s": 8871, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 8945, "s": 8896, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 8989, "s": 8945, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 9020, "s": 8989, "text": "Difference between BFS and DFS" }, { "code": null, "e": 9030, "s": 9020, "text": "Recursion" }, { "code": null, "e": 9083, "s": 9030, "text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)" }, { "code": null, "e": 9134, "s": 9083, "text": "Understanding Time Complexity with Simple Examples" }, { "code": null, "e": 9171, "s": 9134, "text": "Time Complexity and Space Complexity" }, { "code": null, "e": 9218, "s": 9171, "text": "Practice Questions on Time Complexity Analysis" } ]
Kotlin - Basic Syntax
An entry point of a Kotlin application is the main() function. A function can be defined as a block of code designed to perform a particular task. Let's start with a basic Kotlin program to print "Hello, World!" on the standard output: fun main() { var string: String = "Hello, World!" println("$string") } When you run the above Kotlin program, it will generate the following output: Hello, World! Another form of main() function accepts a variable number of String arguments as follows: fun main(args: Array<String>){ println("Hello, world!") } When you run the above Kotlin program, it will generate the following output: Hello, World! If you have observed, its clear that both the programs generate same output, so it is very much optional to pass a parameter in main() function starting from Kotlin version 1.3. The print() is a function in Kotlin which prints its argument to the standard output, similar way the println() is another function which prints its argument on the standard output but it also adds a line break in the output. Let's try the following program to understand the difference between these two important functions: fun main(args: Array<String>){ println("Hello,") println(" world!") print("Hello,") print(" world!") } When you run the above Kotlin program, it will generate the following output: Hello, world! Hello, world! Both the functions (print() and println()) can be used to print numbers as well as strings and at the same time to perform any mathematical calculations as below: fun main(args: Array<String>){ println( 200 ) println( "200" ) println( 2 + 2 ) print(4*3) } When you run the above Kotlin program, it will generate the following output: 200 200 4 12 Kotlin code statements do not require a semicolon (;) to end the statement like many other programming languages, such as Java, C++, C#, etc. do need it. Though you can compile and run a Kotlin program with and without semicolon successfully as follows: fun main() { println("I'm without semi-colon") println("I'm with semi-colon"); } When you run the above Kotlin program, it will generate the following output: I'm without semi-colon I'm with semi-colon So as a good programming practice, it is not recommended to add a semicolon in the end of a Kotlin statement. Kotlin code is usually defined in packages though package specification is optional. If you don't specify a package in a source file, its content goes to the default package. If we specify a package in Kotlin program then it is specified at the top of the file as follows: package org.tutorialspoint.com fun main() { println("Hello, World!") } When you run the above Kotlin program, it will generate the following output: Hello, World! Q 1 - Kotlin main() function should have a mandatory parameter to compile the code successfully: A - True B - False No it is not mandatory that Kotlin main() function should always have a parameter. If you need to pass multiple arguments through an array of string then you can use the paremeter like main(args: Array<String>), otherwise it is not required. Q 2 - What will be the output of the following Kotlin program fun main() { println("1"); println("2") } A - This will give a syntax error B - It will print 12 C - 1 followed by 2 in the next line D - None of the above Though Kotlin does not recommend using a semicolon in the end of the statement, still if you want to separate two statements in a single line then you can separate them using a semicolon otherwise you will get compile time error. Q 3 - Which of the following statement is correct in Kotlin A - A Kotlin program must have a main() function B - A Kotlin program can be compiled without a main() function C - It is mandatory to have a print() or println() functions in a Kotlin program D - All statements are correct from Kotlin programming point of view Only A statement is correct here, because we can not run a Kotlin program without main() function, which is called an entry point for Kotlin program. It does not matter if you use print() or println() functions within a Kotlin program. 68 Lectures 4.5 hours Arnab Chakraborty 71 Lectures 5.5 hours Frahaan Hussain 18 Lectures 1.5 hours Mahmoud Ramadan 49 Lectures 6 hours Catalin Stefan 49 Lectures 2.5 hours Skillbakerystudios 22 Lectures 1 hours CLEMENT OCHIENG Print Add Notes Bookmark this page
[ { "code": null, "e": 2572, "s": 2425, "text": "An entry point of a Kotlin application is the main() function. A function can be defined as a block of code designed to perform a particular task." }, { "code": null, "e": 2661, "s": 2572, "text": "Let's start with a basic Kotlin program to print \"Hello, World!\" on the standard output:" }, { "code": null, "e": 2740, "s": 2661, "text": "fun main() {\n var string: String = \"Hello, World!\"\n println(\"$string\")\n}\n" }, { "code": null, "e": 2818, "s": 2740, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 2833, "s": 2818, "text": "Hello, World!\n" }, { "code": null, "e": 2923, "s": 2833, "text": "Another form of main() function accepts a variable number of String arguments as follows:" }, { "code": null, "e": 2986, "s": 2923, "text": "fun main(args: Array<String>){\n println(\"Hello, world!\")\n}\n" }, { "code": null, "e": 3064, "s": 2986, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 3079, "s": 3064, "text": "Hello, World!\n" }, { "code": null, "e": 3257, "s": 3079, "text": "If you have observed, its clear that both the programs generate same output, so it is very much optional to pass a parameter in main() function starting from Kotlin version 1.3." }, { "code": null, "e": 3483, "s": 3257, "text": "The print() is a function in Kotlin which prints its argument to the standard output, similar way the println() is another function which prints its argument on the standard output but it also adds a line break in the output." }, { "code": null, "e": 3583, "s": 3483, "text": "Let's try the following program to understand the difference between these two important functions:" }, { "code": null, "e": 3704, "s": 3583, "text": "fun main(args: Array<String>){\n println(\"Hello,\")\n println(\" world!\")\n\n print(\"Hello,\")\n print(\" world!\")\n}\n" }, { "code": null, "e": 3782, "s": 3704, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 3813, "s": 3782, "text": "Hello, \n world!\nHello, world!\n" }, { "code": null, "e": 3976, "s": 3813, "text": "Both the functions (print() and println()) can be used to print numbers as well as strings and at the same time to perform any mathematical calculations as below:" }, { "code": null, "e": 4087, "s": 3976, "text": "fun main(args: Array<String>){\n println( 200 )\n println( \"200\" )\n println( 2 + 2 )\n\n print(4*3)\n}\n" }, { "code": null, "e": 4165, "s": 4087, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4179, "s": 4165, "text": "200\n200\n4\n12\n" }, { "code": null, "e": 4333, "s": 4179, "text": "Kotlin code statements do not require a semicolon (;) to end the statement like many other programming languages, such as Java, C++, C#, etc. do need it." }, { "code": null, "e": 4433, "s": 4333, "text": "Though you can compile and run a Kotlin program with and without semicolon successfully as follows:" }, { "code": null, "e": 4528, "s": 4433, "text": "fun main() {\n println(\"I'm without semi-colon\")\n \n println(\"I'm with semi-colon\");\n}\n" }, { "code": null, "e": 4606, "s": 4528, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 4650, "s": 4606, "text": "I'm without semi-colon\nI'm with semi-colon\n" }, { "code": null, "e": 4760, "s": 4650, "text": "So as a good programming practice, it is not recommended to add a semicolon in the end of a Kotlin statement." }, { "code": null, "e": 4935, "s": 4760, "text": "Kotlin code is usually defined in packages though package specification is optional. If you don't specify a package in a source file, its content goes to the default package." }, { "code": null, "e": 5033, "s": 4935, "text": "If we specify a package in Kotlin program then it is specified at the top of the file as follows:" }, { "code": null, "e": 5110, "s": 5033, "text": "package org.tutorialspoint.com\n\nfun main() {\n println(\"Hello, World!\")\n}\n" }, { "code": null, "e": 5188, "s": 5110, "text": "When you run the above Kotlin program, it will generate the following output:" }, { "code": null, "e": 5203, "s": 5188, "text": "Hello, World!\n" }, { "code": null, "e": 5300, "s": 5203, "text": "Q 1 - Kotlin main() function should have a mandatory parameter to compile the code successfully:" }, { "code": null, "e": 5310, "s": 5300, "text": "A - True " }, { "code": null, "e": 5320, "s": 5310, "text": "B - False" }, { "code": null, "e": 5562, "s": 5320, "text": "No it is not mandatory that Kotlin main() function should always have a parameter. If you need to pass multiple arguments through an array of string then you can use the paremeter like main(args: Array<String>), otherwise it is not required." }, { "code": null, "e": 5624, "s": 5562, "text": "Q 2 - What will be the output of the following Kotlin program" }, { "code": null, "e": 5671, "s": 5624, "text": "fun main() {\n println(\"1\"); println(\"2\")\n}\n" }, { "code": null, "e": 5705, "s": 5671, "text": "A - This will give a syntax error" }, { "code": null, "e": 5726, "s": 5705, "text": "B - It will print 12" }, { "code": null, "e": 5763, "s": 5726, "text": "C - 1 followed by 2 in the next line" }, { "code": null, "e": 5785, "s": 5763, "text": "D - None of the above" }, { "code": null, "e": 6015, "s": 5785, "text": "Though Kotlin does not recommend using a semicolon in the end of the statement, still if you want to separate two statements in a single line then you can separate them using a semicolon otherwise you will get compile time error." }, { "code": null, "e": 6075, "s": 6015, "text": "Q 3 - Which of the following statement is correct in Kotlin" }, { "code": null, "e": 6124, "s": 6075, "text": "A - A Kotlin program must have a main() function" }, { "code": null, "e": 6187, "s": 6124, "text": "B - A Kotlin program can be compiled without a main() function" }, { "code": null, "e": 6268, "s": 6187, "text": "C - It is mandatory to have a print() or println() functions in a Kotlin program" }, { "code": null, "e": 6337, "s": 6268, "text": "D - All statements are correct from Kotlin programming point of view" }, { "code": null, "e": 6573, "s": 6337, "text": "Only A statement is correct here, because we can not run a Kotlin program without main() function, which is called an entry point for Kotlin program. It does not matter if you use print() or println() functions within a Kotlin program." }, { "code": null, "e": 6608, "s": 6573, "text": "\n 68 Lectures \n 4.5 hours \n" }, { "code": null, "e": 6627, "s": 6608, "text": " Arnab Chakraborty" }, { "code": null, "e": 6662, "s": 6627, "text": "\n 71 Lectures \n 5.5 hours \n" }, { "code": null, "e": 6679, "s": 6662, "text": " Frahaan Hussain" }, { "code": null, "e": 6714, "s": 6679, "text": "\n 18 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6731, "s": 6714, "text": " Mahmoud Ramadan" }, { "code": null, "e": 6764, "s": 6731, "text": "\n 49 Lectures \n 6 hours \n" }, { "code": null, "e": 6780, "s": 6764, "text": " Catalin Stefan" }, { "code": null, "e": 6815, "s": 6780, "text": "\n 49 Lectures \n 2.5 hours \n" }, { "code": null, "e": 6835, "s": 6815, "text": " Skillbakerystudios" }, { "code": null, "e": 6868, "s": 6835, "text": "\n 22 Lectures \n 1 hours \n" }, { "code": null, "e": 6885, "s": 6868, "text": " CLEMENT OCHIENG" }, { "code": null, "e": 6892, "s": 6885, "text": " Print" }, { "code": null, "e": 6903, "s": 6892, "text": " Add Notes" } ]
Solidity - do...while loop
The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false. The flow chart of a do-while loop would be as follows − The syntax for do-while loop in Solidity is as follows − do { Statement(s) to be executed; } while (expression); Note − Don't miss the semicolon used at the end of the do...while loop. Try the following example to learn how to implement a do-while loop in Solidity. pragma solidity ^0.5.0; contract SolidityTest { uint storedData; constructor() public{ storedData = 10; } function getResult() public view returns(string memory){ uint a = 10; uint b = 2; uint result = a + b; return integerToString(result); } function integerToString(uint _i) internal pure returns (string memory) { if (_i == 0) { return "0"; } uint j = _i; uint len; while (j != 0) { len++; j /= 10; } bytes memory bstr = new bytes(len); uint k = len - 1; do { // do while loop bstr[k--] = byte(uint8(48 + _i % 10)); _i /= 10; } while (_i != 0); return string(bstr); } } Run the above program using steps provided in Solidity First Application chapter. 0: string: 12 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2764, "s": 2555, "text": "The do...while loop is similar to the while loop except that the condition check happens at the end of the loop. This means that the loop will always be executed at least once, even if the condition is false." }, { "code": null, "e": 2820, "s": 2764, "text": "The flow chart of a do-while loop would be as follows −" }, { "code": null, "e": 2877, "s": 2820, "text": "The syntax for do-while loop in Solidity is as follows −" }, { "code": null, "e": 2937, "s": 2877, "text": "do {\n Statement(s) to be executed;\n} while (expression);\n" }, { "code": null, "e": 3009, "s": 2937, "text": "Note − Don't miss the semicolon used at the end of the do...while loop." }, { "code": null, "e": 3090, "s": 3009, "text": "Try the following example to learn how to implement a do-while loop in Solidity." }, { "code": null, "e": 3885, "s": 3090, "text": "pragma solidity ^0.5.0;\n\ncontract SolidityTest {\n uint storedData; \n constructor() public{\n storedData = 10; \n }\n function getResult() public view returns(string memory){\n uint a = 10; \n uint b = 2;\n uint result = a + b;\n return integerToString(result); \n }\n function integerToString(uint _i) internal pure \n returns (string memory) {\n \n if (_i == 0) {\n return \"0\";\n }\n uint j = _i;\n uint len;\n \n while (j != 0) {\n len++;\n j /= 10;\n }\n bytes memory bstr = new bytes(len);\n uint k = len - 1;\n \n do { // do while loop\t\n bstr[k--] = byte(uint8(48 + _i % 10));\n _i /= 10;\n }\n while (_i != 0);\n return string(bstr);\n }\n}" }, { "code": null, "e": 3967, "s": 3885, "text": "Run the above program using steps provided in Solidity First Application chapter." }, { "code": null, "e": 3982, "s": 3967, "text": "0: string: 12\n" }, { "code": null, "e": 4017, "s": 3982, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4034, "s": 4017, "text": " Abhilash Nelson" }, { "code": null, "e": 4069, "s": 4034, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4086, "s": 4069, "text": " Frahaan Hussain" }, { "code": null, "e": 4121, "s": 4086, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4135, "s": 4121, "text": " Swapnil Kole" }, { "code": null, "e": 4142, "s": 4135, "text": " Print" }, { "code": null, "e": 4153, "s": 4142, "text": " Add Notes" } ]
CSS - Rotate In Effect
It provides to move or cause to move in a circle round an axis or centre. @keyframes rotateIn { 0% { transform-origin: center center; transform: rotate(-200deg); opacity: 0; } 100% { transform-origin: center center; transform: rotate(0); opacity: 1; } } Transform − Transform applies to 2d and 3d transformation to an element. Transform − Transform applies to 2d and 3d transformation to an element. Opacity − Opacity applies to an element to make translucence. Opacity − Opacity applies to an element to make translucence. <html> <head> <style> .animated { background-image: url(/css/images/logo.png); background-repeat: no-repeat; background-position: left top; padding-top:95px; margin-bottom:60px; -webkit-animation-duration: 10s; animation-duration: 10s; -webkit-animation-fill-mode: both; animation-fill-mode: both; } @-webkit-keyframes rotateIn { 0% { -webkit-transform-origin: center center; -webkit-transform: rotate(-200deg); opacity: 0; } 100% { -webkit-transform-origin: center center; -webkit-transform: rotate(0); opacity: 1; } } @keyframes rotateIn { 0% { transform-origin: center center; transform: rotate(-200deg); opacity: 0; } 100% { transform-origin: center center; transform: rotate(0); opacity: 1; } } .rotateIn { -webkit-animation-name: rotateIn; animation-name: rotateIn; } </style> </head> <body> <div id = "animated-example" class = "animated rotateIn"></div> <button onclick = "myFunction()">Reload page</button> <script> function myFunction() { location.reload(); } </script> </body> </html> It will produce the following result − Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Academic Tutorials Big Data & Analytics Computer Programming Computer Science Databases DevOps Digital Marketing Engineering Tutorials Exams Syllabus Famous Monuments GATE Exams Tutorials Latest Technologies Machine Learning Mainframe Development Management Tutorials Mathematics Tutorials Microsoft Technologies Misc tutorials Mobile Development Java Technologies Python Technologies SAP Tutorials Programming Scripts Selected Reading Software Quality Soft Skills Telecom Tutorials UPSC IAS Exams Web Development Sports Tutorials XML Technologies Multi-Language Interview Questions Selected Reading UPSC IAS Exams Notes Developer's Best Practices Questions and Answers Effective Resume Writing HR Interview Questions Computer Glossary Who is Who Print Add Notes Bookmark this page
[ { "code": null, "e": 2700, "s": 2626, "text": "It provides to move or cause to move in a circle round an axis or centre." }, { "code": null, "e": 2930, "s": 2700, "text": "@keyframes rotateIn {\n 0% {\n transform-origin: center center;\n transform: rotate(-200deg);\n opacity: 0;\n }\n 100% {\n transform-origin: center center;\n transform: rotate(0);\n opacity: 1;\n } \n} " }, { "code": null, "e": 3003, "s": 2930, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3076, "s": 3003, "text": "Transform − Transform applies to 2d and 3d transformation to an element." }, { "code": null, "e": 3138, "s": 3076, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 3200, "s": 3138, "text": "Opacity − Opacity applies to an element to make translucence." }, { "code": null, "e": 4803, "s": 3200, "text": "<html>\n <head>\n <style>\n .animated {\n background-image: url(/css/images/logo.png);\n background-repeat: no-repeat;\n background-position: left top;\n padding-top:95px;\n margin-bottom:60px;\n -webkit-animation-duration: 10s;\n animation-duration: 10s;\n -webkit-animation-fill-mode: both;\n animation-fill-mode: both;\n }\n \n @-webkit-keyframes rotateIn {\n 0% {\n -webkit-transform-origin: center center;\n -webkit-transform: rotate(-200deg);\n opacity: 0;\n }\n 100% {\n -webkit-transform-origin: center center;\n -webkit-transform: rotate(0);\n opacity: 1;\n }\n }\n \n @keyframes rotateIn {\n 0% {\n transform-origin: center center;\n transform: rotate(-200deg);\n opacity: 0;\n }\n 100% {\n transform-origin: center center;\n transform: rotate(0);\n opacity: 1;\n }\n }\n \n .rotateIn {\n -webkit-animation-name: rotateIn;\n animation-name: rotateIn;\n }\n </style>\n </head>\n\n <body>\n \n <div id = \"animated-example\" class = \"animated rotateIn\"></div>\n <button onclick = \"myFunction()\">Reload page</button>\n \n <script>\n function myFunction() {\n location.reload();\n }\n </script>\n \n </body>\n</html>" }, { "code": null, "e": 4842, "s": 4803, "text": "It will produce the following result −" }, { "code": null, "e": 5489, "s": 4842, "text": "\n\n Academic Tutorials\n Big Data & Analytics \n Computer Programming \n Computer Science \n Databases \n DevOps \n Digital Marketing \n Engineering Tutorials \n Exams Syllabus \n Famous Monuments \n GATE Exams Tutorials\n Latest Technologies \n Machine Learning \n Mainframe Development \n Management Tutorials \n Mathematics Tutorials\n Microsoft Technologies \n Misc tutorials \n Mobile Development \n Java Technologies \n Python Technologies \n SAP Tutorials \nProgramming Scripts \n Selected Reading \n Software Quality \n Soft Skills \n Telecom Tutorials \n UPSC IAS Exams \n Web Development \n Sports Tutorials \n XML Technologies \n Multi-Language\n Interview Questions\n\n" }, { "code": null, "e": 5509, "s": 5489, "text": " Academic Tutorials" }, { "code": null, "e": 5532, "s": 5509, "text": " Big Data & Analytics " }, { "code": null, "e": 5555, "s": 5532, "text": " Computer Programming " }, { "code": null, "e": 5574, "s": 5555, "text": " Computer Science " }, { "code": null, "e": 5586, "s": 5574, "text": " Databases " }, { "code": null, "e": 5595, "s": 5586, "text": " DevOps " }, { "code": null, "e": 5615, "s": 5595, "text": " Digital Marketing " }, { "code": null, "e": 5639, "s": 5615, "text": " Engineering Tutorials " }, { "code": null, "e": 5656, "s": 5639, "text": " Exams Syllabus " }, { "code": null, "e": 5675, "s": 5656, "text": " Famous Monuments " }, { "code": null, "e": 5697, "s": 5675, "text": " GATE Exams Tutorials" }, { "code": null, "e": 5719, "s": 5697, "text": " Latest Technologies " }, { "code": null, "e": 5738, "s": 5719, "text": " Machine Learning " }, { "code": null, "e": 5762, "s": 5738, "text": " Mainframe Development " }, { "code": null, "e": 5785, "s": 5762, "text": " Management Tutorials " }, { "code": null, "e": 5808, "s": 5785, "text": " Mathematics Tutorials" }, { "code": null, "e": 5833, "s": 5808, "text": " Microsoft Technologies " }, { "code": null, "e": 5850, "s": 5833, "text": " Misc tutorials " }, { "code": null, "e": 5871, "s": 5850, "text": " Mobile Development " }, { "code": null, "e": 5891, "s": 5871, "text": " Java Technologies " }, { "code": null, "e": 5913, "s": 5891, "text": " Python Technologies " }, { "code": null, "e": 5929, "s": 5913, "text": " SAP Tutorials " }, { "code": null, "e": 5950, "s": 5929, "text": "Programming Scripts " }, { "code": null, "e": 5969, "s": 5950, "text": " Selected Reading " }, { "code": null, "e": 5988, "s": 5969, "text": " Software Quality " }, { "code": null, "e": 6002, "s": 5988, "text": " Soft Skills " }, { "code": null, "e": 6022, "s": 6002, "text": " Telecom Tutorials " }, { "code": null, "e": 6039, "s": 6022, "text": " UPSC IAS Exams " }, { "code": null, "e": 6057, "s": 6039, "text": " Web Development " }, { "code": null, "e": 6076, "s": 6057, "text": " Sports Tutorials " }, { "code": null, "e": 6095, "s": 6076, "text": " XML Technologies " }, { "code": null, "e": 6111, "s": 6095, "text": " Multi-Language" }, { "code": null, "e": 6132, "s": 6111, "text": " Interview Questions" }, { "code": null, "e": 6149, "s": 6132, "text": "Selected Reading" }, { "code": null, "e": 6170, "s": 6149, "text": "UPSC IAS Exams Notes" }, { "code": null, "e": 6197, "s": 6170, "text": "Developer's Best Practices" }, { "code": null, "e": 6219, "s": 6197, "text": "Questions and Answers" }, { "code": null, "e": 6244, "s": 6219, "text": "Effective Resume Writing" }, { "code": null, "e": 6267, "s": 6244, "text": "HR Interview Questions" }, { "code": null, "e": 6285, "s": 6267, "text": "Computer Glossary" }, { "code": null, "e": 6296, "s": 6285, "text": "Who is Who" }, { "code": null, "e": 6303, "s": 6296, "text": " Print" }, { "code": null, "e": 6314, "s": 6303, "text": " Add Notes" } ]
OVER 100 Data Scientist Interview Questions and Answers! | by Terence Shin | Towards Data Science
I know this is long... Really long. But don’t be intimidated by the length — I have broken this down into four sections (machine learning, stats, SQL, miscellaneous) so that you can go through this bit by bit. Think of this as a workbook or a crash course filled with hundreds of data science interview questions that you can use to hone your knowledge and to identify gaps that you can then fill afterwards. I hope you find this helpful and wish you the best of luck in your data science endeavors! Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! Machine Learning Fundamentals Statistics, Probability, and Mathematics SQL Practice Problems Miscellaneous There are many steps that can be taken when data wrangling and data cleaning. Some of the most common steps are listed below: Data profiling: Almost everyone starts off by getting an understanding of their dataset. More specifically, you can look at the shape of the dataset with .shape and a description of your numerical variables with .describe(). Data visualizations: Sometimes, it’s useful to visualize your data with histograms, boxplots, and scatterplots to better understand the relationships between variables and also to identify potential outliers. Syntax error: This includes making sure there’s no white space, making sure letter casing is consistent, and checking for typos. You can check for typos by using .unique() or by using bar graphs. Standardization or normalization: Depending on the dataset your working with and the machine learning method you decide to use, it may be useful to standardize or normalize your data so that different scales of different variables don’t negatively impact the performance of your model. Handling null values: There are a number of ways to handle null values including deleting rows with null values altogether, replacing null values with the mean/median/mode, replacing null values with a new category (eg. unknown), predicting the values, or using machine learning models that can deal with null values. Read more here. Other things include: removing irrelevant data, removing duplicates, and type conversion. Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! There are a number of ways to handle unbalanced binary classification (assuming that you want to identify the minority class): First, you want to reconsider the metrics that you’d use to evaluate your model. The accuracy of your model might not be the best metric to look at because and I’ll use an example to explain why. Let’s say 99 bank withdrawals were not fraudulent and 1 withdrawal was. If your model simply classified every instance as “not fraudulent”, it would have an accuracy of 99%! Therefore, you may want to consider using metrics like precision and recall. Another method to improve unbalanced binary classification is by increasing the cost of misclassifying the minority class. By increasing the penalty of such, the model should classify the minority class more accurately. Lastly, you can improve the balance of classes by oversampling the minority class or by undersampling the majority class. You can read more about it here. While boxplots and histograms are visualizations used to show the distribution of the data, they communicate information differently. Histograms are bar charts that show the frequency of a numerical variable’s values and are used to approximate the probability distribution of the given variable. It allows you to quickly understand the shape of the distribution, the variation, and potential outliers. Boxplots communicate different aspects of the distribution of data. While you can’t see the shape of the distribution through a box plot, you can gather other information like the quartiles, the range, and outliers. Boxplots are especially useful when you want to compare multiple charts at the same time because they take up less space than histograms. Both L1 and L2 regularization are methods used to reduce the overfitting of training data. Least Squares minimizes the sum of the squared residuals, which can result in low bias but high variance. L2 Regularization, also called ridge regression, minimizes the sum of the squared residuals plus lambda times the slope squared. This additional term is called the Ridge Regression Penalty. This increases the bias of the model, making the fit worse on the training data, but also decreases the variance. If you take the ridge regression penalty and replace it with the absolute value of the slope, then you get Lasso regression or L1 regularization. L2 is less robust but has a stable solution and always one solution. L1 is more robust but has an unstable solution and can possibly have multiple solutions. StatQuest has an amazing video on Lasso and Ridge regression here. A neural network is a multi-layered model inspired by the human brain. Like the neurons in our brain, the circles above represent a node. The blue circles represent the input layer, the black circles represent the hidden layers, and the green circles represent the output layer. Each node in the hidden layers represents a function that the inputs go through, ultimately leading to an output in the green circles. The formal term for these functions is called the sigmoid activation function. If you want a step by step example of creating a neural network, check out Victor Zhou’s article here. If you’re a visual/audio learner, 3Blue1Brown has an amazing series on neural networks and deep learning on YouTube here. Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! Cross-validation is essentially a technique used to assess how well a model performs on a new independent dataset. The simplest example of cross-validation is when you split your data into two groups: training data and testing data, where you use the training data to build the model and the testing data to test the model. There isn’t a one-size-fits-all metric. The metric(s) chosen to evaluate a machine learning model depends on various factors: Is it a regression or classification task? What is the business objective? Eg. precision vs recall What is the distribution of the target variable? There are a number of metrics that can be used, including adjusted r-squared, MAE, MSE, accuracy, recall, precision, f1 score, and the list goes on. Recall attempts to answer “What proportion of actual positives was identified correctly?” Precision attempts to answer “What proportion of positive identifications was actually correct?” A false positive is an incorrect identification of the presence of a condition when it’s absent. A false negative is an incorrect identification of the absence of a condition when it’s actually present. An example of when false negatives are more important than false positives is when screening for cancer. It’s much worse to say that someone doesn’t have cancer when they do, instead of saying that someone does and later realizing that they don’t. This is a subjective argument, but false positives can be worse than false negatives from a psychological point of view. For example, a false positive for winning the lottery could be a worse outcome than a false negative because people normally don’t expect to win the lottery anyways. Supervised learning involves learning a function that maps an input to an output based on example input-output pairs [1]. For example, if I had a dataset with two variables, age (input) and height (output), I could implement a supervised learning model to predict the height of a person based on their age. Unlike supervised learning, unsupervised learning is used to draw inferences and find patterns from input data without references to labeled outcomes. A common use of unsupervised learning is grouping customers by purchasing behavior to find target markets. Check out my article ‘All Machine Learning Models Explained in Six Minutes’ if you’d like to learn more about this! There are two main ways that you can do this: A) Adjusted R-squared. R Squared is a measurement that tells you to what extent the proportion of variance in the dependent variable is explained by the variance in the independent variables. In simpler terms, while the coefficients estimate trends, R-squared represents the scatter around the line of best fit. However, every additional independent variable added to a model always increases the R-squared value — therefore, a model with several independent variables may seem to be a better fit even if it isn’t. This is where adjusted R2 comes in. The adjusted R2 compensates for each additional independent variable and only increases if each given variable improves the model above what is possible by probability. This is important since we are creating a multiple regression model. B) Cross-Validation A method common to most people is cross-validation, splitting the data into two sets: training and testing data. See the answer to the first question for more on this. NLP stands for Natural Language Processing. It is a branch of artificial intelligence that gives machines the ability to read and understand human languages. There are a couple of reasons why a random forest is a better choice of model than a support vector machine: Random forests allow you to determine the feature importance. SVM’s can’t do this. Random forests are much quicker and simpler to build than an SVM. For multi-class classification problems, SVMs require a one-vs-rest method, which is less scalable and more memory intensive. Dimensionality reduction is the process of reducing the number of features in a dataset. This is important mainly in the case when you want to reduce variance in your model (overfitting). Wikipedia states four advantages of dimensionality reduction (see here): It reduces the time and storage space requiredRemoval of multi-collinearity improves the interpretation of the parameters of the machine learning modelIt becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3DIt avoids the curse of dimensionality It reduces the time and storage space required Removal of multi-collinearity improves the interpretation of the parameters of the machine learning model It becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3D It avoids the curse of dimensionality In its simplest sense, PCA involves project higher dimensional data (eg. 3 dimensions) to a smaller space (eg. 2 dimensions). This results in a lower dimension of data, (2 dimensions instead of 3 dimensions) while keeping all original variables in the model. PCA is commonly used for compression purposes, to reduce required memory and to speed up the algorithm, as well as for visualization purposes, making it easier to summarize data. One major drawback of Naive Bayes is that it holds a strong assumption in that the features are assumed to be uncorrelated with one another, which typically is never the case. One way to improve such an algorithm that uses Naive Bayes is by decorrelating the features so that the assumption holds true. There are a couple of drawbacks of a linear model: A linear model holds some strong assumptions that may not be true in application. It assumes a linear relationship, multivariate normality, no or little multicollinearity, no auto-correlation, and homoscedasticity A linear model can’t be used for discrete or binary outcomes. You can’t vary the model flexibility of a linear model. Another way of asking this question is “Is a random forest a better model than a decision tree?” And the answer is yes because a random forest is an ensemble method that takes many weak decision trees to make a strong learner. Random forests are more accurate, more robust, and less prone to overfitting. Mean Squared Error (MSE) gives a relatively high weight to large errors — therefore, MSE tends to put too much emphasis on large deviations. A more robust alternative is MAE (mean absolute deviation). The assumptions are as follows: The sample data used to fit the model is representative of the populationThe relationship between X and the mean of Y is linearThe variance of the residual is the same for any value of X (homoscedasticity)Observations are independent of each otherFor any value of X, Y is normally distributed. The sample data used to fit the model is representative of the population The relationship between X and the mean of Y is linear The variance of the residual is the same for any value of X (homoscedasticity) Observations are independent of each other For any value of X, Y is normally distributed. Extreme violations of these assumptions will make the results redundant. Small violations of these assumptions will result in a greater bias or variance of the estimate. Multicollinearity exists when an independent variable is highly correlated with another independent variable in a multiple regression equation. This can be problematic because it undermines the statistical significance of an independent variable. You could use the Variance Inflation Factors (VIF) to determine if there is any multicollinearity between independent variables — a standard benchmark is that if the VIF is greater than 5 then multicollinearity exists. There are a couple of metrics that you can use: R-squared/Adjusted R-squared: Relative measure of fit. This was explained in a previous answer F1 Score: Evaluates the null hypothesis that all regression coefficients are equal to zero vs the alternative hypothesis that at least one doesn’t equal zero RMSE: Absolute measure of fit. Decision trees are a popular model, used in operations research, strategic planning, and machine learning. Each square above is called a node, and the more nodes you have, the more accurate your decision tree will be (generally). The last nodes of the decision tree, where a decision is made, are called the leaves of the tree. Decision trees are intuitive and easy to build but fall short when it comes to accuracy. Random forests are an ensemble learning technique that builds off of decision trees. Random forests involve creating multiple decision trees using bootstrapped datasets of the original data and randomly selecting a subset of variables at each step of the decision tree. The model then selects the mode of all of the predictions of each decision tree. By relying on a “majority wins” model, it reduces the risk of error from an individual tree. For example, if we created one decision tree, the third one, it would predict 0. But if we relied on the mode of all 4 decision trees, the predicted value would be 1. This is the power of random forests. Random forests offer several other benefits including strong performance, can model non-linear boundaries, no cross-validation needed, and gives feature importance. Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more! A kernel is a way of computing the dot product of two vectors xx and yy in some (possibly very high dimensional) feature space, which is why kernel functions are sometimes called “generalized dot product” [2] The kernel trick is a method of using a linear classifier to solve a non-linear problem by transforming linearly inseparable data to linearly separable ones in a higher dimension. When the number of features is greater than the number of observations, then performing dimensionality reduction will generally improve the SVM. Overfitting is an error where the model ‘fits’ the data too well, resulting in a model with high variance and low bias. As a consequence, an overfit model will inaccurately predict new data points even though it has a high accuracy on the training data. Boosting is an ensemble method to improve a model by reducing its bias and variance, ultimately converting weak learners to strong learners. The general idea is to train a weak learner and sequentially iterate and improve the model by learning from the previous learner. You can learn more about it here. Be sure to subscribe to never miss another article on data science guides, tricks and tips, life lessons, and more! We need to make some assumptions about this question before we can answer it. Let’s assume that there are two possible places to purchase a particular item on Amazon and the probability of finding it at location A is 0.6 and B is 0.8. The probability of finding the item on Amazon can be explained as so: We can reword the above as P(A) = 0.6 and P(B) = 0.8. Furthermore, let’s assume that these are independent events, meaning that the probability of one event is not impacted by the other. We can then use the formula... P(A or B) = P(A) + P(B) — P(A and B)P(A or B) = 0.6 + 0.8 — (0.6*0.8)P(A or B) = 0.92 Check out the Amazon data scientist interview guide here. This can be answered using the Bayes Theorem. The extended equation for the Bayes Theorem is the following: Assume that the probability of picking the unfair coin is denoted as P(A) and the probability of flipping 10 heads in a row is denoted as P(B). Then P(B|A) is equal to 1, P(B∣¬A) is equal to 0.510, and P(¬A) is equal to 0.99. If you fill in the equation, then P(A|B) = 0.9118 or 91.18%. A convex function is one where a line drawn between any two points on the graph lies on or above the graph. It has one minimum. A non-convex function is one where a line drawn between any two points on the graph may intersect other points on the graph. It characterized as “wavy”. When a cost function is non-convex, it means that there’s a likelihood that the function may find local minima instead of the global minimum, which is typically undesired in machine learning models from an optimization perspective. For this, I’m going to look at the eight rules of probability laid out here and the four different counting methods (see more here). Eight rules of probability Rule #1: For any event A, 0 ≤ P(A) ≤ 1; in other words, the probability of an event can range from 0 to 1. Rule #2: The sum of the probabilities of all possible outcomes always equals 1. Rule #3: P(not A) = 1 — P(A); This rule explains the relationship between the probability of an event and its complement event. A complement event is one that includes all possible outcomes that aren’t in A. Rule #4: If A and B are disjoint events (mutually exclusive), then P(A or B) = P(A) + P(B); this is called the addition rule for disjoint events Rule #5: P(A or B) = P(A) + P(B) — P(A and B); this is called the general addition rule. Rule #6: If A and B are two independent events, then P(A and B) = P(A) * P(B); this is called the multiplication rule for independent events. Rule #7: The conditional probability of event B given event A is P(B|A) = P(A and B) / P(A) Rule #8: For any two events A and B, P(A and B) = P(A) * P(B|A); this is called the general multiplication rule Counting Methods Factorial Formula: n! = n x (n -1) x (n — 2) x ... x 2 x 1Use when the number of items is equal to the number of places available.Eg. Find the total number of ways 5 people can sit in 5 empty seats.= 5 x 4 x 3 x 2 x 1 = 120 Fundamental Counting Principle (multiplication)This method should be used when repetitions are allowed and the number of ways to fill an open place is not affected by previous fills.Eg. There are 3 types of breakfasts, 4 types of lunches, and 5 types of desserts. The total number of combinations is = 5 x 4 x 3 = 60 Permutations: P(n,r)= n! / (n−r)!This method is used when replacements are not allowed and order of item ranking matters.Eg. A code has 4 digits in a particular order and the digits range from 0 to 9. How many permutations are there if one digit can only be used once?P(n,r) = 10!/(10–4)! = (10x9x8x7x6x5x4x3x2x1)/(6x5x4x3x2x1) = 5040 Combinations Formula: C(n,r)=(n!)/[(n−r)!r!]This is used when replacements are not allowed and the order in which items are ranked does not mater.Eg. To win the lottery, you must select the 5 correct numbers in any order from 1 to 52. What is the number of possible combinations?C(n,r) = 52! / (52–5)!5! = 2,598,960 Brilliant provides a great definition of Markov chains (here): “A Markov chain is a mathematical system that experiences transitions from one state to another according to certain probabilistic rules. The defining characteristic of a Markov chain is that no matter how the process arrived at its present state, the possible future states are fixed. In other words, the probability of transitioning to any particular state is dependent solely on the current state and time elapsed.” The actual math behind Markov chains requires knowledge on linear algebra and matrices, so I’ll leave some links below in case you want to explore this topic further on your own. See more here or here. The box with 24 red cards and 24 black cards has a higher probability of getting two cards of the same color. Let’s walk through each step. Let’s say the first card you draw from each deck is a red Ace. This means that in the deck with 12 reds and 12 blacks, there’s now 11 reds and 12 blacks. Therefore your odds of drawing another red are equal to 11/(11+12) or 11/23. In the deck with 24 reds and 24 blacks, there would then be 23 reds and 24 blacks. Therefore your odds of drawing another red are equal to 23/(23+24) or 23/47. Since 23/47 > 11/23, the second deck with more cards has a higher probability of getting the same two cards. Let’s assume that it costs $5 every time you want to play. There are 36 possible combinations with two dice. Of the 36 combinations, there are 4 combinations that result in rolling a five (see blue). This means that there is a 4/36 or 1/9 chance of rolling a 5. A 1/9 chance of winning means you’ll lose eight times and win once (theoretically). Therefore, your expected payout is equal to $10.00 * 1 — $5.00 * 9= -$35.00. Edit: Thank you guys for commenting and pointing out that it should be -$35! This isn’t a trick question. The answer is simply to perform a hypothesis test: The null hypothesis is that the coin is not biased and the probability of flipping heads should equal 50% (p=0.5). The alternative hypothesis is that the coin is biased and p != 0.5.Flip the coin 500 times.Calculate Z-score (if the sample is less than 30, you would calculate the t-statistics).Compare against alpha (two-tailed test so 0.05/2 = 0.025).If p-value > alpha, the null is not rejected and the coin is not biased.If p-value < alpha, the null is rejected and the coin is biased. The null hypothesis is that the coin is not biased and the probability of flipping heads should equal 50% (p=0.5). The alternative hypothesis is that the coin is biased and p != 0.5. Flip the coin 500 times. Calculate Z-score (if the sample is less than 30, you would calculate the t-statistics). Compare against alpha (two-tailed test so 0.05/2 = 0.025). If p-value > alpha, the null is not rejected and the coin is not biased.If p-value < alpha, the null is rejected and the coin is biased. Learn more about hypothesis testing here. Since a coin flip is a binary outcome, you can make an unfair coin fair by flipping it twice. If you flip it twice, there are two outcomes that you can bet on: heads followed by tails or tails followed by heads. P(heads) * P(tails) = P(tails) * P(heads) This makes sense since each coin toss is an independent event. This means that if you get heads → heads or tails → tails, you would need to reflip the coin. You can tell that this question is related to Bayesian theory because of the last statement which essentially follows the structure, “What is the probability A is true given B is true?” Therefore we need to know the probability of it raining in London on a given day. Let’s assume it’s 25%. P(A) = probability of it raining = 25%P(B) = probability of all 3 friends say that it’s rainingP(A|B) probability that it’s raining given they’re telling that it is rainingP(B|A) probability that all 3 friends say that it’s raining given it’s raining = (2/3)3 = 8/27 Step 1: Solve for P(B)P(A|B) = P(B|A) * P(A) / P(B), can be rewritten asP(B) = P(B|A) * P(A) + P(B|not A) * P(not A)P(B) = (2/3)3 * 0.25 + (1/3)3 * 0.75 = 0.25*8/27 + 0.75*1/27 Step 2: Solve for P(A|B)P(A|B) = 0.25 * (8/27) / ( 0.25*8/27 + 0.75*1/27)P(A|B) = 8 / (8 + 3) = 8/11 Therefore, if all three friends say that it’s raining, then there’s an 8/11 chance that it’s actually raining. Since these events are not independent, we can use the rule:P(A and B) = P(A) * P(B|A) ,which is also equal toP(not A and not B) = P(not A) * P(not B | not A) For example: P(not 4 and not yellow) = P(not 4) * P(not yellow | not 4)P(not 4 and not yellow) = (36/39) * (27/36)P(not 4 and not yellow) = 0.692 Therefore, the probability that the cards picked are not the same number and the same color is 69.2%. You would perform hypothesis testing to determine statistical significance. First, you would state the null hypothesis and alternative hypothesis. Second, you would calculate the p-value, the probability of obtaining the observed results of a test assuming that the null hypothesis is true. Last, you would set the level of the significance (alpha) and if the p-value is less than the alpha, you would reject the null — in other words, the result is statistically significant. A long-tailed distribution is a type of heavy-tailed distribution that has a tail (or tails) that drop off gradually and asymptotically. 3 practical examples include the power law, the Pareto principle (more commonly known as the 80–20 rule), and product sales (i.e. best selling products vs others). It’s important to be mindful of long-tailed distributions in classification and regression problems because the least frequently occurring values make up the majority of the population. This can ultimately change the way that you deal with outliers, and it also conflicts with some machine learning techniques with the assumption that the data is normally distributed. Statistics How To provides the best definition of CLT, which is: “The central limit theorem states that the sampling distribution of the sample mean approaches a normal distribution as the sample size gets larger no matter what the shape of the population distribution.” [1] The central limit theorem is important because it is used in hypothesis testing and also to calculate confidence intervals. ‘Statistical power’ refers to the power of a binary hypothesis, which is the probability that the test rejects the null hypothesis given that the alternative hypothesis is true. [2] Selection bias is the phenomenon of selecting individuals, groups or data for analysis in such a way that proper randomization is not achieved, ultimately resulting in a sample that is not representative of the population. Understanding and identifying selection bias is important because it can significantly skew results and provide false insights about a particular population group. Types of selection bias include: sampling bias: a biased sample caused by non-random sampling time interval: selecting a specific time frame that supports the desired conclusion. e.g. conducting a sales analysis near Christmas. exposure: includes clinical susceptibility bias, protopathic bias, indication bias. Read more here. data: includes cherry-picking, suppressing evidence, and the fallacy of incomplete evidence. attrition: attrition bias is similar to survivorship bias, where only those that ‘survived’ a long process are included in an analysis, or failure bias, where those that ‘failed’ are only included observer selection: related to the Anthropic principle, which is a philosophical consideration that any data we collect about the universe is filtered by the fact that, in order for it to be observable, it must be compatible with the conscious and sapient life that observes it. [3] Handling missing data can make selection bias worse because different methods impact the data in different ways. For example, if you replace null values with the mean of the data, you adding bias in the sense that you’re assuming that the data is not as spread out as it might actually be. Observational data comes from observational studies which are when you observe certain variables and try to determine if there is any correlation. Experimental data comes from experimental studies which are when you control certain variables and hold them constant to determine if there is any causality. An example of experimental design is the following: split a group up into two. The control group lives their lives normally. The test group is told to drink a glass of wine every night for 30 days. Then research can be conducted to see how wine affects sleep. Mean imputation is the practice of replacing null values in a data set with the mean of the data. Mean imputation is generally bad practice because it doesn’t take into account feature correlation. For example, imagine we have a table showing age and fitness score and imagine that an eighty-year-old has a missing fitness score. If we took the average fitness score from an age range of 15 to 80, then the eighty-year-old will appear to have a much higher fitness score that he actually should. Second, mean imputation reduces the variance of the data and increases bias in our data. This leads to a less accurate model and a narrower confidence interval due to a smaller variance. An outlier is a data point that differs significantly from other observations. Depending on the cause of the outlier, they can be bad from a machine learning perspective because they can worsen the accuracy of a model. If the outlier is caused by a measurement error, it’s important to remove them from the dataset. There are a couple of ways to identify outliers: Z-score/standard deviations: if we know that 99.7% of data in a data set lie within three standard deviations, then we can calculate the size of one standard deviation, multiply it by 3, and identify the data points that are outside of this range. Likewise, we can calculate the z-score of a given point, and if it’s equal to +/- 3, then it’s an outlier.Note: that there are a few contingencies that need to be considered when using this method; the data must be normally distributed, this is not applicable for small data sets, and the presence of too many outliers can throw off z-score. Interquartile Range (IQR): IQR, the concept used to build boxplots, can also be used to identify outliers. The IQR is equal to the difference between the 3rd quartile and the 1st quartile. You can then identify if a point is an outlier if it is less than Q1–1.5*IRQ or greater than Q3 + 1.5*IQR. This comes to approximately 2.698 standard deviations. Other methods include DBScan clustering, Isolation Forests, and Robust Random Cut Forests. An inlier is a data observation that lies within the rest of the dataset and is unusual or an error. Since it lies in the dataset, it is typically harder to identify than an outlier and requires external data to identify them. Should you identify any inliers, you can simply remove them from the dataset to address them. There are several ways to handle missing data: Delete rows with missing data Mean/Median/Mode imputation Assigning a unique value Predicting the missing values Using an algorithm which supports missing values, like random forests The best method is to delete rows with missing data as it ensures that no bias or variance is added or removed, and ultimately results in a robust and accurate model. However, this is only recommended if there’s a lot of data to start with and the percentage of missing values is low. First I would conduct EDA — Exploratory Data Analysis to clean, explore, and understand my data. See my article on EDA here. As part of my EDA, I could compose a histogram of the duration of calls to see the underlying distribution. My guess is that the duration of calls would follow a lognormal distribution (see below). The reason that I believe it’s positively skewed is because the lower end is limited to 0 since a call can’t be negative seconds. However, on the upper end, it’s likely for there to be a small proportion of calls that are extremely long relatively. You could use a QQ plot to confirm whether the duration of calls follows a lognormal distribution or not. See here to learn more about QQ plots. Administrative datasets are typically datasets used by governments or other organizations for non-statistical reasons. Administrative datasets are usually larger and more cost-efficient than experimental studies. They are also regularly updated assuming that the organization associated with the administrative dataset is active and functioning. At the same time, administrative datasets may not capture all of the data that one may want and may not be in the desired format either. It is also prone to quality issues and missing entries. There are a number of potential reasons for a spike in photo uploads: A new feature may have been implemented in October which involves uploading photos and gained a lot of traction by users. For example, a feature that gives the ability to create photo albums.Similarly, it’s possible that the process of uploading photos before was not intuitive and was improved in the month of October.There may have been a viral social media movement that involved uploading photos that lasted for all of October. Eg. Movember but something more scalable.It’s possible that the spike is due to people posting pictures of themselves in costumes for Halloween. A new feature may have been implemented in October which involves uploading photos and gained a lot of traction by users. For example, a feature that gives the ability to create photo albums. Similarly, it’s possible that the process of uploading photos before was not intuitive and was improved in the month of October. There may have been a viral social media movement that involved uploading photos that lasted for all of October. Eg. Movember but something more scalable. It’s possible that the spike is due to people posting pictures of themselves in costumes for Halloween. The method of testing depends on the cause of the spike, but you would conduct hypothesis testing to determine if the inferred cause is the actual cause. Any type of categorical data won’t have a gaussian distribution or lognormal distribution. Exponential distributions — eg. the amount of time that a car battery lasts or the amount of time until an earthquake occurs. Be sure to subscribe to never miss another article on data science guides, tricks and tips, life lessons, and more! Root cause analysis: a method of problem-solving used for identifying the root cause(s) of a problem [5] Correlation measures the relationship between two variables, range from -1 to 1. Causation is when a first event appears to have caused a second event. Causation essentially looks at direct relationships while correlation can look at both direct and indirect relationships. Example: a higher crime rate is associated with higher sales in ice cream in Canada, aka they are positively correlated. However, this doesn’t mean that one causes another. Instead, it’s because both occur more when it’s warmer outside. You can test for causation using hypothesis testing or A/B testing. When there are a number of outliers that positively or negatively skew the data. There are 4 combinations of rolling a 4 (1+3, 3+1, 2+2):P(rolling a 4) = 3/36 = 1/12 There are combinations of rolling an 8 (2+6, 6+2, 3+5, 5+3, 4+4):P(rolling an 8) = 5/36 The Law of Large Numbers is a theory that states that as the number of trials increases, the average of the result will become closer to the expected value. Eg. flipping heads from fair coin 100,000 times should be closer to 0.5 than 100 times. You can use the margin of error (ME) formula to determine the desired sample size. t/z = t/z score used to calculate the confidence interval ME = the desired margin of error S = sample standard deviation Potential biases include the following: Sampling bias: a biased sample caused by non-random sampling Under coverage bias: sampling too few observations Survivorship bias: error of overlooking observations that did not make it past a form of selection process. There are many things that you can do to control and minimize bias. Two common things include randomization, where participants are assigned by chance, and random sampling, sampling in which each member has an equal probability of being chosen. A confounding variable, or a confounder, is a variable that influences both the dependent variable and the independent variable, causing a spurious association, a mathematical relationship in which two or more variables are associated but not causally related. A/B testing is a form of hypothesis testing and two-sample hypothesis testing to compare two versions, the control and variant, of a single variable. It is commonly used to improve and optimize user experience and marketing. Check out my article, A Simple Guide to A/B Testing for Data Science. You can use hypothesis testing to prove that males are taller on average than females. The null hypothesis would state that males and females are the same height on average, while the alternative hypothesis would state that the average height of males is greater than the average height of females. Then you would collect a random sample of heights of males and females and use a t-test to determine if you reject the null or not. Since we looking at the number of events (# of infections) occurring within a given timeframe, this is a Poisson distribution question. Null (H0): 1 infection per person-daysAlternative (H1): >1 infection per person-days k (actual) = 10 infectionslambda (theoretical) = (1/100)*1787p = 0.032372 or 3.2372% calculated using .poisson() in excel or ppois in R Since p-value < alpha (assuming 5% level of significance), we reject the null and conclude that the hospital is below the standard. Use the General Binomial Probability formula to answer this question: p = 0.8n = 5k = 3,4,5 P(3 or more heads) = P(3 heads) + P(4 heads) + P(5 heads) = 0.94 or 94% Using Excel...p =1-norm.dist(1200, 1020, 50, true)p= 0.000159 x = 3mean = 2.5*4 = 10 using Excel... p = poisson.dist(3,10,true)p = 0.010336 Precision = Positive Predictive Value = PVPV = (0.001*0.997)/[(0.001*0.997)+((1–0.001)*(1–0.985))]PV = 0.0624 or 6.24% See more about this equation here. Assume that there’s only you and one other opponent. Also, assume that we want a 95% confidence interval. This gives us a z-score of 1.96. p-hat = 60/100 = 0.6z* = 1.96n = 100This gives us a confidence interval of [50.4,69.6]. Therefore, given a confidence interval of 95%, if you are okay with the worst scenario of tying then you can relax. Otherwise, you cannot relax until you got 61 out of 100 to claim yes. Since this is a Poisson distribution question, mean = lambda = variance, which also means that standard deviation = square root of the mean a 95% confidence interval implies a z score of 1.96 one standard deviation = 10 Therefore the confidence interval = 100 +/- 19.6 = [964.8, 1435.2] Since this is a Poisson distribution question, mean = lambda = variance, which also means that standard deviation = square root of the mean a 95% confidence interval implies a z score of 1.96 one standard deviation = sqrt(115) = 10.724 Therefore the confidence interval = 115+/- 21.45 = [93.55, 136.45]. Since 99 is within this confidence interval, we can assume that this change is not very noteworthy. Using the General Addition Rule in probability:P(mother or father) = P(mother) + P(father) — P(mother and father)P(mother) = P(mother or father) + P(mother and father) — P(father)P(mother) = 0.17 + 0.06–0.12P(mother) = 0.11 Since 70 is one standard deviation below the mean, take the area of the Gaussian distribution to the left of one standard deviation. = 2.3 + 13.6 = 15.9% Given a confidence level of 95% and degrees of freedom equal to 8, the t-score = 2.306 Confidence interval = 1100 +/- 2.306*(30/3)Confidence interval = [1076.94, 1123.06] Upper bound = mean + t-score*(standard deviation/sqrt(sample size))0 = -2 + 2.306*(s/3)2 = 2.306 * s / 3s = 2.601903Therefore the standard deviation would have to be at least approximately 2.60 for the upper bound of the 95% T confidence interval to touch 0. See here for full tutorial on finding the Confidence Interval for Two Independent Samples. Confidence Interval = mean +/- t-score * standard error (see above) mean = new mean — old mean = 3–5 = -2 t-score = 2.101 given df=18 (20–2) and confidence interval of 95% standard error = sqrt((0.62*9+0.682*9)/(10+10–2)) * sqrt(1/10+1/10)standard error = 0.352 confidence interval = [-2.75, -1.25] Assuming we subtract in this order (New System — Old System): confidence interval formula for two independent samples mean = new mean — old mean = 4–6 = -2 z-score = 1.96 confidence interval of 95% st. error = sqrt((0.52*99+22*99)/(100+100–2)) * sqrt(1/100+1/100)standard error = 0.205061lower bound = -2–1.96*0.205061 = -2.40192upper bound = -2+1.96*0.205061 = -1.59808 confidence interval = [-2.40192, -1.59808] Write a SQL query to get the second highest salary from the Employee table. For example, given the Employee table below, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null. +----+--------+| Id | Salary |+----+--------+| 1 | 100 || 2 | 200 || 3 | 300 |+----+--------+ IFNULL(expression, alt) : ifnull() returns the specified value if null, otherwise returns the expected value. We’ll use this to return null if there’s no second-highest salary. OFFSET : offset is used with the ORDER BY clause to disregard the top n rows that you specify. This will be useful as you’ll want to get the second row (2nd highest salary) SELECT IFNULL( (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ), null) as SecondHighestSalaryFROM EmployeeLIMIT 1 This query says to choose the MAX salary that isn’t equal to the MAX salary, which is equivalent to saying to choose the second-highest salary! SELECT MAX(salary) AS SecondHighestSalaryFROM EmployeeWHERE salary != (SELECT MAX(salary) FROM Employee) Here are three SQL concepts to review before your next interview! Write a SQL query to find all duplicate emails in a table named Person. +----+---------+| Id | Email |+----+---------+| 1 | [email protected] || 2 | [email protected] || 3 | [email protected] |+----+---------+ First, a subquery is created to show the count of the frequency of each email. Then the subquery is filtered WHERE the count is greater than 1. SELECT EmailFROM ( SELECT Email, count(Email) AS count FROM Person GROUP BY Email) as email_countWHERE count > 1 HAVING is a clause that essentially allows you to use a WHERE statement in conjunction with aggregates (GROUP BY). SELECT EmailFROM PersonGROUP BY EmailHAVING count(Email) > 1 Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates. +---------+------------------+------------------+| Id(INT) | RecordDate(DATE) | Temperature(INT) |+---------+------------------+------------------+| 1 | 2015-01-01 | 10 || 2 | 2015-01-02 | 25 || 3 | 2015-01-03 | 20 || 4 | 2015-01-04 | 30 |+---------+------------------+------------------+ DATEDIFF calculates the difference between two dates and is used to make sure we’re comparing today’s temperature to yesterday’s temperature. In plain English, the query is saying, Select the Ids where the temperature on a given day is greater than the temperature yesterday. SELECT DISTINCT a.IdFROM Weather a, Weather bWHERE a.Temperature > b.TemperatureAND DATEDIFF(a.Recorddate, b.Recorddate) = 1 The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id. +----+-------+--------+--------------+| Id | Name | Salary | DepartmentId |+----+-------+--------+--------------+| 1 | Joe | 70000 | 1 || 2 | Jim | 90000 | 1 || 3 | Henry | 80000 | 2 || 4 | Sam | 60000 | 2 || 5 | Max | 90000 | 1 |+----+-------+--------+--------------+ The Department table holds all departments of the company. +----+----------+| Id | Name |+----+----------+| 1 | IT || 2 | Sales |+----+----------+ Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter). +------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT | Max | 90000 || IT | Jim | 90000 || Sales | Henry | 80000 |+------------+----------+--------+ The IN clause allows you to use multiple OR clauses in a WHERE statement. For example WHERE country = ‘Canada’ or country = ‘USA’ is the same as WHERE country IN (‘Canada’, ’USA’). In this case, we want to filter the Department table to only show the highest Salary per Department (i.e. DepartmentId). Then we can join the two tables WHERE the DepartmentId and Salary is in the filtered Department table. SELECT Department.name AS 'Department', Employee.name AS 'Employee', SalaryFROM EmployeeINNER JOIN Department ON Employee.DepartmentId = Department.IdWHERE (DepartmentId , Salary) IN ( SELECT DepartmentId, MAX(Salary) FROM Employee GROUP BY DepartmentId ) Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids. The column id is a continuous increment. Mary wants to change seats for the adjacent students. Can you write a SQL query to output the result for Mary? +---------+---------+| id | student |+---------+---------+| 1 | Abbot || 2 | Doris || 3 | Emerson || 4 | Green || 5 | Jeames |+---------+---------+ For the sample input, the output is: +---------+---------+| id | student |+---------+---------+| 1 | Doris || 2 | Abbot || 3 | Green || 4 | Emerson || 5 | Jeames |+---------+---------+ Note:If the number of students is odd, there is no need to change the last one’s seat. Think of a CASE WHEN THEN statement like an IF statement in coding. The first WHEN statement checks to see if there’s an odd number of rows, and if there is, ensure that the id number does not change. The second WHEN statement adds 1 to each id (eg. 1,3,5 becomes 2,4,6) Similarly, the third WHEN statement subtracts 1 to each id (2,4,6 becomes 1,3,5) SELECT CASE WHEN((SELECT MAX(id) FROM seat)%2 = 1) AND id = (SELECT MAX(id) FROM seat) THEN id WHEN id%2 = 1 THEN id + 1 ELSE id - 1 END AS id, studentFROM seatORDER BY id Two weighings would be required (see part A and B above): You would split the nine marbles into three groups of three and weigh two of the groups. If the scale balances (alternative 1), you know that the heavy marble is in the third group of marbles. Otherwise, you’ll take the group that is weighed more heavily (alternative 2).Then you would exercise the same step, but you’d have three groups of one marble instead of three groups of three. You would split the nine marbles into three groups of three and weigh two of the groups. If the scale balances (alternative 1), you know that the heavy marble is in the third group of marbles. Otherwise, you’ll take the group that is weighed more heavily (alternative 2). Then you would exercise the same step, but you’d have three groups of one marble instead of three groups of three. I’m not 100% sure about the answer to this question but will give my best shot! Let’s take the instance where there’s an increase in the prime membership fee — there are two parties involved, the buyers and the sellers. For the buyers, the impact of an increase in a prime membership fee ultimately depends on the price elasticity of demand for the buyers. If the price elasticity is high, then a given increase in price will result in a large drop in demand and vice versa. Buyers that continue to purchase a membership fee are likely Amazon’s most loyal and active customers — they are also likely to place a higher emphasis on products with prime. Sellers will take a hit, as there is now a higher cost of purchasing Amazon’s basket of products. That being said, some products will take a harder hit while others may not be impacted. It is likely that premium products that Amazon’s most loyal customers purchase would not be affected as much, like electronics. There are a number of possible variables that can cause such a discrepancy that I would check to see: The demographics of iOS and Android users might differ significantly. For example, according to Hootsuite, 43% of females use Instagram as opposed to 31% of men. If the proportion of female users for iOS is significantly larger than for Android then this can explain the discrepancy (or at least a part of it). This can also be said for age, race, ethnicity, location, etc... Behavioral factors can also have an impact on the discrepancy. If iOS users use their phones more heavily than Android users, it’s more likely that they’ll indulge in Instagram and other apps than someone who spent significantly less time on their phones. Another possible factor to consider is how Google Play and the App Store differ. For example, if Android users have significantly more apps (and social media apps) to choose from, that may cause greater dilution of users. Lastly, any differences in the user experience can deter Android users from using Instagram compared to iOS users. If the app is more buggy for Android users than iOS users, they’ll be less likely to be active on the app. Check out more Facebook data science interview questions here Generally, you would want to probe the interviewer for more information but let’s assume that this is the only information that he/she is willing to give. Focusing on likes per user, there are two reasons why this would have gone up. The first reason is that the engagement of users has generally increased on average over time — this makes sense because as time passes, active users are more likely to be loyal users as using the platform becomes a habitual practice. The other reason why likes per user would increase is that the denominator, the total number of users, is decreasing. Assuming that users that stop using the platform are inactive users, aka users with little engagement and fewer likes than average, this would increase the average number of likes per user. The explanation above can also be applied to minutes spent on the platform. Active users are becoming more engaged over time, while users with little usage are becoming inactive. Overall the increase in engagement outweighs the users with little engagement. To take it a step further, it’s possible that the ‘users with little engagement’ are bots that Facebook has been able to detect. But over time, Facebook has been able to develop algorithms to spot and remove bots. If were a significant number of bots before, this can potentially be the root cause of this phenomenon. The total number of likes in a given year is a function of the total number of users and the average number of likes per user (which I’ll refer to as engagement). Some potential reasons for an increase in the total number of users are the following: users acquired due to international expansion and younger age groups signing up for Facebook as they get older. Some potential reasons for an increase in engagement are an increase in usage of the app from users that are becoming more and more loyal, new features and functionality, and an improved user experience. The metrics that determine a product’s success are dependent on the business model and what the business is trying to achieve through the product. The book Lean analytics lays out a great framework that one can use to determine what metrics to use in a given scenario: You can perform an A/B test by splitting the users into two groups: a control group with the normal number of ads and a test group with double the number of ads. Then you would choose the metric to define what a “good idea” is. For example, we can say that the null hypothesis is that doubling the number of ads will reduce the time spent on Facebook and the alternative hypothesis is that doubling the number of ads won’t have any impact on the time spent on Facebook. However, you can choose a different metric like the number of active users or the churn rate. Then you would conduct the test and determine the statistical significance of the test to reject or not reject the null. Lift: lift is a measure of the performance of a targeting model measured against a random choice targeting model; in other words, lift tells you how much better your model is at predicting things than if you had no model. KPI: stands for Key Performance Indicator, which is a measurable metric used to determine how well a company is achieving its business objectives. Eg. error rate. Robustness: generally robustness refers to a system’s ability to handle variability and remain effective. Model fitting: refers to how well a model fits a set of observations. Design of experiments: also known as DOE, it is the design of any task that aims to describe and explain the variation of information under conditions that are hypothesized to reflect the variable. [4] In essence, an experiment aims to predict an outcome based on a change in one or more inputs (independent variables). 80/20 rule: also known as the Pareto principle; states that 80% of the effects come from 20% of the causes. Eg. 80% of sales come from 20% of customers. Quality assurance: an activity or set of activities focused on maintaining a desired level of quality by minimizing mistakes and defects. Six sigma: a specific type of quality assurance methodology composed of a set of techniques and tools for process improvement. A six sigma process is one in which 99.99966% of all outcomes are free of defects. [1] Central Limit Theorem, Definition and Examples in Easy Steps, Statistics How To [2] Power, Statistics, Wikipedia [3] Anthropic principle, Wikipedia [4] Design of experiments, Wikipedia [5] Root cause analysis, Wikipedia If you enjoyed this be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!
[ { "code": null, "e": 195, "s": 172, "text": "I know this is long..." }, { "code": null, "e": 382, "s": 195, "text": "Really long. But don’t be intimidated by the length — I have broken this down into four sections (machine learning, stats, SQL, miscellaneous) so that you can go through this bit by bit." }, { "code": null, "e": 581, "s": 382, "text": "Think of this as a workbook or a crash course filled with hundreds of data science interview questions that you can use to hone your knowledge and to identify gaps that you can then fill afterwards." }, { "code": null, "e": 672, "s": 581, "text": "I hope you find this helpful and wish you the best of luck in your data science endeavors!" }, { "code": null, "e": 823, "s": 672, "text": "Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 853, "s": 823, "text": "Machine Learning Fundamentals" }, { "code": null, "e": 894, "s": 853, "text": "Statistics, Probability, and Mathematics" }, { "code": null, "e": 916, "s": 894, "text": "SQL Practice Problems" }, { "code": null, "e": 930, "s": 916, "text": "Miscellaneous" }, { "code": null, "e": 1056, "s": 930, "text": "There are many steps that can be taken when data wrangling and data cleaning. Some of the most common steps are listed below:" }, { "code": null, "e": 1281, "s": 1056, "text": "Data profiling: Almost everyone starts off by getting an understanding of their dataset. More specifically, you can look at the shape of the dataset with .shape and a description of your numerical variables with .describe()." }, { "code": null, "e": 1490, "s": 1281, "text": "Data visualizations: Sometimes, it’s useful to visualize your data with histograms, boxplots, and scatterplots to better understand the relationships between variables and also to identify potential outliers." }, { "code": null, "e": 1686, "s": 1490, "text": "Syntax error: This includes making sure there’s no white space, making sure letter casing is consistent, and checking for typos. You can check for typos by using .unique() or by using bar graphs." }, { "code": null, "e": 1972, "s": 1686, "text": "Standardization or normalization: Depending on the dataset your working with and the machine learning method you decide to use, it may be useful to standardize or normalize your data so that different scales of different variables don’t negatively impact the performance of your model." }, { "code": null, "e": 2306, "s": 1972, "text": "Handling null values: There are a number of ways to handle null values including deleting rows with null values altogether, replacing null values with the mean/median/mode, replacing null values with a new category (eg. unknown), predicting the values, or using machine learning models that can deal with null values. Read more here." }, { "code": null, "e": 2396, "s": 2306, "text": "Other things include: removing irrelevant data, removing duplicates, and type conversion." }, { "code": null, "e": 2547, "s": 2396, "text": "Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 2674, "s": 2547, "text": "There are a number of ways to handle unbalanced binary classification (assuming that you want to identify the minority class):" }, { "code": null, "e": 3121, "s": 2674, "text": "First, you want to reconsider the metrics that you’d use to evaluate your model. The accuracy of your model might not be the best metric to look at because and I’ll use an example to explain why. Let’s say 99 bank withdrawals were not fraudulent and 1 withdrawal was. If your model simply classified every instance as “not fraudulent”, it would have an accuracy of 99%! Therefore, you may want to consider using metrics like precision and recall." }, { "code": null, "e": 3341, "s": 3121, "text": "Another method to improve unbalanced binary classification is by increasing the cost of misclassifying the minority class. By increasing the penalty of such, the model should classify the minority class more accurately." }, { "code": null, "e": 3496, "s": 3341, "text": "Lastly, you can improve the balance of classes by oversampling the minority class or by undersampling the majority class. You can read more about it here." }, { "code": null, "e": 3630, "s": 3496, "text": "While boxplots and histograms are visualizations used to show the distribution of the data, they communicate information differently." }, { "code": null, "e": 3899, "s": 3630, "text": "Histograms are bar charts that show the frequency of a numerical variable’s values and are used to approximate the probability distribution of the given variable. It allows you to quickly understand the shape of the distribution, the variation, and potential outliers." }, { "code": null, "e": 4253, "s": 3899, "text": "Boxplots communicate different aspects of the distribution of data. While you can’t see the shape of the distribution through a box plot, you can gather other information like the quartiles, the range, and outliers. Boxplots are especially useful when you want to compare multiple charts at the same time because they take up less space than histograms." }, { "code": null, "e": 4450, "s": 4253, "text": "Both L1 and L2 regularization are methods used to reduce the overfitting of training data. Least Squares minimizes the sum of the squared residuals, which can result in low bias but high variance." }, { "code": null, "e": 4754, "s": 4450, "text": "L2 Regularization, also called ridge regression, minimizes the sum of the squared residuals plus lambda times the slope squared. This additional term is called the Ridge Regression Penalty. This increases the bias of the model, making the fit worse on the training data, but also decreases the variance." }, { "code": null, "e": 4900, "s": 4754, "text": "If you take the ridge regression penalty and replace it with the absolute value of the slope, then you get Lasso regression or L1 regularization." }, { "code": null, "e": 5058, "s": 4900, "text": "L2 is less robust but has a stable solution and always one solution. L1 is more robust but has an unstable solution and can possibly have multiple solutions." }, { "code": null, "e": 5125, "s": 5058, "text": "StatQuest has an amazing video on Lasso and Ridge regression here." }, { "code": null, "e": 5618, "s": 5125, "text": "A neural network is a multi-layered model inspired by the human brain. Like the neurons in our brain, the circles above represent a node. The blue circles represent the input layer, the black circles represent the hidden layers, and the green circles represent the output layer. Each node in the hidden layers represents a function that the inputs go through, ultimately leading to an output in the green circles. The formal term for these functions is called the sigmoid activation function." }, { "code": null, "e": 5721, "s": 5618, "text": "If you want a step by step example of creating a neural network, check out Victor Zhou’s article here." }, { "code": null, "e": 5843, "s": 5721, "text": "If you’re a visual/audio learner, 3Blue1Brown has an amazing series on neural networks and deep learning on YouTube here." }, { "code": null, "e": 5994, "s": 5843, "text": "Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 6318, "s": 5994, "text": "Cross-validation is essentially a technique used to assess how well a model performs on a new independent dataset. The simplest example of cross-validation is when you split your data into two groups: training data and testing data, where you use the training data to build the model and the testing data to test the model." }, { "code": null, "e": 6444, "s": 6318, "text": "There isn’t a one-size-fits-all metric. The metric(s) chosen to evaluate a machine learning model depends on various factors:" }, { "code": null, "e": 6487, "s": 6444, "text": "Is it a regression or classification task?" }, { "code": null, "e": 6543, "s": 6487, "text": "What is the business objective? Eg. precision vs recall" }, { "code": null, "e": 6592, "s": 6543, "text": "What is the distribution of the target variable?" }, { "code": null, "e": 6741, "s": 6592, "text": "There are a number of metrics that can be used, including adjusted r-squared, MAE, MSE, accuracy, recall, precision, f1 score, and the list goes on." }, { "code": null, "e": 6831, "s": 6741, "text": "Recall attempts to answer “What proportion of actual positives was identified correctly?”" }, { "code": null, "e": 6928, "s": 6831, "text": "Precision attempts to answer “What proportion of positive identifications was actually correct?”" }, { "code": null, "e": 7025, "s": 6928, "text": "A false positive is an incorrect identification of the presence of a condition when it’s absent." }, { "code": null, "e": 7131, "s": 7025, "text": "A false negative is an incorrect identification of the absence of a condition when it’s actually present." }, { "code": null, "e": 7379, "s": 7131, "text": "An example of when false negatives are more important than false positives is when screening for cancer. It’s much worse to say that someone doesn’t have cancer when they do, instead of saying that someone does and later realizing that they don’t." }, { "code": null, "e": 7666, "s": 7379, "text": "This is a subjective argument, but false positives can be worse than false negatives from a psychological point of view. For example, a false positive for winning the lottery could be a worse outcome than a false negative because people normally don’t expect to win the lottery anyways." }, { "code": null, "e": 7788, "s": 7666, "text": "Supervised learning involves learning a function that maps an input to an output based on example input-output pairs [1]." }, { "code": null, "e": 7973, "s": 7788, "text": "For example, if I had a dataset with two variables, age (input) and height (output), I could implement a supervised learning model to predict the height of a person based on their age." }, { "code": null, "e": 8231, "s": 7973, "text": "Unlike supervised learning, unsupervised learning is used to draw inferences and find patterns from input data without references to labeled outcomes. A common use of unsupervised learning is grouping customers by purchasing behavior to find target markets." }, { "code": null, "e": 8347, "s": 8231, "text": "Check out my article ‘All Machine Learning Models Explained in Six Minutes’ if you’d like to learn more about this!" }, { "code": null, "e": 8393, "s": 8347, "text": "There are two main ways that you can do this:" }, { "code": null, "e": 8416, "s": 8393, "text": "A) Adjusted R-squared." }, { "code": null, "e": 8705, "s": 8416, "text": "R Squared is a measurement that tells you to what extent the proportion of variance in the dependent variable is explained by the variance in the independent variables. In simpler terms, while the coefficients estimate trends, R-squared represents the scatter around the line of best fit." }, { "code": null, "e": 9182, "s": 8705, "text": "However, every additional independent variable added to a model always increases the R-squared value — therefore, a model with several independent variables may seem to be a better fit even if it isn’t. This is where adjusted R2 comes in. The adjusted R2 compensates for each additional independent variable and only increases if each given variable improves the model above what is possible by probability. This is important since we are creating a multiple regression model." }, { "code": null, "e": 9202, "s": 9182, "text": "B) Cross-Validation" }, { "code": null, "e": 9370, "s": 9202, "text": "A method common to most people is cross-validation, splitting the data into two sets: training and testing data. See the answer to the first question for more on this." }, { "code": null, "e": 9528, "s": 9370, "text": "NLP stands for Natural Language Processing. It is a branch of artificial intelligence that gives machines the ability to read and understand human languages." }, { "code": null, "e": 9637, "s": 9528, "text": "There are a couple of reasons why a random forest is a better choice of model than a support vector machine:" }, { "code": null, "e": 9720, "s": 9637, "text": "Random forests allow you to determine the feature importance. SVM’s can’t do this." }, { "code": null, "e": 9786, "s": 9720, "text": "Random forests are much quicker and simpler to build than an SVM." }, { "code": null, "e": 9912, "s": 9786, "text": "For multi-class classification problems, SVMs require a one-vs-rest method, which is less scalable and more memory intensive." }, { "code": null, "e": 10100, "s": 9912, "text": "Dimensionality reduction is the process of reducing the number of features in a dataset. This is important mainly in the case when you want to reduce variance in your model (overfitting)." }, { "code": null, "e": 10173, "s": 10100, "text": "Wikipedia states four advantages of dimensionality reduction (see here):" }, { "code": null, "e": 10454, "s": 10173, "text": "It reduces the time and storage space requiredRemoval of multi-collinearity improves the interpretation of the parameters of the machine learning modelIt becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3DIt avoids the curse of dimensionality" }, { "code": null, "e": 10501, "s": 10454, "text": "It reduces the time and storage space required" }, { "code": null, "e": 10607, "s": 10501, "text": "Removal of multi-collinearity improves the interpretation of the parameters of the machine learning model" }, { "code": null, "e": 10700, "s": 10607, "text": "It becomes easier to visualize the data when reduced to very low dimensions such as 2D or 3D" }, { "code": null, "e": 10738, "s": 10700, "text": "It avoids the curse of dimensionality" }, { "code": null, "e": 10997, "s": 10738, "text": "In its simplest sense, PCA involves project higher dimensional data (eg. 3 dimensions) to a smaller space (eg. 2 dimensions). This results in a lower dimension of data, (2 dimensions instead of 3 dimensions) while keeping all original variables in the model." }, { "code": null, "e": 11176, "s": 10997, "text": "PCA is commonly used for compression purposes, to reduce required memory and to speed up the algorithm, as well as for visualization purposes, making it easier to summarize data." }, { "code": null, "e": 11352, "s": 11176, "text": "One major drawback of Naive Bayes is that it holds a strong assumption in that the features are assumed to be uncorrelated with one another, which typically is never the case." }, { "code": null, "e": 11479, "s": 11352, "text": "One way to improve such an algorithm that uses Naive Bayes is by decorrelating the features so that the assumption holds true." }, { "code": null, "e": 11530, "s": 11479, "text": "There are a couple of drawbacks of a linear model:" }, { "code": null, "e": 11744, "s": 11530, "text": "A linear model holds some strong assumptions that may not be true in application. It assumes a linear relationship, multivariate normality, no or little multicollinearity, no auto-correlation, and homoscedasticity" }, { "code": null, "e": 11806, "s": 11744, "text": "A linear model can’t be used for discrete or binary outcomes." }, { "code": null, "e": 11862, "s": 11806, "text": "You can’t vary the model flexibility of a linear model." }, { "code": null, "e": 12167, "s": 11862, "text": "Another way of asking this question is “Is a random forest a better model than a decision tree?” And the answer is yes because a random forest is an ensemble method that takes many weak decision trees to make a strong learner. Random forests are more accurate, more robust, and less prone to overfitting." }, { "code": null, "e": 12368, "s": 12167, "text": "Mean Squared Error (MSE) gives a relatively high weight to large errors — therefore, MSE tends to put too much emphasis on large deviations. A more robust alternative is MAE (mean absolute deviation)." }, { "code": null, "e": 12400, "s": 12368, "text": "The assumptions are as follows:" }, { "code": null, "e": 12694, "s": 12400, "text": "The sample data used to fit the model is representative of the populationThe relationship between X and the mean of Y is linearThe variance of the residual is the same for any value of X (homoscedasticity)Observations are independent of each otherFor any value of X, Y is normally distributed." }, { "code": null, "e": 12768, "s": 12694, "text": "The sample data used to fit the model is representative of the population" }, { "code": null, "e": 12823, "s": 12768, "text": "The relationship between X and the mean of Y is linear" }, { "code": null, "e": 12902, "s": 12823, "text": "The variance of the residual is the same for any value of X (homoscedasticity)" }, { "code": null, "e": 12945, "s": 12902, "text": "Observations are independent of each other" }, { "code": null, "e": 12992, "s": 12945, "text": "For any value of X, Y is normally distributed." }, { "code": null, "e": 13162, "s": 12992, "text": "Extreme violations of these assumptions will make the results redundant. Small violations of these assumptions will result in a greater bias or variance of the estimate." }, { "code": null, "e": 13409, "s": 13162, "text": "Multicollinearity exists when an independent variable is highly correlated with another independent variable in a multiple regression equation. This can be problematic because it undermines the statistical significance of an independent variable." }, { "code": null, "e": 13628, "s": 13409, "text": "You could use the Variance Inflation Factors (VIF) to determine if there is any multicollinearity between independent variables — a standard benchmark is that if the VIF is greater than 5 then multicollinearity exists." }, { "code": null, "e": 13676, "s": 13628, "text": "There are a couple of metrics that you can use:" }, { "code": null, "e": 13771, "s": 13676, "text": "R-squared/Adjusted R-squared: Relative measure of fit. This was explained in a previous answer" }, { "code": null, "e": 13929, "s": 13771, "text": "F1 Score: Evaluates the null hypothesis that all regression coefficients are equal to zero vs the alternative hypothesis that at least one doesn’t equal zero" }, { "code": null, "e": 13960, "s": 13929, "text": "RMSE: Absolute measure of fit." }, { "code": null, "e": 14377, "s": 13960, "text": "Decision trees are a popular model, used in operations research, strategic planning, and machine learning. Each square above is called a node, and the more nodes you have, the more accurate your decision tree will be (generally). The last nodes of the decision tree, where a decision is made, are called the leaves of the tree. Decision trees are intuitive and easy to build but fall short when it comes to accuracy." }, { "code": null, "e": 14821, "s": 14377, "text": "Random forests are an ensemble learning technique that builds off of decision trees. Random forests involve creating multiple decision trees using bootstrapped datasets of the original data and randomly selecting a subset of variables at each step of the decision tree. The model then selects the mode of all of the predictions of each decision tree. By relying on a “majority wins” model, it reduces the risk of error from an individual tree." }, { "code": null, "e": 15025, "s": 14821, "text": "For example, if we created one decision tree, the third one, it would predict 0. But if we relied on the mode of all 4 decision trees, the predicted value would be 1. This is the power of random forests." }, { "code": null, "e": 15190, "s": 15025, "text": "Random forests offer several other benefits including strong performance, can model non-linear boundaries, no cross-validation needed, and gives feature importance." }, { "code": null, "e": 15341, "s": 15190, "text": "Be sure to subscribe here or to my exclusive newsletter to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 15550, "s": 15341, "text": "A kernel is a way of computing the dot product of two vectors xx and yy in some (possibly very high dimensional) feature space, which is why kernel functions are sometimes called “generalized dot product” [2]" }, { "code": null, "e": 15730, "s": 15550, "text": "The kernel trick is a method of using a linear classifier to solve a non-linear problem by transforming linearly inseparable data to linearly separable ones in a higher dimension." }, { "code": null, "e": 15875, "s": 15730, "text": "When the number of features is greater than the number of observations, then performing dimensionality reduction will generally improve the SVM." }, { "code": null, "e": 16129, "s": 15875, "text": "Overfitting is an error where the model ‘fits’ the data too well, resulting in a model with high variance and low bias. As a consequence, an overfit model will inaccurately predict new data points even though it has a high accuracy on the training data." }, { "code": null, "e": 16434, "s": 16129, "text": "Boosting is an ensemble method to improve a model by reducing its bias and variance, ultimately converting weak learners to strong learners. The general idea is to train a weak learner and sequentially iterate and improve the model by learning from the previous learner. You can learn more about it here." }, { "code": null, "e": 16550, "s": 16434, "text": "Be sure to subscribe to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 16855, "s": 16550, "text": "We need to make some assumptions about this question before we can answer it. Let’s assume that there are two possible places to purchase a particular item on Amazon and the probability of finding it at location A is 0.6 and B is 0.8. The probability of finding the item on Amazon can be explained as so:" }, { "code": null, "e": 17073, "s": 16855, "text": "We can reword the above as P(A) = 0.6 and P(B) = 0.8. Furthermore, let’s assume that these are independent events, meaning that the probability of one event is not impacted by the other. We can then use the formula..." }, { "code": null, "e": 17159, "s": 17073, "text": "P(A or B) = P(A) + P(B) — P(A and B)P(A or B) = 0.6 + 0.8 — (0.6*0.8)P(A or B) = 0.92" }, { "code": null, "e": 17217, "s": 17159, "text": "Check out the Amazon data scientist interview guide here." }, { "code": null, "e": 17325, "s": 17217, "text": "This can be answered using the Bayes Theorem. The extended equation for the Bayes Theorem is the following:" }, { "code": null, "e": 17551, "s": 17325, "text": "Assume that the probability of picking the unfair coin is denoted as P(A) and the probability of flipping 10 heads in a row is denoted as P(B). Then P(B|A) is equal to 1, P(B∣¬A) is equal to 0.510, and P(¬A) is equal to 0.99." }, { "code": null, "e": 17612, "s": 17551, "text": "If you fill in the equation, then P(A|B) = 0.9118 or 91.18%." }, { "code": null, "e": 17740, "s": 17612, "text": "A convex function is one where a line drawn between any two points on the graph lies on or above the graph. It has one minimum." }, { "code": null, "e": 17893, "s": 17740, "text": "A non-convex function is one where a line drawn between any two points on the graph may intersect other points on the graph. It characterized as “wavy”." }, { "code": null, "e": 18125, "s": 17893, "text": "When a cost function is non-convex, it means that there’s a likelihood that the function may find local minima instead of the global minimum, which is typically undesired in machine learning models from an optimization perspective." }, { "code": null, "e": 18258, "s": 18125, "text": "For this, I’m going to look at the eight rules of probability laid out here and the four different counting methods (see more here)." }, { "code": null, "e": 18285, "s": 18258, "text": "Eight rules of probability" }, { "code": null, "e": 18392, "s": 18285, "text": "Rule #1: For any event A, 0 ≤ P(A) ≤ 1; in other words, the probability of an event can range from 0 to 1." }, { "code": null, "e": 18472, "s": 18392, "text": "Rule #2: The sum of the probabilities of all possible outcomes always equals 1." }, { "code": null, "e": 18680, "s": 18472, "text": "Rule #3: P(not A) = 1 — P(A); This rule explains the relationship between the probability of an event and its complement event. A complement event is one that includes all possible outcomes that aren’t in A." }, { "code": null, "e": 18825, "s": 18680, "text": "Rule #4: If A and B are disjoint events (mutually exclusive), then P(A or B) = P(A) + P(B); this is called the addition rule for disjoint events" }, { "code": null, "e": 18914, "s": 18825, "text": "Rule #5: P(A or B) = P(A) + P(B) — P(A and B); this is called the general addition rule." }, { "code": null, "e": 19056, "s": 18914, "text": "Rule #6: If A and B are two independent events, then P(A and B) = P(A) * P(B); this is called the multiplication rule for independent events." }, { "code": null, "e": 19148, "s": 19056, "text": "Rule #7: The conditional probability of event B given event A is P(B|A) = P(A and B) / P(A)" }, { "code": null, "e": 19260, "s": 19148, "text": "Rule #8: For any two events A and B, P(A and B) = P(A) * P(B|A); this is called the general multiplication rule" }, { "code": null, "e": 19277, "s": 19260, "text": "Counting Methods" }, { "code": null, "e": 19501, "s": 19277, "text": "Factorial Formula: n! = n x (n -1) x (n — 2) x ... x 2 x 1Use when the number of items is equal to the number of places available.Eg. Find the total number of ways 5 people can sit in 5 empty seats.= 5 x 4 x 3 x 2 x 1 = 120" }, { "code": null, "e": 19818, "s": 19501, "text": "Fundamental Counting Principle (multiplication)This method should be used when repetitions are allowed and the number of ways to fill an open place is not affected by previous fills.Eg. There are 3 types of breakfasts, 4 types of lunches, and 5 types of desserts. The total number of combinations is = 5 x 4 x 3 = 60" }, { "code": null, "e": 20153, "s": 19818, "text": "Permutations: P(n,r)= n! / (n−r)!This method is used when replacements are not allowed and order of item ranking matters.Eg. A code has 4 digits in a particular order and the digits range from 0 to 9. How many permutations are there if one digit can only be used once?P(n,r) = 10!/(10–4)! = (10x9x8x7x6x5x4x3x2x1)/(6x5x4x3x2x1) = 5040" }, { "code": null, "e": 20469, "s": 20153, "text": "Combinations Formula: C(n,r)=(n!)/[(n−r)!r!]This is used when replacements are not allowed and the order in which items are ranked does not mater.Eg. To win the lottery, you must select the 5 correct numbers in any order from 1 to 52. What is the number of possible combinations?C(n,r) = 52! / (52–5)!5! = 2,598,960" }, { "code": null, "e": 20532, "s": 20469, "text": "Brilliant provides a great definition of Markov chains (here):" }, { "code": null, "e": 20951, "s": 20532, "text": "“A Markov chain is a mathematical system that experiences transitions from one state to another according to certain probabilistic rules. The defining characteristic of a Markov chain is that no matter how the process arrived at its present state, the possible future states are fixed. In other words, the probability of transitioning to any particular state is dependent solely on the current state and time elapsed.”" }, { "code": null, "e": 21130, "s": 20951, "text": "The actual math behind Markov chains requires knowledge on linear algebra and matrices, so I’ll leave some links below in case you want to explore this topic further on your own." }, { "code": null, "e": 21153, "s": 21130, "text": "See more here or here." }, { "code": null, "e": 21293, "s": 21153, "text": "The box with 24 red cards and 24 black cards has a higher probability of getting two cards of the same color. Let’s walk through each step." }, { "code": null, "e": 21356, "s": 21293, "text": "Let’s say the first card you draw from each deck is a red Ace." }, { "code": null, "e": 21524, "s": 21356, "text": "This means that in the deck with 12 reds and 12 blacks, there’s now 11 reds and 12 blacks. Therefore your odds of drawing another red are equal to 11/(11+12) or 11/23." }, { "code": null, "e": 21684, "s": 21524, "text": "In the deck with 24 reds and 24 blacks, there would then be 23 reds and 24 blacks. Therefore your odds of drawing another red are equal to 23/(23+24) or 23/47." }, { "code": null, "e": 21793, "s": 21684, "text": "Since 23/47 > 11/23, the second deck with more cards has a higher probability of getting the same two cards." }, { "code": null, "e": 21852, "s": 21793, "text": "Let’s assume that it costs $5 every time you want to play." }, { "code": null, "e": 21902, "s": 21852, "text": "There are 36 possible combinations with two dice." }, { "code": null, "e": 22055, "s": 21902, "text": "Of the 36 combinations, there are 4 combinations that result in rolling a five (see blue). This means that there is a 4/36 or 1/9 chance of rolling a 5." }, { "code": null, "e": 22139, "s": 22055, "text": "A 1/9 chance of winning means you’ll lose eight times and win once (theoretically)." }, { "code": null, "e": 22216, "s": 22139, "text": "Therefore, your expected payout is equal to $10.00 * 1 — $5.00 * 9= -$35.00." }, { "code": null, "e": 22293, "s": 22216, "text": "Edit: Thank you guys for commenting and pointing out that it should be -$35!" }, { "code": null, "e": 22373, "s": 22293, "text": "This isn’t a trick question. The answer is simply to perform a hypothesis test:" }, { "code": null, "e": 22862, "s": 22373, "text": "The null hypothesis is that the coin is not biased and the probability of flipping heads should equal 50% (p=0.5). The alternative hypothesis is that the coin is biased and p != 0.5.Flip the coin 500 times.Calculate Z-score (if the sample is less than 30, you would calculate the t-statistics).Compare against alpha (two-tailed test so 0.05/2 = 0.025).If p-value > alpha, the null is not rejected and the coin is not biased.If p-value < alpha, the null is rejected and the coin is biased." }, { "code": null, "e": 23045, "s": 22862, "text": "The null hypothesis is that the coin is not biased and the probability of flipping heads should equal 50% (p=0.5). The alternative hypothesis is that the coin is biased and p != 0.5." }, { "code": null, "e": 23070, "s": 23045, "text": "Flip the coin 500 times." }, { "code": null, "e": 23159, "s": 23070, "text": "Calculate Z-score (if the sample is less than 30, you would calculate the t-statistics)." }, { "code": null, "e": 23218, "s": 23159, "text": "Compare against alpha (two-tailed test so 0.05/2 = 0.025)." }, { "code": null, "e": 23355, "s": 23218, "text": "If p-value > alpha, the null is not rejected and the coin is not biased.If p-value < alpha, the null is rejected and the coin is biased." }, { "code": null, "e": 23397, "s": 23355, "text": "Learn more about hypothesis testing here." }, { "code": null, "e": 23609, "s": 23397, "text": "Since a coin flip is a binary outcome, you can make an unfair coin fair by flipping it twice. If you flip it twice, there are two outcomes that you can bet on: heads followed by tails or tails followed by heads." }, { "code": null, "e": 23651, "s": 23609, "text": "P(heads) * P(tails) = P(tails) * P(heads)" }, { "code": null, "e": 23808, "s": 23651, "text": "This makes sense since each coin toss is an independent event. This means that if you get heads → heads or tails → tails, you would need to reflip the coin." }, { "code": null, "e": 24099, "s": 23808, "text": "You can tell that this question is related to Bayesian theory because of the last statement which essentially follows the structure, “What is the probability A is true given B is true?” Therefore we need to know the probability of it raining in London on a given day. Let’s assume it’s 25%." }, { "code": null, "e": 24366, "s": 24099, "text": "P(A) = probability of it raining = 25%P(B) = probability of all 3 friends say that it’s rainingP(A|B) probability that it’s raining given they’re telling that it is rainingP(B|A) probability that all 3 friends say that it’s raining given it’s raining = (2/3)3 = 8/27" }, { "code": null, "e": 24543, "s": 24366, "text": "Step 1: Solve for P(B)P(A|B) = P(B|A) * P(A) / P(B), can be rewritten asP(B) = P(B|A) * P(A) + P(B|not A) * P(not A)P(B) = (2/3)3 * 0.25 + (1/3)3 * 0.75 = 0.25*8/27 + 0.75*1/27" }, { "code": null, "e": 24644, "s": 24543, "text": "Step 2: Solve for P(A|B)P(A|B) = 0.25 * (8/27) / ( 0.25*8/27 + 0.75*1/27)P(A|B) = 8 / (8 + 3) = 8/11" }, { "code": null, "e": 24755, "s": 24644, "text": "Therefore, if all three friends say that it’s raining, then there’s an 8/11 chance that it’s actually raining." }, { "code": null, "e": 24914, "s": 24755, "text": "Since these events are not independent, we can use the rule:P(A and B) = P(A) * P(B|A) ,which is also equal toP(not A and not B) = P(not A) * P(not B | not A)" }, { "code": null, "e": 24927, "s": 24914, "text": "For example:" }, { "code": null, "e": 25060, "s": 24927, "text": "P(not 4 and not yellow) = P(not 4) * P(not yellow | not 4)P(not 4 and not yellow) = (36/39) * (27/36)P(not 4 and not yellow) = 0.692" }, { "code": null, "e": 25162, "s": 25060, "text": "Therefore, the probability that the cards picked are not the same number and the same color is 69.2%." }, { "code": null, "e": 25639, "s": 25162, "text": "You would perform hypothesis testing to determine statistical significance. First, you would state the null hypothesis and alternative hypothesis. Second, you would calculate the p-value, the probability of obtaining the observed results of a test assuming that the null hypothesis is true. Last, you would set the level of the significance (alpha) and if the p-value is less than the alpha, you would reject the null — in other words, the result is statistically significant." }, { "code": null, "e": 25776, "s": 25639, "text": "A long-tailed distribution is a type of heavy-tailed distribution that has a tail (or tails) that drop off gradually and asymptotically." }, { "code": null, "e": 25940, "s": 25776, "text": "3 practical examples include the power law, the Pareto principle (more commonly known as the 80–20 rule), and product sales (i.e. best selling products vs others)." }, { "code": null, "e": 26309, "s": 25940, "text": "It’s important to be mindful of long-tailed distributions in classification and regression problems because the least frequently occurring values make up the majority of the population. This can ultimately change the way that you deal with outliers, and it also conflicts with some machine learning techniques with the assumption that the data is normally distributed." }, { "code": null, "e": 26374, "s": 26309, "text": "Statistics How To provides the best definition of CLT, which is:" }, { "code": null, "e": 26584, "s": 26374, "text": "“The central limit theorem states that the sampling distribution of the sample mean approaches a normal distribution as the sample size gets larger no matter what the shape of the population distribution.” [1]" }, { "code": null, "e": 26708, "s": 26584, "text": "The central limit theorem is important because it is used in hypothesis testing and also to calculate confidence intervals." }, { "code": null, "e": 26890, "s": 26708, "text": "‘Statistical power’ refers to the power of a binary hypothesis, which is the probability that the test rejects the null hypothesis given that the alternative hypothesis is true. [2]" }, { "code": null, "e": 27113, "s": 26890, "text": "Selection bias is the phenomenon of selecting individuals, groups or data for analysis in such a way that proper randomization is not achieved, ultimately resulting in a sample that is not representative of the population." }, { "code": null, "e": 27277, "s": 27113, "text": "Understanding and identifying selection bias is important because it can significantly skew results and provide false insights about a particular population group." }, { "code": null, "e": 27310, "s": 27277, "text": "Types of selection bias include:" }, { "code": null, "e": 27371, "s": 27310, "text": "sampling bias: a biased sample caused by non-random sampling" }, { "code": null, "e": 27505, "s": 27371, "text": "time interval: selecting a specific time frame that supports the desired conclusion. e.g. conducting a sales analysis near Christmas." }, { "code": null, "e": 27605, "s": 27505, "text": "exposure: includes clinical susceptibility bias, protopathic bias, indication bias. Read more here." }, { "code": null, "e": 27698, "s": 27605, "text": "data: includes cherry-picking, suppressing evidence, and the fallacy of incomplete evidence." }, { "code": null, "e": 27895, "s": 27698, "text": "attrition: attrition bias is similar to survivorship bias, where only those that ‘survived’ a long process are included in an analysis, or failure bias, where those that ‘failed’ are only included" }, { "code": null, "e": 28178, "s": 27895, "text": "observer selection: related to the Anthropic principle, which is a philosophical consideration that any data we collect about the universe is filtered by the fact that, in order for it to be observable, it must be compatible with the conscious and sapient life that observes it. [3]" }, { "code": null, "e": 28468, "s": 28178, "text": "Handling missing data can make selection bias worse because different methods impact the data in different ways. For example, if you replace null values with the mean of the data, you adding bias in the sense that you’re assuming that the data is not as spread out as it might actually be." }, { "code": null, "e": 28615, "s": 28468, "text": "Observational data comes from observational studies which are when you observe certain variables and try to determine if there is any correlation." }, { "code": null, "e": 28773, "s": 28615, "text": "Experimental data comes from experimental studies which are when you control certain variables and hold them constant to determine if there is any causality." }, { "code": null, "e": 29033, "s": 28773, "text": "An example of experimental design is the following: split a group up into two. The control group lives their lives normally. The test group is told to drink a glass of wine every night for 30 days. Then research can be conducted to see how wine affects sleep." }, { "code": null, "e": 29131, "s": 29033, "text": "Mean imputation is the practice of replacing null values in a data set with the mean of the data." }, { "code": null, "e": 29529, "s": 29131, "text": "Mean imputation is generally bad practice because it doesn’t take into account feature correlation. For example, imagine we have a table showing age and fitness score and imagine that an eighty-year-old has a missing fitness score. If we took the average fitness score from an age range of 15 to 80, then the eighty-year-old will appear to have a much higher fitness score that he actually should." }, { "code": null, "e": 29716, "s": 29529, "text": "Second, mean imputation reduces the variance of the data and increases bias in our data. This leads to a less accurate model and a narrower confidence interval due to a smaller variance." }, { "code": null, "e": 29795, "s": 29716, "text": "An outlier is a data point that differs significantly from other observations." }, { "code": null, "e": 30081, "s": 29795, "text": "Depending on the cause of the outlier, they can be bad from a machine learning perspective because they can worsen the accuracy of a model. If the outlier is caused by a measurement error, it’s important to remove them from the dataset. There are a couple of ways to identify outliers:" }, { "code": null, "e": 30671, "s": 30081, "text": "Z-score/standard deviations: if we know that 99.7% of data in a data set lie within three standard deviations, then we can calculate the size of one standard deviation, multiply it by 3, and identify the data points that are outside of this range. Likewise, we can calculate the z-score of a given point, and if it’s equal to +/- 3, then it’s an outlier.Note: that there are a few contingencies that need to be considered when using this method; the data must be normally distributed, this is not applicable for small data sets, and the presence of too many outliers can throw off z-score." }, { "code": null, "e": 31022, "s": 30671, "text": "Interquartile Range (IQR): IQR, the concept used to build boxplots, can also be used to identify outliers. The IQR is equal to the difference between the 3rd quartile and the 1st quartile. You can then identify if a point is an outlier if it is less than Q1–1.5*IRQ or greater than Q3 + 1.5*IQR. This comes to approximately 2.698 standard deviations." }, { "code": null, "e": 31113, "s": 31022, "text": "Other methods include DBScan clustering, Isolation Forests, and Robust Random Cut Forests." }, { "code": null, "e": 31434, "s": 31113, "text": "An inlier is a data observation that lies within the rest of the dataset and is unusual or an error. Since it lies in the dataset, it is typically harder to identify than an outlier and requires external data to identify them. Should you identify any inliers, you can simply remove them from the dataset to address them." }, { "code": null, "e": 31481, "s": 31434, "text": "There are several ways to handle missing data:" }, { "code": null, "e": 31511, "s": 31481, "text": "Delete rows with missing data" }, { "code": null, "e": 31539, "s": 31511, "text": "Mean/Median/Mode imputation" }, { "code": null, "e": 31564, "s": 31539, "text": "Assigning a unique value" }, { "code": null, "e": 31594, "s": 31564, "text": "Predicting the missing values" }, { "code": null, "e": 31664, "s": 31594, "text": "Using an algorithm which supports missing values, like random forests" }, { "code": null, "e": 31949, "s": 31664, "text": "The best method is to delete rows with missing data as it ensures that no bias or variance is added or removed, and ultimately results in a robust and accurate model. However, this is only recommended if there’s a lot of data to start with and the percentage of missing values is low." }, { "code": null, "e": 32182, "s": 31949, "text": "First I would conduct EDA — Exploratory Data Analysis to clean, explore, and understand my data. See my article on EDA here. As part of my EDA, I could compose a histogram of the duration of calls to see the underlying distribution." }, { "code": null, "e": 32521, "s": 32182, "text": "My guess is that the duration of calls would follow a lognormal distribution (see below). The reason that I believe it’s positively skewed is because the lower end is limited to 0 since a call can’t be negative seconds. However, on the upper end, it’s likely for there to be a small proportion of calls that are extremely long relatively." }, { "code": null, "e": 32666, "s": 32521, "text": "You could use a QQ plot to confirm whether the duration of calls follows a lognormal distribution or not. See here to learn more about QQ plots." }, { "code": null, "e": 32785, "s": 32666, "text": "Administrative datasets are typically datasets used by governments or other organizations for non-statistical reasons." }, { "code": null, "e": 33205, "s": 32785, "text": "Administrative datasets are usually larger and more cost-efficient than experimental studies. They are also regularly updated assuming that the organization associated with the administrative dataset is active and functioning. At the same time, administrative datasets may not capture all of the data that one may want and may not be in the desired format either. It is also prone to quality issues and missing entries." }, { "code": null, "e": 33275, "s": 33205, "text": "There are a number of potential reasons for a spike in photo uploads:" }, { "code": null, "e": 33852, "s": 33275, "text": "A new feature may have been implemented in October which involves uploading photos and gained a lot of traction by users. For example, a feature that gives the ability to create photo albums.Similarly, it’s possible that the process of uploading photos before was not intuitive and was improved in the month of October.There may have been a viral social media movement that involved uploading photos that lasted for all of October. Eg. Movember but something more scalable.It’s possible that the spike is due to people posting pictures of themselves in costumes for Halloween." }, { "code": null, "e": 34044, "s": 33852, "text": "A new feature may have been implemented in October which involves uploading photos and gained a lot of traction by users. For example, a feature that gives the ability to create photo albums." }, { "code": null, "e": 34173, "s": 34044, "text": "Similarly, it’s possible that the process of uploading photos before was not intuitive and was improved in the month of October." }, { "code": null, "e": 34328, "s": 34173, "text": "There may have been a viral social media movement that involved uploading photos that lasted for all of October. Eg. Movember but something more scalable." }, { "code": null, "e": 34432, "s": 34328, "text": "It’s possible that the spike is due to people posting pictures of themselves in costumes for Halloween." }, { "code": null, "e": 34586, "s": 34432, "text": "The method of testing depends on the cause of the spike, but you would conduct hypothesis testing to determine if the inferred cause is the actual cause." }, { "code": null, "e": 34677, "s": 34586, "text": "Any type of categorical data won’t have a gaussian distribution or lognormal distribution." }, { "code": null, "e": 34803, "s": 34677, "text": "Exponential distributions — eg. the amount of time that a car battery lasts or the amount of time until an earthquake occurs." }, { "code": null, "e": 34919, "s": 34803, "text": "Be sure to subscribe to never miss another article on data science guides, tricks and tips, life lessons, and more!" }, { "code": null, "e": 35024, "s": 34919, "text": "Root cause analysis: a method of problem-solving used for identifying the root cause(s) of a problem [5]" }, { "code": null, "e": 35298, "s": 35024, "text": "Correlation measures the relationship between two variables, range from -1 to 1. Causation is when a first event appears to have caused a second event. Causation essentially looks at direct relationships while correlation can look at both direct and indirect relationships." }, { "code": null, "e": 35535, "s": 35298, "text": "Example: a higher crime rate is associated with higher sales in ice cream in Canada, aka they are positively correlated. However, this doesn’t mean that one causes another. Instead, it’s because both occur more when it’s warmer outside." }, { "code": null, "e": 35603, "s": 35535, "text": "You can test for causation using hypothesis testing or A/B testing." }, { "code": null, "e": 35684, "s": 35603, "text": "When there are a number of outliers that positively or negatively skew the data." }, { "code": null, "e": 35769, "s": 35684, "text": "There are 4 combinations of rolling a 4 (1+3, 3+1, 2+2):P(rolling a 4) = 3/36 = 1/12" }, { "code": null, "e": 35857, "s": 35769, "text": "There are combinations of rolling an 8 (2+6, 6+2, 3+5, 5+3, 4+4):P(rolling an 8) = 5/36" }, { "code": null, "e": 36014, "s": 35857, "text": "The Law of Large Numbers is a theory that states that as the number of trials increases, the average of the result will become closer to the expected value." }, { "code": null, "e": 36102, "s": 36014, "text": "Eg. flipping heads from fair coin 100,000 times should be closer to 0.5 than 100 times." }, { "code": null, "e": 36185, "s": 36102, "text": "You can use the margin of error (ME) formula to determine the desired sample size." }, { "code": null, "e": 36243, "s": 36185, "text": "t/z = t/z score used to calculate the confidence interval" }, { "code": null, "e": 36276, "s": 36243, "text": "ME = the desired margin of error" }, { "code": null, "e": 36306, "s": 36276, "text": "S = sample standard deviation" }, { "code": null, "e": 36346, "s": 36306, "text": "Potential biases include the following:" }, { "code": null, "e": 36407, "s": 36346, "text": "Sampling bias: a biased sample caused by non-random sampling" }, { "code": null, "e": 36458, "s": 36407, "text": "Under coverage bias: sampling too few observations" }, { "code": null, "e": 36566, "s": 36458, "text": "Survivorship bias: error of overlooking observations that did not make it past a form of selection process." }, { "code": null, "e": 36811, "s": 36566, "text": "There are many things that you can do to control and minimize bias. Two common things include randomization, where participants are assigned by chance, and random sampling, sampling in which each member has an equal probability of being chosen." }, { "code": null, "e": 37072, "s": 36811, "text": "A confounding variable, or a confounder, is a variable that influences both the dependent variable and the independent variable, causing a spurious association, a mathematical relationship in which two or more variables are associated but not causally related." }, { "code": null, "e": 37297, "s": 37072, "text": "A/B testing is a form of hypothesis testing and two-sample hypothesis testing to compare two versions, the control and variant, of a single variable. It is commonly used to improve and optimize user experience and marketing." }, { "code": null, "e": 37367, "s": 37297, "text": "Check out my article, A Simple Guide to A/B Testing for Data Science." }, { "code": null, "e": 37454, "s": 37367, "text": "You can use hypothesis testing to prove that males are taller on average than females." }, { "code": null, "e": 37666, "s": 37454, "text": "The null hypothesis would state that males and females are the same height on average, while the alternative hypothesis would state that the average height of males is greater than the average height of females." }, { "code": null, "e": 37798, "s": 37666, "text": "Then you would collect a random sample of heights of males and females and use a t-test to determine if you reject the null or not." }, { "code": null, "e": 37934, "s": 37798, "text": "Since we looking at the number of events (# of infections) occurring within a given timeframe, this is a Poisson distribution question." }, { "code": null, "e": 38019, "s": 37934, "text": "Null (H0): 1 infection per person-daysAlternative (H1): >1 infection per person-days" }, { "code": null, "e": 38155, "s": 38019, "text": "k (actual) = 10 infectionslambda (theoretical) = (1/100)*1787p = 0.032372 or 3.2372% calculated using .poisson() in excel or ppois in R" }, { "code": null, "e": 38287, "s": 38155, "text": "Since p-value < alpha (assuming 5% level of significance), we reject the null and conclude that the hospital is below the standard." }, { "code": null, "e": 38357, "s": 38287, "text": "Use the General Binomial Probability formula to answer this question:" }, { "code": null, "e": 38379, "s": 38357, "text": "p = 0.8n = 5k = 3,4,5" }, { "code": null, "e": 38451, "s": 38379, "text": "P(3 or more heads) = P(3 heads) + P(4 heads) + P(5 heads) = 0.94 or 94%" }, { "code": null, "e": 38513, "s": 38451, "text": "Using Excel...p =1-norm.dist(1200, 1020, 50, true)p= 0.000159" }, { "code": null, "e": 38536, "s": 38513, "text": "x = 3mean = 2.5*4 = 10" }, { "code": null, "e": 38551, "s": 38536, "text": "using Excel..." }, { "code": null, "e": 38591, "s": 38551, "text": "p = poisson.dist(3,10,true)p = 0.010336" }, { "code": null, "e": 38710, "s": 38591, "text": "Precision = Positive Predictive Value = PVPV = (0.001*0.997)/[(0.001*0.997)+((1–0.001)*(1–0.985))]PV = 0.0624 or 6.24%" }, { "code": null, "e": 38745, "s": 38710, "text": "See more about this equation here." }, { "code": null, "e": 38798, "s": 38745, "text": "Assume that there’s only you and one other opponent." }, { "code": null, "e": 38884, "s": 38798, "text": "Also, assume that we want a 95% confidence interval. This gives us a z-score of 1.96." }, { "code": null, "e": 39158, "s": 38884, "text": "p-hat = 60/100 = 0.6z* = 1.96n = 100This gives us a confidence interval of [50.4,69.6]. Therefore, given a confidence interval of 95%, if you are okay with the worst scenario of tying then you can relax. Otherwise, you cannot relax until you got 61 out of 100 to claim yes." }, { "code": null, "e": 39298, "s": 39158, "text": "Since this is a Poisson distribution question, mean = lambda = variance, which also means that standard deviation = square root of the mean" }, { "code": null, "e": 39350, "s": 39298, "text": "a 95% confidence interval implies a z score of 1.96" }, { "code": null, "e": 39378, "s": 39350, "text": "one standard deviation = 10" }, { "code": null, "e": 39445, "s": 39378, "text": "Therefore the confidence interval = 100 +/- 19.6 = [964.8, 1435.2]" }, { "code": null, "e": 39585, "s": 39445, "text": "Since this is a Poisson distribution question, mean = lambda = variance, which also means that standard deviation = square root of the mean" }, { "code": null, "e": 39637, "s": 39585, "text": "a 95% confidence interval implies a z score of 1.96" }, { "code": null, "e": 39681, "s": 39637, "text": "one standard deviation = sqrt(115) = 10.724" }, { "code": null, "e": 39849, "s": 39681, "text": "Therefore the confidence interval = 115+/- 21.45 = [93.55, 136.45]. Since 99 is within this confidence interval, we can assume that this change is not very noteworthy." }, { "code": null, "e": 40073, "s": 39849, "text": "Using the General Addition Rule in probability:P(mother or father) = P(mother) + P(father) — P(mother and father)P(mother) = P(mother or father) + P(mother and father) — P(father)P(mother) = 0.17 + 0.06–0.12P(mother) = 0.11" }, { "code": null, "e": 40206, "s": 40073, "text": "Since 70 is one standard deviation below the mean, take the area of the Gaussian distribution to the left of one standard deviation." }, { "code": null, "e": 40227, "s": 40206, "text": "= 2.3 + 13.6 = 15.9%" }, { "code": null, "e": 40314, "s": 40227, "text": "Given a confidence level of 95% and degrees of freedom equal to 8, the t-score = 2.306" }, { "code": null, "e": 40398, "s": 40314, "text": "Confidence interval = 1100 +/- 2.306*(30/3)Confidence interval = [1076.94, 1123.06]" }, { "code": null, "e": 40657, "s": 40398, "text": "Upper bound = mean + t-score*(standard deviation/sqrt(sample size))0 = -2 + 2.306*(s/3)2 = 2.306 * s / 3s = 2.601903Therefore the standard deviation would have to be at least approximately 2.60 for the upper bound of the 95% T confidence interval to touch 0." }, { "code": null, "e": 40748, "s": 40657, "text": "See here for full tutorial on finding the Confidence Interval for Two Independent Samples." }, { "code": null, "e": 40816, "s": 40748, "text": "Confidence Interval = mean +/- t-score * standard error (see above)" }, { "code": null, "e": 40854, "s": 40816, "text": "mean = new mean — old mean = 3–5 = -2" }, { "code": null, "e": 40920, "s": 40854, "text": "t-score = 2.101 given df=18 (20–2) and confidence interval of 95%" }, { "code": null, "e": 41010, "s": 40920, "text": "standard error = sqrt((0.62*9+0.682*9)/(10+10–2)) * sqrt(1/10+1/10)standard error = 0.352" }, { "code": null, "e": 41047, "s": 41010, "text": "confidence interval = [-2.75, -1.25]" }, { "code": null, "e": 41109, "s": 41047, "text": "Assuming we subtract in this order (New System — Old System):" }, { "code": null, "e": 41165, "s": 41109, "text": "confidence interval formula for two independent samples" }, { "code": null, "e": 41203, "s": 41165, "text": "mean = new mean — old mean = 4–6 = -2" }, { "code": null, "e": 41245, "s": 41203, "text": "z-score = 1.96 confidence interval of 95%" }, { "code": null, "e": 41418, "s": 41245, "text": "st. error = sqrt((0.52*99+22*99)/(100+100–2)) * sqrt(1/100+1/100)standard error = 0.205061lower bound = -2–1.96*0.205061 = -2.40192upper bound = -2+1.96*0.205061 = -1.59808" }, { "code": null, "e": 41461, "s": 41418, "text": "confidence interval = [-2.40192, -1.59808]" }, { "code": null, "e": 41713, "s": 41461, "text": "Write a SQL query to get the second highest salary from the Employee table. For example, given the Employee table below, the query should return 200 as the second highest salary. If there is no second highest salary, then the query should return null." }, { "code": null, "e": 41819, "s": 41713, "text": "+----+--------+| Id | Salary |+----+--------+| 1 | 100 || 2 | 200 || 3 | 300 |+----+--------+" }, { "code": null, "e": 41996, "s": 41819, "text": "IFNULL(expression, alt) : ifnull() returns the specified value if null, otherwise returns the expected value. We’ll use this to return null if there’s no second-highest salary." }, { "code": null, "e": 42169, "s": 41996, "text": "OFFSET : offset is used with the ORDER BY clause to disregard the top n rows that you specify. This will be useful as you’ll want to get the second row (2nd highest salary)" }, { "code": null, "e": 42350, "s": 42169, "text": "SELECT IFNULL( (SELECT DISTINCT Salary FROM Employee ORDER BY Salary DESC LIMIT 1 OFFSET 1 ), null) as SecondHighestSalaryFROM EmployeeLIMIT 1" }, { "code": null, "e": 42494, "s": 42350, "text": "This query says to choose the MAX salary that isn’t equal to the MAX salary, which is equivalent to saying to choose the second-highest salary!" }, { "code": null, "e": 42599, "s": 42494, "text": "SELECT MAX(salary) AS SecondHighestSalaryFROM EmployeeWHERE salary != (SELECT MAX(salary) FROM Employee)" }, { "code": null, "e": 42665, "s": 42599, "text": "Here are three SQL concepts to review before your next interview!" }, { "code": null, "e": 42737, "s": 42665, "text": "Write a SQL query to find all duplicate emails in a table named Person." }, { "code": null, "e": 42850, "s": 42737, "text": "+----+---------+| Id | Email |+----+---------+| 1 | [email protected] || 2 | [email protected] || 3 | [email protected] |+----+---------+" }, { "code": null, "e": 42994, "s": 42850, "text": "First, a subquery is created to show the count of the frequency of each email. Then the subquery is filtered WHERE the count is greater than 1." }, { "code": null, "e": 43116, "s": 42994, "text": "SELECT EmailFROM ( SELECT Email, count(Email) AS count FROM Person GROUP BY Email) as email_countWHERE count > 1" }, { "code": null, "e": 43231, "s": 43116, "text": "HAVING is a clause that essentially allows you to use a WHERE statement in conjunction with aggregates (GROUP BY)." }, { "code": null, "e": 43292, "s": 43231, "text": "SELECT EmailFROM PersonGROUP BY EmailHAVING count(Email) > 1" }, { "code": null, "e": 43426, "s": 43292, "text": "Given a Weather table, write a SQL query to find all dates' Ids with higher temperature compared to its previous (yesterday's) dates." }, { "code": null, "e": 43819, "s": 43426, "text": "+---------+------------------+------------------+| Id(INT) | RecordDate(DATE) | Temperature(INT) |+---------+------------------+------------------+| 1 | 2015-01-01 | 10 || 2 | 2015-01-02 | 25 || 3 | 2015-01-03 | 20 || 4 | 2015-01-04 | 30 |+---------+------------------+------------------+" }, { "code": null, "e": 43961, "s": 43819, "text": "DATEDIFF calculates the difference between two dates and is used to make sure we’re comparing today’s temperature to yesterday’s temperature." }, { "code": null, "e": 44095, "s": 43961, "text": "In plain English, the query is saying, Select the Ids where the temperature on a given day is greater than the temperature yesterday." }, { "code": null, "e": 44220, "s": 44095, "text": "SELECT DISTINCT a.IdFROM Weather a, Weather bWHERE a.Temperature > b.TemperatureAND DATEDIFF(a.Recorddate, b.Recorddate) = 1" }, { "code": null, "e": 44346, "s": 44220, "text": "The Employee table holds all employees. Every employee has an Id, a salary, and there is also a column for the department Id." }, { "code": null, "e": 44689, "s": 44346, "text": "+----+-------+--------+--------------+| Id | Name | Salary | DepartmentId |+----+-------+--------+--------------+| 1 | Joe | 70000 | 1 || 2 | Jim | 90000 | 1 || 3 | Henry | 80000 | 2 || 4 | Sam | 60000 | 2 || 5 | Max | 90000 | 1 |+----+-------+--------+--------------+" }, { "code": null, "e": 44748, "s": 44689, "text": "The Department table holds all departments of the company." }, { "code": null, "e": 44851, "s": 44748, "text": "+----+----------+| Id | Name |+----+----------+| 1 | IT || 2 | Sales |+----+----------+" }, { "code": null, "e": 45046, "s": 44851, "text": "Write a SQL query to find employees who have the highest salary in each of the departments. For the above tables, your SQL query should return the following rows (order of rows does not matter)." }, { "code": null, "e": 45285, "s": 45046, "text": "+------------+----------+--------+| Department | Employee | Salary |+------------+----------+--------+| IT | Max | 90000 || IT | Jim | 90000 || Sales | Henry | 80000 |+------------+----------+--------+" }, { "code": null, "e": 45466, "s": 45285, "text": "The IN clause allows you to use multiple OR clauses in a WHERE statement. For example WHERE country = ‘Canada’ or country = ‘USA’ is the same as WHERE country IN (‘Canada’, ’USA’)." }, { "code": null, "e": 45690, "s": 45466, "text": "In this case, we want to filter the Department table to only show the highest Salary per Department (i.e. DepartmentId). Then we can join the two tables WHERE the DepartmentId and Salary is in the filtered Department table." }, { "code": null, "e": 46000, "s": 45690, "text": "SELECT Department.name AS 'Department', Employee.name AS 'Employee', SalaryFROM EmployeeINNER JOIN Department ON Employee.DepartmentId = Department.IdWHERE (DepartmentId , Salary) IN ( SELECT DepartmentId, MAX(Salary) FROM Employee GROUP BY DepartmentId )" }, { "code": null, "e": 46215, "s": 46000, "text": "Mary is a teacher in a middle school and she has a table seat storing students' names and their corresponding seat ids. The column id is a continuous increment. Mary wants to change seats for the adjacent students." }, { "code": null, "e": 46272, "s": 46215, "text": "Can you write a SQL query to output the result for Mary?" }, { "code": null, "e": 46462, "s": 46272, "text": "+---------+---------+| id | student |+---------+---------+| 1 | Abbot || 2 | Doris || 3 | Emerson || 4 | Green || 5 | Jeames |+---------+---------+" }, { "code": null, "e": 46499, "s": 46462, "text": "For the sample input, the output is:" }, { "code": null, "e": 46689, "s": 46499, "text": "+---------+---------+| id | student |+---------+---------+| 1 | Doris || 2 | Abbot || 3 | Green || 4 | Emerson || 5 | Jeames |+---------+---------+" }, { "code": null, "e": 46776, "s": 46689, "text": "Note:If the number of students is odd, there is no need to change the last one’s seat." }, { "code": null, "e": 46844, "s": 46776, "text": "Think of a CASE WHEN THEN statement like an IF statement in coding." }, { "code": null, "e": 46977, "s": 46844, "text": "The first WHEN statement checks to see if there’s an odd number of rows, and if there is, ensure that the id number does not change." }, { "code": null, "e": 47047, "s": 46977, "text": "The second WHEN statement adds 1 to each id (eg. 1,3,5 becomes 2,4,6)" }, { "code": null, "e": 47128, "s": 47047, "text": "Similarly, the third WHEN statement subtracts 1 to each id (2,4,6 becomes 1,3,5)" }, { "code": null, "e": 47329, "s": 47128, "text": "SELECT CASE WHEN((SELECT MAX(id) FROM seat)%2 = 1) AND id = (SELECT MAX(id) FROM seat) THEN id WHEN id%2 = 1 THEN id + 1 ELSE id - 1 END AS id, studentFROM seatORDER BY id" }, { "code": null, "e": 47387, "s": 47329, "text": "Two weighings would be required (see part A and B above):" }, { "code": null, "e": 47773, "s": 47387, "text": "You would split the nine marbles into three groups of three and weigh two of the groups. If the scale balances (alternative 1), you know that the heavy marble is in the third group of marbles. Otherwise, you’ll take the group that is weighed more heavily (alternative 2).Then you would exercise the same step, but you’d have three groups of one marble instead of three groups of three." }, { "code": null, "e": 48045, "s": 47773, "text": "You would split the nine marbles into three groups of three and weigh two of the groups. If the scale balances (alternative 1), you know that the heavy marble is in the third group of marbles. Otherwise, you’ll take the group that is weighed more heavily (alternative 2)." }, { "code": null, "e": 48160, "s": 48045, "text": "Then you would exercise the same step, but you’d have three groups of one marble instead of three groups of three." }, { "code": null, "e": 48240, "s": 48160, "text": "I’m not 100% sure about the answer to this question but will give my best shot!" }, { "code": null, "e": 48380, "s": 48240, "text": "Let’s take the instance where there’s an increase in the prime membership fee — there are two parties involved, the buyers and the sellers." }, { "code": null, "e": 48811, "s": 48380, "text": "For the buyers, the impact of an increase in a prime membership fee ultimately depends on the price elasticity of demand for the buyers. If the price elasticity is high, then a given increase in price will result in a large drop in demand and vice versa. Buyers that continue to purchase a membership fee are likely Amazon’s most loyal and active customers — they are also likely to place a higher emphasis on products with prime." }, { "code": null, "e": 49125, "s": 48811, "text": "Sellers will take a hit, as there is now a higher cost of purchasing Amazon’s basket of products. That being said, some products will take a harder hit while others may not be impacted. It is likely that premium products that Amazon’s most loyal customers purchase would not be affected as much, like electronics." }, { "code": null, "e": 49227, "s": 49125, "text": "There are a number of possible variables that can cause such a discrepancy that I would check to see:" }, { "code": null, "e": 49603, "s": 49227, "text": "The demographics of iOS and Android users might differ significantly. For example, according to Hootsuite, 43% of females use Instagram as opposed to 31% of men. If the proportion of female users for iOS is significantly larger than for Android then this can explain the discrepancy (or at least a part of it). This can also be said for age, race, ethnicity, location, etc..." }, { "code": null, "e": 49859, "s": 49603, "text": "Behavioral factors can also have an impact on the discrepancy. If iOS users use their phones more heavily than Android users, it’s more likely that they’ll indulge in Instagram and other apps than someone who spent significantly less time on their phones." }, { "code": null, "e": 50081, "s": 49859, "text": "Another possible factor to consider is how Google Play and the App Store differ. For example, if Android users have significantly more apps (and social media apps) to choose from, that may cause greater dilution of users." }, { "code": null, "e": 50303, "s": 50081, "text": "Lastly, any differences in the user experience can deter Android users from using Instagram compared to iOS users. If the app is more buggy for Android users than iOS users, they’ll be less likely to be active on the app." }, { "code": null, "e": 50365, "s": 50303, "text": "Check out more Facebook data science interview questions here" }, { "code": null, "e": 50520, "s": 50365, "text": "Generally, you would want to probe the interviewer for more information but let’s assume that this is the only information that he/she is willing to give." }, { "code": null, "e": 51142, "s": 50520, "text": "Focusing on likes per user, there are two reasons why this would have gone up. The first reason is that the engagement of users has generally increased on average over time — this makes sense because as time passes, active users are more likely to be loyal users as using the platform becomes a habitual practice. The other reason why likes per user would increase is that the denominator, the total number of users, is decreasing. Assuming that users that stop using the platform are inactive users, aka users with little engagement and fewer likes than average, this would increase the average number of likes per user." }, { "code": null, "e": 51400, "s": 51142, "text": "The explanation above can also be applied to minutes spent on the platform. Active users are becoming more engaged over time, while users with little usage are becoming inactive. Overall the increase in engagement outweighs the users with little engagement." }, { "code": null, "e": 51718, "s": 51400, "text": "To take it a step further, it’s possible that the ‘users with little engagement’ are bots that Facebook has been able to detect. But over time, Facebook has been able to develop algorithms to spot and remove bots. If were a significant number of bots before, this can potentially be the root cause of this phenomenon." }, { "code": null, "e": 51881, "s": 51718, "text": "The total number of likes in a given year is a function of the total number of users and the average number of likes per user (which I’ll refer to as engagement)." }, { "code": null, "e": 52080, "s": 51881, "text": "Some potential reasons for an increase in the total number of users are the following: users acquired due to international expansion and younger age groups signing up for Facebook as they get older." }, { "code": null, "e": 52284, "s": 52080, "text": "Some potential reasons for an increase in engagement are an increase in usage of the app from users that are becoming more and more loyal, new features and functionality, and an improved user experience." }, { "code": null, "e": 52553, "s": 52284, "text": "The metrics that determine a product’s success are dependent on the business model and what the business is trying to achieve through the product. The book Lean analytics lays out a great framework that one can use to determine what metrics to use in a given scenario:" }, { "code": null, "e": 53238, "s": 52553, "text": "You can perform an A/B test by splitting the users into two groups: a control group with the normal number of ads and a test group with double the number of ads. Then you would choose the metric to define what a “good idea” is. For example, we can say that the null hypothesis is that doubling the number of ads will reduce the time spent on Facebook and the alternative hypothesis is that doubling the number of ads won’t have any impact on the time spent on Facebook. However, you can choose a different metric like the number of active users or the churn rate. Then you would conduct the test and determine the statistical significance of the test to reject or not reject the null." }, { "code": null, "e": 53460, "s": 53238, "text": "Lift: lift is a measure of the performance of a targeting model measured against a random choice targeting model; in other words, lift tells you how much better your model is at predicting things than if you had no model." }, { "code": null, "e": 53623, "s": 53460, "text": "KPI: stands for Key Performance Indicator, which is a measurable metric used to determine how well a company is achieving its business objectives. Eg. error rate." }, { "code": null, "e": 53729, "s": 53623, "text": "Robustness: generally robustness refers to a system’s ability to handle variability and remain effective." }, { "code": null, "e": 53799, "s": 53729, "text": "Model fitting: refers to how well a model fits a set of observations." }, { "code": null, "e": 54119, "s": 53799, "text": "Design of experiments: also known as DOE, it is the design of any task that aims to describe and explain the variation of information under conditions that are hypothesized to reflect the variable. [4] In essence, an experiment aims to predict an outcome based on a change in one or more inputs (independent variables)." }, { "code": null, "e": 54272, "s": 54119, "text": "80/20 rule: also known as the Pareto principle; states that 80% of the effects come from 20% of the causes. Eg. 80% of sales come from 20% of customers." }, { "code": null, "e": 54410, "s": 54272, "text": "Quality assurance: an activity or set of activities focused on maintaining a desired level of quality by minimizing mistakes and defects." }, { "code": null, "e": 54620, "s": 54410, "text": "Six sigma: a specific type of quality assurance methodology composed of a set of techniques and tools for process improvement. A six sigma process is one in which 99.99966% of all outcomes are free of defects." }, { "code": null, "e": 54704, "s": 54620, "text": "[1] Central Limit Theorem, Definition and Examples in Easy Steps, Statistics How To" }, { "code": null, "e": 54737, "s": 54704, "text": "[2] Power, Statistics, Wikipedia" }, { "code": null, "e": 54772, "s": 54737, "text": "[3] Anthropic principle, Wikipedia" }, { "code": null, "e": 54809, "s": 54772, "text": "[4] Design of experiments, Wikipedia" }, { "code": null, "e": 54844, "s": 54809, "text": "[5] Root cause analysis, Wikipedia" } ]
JavaFX | Polygon with examples - GeeksforGeeks
25 Oct, 2019 Polygon is a part of the JavaFX library. Polygon class creates a polygon with the given set of x and y coordinates. Polygon class inherits the shape class. Constructors of the class are: Polygon(): creates a empty polygon with no set of defined coordinates of points(vertices)Polygon(double points[])creates a polygon with a set of defined coordinates of points(vertices) Polygon(): creates a empty polygon with no set of defined coordinates of points(vertices) Polygon(double points[])creates a polygon with a set of defined coordinates of points(vertices) Commonly used methods: Below programs will illustrate the Polygon class of JavaFX: Program to create a polygon with a given set of vertices: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a given set of verticesimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating polygon"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create a polygon with a given set of vertices and specified fill: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The function set Fill() is used to set the fill of the polygon. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a// given set of vertices and specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating polygon"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // set fill for the polygon polygon.setFill(Color.BLUE); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polygon.htmlMy Personal Notes arrow_drop_upSave Program to create a polygon with a given set of vertices: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a given set of verticesimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating polygon"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output: // Java Program to create a polygon with a given set of verticesimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating polygon"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Program to create a polygon with a given set of vertices and specified fill: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The function set Fill() is used to set the fill of the polygon. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a// given set of vertices and specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating polygon"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // set fill for the polygon polygon.setFill(Color.BLUE); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polygon.htmlMy Personal Notes arrow_drop_upSave // Java Program to create a polygon with a// given set of vertices and specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle("creating polygon"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // set fill for the polygon polygon.setFill(Color.BLUE); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }} Output: Note: The above programs might not run in an online IDE please use an offline IDE. Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polygon.html ManasChhabra2 JavaFX Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Initialize an ArrayList in Java Interfaces in Java ArrayList in Java Multidimensional Arrays in Java Stack Class in Java Singleton Class in Java LinkedList in Java Collections in Java Overriding in Java
[ { "code": null, "e": 24073, "s": 24045, "text": "\n25 Oct, 2019" }, { "code": null, "e": 24229, "s": 24073, "text": "Polygon is a part of the JavaFX library. Polygon class creates a polygon with the given set of x and y coordinates. Polygon class inherits the shape class." }, { "code": null, "e": 24260, "s": 24229, "text": "Constructors of the class are:" }, { "code": null, "e": 24445, "s": 24260, "text": "Polygon(): creates a empty polygon with no set of defined coordinates of points(vertices)Polygon(double points[])creates a polygon with a set of defined coordinates of points(vertices)" }, { "code": null, "e": 24535, "s": 24445, "text": "Polygon(): creates a empty polygon with no set of defined coordinates of points(vertices)" }, { "code": null, "e": 24631, "s": 24535, "text": "Polygon(double points[])creates a polygon with a set of defined coordinates of points(vertices)" }, { "code": null, "e": 24654, "s": 24631, "text": "Commonly used methods:" }, { "code": null, "e": 24714, "s": 24654, "text": "Below programs will illustrate the Polygon class of JavaFX:" }, { "code": null, "e": 28353, "s": 24714, "text": "Program to create a polygon with a given set of vertices: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a given set of verticesimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating polygon\"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Program to create a polygon with a given set of vertices and specified fill: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The function set Fill() is used to set the fill of the polygon. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a// given set of vertices and specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating polygon\"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // set fill for the polygon polygon.setFill(Color.BLUE); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polygon.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 29982, "s": 28353, "text": "Program to create a polygon with a given set of vertices: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a given set of verticesimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating polygon\"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:" }, { "code": "// Java Program to create a polygon with a given set of verticesimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_0 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating polygon\"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 31103, "s": 29982, "text": null }, { "code": null, "e": 31111, "s": 31103, "text": "Output:" }, { "code": null, "e": 33122, "s": 31111, "text": "Program to create a polygon with a given set of vertices and specified fill: This program creates a Polygon indicated by the name polygon. The coordinates for the vertices of the polygon are passed as arguments. The function set Fill() is used to set the fill of the polygon. The Polygon will be created inside a scene, which in turn will be hosted inside a stage. The function setTitle() is used to provide title to the stage. Then a Group is created, and the polygon is attached. The group is attached to the scene. Finally, the show() method is called to display the final results.// Java Program to create a polygon with a// given set of vertices and specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating polygon\"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // set fill for the polygon polygon.setFill(Color.BLUE); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}Output:Note: The above programs might not run in an online IDE please use an offline IDE.Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polygon.htmlMy Personal Notes\narrow_drop_upSave" }, { "code": "// Java Program to create a polygon with a// given set of vertices and specified fillimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.Button;import javafx.scene.layout.*;import javafx.scene.paint.Color;import javafx.scene.shape.Polygon;import javafx.scene.control.*;import javafx.stage.Stage; import javafx.scene.Group;public class polygon_1 extends Application { // launch the application public void start(Stage stage) { // set title for the stage stage.setTitle(\"creating polygon\"); // coordinates of the points of polygon double points[] = { 10.0d, 140.0d, 30.0d, 110.0d, 40.0d, 50.0d, 50.0d, 40.0d, 110.0d, 30.0d, 140.0d, 10.0d }; // create a polygon Polygon polygon = new Polygon(points); // set fill for the polygon polygon.setFill(Color.BLUE); // create a Group Group group = new Group(polygon); // create a scene Scene scene = new Scene(group, 500, 300); // set the scene stage.setScene(scene); stage.show(); } public static void main(String args[]) { // launch the application launch(args); }}", "e": 34339, "s": 33122, "text": null }, { "code": null, "e": 34347, "s": 34339, "text": "Output:" }, { "code": null, "e": 34430, "s": 34347, "text": "Note: The above programs might not run in an online IDE please use an offline IDE." }, { "code": null, "e": 34517, "s": 34430, "text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/shape/Polygon.html" }, { "code": null, "e": 34531, "s": 34517, "text": "ManasChhabra2" }, { "code": null, "e": 34538, "s": 34531, "text": "JavaFX" }, { "code": null, "e": 34543, "s": 34538, "text": "Java" }, { "code": null, "e": 34548, "s": 34543, "text": "Java" }, { "code": null, "e": 34646, "s": 34548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34655, "s": 34646, "text": "Comments" }, { "code": null, "e": 34668, "s": 34655, "text": "Old Comments" }, { "code": null, "e": 34698, "s": 34668, "text": "HashMap in Java with Examples" }, { "code": null, "e": 34730, "s": 34698, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 34749, "s": 34730, "text": "Interfaces in Java" }, { "code": null, "e": 34767, "s": 34749, "text": "ArrayList in Java" }, { "code": null, "e": 34799, "s": 34767, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 34819, "s": 34799, "text": "Stack Class in Java" }, { "code": null, "e": 34843, "s": 34819, "text": "Singleton Class in Java" }, { "code": null, "e": 34862, "s": 34843, "text": "LinkedList in Java" }, { "code": null, "e": 34882, "s": 34862, "text": "Collections in Java" } ]
Primality Test | Set 4 (Solovay-Strassen) - GeeksforGeeks
19 May, 2021 We have already been introduced to primality testing in the previous articles in this series. Primality Test | Set 1 (Introduction and School Method) Primality Test | Set 2 (Fermat Method) Primality Test | Set 3 (Miller–Rabin) The Solovay–Strassen primality test is a probabilistic test to determine if a number is composite or probably prime. Before diving into the code we will need to understand some key terms and concepts to be able to code this algorithm. Background:Legendre Symbol: This symbol is defined as a pair of integers a and p such that p is prime. It is denoted by (a/p) and calculated as: = 0 if a%p = 0 (a/p) = 1 if there exists an integer k such that k2 = a(mod p) = -1 otherwise. Euler proved that: (a/p) = a((p-1)/2)%p Condition (i) Jacobian Symbol: This symbol is a generalization of the Legendre Symbol, where p is replaced by n where n is n = p1k1 * .. * pnkn , then the Jacobian symbol is defined as: (a/n) = ((a/p1)k1) * ((a/p2)k2) *.....* ((a/pn)kn) If n is taken as a prime number, then the Jacobian is equal to the Legendre symbol. These symbols have certain properties – 1) (a/n) = 0 if gcd(a,n) != 1, Hence (0/n) = 0. This is because if gcd(a,n) != 1, then there must be some prime pi such that pi divides both a and n. In that case (a/pi) = 0 [by definition of the Legendre Symbol]. 2) (ab/n) = (a/n) * (b/n). It can be easily derived from the fact (ab/p) = (a/p)(b/p) (here (a/p) is the Legendry Symbol). 3) If a is even, then (a/n) = (2/n)*((a/2)/n). It can be shown that: = 1 if n = 1 ( mod 8 ) or n = 7 ( mod 8 ) (2/n) = -1 if n = 3 ( mod 8 ) or n = 5 ( mod 8 ) = 0 otherwise 4) (a/n) = (n/a) * (-1)((a - 1)(n - 1) / 4) if a and n are both odd. The Algorithm: We select a number n to test for its primality and a random number a which lies in the range of [2, n-1] and compute its Jacobian (a/n), if n is a prime number, then the Jacobian will be equal to the Legendre and it will satisfy the condition (i) given by Euler. If it does not satisfy the given condition, then n is composite and the program will stop. Just like every other Probabilistic Primality Test, its accuracy is also directly proportional to the number of iterations. So we ran the test for several iterations to get more accurate results. Note: We are not interested in calculating the Jacobian of even numbers as we already know that they are not prime except 2. Pseudocode: Algorithm for Jacobian: Step 1 //base cases omitted Step 2 if a>n then Step 3 return (a mod n)/n Step 4 else Step 5 return (-1)((a - 1)/2)((n - 1)/2)(a/n) Step 6 endif Algorithm for Solovay-Strassen: Step 1 Pick a random element a < n Step 2 if gcd(a, n) > 1 then Step 3 return COMPOSITE Step 4 end if Step 5 Compute a(n - 1)/2 using repeated squaring and (a/n) using Jacobian algorithm. Step 6 if (a/n) not equal to a(n - 1)/2 then Step 7 return composite Step 8 else Step 9 return prime Step 10 endif Implementation: C++ Java Python3 C# PHP Javascript // C++ program to implement Solovay-Strassen// Primality Test#include <bits/stdc++.h>using namespace std; // modulo function to perform binary exponentiationlong long modulo(long long base, long long exponent, long long mod){ long long x = 1; long long y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod;} // To calculate Jacobian symbol of a given numberint calculateJacobian(long long a, long long n){ if (!a) return 0;// (0/n) = 0 int ans = 1; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans;// (1/n) = 1 while (a) { if (a < 0) { a = -a;// (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans;// (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a = a / 2; if (n % 8 == 3 || n % 8 == 5) ans = -ans; } swap(a, n); if (a % 4 == 3 && n % 4 == 3) ans = -ans; a = a % n; if (a > n / 2) a = a - n; } if (n == 1) return ans; return 0;} // To perform the Solovay-Strassen Primality Testbool solovoyStrassen(long long p, int iterations){ if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; for (int i = 0; i < iterations; i++) { // Generate a random number a long long a = rand() % (p - 1) + 1; long long jacobian = (p + calculateJacobian(a, p)) % p; long long mod = modulo(a, (p - 1) / 2, p); if (!jacobian || mod != jacobian) return false; } return true;} // Driver Codeint main(){ int iterations = 50; long long num1 = 15; long long num2 = 13; if (solovoyStrassen(num1, iterations)) printf("%d is prime\n",num1); else printf("%d is composite\n",num1); if (solovoyStrassen(num2, iterations)) printf("%d is prime\n",num2); else printf("%d is composite\n",num2); return 0;} // Java program to implement Solovay-Strassen// Primality Testimport java.util.Scanner;import java.util.Random; class GFG{ // Modulo function to perform// binary exponentiationstatic long modulo(long base, long exponent, long mod){ long x = 1; long y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod;} // To calculate Jacobian symbol of// a given numberstatic long calculateJacobian(long a, long n){ if (n <= 0 || n % 2 == 0) return 0; long ans = 1L; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans; // (1/n) = 1 while (a != 0) { if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a /= 2; if (n % 8 == 3 || n % 8 == 5) ans = -ans; } long temp = a; a = n; n = temp; if (a % 4 == 3 && n % 4 == 3) ans = -ans; a %= n; if (a > n / 2) a = a - n; } if (n == 1) return ans; return 0;} // To perform the Solovay-Strassen Primality Teststatic boolean solovoyStrassen(long p, int iteration){ if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; // Create Object for Random Class Random rand = new Random(); for(int i = 0; i < iteration; i++) { // Generate a random number r long r = Math.abs(rand.nextLong()); long a = r % (p - 1) + 1; long jacobian = (p + calculateJacobian(a, p)) % p; long mod = modulo(a, (p - 1) / 2, p); if (jacobian == 0 || mod != jacobian) return false; } return true; } // Driver codepublic static void main (String[] args){ int iter = 50; long num1 = 15; long num2 = 13; if (solovoyStrassen(num1, iter)) System.out.println(num1 + " is prime"); else System.out.println(num1 + " is composite"); if (solovoyStrassen(num2,iter)) System.out.println(num2 + " is prime"); else System.out.println(num2 + " is composite");}} // This code is contributed by Srishtik Dutta # Python3 program to implement Solovay-Strassen# Primality Testimport random # modulo function to perform binary# exponentiationdef modulo(base, exponent, mod): x = 1; y = base; while (exponent > 0): if (exponent % 2 == 1): x = (x * y) % mod; y = (y * y) % mod; exponent = exponent // 2; return x % mod; # To calculate Jacobian symbol of a# given numberdef calculateJacobian(a, n): if (a == 0): return 0;# (0/n) = 0 ans = 1; if (a < 0): # (a/n) = (-a/n)*(-1/n) a = -a; if (n % 4 == 3): # (-1/n) = -1 if n = 3 (mod 4) ans = -ans; if (a == 1): return ans; # (1/n) = 1 while (a): if (a < 0): # (a/n) = (-a/n)*(-1/n) a = -a; if (n % 4 == 3): # (-1/n) = -1 if n = 3 (mod 4) ans = -ans; while (a % 2 == 0): a = a // 2; if (n % 8 == 3 or n % 8 == 5): ans = -ans; # swap a, n = n, a; if (a % 4 == 3 and n % 4 == 3): ans = -ans; a = a % n; if (a > n // 2): a = a - n; if (n == 1): return ans; return 0; # To perform the Solovay- Strassen# Primality Testdef solovoyStrassen(p, iterations): if (p < 2): return False; if (p != 2 and p % 2 == 0): return False; for i in range(iterations): # Generate a random number a a = random.randrange(p - 1) + 1; jacobian = (p + calculateJacobian(a, p)) % p; mod = modulo(a, (p - 1) / 2, p); if (jacobian == 0 or mod != jacobian): return False; return True; # Driver Codeiterations = 50;num1 = 15;num2 = 13; if (solovoyStrassen(num1, iterations)): print(num1, "is prime ");else: print(num1, "is composite"); if (solovoyStrassen(num2, iterations)): print(num2, "is prime");else: print(num2, "is composite"); # This code is contributed by mits /// C# program to implement Solovay-Strassen// Primality Testusing System;using System.Collections.Generic; class GFG { // Modulo function to perform // binary exponentiation static long modulo(long Base, long exponent, long mod) { long x = 1; long y = Base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod; } // To calculate Jacobian symbol of // a given number static long calculateJacobian(long a, long n) { if (n <= 0 || n % 2 == 0) return 0; long ans = 1L; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans; // (1/n) = 1 while (a != 0) { if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a /= 2; if (n % 8 == 3 || n % 8 == 5) ans = -ans; } long temp = a; a = n; n = temp; if (a % 4 == 3 && n % 4 == 3) ans = -ans; a %= n; if (a > n / 2) a = a - n; } if (n == 1) return ans; return 0; } // To perform the Solovay-Strassen Primality Test static bool solovoyStrassen(long p, int iteration) { if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; // Create Object for Random Class Random rand = new Random(); for(int i = 0; i < iteration; i++) { // Generate a random number r long r = Math.Abs(rand.Next()); long a = r % (p - 1) + 1; long jacobian = (p + calculateJacobian(a, p)) % p; long mod = modulo(a, (p - 1) / 2, p); if (jacobian == 0 || mod != jacobian) return false; } return true; } // Driver code static void Main() { int iter = 50; long num1 = 15; long num2 = 13; if (solovoyStrassen(num1, iter)) Console.WriteLine(num1 + " is prime"); else Console.WriteLine(num1 + " is composite"); if (solovoyStrassen(num2,iter)) Console.WriteLine(num2 + " is prime"); else Console.WriteLine(num2 + " is composite"); }} // This code is contributed by divyeshrabadiya07 <?php// PHP program to implement// Solovay-Strassen Primality Test // modulo function to perform// binary exponentiationfunction modulo($base, $exponent, $mod){ $x = 1; $y = $base; while ($exponent > 0) { if ($exponent % 2 == 1) $x = ($x * $y) % $mod; $y = ($y * $y) % $mod; $exponent = $exponent / 2; } return $x % $mod;} // To calculate Jacobian// symbol of a given numberfunction calculateJacobian($a, $n){ if (!$a) return 0;// (0/n) = 0 $ans = 1; if ($a < 0) { // (a/n) = (-a/n)*(-1/n) $a = -$a; if ($n % 4 == 3) // (-1/n) = -1 if n = 3 (mod 4) $ans = -$ans; } if ($a == 1) return $ans;// (1/n) = 1 while ($a) { if ($a < 0) { // (a/n) = (-a/n)*(-1/n) $a = -$a; if ($n % 4 == 3) // (-1/n) = -1 if n = 3 (mod 4) $ans = -$ans; } while ($a % 2 == 0) { $a = $a / 2; if ($n % 8 == 3 || $n % 8 == 5) $ans = -$ans; } //swap list($a, $n) = array($n, $a); if ($a % 4 == 3 && $n % 4 == 3) $ans = -$ans; $a = $a % $n; if ($a > $n / 2) $a = $a - $n; } if ($n == 1) return $ans; return 0;} // To perform the Solovay-// Strassen Primality Testfunction solovoyStrassen($p, $iterations){ if ($p < 2) return false; if ($p != 2 && $p % 2 == 0) return false; for ($i = 0; $i < $iterations; $i++) { // Generate a random number a $a = rand() % ($p - 1) + 1; $jacobian = ($p + calculateJacobian($a, $p)) % $p; $mod = modulo($a, ($p - 1) / 2, $p); if (!$jacobian || $mod != $jacobian) return false; } return true;} // Driver Code$iterations = 50;$num1 = 15;$num2 = 13; if (solovoyStrassen($num1, $iterations)) echo $num1," is prime ","\n";else echo $num1," is composite\n"; if (solovoyStrassen($num2, $iterations)) echo $num2," is prime\n";else echo $num2," is composite\n"; // This code is contributed by ajit?> <script> // Javascript program to implement Solovay-Strassen// Primality Test // Modulo function to perform// binary exponentiationfunction modulo( base, exponent,mod){ let x = 1; let y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = Math.floor(exponent / 2); } return x % mod;} // To calculate Jacobian symbol of// a given numberfunction calculateJacobian( a, n){ if (n <= 0 || n % 2 == 0) return 0; let ans = 1; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans; // (1/n) = 1 while (a != 0) { if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a = Math.floor(a/2); if (n % 8 == 3 || n % 8 == 5) ans = -ans; } let temp= a; a = n; n = temp; if (a % 4 == 3 && n % 4 == 3) ans = -ans; a %= n; if (a > Math.floor(n / 2)) a = a - n; } if (n == 1) return ans; return 0;} // To perform the Solovay-Strassen Primality Testfunction solovoyStrassen( p, iteration){ if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; for(let i = 0; i < iteration; i++) { // Generate a random number r let r = Math.floor(Math.random()* (Number.MAX_VALUE, 2) ); let a = r % (p - 1) + 1; let jacobian = (p + calculateJacobian(a, p)) % p; let mod = modulo(a, Math.floor((p - 1) / 2), p); if (jacobian == 0 || mod != jacobian) return false; } return true; } // Driver Code let iter = 50;let num1 = 15;let num2 = 13; if (solovoyStrassen(num1, iter)) document.write(num1 + " is prime"+ "</br>");else document.write(num1 + " is composite" + "</br>"); if (solovoyStrassen(num2,iter)) document.write(num2 + " is prime"+ "</br>");else document.write(num2 + " is composite"+ "</br>"); </script> Output : 15 is composite 13 is prime Running Time: Using fast algorithms for modular exponentiation, the running time of this algorithm is O(k·n), where k is the number of different values we test. Accuracy: It is possible for the algorithm to return an incorrect answer. If the input n is indeed prime, then the output will always probably be correctly prime. However, if the input n is composite, then it is possible for the output to probably be incorrect prime. The number n is then called an Euler-Jacobi pseudoprime. This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t Mithun Kumar Srishtik Dutta divyeshrabadiya07 jana_sayantan number-theory Prime Number Mathematical number-theory Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Program to find sum of elements in a given array Operators in C / C++ Program for factorial of a number Program for Decimal to Binary Conversion Algorithm to solve Rubik's Cube Print all possible combinations of r elements in a given array of size n The Knight's tour problem | Backtracking-1 Minimum number of jumps to reach end
[ { "code": null, "e": 24692, "s": 24664, "text": "\n19 May, 2021" }, { "code": null, "e": 24787, "s": 24692, "text": "We have already been introduced to primality testing in the previous articles in this series. " }, { "code": null, "e": 24843, "s": 24787, "text": "Primality Test | Set 1 (Introduction and School Method)" }, { "code": null, "e": 24882, "s": 24843, "text": "Primality Test | Set 2 (Fermat Method)" }, { "code": null, "e": 24920, "s": 24882, "text": "Primality Test | Set 3 (Miller–Rabin)" }, { "code": null, "e": 25155, "s": 24920, "text": "The Solovay–Strassen primality test is a probabilistic test to determine if a number is composite or probably prime. Before diving into the code we will need to understand some key terms and concepts to be able to code this algorithm." }, { "code": null, "e": 25301, "s": 25155, "text": "Background:Legendre Symbol: This symbol is defined as a pair of integers a and p such that p is prime. It is denoted by (a/p) and calculated as: " }, { "code": null, "e": 25415, "s": 25301, "text": " = 0 if a%p = 0\n(a/p) = 1 if there exists an integer k such that k2 = a(mod p)\n = -1 otherwise." }, { "code": null, "e": 25435, "s": 25415, "text": "Euler proved that: " }, { "code": null, "e": 25471, "s": 25435, "text": " (a/p) = a((p-1)/2)%p Condition (i)" }, { "code": null, "e": 25580, "s": 25471, "text": "Jacobian Symbol: This symbol is a generalization of the Legendre Symbol, where p is replaced by n where n is" }, { "code": null, "e": 25601, "s": 25580, "text": "n = p1k1 * .. * pnkn" }, { "code": null, "e": 25644, "s": 25601, "text": ", then the Jacobian symbol is defined as: " }, { "code": null, "e": 25695, "s": 25644, "text": "(a/n) = ((a/p1)k1) * ((a/p2)k2) *.....* ((a/pn)kn)" }, { "code": null, "e": 26226, "s": 25695, "text": "If n is taken as a prime number, then the Jacobian is equal to the Legendre symbol. These symbols have certain properties – 1) (a/n) = 0 if gcd(a,n) != 1, Hence (0/n) = 0. This is because if gcd(a,n) != 1, then there must be some prime pi such that pi divides both a and n. In that case (a/pi) = 0 [by definition of the Legendre Symbol]. 2) (ab/n) = (a/n) * (b/n). It can be easily derived from the fact (ab/p) = (a/p)(b/p) (here (a/p) is the Legendry Symbol). 3) If a is even, then (a/n) = (2/n)*((a/2)/n). It can be shown that: " }, { "code": null, "e": 26343, "s": 26226, "text": " = 1 if n = 1 ( mod 8 ) or n = 7 ( mod 8 )\n(2/n) = -1 if n = 3 ( mod 8 ) or n = 5 ( mod 8 )\n = 0 otherwise" }, { "code": null, "e": 26413, "s": 26343, "text": "4) (a/n) = (n/a) * (-1)((a - 1)(n - 1) / 4) if a and n are both odd." }, { "code": null, "e": 26978, "s": 26413, "text": "The Algorithm: We select a number n to test for its primality and a random number a which lies in the range of [2, n-1] and compute its Jacobian (a/n), if n is a prime number, then the Jacobian will be equal to the Legendre and it will satisfy the condition (i) given by Euler. If it does not satisfy the given condition, then n is composite and the program will stop. Just like every other Probabilistic Primality Test, its accuracy is also directly proportional to the number of iterations. So we ran the test for several iterations to get more accurate results." }, { "code": null, "e": 27103, "s": 26978, "text": "Note: We are not interested in calculating the Jacobian of even numbers as we already know that they are not prime except 2." }, { "code": null, "e": 27116, "s": 27103, "text": "Pseudocode: " }, { "code": null, "e": 27316, "s": 27116, "text": "Algorithm for Jacobian:\nStep 1 //base cases omitted\nStep 2 if a>n then\nStep 3 return (a mod n)/n\nStep 4 else\n\nStep 5 return (-1)((a - 1)/2)((n - 1)/2)(a/n)\nStep 6 endif" }, { "code": null, "e": 27702, "s": 27316, "text": "Algorithm for Solovay-Strassen:\nStep 1 Pick a random element a < n\nStep 2 if gcd(a, n) > 1 then\nStep 3 return COMPOSITE\nStep 4 end if\nStep 5 Compute a(n - 1)/2 using repeated squaring\n and (a/n) using Jacobian algorithm.\nStep 6 if (a/n) not equal to a(n - 1)/2 then\nStep 7 return composite\nStep 8 else\nStep 9 return prime\nStep 10 endif" }, { "code": null, "e": 27718, "s": 27702, "text": "Implementation:" }, { "code": null, "e": 27722, "s": 27718, "text": "C++" }, { "code": null, "e": 27727, "s": 27722, "text": "Java" }, { "code": null, "e": 27735, "s": 27727, "text": "Python3" }, { "code": null, "e": 27738, "s": 27735, "text": "C#" }, { "code": null, "e": 27742, "s": 27738, "text": "PHP" }, { "code": null, "e": 27753, "s": 27742, "text": "Javascript" }, { "code": "// C++ program to implement Solovay-Strassen// Primality Test#include <bits/stdc++.h>using namespace std; // modulo function to perform binary exponentiationlong long modulo(long long base, long long exponent, long long mod){ long long x = 1; long long y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod;} // To calculate Jacobian symbol of a given numberint calculateJacobian(long long a, long long n){ if (!a) return 0;// (0/n) = 0 int ans = 1; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans;// (1/n) = 1 while (a) { if (a < 0) { a = -a;// (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans;// (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a = a / 2; if (n % 8 == 3 || n % 8 == 5) ans = -ans; } swap(a, n); if (a % 4 == 3 && n % 4 == 3) ans = -ans; a = a % n; if (a > n / 2) a = a - n; } if (n == 1) return ans; return 0;} // To perform the Solovay-Strassen Primality Testbool solovoyStrassen(long long p, int iterations){ if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; for (int i = 0; i < iterations; i++) { // Generate a random number a long long a = rand() % (p - 1) + 1; long long jacobian = (p + calculateJacobian(a, p)) % p; long long mod = modulo(a, (p - 1) / 2, p); if (!jacobian || mod != jacobian) return false; } return true;} // Driver Codeint main(){ int iterations = 50; long long num1 = 15; long long num2 = 13; if (solovoyStrassen(num1, iterations)) printf(\"%d is prime\\n\",num1); else printf(\"%d is composite\\n\",num1); if (solovoyStrassen(num2, iterations)) printf(\"%d is prime\\n\",num2); else printf(\"%d is composite\\n\",num2); return 0;}", "e": 29980, "s": 27753, "text": null }, { "code": "// Java program to implement Solovay-Strassen// Primality Testimport java.util.Scanner;import java.util.Random; class GFG{ // Modulo function to perform// binary exponentiationstatic long modulo(long base, long exponent, long mod){ long x = 1; long y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod;} // To calculate Jacobian symbol of// a given numberstatic long calculateJacobian(long a, long n){ if (n <= 0 || n % 2 == 0) return 0; long ans = 1L; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans; // (1/n) = 1 while (a != 0) { if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a /= 2; if (n % 8 == 3 || n % 8 == 5) ans = -ans; } long temp = a; a = n; n = temp; if (a % 4 == 3 && n % 4 == 3) ans = -ans; a %= n; if (a > n / 2) a = a - n; } if (n == 1) return ans; return 0;} // To perform the Solovay-Strassen Primality Teststatic boolean solovoyStrassen(long p, int iteration){ if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; // Create Object for Random Class Random rand = new Random(); for(int i = 0; i < iteration; i++) { // Generate a random number r long r = Math.abs(rand.nextLong()); long a = r % (p - 1) + 1; long jacobian = (p + calculateJacobian(a, p)) % p; long mod = modulo(a, (p - 1) / 2, p); if (jacobian == 0 || mod != jacobian) return false; } return true; } // Driver codepublic static void main (String[] args){ int iter = 50; long num1 = 15; long num2 = 13; if (solovoyStrassen(num1, iter)) System.out.println(num1 + \" is prime\"); else System.out.println(num1 + \" is composite\"); if (solovoyStrassen(num2,iter)) System.out.println(num2 + \" is prime\"); else System.out.println(num2 + \" is composite\");}} // This code is contributed by Srishtik Dutta", "e": 32578, "s": 29980, "text": null }, { "code": "# Python3 program to implement Solovay-Strassen# Primality Testimport random # modulo function to perform binary# exponentiationdef modulo(base, exponent, mod): x = 1; y = base; while (exponent > 0): if (exponent % 2 == 1): x = (x * y) % mod; y = (y * y) % mod; exponent = exponent // 2; return x % mod; # To calculate Jacobian symbol of a# given numberdef calculateJacobian(a, n): if (a == 0): return 0;# (0/n) = 0 ans = 1; if (a < 0): # (a/n) = (-a/n)*(-1/n) a = -a; if (n % 4 == 3): # (-1/n) = -1 if n = 3 (mod 4) ans = -ans; if (a == 1): return ans; # (1/n) = 1 while (a): if (a < 0): # (a/n) = (-a/n)*(-1/n) a = -a; if (n % 4 == 3): # (-1/n) = -1 if n = 3 (mod 4) ans = -ans; while (a % 2 == 0): a = a // 2; if (n % 8 == 3 or n % 8 == 5): ans = -ans; # swap a, n = n, a; if (a % 4 == 3 and n % 4 == 3): ans = -ans; a = a % n; if (a > n // 2): a = a - n; if (n == 1): return ans; return 0; # To perform the Solovay- Strassen# Primality Testdef solovoyStrassen(p, iterations): if (p < 2): return False; if (p != 2 and p % 2 == 0): return False; for i in range(iterations): # Generate a random number a a = random.randrange(p - 1) + 1; jacobian = (p + calculateJacobian(a, p)) % p; mod = modulo(a, (p - 1) / 2, p); if (jacobian == 0 or mod != jacobian): return False; return True; # Driver Codeiterations = 50;num1 = 15;num2 = 13; if (solovoyStrassen(num1, iterations)): print(num1, \"is prime \");else: print(num1, \"is composite\"); if (solovoyStrassen(num2, iterations)): print(num2, \"is prime\");else: print(num2, \"is composite\"); # This code is contributed by mits", "e": 34602, "s": 32578, "text": null }, { "code": "/// C# program to implement Solovay-Strassen// Primality Testusing System;using System.Collections.Generic; class GFG { // Modulo function to perform // binary exponentiation static long modulo(long Base, long exponent, long mod) { long x = 1; long y = Base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = exponent / 2; } return x % mod; } // To calculate Jacobian symbol of // a given number static long calculateJacobian(long a, long n) { if (n <= 0 || n % 2 == 0) return 0; long ans = 1L; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans; // (1/n) = 1 while (a != 0) { if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a /= 2; if (n % 8 == 3 || n % 8 == 5) ans = -ans; } long temp = a; a = n; n = temp; if (a % 4 == 3 && n % 4 == 3) ans = -ans; a %= n; if (a > n / 2) a = a - n; } if (n == 1) return ans; return 0; } // To perform the Solovay-Strassen Primality Test static bool solovoyStrassen(long p, int iteration) { if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; // Create Object for Random Class Random rand = new Random(); for(int i = 0; i < iteration; i++) { // Generate a random number r long r = Math.Abs(rand.Next()); long a = r % (p - 1) + 1; long jacobian = (p + calculateJacobian(a, p)) % p; long mod = modulo(a, (p - 1) / 2, p); if (jacobian == 0 || mod != jacobian) return false; } return true; } // Driver code static void Main() { int iter = 50; long num1 = 15; long num2 = 13; if (solovoyStrassen(num1, iter)) Console.WriteLine(num1 + \" is prime\"); else Console.WriteLine(num1 + \" is composite\"); if (solovoyStrassen(num2,iter)) Console.WriteLine(num2 + \" is prime\"); else Console.WriteLine(num2 + \" is composite\"); }} // This code is contributed by divyeshrabadiya07", "e": 37569, "s": 34602, "text": null }, { "code": "<?php// PHP program to implement// Solovay-Strassen Primality Test // modulo function to perform// binary exponentiationfunction modulo($base, $exponent, $mod){ $x = 1; $y = $base; while ($exponent > 0) { if ($exponent % 2 == 1) $x = ($x * $y) % $mod; $y = ($y * $y) % $mod; $exponent = $exponent / 2; } return $x % $mod;} // To calculate Jacobian// symbol of a given numberfunction calculateJacobian($a, $n){ if (!$a) return 0;// (0/n) = 0 $ans = 1; if ($a < 0) { // (a/n) = (-a/n)*(-1/n) $a = -$a; if ($n % 4 == 3) // (-1/n) = -1 if n = 3 (mod 4) $ans = -$ans; } if ($a == 1) return $ans;// (1/n) = 1 while ($a) { if ($a < 0) { // (a/n) = (-a/n)*(-1/n) $a = -$a; if ($n % 4 == 3) // (-1/n) = -1 if n = 3 (mod 4) $ans = -$ans; } while ($a % 2 == 0) { $a = $a / 2; if ($n % 8 == 3 || $n % 8 == 5) $ans = -$ans; } //swap list($a, $n) = array($n, $a); if ($a % 4 == 3 && $n % 4 == 3) $ans = -$ans; $a = $a % $n; if ($a > $n / 2) $a = $a - $n; } if ($n == 1) return $ans; return 0;} // To perform the Solovay-// Strassen Primality Testfunction solovoyStrassen($p, $iterations){ if ($p < 2) return false; if ($p != 2 && $p % 2 == 0) return false; for ($i = 0; $i < $iterations; $i++) { // Generate a random number a $a = rand() % ($p - 1) + 1; $jacobian = ($p + calculateJacobian($a, $p)) % $p; $mod = modulo($a, ($p - 1) / 2, $p); if (!$jacobian || $mod != $jacobian) return false; } return true;} // Driver Code$iterations = 50;$num1 = 15;$num2 = 13; if (solovoyStrassen($num1, $iterations)) echo $num1,\" is prime \",\"\\n\";else echo $num1,\" is composite\\n\"; if (solovoyStrassen($num2, $iterations)) echo $num2,\" is prime\\n\";else echo $num2,\" is composite\\n\"; // This code is contributed by ajit?>", "e": 39796, "s": 37569, "text": null }, { "code": "<script> // Javascript program to implement Solovay-Strassen// Primality Test // Modulo function to perform// binary exponentiationfunction modulo( base, exponent,mod){ let x = 1; let y = base; while (exponent > 0) { if (exponent % 2 == 1) x = (x * y) % mod; y = (y * y) % mod; exponent = Math.floor(exponent / 2); } return x % mod;} // To calculate Jacobian symbol of// a given numberfunction calculateJacobian( a, n){ if (n <= 0 || n % 2 == 0) return 0; let ans = 1; if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } if (a == 1) return ans; // (1/n) = 1 while (a != 0) { if (a < 0) { a = -a; // (a/n) = (-a/n)*(-1/n) if (n % 4 == 3) ans = -ans; // (-1/n) = -1 if n = 3 (mod 4) } while (a % 2 == 0) { a = Math.floor(a/2); if (n % 8 == 3 || n % 8 == 5) ans = -ans; } let temp= a; a = n; n = temp; if (a % 4 == 3 && n % 4 == 3) ans = -ans; a %= n; if (a > Math.floor(n / 2)) a = a - n; } if (n == 1) return ans; return 0;} // To perform the Solovay-Strassen Primality Testfunction solovoyStrassen( p, iteration){ if (p < 2) return false; if (p != 2 && p % 2 == 0) return false; for(let i = 0; i < iteration; i++) { // Generate a random number r let r = Math.floor(Math.random()* (Number.MAX_VALUE, 2) ); let a = r % (p - 1) + 1; let jacobian = (p + calculateJacobian(a, p)) % p; let mod = modulo(a, Math.floor((p - 1) / 2), p); if (jacobian == 0 || mod != jacobian) return false; } return true; } // Driver Code let iter = 50;let num1 = 15;let num2 = 13; if (solovoyStrassen(num1, iter)) document.write(num1 + \" is prime\"+ \"</br>\");else document.write(num1 + \" is composite\" + \"</br>\"); if (solovoyStrassen(num2,iter)) document.write(num2 + \" is prime\"+ \"</br>\");else document.write(num2 + \" is composite\"+ \"</br>\"); </script>", "e": 42122, "s": 39796, "text": null }, { "code": null, "e": 42132, "s": 42122, "text": "Output : " }, { "code": null, "e": 42160, "s": 42132, "text": "15 is composite\n13 is prime" }, { "code": null, "e": 42321, "s": 42160, "text": "Running Time: Using fast algorithms for modular exponentiation, the running time of this algorithm is O(k·n), where k is the number of different values we test." }, { "code": null, "e": 42646, "s": 42321, "text": "Accuracy: It is possible for the algorithm to return an incorrect answer. If the input n is indeed prime, then the output will always probably be correctly prime. However, if the input n is composite, then it is possible for the output to probably be incorrect prime. The number n is then called an Euler-Jacobi pseudoprime." }, { "code": null, "e": 43068, "s": 42646, "text": "This article is contributed by Palash Nigam . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 43076, "s": 43070, "text": "jit_t" }, { "code": null, "e": 43089, "s": 43076, "text": "Mithun Kumar" }, { "code": null, "e": 43104, "s": 43089, "text": "Srishtik Dutta" }, { "code": null, "e": 43122, "s": 43104, "text": "divyeshrabadiya07" }, { "code": null, "e": 43136, "s": 43122, "text": "jana_sayantan" }, { "code": null, "e": 43150, "s": 43136, "text": "number-theory" }, { "code": null, "e": 43163, "s": 43150, "text": "Prime Number" }, { "code": null, "e": 43176, "s": 43163, "text": "Mathematical" }, { "code": null, "e": 43190, "s": 43176, "text": "number-theory" }, { "code": null, "e": 43203, "s": 43190, "text": "Mathematical" }, { "code": null, "e": 43216, "s": 43203, "text": "Prime Number" }, { "code": null, "e": 43314, "s": 43216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43323, "s": 43314, "text": "Comments" }, { "code": null, "e": 43336, "s": 43323, "text": "Old Comments" }, { "code": null, "e": 43360, "s": 43336, "text": "Merge two sorted arrays" }, { "code": null, "e": 43403, "s": 43360, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 43452, "s": 43403, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 43473, "s": 43452, "text": "Operators in C / C++" }, { "code": null, "e": 43507, "s": 43473, "text": "Program for factorial of a number" }, { "code": null, "e": 43548, "s": 43507, "text": "Program for Decimal to Binary Conversion" }, { "code": null, "e": 43580, "s": 43548, "text": "Algorithm to solve Rubik's Cube" }, { "code": null, "e": 43653, "s": 43580, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 43696, "s": 43653, "text": "The Knight's tour problem | Backtracking-1" } ]
How to get the system configuration information relevant to an open file using Python?
You can call the fpathconf(file_descriptor, name) function to get the system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards. Note that this function is only available on Unix systems. For example, import os, sys # Open a file fd = os.open( "foo.txt", os.O_RDWR|os.O_CREAT ) # Now get maximum number of links to the file. no = os.fpathconf(fd, 'PC_LINK_MAX') print "Maximum number of links to the file. :%d" % no # Now get maximum length of a filename no = os.fpathconf(fd, 'PC_NAME_MAX') print "Maximum length of a filename :%d" % no os.close( fd) When we run above program, it produces following result: Maximum number of links to the file. :127 Maximum length of a filename :255
[ { "code": null, "e": 1431, "s": 1062, "text": "You can call the fpathconf(file_descriptor, name) function to get the system configuration information relevant to an open file. name specifies the configuration value to retrieve; it may be a string which is the name of a defined system value; these names are specified in a number of standards. Note that this function is only available on Unix systems. For example," }, { "code": null, "e": 1782, "s": 1431, "text": "import os, sys\n# Open a file\nfd = os.open( \"foo.txt\", os.O_RDWR|os.O_CREAT )\n# Now get maximum number of links to the file.\nno = os.fpathconf(fd, 'PC_LINK_MAX')\nprint \"Maximum number of links to the file. :%d\" % no\n# Now get maximum length of a filename\nno = os.fpathconf(fd, 'PC_NAME_MAX')\nprint \"Maximum length of a filename :%d\" % no\nos.close( fd)" }, { "code": null, "e": 1839, "s": 1782, "text": "When we run above program, it produces following result:" }, { "code": null, "e": 1916, "s": 1839, "text": "Maximum number of links to the file. :127\n Maximum length of a filename :255" } ]
numpy.exp() in Python
29 Nov, 2018 numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :This mathematical function helps user to calculate exponential of all the elements in the input array. Parameters : array : [array_like]Input array or object whose elements, we need to test. out : [ndarray, optional]Output array with same dimensions as Input array, placed with result. **kwargs : Allows you to pass keyword variable length of argument to a function. It is used when we want to handle named argument in a function. where : [array_like, optional]True value means to calculate the universal functions(ufunc) at that position, False value means to leave the value in the output alone. Return : An array with exponential of all elements of input array. Code 1 : Working # Python program explaining# exp() functionimport numpy as np in_array = [1, 3, 5]print ("Input array : ", in_array) out_array = np.exp(in_array)print ("Output array : ", out_array) Output : Input array : [1, 3, 5] Output array : [ 2.71828183 20.08553692 148.4131591 ] Code 2 : Graphical representation # Python program showing# Graphical representation of # exp() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.exp(in_array) y = [1, 1.2, 1.4, 1.6, 1.8, 2]plt.plot(in_array, y, color = 'blue', marker = "*") # red for numpy.exp()plt.plot(out_array, y, color = 'red', marker = "o")plt.title("numpy.exp()")plt.xlabel("X")plt.ylabel("Y")plt.show() Output : References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp.html. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n29 Nov, 2018" }, { "code": null, "e": 225, "s": 28, "text": "numpy.exp(array, out = None, where = True, casting = ‘same_kind’, order = ‘K’, dtype = None) :This mathematical function helps user to calculate exponential of all the elements in the input array." }, { "code": null, "e": 238, "s": 225, "text": "Parameters :" }, { "code": null, "e": 782, "s": 238, "text": "array : [array_like]Input array or object whose elements, we need to test.\nout : [ndarray, optional]Output array with same dimensions as Input array, \n placed with result.\n**kwargs : Allows you to pass keyword variable length of argument to a function. \n It is used when we want to handle named argument in a function.\nwhere : [array_like, optional]True value means to calculate the universal \n functions(ufunc) at that position, False value means to leave the \n value in the output alone.\n" }, { "code": null, "e": 791, "s": 782, "text": "Return :" }, { "code": null, "e": 851, "s": 791, "text": "An array with exponential of all elements of input array. \n" }, { "code": null, "e": 869, "s": 851, "text": " Code 1 : Working" }, { "code": "# Python program explaining# exp() functionimport numpy as np in_array = [1, 3, 5]print (\"Input array : \", in_array) out_array = np.exp(in_array)print (\"Output array : \", out_array)", "e": 1053, "s": 869, "text": null }, { "code": null, "e": 1062, "s": 1053, "text": "Output :" }, { "code": null, "e": 1148, "s": 1062, "text": "Input array : [1, 3, 5]\nOutput array : [ 2.71828183 20.08553692 148.4131591 ]\n" }, { "code": null, "e": 1183, "s": 1148, "text": " Code 2 : Graphical representation" }, { "code": "# Python program showing# Graphical representation of # exp() functionimport numpy as npimport matplotlib.pyplot as plt in_array = [1, 1.2, 1.4, 1.6, 1.8, 2]out_array = np.exp(in_array) y = [1, 1.2, 1.4, 1.6, 1.8, 2]plt.plot(in_array, y, color = 'blue', marker = \"*\") # red for numpy.exp()plt.plot(out_array, y, color = 'red', marker = \"o\")plt.title(\"numpy.exp()\")plt.xlabel(\"X\")plt.ylabel(\"Y\")plt.show() ", "e": 1593, "s": 1183, "text": null }, { "code": null, "e": 1602, "s": 1593, "text": "Output :" }, { "code": null, "e": 1690, "s": 1602, "text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.exp.html." }, { "code": null, "e": 1725, "s": 1690, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 1738, "s": 1725, "text": "Python-numpy" }, { "code": null, "e": 1745, "s": 1738, "text": "Python" }, { "code": null, "e": 1843, "s": 1745, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1861, "s": 1843, "text": "Python Dictionary" }, { "code": null, "e": 1903, "s": 1861, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1925, "s": 1903, "text": "Enumerate() in Python" }, { "code": null, "e": 1960, "s": 1925, "text": "Read a file line by line in Python" }, { "code": null, "e": 1992, "s": 1960, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2018, "s": 1992, "text": "Python String | replace()" }, { "code": null, "e": 2047, "s": 2018, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2074, "s": 2047, "text": "Python Classes and Objects" }, { "code": null, "e": 2095, "s": 2074, "text": "Python OOPs Concepts" } ]
Plotly - Heatmap
A heat map (or heatmap) is a graphical representation of data where the individual values contained in a matrix are represented as colors. The primary purpose of Heat Maps is to better visualize the volume of locations/events within a dataset and assist in directing viewers towards areas on data visualizations that matter most. Because of their reliance on color to communicate values, Heat Maps are perhaps most commonly used to display a more generalized view of numeric values. Heat Maps are extremely versatile and efficient in drawing attention to trends, and it’s for these reasons they have become increasingly popular within the analytics community. Heat Maps are innately self-explanatory. The darker the shade, the greater the quantity (the higher the value, the tighter the dispersion, etc.). Plotly’s graph_objects module contains Heatmap() function. It needs x, y and z attributes. Their value can be a list, numpy array or Pandas dataframe. In the following example, we have a 2D list or array which defines the data (harvest by different farmers in tons/year) to color code. We then also need two lists of names of farmers and vegetables cultivated by them. vegetables = [ "cucumber", "tomato", "lettuce", "asparagus", "potato", "wheat", "barley" ] farmers = [ "Farmer Joe", "Upland Bros.", "Smith Gardening", "Agrifun", "Organiculture", "BioGoods Ltd.", "Cornylee Corp." ] harvest = np.array( [ [0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0], [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0], [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0], [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0], [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0], [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1], [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3] ] ) trace = go.Heatmap( x = vegetables, y = farmers, z = harvest, type = 'heatmap', colorscale = 'Viridis' ) data = [trace] fig = go.Figure(data = data) iplot(fig) The output of the above mentioned code is given as follows −
[ { "code": null, "e": 2824, "s": 2494, "text": "A heat map (or heatmap) is a graphical representation of data where the individual values contained in a matrix are represented as colors. The primary purpose of Heat Maps is to better visualize the volume of locations/events within a dataset and assist in directing viewers towards areas on data visualizations that matter most." }, { "code": null, "e": 3154, "s": 2824, "text": "Because of their reliance on color to communicate values, Heat Maps are perhaps most commonly used to display a more generalized view of numeric values. Heat Maps are extremely versatile and efficient in drawing attention to trends, and it’s for these reasons they have become increasingly popular within the analytics community." }, { "code": null, "e": 3451, "s": 3154, "text": "Heat Maps are innately self-explanatory. The darker the shade, the greater the quantity (the higher the value, the tighter the dispersion, etc.). Plotly’s graph_objects module contains Heatmap() function. It needs x, y and z attributes. Their value can be a list, numpy array or Pandas dataframe." }, { "code": null, "e": 3669, "s": 3451, "text": "In the following example, we have a 2D list or array which defines the data (harvest by different farmers in tons/year) to color code. We then also need two lists of names of farmers and vegetables cultivated by them." }, { "code": null, "e": 4444, "s": 3669, "text": "vegetables = [\n \"cucumber\", \n \"tomato\", \n \"lettuce\", \n \"asparagus\",\n \"potato\", \n \"wheat\", \n \"barley\"\n]\nfarmers = [\n \"Farmer Joe\", \n \"Upland Bros.\", \n \"Smith Gardening\",\n \"Agrifun\", \n \"Organiculture\", \n \"BioGoods Ltd.\", \n \"Cornylee Corp.\"\n]\nharvest = np.array(\n [\n [0.8, 2.4, 2.5, 3.9, 0.0, 4.0, 0.0],\n [2.4, 0.0, 4.0, 1.0, 2.7, 0.0, 0.0],\n [1.1, 2.4, 0.8, 4.3, 1.9, 4.4, 0.0],\n [0.6, 0.0, 0.3, 0.0, 3.1, 0.0, 0.0],\n [0.7, 1.7, 0.6, 2.6, 2.2, 6.2, 0.0],\n [1.3, 1.2, 0.0, 0.0, 0.0, 3.2, 5.1],\n [0.1, 2.0, 0.0, 1.4, 0.0, 1.9, 6.3]\n ]\n)\ntrace = go.Heatmap(\n x = vegetables,\n y = farmers,\n z = harvest,\n type = 'heatmap',\n colorscale = 'Viridis'\n)\ndata = [trace]\nfig = go.Figure(data = data)\niplot(fig)" } ]
Log and natural Logarithmic value of a column in Pandas – Python
28 Jul, 2020 Log and natural logarithmic value of a column in pandas can be calculated using the log(), log2(), and log10() numpy functions respectively. Before applying the functions, we need to create a dataframe. Code: Python3 # Import required librariesimport pandas as pdimport numpy as np # Dictionarydata = { 'Name': ['Geek1', 'Geek2', 'Geek3', 'Geek4'], 'Salary': [18000, 20000, 15000, 35000]} # Create a dataframedata = pd.DataFrame(data, columns = ['Name', 'Salary']) # Show the dataframedata Output: After the dataframe is created, we can apply numpy.log2() function to the columns. In this case, we will be finding the logarithm values of the column salary. The computed values are stored in the new column “logarithm_base2”. Code: Python3 # Calculate logarithm to base 2 # on 'Salary' columndata['logarithm_base2'] = np.log2(data['Salary']) # Show the dataframedata Output : To find the logarithm on base 10 values we can apply numpy.log10() function to the columns. In this case, we will be finding the logarithm values of the column salary. The computed values are stored in the new column “logarithm_base10”. Code: Python3 # Calculate logarithm to # base 10 on 'Salary' columndata['logarithm_base10'] = np.log10(data['Salary']) # Show the dataframedata Output : Natural logarithmic value of a column in pandas: To find the natural logarithmic values we can apply numpy.log() function to the columns. In this case, we will be finding the natural logarithm values of the column salary. The computed values are stored in the new column “natural_log”. Code: Python3 # Calculate natural logarithm on# 'Salary' columndata['natural_log'] = np.log(data['Salary']) # Show the dataframedata Output : Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Jul, 2020" }, { "code": null, "e": 231, "s": 28, "text": "Log and natural logarithmic value of a column in pandas can be calculated using the log(), log2(), and log10() numpy functions respectively. Before applying the functions, we need to create a dataframe." }, { "code": null, "e": 237, "s": 231, "text": "Code:" }, { "code": null, "e": 245, "s": 237, "text": "Python3" }, { "code": "# Import required librariesimport pandas as pdimport numpy as np # Dictionarydata = { 'Name': ['Geek1', 'Geek2', 'Geek3', 'Geek4'], 'Salary': [18000, 20000, 15000, 35000]} # Create a dataframedata = pd.DataFrame(data, columns = ['Name', 'Salary']) # Show the dataframedata", "e": 604, "s": 245, "text": null }, { "code": null, "e": 614, "s": 604, "text": "Output: " }, { "code": null, "e": 842, "s": 614, "text": "After the dataframe is created, we can apply numpy.log2() function to the columns. In this case, we will be finding the logarithm values of the column salary. The computed values are stored in the new column “logarithm_base2”. " }, { "code": null, "e": 848, "s": 842, "text": "Code:" }, { "code": null, "e": 856, "s": 848, "text": "Python3" }, { "code": "# Calculate logarithm to base 2 # on 'Salary' columndata['logarithm_base2'] = np.log2(data['Salary']) # Show the dataframedata ", "e": 988, "s": 856, "text": null }, { "code": null, "e": 998, "s": 988, "text": "Output : " }, { "code": null, "e": 1236, "s": 998, "text": "To find the logarithm on base 10 values we can apply numpy.log10() function to the columns. In this case, we will be finding the logarithm values of the column salary. The computed values are stored in the new column “logarithm_base10”. " }, { "code": null, "e": 1242, "s": 1236, "text": "Code:" }, { "code": null, "e": 1250, "s": 1242, "text": "Python3" }, { "code": "# Calculate logarithm to # base 10 on 'Salary' columndata['logarithm_base10'] = np.log10(data['Salary']) # Show the dataframedata", "e": 1381, "s": 1250, "text": null }, { "code": null, "e": 1391, "s": 1381, "text": "Output : " }, { "code": null, "e": 1440, "s": 1391, "text": "Natural logarithmic value of a column in pandas:" }, { "code": null, "e": 1678, "s": 1440, "text": "To find the natural logarithmic values we can apply numpy.log() function to the columns. In this case, we will be finding the natural logarithm values of the column salary. The computed values are stored in the new column “natural_log”. " }, { "code": null, "e": 1684, "s": 1678, "text": "Code:" }, { "code": null, "e": 1692, "s": 1684, "text": "Python3" }, { "code": "# Calculate natural logarithm on# 'Salary' columndata['natural_log'] = np.log(data['Salary']) # Show the dataframedata ", "e": 1816, "s": 1692, "text": null }, { "code": null, "e": 1827, "s": 1816, "text": "Output : " }, { "code": null, "e": 1853, "s": 1829, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1867, "s": 1853, "text": "Python-pandas" }, { "code": null, "e": 1874, "s": 1867, "text": "Python" }, { "code": null, "e": 1972, "s": 1874, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1990, "s": 1972, "text": "Python Dictionary" }, { "code": null, "e": 2032, "s": 1990, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2054, "s": 2032, "text": "Enumerate() in Python" }, { "code": null, "e": 2089, "s": 2054, "text": "Read a file line by line in Python" }, { "code": null, "e": 2115, "s": 2089, "text": "Python String | replace()" }, { "code": null, "e": 2147, "s": 2115, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2176, "s": 2147, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2203, "s": 2176, "text": "Python Classes and Objects" }, { "code": null, "e": 2233, "s": 2203, "text": "Iterate over a list in Python" } ]
Shortest path between two points in a Matrix with at most K obstacles
04 Apr, 2022 Given a 2-D array matrix[][] of size ROW * COL and an integer K, where each cell matrix[i][j] is either 0 (empty) or 1 (obstacle). A pointer can move up, down, left, or right from and to an empty cell in a single step. The task is to find the minimum number of steps required to go from the source (0, 0) to the destination (ROW-1, COL-1) with less than or equal to K obstacle eliminations. An obstacle elimination is defined as changing a cell’s value matrix[i][j] from 1 to 0. If no path is possible then return -1. Examples: Input: matrix[][] = { {0,0,1}, {1,0,1}, {0,1,0} }, ROW = 3, COL = 3, K = 2Output: 4Explanation: Change the value of matrix[0][2] and matrix[1][2] to 0 and the path is 0,0 -> 0,1 -> 0,2 -> 1,2 -> 2,2. Input: matrix[][] = { {0,1,0}, {1,1,0}, {0,0,0}, {0,0,0} }, ROW = 4, COL = 3, K = 1Output: 5 Approach: The shortest path can be searched using BFS on a Matrix. Initialize a counter[][] vector, this array will keep track of the number of remaining obstacles that can be eliminated for each visited cell. Run a Breadth-first search on each cell and while keeping track of the number of obstacles we can still eliminate. At each cell, first, check if it is the destination cell or not. Then, it is checked if the current cell is an obstacle then the count of eliminations available is decremented by 1. If the cell value in the counter array has a lower value than the current variable then it is updated. The length array is updated at every step. Follow the steps below to solve the problem: Define 2 arrays dir_Row[4] and dir_Col[4] to store the direction coordinates possible from each point. Define a structure pointLoc as x, y, and k. Initialize a queue q[] of pointLoc datatype. Initialize a 2-D vector distance[ROW][COL] with values 0 to store the distance of each cell from the source cell. Initialize a 2-D vector obstackles[ROW][COL] with values -1 to store the count of available obstacle eliminations. Enqueue the value {0, 0, K} into the queue q[]. Traverse in a while loop till the size of the queue q[] is greater than 0 and perform the following tasks:Initialize a variable te as the front of the queue q[].Initialize the variables x, y and tk as te.x, te.y and te.k.If the current cell equals the destination cell, then return the value of distance[x][y] as the answer.Dequeue the front element from the queue q[].If the current cell is an obstacle then if tk is greater than 0 then decrease its value by 1 else continue.If obstacles[x][y] is greater than equal to tk then continue else set its value as tk.Iterate over the range [0, 4) using the variable i and perform the following tasks:See all the neighboring cells (ax, ay) and check if they are valid cells or not. If not, then continue. Else enqueue {ax, ay, tk} into the queue q[] and set the value of distance[ax][ay] as distance[x][y] + 1. Initialize a variable te as the front of the queue q[]. Initialize the variables x, y and tk as te.x, te.y and te.k. If the current cell equals the destination cell, then return the value of distance[x][y] as the answer. Dequeue the front element from the queue q[]. If the current cell is an obstacle then if tk is greater than 0 then decrease its value by 1 else continue. If obstacles[x][y] is greater than equal to tk then continue else set its value as tk. Iterate over the range [0, 4) using the variable i and perform the following tasks:See all the neighboring cells (ax, ay) and check if they are valid cells or not. If not, then continue. Else enqueue {ax, ay, tk} into the queue q[] and set the value of distance[ax][ay] as distance[x][y] + 1. See all the neighboring cells (ax, ay) and check if they are valid cells or not. If not, then continue. Else enqueue {ax, ay, tk} into the queue q[] and set the value of distance[ax][ay] as distance[x][y] + 1. After performing the above steps, print the value -1 if no answer is found. 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; #define ROW 3#define COL 3 // Direction Vectorsint dir_Row[4] = { -1, 0, 1, 0 };int dir_Col[4] = { 0, 1, 0, -1 }; // Structure for storing coordinates// count of remaining obstacle eliminationsstruct pointLoc { int x, y, k;}; // Function to perform BFSint BFS(int matrix[][COL], int k, pair<int, int> source, pair<int, int> destination){ // Stores pointLoc of each cell queue<struct pointLoc> q; // Vector array to store distance of // each cell from source cell vector<vector<int> > distance( ROW, vector<int>(COL, 0)); // Vector array to store count of // available obstacle eliminations vector<vector<int> > obstacles( ROW, vector<int>(COL, -1)); // Push the source cell into queue // and use as starting point q.push({ source.first, source.second, k }); // Iterate while queue is not empty while (!q.empty()) { struct pointLoc te = q.front(); int x = te.x; int y = te.y; int tk = te.k; // If current cell is same as // destination then return distance if (x == destination.first && y == destination.second) return distance[x][y]; q.pop(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x][y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x][y] >= tk) continue; // Else update value obstacles[x][y] = tk; // Push all valid adjacent // cells into queue for (int i = 0; i < 4; i++) { int ax = x + dir_Row[i]; int ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.push({ ax, ay, tk }); // Update distance of current // cell from source cell distance[ax][ay] = distance[x][y] + 1; } } // If not possible to reach // destination from source return -1;} // Driver Codeint main(){ // Given input int matrix[ROW][COL] = { { 0, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 } }; int k = 2; pair<int, int> source = { 0, 0 }; pair<int, int> destination = { 2, 2 }; cout << BFS(matrix, k, source, destination); return 0;} // Java program for the above approachimport java.util.*; class GFG { static final int ROW = 3; static final int COL = 3; // Direction Vectors static int dir_Row[] = { -1, 0, 1, 0 }; static int dir_Col[] = { 0, 1, 0, -1 }; // Structure for storing coordinates // count of remaining obstacle eliminations static class pointLoc { int x, y, k; public pointLoc(int x, int y, int k) { super(); this.x = x; this.y = y; this.k = k; } }; static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to perform BFS static int BFS(int matrix[][], int k, pair source, pair destination) { // Stores pointLoc of each cell Queue<pointLoc> q = new LinkedList<GFG.pointLoc>(); // Vector array to store distance of // each cell from source cell int[][] distance = new int[ROW][COL]; // Vector array to store count of // available obstacle eliminations int[][] obstacles = new int[ROW][COL]; // Push the source cell into queue // and use as starting point q.add(new pointLoc(source.first, source.second, k)); // Iterate while queue is not empty while (!q.isEmpty()) { pointLoc te = q.peek(); int x = te.x; int y = te.y; int tk = te.k; // If current cell is same as // destination then return distance if (x == destination.first && y == destination.second) return distance[x][y]; q.remove(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x][y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x][y] >= tk) continue; // Else update value obstacles[x][y] = tk; // Push all valid adjacent // cells into queue for (int i = 0; i < 4; i++) { int ax = x + dir_Row[i]; int ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.add(new pointLoc(ax, ay, tk)); // Update distance of current // cell from source cell distance[ax][ay] = distance[x][y] + 1; } } // If not possible to reach // destination from source return -1; } // Driver Code public static void main(String[] args) { // Given input int matrix[][] = { { 0, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 } }; int k = 2; pair source = new pair(0, 0); pair destination = new pair(2, 2); System.out.print(BFS(matrix, k, source, destination)); }} // This code is contributed by shikhasingrajput # Python Program to implement# the above approachROW = 3COL = 3 # Direction Vectorsdir_Row = [-1, 0, 1, 0]dir_Col = [0, 1, 0, -1] # Structure for storing coordinates# count of remaining obstacle eliminationsclass pointLoc: def __init__(self,x, y, k): self.x = x self.y = y self.k = k # Function to perform BFSdef BFS(matrix, k, source,destination): # Stores pointLoc of each cell q = [] # Vector array to store distance of # each cell from source cell distance = [0 for i in range(ROW)] for i in range(len(distance)): distance[i] = [0 for i in range(COL)] # Vector array to store count of # available obstacle eliminations obstacles = [0 for i in range(ROW)] for i in range(len(obstacles)): obstacles[i] = [-1 for i in range(COL)] # Push the source cell into queue # and use as starting point q.append(pointLoc(source[0], source[1], k)) # Iterate while queue is not empty while (len(q) > 0): te = q[0] x = te.x y = te.y tk = te.k # If current cell is same as # destination then return distance if (x == destination[0] and y == destination[1]): return distance[x][y] q = q[1:] # If current cell is an obstacle # then decrement current value # if possible else skip the cell if (matrix[x][y] == 1): if (tk > 0): tk -= 1 else: continue # Cell is skipped only if current # value is less than previous # value of cell if (obstacles[x][y] >= tk): continue # Else update value obstacles[x][y] = tk # Push all valid adjacent # cells into queue for i in range(4): ax = x + dir_Row[i] ay = y + dir_Col[i] if (ax < 0 or ay < 0 or ax >= ROW or ay >= COL): continue q.append(pointLoc(ax, ay, tk)) # Update distance of current # cell from source cell distance[ax][ay] = distance[x][y] + 1 # If not possible to reach # destination from source return -1 # Driver Code # Given inputmatrix = [[0, 0, 1],[1, 0, 1],[0, 1, 0]] k = 2source = [0, 0]destination = [2, 2]print(BFS(matrix, k, source, destination)) # This code is contributed by shinjanpatra // C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static readonly int ROW = 3;static readonly int COL = 3; // Direction Listsstatic int []dir_Row = { -1, 0, 1, 0 };static int []dir_Col = { 0, 1, 0, -1 }; // Structure for storing coordinates// count of remaining obstacle eliminationsclass pointLoc{ public int x, y, k; public pointLoc(int x, int y, int k) { this.x = x; this.y = y; this.k = k; }}; class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to perform BFSstatic int BFS(int [,]matrix, int k, pair source, pair destination){ // Stores pointLoc of each cell Queue<pointLoc> q = new Queue<GFG.pointLoc>(); // List array to store distance of // each cell from source cell int[,] distance = new int[ROW, COL]; // List array to store count of // available obstacle eliminations int[,] obstacles = new int[ROW, COL]; // Push the source cell into queue // and use as starting point q.Enqueue(new pointLoc(source.first, source.second, k)); // Iterate while queue is not empty while (q.Count != 0) { pointLoc te = q.Peek(); int x = te.x; int y = te.y; int tk = te.k; // If current cell is same as // destination then return distance if (x == destination.first && y == destination.second) return distance[x, y]; q.Dequeue(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x, y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x, y] >= tk) continue; // Else update value obstacles[x, y] = tk; // Push all valid adjacent // cells into queue for(int i = 0; i < 4; i++) { int ax = x + dir_Row[i]; int ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.Enqueue(new pointLoc(ax, ay, tk)); // Update distance of current // cell from source cell distance[ax, ay] = distance[x, y] + 1; } } // If not possible to reach // destination from source return -1;} // Driver Codepublic static void Main(String[] args){ // Given input int [,]matrix = { { 0, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 } }; int k = 2; pair source = new pair(0, 0); pair destination = new pair(2, 2); Console.Write(BFS(matrix, k, source, destination));}} // This code is contributed by shikhasingrajput <script> // JavaScript Program to implement // the above approach let ROW = 3 let COL = 3 // Direction Vectors let dir_Row = [-1, 0, 1, 0]; let dir_Col = [0, 1, 0, -1]; // Structure for storing coordinates // count of remaining obstacle eliminations class pointLoc { constructor(x, y, k) { this.x = x; this.y = y; this.k = k; } }; // Function to perform BFS function BFS(matrix, k, source, destination) { // Stores pointLoc of each cell let q = []; // Vector array to store distance of // each cell from source cell let distance = new Array(ROW); for (let i = 0; i < distance.length; i++) { distance[i] = new Array(COL).fill(0); } // Vector array to store count of // available obstacle eliminations let obstacles = new Array(ROW); for (let i = 0; i < obstacles.length; i++) { obstacles[i] = new Array(COL).fill(-1); } // Push the source cell into queue // and use as starting point q.push(new pointLoc(source[0], source[1], k)); // Iterate while queue is not empty while (q.length > 0) { let te = q[0]; let x = te.x; let y = te.y; let tk = te.k; // If current cell is same as // destination then return distance if (x == destination[0] && y == destination[1]) return distance[x][y]; q.shift(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x][y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x][y] >= tk) continue; // Else update value obstacles[x][y] = tk; // Push all valid adjacent // cells into queue for (let i = 0; i < 4; i++) { let ax = x + dir_Row[i]; let ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.push(new pointLoc(ax, ay, tk)); // Update distance of current // cell from source cell distance[ax][ay] = distance[x][y] + 1; } } // If not possible to reach // destination from source return -1; } // Driver Code // Given input let matrix = [[0, 0, 1], [1, 0, 1], [0, 1, 0]]; let k = 2; let source = [0, 0]; let destination = [2, 2]; document.write(BFS(matrix, k, source, destination)); // This code is contributed by Potta Lokesh </script> 4 Time Complexity: O(ROW*COL*K)Auxiliary Space: O(ROW*COL*K) lokeshpotta20 shikhasingrajput shinjanpatra BFS Matrix Queue Matrix Queue BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n04 Apr, 2022" }, { "code": null, "e": 571, "s": 52, "text": "Given a 2-D array matrix[][] of size ROW * COL and an integer K, where each cell matrix[i][j] is either 0 (empty) or 1 (obstacle). A pointer can move up, down, left, or right from and to an empty cell in a single step. The task is to find the minimum number of steps required to go from the source (0, 0) to the destination (ROW-1, COL-1) with less than or equal to K obstacle eliminations. An obstacle elimination is defined as changing a cell’s value matrix[i][j] from 1 to 0. If no path is possible then return -1. " }, { "code": null, "e": 581, "s": 571, "text": "Examples:" }, { "code": null, "e": 739, "s": 581, "text": "Input: matrix[][] = { {0,0,1}, {1,0,1}, {0,1,0} }, ROW = 3, COL = 3, K = 2Output: 4Explanation: " }, { "code": null, "e": 843, "s": 739, "text": "Change the value of matrix[0][2] and matrix[1][2] to 0 and the path is 0,0 -> 0,1 -> 0,2 -> 1,2 -> 2,2." }, { "code": null, "e": 1025, "s": 843, "text": "Input: matrix[][] = { {0,1,0}, {1,1,0}, {0,0,0}, {0,0,0} }, ROW = 4, COL = 3, K = 1Output: 5" }, { "code": null, "e": 1723, "s": 1025, "text": "Approach: The shortest path can be searched using BFS on a Matrix. Initialize a counter[][] vector, this array will keep track of the number of remaining obstacles that can be eliminated for each visited cell. Run a Breadth-first search on each cell and while keeping track of the number of obstacles we can still eliminate. At each cell, first, check if it is the destination cell or not. Then, it is checked if the current cell is an obstacle then the count of eliminations available is decremented by 1. If the cell value in the counter array has a lower value than the current variable then it is updated. The length array is updated at every step. Follow the steps below to solve the problem:" }, { "code": null, "e": 1826, "s": 1723, "text": "Define 2 arrays dir_Row[4] and dir_Col[4] to store the direction coordinates possible from each point." }, { "code": null, "e": 1870, "s": 1826, "text": "Define a structure pointLoc as x, y, and k." }, { "code": null, "e": 1915, "s": 1870, "text": "Initialize a queue q[] of pointLoc datatype." }, { "code": null, "e": 2029, "s": 1915, "text": "Initialize a 2-D vector distance[ROW][COL] with values 0 to store the distance of each cell from the source cell." }, { "code": null, "e": 2144, "s": 2029, "text": "Initialize a 2-D vector obstackles[ROW][COL] with values -1 to store the count of available obstacle eliminations." }, { "code": null, "e": 2192, "s": 2144, "text": "Enqueue the value {0, 0, K} into the queue q[]." }, { "code": null, "e": 3047, "s": 2192, "text": "Traverse in a while loop till the size of the queue q[] is greater than 0 and perform the following tasks:Initialize a variable te as the front of the queue q[].Initialize the variables x, y and tk as te.x, te.y and te.k.If the current cell equals the destination cell, then return the value of distance[x][y] as the answer.Dequeue the front element from the queue q[].If the current cell is an obstacle then if tk is greater than 0 then decrease its value by 1 else continue.If obstacles[x][y] is greater than equal to tk then continue else set its value as tk.Iterate over the range [0, 4) using the variable i and perform the following tasks:See all the neighboring cells (ax, ay) and check if they are valid cells or not. If not, then continue. Else enqueue {ax, ay, tk} into the queue q[] and set the value of distance[ax][ay] as distance[x][y] + 1." }, { "code": null, "e": 3103, "s": 3047, "text": "Initialize a variable te as the front of the queue q[]." }, { "code": null, "e": 3164, "s": 3103, "text": "Initialize the variables x, y and tk as te.x, te.y and te.k." }, { "code": null, "e": 3268, "s": 3164, "text": "If the current cell equals the destination cell, then return the value of distance[x][y] as the answer." }, { "code": null, "e": 3314, "s": 3268, "text": "Dequeue the front element from the queue q[]." }, { "code": null, "e": 3422, "s": 3314, "text": "If the current cell is an obstacle then if tk is greater than 0 then decrease its value by 1 else continue." }, { "code": null, "e": 3509, "s": 3422, "text": "If obstacles[x][y] is greater than equal to tk then continue else set its value as tk." }, { "code": null, "e": 3802, "s": 3509, "text": "Iterate over the range [0, 4) using the variable i and perform the following tasks:See all the neighboring cells (ax, ay) and check if they are valid cells or not. If not, then continue. Else enqueue {ax, ay, tk} into the queue q[] and set the value of distance[ax][ay] as distance[x][y] + 1." }, { "code": null, "e": 4012, "s": 3802, "text": "See all the neighboring cells (ax, ay) and check if they are valid cells or not. If not, then continue. Else enqueue {ax, ay, tk} into the queue q[] and set the value of distance[ax][ay] as distance[x][y] + 1." }, { "code": null, "e": 4088, "s": 4012, "text": "After performing the above steps, print the value -1 if no answer is found." }, { "code": null, "e": 4139, "s": 4088, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 4143, "s": 4139, "text": "C++" }, { "code": null, "e": 4148, "s": 4143, "text": "Java" }, { "code": null, "e": 4156, "s": 4148, "text": "Python3" }, { "code": null, "e": 4159, "s": 4156, "text": "C#" }, { "code": null, "e": 4170, "s": 4159, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; #define ROW 3#define COL 3 // Direction Vectorsint dir_Row[4] = { -1, 0, 1, 0 };int dir_Col[4] = { 0, 1, 0, -1 }; // Structure for storing coordinates// count of remaining obstacle eliminationsstruct pointLoc { int x, y, k;}; // Function to perform BFSint BFS(int matrix[][COL], int k, pair<int, int> source, pair<int, int> destination){ // Stores pointLoc of each cell queue<struct pointLoc> q; // Vector array to store distance of // each cell from source cell vector<vector<int> > distance( ROW, vector<int>(COL, 0)); // Vector array to store count of // available obstacle eliminations vector<vector<int> > obstacles( ROW, vector<int>(COL, -1)); // Push the source cell into queue // and use as starting point q.push({ source.first, source.second, k }); // Iterate while queue is not empty while (!q.empty()) { struct pointLoc te = q.front(); int x = te.x; int y = te.y; int tk = te.k; // If current cell is same as // destination then return distance if (x == destination.first && y == destination.second) return distance[x][y]; q.pop(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x][y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x][y] >= tk) continue; // Else update value obstacles[x][y] = tk; // Push all valid adjacent // cells into queue for (int i = 0; i < 4; i++) { int ax = x + dir_Row[i]; int ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.push({ ax, ay, tk }); // Update distance of current // cell from source cell distance[ax][ay] = distance[x][y] + 1; } } // If not possible to reach // destination from source return -1;} // Driver Codeint main(){ // Given input int matrix[ROW][COL] = { { 0, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 } }; int k = 2; pair<int, int> source = { 0, 0 }; pair<int, int> destination = { 2, 2 }; cout << BFS(matrix, k, source, destination); return 0;}", "e": 6736, "s": 4170, "text": null }, { "code": "// Java program for the above approachimport java.util.*; class GFG { static final int ROW = 3; static final int COL = 3; // Direction Vectors static int dir_Row[] = { -1, 0, 1, 0 }; static int dir_Col[] = { 0, 1, 0, -1 }; // Structure for storing coordinates // count of remaining obstacle eliminations static class pointLoc { int x, y, k; public pointLoc(int x, int y, int k) { super(); this.x = x; this.y = y; this.k = k; } }; static class pair { int first, second; public pair(int first, int second) { this.first = first; this.second = second; } } // Function to perform BFS static int BFS(int matrix[][], int k, pair source, pair destination) { // Stores pointLoc of each cell Queue<pointLoc> q = new LinkedList<GFG.pointLoc>(); // Vector array to store distance of // each cell from source cell int[][] distance = new int[ROW][COL]; // Vector array to store count of // available obstacle eliminations int[][] obstacles = new int[ROW][COL]; // Push the source cell into queue // and use as starting point q.add(new pointLoc(source.first, source.second, k)); // Iterate while queue is not empty while (!q.isEmpty()) { pointLoc te = q.peek(); int x = te.x; int y = te.y; int tk = te.k; // If current cell is same as // destination then return distance if (x == destination.first && y == destination.second) return distance[x][y]; q.remove(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x][y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x][y] >= tk) continue; // Else update value obstacles[x][y] = tk; // Push all valid adjacent // cells into queue for (int i = 0; i < 4; i++) { int ax = x + dir_Row[i]; int ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.add(new pointLoc(ax, ay, tk)); // Update distance of current // cell from source cell distance[ax][ay] = distance[x][y] + 1; } } // If not possible to reach // destination from source return -1; } // Driver Code public static void main(String[] args) { // Given input int matrix[][] = { { 0, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 } }; int k = 2; pair source = new pair(0, 0); pair destination = new pair(2, 2); System.out.print(BFS(matrix, k, source, destination)); }} // This code is contributed by shikhasingrajput", "e": 9927, "s": 6736, "text": null }, { "code": "# Python Program to implement# the above approachROW = 3COL = 3 # Direction Vectorsdir_Row = [-1, 0, 1, 0]dir_Col = [0, 1, 0, -1] # Structure for storing coordinates# count of remaining obstacle eliminationsclass pointLoc: def __init__(self,x, y, k): self.x = x self.y = y self.k = k # Function to perform BFSdef BFS(matrix, k, source,destination): # Stores pointLoc of each cell q = [] # Vector array to store distance of # each cell from source cell distance = [0 for i in range(ROW)] for i in range(len(distance)): distance[i] = [0 for i in range(COL)] # Vector array to store count of # available obstacle eliminations obstacles = [0 for i in range(ROW)] for i in range(len(obstacles)): obstacles[i] = [-1 for i in range(COL)] # Push the source cell into queue # and use as starting point q.append(pointLoc(source[0], source[1], k)) # Iterate while queue is not empty while (len(q) > 0): te = q[0] x = te.x y = te.y tk = te.k # If current cell is same as # destination then return distance if (x == destination[0] and y == destination[1]): return distance[x][y] q = q[1:] # If current cell is an obstacle # then decrement current value # if possible else skip the cell if (matrix[x][y] == 1): if (tk > 0): tk -= 1 else: continue # Cell is skipped only if current # value is less than previous # value of cell if (obstacles[x][y] >= tk): continue # Else update value obstacles[x][y] = tk # Push all valid adjacent # cells into queue for i in range(4): ax = x + dir_Row[i] ay = y + dir_Col[i] if (ax < 0 or ay < 0 or ax >= ROW or ay >= COL): continue q.append(pointLoc(ax, ay, tk)) # Update distance of current # cell from source cell distance[ax][ay] = distance[x][y] + 1 # If not possible to reach # destination from source return -1 # Driver Code # Given inputmatrix = [[0, 0, 1],[1, 0, 1],[0, 1, 0]] k = 2source = [0, 0]destination = [2, 2]print(BFS(matrix, k, source, destination)) # This code is contributed by shinjanpatra", "e": 12285, "s": 9927, "text": null }, { "code": "// C# program for the above approachusing System;using System.Collections.Generic; class GFG{ static readonly int ROW = 3;static readonly int COL = 3; // Direction Listsstatic int []dir_Row = { -1, 0, 1, 0 };static int []dir_Col = { 0, 1, 0, -1 }; // Structure for storing coordinates// count of remaining obstacle eliminationsclass pointLoc{ public int x, y, k; public pointLoc(int x, int y, int k) { this.x = x; this.y = y; this.k = k; }}; class pair{ public int first, second; public pair(int first, int second) { this.first = first; this.second = second; }} // Function to perform BFSstatic int BFS(int [,]matrix, int k, pair source, pair destination){ // Stores pointLoc of each cell Queue<pointLoc> q = new Queue<GFG.pointLoc>(); // List array to store distance of // each cell from source cell int[,] distance = new int[ROW, COL]; // List array to store count of // available obstacle eliminations int[,] obstacles = new int[ROW, COL]; // Push the source cell into queue // and use as starting point q.Enqueue(new pointLoc(source.first, source.second, k)); // Iterate while queue is not empty while (q.Count != 0) { pointLoc te = q.Peek(); int x = te.x; int y = te.y; int tk = te.k; // If current cell is same as // destination then return distance if (x == destination.first && y == destination.second) return distance[x, y]; q.Dequeue(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x, y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x, y] >= tk) continue; // Else update value obstacles[x, y] = tk; // Push all valid adjacent // cells into queue for(int i = 0; i < 4; i++) { int ax = x + dir_Row[i]; int ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.Enqueue(new pointLoc(ax, ay, tk)); // Update distance of current // cell from source cell distance[ax, ay] = distance[x, y] + 1; } } // If not possible to reach // destination from source return -1;} // Driver Codepublic static void Main(String[] args){ // Given input int [,]matrix = { { 0, 0, 1 }, { 1, 0, 1 }, { 0, 1, 0 } }; int k = 2; pair source = new pair(0, 0); pair destination = new pair(2, 2); Console.Write(BFS(matrix, k, source, destination));}} // This code is contributed by shikhasingrajput", "e": 15267, "s": 12285, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach let ROW = 3 let COL = 3 // Direction Vectors let dir_Row = [-1, 0, 1, 0]; let dir_Col = [0, 1, 0, -1]; // Structure for storing coordinates // count of remaining obstacle eliminations class pointLoc { constructor(x, y, k) { this.x = x; this.y = y; this.k = k; } }; // Function to perform BFS function BFS(matrix, k, source, destination) { // Stores pointLoc of each cell let q = []; // Vector array to store distance of // each cell from source cell let distance = new Array(ROW); for (let i = 0; i < distance.length; i++) { distance[i] = new Array(COL).fill(0); } // Vector array to store count of // available obstacle eliminations let obstacles = new Array(ROW); for (let i = 0; i < obstacles.length; i++) { obstacles[i] = new Array(COL).fill(-1); } // Push the source cell into queue // and use as starting point q.push(new pointLoc(source[0], source[1], k)); // Iterate while queue is not empty while (q.length > 0) { let te = q[0]; let x = te.x; let y = te.y; let tk = te.k; // If current cell is same as // destination then return distance if (x == destination[0] && y == destination[1]) return distance[x][y]; q.shift(); // If current cell is an obstacle // then decrement current value // if possible else skip the cell if (matrix[x][y] == 1) { if (tk > 0) tk--; else continue; } // Cell is skipped only if current // value is less than previous // value of cell if (obstacles[x][y] >= tk) continue; // Else update value obstacles[x][y] = tk; // Push all valid adjacent // cells into queue for (let i = 0; i < 4; i++) { let ax = x + dir_Row[i]; let ay = y + dir_Col[i]; if (ax < 0 || ay < 0 || ax >= ROW || ay >= COL) continue; q.push(new pointLoc(ax, ay, tk)); // Update distance of current // cell from source cell distance[ax][ay] = distance[x][y] + 1; } } // If not possible to reach // destination from source return -1; } // Driver Code // Given input let matrix = [[0, 0, 1], [1, 0, 1], [0, 1, 0]]; let k = 2; let source = [0, 0]; let destination = [2, 2]; document.write(BFS(matrix, k, source, destination)); // This code is contributed by Potta Lokesh </script>", "e": 18549, "s": 15267, "text": null }, { "code": null, "e": 18551, "s": 18549, "text": "4" }, { "code": null, "e": 18610, "s": 18551, "text": "Time Complexity: O(ROW*COL*K)Auxiliary Space: O(ROW*COL*K)" }, { "code": null, "e": 18626, "s": 18612, "text": "lokeshpotta20" }, { "code": null, "e": 18643, "s": 18626, "text": "shikhasingrajput" }, { "code": null, "e": 18656, "s": 18643, "text": "shinjanpatra" }, { "code": null, "e": 18660, "s": 18656, "text": "BFS" }, { "code": null, "e": 18667, "s": 18660, "text": "Matrix" }, { "code": null, "e": 18673, "s": 18667, "text": "Queue" }, { "code": null, "e": 18680, "s": 18673, "text": "Matrix" }, { "code": null, "e": 18686, "s": 18680, "text": "Queue" }, { "code": null, "e": 18690, "s": 18686, "text": "BFS" } ]
Pygame – Time
25 Oct, 2021 While using pygame we sometimes need to perform certain operations that include the usage of time. Like finding how much time our program has been running, pausing the program for an amount of time, etc. For operations of this kind, we need to use the time methods of pygame. In this article, we will be discussing the various methods that can be used for performing these operations. The function that we will discuss are:- pygame.time.wait pygame.time.get_ticks pygame.time.delay pygame.time.Clock This function is used to pause the running of the program for few seconds. it takes time in milliseconds as parameter. For example to demonstrate this function we will write a simple program to make geeksforgeeks logo appear on screen only after 5 seconds. The code for this will be: Python # importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((500, 500)) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surfacedisplay.blit(image,(100,100)) # making the script wait for 5000 secondspygame.time.wait(5000) # creating a running loopwhile True: # creating a loop to check events that are occurring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # updating the display pygame.display.flip() Output: The output of this will be that the script will wait for 5 seconds and then update the display to show geeksforgeeks logo. It is slightly less accurate than pygame.time.delay which we will discuss later in this article because it uses sleeping but the other one uses the processor. This function gives a time which has been running in milliseconds. For example, if we want to write a simple code to demonstrate this example, it can be: Python # importing pygame moduleimport pygame # initialising pygamepygame.init() # creating a variablei=0while i<5: # storing the time in ticks variable ticks=pygame.time.get_ticks() # printing the variable ticks print(ticks) # increasing the value of i by 1 i=i+1 # pausing the script for 1 second pygame.time.wait(1000) Output: The time is printed for every iteration, including the time for which we paused the script in every iteration. This function works the same as pygame.time.wait function the difference is that this function will use the processor (rather than sleeping) in order to make the delay more accurate. The sample code can be written the same as pygame.time.wait function by just replacing the name: Python # importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((500, 500)) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surfacedisplay.blit(image,(100,100)) # making the script wait for 5000 secondspygame.time.delay(5000) # creating a running loopwhile True: # creating a loop to check events that are occurring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # updating the display pygame.display.flip() Output: This function is used to create a clock object which can be used to keep track of time. The various methods of clock object are below: tick():This method should be called once per frame. It will compute how many milliseconds have passed since the previous call. If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. For example if we pass 10 as argument the program will never run at more than 10 frames per second. get_time():It is used to obtain a number of milliseconds used between two tick(). get_fps():it gives information regarding the clock frame rate. it returns the output in floating-point value. A simple Program to demonstrate this function could be: Python # importing the pygame moduleimport pygame # initialising the pygamepygame.init() # declaring a variable i with value 0i=0 # creating a clock objectclock=pygame.time.Clock() # creating a loop for 5 iterationswhile i<5: # setting fps of program to max 1 per second clock.tick(1) # printing time used in the previous tick print(clock.get_time()) # printing compute the clock framerate print(clock.get_fps()) i=i+1 Output: As we have passed 1 in the tick method, it sets maximum fps to 1. Which results in time between each frame nearing 1000 milliseconds. akshaysingh98088 saurabh1990aror anikakapoor Picked Python-PyGame Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n25 Oct, 2021" }, { "code": null, "e": 413, "s": 28, "text": "While using pygame we sometimes need to perform certain operations that include the usage of time. Like finding how much time our program has been running, pausing the program for an amount of time, etc. For operations of this kind, we need to use the time methods of pygame. In this article, we will be discussing the various methods that can be used for performing these operations." }, { "code": null, "e": 453, "s": 413, "text": "The function that we will discuss are:-" }, { "code": null, "e": 470, "s": 453, "text": "pygame.time.wait" }, { "code": null, "e": 492, "s": 470, "text": "pygame.time.get_ticks" }, { "code": null, "e": 510, "s": 492, "text": "pygame.time.delay" }, { "code": null, "e": 528, "s": 510, "text": "pygame.time.Clock" }, { "code": null, "e": 812, "s": 528, "text": "This function is used to pause the running of the program for few seconds. it takes time in milliseconds as parameter. For example to demonstrate this function we will write a simple program to make geeksforgeeks logo appear on screen only after 5 seconds. The code for this will be:" }, { "code": null, "e": 819, "s": 812, "text": "Python" }, { "code": "# importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((500, 500)) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surfacedisplay.blit(image,(100,100)) # making the script wait for 5000 secondspygame.time.wait(5000) # creating a running loopwhile True: # creating a loop to check events that are occurring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # updating the display pygame.display.flip()", "e": 1469, "s": 819, "text": null }, { "code": null, "e": 1479, "s": 1469, "text": " Output:" }, { "code": null, "e": 1607, "s": 1483, "text": "The output of this will be that the script will wait for 5 seconds and then update the display to show geeksforgeeks logo. " }, { "code": null, "e": 1766, "s": 1607, "text": "It is slightly less accurate than pygame.time.delay which we will discuss later in this article because it uses sleeping but the other one uses the processor." }, { "code": null, "e": 1920, "s": 1766, "text": "This function gives a time which has been running in milliseconds. For example, if we want to write a simple code to demonstrate this example, it can be:" }, { "code": null, "e": 1927, "s": 1920, "text": "Python" }, { "code": "# importing pygame moduleimport pygame # initialising pygamepygame.init() # creating a variablei=0while i<5: # storing the time in ticks variable ticks=pygame.time.get_ticks() # printing the variable ticks print(ticks) # increasing the value of i by 1 i=i+1 # pausing the script for 1 second pygame.time.wait(1000)", "e": 2287, "s": 1927, "text": null }, { "code": null, "e": 2297, "s": 2287, "text": " Output:" }, { "code": null, "e": 2408, "s": 2297, "text": "The time is printed for every iteration, including the time for which we paused the script in every iteration." }, { "code": null, "e": 2689, "s": 2408, "text": "This function works the same as pygame.time.wait function the difference is that this function will use the processor (rather than sleeping) in order to make the delay more accurate. The sample code can be written the same as pygame.time.wait function by just replacing the name: " }, { "code": null, "e": 2696, "s": 2689, "text": "Python" }, { "code": "# importing pygame moduleimport pygame # importing sys moduleimport sys # initialising pygamepygame.init() # creating displaydisplay = pygame.display.set_mode((500, 500)) # Creating the image surfaceimage = pygame.image.load('gfg_logo.png') # putting our image surface on display surfacedisplay.blit(image,(100,100)) # making the script wait for 5000 secondspygame.time.delay(5000) # creating a running loopwhile True: # creating a loop to check events that are occurring for event in pygame.event.get(): if event.type == pygame.QUIT: pygame.quit() sys.exit() # updating the display pygame.display.flip()", "e": 3347, "s": 2696, "text": null }, { "code": null, "e": 3355, "s": 3347, "text": "Output:" }, { "code": null, "e": 3490, "s": 3355, "text": "This function is used to create a clock object which can be used to keep track of time. The various methods of clock object are below:" }, { "code": null, "e": 3850, "s": 3490, "text": "tick():This method should be called once per frame. It will compute how many milliseconds have passed since the previous call. If you pass the optional framerate argument the function will delay to keep the game running slower than the given ticks per second. For example if we pass 10 as argument the program will never run at more than 10 frames per second." }, { "code": null, "e": 3932, "s": 3850, "text": "get_time():It is used to obtain a number of milliseconds used between two tick()." }, { "code": null, "e": 4042, "s": 3932, "text": "get_fps():it gives information regarding the clock frame rate. it returns the output in floating-point value." }, { "code": null, "e": 4098, "s": 4042, "text": "A simple Program to demonstrate this function could be:" }, { "code": null, "e": 4105, "s": 4098, "text": "Python" }, { "code": "# importing the pygame moduleimport pygame # initialising the pygamepygame.init() # declaring a variable i with value 0i=0 # creating a clock objectclock=pygame.time.Clock() # creating a loop for 5 iterationswhile i<5: # setting fps of program to max 1 per second clock.tick(1) # printing time used in the previous tick print(clock.get_time()) # printing compute the clock framerate print(clock.get_fps()) i=i+1", "e": 4555, "s": 4105, "text": null }, { "code": null, "e": 4566, "s": 4555, "text": " Output: " }, { "code": null, "e": 4701, "s": 4566, "text": " As we have passed 1 in the tick method, it sets maximum fps to 1. Which results in time between each frame nearing 1000 milliseconds." }, { "code": null, "e": 4720, "s": 4703, "text": "akshaysingh98088" }, { "code": null, "e": 4736, "s": 4720, "text": "saurabh1990aror" }, { "code": null, "e": 4748, "s": 4736, "text": "anikakapoor" }, { "code": null, "e": 4755, "s": 4748, "text": "Picked" }, { "code": null, "e": 4769, "s": 4755, "text": "Python-PyGame" }, { "code": null, "e": 4776, "s": 4769, "text": "Python" } ]
Python Web Development – Django Tutorial
29 Dec, 2021 Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use. Excellent documentation and high scalability. Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket, Dropbox, etc. and the list is never-ending. Easiest Framework to learn, rapid development, and Batteries fully included. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time. The last but not least reason to learn Django is Python, Python has a huge library and features such as Web Scrapping, Machine Learning, Image Processing, Scientific Computing, etc. One can integrate all this with web applications and do lots and lots of advanced stuff. Django is based on MVT (Model-View-Template) architecture which has the following three parts – Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres). View: The View is the user interface that you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files. Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. To check more, visit – Django Templates For more information, refer to Django Project MVT Structure Most of the time when you’ll be working on some Django projects, you’ll find that each project may need a different version of Django. This problem may arise when you install Django in a global or default environment. To overcome this problem we will use virtual environments in Python. This enables us to create multiple different Django environments on a single computer. To create a virtual environment type the below command in the terminal. python3 -m venv ./name Here the name suggests the name of the virtual environment. Let’s create our virtual environment with the name as venv only. So the command to create it will be – python3 -m venv ./venv After running the above command you will see a folder named venv with the following sub-directories. After creating the virtual environment let’s activate it. To activate it type the below command in the terminal. source ./venv/bin/activate In the above command ./ is used to tell the current working directory. Note: If you have your virtual environment set up in another location and your terminal opened up in another location, then provide the location to the venv folder i.e. our virtual environment folder. After you run the above command you should see (venv) at the starting of every line of your terminal as shown in the below image. We can install Django using the pip command. To install this type the below command in the terminal. pip install django For more information, refer to Django Introduction and Installation To initiate a project of Django on Your PC, open Terminal and Enter the following command django-admin startproject projectName A New Folder with the name projectName will be created. To enter in the project using the terminal enter command cd projectName Now let’s un the server and see everything is working fine or not. To run the server type the below command in the terminal. python manage.py runserver After running the server go to http://127.0.0.1:8000/ and you’ll see something like this – For more information, refer to How to Create a Basic Project using MVT in Django ? A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files- Let’s discuss these files in detail – manage.py: This file is used to interact with your project via the command line(start the server, sync the database... etc). For getting the full list of commands that can be executed by manage.py type this code in the command window- python manage.py help _init_.py: It is a python package. It is invoked when the package or a module in the package is imported. We usually use this to execute package initialization code, for example for the initialization of package-level data. settings.py: As the name indicates it contains all the website settings. In this file, we register any applications we create, the location of our static files, database configuration details, etc. urls.py: In this file, we store all links of the project and functions to call. wsgi.py: This file is used in deploying the project in WSGI. It is used to help your Django application communicate with the webserver. Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. Benefits of using Django apps – Django apps are reusable i.e. a Django app can be used with multiple projects. We have loosely coupled i.e. almost independent components Multiple developers can work on different components Debugging and code organization are easy. Django has an excellent debugger tool. It has in-built features like admin pages etc, which reduces the effort of building the same from scratch Django provides some pre-installed apps for users. To see pre-installed apps, navigate to projectName –> projectName –> settings.py. In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer’s comfort. Python3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',] We can also create our own custom apps. To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command : python manage.py startapp projectApp Now let’s create an app called gfg_site_app, so the command to create the app would be – python manage.py startapp gfg_site_app Now you can see your directory structure as under : To consider the app in your project you need to specify your project name in the INSTALLED_APPS list as follows in settings.py: Python3 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gfg_site_app.apps.GfgSiteAppConfig',] For more information, refer to How to Create an App in Django ? A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page. Python3 from django.http import HttpResponse # create a functiondef geeks_view(request): return HttpResponse("<h1>Welcome to GeeksforGeeks</h1>") Let’s step through this code one line at a time: First, we import the class HttpResponse from the django.http module, along with Python’s datetime library. Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request. The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object. Note: For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse Objects The above Function will render the text Welcome to GeeksforGeeks as h1 on the page. Now the question that may be arising is at what URL this function will be called and how will we handle such URLs. Don’t worry we will handle URL in the section but in this section let us continue with the Django views only. Django views are divided into two major categories:- Function-Based Views Class-Based Views Function-based views are writer using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function-based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development. Refer to the below articles to get more information on Function-Based views – Django CRUD (Create, Retrieve, Update, Delete) Function Based Views Create View List View Detail View Update View Delete View Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views: Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching. Object-oriented techniques such as mixins (multiple inheritances) can be used to factor code into reusable components. Refer to the below articles to get more information on Class-Based views – Class Based Generic Views Django (Create, Retrieve, Update, Delete) Createview ListView DetailView UpdateView DeleteView FormView In Django, each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration). Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view. Now if we see our project we have created an app called gfg_site, the Python module to be used as URLConf is the value of ROOT_URLCONF in gfg_site/settings.py. By default this is set to ‘gfg_site.urls’. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view. Here’s a sample code for gfg_site/urls.py: Python3 from django.urls import pathfrom . import views urlpatterns = [ path('', views.geeks_view, name='geeks_view'),] Including other URLConf modules It is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows: Python3 from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('gfg_site_app.urls'))] Now if head towards http://127.0.0.1:8000/ then our site will be – In the above example, include statement will look into the URLpatterns list in the gfg_site_app/urls.py And then it will look into all the paths defined in the url.py file and will call the respective views function. Till now we have seen how to show HTML on our website. Now let’s suppose we want to use some kind of relational database that, let’s say SQLite for our site and we want to create a table in this database and want to link this database to our website. Don’t worry we will discuss this in the next section. To tackle the above-said problem Django provides something called Django Models. A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or any other stuff related to the database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table. This section revolves around how one can use Django models to store data in the database conveniently. Moreover, we can use the admin panel of Django to create, update, delete or retrieve fields of a model and various similar operations. Django models provide simplicity, consistency, version control, and advanced metadata handling. Basics of a model include – Each model is a Python class that subclasses django.db.models.Model. Each attribute of the model represents a database field. With all of this, Django gives you an automatically-generated database-access API; see Making queries. Syntax: from django.db import models class ModelName(models.Model): field_name = models.Field(**options) Example: Python3 # import the standard Django Model# from built-in libraryfrom django.db import modelsfrom datetime import datetime class GeeksModel(models.Model): # Field Names title = models.CharField(max_length=200) description = models.TextField() created_on = models.DateTimeField(default=datetime.now) image = models.ImageField(upload_to="images/%Y/%m/%d") # rename the instances of the model # with their title name def __str__(self) -> str: return self.title Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file. So when we run, Python manage.py makemigrations SQL Query to create above Model as a Table is created and Python manage.py migrate creates the table in the database. Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django Creating an instance of Model. To know more visit – Django Basic App Model – Makemigrations and Migrate. Now let’s see how to add data to our newly created SQLite table. Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). We can access the Django ORM by running the following command inside our project directory. python manage.py shell Adding objects To create an object of model Album and save it into the database, we need to write the following command: Python3 from gfg_site_app.models import GeeksModel obj = GeeksModel(title="GeeksforGeeks", description="GFG is a portal for computer science students")obj.save() Retrieving objects To retrieve all the objects of a model, we write the following command: Python3 GeeksModel.objects.all() Output: <QuerySet [<GeeksModel: GeeksforGeeks>]> Modifying existing objects We can modify an existing object as follows: Python3 obj = GeeksModel.objects.get(id=1)obj.title = "GFG"obj.save() GeeksModel.objects.all() Output: <QuerySet [<GeeksModel: GFG>]> Deleting objects To delete a single object, we need to write the following commands: Python3 obj = GeeksModel.objects.get(id=1)obj.delete() GeeksModel.objects.all() Output: (1, {'gfg_site_app.GeeksModel': 1}) <QuerySet []> Refer to the below articles to get more information about Django Models – Django Models ORM – Inserting, Updating & Deleting Data Basic App Model – Makemigrations and Migrate model data types and fields list Add the slug field inside Django Model Intermediate fields in Django Uploading images in Django Change Object Display Name using __str__ function – Django Models Built-in Field Validations – Django Models Custom Field Validations in Django Models How to use Django Field Choices ? Overriding the save method – Django Models When defining the models we used the ImageField for uploading images and we wrote the upload_to parameter as upload_to=”images/%Y/%m/%d”) because this will create a directory data structure of the format image>>year>>month>>date so that tracking images may become easier. Before uploading the image we need to write the below code in the setting.py file. Python3 MEDIA_ROOT = BASE_DIR/'media'MEDIA_URL = '/media/' MEDIA_ROOT is for server path to store files in the computer. MEDIA_URL is the reference URL for browser to access the files over Http In the urls.py we should edit the configuration like this from django.conf import settings from django.conf.urls.static import static if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Let’s see how to upload data into the model using Django Admin Interface. To render a model in Django admin, we need to modify app/admin.py. Go to admin.py in geeks_site_app and enter the following code. Import the corresponding model from models.py and register it to the admin interface. Python3 from django.contrib import adminfrom .models import GeeksModel # Register your models here.admin.site.register(GeeksModel,) Now let’s create a superuser for our project that can have access to the admin area of our site. To create a super user type the below command – python manage.py createsuperuser Now go to http://127.0.0.1:8000/admin on the browser to access the admin interface panel. Give the username and password created for superuser and then the admin dashboard will open and there we will be able to see our Geeks models that we just created. Note: For more information refer to Render Model in Django Admin Interface. Now let’s see how to enter data using the admin dashboard. Now clicking on the Geeks Model we will see something like this – We can click on the Add Geeks Model button on the right top corner and then we will be able to see the fields for adding data. See the below image – After adding the required data and the image field we will see something like this on our admin dashboard – You can also see the media folder in your code editor – Django comes built-in with the SQLite database. We can also see this in the DATABASES dictionary in our settings.py file. Python3 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }} If you want to change this to another database you can change the above dictionary. Let’s suppose we want to change this database to PostgreSQL. Assuming the required dependencies are installed and the PostgreSQL is set up then the DATABASES dictionary will look like – Python3 DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ‘<database_name>’, 'USER': '<database_username>', 'PASSWORD': '<password>', 'HOST': '<database_hostname_or_ip>', 'PORT': '<database_port>', }} Refer to the below articles to get more information about connecting Django to different databases – How to use PostgreSQL Database in Django? Connect Django Project to MongoDB using Django Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs. We can use a single template directory which will be spread over the entire project. For each app of our project, we can create a different template directory. For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage. Configuration Django Templates can be configured in app_name/settings.py, Python3 TEMPLATES = [ { # Template backend to be used, For example Jinja 'BACKEND': 'django.template.backends.django.DjangoTemplates', # directories for templates 'DIRS': [], 'APP_DIRS': True, # options to configure 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] Now let’s create a template directory and add that directory in the above configuration. After creating the templates folder our directory should look like this – Let’s add the location of this directory in our templates dictionary. Python3 TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # adding the location of our templates directory 'DIRS': [BASE_DIR/"templates"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },] After adding the location of the template directory we will create a simple HTML file and name it as index.html and then we will render this file from our view function. HTML file: HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title></head><body> <h1>Welcome to Geeksforgeeks</h1></body></html> To render this HTML on our site we need to use the render function from the django.shortcuts. Below is the updated view function. views.py Python3 from django.shortcuts import render # create a functiondef geeks_view(request): return render(request, "index.html") If we head to our website we will see the HTML data on our site as – The Django Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Let’s see this with an example. We will try to render the content of our database dynamically to our website. First, let’s update our views.py file. In this file we will get our data from our database and then pass this database as a dictionary to our HTML file. views.py Python3 from django.shortcuts import renderfrom .models import GeeksModel # create a functiondef geeks_view(request): content = GeeksModel.objects.all() context = { 'content': content } return render(request, "index.html", context=context) index.html HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Homepage</title></head><body> {% for data in content %} <h2>{{data.title}}</h2> <img src="{{ data.image.url }}" alt=""> <p><strong>Description:</strong>{{data.description}}</p> <p><strong>Created On:</strong>{{data.created_on}}</p> {% endfor %} </body></html> Our website now looks like this – Now if we add more data to our site then that data will also be shown to our site without making any changes to our HTML or views.py. Let’s add some data and then see if it works or not. This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments. Variables Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template. Syntax {{ variable_name }} Tags Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags. Syntax {% tag_name %} Filters Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need. Syntax {{ variable_name | filter_name }} Comments Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled. Syntax {% comment 'comment_name' %} {% endcomment %} The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables. Syntax {% extends 'template_name.html' %} Example: Assume the following directory structure: dir1/ template.html base2.html my/ base3.html base1.html In template.html, the following paths would be valid: HTML {% extends "./base2.html" %}{% extends "../base1.html" %}{% extends "./my/base3.html" %} Refer to the below articles to get more information about Django Templates – Boolean Operators for loop if – Django Templates Template Inheritance When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. Forms are basically used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input as his name, email, password, etc. Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of the work involved in forms: preparing and restructuring data to make it ready for rendering creating HTML forms for the data receiving and processing submitted forms and data from the client Note: All types of work done by Django forms can be done with advanced HTML stuff, but Django makes it easier and efficient especially the validation part. Once you get hold of Django forms you will just forget about HTML forms. Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on. To create a Django form, first create a forms.py inside the app folder. Python3 from django import forms class GeeksForm(forms.Form): title = forms.CharField(max_length=200) description = forms.CharField(widget=forms.Textarea) image = forms.ImageField() Let’s create a different view function for handling forms and we will map this view function to a different URL. In the above created views.py file import the GeeksForm from the forms.py and create the below function. views.py Python3 from .forms import GeeksForm def geeks_form(request): context = {} context['form'] = GeeksForm return render(request, "form.html", context=context) Map this function to a different URL let’s say we will map this function to the http://127.0.0.1:8000/add/. To do this go to urls.py file of the app and another path for above URL. urls.py Python3 from django.urls import pathfrom . import views urlpatterns = [ path('', views.geeks_view, name='geeks_view'), path('add/', views.geeks_form, name="geeks_form")] Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). A form comes with 3 in-built methods that can be used to render Django form fields. {{ form.as_table }} will render them as table cells wrapped in <tr> tags {{ form.as_p }} will render them wrapped in <p> tags {{ form.as_ul }} will render them wrapped in <li> tags Now let’s make the form.html for rendering our form. HTML <form action="" method="POST"> {% csrf_token %} {{form.as_p}} <input type="submit" value="submit"></form> After doing this save all the files and go to http://127.0.0.1:8000/add/ to see the form we created. It should look like this – We can also see that our form is validated automatically. We cannot submit an empty form. Django ModelForm is a class that is used to directly convert a model into a Django form. To create a form directly for our model, dive into forms.py and Enter the following – Python3 from django import formsfrom .models import GeeksModel class GeeksForm(forms.ModelForm): class Meta: model = GeeksModel fields = ['title', 'description', 'image'] Now visit http://127.0.0.1:8000/add/ you will see the same form as above but with less code. Both the Django forms we created are similar but the only difference is the save() method. Every ModelForm has a save() method which saves the database object from the data bound to the form. In simpler words we will be able to save the data to our database using the ModelForm only. For this change the view method as follow – views.py Python3 def geeks_form(request): if request.method == 'POST': form = GeeksForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect("geeks_view") else: # uncomment the below line to see errors # in the form (if any) # print(form.errors) return redirect("geeks_form") else: context = {} context['form'] = GeeksForm return render(request, "form.html", context=context) Note: Add enctype= multipart/form-data to our <form> element in our template tag. If we don’t have this then our request.FILES will always be empty and our form will not validate. Let’s add some data with our form and see if its get saved in our database or not. After hitting submit the form gets saved automatically to database. We can verify it from the above GIF. Refer to the below articles to get more information about Django Forms – Django Forms How to create a form using Django Forms ? Render HTML Forms (GET & POST) in Django Django Form Fields form field custom widgets Initial form data – Django Forms ModelForm – Create form from Models Render Form Fields Manually Django Formsets Django ModelFormSets Handling Ajax request in Django User groups with Custom permissions in Django Django Admin Interface Extending and customizing django-allauth Django – Dealing with warnings Sessions framework using django Django Sign Up and login with confirmation Email How to add Pagination in Django Project? How to Deploy Django project on PythonAnywhere? Google authentication and Fetching mails from scratch ToDo webapp using Django Django News App Weather app using Django Django project to create a Comments System Integrating Facebook Comments Plugin in Django Project Translator App Project using Django Creating a Basic E-commerce Website for Displaying Products Python Django Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n29 Dec, 2021" }, { "code": null, "e": 562, "s": 53, "text": "Python Django is a web framework that allows to quickly create efficient web pages. Django is also called batteries included framework because it provides built-in features such as Django Admin Interface, default database – SQLite3, etc. When you’re building a website, you always need a similar set of components: a way to handle user authentication (signing up, signing in, signing out), a management panel for your website, forms, a way to upload files, etc. Django gives you ready-made components to use." }, { "code": null, "e": 608, "s": 562, "text": "Excellent documentation and high scalability." }, { "code": null, "e": 740, "s": 608, "text": "Used by Top MNCs and Companies, such as Instagram, Disqus, Spotify, Youtube, Bitbucket, Dropbox, etc. and the list is never-ending." }, { "code": null, "e": 947, "s": 740, "text": "Easiest Framework to learn, rapid development, and Batteries fully included. Django is a rapid web development framework that can be used to develop fully fleshed web applications in a short period of time." }, { "code": null, "e": 1218, "s": 947, "text": "The last but not least reason to learn Django is Python, Python has a huge library and features such as Web Scrapping, Machine Learning, Image Processing, Scientific Computing, etc. One can integrate all this with web applications and do lots and lots of advanced stuff." }, { "code": null, "e": 1315, "s": 1218, "text": "Django is based on MVT (Model-View-Template) architecture which has the following three parts – " }, { "code": null, "e": 1573, "s": 1315, "text": "Model: The model is going to act as the interface of your data. It is responsible for maintaining data. It is the logical data structure behind the entire application and is represented by a database (generally relational databases such as MySql, Postgres)." }, { "code": null, "e": 1724, "s": 1573, "text": "View: The View is the user interface that you see in your browser when you render a website. It is represented by HTML/CSS/Javascript and Jinja files." }, { "code": null, "e": 1917, "s": 1724, "text": "Template: A template consists of static parts of the desired HTML output as well as some special syntax describing how dynamic content will be inserted. To check more, visit – Django Templates" }, { "code": null, "e": 1977, "s": 1917, "text": "For more information, refer to Django Project MVT Structure" }, { "code": null, "e": 2423, "s": 1977, "text": "Most of the time when you’ll be working on some Django projects, you’ll find that each project may need a different version of Django. This problem may arise when you install Django in a global or default environment. To overcome this problem we will use virtual environments in Python. This enables us to create multiple different Django environments on a single computer. To create a virtual environment type the below command in the terminal." }, { "code": null, "e": 2446, "s": 2423, "text": "python3 -m venv ./name" }, { "code": null, "e": 2610, "s": 2446, "text": "Here the name suggests the name of the virtual environment. Let’s create our virtual environment with the name as venv only. So the command to create it will be – " }, { "code": null, "e": 2633, "s": 2610, "text": "python3 -m venv ./venv" }, { "code": null, "e": 2734, "s": 2633, "text": "After running the above command you will see a folder named venv with the following sub-directories." }, { "code": null, "e": 2847, "s": 2734, "text": "After creating the virtual environment let’s activate it. To activate it type the below command in the terminal." }, { "code": null, "e": 2874, "s": 2847, "text": "source ./venv/bin/activate" }, { "code": null, "e": 2946, "s": 2874, "text": "In the above command ./ is used to tell the current working directory. " }, { "code": null, "e": 3147, "s": 2946, "text": "Note: If you have your virtual environment set up in another location and your terminal opened up in another location, then provide the location to the venv folder i.e. our virtual environment folder." }, { "code": null, "e": 3277, "s": 3147, "text": "After you run the above command you should see (venv) at the starting of every line of your terminal as shown in the below image." }, { "code": null, "e": 3378, "s": 3277, "text": "We can install Django using the pip command. To install this type the below command in the terminal." }, { "code": null, "e": 3397, "s": 3378, "text": "pip install django" }, { "code": null, "e": 3465, "s": 3397, "text": "For more information, refer to Django Introduction and Installation" }, { "code": null, "e": 3555, "s": 3465, "text": "To initiate a project of Django on Your PC, open Terminal and Enter the following command" }, { "code": null, "e": 3593, "s": 3555, "text": "django-admin startproject projectName" }, { "code": null, "e": 3706, "s": 3593, "text": "A New Folder with the name projectName will be created. To enter in the project using the terminal enter command" }, { "code": null, "e": 3721, "s": 3706, "text": "cd projectName" }, { "code": null, "e": 3846, "s": 3721, "text": "Now let’s un the server and see everything is working fine or not. To run the server type the below command in the terminal." }, { "code": null, "e": 3873, "s": 3846, "text": "python manage.py runserver" }, { "code": null, "e": 3964, "s": 3873, "text": "After running the server go to http://127.0.0.1:8000/ and you’ll see something like this –" }, { "code": null, "e": 4047, "s": 3964, "text": "For more information, refer to How to Create a Basic Project using MVT in Django ?" }, { "code": null, "e": 4353, "s": 4047, "text": "A Django Project when initialized contains basic files by default such as manage.py, view.py, etc. A simple project structure is enough to create a single-page application. Here are the major files and their explanations. Inside the geeks_site folder ( project folder ) there will be the following files- " }, { "code": null, "e": 4392, "s": 4353, "text": "Let’s discuss these files in detail – " }, { "code": null, "e": 4628, "s": 4392, "text": "manage.py: This file is used to interact with your project via the command line(start the server, sync the database... etc). For getting the full list of commands that can be executed by manage.py type this code in the command window- " }, { "code": null, "e": 4650, "s": 4628, "text": "python manage.py help" }, { "code": null, "e": 4874, "s": 4650, "text": "_init_.py: It is a python package. It is invoked when the package or a module in the package is imported. We usually use this to execute package initialization code, for example for the initialization of package-level data." }, { "code": null, "e": 5072, "s": 4874, "text": "settings.py: As the name indicates it contains all the website settings. In this file, we register any applications we create, the location of our static files, database configuration details, etc." }, { "code": null, "e": 5152, "s": 5072, "text": "urls.py: In this file, we store all links of the project and functions to call." }, { "code": null, "e": 5288, "s": 5152, "text": "wsgi.py: This file is used in deploying the project in WSGI. It is used to help your Django application communicate with the webserver." }, { "code": null, "e": 5670, "s": 5288, "text": "Django is famous for its unique and fully managed app structure. For every functionality, an app can be created like a completely independent module. For example, if you are creating a Blog, Separate modules should be created for Comments, Posts, Login/Logout, etc. In Django, these modules are known as apps. There is a different app for each task. Benefits of using Django apps –" }, { "code": null, "e": 5749, "s": 5670, "text": "Django apps are reusable i.e. a Django app can be used with multiple projects." }, { "code": null, "e": 5808, "s": 5749, "text": "We have loosely coupled i.e. almost independent components" }, { "code": null, "e": 5861, "s": 5808, "text": "Multiple developers can work on different components" }, { "code": null, "e": 5942, "s": 5861, "text": "Debugging and code organization are easy. Django has an excellent debugger tool." }, { "code": null, "e": 6048, "s": 5942, "text": "It has in-built features like admin pages etc, which reduces the effort of building the same from scratch" }, { "code": null, "e": 6319, "s": 6048, "text": "Django provides some pre-installed apps for users. To see pre-installed apps, navigate to projectName –> projectName –> settings.py. In your settings.py file, you will find INSTALLED_APPS. Apps listed in INSTALLED_APPS are provided by Django for the developer’s comfort." }, { "code": null, "e": 6327, "s": 6319, "text": "Python3" }, { "code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles',]", "e": 6527, "s": 6327, "text": null }, { "code": null, "e": 6700, "s": 6527, "text": "We can also create our own custom apps. To create a basic app in your Django project you need to go to the directory containing manage.py and from there enter the command :" }, { "code": null, "e": 6737, "s": 6700, "text": "python manage.py startapp projectApp" }, { "code": null, "e": 6827, "s": 6737, "text": "Now let’s create an app called gfg_site_app, so the command to create the app would be – " }, { "code": null, "e": 6866, "s": 6827, "text": "python manage.py startapp gfg_site_app" }, { "code": null, "e": 6918, "s": 6866, "text": "Now you can see your directory structure as under :" }, { "code": null, "e": 7046, "s": 6918, "text": "To consider the app in your project you need to specify your project name in the INSTALLED_APPS list as follows in settings.py:" }, { "code": null, "e": 7054, "s": 7046, "text": "Python3" }, { "code": "INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'gfg_site_app.apps.GfgSiteAppConfig',]", "e": 7295, "s": 7054, "text": null }, { "code": null, "e": 7359, "s": 7295, "text": "For more information, refer to How to Create an App in Django ?" }, { "code": null, "e": 7783, "s": 7359, "text": "A view function is a Python function that takes a Web request and returns a Web response. This response can be the HTML contents of a Web page, or a redirect, or a 404 error, or an XML document, or an image, anything that a web browser can display. Django views are part of the user interface — they usually render the HTML/CSS/Javascript in your Template files into what you see in your browser when you render a web page." }, { "code": null, "e": 7791, "s": 7783, "text": "Python3" }, { "code": "from django.http import HttpResponse # create a functiondef geeks_view(request): return HttpResponse(\"<h1>Welcome to GeeksforGeeks</h1>\")", "e": 7939, "s": 7791, "text": null }, { "code": null, "e": 7988, "s": 7939, "text": "Let’s step through this code one line at a time:" }, { "code": null, "e": 8095, "s": 7988, "text": "First, we import the class HttpResponse from the django.http module, along with Python’s datetime library." }, { "code": null, "e": 8273, "s": 8095, "text": "Next, we define a function called geeks_view. This is the view function. Each view function takes an HttpRequest object as its first parameter, which is typically named request." }, { "code": null, "e": 8423, "s": 8273, "text": "The view returns an HttpResponse object that contains the generated response. Each view function is responsible for returning an HttpResponse object." }, { "code": null, "e": 8556, "s": 8423, "text": "Note: For more info on HttpRequest and HttpResponse visit – Django Request and Response cycle – HttpRequest and HttpResponse Objects" }, { "code": null, "e": 8865, "s": 8556, "text": "The above Function will render the text Welcome to GeeksforGeeks as h1 on the page. Now the question that may be arising is at what URL this function will be called and how will we handle such URLs. Don’t worry we will handle URL in the section but in this section let us continue with the Django views only." }, { "code": null, "e": 8918, "s": 8865, "text": "Django views are divided into two major categories:-" }, { "code": null, "e": 8939, "s": 8918, "text": "Function-Based Views" }, { "code": null, "e": 8957, "s": 8939, "text": "Class-Based Views" }, { "code": null, "e": 9281, "s": 8957, "text": "Function-based views are writer using a function in python which receives as an argument HttpRequest object and returns an HttpResponse Object. Function-based views are generally divided into 4 basic strategies, i.e., CRUD (Create, Retrieve, Update, Delete). CRUD is the base of any framework one is using for development. " }, { "code": null, "e": 9360, "s": 9281, "text": "Refer to the below articles to get more information on Function-Based views – " }, { "code": null, "e": 9428, "s": 9360, "text": "Django CRUD (Create, Retrieve, Update, Delete) Function Based Views" }, { "code": null, "e": 9440, "s": 9428, "text": "Create View" }, { "code": null, "e": 9450, "s": 9440, "text": "List View" }, { "code": null, "e": 9462, "s": 9450, "text": "Detail View" }, { "code": null, "e": 9474, "s": 9462, "text": "Update View" }, { "code": null, "e": 9486, "s": 9474, "text": "Delete View" }, { "code": null, "e": 9715, "s": 9486, "text": "Class-based views provide an alternative way to implement views as Python objects instead of functions. They do not replace function-based views, but have certain differences and advantages when compared to function-based views:" }, { "code": null, "e": 9858, "s": 9715, "text": "Organization of code related to specific HTTP methods (GET, POST, etc.) can be addressed by separate methods instead of conditional branching." }, { "code": null, "e": 9977, "s": 9858, "text": "Object-oriented techniques such as mixins (multiple inheritances) can be used to factor code into reusable components." }, { "code": null, "e": 10053, "s": 9977, "text": "Refer to the below articles to get more information on Class-Based views – " }, { "code": null, "e": 10121, "s": 10053, "text": "Class Based Generic Views Django (Create, Retrieve, Update, Delete)" }, { "code": null, "e": 10132, "s": 10121, "text": "Createview" }, { "code": null, "e": 10141, "s": 10132, "text": "ListView" }, { "code": null, "e": 10152, "s": 10141, "text": "DetailView" }, { "code": null, "e": 10163, "s": 10152, "text": "UpdateView" }, { "code": null, "e": 10174, "s": 10163, "text": "DeleteView" }, { "code": null, "e": 10183, "s": 10174, "text": "FormView" }, { "code": null, "e": 10664, "s": 10183, "text": "In Django, each view needs to be mapped to a corresponding URL pattern. This is done via a Python module called URLConf(URL configuration). Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view." }, { "code": null, "e": 11209, "s": 10664, "text": "Now if we see our project we have created an app called gfg_site, the Python module to be used as URLConf is the value of ROOT_URLCONF in gfg_site/settings.py. By default this is set to ‘gfg_site.urls’. Every URLConf module must contain a variable urlpatterns which is a set of URL patterns to be matched against the requested URL. These patterns will be checked in sequence, until the first match is found. Then the view corresponding to the first match is invoked. If no URL pattern matches, Django invokes an appropriate error handling view." }, { "code": null, "e": 11252, "s": 11209, "text": "Here’s a sample code for gfg_site/urls.py:" }, { "code": null, "e": 11260, "s": 11252, "text": "Python3" }, { "code": "from django.urls import pathfrom . import views urlpatterns = [ path('', views.geeks_view, name='geeks_view'),]", "e": 11376, "s": 11260, "text": null }, { "code": null, "e": 11408, "s": 11376, "text": "Including other URLConf modules" }, { "code": null, "e": 11552, "s": 11408, "text": "It is a good practice to have a URLConf module for every app in Django. This module needs to be included in the root URLConf module as follows:" }, { "code": null, "e": 11560, "s": 11552, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('gfg_site_app.urls'))]", "e": 11726, "s": 11560, "text": null }, { "code": null, "e": 11794, "s": 11726, "text": "Now if head towards http://127.0.0.1:8000/ then our site will be – " }, { "code": null, "e": 12011, "s": 11794, "text": "In the above example, include statement will look into the URLpatterns list in the gfg_site_app/urls.py And then it will look into all the paths defined in the url.py file and will call the respective views function." }, { "code": null, "e": 12316, "s": 12011, "text": "Till now we have seen how to show HTML on our website. Now let’s suppose we want to use some kind of relational database that, let’s say SQLite for our site and we want to create a table in this database and want to link this database to our website. Don’t worry we will discuss this in the next section." }, { "code": null, "e": 12397, "s": 12316, "text": "To tackle the above-said problem Django provides something called Django Models." }, { "code": null, "e": 12862, "s": 12397, "text": " A Django model is the built-in feature that Django uses to create tables, their fields, and various constraints. In short, Django Models is the SQL of Database one uses with Django. SQL (Structured Query Language) is complex and involves a lot of different queries for creating, deleting, updating, or any other stuff related to the database. Django models simplify the tasks and organize tables into models. Generally, each model maps to a single database table." }, { "code": null, "e": 13224, "s": 12862, "text": "This section revolves around how one can use Django models to store data in the database conveniently. Moreover, we can use the admin panel of Django to create, update, delete or retrieve fields of a model and various similar operations. Django models provide simplicity, consistency, version control, and advanced metadata handling. Basics of a model include –" }, { "code": null, "e": 13293, "s": 13224, "text": "Each model is a Python class that subclasses django.db.models.Model." }, { "code": null, "e": 13350, "s": 13293, "text": "Each attribute of the model represents a database field." }, { "code": null, "e": 13453, "s": 13350, "text": "With all of this, Django gives you an automatically-generated database-access API; see Making queries." }, { "code": null, "e": 13461, "s": 13453, "text": "Syntax:" }, { "code": null, "e": 13572, "s": 13461, "text": "from django.db import models \nclass ModelName(models.Model):\n field_name = models.Field(**options)" }, { "code": null, "e": 13581, "s": 13572, "text": "Example:" }, { "code": null, "e": 13589, "s": 13581, "text": "Python3" }, { "code": "# import the standard Django Model# from built-in libraryfrom django.db import modelsfrom datetime import datetime class GeeksModel(models.Model): # Field Names title = models.CharField(max_length=200) description = models.TextField() created_on = models.DateTimeField(default=datetime.now) image = models.ImageField(upload_to=\"images/%Y/%m/%d\") # rename the instances of the model # with their title name def __str__(self) -> str: return self.title", "e": 14075, "s": 13589, "text": null }, { "code": null, "e": 14492, "s": 14075, "text": "Whenever we create a Model, Delete a Model, or update anything in any of models.py of our project. We need to run two commands makemigrations and migrate. makemigrations basically generates the SQL commands for preinstalled apps (which can be viewed in installed apps in settings.py) and your newly created app’s model which you add in installed apps whereas migrate executes those SQL commands in the database file." }, { "code": null, "e": 14508, "s": 14492, "text": "So when we run," }, { "code": null, "e": 14540, "s": 14508, "text": "Python manage.py makemigrations" }, { "code": null, "e": 14598, "s": 14540, "text": "SQL Query to create above Model as a Table is created and" }, { "code": null, "e": 14623, "s": 14598, "text": "Python manage.py migrate" }, { "code": null, "e": 14658, "s": 14623, "text": "creates the table in the database." }, { "code": null, "e": 14884, "s": 14658, "text": "Now we have created a model we can perform various operations such as creating a Row for the table or in terms of Django Creating an instance of Model. To know more visit – Django Basic App Model – Makemigrations and Migrate." }, { "code": null, "e": 14949, "s": 14884, "text": "Now let’s see how to add data to our newly created SQLite table." }, { "code": null, "e": 15206, "s": 14949, "text": "Django lets us interact with its database models, i.e. add, delete, modify and query objects, using a database-abstraction API called ORM(Object Relational Mapper). We can access the Django ORM by running the following command inside our project directory." }, { "code": null, "e": 15229, "s": 15206, "text": "python manage.py shell" }, { "code": null, "e": 15244, "s": 15229, "text": "Adding objects" }, { "code": null, "e": 15350, "s": 15244, "text": "To create an object of model Album and save it into the database, we need to write the following command:" }, { "code": null, "e": 15358, "s": 15350, "text": "Python3" }, { "code": "from gfg_site_app.models import GeeksModel obj = GeeksModel(title=\"GeeksforGeeks\", description=\"GFG is a portal for computer science students\")obj.save()", "e": 15515, "s": 15358, "text": null }, { "code": null, "e": 15534, "s": 15515, "text": "Retrieving objects" }, { "code": null, "e": 15606, "s": 15534, "text": "To retrieve all the objects of a model, we write the following command:" }, { "code": null, "e": 15614, "s": 15606, "text": "Python3" }, { "code": "GeeksModel.objects.all()", "e": 15639, "s": 15614, "text": null }, { "code": null, "e": 15647, "s": 15639, "text": "Output:" }, { "code": null, "e": 15688, "s": 15647, "text": "<QuerySet [<GeeksModel: GeeksforGeeks>]>" }, { "code": null, "e": 15715, "s": 15688, "text": "Modifying existing objects" }, { "code": null, "e": 15760, "s": 15715, "text": "We can modify an existing object as follows:" }, { "code": null, "e": 15768, "s": 15760, "text": "Python3" }, { "code": "obj = GeeksModel.objects.get(id=1)obj.title = \"GFG\"obj.save() GeeksModel.objects.all()", "e": 15856, "s": 15768, "text": null }, { "code": null, "e": 15864, "s": 15856, "text": "Output:" }, { "code": null, "e": 15895, "s": 15864, "text": "<QuerySet [<GeeksModel: GFG>]>" }, { "code": null, "e": 15912, "s": 15895, "text": "Deleting objects" }, { "code": null, "e": 15980, "s": 15912, "text": "To delete a single object, we need to write the following commands:" }, { "code": null, "e": 15988, "s": 15980, "text": "Python3" }, { "code": "obj = GeeksModel.objects.get(id=1)obj.delete() GeeksModel.objects.all()", "e": 16061, "s": 15988, "text": null }, { "code": null, "e": 16069, "s": 16061, "text": "Output:" }, { "code": null, "e": 16105, "s": 16069, "text": "(1, {'gfg_site_app.GeeksModel': 1})" }, { "code": null, "e": 16119, "s": 16105, "text": "<QuerySet []>" }, { "code": null, "e": 16194, "s": 16119, "text": "Refer to the below articles to get more information about Django Models – " }, { "code": null, "e": 16208, "s": 16194, "text": "Django Models" }, { "code": null, "e": 16250, "s": 16208, "text": "ORM – Inserting, Updating & Deleting Data" }, { "code": null, "e": 16295, "s": 16250, "text": "Basic App Model – Makemigrations and Migrate" }, { "code": null, "e": 16328, "s": 16295, "text": "model data types and fields list" }, { "code": null, "e": 16367, "s": 16328, "text": "Add the slug field inside Django Model" }, { "code": null, "e": 16397, "s": 16367, "text": "Intermediate fields in Django" }, { "code": null, "e": 16424, "s": 16397, "text": "Uploading images in Django" }, { "code": null, "e": 16490, "s": 16424, "text": "Change Object Display Name using __str__ function – Django Models" }, { "code": null, "e": 16533, "s": 16490, "text": "Built-in Field Validations – Django Models" }, { "code": null, "e": 16575, "s": 16533, "text": "Custom Field Validations in Django Models" }, { "code": null, "e": 16609, "s": 16575, "text": "How to use Django Field Choices ?" }, { "code": null, "e": 16652, "s": 16609, "text": "Overriding the save method – Django Models" }, { "code": null, "e": 16925, "s": 16652, "text": "When defining the models we used the ImageField for uploading images and we wrote the upload_to parameter as upload_to=”images/%Y/%m/%d”) because this will create a directory data structure of the format image>>year>>month>>date so that tracking images may become easier. " }, { "code": null, "e": 17008, "s": 16925, "text": "Before uploading the image we need to write the below code in the setting.py file." }, { "code": null, "e": 17016, "s": 17008, "text": "Python3" }, { "code": "MEDIA_ROOT = BASE_DIR/'media'MEDIA_URL = '/media/'", "e": 17068, "s": 17016, "text": null }, { "code": null, "e": 17130, "s": 17068, "text": "MEDIA_ROOT is for server path to store files in the computer." }, { "code": null, "e": 17203, "s": 17130, "text": "MEDIA_URL is the reference URL for browser to access the files over Http" }, { "code": null, "e": 17261, "s": 17203, "text": "In the urls.py we should edit the configuration like this" }, { "code": null, "e": 17469, "s": 17261, "text": "from django.conf import settings\nfrom django.conf.urls.static import static\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)" }, { "code": null, "e": 17543, "s": 17469, "text": "Let’s see how to upload data into the model using Django Admin Interface." }, { "code": null, "e": 17759, "s": 17543, "text": "To render a model in Django admin, we need to modify app/admin.py. Go to admin.py in geeks_site_app and enter the following code. Import the corresponding model from models.py and register it to the admin interface." }, { "code": null, "e": 17767, "s": 17759, "text": "Python3" }, { "code": "from django.contrib import adminfrom .models import GeeksModel # Register your models here.admin.site.register(GeeksModel,)", "e": 17892, "s": 17767, "text": null }, { "code": null, "e": 18038, "s": 17892, "text": "Now let’s create a superuser for our project that can have access to the admin area of our site. To create a super user type the below command – " }, { "code": null, "e": 18071, "s": 18038, "text": "python manage.py createsuperuser" }, { "code": null, "e": 18162, "s": 18071, "text": "Now go to http://127.0.0.1:8000/admin on the browser to access the admin interface panel. " }, { "code": null, "e": 18326, "s": 18162, "text": "Give the username and password created for superuser and then the admin dashboard will open and there we will be able to see our Geeks models that we just created." }, { "code": null, "e": 18402, "s": 18326, "text": "Note: For more information refer to Render Model in Django Admin Interface." }, { "code": null, "e": 18528, "s": 18402, "text": "Now let’s see how to enter data using the admin dashboard. Now clicking on the Geeks Model we will see something like this – " }, { "code": null, "e": 18678, "s": 18528, "text": "We can click on the Add Geeks Model button on the right top corner and then we will be able to see the fields for adding data. See the below image – " }, { "code": null, "e": 18787, "s": 18678, "text": "After adding the required data and the image field we will see something like this on our admin dashboard – " }, { "code": null, "e": 18843, "s": 18787, "text": "You can also see the media folder in your code editor –" }, { "code": null, "e": 18965, "s": 18843, "text": "Django comes built-in with the SQLite database. We can also see this in the DATABASES dictionary in our settings.py file." }, { "code": null, "e": 18973, "s": 18965, "text": "Python3" }, { "code": "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', }}", "e": 19096, "s": 18973, "text": null }, { "code": null, "e": 19367, "s": 19096, "text": "If you want to change this to another database you can change the above dictionary. Let’s suppose we want to change this database to PostgreSQL. Assuming the required dependencies are installed and the PostgreSQL is set up then the DATABASES dictionary will look like – " }, { "code": null, "e": 19375, "s": 19367, "text": "Python3" }, { "code": "DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': ‘<database_name>’, 'USER': '<database_username>', 'PASSWORD': '<password>', 'HOST': '<database_hostname_or_ip>', 'PORT': '<database_port>', }}", "e": 19636, "s": 19375, "text": null }, { "code": null, "e": 19738, "s": 19636, "text": "Refer to the below articles to get more information about connecting Django to different databases – " }, { "code": null, "e": 19780, "s": 19738, "text": "How to use PostgreSQL Database in Django?" }, { "code": null, "e": 19827, "s": 19780, "text": "Connect Django Project to MongoDB using Django" }, { "code": null, "e": 20315, "s": 19827, "text": "Templates are the third and most important part of Django’s MVT Structure. A template in Django is basically written in HTML, CSS, and Javascript in a .html file. Django framework efficiently handles and generates dynamically HTML web pages that are visible to the end-user. Django mainly functions with a backend so, in order to provide a frontend and provide a layout to our website, we use templates. There are two methods of adding the template to our website depending on our needs." }, { "code": null, "e": 20400, "s": 20315, "text": "We can use a single template directory which will be spread over the entire project." }, { "code": null, "e": 20475, "s": 20400, "text": "For each app of our project, we can create a different template directory." }, { "code": null, "e": 20741, "s": 20475, "text": "For our current project, we will create a single template directory that will be spread over the entire project for simplicity. App-level templates are generally used in big projects or in case we want to provide a different layout to each component of our webpage." }, { "code": null, "e": 20755, "s": 20741, "text": "Configuration" }, { "code": null, "e": 20817, "s": 20755, "text": "Django Templates can be configured in app_name/settings.py, " }, { "code": null, "e": 20825, "s": 20817, "text": "Python3" }, { "code": "TEMPLATES = [ { # Template backend to be used, For example Jinja 'BACKEND': 'django.template.backends.django.DjangoTemplates', # directories for templates 'DIRS': [], 'APP_DIRS': True, # options to configure 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]", "e": 21438, "s": 20825, "text": null }, { "code": null, "e": 21602, "s": 21438, "text": "Now let’s create a template directory and add that directory in the above configuration. After creating the templates folder our directory should look like this – " }, { "code": null, "e": 21672, "s": 21602, "text": "Let’s add the location of this directory in our templates dictionary." }, { "code": null, "e": 21680, "s": 21672, "text": "Python3" }, { "code": "TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', # adding the location of our templates directory 'DIRS': [BASE_DIR/\"templates\"], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, },]", "e": 22234, "s": 21680, "text": null }, { "code": null, "e": 22404, "s": 22234, "text": "After adding the location of the template directory we will create a simple HTML file and name it as index.html and then we will render this file from our view function." }, { "code": null, "e": 22415, "s": 22404, "text": "HTML file:" }, { "code": null, "e": 22420, "s": 22415, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Homepage</title></head><body> <h1>Welcome to Geeksforgeeks</h1></body></html>", "e": 22706, "s": 22420, "text": null }, { "code": null, "e": 22836, "s": 22706, "text": "To render this HTML on our site we need to use the render function from the django.shortcuts. Below is the updated view function." }, { "code": null, "e": 22845, "s": 22836, "text": "views.py" }, { "code": null, "e": 22853, "s": 22845, "text": "Python3" }, { "code": "from django.shortcuts import render # create a functiondef geeks_view(request): return render(request, \"index.html\")", "e": 22980, "s": 22853, "text": null }, { "code": null, "e": 23049, "s": 22980, "text": "If we head to our website we will see the HTML data on our site as –" }, { "code": null, "e": 23308, "s": 23049, "text": "The Django Templates not only show static data but also the data from different databases connected to the application through a context dictionary. Let’s see this with an example. We will try to render the content of our database dynamically to our website." }, { "code": null, "e": 23461, "s": 23308, "text": "First, let’s update our views.py file. In this file we will get our data from our database and then pass this database as a dictionary to our HTML file." }, { "code": null, "e": 23470, "s": 23461, "text": "views.py" }, { "code": null, "e": 23478, "s": 23470, "text": "Python3" }, { "code": "from django.shortcuts import renderfrom .models import GeeksModel # create a functiondef geeks_view(request): content = GeeksModel.objects.all() context = { 'content': content } return render(request, \"index.html\", context=context)", "e": 23736, "s": 23478, "text": null }, { "code": null, "e": 23747, "s": 23736, "text": "index.html" }, { "code": null, "e": 23752, "s": 23747, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Homepage</title></head><body> {% for data in content %} <h2>{{data.title}}</h2> <img src=\"{{ data.image.url }}\" alt=\"\"> <p><strong>Description:</strong>{{data.description}}</p> <p><strong>Created On:</strong>{{data.created_on}}</p> {% endfor %} </body></html>", "e": 24246, "s": 23752, "text": null }, { "code": null, "e": 24281, "s": 24246, "text": "Our website now looks like this – " }, { "code": null, "e": 24468, "s": 24281, "text": "Now if we add more data to our site then that data will also be shown to our site without making any changes to our HTML or views.py. Let’s add some data and then see if it works or not." }, { "code": null, "e": 25005, "s": 24468, "text": "This is one of the most important facilities provided by Django Templates. A Django template is a text document or a Python string marked-up using the Django template language. Some constructs are recognized and interpreted by the template engine. The main ones are variables and tags. As we used for the loop in the above example, we used it as a tag. similarly, we can use various other conditions such as if, else, if-else, empty, etc. The main characteristics of Django Template language are Variables, Tags, Filters, and Comments. " }, { "code": null, "e": 25015, "s": 25005, "text": "Variables" }, { "code": null, "e": 25220, "s": 25015, "text": "Variables output a value from the context, which is a dict-like object mapping keys to values. The context object we sent from the view can be accessed in the template using variables of Django Template. " }, { "code": null, "e": 25227, "s": 25220, "text": "Syntax" }, { "code": null, "e": 25247, "s": 25227, "text": "{{ variable_name }}" }, { "code": null, "e": 25252, "s": 25247, "text": "Tags" }, { "code": null, "e": 25491, "s": 25252, "text": "Tags provide arbitrary logic in the rendering process. For example, a tag can output content, serve as a control structure e.g. an “if” statement or a “for” loop, grab content from a database, or even enable access to other template tags." }, { "code": null, "e": 25498, "s": 25491, "text": "Syntax" }, { "code": null, "e": 25513, "s": 25498, "text": "{% tag_name %}" }, { "code": null, "e": 25521, "s": 25513, "text": "Filters" }, { "code": null, "e": 25831, "s": 25521, "text": "Django Template Engine provides filters that are used to transform the values of variables and tag arguments. We have already discussed major Django Template Tags. Tags can’t modify the value of a variable whereas filters can be used for incrementing the value of a variable or modifying it to one’s own need." }, { "code": null, "e": 25838, "s": 25831, "text": "Syntax" }, { "code": null, "e": 25872, "s": 25838, "text": "{{ variable_name | filter_name }}" }, { "code": null, "e": 25881, "s": 25872, "text": "Comments" }, { "code": null, "e": 26101, "s": 25881, "text": "Template ignores everything between {% comment %} and {% end comment %}. An optional note may be inserted in the first tag. For example, this is useful when commenting out code for documenting why the code was disabled." }, { "code": null, "e": 26108, "s": 26101, "text": "Syntax" }, { "code": null, "e": 26154, "s": 26108, "text": "{% comment 'comment_name' %}\n{% endcomment %}" }, { "code": null, "e": 26605, "s": 26154, "text": "The most powerful and thus the most complex part of Django’s template engine is template inheritance. Template inheritance allows you to build a base “skeleton” template that contains all the common elements of your site and defines blocks that child templates can override. extends tag is used for the inheritance of templates in Django. One needs to repeat the same code again and again. Using extends we can inherit templates as well as variables." }, { "code": null, "e": 26612, "s": 26605, "text": "Syntax" }, { "code": null, "e": 26648, "s": 26612, "text": "{% extends 'template_name.html' %} " }, { "code": null, "e": 26699, "s": 26648, "text": "Example: Assume the following directory structure:" }, { "code": null, "e": 26772, "s": 26699, "text": "dir1/\n template.html\n base2.html\n my/\n base3.html\nbase1.html" }, { "code": null, "e": 26827, "s": 26772, "text": "In template.html, the following paths would be valid: " }, { "code": null, "e": 26832, "s": 26827, "text": "HTML" }, { "code": "{% extends \"./base2.html\" %}{% extends \"../base1.html\" %}{% extends \"./my/base3.html\" %}", "e": 26921, "s": 26832, "text": null }, { "code": null, "e": 26999, "s": 26921, "text": "Refer to the below articles to get more information about Django Templates – " }, { "code": null, "e": 27017, "s": 26999, "text": "Boolean Operators" }, { "code": null, "e": 27026, "s": 27017, "text": "for loop" }, { "code": null, "e": 27048, "s": 27026, "text": "if – Django Templates" }, { "code": null, "e": 27069, "s": 27048, "text": "Template Inheritance" }, { "code": null, "e": 27586, "s": 27069, "text": "When one creates a Form class, the most important part is defining the fields of the form. Each field has custom validation logic, along with a few other hooks. Forms are basically used for taking input from the user in some manner and using that information for logical operations on databases. For example, Registering a user by taking input as his name, email, password, etc. Django maps the fields defined in Django forms into HTML input fields. Django handles three distinct parts of the work involved in forms:" }, { "code": null, "e": 27650, "s": 27586, "text": "preparing and restructuring data to make it ready for rendering" }, { "code": null, "e": 27683, "s": 27650, "text": "creating HTML forms for the data" }, { "code": null, "e": 27749, "s": 27683, "text": "receiving and processing submitted forms and data from the client" }, { "code": null, "e": 27978, "s": 27749, "text": "Note: All types of work done by Django forms can be done with advanced HTML stuff, but Django makes it easier and efficient especially the validation part. Once you get hold of Django forms you will just forget about HTML forms." }, { "code": null, "e": 28244, "s": 27978, "text": "Creating a form in Django is completely similar to creating a model, one needs to specify what fields would exist in the form and of what type. For example, to input, a registration form one might need First Name (CharField), Roll Number (IntegerField), and so on. " }, { "code": null, "e": 28316, "s": 28244, "text": "To create a Django form, first create a forms.py inside the app folder." }, { "code": null, "e": 28324, "s": 28316, "text": "Python3" }, { "code": "from django import forms class GeeksForm(forms.Form): title = forms.CharField(max_length=200) description = forms.CharField(widget=forms.Textarea) image = forms.ImageField()", "e": 28510, "s": 28324, "text": null }, { "code": null, "e": 28728, "s": 28510, "text": "Let’s create a different view function for handling forms and we will map this view function to a different URL. In the above created views.py file import the GeeksForm from the forms.py and create the below function." }, { "code": null, "e": 28737, "s": 28728, "text": "views.py" }, { "code": null, "e": 28745, "s": 28737, "text": "Python3" }, { "code": "from .forms import GeeksForm def geeks_form(request): context = {} context['form'] = GeeksForm return render(request, \"form.html\", context=context)", "e": 28903, "s": 28745, "text": null }, { "code": null, "e": 29084, "s": 28903, "text": "Map this function to a different URL let’s say we will map this function to the http://127.0.0.1:8000/add/. To do this go to urls.py file of the app and another path for above URL." }, { "code": null, "e": 29092, "s": 29084, "text": "urls.py" }, { "code": null, "e": 29100, "s": 29092, "text": "Python3" }, { "code": "from django.urls import pathfrom . import views urlpatterns = [ path('', views.geeks_view, name='geeks_view'), path('add/', views.geeks_form, name=\"geeks_form\")]", "e": 29269, "s": 29100, "text": null }, { "code": null, "e": 29527, "s": 29269, "text": "Django form fields have several built-in methods to ease the work of the developer but sometimes one needs to implement things manually for customizing User Interface(UI). A form comes with 3 in-built methods that can be used to render Django form fields. " }, { "code": null, "e": 29600, "s": 29527, "text": "{{ form.as_table }} will render them as table cells wrapped in <tr> tags" }, { "code": null, "e": 29653, "s": 29600, "text": "{{ form.as_p }} will render them wrapped in <p> tags" }, { "code": null, "e": 29708, "s": 29653, "text": "{{ form.as_ul }} will render them wrapped in <li> tags" }, { "code": null, "e": 29761, "s": 29708, "text": "Now let’s make the form.html for rendering our form." }, { "code": null, "e": 29766, "s": 29761, "text": "HTML" }, { "code": "<form action=\"\" method=\"POST\"> {% csrf_token %} {{form.as_p}} <input type=\"submit\" value=\"submit\"></form>", "e": 29881, "s": 29766, "text": null }, { "code": null, "e": 30010, "s": 29881, "text": "After doing this save all the files and go to http://127.0.0.1:8000/add/ to see the form we created. It should look like this – " }, { "code": null, "e": 30100, "s": 30010, "text": "We can also see that our form is validated automatically. We cannot submit an empty form." }, { "code": null, "e": 30275, "s": 30100, "text": "Django ModelForm is a class that is used to directly convert a model into a Django form. To create a form directly for our model, dive into forms.py and Enter the following –" }, { "code": null, "e": 30283, "s": 30275, "text": "Python3" }, { "code": "from django import formsfrom .models import GeeksModel class GeeksForm(forms.ModelForm): class Meta: model = GeeksModel fields = ['title', 'description', 'image']", "e": 30466, "s": 30283, "text": null }, { "code": null, "e": 30560, "s": 30466, "text": "Now visit http://127.0.0.1:8000/add/ you will see the same form as above but with less code. " }, { "code": null, "e": 30889, "s": 30560, "text": "Both the Django forms we created are similar but the only difference is the save() method. Every ModelForm has a save() method which saves the database object from the data bound to the form. In simpler words we will be able to save the data to our database using the ModelForm only. For this change the view method as follow – " }, { "code": null, "e": 30898, "s": 30889, "text": "views.py" }, { "code": null, "e": 30906, "s": 30898, "text": "Python3" }, { "code": "def geeks_form(request): if request.method == 'POST': form = GeeksForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect(\"geeks_view\") else: # uncomment the below line to see errors # in the form (if any) # print(form.errors) return redirect(\"geeks_form\") else: context = {} context['form'] = GeeksForm return render(request, \"form.html\", context=context)", "e": 31407, "s": 30906, "text": null }, { "code": null, "e": 31587, "s": 31407, "text": "Note: Add enctype= multipart/form-data to our <form> element in our template tag. If we don’t have this then our request.FILES will always be empty and our form will not validate." }, { "code": null, "e": 31671, "s": 31587, "text": " Let’s add some data with our form and see if its get saved in our database or not." }, { "code": null, "e": 31776, "s": 31671, "text": "After hitting submit the form gets saved automatically to database. We can verify it from the above GIF." }, { "code": null, "e": 31850, "s": 31776, "text": "Refer to the below articles to get more information about Django Forms – " }, { "code": null, "e": 31863, "s": 31850, "text": "Django Forms" }, { "code": null, "e": 31905, "s": 31863, "text": "How to create a form using Django Forms ?" }, { "code": null, "e": 31946, "s": 31905, "text": "Render HTML Forms (GET & POST) in Django" }, { "code": null, "e": 31965, "s": 31946, "text": "Django Form Fields" }, { "code": null, "e": 31991, "s": 31965, "text": "form field custom widgets" }, { "code": null, "e": 32024, "s": 31991, "text": "Initial form data – Django Forms" }, { "code": null, "e": 32060, "s": 32024, "text": "ModelForm – Create form from Models" }, { "code": null, "e": 32088, "s": 32060, "text": "Render Form Fields Manually" }, { "code": null, "e": 32104, "s": 32088, "text": "Django Formsets" }, { "code": null, "e": 32125, "s": 32104, "text": "Django ModelFormSets" }, { "code": null, "e": 32157, "s": 32125, "text": "Handling Ajax request in Django" }, { "code": null, "e": 32203, "s": 32157, "text": "User groups with Custom permissions in Django" }, { "code": null, "e": 32226, "s": 32203, "text": "Django Admin Interface" }, { "code": null, "e": 32267, "s": 32226, "text": "Extending and customizing django-allauth" }, { "code": null, "e": 32298, "s": 32267, "text": "Django – Dealing with warnings" }, { "code": null, "e": 32330, "s": 32298, "text": "Sessions framework using django" }, { "code": null, "e": 32379, "s": 32330, "text": "Django Sign Up and login with confirmation Email" }, { "code": null, "e": 32420, "s": 32379, "text": "How to add Pagination in Django Project?" }, { "code": null, "e": 32468, "s": 32420, "text": "How to Deploy Django project on PythonAnywhere?" }, { "code": null, "e": 32522, "s": 32468, "text": "Google authentication and Fetching mails from scratch" }, { "code": null, "e": 32547, "s": 32522, "text": "ToDo webapp using Django" }, { "code": null, "e": 32563, "s": 32547, "text": "Django News App" }, { "code": null, "e": 32588, "s": 32563, "text": "Weather app using Django" }, { "code": null, "e": 32631, "s": 32588, "text": "Django project to create a Comments System" }, { "code": null, "e": 32686, "s": 32631, "text": "Integrating Facebook Comments Plugin in Django Project" }, { "code": null, "e": 32722, "s": 32686, "text": "Translator App Project using Django" }, { "code": null, "e": 32782, "s": 32722, "text": "Creating a Basic E-commerce Website for Displaying Products" }, { "code": null, "e": 32796, "s": 32782, "text": "Python Django" }, { "code": null, "e": 32803, "s": 32796, "text": "Python" } ]
Flappy Bird Game in JavaScript
19 Mar, 2021 Flappy Bird is an endless game that involves a bird that the player can control. The player has to save the bird from colliding with the hurdles like pipes. Each time the bird passes through the pipes, the score gets incremented by one. The game ends when the bird collides with the pipes or falls down due to gravity. The sections below describe the steps that have to be taken for building this game. HTML Section: In this section, the elements of the game are created and loaded. The images for the background, bird, hurdles and the score elements are selected. Next, we create and link the style.css and index.js file. HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"></head> <body> <div class="background"></div> <img class="bird" src="logo.png" alt="bird-img"> <div class="message"> Press Enter To Start Game </div> <div class="score"> <span class="score_title"></span> <span class="score_val"></span> </div> <script src="gfg.js"></script></body> </html> CSS Section: In this section, the size, position and style of the game objects are modified according to need. CSS * { margin: 0; padding: 0; box-sizing: border-box;} body { height: 100vh; width: 100vw;} .background { height: 100vh; width: 100vw; background-color: skyblue;} .bird { height: 100px; width: 160px; position: fixed; top: 40vh; left: 30vw; z-index: 100;} .pipe_sprite { position: fixed; top: 40vh; left: 100vw; height: 70vh; width: 6vw; background-color: green;} .message { position: fixed; z-index: 10; height: 10vh; font-size: 10vh; font-weight: 100; color: black; top: 12vh; left: 20vw; text-align: center;} .score { position: fixed; z-index: 10; height: 10vh; font-size: 10vh; font-weight: 100; color: goldenrod; top: 0; left: 0;} .score_val { color: gold;} JavaScript Section: This section contains the part of the code that controls the game state and the moving objects. The following steps have to be followed in this section. Get a reference to bird and background image in JavaScript file. Set some values for background scrolling speed, the flying speed of the bird, and gravity. Create the infinite scrolling background. A guide for doing this can be read from this link. Add an event listener to listen for the “enter” keypress to change the game state to the play state and apply gravity to the bird by decreasing the gravity value from the bird’s y-coordinate every frame. Generate hurdles (pipes) at the end of the view width so that they are not visible initially, but as the background moves, decrease the pipe’s x-coordinate by the background scrolling value so that it looks like the bird is moving. Apply collision with ground and pipes and if the bird collides then change the game state to end state and show a message to restart the game. Increment score value after every successful navigation between the pipes. JavaScript // Background scrolling speedlet move_speed = 3; // Gravity constant valuelet gravity = 0.5; // Getting reference to the bird elementlet bird = document.querySelector('.bird'); // Getting bird element propertieslet bird_props = bird.getBoundingClientRect();let background = document.querySelector('.background') .getBoundingClientRect(); // Getting reference to the score elementlet score_val = document.querySelector('.score_val');let message = document.querySelector('.message');let score_title = document.querySelector('.score_title'); // Setting initial game state to startlet game_state = 'Start'; // Add an eventlistener for key pressesdocument.addEventListener('keydown', (e) => { // Start the game if enter key is pressed if (e.key == 'Enter' && game_state != 'Play') { document.querySelectorAll('.pipe_sprite') .forEach((e) => { e.remove(); }); bird.style.top = '40vh'; game_state = 'Play'; message.innerHTML = ''; score_title.innerHTML = 'Score : '; score_val.innerHTML = '0'; play(); }});function play() { function move() { // Detect if game has ended if (game_state != 'Play') return; // Getting reference to all the pipe elements let pipe_sprite = document.querySelectorAll('.pipe_sprite'); pipe_sprite.forEach((element) => { let pipe_sprite_props = element.getBoundingClientRect(); bird_props = bird.getBoundingClientRect(); // Delete the pipes if they have moved out // of the screen hence saving memory if (pipe_sprite_props.right <= 0) { element.remove(); } else { // Collision detection with bird and pipes if ( bird_props.left < pipe_sprite_props.left + pipe_sprite_props.width && bird_props.left + bird_props.width > pipe_sprite_props.left && bird_props.top < pipe_sprite_props.top + pipe_sprite_props.height && bird_props.top + bird_props.height > pipe_sprite_props.top ) { // Change game state and end the game // if collision occurs game_state = 'End'; message.innerHTML = 'Press Enter To Restart'; message.style.left = '28vw'; return; } else { // Increase the score if player // has the successfully dodged the if ( pipe_sprite_props.right < bird_props.left && pipe_sprite_props.right + move_speed >= bird_props.left && element.increase_score == '1' ) { score_val.innerHTML = +score_val.innerHTML + 1; } element.style.left = pipe_sprite_props.left - move_speed + 'px'; } } }); requestAnimationFrame(move); } requestAnimationFrame(move); let bird_dy = 0; function apply_gravity() { if (game_state != 'Play') return; bird_dy = bird_dy + gravity; document.addEventListener('keydown', (e) => { if (e.key == 'ArrowUp' || e.key == ' ') { bird_dy = -7.6; } }); // Collision detection with bird and // window top and bottom if (bird_props.top <= 0 || bird_props.bottom >= background.bottom) { game_state = 'End'; message.innerHTML = 'Press Enter To Restart'; message.style.left = '28vw'; return; } bird.style.top = bird_props.top + bird_dy + 'px'; bird_props = bird.getBoundingClientRect(); requestAnimationFrame(apply_gravity); } requestAnimationFrame(apply_gravity); let pipe_seperation = 0; // Constant value for the gap between two pipes let pipe_gap = 35; function create_pipe() { if (game_state != 'Play') return; // Create another set of pipes // if distance between two pipe has exceeded // a predefined value if (pipe_seperation > 115) { pipe_seperation = 0 // Calculate random position of pipes on y axis let pipe_posi = Math.floor(Math.random() * 43) + 8; let pipe_sprite_inv = document.createElement('div'); pipe_sprite_inv.className = 'pipe_sprite'; pipe_sprite_inv.style.top = pipe_posi - 70 + 'vh'; pipe_sprite_inv.style.left = '100vw'; // Append the created pipe element in DOM document.body.appendChild(pipe_sprite_inv); let pipe_sprite = document.createElement('div'); pipe_sprite.className = 'pipe_sprite'; pipe_sprite.style.top = pipe_posi + pipe_gap + 'vh'; pipe_sprite.style.left = '100vw'; pipe_sprite.increase_score = '1'; // Append the created pipe element in DOM document.body.appendChild(pipe_sprite); } pipe_seperation++; requestAnimationFrame(create_pipe); } requestAnimationFrame(create_pipe);} Output: CSS-Questions HTML-Questions JavaScript-Questions Technical Scripter 2020 CSS HTML JavaScript Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 52, "s": 24, "text": "\n19 Mar, 2021" }, { "code": null, "e": 455, "s": 52, "text": "Flappy Bird is an endless game that involves a bird that the player can control. The player has to save the bird from colliding with the hurdles like pipes. Each time the bird passes through the pipes, the score gets incremented by one. The game ends when the bird collides with the pipes or falls down due to gravity. The sections below describe the steps that have to be taken for building this game." }, { "code": null, "e": 675, "s": 455, "text": "HTML Section: In this section, the elements of the game are created and loaded. The images for the background, bird, hurdles and the score elements are selected. Next, we create and link the style.css and index.js file." }, { "code": null, "e": 680, "s": 675, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <div class=\"background\"></div> <img class=\"bird\" src=\"logo.png\" alt=\"bird-img\"> <div class=\"message\"> Press Enter To Start Game </div> <div class=\"score\"> <span class=\"score_title\"></span> <span class=\"score_val\"></span> </div> <script src=\"gfg.js\"></script></body> </html>", "e": 1086, "s": 680, "text": null }, { "code": null, "e": 1197, "s": 1086, "text": "CSS Section: In this section, the size, position and style of the game objects are modified according to need." }, { "code": null, "e": 1201, "s": 1197, "text": "CSS" }, { "code": "* { margin: 0; padding: 0; box-sizing: border-box;} body { height: 100vh; width: 100vw;} .background { height: 100vh; width: 100vw; background-color: skyblue;} .bird { height: 100px; width: 160px; position: fixed; top: 40vh; left: 30vw; z-index: 100;} .pipe_sprite { position: fixed; top: 40vh; left: 100vw; height: 70vh; width: 6vw; background-color: green;} .message { position: fixed; z-index: 10; height: 10vh; font-size: 10vh; font-weight: 100; color: black; top: 12vh; left: 20vw; text-align: center;} .score { position: fixed; z-index: 10; height: 10vh; font-size: 10vh; font-weight: 100; color: goldenrod; top: 0; left: 0;} .score_val { color: gold;}", "e": 1981, "s": 1201, "text": null }, { "code": null, "e": 2154, "s": 1981, "text": "JavaScript Section: This section contains the part of the code that controls the game state and the moving objects. The following steps have to be followed in this section." }, { "code": null, "e": 2219, "s": 2154, "text": "Get a reference to bird and background image in JavaScript file." }, { "code": null, "e": 2310, "s": 2219, "text": "Set some values for background scrolling speed, the flying speed of the bird, and gravity." }, { "code": null, "e": 2403, "s": 2310, "text": "Create the infinite scrolling background. A guide for doing this can be read from this link." }, { "code": null, "e": 2607, "s": 2403, "text": "Add an event listener to listen for the “enter” keypress to change the game state to the play state and apply gravity to the bird by decreasing the gravity value from the bird’s y-coordinate every frame." }, { "code": null, "e": 2839, "s": 2607, "text": "Generate hurdles (pipes) at the end of the view width so that they are not visible initially, but as the background moves, decrease the pipe’s x-coordinate by the background scrolling value so that it looks like the bird is moving." }, { "code": null, "e": 2982, "s": 2839, "text": "Apply collision with ground and pipes and if the bird collides then change the game state to end state and show a message to restart the game." }, { "code": null, "e": 3057, "s": 2982, "text": "Increment score value after every successful navigation between the pipes." }, { "code": null, "e": 3068, "s": 3057, "text": "JavaScript" }, { "code": "// Background scrolling speedlet move_speed = 3; // Gravity constant valuelet gravity = 0.5; // Getting reference to the bird elementlet bird = document.querySelector('.bird'); // Getting bird element propertieslet bird_props = bird.getBoundingClientRect();let background = document.querySelector('.background') .getBoundingClientRect(); // Getting reference to the score elementlet score_val = document.querySelector('.score_val');let message = document.querySelector('.message');let score_title = document.querySelector('.score_title'); // Setting initial game state to startlet game_state = 'Start'; // Add an eventlistener for key pressesdocument.addEventListener('keydown', (e) => { // Start the game if enter key is pressed if (e.key == 'Enter' && game_state != 'Play') { document.querySelectorAll('.pipe_sprite') .forEach((e) => { e.remove(); }); bird.style.top = '40vh'; game_state = 'Play'; message.innerHTML = ''; score_title.innerHTML = 'Score : '; score_val.innerHTML = '0'; play(); }});function play() { function move() { // Detect if game has ended if (game_state != 'Play') return; // Getting reference to all the pipe elements let pipe_sprite = document.querySelectorAll('.pipe_sprite'); pipe_sprite.forEach((element) => { let pipe_sprite_props = element.getBoundingClientRect(); bird_props = bird.getBoundingClientRect(); // Delete the pipes if they have moved out // of the screen hence saving memory if (pipe_sprite_props.right <= 0) { element.remove(); } else { // Collision detection with bird and pipes if ( bird_props.left < pipe_sprite_props.left + pipe_sprite_props.width && bird_props.left + bird_props.width > pipe_sprite_props.left && bird_props.top < pipe_sprite_props.top + pipe_sprite_props.height && bird_props.top + bird_props.height > pipe_sprite_props.top ) { // Change game state and end the game // if collision occurs game_state = 'End'; message.innerHTML = 'Press Enter To Restart'; message.style.left = '28vw'; return; } else { // Increase the score if player // has the successfully dodged the if ( pipe_sprite_props.right < bird_props.left && pipe_sprite_props.right + move_speed >= bird_props.left && element.increase_score == '1' ) { score_val.innerHTML = +score_val.innerHTML + 1; } element.style.left = pipe_sprite_props.left - move_speed + 'px'; } } }); requestAnimationFrame(move); } requestAnimationFrame(move); let bird_dy = 0; function apply_gravity() { if (game_state != 'Play') return; bird_dy = bird_dy + gravity; document.addEventListener('keydown', (e) => { if (e.key == 'ArrowUp' || e.key == ' ') { bird_dy = -7.6; } }); // Collision detection with bird and // window top and bottom if (bird_props.top <= 0 || bird_props.bottom >= background.bottom) { game_state = 'End'; message.innerHTML = 'Press Enter To Restart'; message.style.left = '28vw'; return; } bird.style.top = bird_props.top + bird_dy + 'px'; bird_props = bird.getBoundingClientRect(); requestAnimationFrame(apply_gravity); } requestAnimationFrame(apply_gravity); let pipe_seperation = 0; // Constant value for the gap between two pipes let pipe_gap = 35; function create_pipe() { if (game_state != 'Play') return; // Create another set of pipes // if distance between two pipe has exceeded // a predefined value if (pipe_seperation > 115) { pipe_seperation = 0 // Calculate random position of pipes on y axis let pipe_posi = Math.floor(Math.random() * 43) + 8; let pipe_sprite_inv = document.createElement('div'); pipe_sprite_inv.className = 'pipe_sprite'; pipe_sprite_inv.style.top = pipe_posi - 70 + 'vh'; pipe_sprite_inv.style.left = '100vw'; // Append the created pipe element in DOM document.body.appendChild(pipe_sprite_inv); let pipe_sprite = document.createElement('div'); pipe_sprite.className = 'pipe_sprite'; pipe_sprite.style.top = pipe_posi + pipe_gap + 'vh'; pipe_sprite.style.left = '100vw'; pipe_sprite.increase_score = '1'; // Append the created pipe element in DOM document.body.appendChild(pipe_sprite); } pipe_seperation++; requestAnimationFrame(create_pipe); } requestAnimationFrame(create_pipe);}", "e": 7829, "s": 3068, "text": null }, { "code": null, "e": 7837, "s": 7829, "text": "Output:" }, { "code": null, "e": 7851, "s": 7837, "text": "CSS-Questions" }, { "code": null, "e": 7866, "s": 7851, "text": "HTML-Questions" }, { "code": null, "e": 7887, "s": 7866, "text": "JavaScript-Questions" }, { "code": null, "e": 7911, "s": 7887, "text": "Technical Scripter 2020" }, { "code": null, "e": 7915, "s": 7911, "text": "CSS" }, { "code": null, "e": 7920, "s": 7915, "text": "HTML" }, { "code": null, "e": 7931, "s": 7920, "text": "JavaScript" }, { "code": null, "e": 7950, "s": 7931, "text": "Technical Scripter" }, { "code": null, "e": 7967, "s": 7950, "text": "Web Technologies" }, { "code": null, "e": 7972, "s": 7967, "text": "HTML" }, { "code": null, "e": 8070, "s": 7972, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8109, "s": 8070, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 8148, "s": 8109, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 8187, "s": 8148, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 8216, "s": 8187, "text": "Form validation using jQuery" }, { "code": null, "e": 8253, "s": 8216, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 8277, "s": 8253, "text": "REST API (Introduction)" }, { "code": null, "e": 8330, "s": 8277, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 8390, "s": 8330, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 8451, "s": 8390, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
How to use Google Colab
01 May, 2019 If you want to create a machine learning model but say you don’t have a computer that can take the workload, Google Colab is the platform for you. Even if you have a GPU or a good computer creating a local environment with anaconda and installing packages and resolving installation issues are a hassle.Colaboratory is a free Jupyter notebook environment provided by Google where you can use free GPUs and TPUs which can solve all these issues. To start working with Colab you first need to log in to your google account, then go to this link https://colab.research.google.com. Opening Jupyter Notebook:On opening the website you will see a pop-up containing following tabs – EXAMPLES: Contain a number of Jupyter notebooks of various examples.RECENT: Jupyter notebook you have recently worked with.GOOGLE DRIVE: Jupyter notebook in your google drive.GITHUB: You can add Jupyter notebook from your GitHub but you first need to connect Colab with GitHub.UPLOAD: Upload from your local directory. Else you can create a new Jupyter notebook by clicking New Python3 Notebook or New Python2 Notebook at the bottom right corner. Notebook’s Description:On creating a new notebook, it will create a Jupyter notebook with Untitled0.ipynb and save it to your google drive in a folder named Colab Notebooks. Now as it is essentially a Jupyter notebook, all commands of Jupyter notebooks will work here. Though, you can refer the details in Getting started with Jupyter Notebook. Let’s talk about what different here. Change Runtime Environment:Click the “Runtime” dropdown menu. Select “Change runtime type”. Select python2 or 3 from “Runtime type” dropdown menu. Use GPU and TPU:Click the “Runtime” dropdown menu. Select “Change runtime type”. Now select anything(GPU, CPU, None) you want in the “Hardware accelerator” dropdown menu. Verify GPU: import tensorflow as tftf.test.gpu_device_name() If gpu is connected it will output following – '/device:GPU:0' Otherwise, it will output following '' Verify TPU: import os if 'COLAB_TPU_ADDR' not in os.environ: print('Not connected to TPU')else: print("Connected to TPU") If gpu is connected it will output following Connected to TPU Otherwise, it will output following Not connected to TPU Install Python packages –Use can use pip to install any package. For example: ! pip install pandas Clone GitHub repos:Use git clone command. For example: ! git clone https://github.com/souvik3333/Testing-and-Debugging-Tools Upload File: from google.colab import filesuploaded = files.upload() Select “Choose file” and upload the file you want. Enable third-party cookies if they are disabled. Then you can save it in a dataframe. import iodf2 = pd.read_csv(io.BytesIO(uploaded['file_name.csv'])) Upload File By Mounting Google Drive:To mount your drive inside “mntDrive” folder execute following – from google.colab import drivedrive.mount('/mntDrive') Then you’ll see a link, click on link, then allow access, copy the code that pops up, paste it at “Enter your authorization code:”. Now to see all data in your google drive you need to execute following: ! ls "/mntDrive/My Drive" File Hierarchy:You can also see file hierarchy by clicking “>” at top left below the control buttons (CODE, TEXT, CELL). Download Files:Let’s say you want to download “file_name.csv”. You can copy the file to your google drive (In “data” folder, you need to create the “data” folder in google drive) by executing this: cp file_name.csv "/mntDrive/My Drive/data/renamed_file_name.csv" The file will be saved at “data” folder with “renamed_file_name.csv” name. Now you can directly download from there, Or, you can just open file hierarchy and right clicking will give download option. Download Jupyter Notebook:Click “File” dropdown menu at top left corner. Choose “download .ipynb” or “download .py” Share Jupyter Notebook:You can share your notebook by adding others email address or by creating a shareable link. data-science Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n01 May, 2019" }, { "code": null, "e": 498, "s": 53, "text": "If you want to create a machine learning model but say you don’t have a computer that can take the workload, Google Colab is the platform for you. Even if you have a GPU or a good computer creating a local environment with anaconda and installing packages and resolving installation issues are a hassle.Colaboratory is a free Jupyter notebook environment provided by Google where you can use free GPUs and TPUs which can solve all these issues." }, { "code": null, "e": 631, "s": 498, "text": "To start working with Colab you first need to log in to your google account, then go to this link https://colab.research.google.com." }, { "code": null, "e": 729, "s": 631, "text": "Opening Jupyter Notebook:On opening the website you will see a pop-up containing following tabs –" }, { "code": null, "e": 1048, "s": 729, "text": "EXAMPLES: Contain a number of Jupyter notebooks of various examples.RECENT: Jupyter notebook you have recently worked with.GOOGLE DRIVE: Jupyter notebook in your google drive.GITHUB: You can add Jupyter notebook from your GitHub but you first need to connect Colab with GitHub.UPLOAD: Upload from your local directory." }, { "code": null, "e": 1176, "s": 1048, "text": "Else you can create a new Jupyter notebook by clicking New Python3 Notebook or New Python2 Notebook at the bottom right corner." }, { "code": null, "e": 1521, "s": 1176, "text": "Notebook’s Description:On creating a new notebook, it will create a Jupyter notebook with Untitled0.ipynb and save it to your google drive in a folder named Colab Notebooks. Now as it is essentially a Jupyter notebook, all commands of Jupyter notebooks will work here. Though, you can refer the details in Getting started with Jupyter Notebook." }, { "code": null, "e": 1559, "s": 1521, "text": "Let’s talk about what different here." }, { "code": null, "e": 1707, "s": 1559, "text": "Change Runtime Environment:Click the “Runtime” dropdown menu. Select “Change runtime type”. Select python2 or 3 from “Runtime type” dropdown menu. " }, { "code": null, "e": 1878, "s": 1707, "text": "Use GPU and TPU:Click the “Runtime” dropdown menu. Select “Change runtime type”. Now select anything(GPU, CPU, None) you want in the “Hardware accelerator” dropdown menu." }, { "code": null, "e": 1890, "s": 1878, "text": "Verify GPU:" }, { "code": "import tensorflow as tftf.test.gpu_device_name()", "e": 1939, "s": 1890, "text": null }, { "code": null, "e": 1986, "s": 1939, "text": "If gpu is connected it will output following –" }, { "code": null, "e": 2003, "s": 1986, "text": "'/device:GPU:0'\n" }, { "code": null, "e": 2039, "s": 2003, "text": "Otherwise, it will output following" }, { "code": null, "e": 2043, "s": 2039, "text": "''\n" }, { "code": null, "e": 2055, "s": 2043, "text": "Verify TPU:" }, { "code": "import os if 'COLAB_TPU_ADDR' not in os.environ: print('Not connected to TPU')else: print(\"Connected to TPU\")", "e": 2168, "s": 2055, "text": null }, { "code": null, "e": 2213, "s": 2168, "text": "If gpu is connected it will output following" }, { "code": null, "e": 2231, "s": 2213, "text": "Connected to TPU\n" }, { "code": null, "e": 2267, "s": 2231, "text": "Otherwise, it will output following" }, { "code": null, "e": 2289, "s": 2267, "text": "Not connected to TPU\n" }, { "code": null, "e": 2368, "s": 2289, "text": " Install Python packages –Use can use pip to install any package. For example:" }, { "code": "! pip install pandas", "e": 2389, "s": 2368, "text": null }, { "code": null, "e": 2445, "s": 2389, "text": " Clone GitHub repos:Use git clone command. For example:" }, { "code": "! git clone https://github.com/souvik3333/Testing-and-Debugging-Tools", "e": 2515, "s": 2445, "text": null }, { "code": null, "e": 2529, "s": 2515, "text": " Upload File:" }, { "code": "from google.colab import filesuploaded = files.upload()", "e": 2585, "s": 2529, "text": null }, { "code": null, "e": 2685, "s": 2585, "text": "Select “Choose file” and upload the file you want. Enable third-party cookies if they are disabled." }, { "code": null, "e": 2722, "s": 2685, "text": "Then you can save it in a dataframe." }, { "code": "import iodf2 = pd.read_csv(io.BytesIO(uploaded['file_name.csv']))", "e": 2788, "s": 2722, "text": null }, { "code": null, "e": 2890, "s": 2788, "text": "Upload File By Mounting Google Drive:To mount your drive inside “mntDrive” folder execute following –" }, { "code": "from google.colab import drivedrive.mount('/mntDrive')", "e": 2945, "s": 2890, "text": null }, { "code": null, "e": 3077, "s": 2945, "text": "Then you’ll see a link, click on link, then allow access, copy the code that pops up, paste it at “Enter your authorization code:”." }, { "code": null, "e": 3149, "s": 3077, "text": "Now to see all data in your google drive you need to execute following:" }, { "code": "! ls \"/mntDrive/My Drive\"", "e": 3175, "s": 3149, "text": null }, { "code": null, "e": 3296, "s": 3175, "text": "File Hierarchy:You can also see file hierarchy by clicking “>” at top left below the control buttons (CODE, TEXT, CELL)." }, { "code": null, "e": 3494, "s": 3296, "text": "Download Files:Let’s say you want to download “file_name.csv”. You can copy the file to your google drive (In “data” folder, you need to create the “data” folder in google drive) by executing this:" }, { "code": "cp file_name.csv \"/mntDrive/My Drive/data/renamed_file_name.csv\"", "e": 3559, "s": 3494, "text": null }, { "code": null, "e": 3759, "s": 3559, "text": "The file will be saved at “data” folder with “renamed_file_name.csv” name. Now you can directly download from there, Or, you can just open file hierarchy and right clicking will give download option." }, { "code": null, "e": 3875, "s": 3759, "text": "Download Jupyter Notebook:Click “File” dropdown menu at top left corner. Choose “download .ipynb” or “download .py”" }, { "code": null, "e": 3990, "s": 3875, "text": "Share Jupyter Notebook:You can share your notebook by adding others email address or by creating a shareable link." }, { "code": null, "e": 4003, "s": 3990, "text": "data-science" }, { "code": null, "e": 4020, "s": 4003, "text": "Machine Learning" }, { "code": null, "e": 4027, "s": 4020, "text": "Python" }, { "code": null, "e": 4044, "s": 4027, "text": "Machine Learning" } ]
How do I select elements inside an iframe with Xpath?
We can select elements inside an iframe with xpath in Selenium webdriver. A frame is defined with <iframe>, <frameset> or <frame> tag in html code. A frame is used to embed an HTML document within another HTML document. Let us see the html code of a frame. Selenium by default has access to the parent browser driver. In order to access inside a frame, the driver focus has to shift from the main browser window to the frame. There are more than one methods to shift focus to frames − switchTo().frame(id) - The id or name of frame is passed as an argument.Syntax − driver.switchTo().frame("id"), switching to the frame with id. switchTo().frame(id) - The id or name of frame is passed as an argument. Syntax − driver.switchTo().frame("id"), switching to the frame with id. switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.Syntax − driver.switchTo().frame(0), switching to the first frame in the page. switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero. Syntax − driver.switchTo().frame(0), switching to the first frame in the page. switchTo().frame(webelement n) - The webelement of frame is passed as an argument.Syntax − driver.switchTo().frame(l), switching to the frame with l webelement. switchTo().frame(webelement n) - The webelement of frame is passed as an argument. Syntax − driver.switchTo().frame(l), switching to the frame with l webelement. Once we move the driver focus inside the frame, we can access the elements inside the frame by the xpath locator with the help of the driver.findElement(By.xpath(<xpath value>)) method. Code Implementation. import org.openqa.selenium.By; import org.openqa.selenium.WebDriver; import org.openqa.selenium.WebElement; import org.openqa.selenium.chrome.ChromeDriver; import java.util.concurrent.TimeUnit; public class iFrameXpath{ public static void main(String[] args) { System.setProperty("webdriver.chrome.driver", "C:\\Users\\ghs6kor\\Desktop\\Java\\chromedriver.exe"); WebDriver driver = new ChromeDriver(); driver.get("https://the-internet.herokuapp.com/frames"); driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS); // identify element and click driver.findElement(By.partialLinkText("Nested")).click(); // switching to frame with frame name driver.switchTo().frame("frame-bottom"); WebElement m = driver.findElement(By.xpath("//body")); System.out.println("Element identified with xpath: " +m.getText()); driver.close(); } }
[ { "code": null, "e": 1444, "s": 1187, "text": "We can select elements inside an iframe with xpath in Selenium webdriver. A frame is defined with <iframe>, <frameset> or <frame> tag in html code. A frame is used to embed an HTML document within another HTML document. Let us see the html code of a frame." }, { "code": null, "e": 1672, "s": 1444, "text": "Selenium by default has access to the parent browser driver. In order to access inside a frame, the driver focus has to shift from the main browser window to the frame. There are more than one methods to shift focus to frames −" }, { "code": null, "e": 1816, "s": 1672, "text": "switchTo().frame(id) - The id or name of frame is passed as an argument.Syntax −\ndriver.switchTo().frame(\"id\"), switching to the frame with id." }, { "code": null, "e": 1889, "s": 1816, "text": "switchTo().frame(id) - The id or name of frame is passed as an argument." }, { "code": null, "e": 1961, "s": 1889, "text": "Syntax −\ndriver.switchTo().frame(\"id\"), switching to the frame with id." }, { "code": null, "e": 2134, "s": 1961, "text": "switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero.Syntax −\ndriver.switchTo().frame(0), switching to the first frame in the page." }, { "code": null, "e": 2229, "s": 2134, "text": "switchTo().frame(m) - The index of frame is passed as an argument. The index begins from zero." }, { "code": null, "e": 2308, "s": 2229, "text": "Syntax −\ndriver.switchTo().frame(0), switching to the first frame in the page." }, { "code": null, "e": 2469, "s": 2308, "text": "switchTo().frame(webelement n) - The webelement of frame is passed as an argument.Syntax −\ndriver.switchTo().frame(l), switching to the frame with l webelement." }, { "code": null, "e": 2552, "s": 2469, "text": "switchTo().frame(webelement n) - The webelement of frame is passed as an argument." }, { "code": null, "e": 2631, "s": 2552, "text": "Syntax −\ndriver.switchTo().frame(l), switching to the frame with l webelement." }, { "code": null, "e": 2817, "s": 2631, "text": "Once we move the driver focus inside the frame, we can access the elements inside the frame by the xpath locator with the help of the driver.findElement(By.xpath(<xpath value>)) method." }, { "code": null, "e": 2838, "s": 2817, "text": "Code Implementation." }, { "code": null, "e": 3743, "s": 2838, "text": "import org.openqa.selenium.By;\nimport org.openqa.selenium.WebDriver;\nimport org.openqa.selenium.WebElement;\nimport org.openqa.selenium.chrome.ChromeDriver;\nimport java.util.concurrent.TimeUnit;\npublic class iFrameXpath{\n public static void main(String[] args) {\n System.setProperty(\"webdriver.chrome.driver\", \"C:\\\\Users\\\\ghs6kor\\\\Desktop\\\\Java\\\\chromedriver.exe\");\n WebDriver driver = new ChromeDriver();\n driver.get(\"https://the-internet.herokuapp.com/frames\");\n driver.manage().timeouts().implicitlyWait(8, TimeUnit.SECONDS);\n // identify element and click\n driver.findElement(By.partialLinkText(\"Nested\")).click();\n // switching to frame with frame name\n driver.switchTo().frame(\"frame-bottom\");\n WebElement m = driver.findElement(By.xpath(\"//body\"));\n System.out.println(\"Element identified with xpath: \" +m.getText());\n driver.close();\n }\n}" } ]
Python OpenCV – cv2.polylines() method
15 Jun, 2022 OpenCV is the huge open-source library for computer vision, machine learning, and image processing and it now plays a major role in real-time operations which are very important in today’s systems. By using OpenCV one can process images and videos to identify objects, faces, or even the handwriting of a human. When it is combined with various libraries such as Numpy, Python is capable of processing the OpenCV array structure for analysis. Note: For more information, refer to OpenCV Python Tutorial cv2.polylines() method is used to draw a polygon on any image. Syntax: cv2.polylines(image, [pts], isClosed, color, thickness) Parameters: image: It is the image on which circle is to be drawn. pts: Array of polygonal curves. npts: Array of polygon vertex counters. ncontours: Number of curves. isClosed: Flag indicating whether the drawn polylines are closed or not. If they are closed, the function draws a line from the last vertex of each curve to its first vertex. color: It is the color of polyline to be drawn. For BGR, we pass a tuple. thickness: It is thickness of the polyline edges. Return Value: It returns an image. Image used for all the below examples: Image used for all the below examples: Example #1: Python3 # Python program to explain# cv2.polylines() method import cv2import numpy as np # pathpath = gfg.jpeg' # Reading an image in default# modeimage = cv2.imread(path) # Window name in which image is# displayedwindow_name = 'Image' # Polygon corner points coordinatespts = np.array([[25, 70], [25, 160], [110, 200], [200, 160], [200, 70], [110, 20]], np.int32) pts = pts.reshape((-1, 1, 2)) isClosed = True # Blue color in BGRcolor = (255, 0, 0) # Line thickness of 2 pxthickness = 2 # Using cv2.polylines() method# Draw a Blue polygon with# thickness of 1 pximage = cv2.polylines(image, [pts], isClosed, color, thickness) # Displaying the imagewhile(1): cv2.imshow('image', image) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows() Output: Example #2: Python3 # Python program to explain# cv2.polylines() method import cv2import numpy as np # pathpath = r'gfg.jpeg' # Reading an image in default# modeimage = cv2.imread(path) # Window name in which image is# displayedwindow_name = 'Image' # Polygon corner points coordinatespts = np.array([[25, 70], [25, 145], [75, 190], [150, 190], [200, 145], [200, 70], [150, 25], [75, 25]], np.int32) pts = pts.reshape((-1, 1, 2)) isClosed = True # Green color in BGRcolor = (0, 255, 0) # Line thickness of 8 pxthickness = 8 # Using cv2.polylines() method# Draw a Green polygon with# thickness of 1 pximage = cv2.polylines(image, [pts], isClosed, color, thickness) # Displaying the imagewhile(1): cv2.imshow('image', image) if cv2.waitKey(20) & 0xFF == 27: breakcv2.destroyAllWindows() Output: miktw0d Python-OpenCV Python Write From Home Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n15 Jun, 2022" }, { "code": null, "e": 497, "s": 53, "text": "OpenCV is the huge open-source library for computer vision, machine learning, and image processing and it now plays a major role in real-time operations which are very important in today’s systems. By using OpenCV one can process images and videos to identify objects, faces, or even the handwriting of a human. When it is combined with various libraries such as Numpy, Python is capable of processing the OpenCV array structure for analysis. " }, { "code": null, "e": 557, "s": 497, "text": "Note: For more information, refer to OpenCV Python Tutorial" }, { "code": null, "e": 620, "s": 557, "text": "cv2.polylines() method is used to draw a polygon on any image." }, { "code": null, "e": 685, "s": 620, "text": "Syntax: cv2.polylines(image, [pts], isClosed, color, thickness) " }, { "code": null, "e": 753, "s": 685, "text": "Parameters: image: It is the image on which circle is to be drawn. " }, { "code": null, "e": 786, "s": 753, "text": "pts: Array of polygonal curves. " }, { "code": null, "e": 827, "s": 786, "text": "npts: Array of polygon vertex counters. " }, { "code": null, "e": 857, "s": 827, "text": "ncontours: Number of curves. " }, { "code": null, "e": 1033, "s": 857, "text": "isClosed: Flag indicating whether the drawn polylines are closed or not. If they are closed, the function draws a line from the last vertex of each curve to its first vertex. " }, { "code": null, "e": 1108, "s": 1033, "text": "color: It is the color of polyline to be drawn. For BGR, we pass a tuple. " }, { "code": null, "e": 1159, "s": 1108, "text": "thickness: It is thickness of the polyline edges. " }, { "code": null, "e": 1194, "s": 1159, "text": "Return Value: It returns an image." }, { "code": null, "e": 1233, "s": 1194, "text": "Image used for all the below examples:" }, { "code": null, "e": 1272, "s": 1233, "text": "Image used for all the below examples:" }, { "code": null, "e": 1285, "s": 1272, "text": "Example #1: " }, { "code": null, "e": 1293, "s": 1285, "text": "Python3" }, { "code": "# Python program to explain# cv2.polylines() method import cv2import numpy as np # pathpath = gfg.jpeg' # Reading an image in default# modeimage = cv2.imread(path) # Window name in which image is# displayedwindow_name = 'Image' # Polygon corner points coordinatespts = np.array([[25, 70], [25, 160], [110, 200], [200, 160], [200, 70], [110, 20]], np.int32) pts = pts.reshape((-1, 1, 2)) isClosed = True # Blue color in BGRcolor = (255, 0, 0) # Line thickness of 2 pxthickness = 2 # Using cv2.polylines() method# Draw a Blue polygon with# thickness of 1 pximage = cv2.polylines(image, [pts], isClosed, color, thickness) # Displaying the imagewhile(1): cv2.imshow('image', image) if cv2.waitKey(20) & 0xFF == 27: break cv2.destroyAllWindows()", "e": 2125, "s": 1293, "text": null }, { "code": null, "e": 2133, "s": 2125, "text": "Output:" }, { "code": null, "e": 2149, "s": 2136, "text": "Example #2: " }, { "code": null, "e": 2157, "s": 2149, "text": "Python3" }, { "code": "# Python program to explain# cv2.polylines() method import cv2import numpy as np # pathpath = r'gfg.jpeg' # Reading an image in default# modeimage = cv2.imread(path) # Window name in which image is# displayedwindow_name = 'Image' # Polygon corner points coordinatespts = np.array([[25, 70], [25, 145], [75, 190], [150, 190], [200, 145], [200, 70], [150, 25], [75, 25]], np.int32) pts = pts.reshape((-1, 1, 2)) isClosed = True # Green color in BGRcolor = (0, 255, 0) # Line thickness of 8 pxthickness = 8 # Using cv2.polylines() method# Draw a Green polygon with# thickness of 1 pximage = cv2.polylines(image, [pts], isClosed, color, thickness) # Displaying the imagewhile(1): cv2.imshow('image', image) if cv2.waitKey(20) & 0xFF == 27: breakcv2.destroyAllWindows()", "e": 3050, "s": 2157, "text": null }, { "code": null, "e": 3058, "s": 3050, "text": "Output:" }, { "code": null, "e": 3068, "s": 3060, "text": "miktw0d" }, { "code": null, "e": 3082, "s": 3068, "text": "Python-OpenCV" }, { "code": null, "e": 3089, "s": 3082, "text": "Python" }, { "code": null, "e": 3105, "s": 3089, "text": "Write From Home" } ]
Java Program to Convert Byte Array to Hex String
24 Sep, 2021 Byte Array – A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0. Hex String – A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0’s and 1’s. Eg: “245FC” is a hexadecimal string. Problem Statement – Given a byte array, the task is to convert the Byte Array to Hex String. Example: Input : byteArray = { 9, 2, 14, 10 } Output: 9 2 E A Input : byteArray = { 7, 12, 13, 127 } Output: 7 C D 7F The conversion of a Byte Array to Hex String involves changing an array of byte datatype to its hexadecimal value in the form of a string. There are numerous approaches to do the same; a few of them are listed below. Approaches: Using Format() Method in Java Using Bitwise Shift Operators Using the predefined method in Integer/Long Class Using Hexadecimal Representation of BigInteger in Java Java String Format() method can be used for the specified conversion. For this, Iterate through each byte in the array and calculate its hexadecimal equivalent.The string.format() is used to print the number of places of a hexadecimal value and store the value in a string.%02X is used to print add two spaced between two hexadecimal values(of a hexadecimal (X)). Iterate through each byte in the array and calculate its hexadecimal equivalent. The string.format() is used to print the number of places of a hexadecimal value and store the value in a string. %02X is used to print add two spaced between two hexadecimal values(of a hexadecimal (X)). Following is the implementation of the foregoing approach: Java // Java Program to convert byte// array to hex string // Approach 1 - Using Format() Method in Java import java.io.*; public class GFG { public static void convertByteToHexadecimal(byte[] byteArray) { String hex = ""; // Iterating through each byte in the array for (byte i : byteArray) { hex += String.format("%02X", i); } System.out.print(hex); } public static void main(String[] args) { byte[] byteArray = { 7, 12, 13, 127 }; convertByteToHexadecimal(byteArray); }} 070C0D7F In the previous approach, if the byte array gets larger, the process becomes slow. A byte operation is used to convert the byte array to a hexadecimal value to increase efficiency. Here “>>>” unsigned right shift operator is used. And, toCharArray() method converts the given string into a sequence of characters. Following is the implementation of the foregoing approach – Java // Java program to convert byte// array to hex string // Approach 2 - Using Bitwise Shift Operators import java.io.*; public class GFG { public static void convertByteToHexadecimal(byte[] byteArray) { int len = byteArray.length; // storing the hexadecimal values char[] hexValues = "0123456789ABCDEF".toCharArray(); char[] hexCharacter = new char[len * 2]; // using byte operation converting byte // array to hexadecimal value for (int i = 0; i < len; i++) { int v = byteArray[i] & 0xFF; hexCharacter[i * 2] = hexValues[v >>> 4]; hexCharacter[i * 2 + 1] = hexValues[v & 0x0F]; } System.out.println(hexCharacter); } public static void main(String[] args) { byte[] bytes = { 9, 2, 14, 127 }; convertByteToHexadecimal(bytes); }} 09020E7F The Integer class has toHexString() method that converts an integer to its hexadecimal equivalent. We now need to convert the byte array into an integer (for 4-sized) or long (for 8-sized) and use this method (as this method is present in both of the classes, i.e., Integer and Long with the same name). For converting byte array to integer or long, we can use the wrap method of the ByteBuffer class. Following is the implementation of the foregoing approach – Java // Java program to convert byte// array to hex string // Approach 3 - Using the predefined method // in Integer/Long Class import java.io.*;// Importing packages to use wrap methods // of ByteBuffer Classimport java.nio.*; public class GFG { public static String toHexadecimal(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte i : bytes) { int decimal = (int)i & 0XFF; String hex = Integer.toHexString(decimal); if (hex.length() % 2 == 1) { hex = "0" + hex; } result.append(hex); } return result.toString(); } public static void main(String[] args) { byte[] byteArray = { 9, 2, 14, 127 }; System.out.println(toHexadecimal(byteArray)); }} 09020e7f Using the Hexadecimal Representation of BigInteger class in Java is quite an avoided way of converting byte array to hex string due to its slow speed. Here one can also observe that since we deal with numbers and not arbitrary byte strings, this may omit leading zeros in cases. Following is the implementation of the foregoing approach – Java // Java program to convert byte// array to hex string // Approach 4 - Using Hexadecimal Representation// of BigInteger in Java import java.io.*;// Importing the BigInteger classimport java.math.BigInteger; public class GFG { public static void toHexString(byte[] byteArray) { // Printing the hexadecimal equivalent as string // representation from the BigInteger class. System.out.print( new BigInteger(1, byteArray).toString(16)); } public static void main(String[] args) { byte[] byteArray = { 17, 2, 14, 127 }; toHexString(byteArray); }} 11020e7f nishkarshgandhi Java-Array-Programs Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Stream In Java Introduction to Java Constructors in Java Exceptions in Java Generics in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class Factory method design pattern in Java Java Program to Remove Duplicate Elements From the Array
[ { "code": null, "e": 28, "s": 0, "text": "\n24 Sep, 2021" }, { "code": null, "e": 165, "s": 28, "text": "Byte Array – A Java Byte Array is an array used to store byte data types only. The default value of each element of the byte array is 0." }, { "code": null, "e": 341, "s": 165, "text": "Hex String – A Hex String is a combination of the digits 0-9 and characters A-F, just like how a binary string comprises only 0’s and 1’s. Eg: “245FC” is a hexadecimal string." }, { "code": null, "e": 435, "s": 341, "text": "Problem Statement – Given a byte array, the task is to convert the Byte Array to Hex String. " }, { "code": null, "e": 445, "s": 435, "text": "Example: " }, { "code": null, "e": 555, "s": 445, "text": "Input : byteArray = { 9, 2, 14, 10 }\nOutput: 9 2 E A\n\nInput : byteArray = { 7, 12, 13, 127 }\nOutput: 7 C D 7F" }, { "code": null, "e": 772, "s": 555, "text": "The conversion of a Byte Array to Hex String involves changing an array of byte datatype to its hexadecimal value in the form of a string. There are numerous approaches to do the same; a few of them are listed below." }, { "code": null, "e": 784, "s": 772, "text": "Approaches:" }, { "code": null, "e": 814, "s": 784, "text": "Using Format() Method in Java" }, { "code": null, "e": 844, "s": 814, "text": "Using Bitwise Shift Operators" }, { "code": null, "e": 894, "s": 844, "text": "Using the predefined method in Integer/Long Class" }, { "code": null, "e": 949, "s": 894, "text": "Using Hexadecimal Representation of BigInteger in Java" }, { "code": null, "e": 1029, "s": 949, "text": "Java String Format() method can be used for the specified conversion. For this," }, { "code": null, "e": 1313, "s": 1029, "text": "Iterate through each byte in the array and calculate its hexadecimal equivalent.The string.format() is used to print the number of places of a hexadecimal value and store the value in a string.%02X is used to print add two spaced between two hexadecimal values(of a hexadecimal (X))." }, { "code": null, "e": 1394, "s": 1313, "text": "Iterate through each byte in the array and calculate its hexadecimal equivalent." }, { "code": null, "e": 1508, "s": 1394, "text": "The string.format() is used to print the number of places of a hexadecimal value and store the value in a string." }, { "code": null, "e": 1599, "s": 1508, "text": "%02X is used to print add two spaced between two hexadecimal values(of a hexadecimal (X))." }, { "code": null, "e": 1658, "s": 1599, "text": "Following is the implementation of the foregoing approach:" }, { "code": null, "e": 1663, "s": 1658, "text": "Java" }, { "code": "// Java Program to convert byte// array to hex string // Approach 1 - Using Format() Method in Java import java.io.*; public class GFG { public static void convertByteToHexadecimal(byte[] byteArray) { String hex = \"\"; // Iterating through each byte in the array for (byte i : byteArray) { hex += String.format(\"%02X\", i); } System.out.print(hex); } public static void main(String[] args) { byte[] byteArray = { 7, 12, 13, 127 }; convertByteToHexadecimal(byteArray); }}", "e": 2220, "s": 1663, "text": null }, { "code": null, "e": 2229, "s": 2220, "text": "070C0D7F" }, { "code": null, "e": 2410, "s": 2229, "text": "In the previous approach, if the byte array gets larger, the process becomes slow. A byte operation is used to convert the byte array to a hexadecimal value to increase efficiency." }, { "code": null, "e": 2543, "s": 2410, "text": "Here “>>>” unsigned right shift operator is used. And, toCharArray() method converts the given string into a sequence of characters." }, { "code": null, "e": 2603, "s": 2543, "text": "Following is the implementation of the foregoing approach –" }, { "code": null, "e": 2608, "s": 2603, "text": "Java" }, { "code": "// Java program to convert byte// array to hex string // Approach 2 - Using Bitwise Shift Operators import java.io.*; public class GFG { public static void convertByteToHexadecimal(byte[] byteArray) { int len = byteArray.length; // storing the hexadecimal values char[] hexValues = \"0123456789ABCDEF\".toCharArray(); char[] hexCharacter = new char[len * 2]; // using byte operation converting byte // array to hexadecimal value for (int i = 0; i < len; i++) { int v = byteArray[i] & 0xFF; hexCharacter[i * 2] = hexValues[v >>> 4]; hexCharacter[i * 2 + 1] = hexValues[v & 0x0F]; } System.out.println(hexCharacter); } public static void main(String[] args) { byte[] bytes = { 9, 2, 14, 127 }; convertByteToHexadecimal(bytes); }}", "e": 3481, "s": 2608, "text": null }, { "code": null, "e": 3490, "s": 3481, "text": "09020E7F" }, { "code": null, "e": 3892, "s": 3490, "text": "The Integer class has toHexString() method that converts an integer to its hexadecimal equivalent. We now need to convert the byte array into an integer (for 4-sized) or long (for 8-sized) and use this method (as this method is present in both of the classes, i.e., Integer and Long with the same name). For converting byte array to integer or long, we can use the wrap method of the ByteBuffer class." }, { "code": null, "e": 3952, "s": 3892, "text": "Following is the implementation of the foregoing approach –" }, { "code": null, "e": 3957, "s": 3952, "text": "Java" }, { "code": "// Java program to convert byte// array to hex string // Approach 3 - Using the predefined method // in Integer/Long Class import java.io.*;// Importing packages to use wrap methods // of ByteBuffer Classimport java.nio.*; public class GFG { public static String toHexadecimal(byte[] bytes) { StringBuilder result = new StringBuilder(); for (byte i : bytes) { int decimal = (int)i & 0XFF; String hex = Integer.toHexString(decimal); if (hex.length() % 2 == 1) { hex = \"0\" + hex; } result.append(hex); } return result.toString(); } public static void main(String[] args) { byte[] byteArray = { 9, 2, 14, 127 }; System.out.println(toHexadecimal(byteArray)); }}", "e": 4756, "s": 3957, "text": null }, { "code": null, "e": 4765, "s": 4756, "text": "09020e7f" }, { "code": null, "e": 5044, "s": 4765, "text": "Using the Hexadecimal Representation of BigInteger class in Java is quite an avoided way of converting byte array to hex string due to its slow speed. Here one can also observe that since we deal with numbers and not arbitrary byte strings, this may omit leading zeros in cases." }, { "code": null, "e": 5104, "s": 5044, "text": "Following is the implementation of the foregoing approach –" }, { "code": null, "e": 5109, "s": 5104, "text": "Java" }, { "code": "// Java program to convert byte// array to hex string // Approach 4 - Using Hexadecimal Representation// of BigInteger in Java import java.io.*;// Importing the BigInteger classimport java.math.BigInteger; public class GFG { public static void toHexString(byte[] byteArray) { // Printing the hexadecimal equivalent as string // representation from the BigInteger class. System.out.print( new BigInteger(1, byteArray).toString(16)); } public static void main(String[] args) { byte[] byteArray = { 17, 2, 14, 127 }; toHexString(byteArray); }}", "e": 5719, "s": 5109, "text": null }, { "code": null, "e": 5728, "s": 5719, "text": "11020e7f" }, { "code": null, "e": 5744, "s": 5728, "text": "nishkarshgandhi" }, { "code": null, "e": 5764, "s": 5744, "text": "Java-Array-Programs" }, { "code": null, "e": 5769, "s": 5764, "text": "Java" }, { "code": null, "e": 5783, "s": 5769, "text": "Java Programs" }, { "code": null, "e": 5788, "s": 5783, "text": "Java" }, { "code": null, "e": 5886, "s": 5788, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5901, "s": 5886, "text": "Stream In Java" }, { "code": null, "e": 5922, "s": 5901, "text": "Introduction to Java" }, { "code": null, "e": 5943, "s": 5922, "text": "Constructors in Java" }, { "code": null, "e": 5962, "s": 5943, "text": "Exceptions in Java" }, { "code": null, "e": 5979, "s": 5962, "text": "Generics in Java" }, { "code": null, "e": 6005, "s": 5979, "text": "Java Programming Examples" }, { "code": null, "e": 6039, "s": 6005, "text": "Convert Double to Integer in Java" }, { "code": null, "e": 6086, "s": 6039, "text": "Implementing a Linked List in Java using Class" }, { "code": null, "e": 6124, "s": 6086, "text": "Factory method design pattern in Java" } ]
time.Time.Truncate() Function in Golang with Examples
28 Apr, 2020 In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Truncate() function in Go language is used to find the output of rounding the stated time “t” to the closest multiple of the given duration “d” from the zero time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions. Syntax: func (t Time) Truncate(d Duration) Time Here, “t” is the stated time, and “d” is the given duration. Note: The Truncate() method works on the time in the form of an absolute duration from zero time. However, it doesn’t work on the layout form of the time. Return Value: It returns the output of rounding the given time “t” to the closest multiple of the stated duration “d”. Where, if d is less than or equal to zero then it returns “t” out of any monotonic clock reading but else unaltered. Example 1: // Golang program to illustrate the usage of// Time.Truncate() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t for Truncate method t := time.Date(2007, 7, 6, 23, 58, 11, 60, time.UTC) // Defining duration d := (60 * time.Second) // Calling Truncate() method trunc := t.Truncate(d) // Prints output fmt.Printf("The result after rounding 't' is: %v\n", trunc)} Output: The result after rounding 't' is: 2007-07-06 23:58:00 +0000 UTC Example 2: // Golang program to illustrate the usage of// Time.Truncate() function // Including main packagepackage main // Importing fmt and timeimport "fmt"import "time" // Calling mainfunc main() { // Defining t for Truncate method t := time.Date(2047, 47, 96, 123, 98, 81, 999434, time.UTC) // Defining duration d := (2 * time.Hour) // Calling Truncate() method trunc := t.Truncate(d) // Prints output fmt.Printf("The result after rounding 't' is: %v\n", trunc)} Output: The result after rounding 't' is: 2051-02-09 04:00:00 +0000 UTC Here, the “t” stated in the above code has values that are outside the usual range but they are normalized while conversion. GoLang-time Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Golang Maps Arrays in Go fmt.Sprintf() Function in Golang With Examples How to copy one slice into another slice in Golang? Time Durations in Golang How to convert a string in lower case in Golang? Interfaces in Golang Inheritance in GoLang Check if the String starts with specified prefix in Golang strings.Replace() Function in Golang With Examples
[ { "code": null, "e": 28, "s": 0, "text": "\n28 Apr, 2020" }, { "code": null, "e": 431, "s": 28, "text": "In Go language, time packages supplies functionality for determining as well as viewing time. The Time.Truncate() function in Go language is used to find the output of rounding the stated time “t” to the closest multiple of the given duration “d” from the zero time. Moreover, this function is defined under the time package. Here, you need to import the “time” package in order to use these functions." }, { "code": null, "e": 439, "s": 431, "text": "Syntax:" }, { "code": null, "e": 480, "s": 439, "text": "func (t Time) Truncate(d Duration) Time\n" }, { "code": null, "e": 541, "s": 480, "text": "Here, “t” is the stated time, and “d” is the given duration." }, { "code": null, "e": 696, "s": 541, "text": "Note: The Truncate() method works on the time in the form of an absolute duration from zero time. However, it doesn’t work on the layout form of the time." }, { "code": null, "e": 932, "s": 696, "text": "Return Value: It returns the output of rounding the given time “t” to the closest multiple of the stated duration “d”. Where, if d is less than or equal to zero then it returns “t” out of any monotonic clock reading but else unaltered." }, { "code": null, "e": 943, "s": 932, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// Time.Truncate() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t for Truncate method t := time.Date(2007, 7, 6, 23, 58, 11, 60, time.UTC) // Defining duration d := (60 * time.Second) // Calling Truncate() method trunc := t.Truncate(d) // Prints output fmt.Printf(\"The result after rounding 't' is: %v\\n\", trunc)}", "e": 1430, "s": 943, "text": null }, { "code": null, "e": 1438, "s": 1430, "text": "Output:" }, { "code": null, "e": 1503, "s": 1438, "text": "The result after rounding 't' is: 2007-07-06 23:58:00 +0000 UTC\n" }, { "code": null, "e": 1514, "s": 1503, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// Time.Truncate() function // Including main packagepackage main // Importing fmt and timeimport \"fmt\"import \"time\" // Calling mainfunc main() { // Defining t for Truncate method t := time.Date(2047, 47, 96, 123, 98, 81, 999434, time.UTC) // Defining duration d := (2 * time.Hour) // Calling Truncate() method trunc := t.Truncate(d) // Prints output fmt.Printf(\"The result after rounding 't' is: %v\\n\", trunc)}", "e": 2005, "s": 1514, "text": null }, { "code": null, "e": 2013, "s": 2005, "text": "Output:" }, { "code": null, "e": 2078, "s": 2013, "text": "The result after rounding 't' is: 2051-02-09 04:00:00 +0000 UTC\n" }, { "code": null, "e": 2203, "s": 2078, "text": "Here, the “t” stated in the above code has values that are outside the usual range but they are normalized while conversion." }, { "code": null, "e": 2215, "s": 2203, "text": "GoLang-time" }, { "code": null, "e": 2227, "s": 2215, "text": "Go Language" }, { "code": null, "e": 2325, "s": 2227, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2337, "s": 2325, "text": "Golang Maps" }, { "code": null, "e": 2350, "s": 2337, "text": "Arrays in Go" }, { "code": null, "e": 2397, "s": 2350, "text": "fmt.Sprintf() Function in Golang With Examples" }, { "code": null, "e": 2449, "s": 2397, "text": "How to copy one slice into another slice in Golang?" }, { "code": null, "e": 2474, "s": 2449, "text": "Time Durations in Golang" }, { "code": null, "e": 2523, "s": 2474, "text": "How to convert a string in lower case in Golang?" }, { "code": null, "e": 2544, "s": 2523, "text": "Interfaces in Golang" }, { "code": null, "e": 2566, "s": 2544, "text": "Inheritance in GoLang" }, { "code": null, "e": 2625, "s": 2566, "text": "Check if the String starts with specified prefix in Golang" } ]
How to make checkbox visible when hover or select the element?
31 Jan, 2020 The problem here is how to make a checkbox visible only when: It is hovered overSelected It is hovered over Selected Approach:The checkbox shouldn’t be visible when not selected. It only becomes visible when hovered over again.The solution to the problem is simple. We can use the opacity property of the checkbox element and manipulate that. Just change the opacity value of the checkbox to 1 when the checkbox element is hovered over or when it is selected, using CSS. The default value of opacity should be 0. Example: <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Checkbox</title> <style> #box{ margin:50px; width:50px; height:50px; border:2px solid black; padding:10px; } .cardcheckbox { opacity: 0; } .cardcheckbox:hover, .cardcheckbox:checked { opacity: 1; } </style></head><body> <div id="box"> <div> <input type="checkbox" class="cardcheckbox" align="right"/> </div> </div></body></html> Output: Bootstrap-Misc CSS-Misc Picked Technical Scripter 2019 Bootstrap Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n31 Jan, 2020" }, { "code": null, "e": 116, "s": 54, "text": "The problem here is how to make a checkbox visible only when:" }, { "code": null, "e": 143, "s": 116, "text": "It is hovered overSelected" }, { "code": null, "e": 162, "s": 143, "text": "It is hovered over" }, { "code": null, "e": 171, "s": 162, "text": "Selected" }, { "code": null, "e": 567, "s": 171, "text": "Approach:The checkbox shouldn’t be visible when not selected. It only becomes visible when hovered over again.The solution to the problem is simple. We can use the opacity property of the checkbox element and manipulate that. Just change the opacity value of the checkbox to 1 when the checkbox element is hovered over or when it is selected, using CSS. The default value of opacity should be 0." }, { "code": null, "e": 576, "s": 567, "text": "Example:" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\"> <title>Checkbox</title> <style> #box{ margin:50px; width:50px; height:50px; border:2px solid black; padding:10px; } .cardcheckbox { opacity: 0; } .cardcheckbox:hover, .cardcheckbox:checked { opacity: 1; } </style></head><body> <div id=\"box\"> <div> <input type=\"checkbox\" class=\"cardcheckbox\" align=\"right\"/> </div> </div></body></html>", "e": 1320, "s": 576, "text": null }, { "code": null, "e": 1328, "s": 1320, "text": "Output:" }, { "code": null, "e": 1343, "s": 1328, "text": "Bootstrap-Misc" }, { "code": null, "e": 1352, "s": 1343, "text": "CSS-Misc" }, { "code": null, "e": 1359, "s": 1352, "text": "Picked" }, { "code": null, "e": 1383, "s": 1359, "text": "Technical Scripter 2019" }, { "code": null, "e": 1393, "s": 1383, "text": "Bootstrap" }, { "code": null, "e": 1412, "s": 1393, "text": "Technical Scripter" } ]
C/C++ Program to find Prime Numbers between given range
05 Jul, 2021 Given two numbers L and R, the task is to find the prime numbers between L and R. Examples: Input: L = 1, R = 10Output: 2 3 5 7Explanation:Prime number between the 1 and 10 are 2, 3, 5, and 7 Input: L = 30, R = 40Output: 31 37 Approach: The idea is to iterate from in the range [L, R] and check if any number in the given range is prime or not. If yes then print that number and check for the next number till we iterate all the numbers. Below the implementation of the above approach: C C++ // C program to find the prime numbers// between a given interval#include <stdio.h> // Function for print prime// number in given rangevoid primeInRange(int L, int R){ int i, j, flag; // Traverse each number in the // interval with the help of for loop for (i = L; i <= R; i++) { // Skip 0 and 1 as they are // neither prime nor composite if (i == 1 || i == 0) continue; // flag variable to tell // if i is prime or not flag = 1; // Iterate to check if i is prime // or not for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } // flag = 1 means i is prime // and flag = 0 means i is not prime if (flag == 1) printf("%d ", i); }} // Driver Codeint main(){ // Given Range int L = 1; int R = 10; // Function Call primeInRange(L, R); return 0;} // C++ program to find the prime numbers// between a given interval#include <bits/stdc++.h>using namespace std; // Function for print prime// number in given rangevoid primeInRange(int L, int R){ int flag; // Traverse each number in the // interval with the help of for loop for (int i = L; i <= R; i++) { // Skip 0 and 1 as they are // neither prime nor composite if (i == 1 || i == 0) continue; // flag variable to tell // if i is prime or not flag = 1; // Iterate to check if i is prime // or not for (int j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } // flag = 1 means i is prime // and flag = 0 means i is not prime if (flag == 1) cout << i << " "; }} // Driver Codeint main(){ // Given Range int L = 1; int R = 10; // Function Call primeInRange(L, R); return 0;} 2 3 5 7 Time Complexity: O((R-L)*N), where N is the number, and L and R are the given range.Auxiliary Space: O(1) gabaa406 ruhelaa48 array-range-queries Prime Number C Programs C++ Programs Mathematical Mathematical Prime Number Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 53, "s": 25, "text": "\n05 Jul, 2021" }, { "code": null, "e": 135, "s": 53, "text": "Given two numbers L and R, the task is to find the prime numbers between L and R." }, { "code": null, "e": 145, "s": 135, "text": "Examples:" }, { "code": null, "e": 247, "s": 145, "text": "Input: L = 1, R = 10Output: 2 3 5 7Explanation:Prime number between the 1 and 10 are 2, 3, 5, and 7 " }, { "code": null, "e": 284, "s": 247, "text": "Input: L = 30, R = 40Output: 31 37 " }, { "code": null, "e": 495, "s": 284, "text": "Approach: The idea is to iterate from in the range [L, R] and check if any number in the given range is prime or not. If yes then print that number and check for the next number till we iterate all the numbers." }, { "code": null, "e": 543, "s": 495, "text": "Below the implementation of the above approach:" }, { "code": null, "e": 545, "s": 543, "text": "C" }, { "code": null, "e": 549, "s": 545, "text": "C++" }, { "code": "// C program to find the prime numbers// between a given interval#include <stdio.h> // Function for print prime// number in given rangevoid primeInRange(int L, int R){ int i, j, flag; // Traverse each number in the // interval with the help of for loop for (i = L; i <= R; i++) { // Skip 0 and 1 as they are // neither prime nor composite if (i == 1 || i == 0) continue; // flag variable to tell // if i is prime or not flag = 1; // Iterate to check if i is prime // or not for (j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } // flag = 1 means i is prime // and flag = 0 means i is not prime if (flag == 1) printf(\"%d \", i); }} // Driver Codeint main(){ // Given Range int L = 1; int R = 10; // Function Call primeInRange(L, R); return 0;}", "e": 1512, "s": 549, "text": null }, { "code": "// C++ program to find the prime numbers// between a given interval#include <bits/stdc++.h>using namespace std; // Function for print prime// number in given rangevoid primeInRange(int L, int R){ int flag; // Traverse each number in the // interval with the help of for loop for (int i = L; i <= R; i++) { // Skip 0 and 1 as they are // neither prime nor composite if (i == 1 || i == 0) continue; // flag variable to tell // if i is prime or not flag = 1; // Iterate to check if i is prime // or not for (int j = 2; j <= i / 2; ++j) { if (i % j == 0) { flag = 0; break; } } // flag = 1 means i is prime // and flag = 0 means i is not prime if (flag == 1) cout << i << \" \"; }} // Driver Codeint main(){ // Given Range int L = 1; int R = 10; // Function Call primeInRange(L, R); return 0;}", "e": 2505, "s": 1512, "text": null }, { "code": null, "e": 2516, "s": 2508, "text": "2 3 5 7" }, { "code": null, "e": 2626, "s": 2520, "text": "Time Complexity: O((R-L)*N), where N is the number, and L and R are the given range.Auxiliary Space: O(1)" }, { "code": null, "e": 2637, "s": 2628, "text": "gabaa406" }, { "code": null, "e": 2647, "s": 2637, "text": "ruhelaa48" }, { "code": null, "e": 2667, "s": 2647, "text": "array-range-queries" }, { "code": null, "e": 2680, "s": 2667, "text": "Prime Number" }, { "code": null, "e": 2691, "s": 2680, "text": "C Programs" }, { "code": null, "e": 2704, "s": 2691, "text": "C++ Programs" }, { "code": null, "e": 2717, "s": 2704, "text": "Mathematical" }, { "code": null, "e": 2730, "s": 2717, "text": "Mathematical" }, { "code": null, "e": 2743, "s": 2730, "text": "Prime Number" } ]
How to remove the space between inline-block elements?
10 Aug, 2021 There are two methods to remove the space between inline-block elements. Method 1: Assign the font size of the parent of the inline block element to 0px and then assign the proper font-size to the inline block element Syntax:parent-element{ font-size:0px;}parent-element child-element{ display:inline-block; font-size:Required font size;} The above concept is illustrated by the following code: html <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /*Assign font-size of parent element to 0px*/ div { font-size: 0px; } /*Making the element inline-block*/ /*Assign proper font-size to the inline block element*/ div span { display: inline-block; background-color: green; font-size: 10rem; } </style> <title>How to remove spaces between inline block elements</title></head> <body> <div> <span>Geeks</span> <span>For</span> <span>Geeks</span> </div></body> </html> Output: Method 2:Make the display of the parent element to flex. Syntax: parent-element{ display:flex;}parent-element child-element{ display:inline-block; font-size:Required font size;} HTML <!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> /*Making the parent element a flexbox*/ div { display: flex; } /*Making the element inline-block*/ /*Assign proper font-size to the inline block element*/ div span { display: inline-block; background-color:rgb(53, 77, 5); font-size: 10rem; } </style> <title>How to remove spaces between inline block elements</title></head> <body> <div> <span>Geeks</span> <span>For</span> <span>Geeks</span> </div></body> </html> OUTPUT: shahbazalam75508 akshaysingh98088 CSS-Misc HTML-Misc Picked CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to position a div at the bottom of its container using CSS? How to set space between the flexbox ? How to update Node.js and NPM to next version ? How to insert spaces/tabs in text using HTML/CSS? How to update Node.js and NPM to next version ? Types of CSS (Cascading Style Sheet) How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 54, "s": 26, "text": "\n10 Aug, 2021" }, { "code": null, "e": 127, "s": 54, "text": "There are two methods to remove the space between inline-block elements." }, { "code": null, "e": 272, "s": 127, "text": "Method 1: Assign the font size of the parent of the inline block element to 0px and then assign the proper font-size to the inline block element" }, { "code": null, "e": 412, "s": 272, "text": "Syntax:parent-element{ font-size:0px;}parent-element child-element{ display:inline-block; font-size:Required font size;} " }, { "code": null, "e": 468, "s": 412, "text": "The above concept is illustrated by the following code:" }, { "code": null, "e": 473, "s": 468, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> /*Assign font-size of parent element to 0px*/ div { font-size: 0px; } /*Making the element inline-block*/ /*Assign proper font-size to the inline block element*/ div span { display: inline-block; background-color: green; font-size: 10rem; } </style> <title>How to remove spaces between inline block elements</title></head> <body> <div> <span>Geeks</span> <span>For</span> <span>Geeks</span> </div></body> </html>", "e": 1253, "s": 473, "text": null }, { "code": null, "e": 1262, "s": 1253, "text": "Output: " }, { "code": null, "e": 1320, "s": 1262, "text": "Method 2:Make the display of the parent element to flex. " }, { "code": null, "e": 1328, "s": 1320, "text": "Syntax:" }, { "code": null, "e": 1466, "s": 1328, "text": "parent-element{ display:flex;}parent-element child-element{ display:inline-block; font-size:Required font size;} " }, { "code": null, "e": 1471, "s": 1466, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <style> /*Making the parent element a flexbox*/ div { display: flex; } /*Making the element inline-block*/ /*Assign proper font-size to the inline block element*/ div span { display: inline-block; background-color:rgb(53, 77, 5); font-size: 10rem; } </style> <title>How to remove spaces between inline block elements</title></head> <body> <div> <span>Geeks</span> <span>For</span> <span>Geeks</span> </div></body> </html>", "e": 2244, "s": 1471, "text": null }, { "code": null, "e": 2252, "s": 2244, "text": "OUTPUT:" }, { "code": null, "e": 2271, "s": 2254, "text": "shahbazalam75508" }, { "code": null, "e": 2288, "s": 2271, "text": "akshaysingh98088" }, { "code": null, "e": 2297, "s": 2288, "text": "CSS-Misc" }, { "code": null, "e": 2307, "s": 2297, "text": "HTML-Misc" }, { "code": null, "e": 2314, "s": 2307, "text": "Picked" }, { "code": null, "e": 2318, "s": 2314, "text": "CSS" }, { "code": null, "e": 2323, "s": 2318, "text": "HTML" }, { "code": null, "e": 2340, "s": 2323, "text": "Web Technologies" }, { "code": null, "e": 2345, "s": 2340, "text": "HTML" }, { "code": null, "e": 2443, "s": 2345, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2480, "s": 2443, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2544, "s": 2480, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 2583, "s": 2544, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2631, "s": 2583, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2681, "s": 2631, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2729, "s": 2681, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2766, "s": 2729, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2816, "s": 2766, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2878, "s": 2816, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
ReactJS useContext Hook
01 Nov, 2020 Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes). Context API uses Context. Provider and Context. Consumer Components pass down the data but it is very cumbersome to write the long functional code to use this Context API. So useContext hook helps to make the code more readable, less verbose and removes the need to introduce Consumer Component. The useContext hook is the new addition in React 16.8. Syntax: const authContext = useContext(initialValue); The useContext accepts the value provided by React.createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memorization. Example: Program to demonstrate the use of useContext Hook. In this example, we have a button, whenever we click on the button the onClick handler is getting triggered and it changes the authentication status(with a default value to Nopes) with the help of the useContext hook. Let’s see the output of the above code: auth-context.jsJavascriptJavascriptimport React from 'react'; // Creating the context object and passing the default values.const authContext = React.createContext({status:null,login:()=>{}}); export default authContext; auth-context.js Javascript import React from 'react'; // Creating the context object and passing the default values.const authContext = React.createContext({status:null,login:()=>{}}); export default authContext; App.jsJavascriptJavascriptimport React, { useState } from "react";import Auth from "./Auth";import AuthContext from "./auth-context"; const App = () => { //using the state to dynamicallly pass the values to the context const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return ( <React.Fragment> <AuthContext.Provider value={{ status: authstatus, login: login }}> <Auth /> </AuthContext.Provider> </React.Fragment> );};export default App; App.js Javascript import React, { useState } from "react";import Auth from "./Auth";import AuthContext from "./auth-context"; const App = () => { //using the state to dynamicallly pass the values to the context const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return ( <React.Fragment> <AuthContext.Provider value={{ status: authstatus, login: login }}> <Auth /> </AuthContext.Provider> </React.Fragment> );};export default App; Auth.jsJavascriptJavascriptimport React, { useContext } from "react";import AuthContext from "./auth-context"; const Auth = () => { // Now all the data stored in the context can // be accessed with the auth variable const auth = useContext(AuthContext); console.log(auth.status); return ( <div> <h1>Are you authenticated?</h1> {auth.status ? <p>Yes you are</p> : <p>Nopes</p>} <button onClick={auth.login}>Click To Login</button> </div> );};export default Auth; Auth.js Javascript import React, { useContext } from "react";import AuthContext from "./auth-context"; const Auth = () => { // Now all the data stored in the context can // be accessed with the auth variable const auth = useContext(AuthContext); console.log(auth.status); return ( <div> <h1>Are you authenticated?</h1> {auth.status ? <p>Yes you are</p> : <p>Nopes</p>} <button onClick={auth.login}>Click To Login</button> </div> );};export default Auth; Output: react-js 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Difference Between PUT and PATCH Request Roadmap to Learn JavaScript For Beginners How to float three div side by side using CSS? ReactJS | Router How to get character array from string in JavaScript?
[ { "code": null, "e": 54, "s": 26, "text": "\n01 Nov, 2020" }, { "code": null, "e": 391, "s": 54, "text": "Context provides a way to pass data or state through the component tree without having to pass props down manually through each nested component. It is designed to share data that can be considered as global data for a tree of React components, such as the current authenticated user or theme(e.g. color, paddings, margins, font-sizes)." }, { "code": null, "e": 743, "s": 391, "text": "Context API uses Context. Provider and Context. Consumer Components pass down the data but it is very cumbersome to write the long functional code to use this Context API. So useContext hook helps to make the code more readable, less verbose and removes the need to introduce Consumer Component. The useContext hook is the new addition in React 16.8. " }, { "code": null, "e": 751, "s": 743, "text": "Syntax:" }, { "code": null, "e": 797, "s": 751, "text": "const authContext = useContext(initialValue);" }, { "code": null, "e": 988, "s": 797, "text": "The useContext accepts the value provided by React.createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memorization." }, { "code": null, "e": 1306, "s": 988, "text": "Example: Program to demonstrate the use of useContext Hook. In this example, we have a button, whenever we click on the button the onClick handler is getting triggered and it changes the authentication status(with a default value to Nopes) with the help of the useContext hook. Let’s see the output of the above code:" }, { "code": null, "e": 1529, "s": 1306, "text": "auth-context.jsJavascriptJavascriptimport React from 'react'; // Creating the context object and passing the default values.const authContext = React.createContext({status:null,login:()=>{}}); export default authContext;" }, { "code": null, "e": 1545, "s": 1529, "text": "auth-context.js" }, { "code": null, "e": 1556, "s": 1545, "text": "Javascript" }, { "code": "import React from 'react'; // Creating the context object and passing the default values.const authContext = React.createContext({status:null,login:()=>{}}); export default authContext;", "e": 1744, "s": 1556, "text": null }, { "code": null, "e": 2266, "s": 1744, "text": "App.jsJavascriptJavascriptimport React, { useState } from \"react\";import Auth from \"./Auth\";import AuthContext from \"./auth-context\"; const App = () => { //using the state to dynamicallly pass the values to the context const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return ( <React.Fragment> <AuthContext.Provider value={{ status: authstatus, login: login }}> <Auth /> </AuthContext.Provider> </React.Fragment> );};export default App;" }, { "code": null, "e": 2273, "s": 2266, "text": "App.js" }, { "code": null, "e": 2284, "s": 2273, "text": "Javascript" }, { "code": "import React, { useState } from \"react\";import Auth from \"./Auth\";import AuthContext from \"./auth-context\"; const App = () => { //using the state to dynamicallly pass the values to the context const [authstatus, setauthstatus] = useState(false); const login = () => { setauthstatus(true); }; return ( <React.Fragment> <AuthContext.Provider value={{ status: authstatus, login: login }}> <Auth /> </AuthContext.Provider> </React.Fragment> );};export default App;", "e": 2780, "s": 2284, "text": null }, { "code": null, "e": 3273, "s": 2780, "text": "Auth.jsJavascriptJavascriptimport React, { useContext } from \"react\";import AuthContext from \"./auth-context\"; const Auth = () => { // Now all the data stored in the context can // be accessed with the auth variable const auth = useContext(AuthContext); console.log(auth.status); return ( <div> <h1>Are you authenticated?</h1> {auth.status ? <p>Yes you are</p> : <p>Nopes</p>} <button onClick={auth.login}>Click To Login</button> </div> );};export default Auth;" }, { "code": null, "e": 3281, "s": 3273, "text": "Auth.js" }, { "code": null, "e": 3292, "s": 3281, "text": "Javascript" }, { "code": "import React, { useContext } from \"react\";import AuthContext from \"./auth-context\"; const Auth = () => { // Now all the data stored in the context can // be accessed with the auth variable const auth = useContext(AuthContext); console.log(auth.status); return ( <div> <h1>Are you authenticated?</h1> {auth.status ? <p>Yes you are</p> : <p>Nopes</p>} <button onClick={auth.login}>Click To Login</button> </div> );};export default Auth;", "e": 3758, "s": 3292, "text": null }, { "code": null, "e": 3766, "s": 3758, "text": "Output:" }, { "code": null, "e": 3775, "s": 3766, "text": "react-js" }, { "code": null, "e": 3792, "s": 3775, "text": "Web Technologies" }, { "code": null, "e": 3890, "s": 3792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3951, "s": 3890, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3994, "s": 3951, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 4066, "s": 3994, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 4106, "s": 4066, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 4130, "s": 4106, "text": "REST API (Introduction)" }, { "code": null, "e": 4171, "s": 4130, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 4213, "s": 4171, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 4260, "s": 4213, "text": "How to float three div side by side using CSS?" }, { "code": null, "e": 4277, "s": 4260, "text": "ReactJS | Router" } ]
Running Commands Inside Docker Container
31 Oct, 2020 If you are working on an application inside Docker Container, you might need commands to install packages or access file system inside the Docker Container. Executing commands inside Docker Containers should be easy enough for you since you have to do it multiple times across your development phase. Docker provides you with many ways to execute commands inside the Containers. In this article, we are going to discuss different ways to execute any type of command inside the Docker Container. You can directly access the bash of the Docker Container and execute commands there. It’s very easy to launch the bash of the Container and you can do so using this command. sudo docker run -it ubuntu bash The above command runs an Ubuntu Container and fires up its bash. Once you have access to the bash, you can start executing any command there. In this example, we will perform an echo command execution. echo geeksforgeeks In order to run a command inside a Docker Container using the exec command, you have to know the Container Id of the Docker Container. You can get the Container Id using the following Command. sudo docker container ls or sudo docker ps -a Once you have the Container ID, you can use the Docker exec command. But you have to confirm that the Container is running before you can execute the exec command. To start the Container, use this command. sudo docker start d64b00529582 After that, execute the exec command. sudo docker exec -it d64b00529582 echo "GeeksforGeeks" When you are creating a large application, it is always advised that you execute your commands by specifying it inside the Dockerfile. However, you should only include those commands inside the Dockerfile which you want to execute while building the Container. For executing commands on the go, you can use any of the two methods above. To execute commands through Dockerfile, you can specify them using the Docker Run Commands. FROM ubuntu:latest RUN echo "geeksforgeeks" After you have created the above Dockerfile, you can build the images using the Docker build command. sudo docker build -t sample-image . You can see that after step 2, “geeksforgeeks” has been printed. Docker Container linux Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. System Design Tutorial ML | Linear Regression Docker - COPY Instruction Reinforcement learning Decision Tree Introduction with example Getting started with Machine Learning How to Run a Python Script using Docker? ML | Monte Carlo Tree Search (MCTS) ML | Underfitting and Overfitting Copying Files to and from Docker Containers
[ { "code": null, "e": 53, "s": 25, "text": "\n31 Oct, 2020" }, { "code": null, "e": 432, "s": 53, "text": "If you are working on an application inside Docker Container, you might need commands to install packages or access file system inside the Docker Container. Executing commands inside Docker Containers should be easy enough for you since you have to do it multiple times across your development phase. Docker provides you with many ways to execute commands inside the Containers." }, { "code": null, "e": 548, "s": 432, "text": "In this article, we are going to discuss different ways to execute any type of command inside the Docker Container." }, { "code": null, "e": 722, "s": 548, "text": "You can directly access the bash of the Docker Container and execute commands there. It’s very easy to launch the bash of the Container and you can do so using this command." }, { "code": null, "e": 755, "s": 722, "text": "sudo docker run -it ubuntu bash\n" }, { "code": null, "e": 821, "s": 755, "text": "The above command runs an Ubuntu Container and fires up its bash." }, { "code": null, "e": 958, "s": 821, "text": "Once you have access to the bash, you can start executing any command there. In this example, we will perform an echo command execution." }, { "code": null, "e": 978, "s": 958, "text": "echo geeksforgeeks\n" }, { "code": null, "e": 1171, "s": 978, "text": "In order to run a command inside a Docker Container using the exec command, you have to know the Container Id of the Docker Container. You can get the Container Id using the following Command." }, { "code": null, "e": 1197, "s": 1171, "text": "sudo docker container ls\n" }, { "code": null, "e": 1201, "s": 1197, "text": "or " }, { "code": null, "e": 1220, "s": 1201, "text": "sudo docker ps -a\n" }, { "code": null, "e": 1426, "s": 1220, "text": "Once you have the Container ID, you can use the Docker exec command. But you have to confirm that the Container is running before you can execute the exec command. To start the Container, use this command." }, { "code": null, "e": 1458, "s": 1426, "text": "sudo docker start d64b00529582\n" }, { "code": null, "e": 1496, "s": 1458, "text": "After that, execute the exec command." }, { "code": null, "e": 1552, "s": 1496, "text": "sudo docker exec -it d64b00529582 echo \"GeeksforGeeks\"\n" }, { "code": null, "e": 1981, "s": 1552, "text": "When you are creating a large application, it is always advised that you execute your commands by specifying it inside the Dockerfile. However, you should only include those commands inside the Dockerfile which you want to execute while building the Container. For executing commands on the go, you can use any of the two methods above. To execute commands through Dockerfile, you can specify them using the Docker Run Commands." }, { "code": null, "e": 2026, "s": 1981, "text": "FROM ubuntu:latest\nRUN echo \"geeksforgeeks\"\n" }, { "code": null, "e": 2128, "s": 2026, "text": "After you have created the above Dockerfile, you can build the images using the Docker build command." }, { "code": null, "e": 2165, "s": 2128, "text": "sudo docker build -t sample-image .\n" }, { "code": null, "e": 2230, "s": 2165, "text": "You can see that after step 2, “geeksforgeeks” has been printed." }, { "code": null, "e": 2247, "s": 2230, "text": "Docker Container" }, { "code": null, "e": 2253, "s": 2247, "text": "linux" }, { "code": null, "e": 2279, "s": 2253, "text": "Advanced Computer Subject" }, { "code": null, "e": 2377, "s": 2279, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2400, "s": 2377, "text": "System Design Tutorial" }, { "code": null, "e": 2423, "s": 2400, "text": "ML | Linear Regression" }, { "code": null, "e": 2449, "s": 2423, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2472, "s": 2449, "text": "Reinforcement learning" }, { "code": null, "e": 2512, "s": 2472, "text": "Decision Tree Introduction with example" }, { "code": null, "e": 2550, "s": 2512, "text": "Getting started with Machine Learning" }, { "code": null, "e": 2591, "s": 2550, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 2627, "s": 2591, "text": "ML | Monte Carlo Tree Search (MCTS)" }, { "code": null, "e": 2661, "s": 2627, "text": "ML | Underfitting and Overfitting" } ]
Memory leak in C++ and How to avoid it?
16 Jun, 2021 Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator. The delete operator should be used to free a single allocated memory space, whereas the delete [] operator should be used to free an array of data values. Disadvantage with memory leakage: If a program has memory leaks, then its memory usage is satirically increasing since all systems have limited amount of memory and memory is costly. Hence it will create problems.Example of memory leakage in C++ CPP // Program with memory leak#include <bits/stdc++.h>using namespace std; // function with memory leakvoid func_to_show_mem_leak(){ int* ptr = new int(5); // body // return without deallocating ptr return;} // driver codeint main(){ // Call the function // to get the memory leak func_to_show_mem_leak(); return 0;} How to avoid Memory Leak? Instead of managing memory manually, try to use smart pointers where applicable. use std::string instead of char *. The std::string class handles all memory management internally, and it’s fast and well-optimized. Never use a raw pointer unless it’s to interface with an older lib. The best way to avoid memory leaks in C++ is to have as few new/delete calls at the program level as possible – ideally NONE. Anything that requires dynamic memory should be buried inside an RAII object that releases the memory when it goes out of scope. RAII allocate memory in constructor and release it in destructor, so that memory is guaranteed to be deallocated when the variable leave the current scope. Allocate memory by new keyword and deallocate memory by delete keyword and write all code between them. Example to handle memory leaks CPP // CPP program to// illustrate how to avoid// memory leak#include <bits/stdc++.h>using namespace std; // function to see memory handlingvoid func_to_handle_mem_leak(){ int* ptr = new int(5); // body // Now delete pointer ptr using delete delete (ptr);} // Driver codeint main(){ // Call function to handle // the memory leak func_to_handle_mem_leak() return 0;} Therefore, Always write delete pointer for matching of new pointer in C++ and always write code between these new and delete as explained in above example. In above example, no memory is wasted because when we are coming out from the function we are deallocating the memory by using delete function. thilak clintra C-Dynamic Memory Allocation memory-management C++ CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Set in C++ Standard Template Library (STL) unordered_map in C++ STL vector erase() and clear() in C++ Substring in C++ Priority Queue in C++ Standard Template Library (STL) Sorting a vector in C++ 2D Vector In C++ With User Defined Size Virtual Function in C++ C++ Data Types Templates in C++ with Examples
[ { "code": null, "e": 52, "s": 24, "text": "\n16 Jun, 2021" }, { "code": null, "e": 702, "s": 52, "text": "Memory leakage occurs in C++ when programmers allocates memory by using new keyword and forgets to deallocate the memory by using delete() function or delete[] operator. One of the most memory leakage occurs in C++ by using wrong delete operator. The delete operator should be used to free a single allocated memory space, whereas the delete [] operator should be used to free an array of data values. Disadvantage with memory leakage: If a program has memory leaks, then its memory usage is satirically increasing since all systems have limited amount of memory and memory is costly. Hence it will create problems.Example of memory leakage in C++ " }, { "code": null, "e": 706, "s": 702, "text": "CPP" }, { "code": "// Program with memory leak#include <bits/stdc++.h>using namespace std; // function with memory leakvoid func_to_show_mem_leak(){ int* ptr = new int(5); // body // return without deallocating ptr return;} // driver codeint main(){ // Call the function // to get the memory leak func_to_show_mem_leak(); return 0;}", "e": 1048, "s": 706, "text": null }, { "code": null, "e": 1074, "s": 1048, "text": "How to avoid Memory Leak?" }, { "code": null, "e": 1155, "s": 1074, "text": "Instead of managing memory manually, try to use smart pointers where applicable." }, { "code": null, "e": 1288, "s": 1155, "text": "use std::string instead of char *. The std::string class handles all memory management internally, and it’s fast and well-optimized." }, { "code": null, "e": 1356, "s": 1288, "text": "Never use a raw pointer unless it’s to interface with an older lib." }, { "code": null, "e": 1767, "s": 1356, "text": "The best way to avoid memory leaks in C++ is to have as few new/delete calls at the program level as possible – ideally NONE. Anything that requires dynamic memory should be buried inside an RAII object that releases the memory when it goes out of scope. RAII allocate memory in constructor and release it in destructor, so that memory is guaranteed to be deallocated when the variable leave the current scope." }, { "code": null, "e": 1871, "s": 1767, "text": "Allocate memory by new keyword and deallocate memory by delete keyword and write all code between them." }, { "code": null, "e": 1903, "s": 1871, "text": "Example to handle memory leaks " }, { "code": null, "e": 1907, "s": 1903, "text": "CPP" }, { "code": "// CPP program to// illustrate how to avoid// memory leak#include <bits/stdc++.h>using namespace std; // function to see memory handlingvoid func_to_handle_mem_leak(){ int* ptr = new int(5); // body // Now delete pointer ptr using delete delete (ptr);} // Driver codeint main(){ // Call function to handle // the memory leak func_to_handle_mem_leak() return 0;}", "e": 2301, "s": 1907, "text": null }, { "code": null, "e": 2602, "s": 2301, "text": "Therefore, Always write delete pointer for matching of new pointer in C++ and always write code between these new and delete as explained in above example. In above example, no memory is wasted because when we are coming out from the function we are deallocating the memory by using delete function. " }, { "code": null, "e": 2609, "s": 2602, "text": "thilak" }, { "code": null, "e": 2617, "s": 2609, "text": "clintra" }, { "code": null, "e": 2645, "s": 2617, "text": "C-Dynamic Memory Allocation" }, { "code": null, "e": 2663, "s": 2645, "text": "memory-management" }, { "code": null, "e": 2667, "s": 2663, "text": "C++" }, { "code": null, "e": 2671, "s": 2667, "text": "CPP" }, { "code": null, "e": 2769, "s": 2671, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2812, "s": 2769, "text": "Set in C++ Standard Template Library (STL)" }, { "code": null, "e": 2837, "s": 2812, "text": "unordered_map in C++ STL" }, { "code": null, "e": 2871, "s": 2837, "text": "vector erase() and clear() in C++" }, { "code": null, "e": 2888, "s": 2871, "text": "Substring in C++" }, { "code": null, "e": 2942, "s": 2888, "text": "Priority Queue in C++ Standard Template Library (STL)" }, { "code": null, "e": 2966, "s": 2942, "text": "Sorting a vector in C++" }, { "code": null, "e": 3006, "s": 2966, "text": "2D Vector In C++ With User Defined Size" }, { "code": null, "e": 3030, "s": 3006, "text": "Virtual Function in C++" }, { "code": null, "e": 3045, "s": 3030, "text": "C++ Data Types" } ]
vector : : resize() in C++ STL
26 Apr, 2018 Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container. The function alters the container’s content in actual by inserting or deleting the elements from it. It happens so, If the given value of n is less than the size at present then extra elements are demolished. If n is more than current size of container then upcoming elements are appended at the end of the vector. Syntax: vectorname.resize(int n, int val) Parameters: n – it is new container size, expressed in number of elements. val – if this parameter is specified then new elements are initialized with this value. Return value: This function do not returns anything. Exception: The only exception if it so happens is Bad_alloc thrown, if reallocation fails. Below programs illustrate the working of the function Size of the vector container is lowered.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(4); cout << "Contents of vector after resizing:" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;}Output:Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 Size of the vector container is increased.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(8); cout << "Contents of vector after resizing:" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;}Output:Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 0 0 0 Size of the vector container is increased and new elements are initialized with specified value.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(12, 9); cout << "Contents of vector after resizing:" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;}Output:Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 9 9 9 9 9 9 9 Size of the vector container is lowered.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(4); cout << "Contents of vector after resizing:" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;}Output:Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 // resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(4); cout << "Contents of vector after resizing:" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;} Output: Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 Size of the vector container is increased.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(8); cout << "Contents of vector after resizing:" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;}Output:Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 0 0 0 // resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(8); cout << "Contents of vector after resizing:" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;} Output: Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 0 0 0 Size of the vector container is increased and new elements are initialized with specified value.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(12, 9); cout << "Contents of vector after resizing:" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;}Output:Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 9 9 9 9 9 9 9 // resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << "Contents of vector before resizing:" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; cout << endl; // vector is resized vec.resize(12, 9); cout << "Contents of vector after resizing:" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << " "; return 0;} Output: Contents of the vector before resizing: 1 2 3 4 5 Contents of the vector after resizing: 1 2 3 4 5 9 9 9 9 9 9 9 cpp-vector STL C++ Technical Scripter STL CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n26 Apr, 2018" }, { "code": null, "e": 209, "s": 52, "text": "Vectors are known as dynamic arrays which can change its size automatically when an element is inserted or deleted. This storage is maintained by container." }, { "code": null, "e": 325, "s": 209, "text": "The function alters the container’s content in actual by inserting or deleting the elements from it. It happens so," }, { "code": null, "e": 418, "s": 325, "text": "If the given value of n is less than the size at present then extra elements are demolished." }, { "code": null, "e": 524, "s": 418, "text": "If n is more than current size of container then upcoming elements are appended at the end of the vector." }, { "code": null, "e": 532, "s": 524, "text": "Syntax:" }, { "code": null, "e": 567, "s": 532, "text": "vectorname.resize(int n, int val)\n" }, { "code": null, "e": 579, "s": 567, "text": "Parameters:" }, { "code": null, "e": 642, "s": 579, "text": "n – it is new container size, expressed in number of elements." }, { "code": null, "e": 730, "s": 642, "text": "val – if this parameter is specified then new elements are initialized with this value." }, { "code": null, "e": 744, "s": 730, "text": "Return value:" }, { "code": null, "e": 783, "s": 744, "text": "This function do not returns anything." }, { "code": null, "e": 794, "s": 783, "text": "Exception:" }, { "code": null, "e": 874, "s": 794, "text": "The only exception if it so happens is Bad_alloc thrown, if reallocation fails." }, { "code": null, "e": 928, "s": 874, "text": "Below programs illustrate the working of the function" }, { "code": null, "e": 3764, "s": 928, "text": "Size of the vector container is lowered.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(4); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}Output:Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 \nSize of the vector container is increased.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(8); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}Output:Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 5 0 0 0 \nSize of the vector container is increased and new elements are initialized with specified value.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(12, 9); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}Output:Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 5 9 9 9 9 9 9 9 \n" }, { "code": null, "e": 4683, "s": 3764, "text": "Size of the vector container is lowered.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(4); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}Output:Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 \n" }, { "code": "// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(4); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents of the // vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}", "e": 5456, "s": 4683, "text": null }, { "code": null, "e": 5464, "s": 5456, "text": "Output:" }, { "code": null, "e": 5564, "s": 5464, "text": "Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 \n" }, { "code": null, "e": 6491, "s": 5564, "text": "Size of the vector container is increased.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(8); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}Output:Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 5 0 0 0 \n" }, { "code": "// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of the // vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(8); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents of // the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}", "e": 7262, "s": 6491, "text": null }, { "code": null, "e": 7270, "s": 7262, "text": "Output:" }, { "code": null, "e": 7378, "s": 7270, "text": "Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 5 0 0 0 \n" }, { "code": null, "e": 8370, "s": 7378, "text": "Size of the vector container is increased and new elements are initialized with specified value.// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(12, 9); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}Output:Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 5 9 9 9 9 9 9 9 \n" }, { "code": "// resizing of the vector#include <iostream>#include <vector> using namespace std; int main(){ vector<int> vec; // 5 elements are inserted // in the vector vec.push_back(1); vec.push_back(2); vec.push_back(3); vec.push_back(4); vec.push_back(5); cout << \"Contents of vector before resizing:\" << endl; // displaying the contents of // the vector before resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; cout << endl; // vector is resized vec.resize(12, 9); cout << \"Contents of vector after resizing:\" << endl; // displaying the contents // of the vector after resizing for (int i = 0; i < vec.size(); i++) cout << vec[i] << \" \"; return 0;}", "e": 9144, "s": 8370, "text": null }, { "code": null, "e": 9152, "s": 9144, "text": "Output:" }, { "code": null, "e": 9268, "s": 9152, "text": "Contents of the vector before resizing:\n1 2 3 4 5 \nContents of the vector after resizing:\n1 2 3 4 5 9 9 9 9 9 9 9 \n" }, { "code": null, "e": 9279, "s": 9268, "text": "cpp-vector" }, { "code": null, "e": 9283, "s": 9279, "text": "STL" }, { "code": null, "e": 9287, "s": 9283, "text": "C++" }, { "code": null, "e": 9306, "s": 9287, "text": "Technical Scripter" }, { "code": null, "e": 9310, "s": 9306, "text": "STL" }, { "code": null, "e": 9314, "s": 9310, "text": "CPP" } ]
Social Mapper – Find Social Media Profiles Using Photo Only
23 Sep, 2021 OSINT techniques are too powerful that they can even search the information about the anonymous person on the internet by using his/her face without knowing the actual name of the person. Social Mapper is a Python-based open-source intelligence tool that correlates social media profiles via facial recognition. The Social Mapper tool is available on the GitHub platform, it is free and open-source to use. Social Mapper tool collects various data from many popular social media like: Facebook Instagram LinkedIn Google plus Twitter Vkontakte This tool can be used in the phases of Reconnaissance and can help to perform Social Engineering attacks on the Organization or the Individual Victim. Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process – Python Installation Steps on Linux Step 1: Use the following command to install the tool in your Kali Linux operating system. git clone https://github.com/Greenwolf/social_mapper Step 2: Now use the following command to move into the directory of the tool. You have to move to the directory to run the tool. cd social_mapper Step 3: You are in the directory of the Social Mapper. Now you have to install a dependency of the Social Mapper using the following command. sudo pip3 install -r requirements.txt Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section. python3 social_mapper.py -h Step 5: Add social platform credentials in the social_mapper.py file. leafpad social_mapper.py Example: Perform a fast scan python3 social_mapper.py -f imagefolder -i /home/kali/Desktop/social_mapper/Input-Examples/imagefolder -m fast -tw In this example, we will be performing a fast scan on images specified in the image folder. We are performing a Twitter scan on faces saved in the image folder. Results are saved in the SM-Results folder. Displaying the .html format result file. Kali-Linux Linux-Tools Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Docker - COPY Instruction scp command in Linux with Examples chown command in Linux with Examples SED command in Linux | Set 2 nohup Command in Linux with Examples mv command in Linux with examples chmod command in Linux with examples Array Basics in Shell Scripting | Set 1 Introduction to Linux Operating System Basic Operators in Shell Scripting
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Sep, 2021" }, { "code": null, "e": 513, "s": 28, "text": "OSINT techniques are too powerful that they can even search the information about the anonymous person on the internet by using his/her face without knowing the actual name of the person. Social Mapper is a Python-based open-source intelligence tool that correlates social media profiles via facial recognition. The Social Mapper tool is available on the GitHub platform, it is free and open-source to use. Social Mapper tool collects various data from many popular social media like:" }, { "code": null, "e": 522, "s": 513, "text": "Facebook" }, { "code": null, "e": 532, "s": 522, "text": "Instagram" }, { "code": null, "e": 541, "s": 532, "text": "LinkedIn" }, { "code": null, "e": 553, "s": 541, "text": "Google plus" }, { "code": null, "e": 561, "s": 553, "text": "Twitter" }, { "code": null, "e": 571, "s": 561, "text": "Vkontakte" }, { "code": null, "e": 722, "s": 571, "text": "This tool can be used in the phases of Reconnaissance and can help to perform Social Engineering attacks on the Organization or the Individual Victim." }, { "code": null, "e": 889, "s": 722, "text": "Note: Make Sure You have Python Installed on your System, as this is a python-based tool. Click to check the Installation process – Python Installation Steps on Linux" }, { "code": null, "e": 980, "s": 889, "text": "Step 1: Use the following command to install the tool in your Kali Linux operating system." }, { "code": null, "e": 1033, "s": 980, "text": "git clone https://github.com/Greenwolf/social_mapper" }, { "code": null, "e": 1162, "s": 1033, "text": "Step 2: Now use the following command to move into the directory of the tool. You have to move to the directory to run the tool." }, { "code": null, "e": 1179, "s": 1162, "text": "cd social_mapper" }, { "code": null, "e": 1321, "s": 1179, "text": "Step 3: You are in the directory of the Social Mapper. Now you have to install a dependency of the Social Mapper using the following command." }, { "code": null, "e": 1359, "s": 1321, "text": "sudo pip3 install -r requirements.txt" }, { "code": null, "e": 1519, "s": 1359, "text": "Step 4: All the dependencies have been installed in your Kali Linux operating system. Now use the following command to run the tool and check the help section." }, { "code": null, "e": 1547, "s": 1519, "text": "python3 social_mapper.py -h" }, { "code": null, "e": 1617, "s": 1547, "text": "Step 5: Add social platform credentials in the social_mapper.py file." }, { "code": null, "e": 1642, "s": 1617, "text": "leafpad social_mapper.py" }, { "code": null, "e": 1671, "s": 1642, "text": "Example: Perform a fast scan" }, { "code": null, "e": 1786, "s": 1671, "text": "python3 social_mapper.py -f imagefolder -i /home/kali/Desktop/social_mapper/Input-Examples/imagefolder -m fast -tw" }, { "code": null, "e": 1878, "s": 1786, "text": "In this example, we will be performing a fast scan on images specified in the image folder." }, { "code": null, "e": 1947, "s": 1878, "text": "We are performing a Twitter scan on faces saved in the image folder." }, { "code": null, "e": 1991, "s": 1947, "text": "Results are saved in the SM-Results folder." }, { "code": null, "e": 2032, "s": 1991, "text": "Displaying the .html format result file." }, { "code": null, "e": 2043, "s": 2032, "text": "Kali-Linux" }, { "code": null, "e": 2055, "s": 2043, "text": "Linux-Tools" }, { "code": null, "e": 2066, "s": 2055, "text": "Linux-Unix" }, { "code": null, "e": 2164, "s": 2066, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2190, "s": 2164, "text": "Docker - COPY Instruction" }, { "code": null, "e": 2225, "s": 2190, "text": "scp command in Linux with Examples" }, { "code": null, "e": 2262, "s": 2225, "text": "chown command in Linux with Examples" }, { "code": null, "e": 2291, "s": 2262, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 2328, "s": 2291, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 2362, "s": 2328, "text": "mv command in Linux with examples" }, { "code": null, "e": 2399, "s": 2362, "text": "chmod command in Linux with examples" }, { "code": null, "e": 2439, "s": 2399, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 2478, "s": 2439, "text": "Introduction to Linux Operating System" } ]
How to list the Azure VMs using Azure CLI in PowerShell?
To list all the Azure VMs connected to the particular subscription, we need to use the “Az vm” command. Before that, we need to make sure the Azure is connected to the desired subscription, if not use the below command to set the Azure Subscription. az account set -s 'subscription name or id' Once the Azure subscription is set, we can use the below command to retrieve the Azure VMs. PS C:\> az vm list -otable To get the particular azure VM using CLI, we need to provide the VM name and resource group name. PS C:\> az vm show -n VmName -g ResourceGroupName -otable “az vm show” command finds the VM from the list using parameter -n (VMName) -g (resource group Name).
[ { "code": null, "e": 1437, "s": 1187, "text": "To list all the Azure VMs connected to the particular subscription, we need to use the “Az vm” command. Before that, we need to make sure the Azure is connected to the desired subscription, if not use the below command to set the Azure Subscription." }, { "code": null, "e": 1481, "s": 1437, "text": "az account set -s 'subscription name or id'" }, { "code": null, "e": 1573, "s": 1481, "text": "Once the Azure subscription is set, we can use the below command to retrieve the Azure VMs." }, { "code": null, "e": 1600, "s": 1573, "text": "PS C:\\> az vm list -otable" }, { "code": null, "e": 1698, "s": 1600, "text": "To get the particular azure VM using CLI, we need to provide the VM name and resource group name." }, { "code": null, "e": 1756, "s": 1698, "text": "PS C:\\> az vm show -n VmName -g ResourceGroupName -otable" }, { "code": null, "e": 1858, "s": 1756, "text": "“az vm show” command finds the VM from the list using parameter -n (VMName) -g (resource group Name)." } ]
Underscore.js _.merge() Method
04 Aug, 2020 The _.merge() method merges two or more objects starting with the left-most to the rightmost to create a parent mapping object. Syntax: _.merge(obj1, obj2,..., objn); Parameters: This method takes n objects to merge them. Return Value: This method returns a newly generated merged object. Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed. underscore.js contrib library can be installed using npm install underscore-contrib –save. Example 1: Javascript // Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: "1" }, { b: "2" }, { c:"3" });; console.log("Generated Mapping Object: ", obj); Output: Generated Mapping Object: { a: '1', b: '2', c: '3' } Example 2: if two keys are the same, the generated object will have value for the rightmost key. Javascript // Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: "1" }, { a: "2" }, { b: "2" }, { c:"3" });; console.log("Generated Mapping Object: ", obj); Output: Generated Mapping Object: { a: '2', b: '2', c: '3' } Example 3: If more than one object is the same, the newly generated object will have only one key and value corresponding to those objects. Javascript // Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: "1" }, { a: "1" }, { b: "2" }, { c:"3" });; console.log("Generated Mapping Object: ", obj); Output: Generated Mapping Object: { a: '1', b: '2', c: '3' } Example 4: Javascript // Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: "1", d: "4"}, { a: "1" }, { b: "2" }, { c:"3" });; console.log("Generated Mapping Object: ", obj); Output: Generated Mapping Object: { a: '1', d: '4', b: '2', c: '3' } JavaScript - Underscore.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n04 Aug, 2020" }, { "code": null, "e": 156, "s": 28, "text": "The _.merge() method merges two or more objects starting with the left-most to the rightmost to create a parent mapping object." }, { "code": null, "e": 164, "s": 156, "text": "Syntax:" }, { "code": null, "e": 196, "s": 164, "text": "_.merge(obj1, obj2,..., objn);\n" }, { "code": null, "e": 251, "s": 196, "text": "Parameters: This method takes n objects to merge them." }, { "code": null, "e": 318, "s": 251, "text": "Return Value: This method returns a newly generated merged object." }, { "code": null, "e": 436, "s": 318, "text": "Note: This will not work in normal JavaScript because it requires the underscore.js contrib library to be installed. " }, { "code": null, "e": 527, "s": 436, "text": "underscore.js contrib library can be installed using npm install underscore-contrib –save." }, { "code": null, "e": 539, "s": 527, "text": "Example 1: " }, { "code": null, "e": 550, "s": 539, "text": "Javascript" }, { "code": "// Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: \"1\" }, { b: \"2\" }, { c:\"3\" });; console.log(\"Generated Mapping Object: \", obj);", "e": 734, "s": 550, "text": null }, { "code": null, "e": 742, "s": 734, "text": "Output:" }, { "code": null, "e": 797, "s": 742, "text": "Generated Mapping Object: { a: '1', b: '2', c: '3' }\n" }, { "code": null, "e": 894, "s": 797, "text": "Example 2: if two keys are the same, the generated object will have value for the rightmost key." }, { "code": null, "e": 905, "s": 894, "text": "Javascript" }, { "code": "// Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: \"1\" }, { a: \"2\" }, { b: \"2\" }, { c:\"3\" });; console.log(\"Generated Mapping Object: \", obj);", "e": 1119, "s": 905, "text": null }, { "code": null, "e": 1128, "s": 1119, "text": "Output: " }, { "code": null, "e": 1183, "s": 1128, "text": "Generated Mapping Object: { a: '2', b: '2', c: '3' }\n" }, { "code": null, "e": 1323, "s": 1183, "text": "Example 3: If more than one object is the same, the newly generated object will have only one key and value corresponding to those objects." }, { "code": null, "e": 1334, "s": 1323, "text": "Javascript" }, { "code": "// Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: \"1\" }, { a: \"1\" }, { b: \"2\" }, { c:\"3\" });; console.log(\"Generated Mapping Object: \", obj);", "e": 1548, "s": 1334, "text": null }, { "code": null, "e": 1557, "s": 1548, "text": "Output: " }, { "code": null, "e": 1612, "s": 1557, "text": "Generated Mapping Object: { a: '1', b: '2', c: '3' }\n" }, { "code": null, "e": 1624, "s": 1612, "text": "Example 4: " }, { "code": null, "e": 1635, "s": 1624, "text": "Javascript" }, { "code": "// Defining underscore contrib variablevar _ = require('underscore-contrib'); var obj = _.merge({ a: \"1\", d: \"4\"}, { a: \"1\" }, { b: \"2\" }, { c:\"3\" });; console.log(\"Generated Mapping Object: \", obj);", "e": 1875, "s": 1635, "text": null }, { "code": null, "e": 1884, "s": 1875, "text": "Output: " }, { "code": null, "e": 1947, "s": 1884, "text": "Generated Mapping Object: { a: '1', d: '4', b: '2', c: '3' }\n" }, { "code": null, "e": 1974, "s": 1947, "text": "JavaScript - Underscore.js" }, { "code": null, "e": 1985, "s": 1974, "text": "JavaScript" }, { "code": null, "e": 2002, "s": 1985, "text": "Web Technologies" } ]
LinkedList getLast() Method in Java
02 Jun, 2022 Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and. The Java.util.LinkedList.getLast() method is used to fetch or retrieve the last element from a LinkedList or the element present at the tail of the list. Illustration: Input : 4 --> 1 --> 5 --> 6 --> 1 --> 3 Output: 3 As we all know that getLast() is one of the methods been there up present inside LinkedList class. It retrieves the last element from the object inside which elements of LinkedList are present. As we know LinkedList is a class been present inside java.util package so and if we do operate the following methods the syntax will look like as shown below as follows: import java.util.LinkedList; LinkedList ll = new LinkedList<T>(); ll.getLast(); In simpler words, if we want to know the last element or the tail of LinkedList then do perform the below check as listed below. It will, later on, be illustrated as an example while implementing. Syntax: LinkedList.getLast(); Return Type: The last element or the element present at the tail of the list. Example: Java // Java Program to Illustrate getLast() method // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList class object // Declaring object of string type LinkedList<String> list = new LinkedList<String>(); // Adding elements in the list // using add() method list.add("Geeks"); list.add("for"); list.add("Geeks"); list.add("10"); list.add("20"); // Displaying all elements of LinkedList System.out.println("LinkedList:" + list); // Now from these elements procuring // last element from the list // using getLast() method System.out.println("The last element is: " + list.getLast()); }} LinkedList:[Geeks, for, Geeks, 10, 20] The last element is: 20 solankimayank sweetyty surinderdawra388 simmytarika5 Java - util package Java-Collections Java-Functions java-LinkedList Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Interfaces in Java Stream In Java Collections in Java Singleton Class in Java Multidimensional Arrays in Java Set in Java Stack Class in Java Initialize an ArrayList in Java Introduction to Java Initializing a List in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Jun, 2022" }, { "code": null, "e": 479, "s": 28, "text": "Linked List is a part of the Collection framework present in java.util package. This class is an implementation of the LinkedList data structure which is a linear data structure where the elements are not stored in contiguous locations and every element is a separate object with a data part and. The Java.util.LinkedList.getLast() method is used to fetch or retrieve the last element from a LinkedList or the element present at the tail of the list." }, { "code": null, "e": 493, "s": 479, "text": "Illustration:" }, { "code": null, "e": 543, "s": 493, "text": "Input : 4 --> 1 --> 5 --> 6 --> 1 --> 3\nOutput: 3" }, { "code": null, "e": 907, "s": 543, "text": "As we all know that getLast() is one of the methods been there up present inside LinkedList class. It retrieves the last element from the object inside which elements of LinkedList are present. As we know LinkedList is a class been present inside java.util package so and if we do operate the following methods the syntax will look like as shown below as follows:" }, { "code": null, "e": 989, "s": 907, "text": "import java.util.LinkedList;\nLinkedList ll = new LinkedList<T>(); \nll.getLast();" }, { "code": null, "e": 1186, "s": 989, "text": "In simpler words, if we want to know the last element or the tail of LinkedList then do perform the below check as listed below. It will, later on, be illustrated as an example while implementing." }, { "code": null, "e": 1195, "s": 1186, "text": "Syntax: " }, { "code": null, "e": 1217, "s": 1195, "text": "LinkedList.getLast();" }, { "code": null, "e": 1295, "s": 1217, "text": "Return Type: The last element or the element present at the tail of the list." }, { "code": null, "e": 1304, "s": 1295, "text": "Example:" }, { "code": null, "e": 1309, "s": 1304, "text": "Java" }, { "code": "// Java Program to Illustrate getLast() method // Importing required classesimport java.io.*;import java.util.LinkedList; // Main classpublic class GFG { // Main driver method public static void main(String args[]) { // Creating an empty LinkedList class object // Declaring object of string type LinkedList<String> list = new LinkedList<String>(); // Adding elements in the list // using add() method list.add(\"Geeks\"); list.add(\"for\"); list.add(\"Geeks\"); list.add(\"10\"); list.add(\"20\"); // Displaying all elements of LinkedList System.out.println(\"LinkedList:\" + list); // Now from these elements procuring // last element from the list // using getLast() method System.out.println(\"The last element is: \" + list.getLast()); }}", "e": 2194, "s": 1309, "text": null }, { "code": null, "e": 2257, "s": 2194, "text": "LinkedList:[Geeks, for, Geeks, 10, 20]\nThe last element is: 20" }, { "code": null, "e": 2273, "s": 2259, "text": "solankimayank" }, { "code": null, "e": 2282, "s": 2273, "text": "sweetyty" }, { "code": null, "e": 2299, "s": 2282, "text": "surinderdawra388" }, { "code": null, "e": 2312, "s": 2299, "text": "simmytarika5" }, { "code": null, "e": 2332, "s": 2312, "text": "Java - util package" }, { "code": null, "e": 2349, "s": 2332, "text": "Java-Collections" }, { "code": null, "e": 2364, "s": 2349, "text": "Java-Functions" }, { "code": null, "e": 2380, "s": 2364, "text": "java-LinkedList" }, { "code": null, "e": 2385, "s": 2380, "text": "Java" }, { "code": null, "e": 2390, "s": 2385, "text": "Java" }, { "code": null, "e": 2407, "s": 2390, "text": "Java-Collections" }, { "code": null, "e": 2505, "s": 2407, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2524, "s": 2505, "text": "Interfaces in Java" }, { "code": null, "e": 2539, "s": 2524, "text": "Stream In Java" }, { "code": null, "e": 2559, "s": 2539, "text": "Collections in Java" }, { "code": null, "e": 2583, "s": 2559, "text": "Singleton Class in Java" }, { "code": null, "e": 2615, "s": 2583, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 2627, "s": 2615, "text": "Set in Java" }, { "code": null, "e": 2647, "s": 2627, "text": "Stack Class in Java" }, { "code": null, "e": 2679, "s": 2647, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 2700, "s": 2679, "text": "Introduction to Java" } ]
Python | Split strings and digits from string list
02 Dec, 2019 Sometimes, while working with String list, we can have a problem in which we need to remove the surrounding stray characters or noise from list of digits. This can be in form of Currency prefix, signs of numbers etc. Let’s discuss a way in which this task can be performed. Method : Using list comprehension + strip() + isdigit() + join()The combination of above functions can be used to perform this task. In this, we strip the stray characters from numbers that are identified from the strings and return the result. # Python3 code to demonstrate working of# Extract digit from string list # using list comprehension + strip() + isdigit() + join()from itertools import groupby # initialize list test_list = ["-4", "Rs 25", "5 kg", "+15"] # printing original list print("The original list : " + str(test_list)) # Extract digit from string list # using list comprehension + strip() + isdigit() + join()res = [''.join(j).strip() for sub in test_list for k, j in groupby(sub, str.isdigit)] # printing resultprint("List after removing stray characters : " + str(res)) The original list : ['-4', 'Rs 25', '5 kg', '+15'] List after removing stray characters : ['-', '4', 'Rs', '25', '5', 'kg', '+', '15'] Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers Python program to check whether a number is Prime or not
[ { "code": null, "e": 28, "s": 0, "text": "\n02 Dec, 2019" }, { "code": null, "e": 302, "s": 28, "text": "Sometimes, while working with String list, we can have a problem in which we need to remove the surrounding stray characters or noise from list of digits. This can be in form of Currency prefix, signs of numbers etc. Let’s discuss a way in which this task can be performed." }, { "code": null, "e": 547, "s": 302, "text": "Method : Using list comprehension + strip() + isdigit() + join()The combination of above functions can be used to perform this task. In this, we strip the stray characters from numbers that are identified from the strings and return the result." }, { "code": "# Python3 code to demonstrate working of# Extract digit from string list # using list comprehension + strip() + isdigit() + join()from itertools import groupby # initialize list test_list = [\"-4\", \"Rs 25\", \"5 kg\", \"+15\"] # printing original list print(\"The original list : \" + str(test_list)) # Extract digit from string list # using list comprehension + strip() + isdigit() + join()res = [''.join(j).strip() for sub in test_list for k, j in groupby(sub, str.isdigit)] # printing resultprint(\"List after removing stray characters : \" + str(res))", "e": 1105, "s": 547, "text": null }, { "code": null, "e": 1241, "s": 1105, "text": "The original list : ['-4', 'Rs 25', '5 kg', '+15']\nList after removing stray characters : ['-', '4', 'Rs', '25', '5', 'kg', '+', '15']\n" }, { "code": null, "e": 1262, "s": 1241, "text": "Python list-programs" }, { "code": null, "e": 1269, "s": 1262, "text": "Python" }, { "code": null, "e": 1285, "s": 1269, "text": "Python Programs" }, { "code": null, "e": 1383, "s": 1285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1425, "s": 1383, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1447, "s": 1425, "text": "Enumerate() in Python" }, { "code": null, "e": 1473, "s": 1447, "text": "Python String | replace()" }, { "code": null, "e": 1505, "s": 1473, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1534, "s": 1505, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1556, "s": 1534, "text": "Defaultdict in Python" }, { "code": null, "e": 1595, "s": 1556, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 1633, "s": 1595, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 1670, "s": 1633, "text": "Python Program for Fibonacci numbers" } ]
HTTP headers | Clear-Site-Data
31 Oct, 2019 The HTTP header Clear-Site-Header is a response-type header. This header is used in deleting the browsing data which is in the requesting website. These browsing data includes cache, cookies, storage and executionContents. It helps the web developers to have an improved level of control over data stored by the browser locally. Syntax: Clear-Site-Data: "cache"|"cookies"|"storage"|"executionContexts"|"*" Note: The data to be deleted, directibves should be given within double quotes (” “). Multiple directives can be given at a time. Directives: This header accepts four directives mentioned above and described below: “cache”: It represents that the server wishes to remove locally cached data. “cookies”: It represents the server wishes to delete all the cookies for the origin of response URL. “storage:” It represents the server wishes to remove locally stored data. “executionContents”: It represents the server wishes to remove all the browsing contents for the origin of response URL. ” * “: It represents the server wishes to delete all types of data for the origin of response URL. Examples: In this example header wants to delete the cache, cookies, storage and executionContents data.Clear-Site-Data: "cache", "cookies", "storage", "executionContents" Clear-Site-Data: "cache", "cookies", "storage", "executionContents" In this example header wants to delete all the data.Clear-Site-Data: " * " Clear-Site-Data: " * " Based on the directives mentioned, the corresponding type of data will be removed. To check the Clear-Site-Data go to the Inspect Element->Network click any visible name after that click the header tab if this header is used then it will be visible to you. Supported Browsers: The browsers compatible with HTTP Clear-Site-Data headers are given below. Google Chrome Firefox Opera HTTP-headers Picked 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 How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ? Difference Between PUT and PATCH Request How to Open URL in New Tab using JavaScript ?
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Oct, 2019" }, { "code": null, "e": 357, "s": 28, "text": "The HTTP header Clear-Site-Header is a response-type header. This header is used in deleting the browsing data which is in the requesting website. These browsing data includes cache, cookies, storage and executionContents. It helps the web developers to have an improved level of control over data stored by the browser locally." }, { "code": null, "e": 365, "s": 357, "text": "Syntax:" }, { "code": null, "e": 434, "s": 365, "text": "Clear-Site-Data: \"cache\"|\"cookies\"|\"storage\"|\"executionContexts\"|\"*\"" }, { "code": null, "e": 564, "s": 434, "text": "Note: The data to be deleted, directibves should be given within double quotes (” “). Multiple directives can be given at a time." }, { "code": null, "e": 649, "s": 564, "text": "Directives: This header accepts four directives mentioned above and described below:" }, { "code": null, "e": 726, "s": 649, "text": "“cache”: It represents that the server wishes to remove locally cached data." }, { "code": null, "e": 827, "s": 726, "text": "“cookies”: It represents the server wishes to delete all the cookies for the origin of response URL." }, { "code": null, "e": 901, "s": 827, "text": "“storage:” It represents the server wishes to remove locally stored data." }, { "code": null, "e": 1022, "s": 901, "text": "“executionContents”: It represents the server wishes to remove all the browsing contents for the origin of response URL." }, { "code": null, "e": 1121, "s": 1022, "text": "” * “: It represents the server wishes to delete all types of data for the origin of response URL." }, { "code": null, "e": 1131, "s": 1121, "text": "Examples:" }, { "code": null, "e": 1293, "s": 1131, "text": "In this example header wants to delete the cache, cookies, storage and executionContents data.Clear-Site-Data: \"cache\", \"cookies\", \"storage\", \"executionContents\"" }, { "code": null, "e": 1361, "s": 1293, "text": "Clear-Site-Data: \"cache\", \"cookies\", \"storage\", \"executionContents\"" }, { "code": null, "e": 1436, "s": 1361, "text": "In this example header wants to delete all the data.Clear-Site-Data: \" * \"" }, { "code": null, "e": 1459, "s": 1436, "text": "Clear-Site-Data: \" * \"" }, { "code": null, "e": 1716, "s": 1459, "text": "Based on the directives mentioned, the corresponding type of data will be removed. To check the Clear-Site-Data go to the Inspect Element->Network click any visible name after that click the header tab if this header is used then it will be visible to you." }, { "code": null, "e": 1811, "s": 1716, "text": "Supported Browsers: The browsers compatible with HTTP Clear-Site-Data headers are given below." }, { "code": null, "e": 1825, "s": 1811, "text": "Google Chrome" }, { "code": null, "e": 1833, "s": 1825, "text": "Firefox" }, { "code": null, "e": 1839, "s": 1833, "text": "Opera" }, { "code": null, "e": 1852, "s": 1839, "text": "HTTP-headers" }, { "code": null, "e": 1859, "s": 1852, "text": "Picked" }, { "code": null, "e": 1876, "s": 1859, "text": "Web Technologies" }, { "code": null, "e": 1974, "s": 1876, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2035, "s": 1974, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2078, "s": 2035, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 2150, "s": 2078, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 2190, "s": 2150, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2214, "s": 2190, "text": "REST API (Introduction)" }, { "code": null, "e": 2274, "s": 2214, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2332, "s": 2274, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 2393, "s": 2332, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 2434, "s": 2393, "text": "Difference Between PUT and PATCH Request" } ]
How to Shake Text on hover using HTML and CSS?
31 Jul, 2020 Shaking Text animation is a very cool animation which can be used in websites, this animation can be easily created using some basic HTML and CSS, the below section will guide on how to create the animation. HTML Code: In this section we have a basic div element which contains some text inside of it. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shake Text</title></head><body> <div> <h2>Shake!</h2> </div> </body></html> CSS Code: In this section first we will design the text with some basic CSS and use @keyframes animation and then use the transitionX() function to produce the shaking effect when we hover over the text. <style> *{ margin: 0; padding: 0; } /* designing the text*/ div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 2.5em; color: rgb(4, 110, 4); } /*creating the shake animation*/ div:hover h2{ animation: shake 0.8s ; } @keyframes shake{ 0%{ transform: translateX(0) } 25%{ transform: translateX(25px); } 50%{ transform: translateX(-25px); } 100%{ transform: translateX(0px); } } </style> Final Code: It is the combination of the above two code sections. <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Shake Text</title></head><style> *{ margin: 0; padding: 0; } /* designing the text*/ div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 2.5em; color: rgb(4, 110, 4); } /*creating the shake animation*/ div:hover h2{ animation: shake 0.8s ; } @keyframes shake{ 0%{ transform: translateX(0) } 25%{ transform: translateX(25px); } 50%{ transform: translateX(-25px); } 100%{ transform: translateX(0px); } } </style> <body> <div> <h2>Shake!</h2> </div> </body></html> Output: HTML-DOM CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? Design a Tribute Page using HTML & CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? Design a Tribute Page using HTML & CSS Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 28, "s": 0, "text": "\n31 Jul, 2020" }, { "code": null, "e": 236, "s": 28, "text": "Shaking Text animation is a very cool animation which can be used in websites, this animation can be easily created using some basic HTML and CSS, the below section will guide on how to create the animation." }, { "code": null, "e": 330, "s": 236, "text": "HTML Code: In this section we have a basic div element which contains some text inside of it." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Shake Text</title></head><body> <div> <h2>Shake!</h2> </div> </body></html>", "e": 565, "s": 330, "text": null }, { "code": null, "e": 769, "s": 565, "text": "CSS Code: In this section first we will design the text with some basic CSS and use @keyframes animation and then use the transitionX() function to produce the shaking effect when we hover over the text." }, { "code": "<style> *{ margin: 0; padding: 0; } /* designing the text*/ div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 2.5em; color: rgb(4, 110, 4); } /*creating the shake animation*/ div:hover h2{ animation: shake 0.8s ; } @keyframes shake{ 0%{ transform: translateX(0) } 25%{ transform: translateX(25px); } 50%{ transform: translateX(-25px); } 100%{ transform: translateX(0px); } } </style>", "e": 1292, "s": 769, "text": null }, { "code": null, "e": 1358, "s": 1292, "text": "Final Code: It is the combination of the above two code sections." }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Shake Text</title></head><style> *{ margin: 0; padding: 0; } /* designing the text*/ div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); font-size: 2.5em; color: rgb(4, 110, 4); } /*creating the shake animation*/ div:hover h2{ animation: shake 0.8s ; } @keyframes shake{ 0%{ transform: translateX(0) } 25%{ transform: translateX(25px); } 50%{ transform: translateX(-25px); } 100%{ transform: translateX(0px); } } </style> <body> <div> <h2>Shake!</h2> </div> </body></html>", "e": 2156, "s": 1358, "text": null }, { "code": null, "e": 2164, "s": 2156, "text": "Output:" }, { "code": null, "e": 2173, "s": 2164, "text": "HTML-DOM" }, { "code": null, "e": 2177, "s": 2173, "text": "CSS" }, { "code": null, "e": 2182, "s": 2177, "text": "HTML" }, { "code": null, "e": 2199, "s": 2182, "text": "Web Technologies" }, { "code": null, "e": 2204, "s": 2199, "text": "HTML" }, { "code": null, "e": 2302, "s": 2204, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2339, "s": 2302, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2378, "s": 2339, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2442, "s": 2378, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 2503, "s": 2442, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2542, "s": 2503, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2566, "s": 2542, "text": "REST API (Introduction)" }, { "code": null, "e": 2619, "s": 2566, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2679, "s": 2619, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2718, "s": 2679, "text": "Design a Tribute Page using HTML & CSS" } ]
Create Rock Paper Scissor Game using ReactJS
10 Dec, 2020 Here both the players will take their turn one by one. Starting with player one followed by player two. There are three weapons to select from namely stone, paper, scissors. Once player two plays his turn result is computed updating the win/lose the status of both the players. Technologies Used / Pre-requisites: ReactJSAntd library for UI ReactJS Antd library for UI Approach: Containers are ​ Stateful​ React components ( Class Based ). Components are ​ Stateless​ React Components ( Function-Based ). In this project, I have one container that is Controller which is responsible for state management and the entire game logic. Also, there are three components namely: Player ->Represent​ing a Player entity in-game; GameControls -> For Choosing stone, paper, or scissor; DecisionBox -> Displays win/loose status for players; On clicking weapon buttons state in Controller is updated for the respective player. When the second player’s weapon is updated result is computed by the result handler function which covers all nine combinations of stone, paper, scissors taken two at a time. Project Structure: Steps : Set up React project using create-react-app command: create-react-app <<name of project>> –scripts-version 1.1.5. Using this command project structure like above will be generated except components and container folders that are to be created inside src folder manually.Install antd library using the command: npm install antdRemove the code inside App.css.Edit code inside App.js: App Component renders Controller and displays title.App.jsJavascriptJavascriptimport React, { Component } from "react";import Controller from "./containers/controller/controller";import { Typography } from "antd"; import "antd/dist/antd.css"; import "./App.css";const { Title } = Typography; class App extends Component { render() { return ( <div className="App"> <Title level={3} style={{ textAlign: "center" }}> Stone Paper Scissor </Title> <Controller /> </div> ); }} export default App;Controller.js: The controller holds a state which includes each player’s last used weapon, current win/loose status, and active state indicating which player’s turn it isJavascriptJavascriptimport React, { Component } from "react";import { Row, Col, Divider } from "antd";import { Typography } from "antd";import axios from "axios";import "antd/dist/antd.css"; import Player from "../../components/Player/Player";const { Title } = Typography; class Controller extends Component { state = { playerOne: { active: true, weapon: "", status: "" }, playerTwo: { active: false, weapon: "", status: "" } };The core idea here is that on clicking weapon buttons corresponding player’s weapon in the state should get updated and the next player’s turn should come which is done here via toggleactive function. Also, if the second player’s weapon is updated then win/loose should be updated too which is done here via resultHandler function. For game logic it holds a bunch of functions :WeaponUpdate: For updating a player’s weapon in the state. It takes two arguments first is playerId i.e playerOne or playerTwo since it’s a two-player game and the second is a weapon that is chosen by the player.JavascriptJavascriptweaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == "playerTwo") {this.resultHandler();} else {this.toggleActive();}};ToggleActive: For reversing active status of players once either of player selects a weapon. Active property in the state is a boolean variable, so we just have to use NOT operator to reverse the current state of each player.JavascriptJavascripttoggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});};ResultHandler: It contains the major game logic which decides which player has won. It uses a helper function called decision helper which takes two arguments that are each player’s weapon and returns an array containing two elements wherein the first element corresponds to the first player’s win/loose status and similarly the second element to the second player’s status. Then resulthandler updates state with values returned by decicerhelper function.JavascriptJavascriptresultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();};DeciderHelper: It is a helper function that takes two inputs that are weapons for each player and returns an array consisting of two elements each denoting the win/loose status of player 1 and player 2 respectively. Here ‘r’ stands for rock, ‘s’ stands for scissors, ‘p’ stands for the paper, ‘w’ for the win, and ‘l’ stands for loose. All possible combinations of rock, stone, scissors are considered in case of a tie both players with win status are returned.JavascriptJavascriptdeciderHelper = (p1, p2) => { if (p1 == "r" && p2 == "s") { return ["w", "l"]; } if (p1 == "r" && p2 == "p") { return ["l", "w"]; } if (p1 == "r" && p2 == "r") { return ["w", "w"]; } if (p1 == "p" && p2 == "r") { return ["w", "l"]; } if (p1 == "p" && p2 == "s") { return ["l", "w"]; } if (p1 == "p" && p2 == "p") { return ["w", "w"]; } if (p1 == "s" && p2 == "r") { return ["l", "w"]; } if (p1 == "s" && p2 == "p") { return ["w", "l"]; } if (p1 == "s" && p2 == "s") { return ["w", "w"]; }};Render Method:JavascriptJavascriptrender() { return ( <Row justify="space-around" align="middle"> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate("playerOne", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate("playerTwo", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller;Coding the Components: Code is very simple in these. Just the representational logic resides here.Player.js: As mentioned earlier it’s a stateless component representing a player entity. It receives four props that are the active status of the player, current weapon, win/loose status, and functionHandler for updating weapon. It further uses two components GameControls and decision box which are discussed below. Also, if active props received are true then a CSS object called glowEffect is applied to the div.JavascriptJavascriptimport React from "react";import GameControls from "../GameControls/GameControls";import DecisionBox from "../DecisionBox/DecisionBox"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { "-webkit-box-shadow": "0 0 20px blue", "-moz-box-shadow": "0 0 20px blue", "box-shadow": "0 0 20px blue" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player;GameControls.js: It contains three buttons rock, stone, scissors. If the player is not active then the buttons are disabled. On button click weaponupdate function is called which takes one argument ‘p’ for paper, ‘r’ for rock, ‘s’ for scissors and state of corresponding gets updated.JavascriptJavascriptimport React from "react";import { Card } from "antd";import { Button } from "antd"; import "antd/dist/antd.css"; const GameControls = props => { return ( <Card title="Controls" style={{ width: "300px", height: "250px", alignItems: "center" }} > <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("r")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: "center" }}> {" "} <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("p")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("s")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls;DecisionBox.js: It displays two things player’s weapon and the player’s win/loose status. It receives two props weapon (‘r’ or ‘p’ or ‘s’ ) and status (‘w’ or ‘l’ ). Two objects weaponmap and status map are used for mapping shortforms to proper words that can be displayed on the screen.JavascriptJavascriptimport React from "react";import { Card } from "antd";import { Typography } from "antd"; const { Title } = Typography; const weaponMap = { s: "Scissors", p: "Paper", r: "Rock"};const statusMap = { w: "Win", l: "Loose"}; const DecisionBox = props => { return ( <Card title="Decision Box" style={{ width: "300px", height: "250px", alignItems: "center", marginTop: "15px" }} bodyStyle={{ textAlign: "center" }} > <Title level={1} type="warning"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type="secondary"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox; Set up React project using create-react-app command: create-react-app <<name of project>> –scripts-version 1.1.5. Using this command project structure like above will be generated except components and container folders that are to be created inside src folder manually. Install antd library using the command: npm install antd Remove the code inside App.css. Edit code inside App.js: App Component renders Controller and displays title.App.jsJavascriptJavascriptimport React, { Component } from "react";import Controller from "./containers/controller/controller";import { Typography } from "antd"; import "antd/dist/antd.css"; import "./App.css";const { Title } = Typography; class App extends Component { render() { return ( <div className="App"> <Title level={3} style={{ textAlign: "center" }}> Stone Paper Scissor </Title> <Controller /> </div> ); }} export default App; Javascript import React, { Component } from "react";import Controller from "./containers/controller/controller";import { Typography } from "antd"; import "antd/dist/antd.css"; import "./App.css";const { Title } = Typography; class App extends Component { render() { return ( <div className="App"> <Title level={3} style={{ textAlign: "center" }}> Stone Paper Scissor </Title> <Controller /> </div> ); }} export default App; Controller.js: The controller holds a state which includes each player’s last used weapon, current win/loose status, and active state indicating which player’s turn it isJavascriptJavascriptimport React, { Component } from "react";import { Row, Col, Divider } from "antd";import { Typography } from "antd";import axios from "axios";import "antd/dist/antd.css"; import Player from "../../components/Player/Player";const { Title } = Typography; class Controller extends Component { state = { playerOne: { active: true, weapon: "", status: "" }, playerTwo: { active: false, weapon: "", status: "" } };The core idea here is that on clicking weapon buttons corresponding player’s weapon in the state should get updated and the next player’s turn should come which is done here via toggleactive function. Also, if the second player’s weapon is updated then win/loose should be updated too which is done here via resultHandler function. For game logic it holds a bunch of functions :WeaponUpdate: For updating a player’s weapon in the state. It takes two arguments first is playerId i.e playerOne or playerTwo since it’s a two-player game and the second is a weapon that is chosen by the player.JavascriptJavascriptweaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == "playerTwo") {this.resultHandler();} else {this.toggleActive();}};ToggleActive: For reversing active status of players once either of player selects a weapon. Active property in the state is a boolean variable, so we just have to use NOT operator to reverse the current state of each player.JavascriptJavascripttoggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});};ResultHandler: It contains the major game logic which decides which player has won. It uses a helper function called decision helper which takes two arguments that are each player’s weapon and returns an array containing two elements wherein the first element corresponds to the first player’s win/loose status and similarly the second element to the second player’s status. Then resulthandler updates state with values returned by decicerhelper function.JavascriptJavascriptresultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();};DeciderHelper: It is a helper function that takes two inputs that are weapons for each player and returns an array consisting of two elements each denoting the win/loose status of player 1 and player 2 respectively. Here ‘r’ stands for rock, ‘s’ stands for scissors, ‘p’ stands for the paper, ‘w’ for the win, and ‘l’ stands for loose. All possible combinations of rock, stone, scissors are considered in case of a tie both players with win status are returned.JavascriptJavascriptdeciderHelper = (p1, p2) => { if (p1 == "r" && p2 == "s") { return ["w", "l"]; } if (p1 == "r" && p2 == "p") { return ["l", "w"]; } if (p1 == "r" && p2 == "r") { return ["w", "w"]; } if (p1 == "p" && p2 == "r") { return ["w", "l"]; } if (p1 == "p" && p2 == "s") { return ["l", "w"]; } if (p1 == "p" && p2 == "p") { return ["w", "w"]; } if (p1 == "s" && p2 == "r") { return ["l", "w"]; } if (p1 == "s" && p2 == "p") { return ["w", "l"]; } if (p1 == "s" && p2 == "s") { return ["w", "w"]; }};Render Method:JavascriptJavascriptrender() { return ( <Row justify="space-around" align="middle"> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate("playerOne", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate("playerTwo", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller; Controller.js: The controller holds a state which includes each player’s last used weapon, current win/loose status, and active state indicating which player’s turn it is Javascript import React, { Component } from "react";import { Row, Col, Divider } from "antd";import { Typography } from "antd";import axios from "axios";import "antd/dist/antd.css"; import Player from "../../components/Player/Player";const { Title } = Typography; class Controller extends Component { state = { playerOne: { active: true, weapon: "", status: "" }, playerTwo: { active: false, weapon: "", status: "" } }; The core idea here is that on clicking weapon buttons corresponding player’s weapon in the state should get updated and the next player’s turn should come which is done here via toggleactive function. Also, if the second player’s weapon is updated then win/loose should be updated too which is done here via resultHandler function. For game logic it holds a bunch of functions : WeaponUpdate: For updating a player’s weapon in the state. It takes two arguments first is playerId i.e playerOne or playerTwo since it’s a two-player game and the second is a weapon that is chosen by the player.JavascriptJavascriptweaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == "playerTwo") {this.resultHandler();} else {this.toggleActive();}}; Javascript weaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == "playerTwo") {this.resultHandler();} else {this.toggleActive();}}; ToggleActive: For reversing active status of players once either of player selects a weapon. Active property in the state is a boolean variable, so we just have to use NOT operator to reverse the current state of each player.JavascriptJavascripttoggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});}; Javascript toggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});}; ResultHandler: It contains the major game logic which decides which player has won. It uses a helper function called decision helper which takes two arguments that are each player’s weapon and returns an array containing two elements wherein the first element corresponds to the first player’s win/loose status and similarly the second element to the second player’s status. Then resulthandler updates state with values returned by decicerhelper function.JavascriptJavascriptresultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();}; Javascript resultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();}; DeciderHelper: It is a helper function that takes two inputs that are weapons for each player and returns an array consisting of two elements each denoting the win/loose status of player 1 and player 2 respectively. Here ‘r’ stands for rock, ‘s’ stands for scissors, ‘p’ stands for the paper, ‘w’ for the win, and ‘l’ stands for loose. All possible combinations of rock, stone, scissors are considered in case of a tie both players with win status are returned.JavascriptJavascriptdeciderHelper = (p1, p2) => { if (p1 == "r" && p2 == "s") { return ["w", "l"]; } if (p1 == "r" && p2 == "p") { return ["l", "w"]; } if (p1 == "r" && p2 == "r") { return ["w", "w"]; } if (p1 == "p" && p2 == "r") { return ["w", "l"]; } if (p1 == "p" && p2 == "s") { return ["l", "w"]; } if (p1 == "p" && p2 == "p") { return ["w", "w"]; } if (p1 == "s" && p2 == "r") { return ["l", "w"]; } if (p1 == "s" && p2 == "p") { return ["w", "l"]; } if (p1 == "s" && p2 == "s") { return ["w", "w"]; }}; Javascript deciderHelper = (p1, p2) => { if (p1 == "r" && p2 == "s") { return ["w", "l"]; } if (p1 == "r" && p2 == "p") { return ["l", "w"]; } if (p1 == "r" && p2 == "r") { return ["w", "w"]; } if (p1 == "p" && p2 == "r") { return ["w", "l"]; } if (p1 == "p" && p2 == "s") { return ["l", "w"]; } if (p1 == "p" && p2 == "p") { return ["w", "w"]; } if (p1 == "s" && p2 == "r") { return ["l", "w"]; } if (p1 == "s" && p2 == "p") { return ["w", "l"]; } if (p1 == "s" && p2 == "s") { return ["w", "w"]; }}; Render Method:JavascriptJavascriptrender() { return ( <Row justify="space-around" align="middle"> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate("playerOne", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate("playerTwo", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller; Javascript render() { return ( <Row justify="space-around" align="middle"> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate("playerOne", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className="gutter-row" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate("playerTwo", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller; Coding the Components: Code is very simple in these. Just the representational logic resides here.Player.js: As mentioned earlier it’s a stateless component representing a player entity. It receives four props that are the active status of the player, current weapon, win/loose status, and functionHandler for updating weapon. It further uses two components GameControls and decision box which are discussed below. Also, if active props received are true then a CSS object called glowEffect is applied to the div.JavascriptJavascriptimport React from "react";import GameControls from "../GameControls/GameControls";import DecisionBox from "../DecisionBox/DecisionBox"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { "-webkit-box-shadow": "0 0 20px blue", "-moz-box-shadow": "0 0 20px blue", "box-shadow": "0 0 20px blue" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player;GameControls.js: It contains three buttons rock, stone, scissors. If the player is not active then the buttons are disabled. On button click weaponupdate function is called which takes one argument ‘p’ for paper, ‘r’ for rock, ‘s’ for scissors and state of corresponding gets updated.JavascriptJavascriptimport React from "react";import { Card } from "antd";import { Button } from "antd"; import "antd/dist/antd.css"; const GameControls = props => { return ( <Card title="Controls" style={{ width: "300px", height: "250px", alignItems: "center" }} > <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("r")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: "center" }}> {" "} <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("p")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("s")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls;DecisionBox.js: It displays two things player’s weapon and the player’s win/loose status. It receives two props weapon (‘r’ or ‘p’ or ‘s’ ) and status (‘w’ or ‘l’ ). Two objects weaponmap and status map are used for mapping shortforms to proper words that can be displayed on the screen.JavascriptJavascriptimport React from "react";import { Card } from "antd";import { Typography } from "antd"; const { Title } = Typography; const weaponMap = { s: "Scissors", p: "Paper", r: "Rock"};const statusMap = { w: "Win", l: "Loose"}; const DecisionBox = props => { return ( <Card title="Decision Box" style={{ width: "300px", height: "250px", alignItems: "center", marginTop: "15px" }} bodyStyle={{ textAlign: "center" }} > <Title level={1} type="warning"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type="secondary"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox; Coding the Components: Code is very simple in these. Just the representational logic resides here. Player.js: As mentioned earlier it’s a stateless component representing a player entity. It receives four props that are the active status of the player, current weapon, win/loose status, and functionHandler for updating weapon. It further uses two components GameControls and decision box which are discussed below. Also, if active props received are true then a CSS object called glowEffect is applied to the div.JavascriptJavascriptimport React from "react";import GameControls from "../GameControls/GameControls";import DecisionBox from "../DecisionBox/DecisionBox"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { "-webkit-box-shadow": "0 0 20px blue", "-moz-box-shadow": "0 0 20px blue", "box-shadow": "0 0 20px blue" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player; Javascript import React from "react";import GameControls from "../GameControls/GameControls";import DecisionBox from "../DecisionBox/DecisionBox"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { "-webkit-box-shadow": "0 0 20px blue", "-moz-box-shadow": "0 0 20px blue", "box-shadow": "0 0 20px blue" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player; GameControls.js: It contains three buttons rock, stone, scissors. If the player is not active then the buttons are disabled. On button click weaponupdate function is called which takes one argument ‘p’ for paper, ‘r’ for rock, ‘s’ for scissors and state of corresponding gets updated.JavascriptJavascriptimport React from "react";import { Card } from "antd";import { Button } from "antd"; import "antd/dist/antd.css"; const GameControls = props => { return ( <Card title="Controls" style={{ width: "300px", height: "250px", alignItems: "center" }} > <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("r")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: "center" }}> {" "} <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("p")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("s")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls; Javascript import React from "react";import { Card } from "antd";import { Button } from "antd"; import "antd/dist/antd.css"; const GameControls = props => { return ( <Card title="Controls" style={{ width: "300px", height: "250px", alignItems: "center" }} > <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("r")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: "center" }}> {" "} <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("p")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: "center" }}> <Button type="dashed" size="large" shape="round" block onClick={() => props.wUpdate("s")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls; DecisionBox.js: It displays two things player’s weapon and the player’s win/loose status. It receives two props weapon (‘r’ or ‘p’ or ‘s’ ) and status (‘w’ or ‘l’ ). Two objects weaponmap and status map are used for mapping shortforms to proper words that can be displayed on the screen.JavascriptJavascriptimport React from "react";import { Card } from "antd";import { Typography } from "antd"; const { Title } = Typography; const weaponMap = { s: "Scissors", p: "Paper", r: "Rock"};const statusMap = { w: "Win", l: "Loose"}; const DecisionBox = props => { return ( <Card title="Decision Box" style={{ width: "300px", height: "250px", alignItems: "center", marginTop: "15px" }} bodyStyle={{ textAlign: "center" }} > <Title level={1} type="warning"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type="secondary"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox; Javascript import React from "react";import { Card } from "antd";import { Typography } from "antd"; const { Title } = Typography; const weaponMap = { s: "Scissors", p: "Paper", r: "Rock"};const statusMap = { w: "Win", l: "Loose"}; const DecisionBox = props => { return ( <Card title="Decision Box" style={{ width: "300px", height: "250px", alignItems: "center", marginTop: "15px" }} bodyStyle={{ textAlign: "center" }} > <Title level={1} type="warning"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type="secondary"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox; Output: react-js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Dec, 2020" }, { "code": null, "e": 306, "s": 28, "text": "Here both the players will take their turn one by one. Starting with player one followed by player two. There are three weapons to select from namely stone, paper, scissors. Once player two plays his turn result is computed updating the win/lose the status of both the players." }, { "code": null, "e": 342, "s": 306, "text": "Technologies Used / Pre-requisites:" }, { "code": null, "e": 369, "s": 342, "text": "ReactJSAntd library for UI" }, { "code": null, "e": 377, "s": 369, "text": "ReactJS" }, { "code": null, "e": 397, "s": 377, "text": "Antd library for UI" }, { "code": null, "e": 700, "s": 397, "text": "Approach: Containers are ​ Stateful​ React components ( Class Based ). Components are ​ Stateless​ React Components ( Function-Based ). In this project, I have one container that is Controller which is responsible for state management and the entire game logic. Also, there are three components namely:" }, { "code": null, "e": 858, "s": 700, "text": "Player ->Represent​ing a Player entity in-game;\nGameControls -> For Choosing stone, paper, or scissor; \nDecisionBox -> Displays win/loose status for players;" }, { "code": null, "e": 1118, "s": 858, "text": "On clicking weapon buttons state in Controller is updated for the respective player. When the second player’s weapon is updated result is computed by the result handler function which covers all nine combinations of stone, paper, scissors taken two at a time." }, { "code": null, "e": 1137, "s": 1118, "text": "Project Structure:" }, { "code": null, "e": 1145, "s": 1137, "text": "Steps :" }, { "code": null, "e": 10210, "s": 1145, "text": "Set up React project using create-react-app command: create-react-app <<name of project>> –scripts-version 1.1.5. Using this command project structure like above will be generated except components and container folders that are to be created inside src folder manually.Install antd library using the command: npm install antdRemove the code inside App.css.Edit code inside App.js: App Component renders Controller and displays title.App.jsJavascriptJavascriptimport React, { Component } from \"react\";import Controller from \"./containers/controller/controller\";import { Typography } from \"antd\"; import \"antd/dist/antd.css\"; import \"./App.css\";const { Title } = Typography; class App extends Component { render() { return ( <div className=\"App\"> <Title level={3} style={{ textAlign: \"center\" }}> Stone Paper Scissor </Title> <Controller /> </div> ); }} export default App;Controller.js: The controller holds a state which includes each player’s last used weapon, current win/loose status, and active state indicating which player’s turn it isJavascriptJavascriptimport React, { Component } from \"react\";import { Row, Col, Divider } from \"antd\";import { Typography } from \"antd\";import axios from \"axios\";import \"antd/dist/antd.css\"; import Player from \"../../components/Player/Player\";const { Title } = Typography; class Controller extends Component { state = { playerOne: { active: true, weapon: \"\", status: \"\" }, playerTwo: { active: false, weapon: \"\", status: \"\" } };The core idea here is that on clicking weapon buttons corresponding player’s weapon in the state should get updated and the next player’s turn should come which is done here via toggleactive function. Also, if the second player’s weapon is updated then win/loose should be updated too which is done here via resultHandler function. For game logic it holds a bunch of functions :WeaponUpdate: For updating a player’s weapon in the state. It takes two arguments first is playerId i.e playerOne or playerTwo since it’s a two-player game and the second is a weapon that is chosen by the player.JavascriptJavascriptweaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == \"playerTwo\") {this.resultHandler();} else {this.toggleActive();}};ToggleActive: For reversing active status of players once either of player selects a weapon. Active property in the state is a boolean variable, so we just have to use NOT operator to reverse the current state of each player.JavascriptJavascripttoggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});};ResultHandler: It contains the major game logic which decides which player has won. It uses a helper function called decision helper which takes two arguments that are each player’s weapon and returns an array containing two elements wherein the first element corresponds to the first player’s win/loose status and similarly the second element to the second player’s status. Then resulthandler updates state with values returned by decicerhelper function.JavascriptJavascriptresultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();};DeciderHelper: It is a helper function that takes two inputs that are weapons for each player and returns an array consisting of two elements each denoting the win/loose status of player 1 and player 2 respectively. Here ‘r’ stands for rock, ‘s’ stands for scissors, ‘p’ stands for the paper, ‘w’ for the win, and ‘l’ stands for loose. All possible combinations of rock, stone, scissors are considered in case of a tie both players with win status are returned.JavascriptJavascriptdeciderHelper = (p1, p2) => { if (p1 == \"r\" && p2 == \"s\") { return [\"w\", \"l\"]; } if (p1 == \"r\" && p2 == \"p\") { return [\"l\", \"w\"]; } if (p1 == \"r\" && p2 == \"r\") { return [\"w\", \"w\"]; } if (p1 == \"p\" && p2 == \"r\") { return [\"w\", \"l\"]; } if (p1 == \"p\" && p2 == \"s\") { return [\"l\", \"w\"]; } if (p1 == \"p\" && p2 == \"p\") { return [\"w\", \"w\"]; } if (p1 == \"s\" && p2 == \"r\") { return [\"l\", \"w\"]; } if (p1 == \"s\" && p2 == \"p\") { return [\"w\", \"l\"]; } if (p1 == \"s\" && p2 == \"s\") { return [\"w\", \"w\"]; }};Render Method:JavascriptJavascriptrender() { return ( <Row justify=\"space-around\" align=\"middle\"> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate(\"playerOne\", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate(\"playerTwo\", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller;Coding the Components: Code is very simple in these. Just the representational logic resides here.Player.js: As mentioned earlier it’s a stateless component representing a player entity. It receives four props that are the active status of the player, current weapon, win/loose status, and functionHandler for updating weapon. It further uses two components GameControls and decision box which are discussed below. Also, if active props received are true then a CSS object called glowEffect is applied to the div.JavascriptJavascriptimport React from \"react\";import GameControls from \"../GameControls/GameControls\";import DecisionBox from \"../DecisionBox/DecisionBox\"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { \"-webkit-box-shadow\": \"0 0 20px blue\", \"-moz-box-shadow\": \"0 0 20px blue\", \"box-shadow\": \"0 0 20px blue\" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player;GameControls.js: It contains three buttons rock, stone, scissors. If the player is not active then the buttons are disabled. On button click weaponupdate function is called which takes one argument ‘p’ for paper, ‘r’ for rock, ‘s’ for scissors and state of corresponding gets updated.JavascriptJavascriptimport React from \"react\";import { Card } from \"antd\";import { Button } from \"antd\"; import \"antd/dist/antd.css\"; const GameControls = props => { return ( <Card title=\"Controls\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\" }} > <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"r\")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: \"center\" }}> {\" \"} <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"p\")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"s\")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls;DecisionBox.js: It displays two things player’s weapon and the player’s win/loose status. It receives two props weapon (‘r’ or ‘p’ or ‘s’ ) and status (‘w’ or ‘l’ ). Two objects weaponmap and status map are used for mapping shortforms to proper words that can be displayed on the screen.JavascriptJavascriptimport React from \"react\";import { Card } from \"antd\";import { Typography } from \"antd\"; const { Title } = Typography; const weaponMap = { s: \"Scissors\", p: \"Paper\", r: \"Rock\"};const statusMap = { w: \"Win\", l: \"Loose\"}; const DecisionBox = props => { return ( <Card title=\"Decision Box\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\", marginTop: \"15px\" }} bodyStyle={{ textAlign: \"center\" }} > <Title level={1} type=\"warning\"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type=\"secondary\"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox;" }, { "code": null, "e": 10481, "s": 10210, "text": "Set up React project using create-react-app command: create-react-app <<name of project>> –scripts-version 1.1.5. Using this command project structure like above will be generated except components and container folders that are to be created inside src folder manually." }, { "code": null, "e": 10538, "s": 10481, "text": "Install antd library using the command: npm install antd" }, { "code": null, "e": 10570, "s": 10538, "text": "Remove the code inside App.css." }, { "code": null, "e": 11138, "s": 10570, "text": "Edit code inside App.js: App Component renders Controller and displays title.App.jsJavascriptJavascriptimport React, { Component } from \"react\";import Controller from \"./containers/controller/controller\";import { Typography } from \"antd\"; import \"antd/dist/antd.css\"; import \"./App.css\";const { Title } = Typography; class App extends Component { render() { return ( <div className=\"App\"> <Title level={3} style={{ textAlign: \"center\" }}> Stone Paper Scissor </Title> <Controller /> </div> ); }} export default App;" }, { "code": null, "e": 11149, "s": 11138, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import Controller from \"./containers/controller/controller\";import { Typography } from \"antd\"; import \"antd/dist/antd.css\"; import \"./App.css\";const { Title } = Typography; class App extends Component { render() { return ( <div className=\"App\"> <Title level={3} style={{ textAlign: \"center\" }}> Stone Paper Scissor </Title> <Controller /> </div> ); }} export default App;", "e": 11614, "s": 11149, "text": null }, { "code": null, "e": 16195, "s": 11614, "text": "Controller.js: The controller holds a state which includes each player’s last used weapon, current win/loose status, and active state indicating which player’s turn it isJavascriptJavascriptimport React, { Component } from \"react\";import { Row, Col, Divider } from \"antd\";import { Typography } from \"antd\";import axios from \"axios\";import \"antd/dist/antd.css\"; import Player from \"../../components/Player/Player\";const { Title } = Typography; class Controller extends Component { state = { playerOne: { active: true, weapon: \"\", status: \"\" }, playerTwo: { active: false, weapon: \"\", status: \"\" } };The core idea here is that on clicking weapon buttons corresponding player’s weapon in the state should get updated and the next player’s turn should come which is done here via toggleactive function. Also, if the second player’s weapon is updated then win/loose should be updated too which is done here via resultHandler function. For game logic it holds a bunch of functions :WeaponUpdate: For updating a player’s weapon in the state. It takes two arguments first is playerId i.e playerOne or playerTwo since it’s a two-player game and the second is a weapon that is chosen by the player.JavascriptJavascriptweaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == \"playerTwo\") {this.resultHandler();} else {this.toggleActive();}};ToggleActive: For reversing active status of players once either of player selects a weapon. Active property in the state is a boolean variable, so we just have to use NOT operator to reverse the current state of each player.JavascriptJavascripttoggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});};ResultHandler: It contains the major game logic which decides which player has won. It uses a helper function called decision helper which takes two arguments that are each player’s weapon and returns an array containing two elements wherein the first element corresponds to the first player’s win/loose status and similarly the second element to the second player’s status. Then resulthandler updates state with values returned by decicerhelper function.JavascriptJavascriptresultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();};DeciderHelper: It is a helper function that takes two inputs that are weapons for each player and returns an array consisting of two elements each denoting the win/loose status of player 1 and player 2 respectively. Here ‘r’ stands for rock, ‘s’ stands for scissors, ‘p’ stands for the paper, ‘w’ for the win, and ‘l’ stands for loose. All possible combinations of rock, stone, scissors are considered in case of a tie both players with win status are returned.JavascriptJavascriptdeciderHelper = (p1, p2) => { if (p1 == \"r\" && p2 == \"s\") { return [\"w\", \"l\"]; } if (p1 == \"r\" && p2 == \"p\") { return [\"l\", \"w\"]; } if (p1 == \"r\" && p2 == \"r\") { return [\"w\", \"w\"]; } if (p1 == \"p\" && p2 == \"r\") { return [\"w\", \"l\"]; } if (p1 == \"p\" && p2 == \"s\") { return [\"l\", \"w\"]; } if (p1 == \"p\" && p2 == \"p\") { return [\"w\", \"w\"]; } if (p1 == \"s\" && p2 == \"r\") { return [\"l\", \"w\"]; } if (p1 == \"s\" && p2 == \"p\") { return [\"w\", \"l\"]; } if (p1 == \"s\" && p2 == \"s\") { return [\"w\", \"w\"]; }};Render Method:JavascriptJavascriptrender() { return ( <Row justify=\"space-around\" align=\"middle\"> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate(\"playerOne\", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate(\"playerTwo\", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller;" }, { "code": null, "e": 16366, "s": 16195, "text": "Controller.js: The controller holds a state which includes each player’s last used weapon, current win/loose status, and active state indicating which player’s turn it is" }, { "code": null, "e": 16377, "s": 16366, "text": "Javascript" }, { "code": "import React, { Component } from \"react\";import { Row, Col, Divider } from \"antd\";import { Typography } from \"antd\";import axios from \"axios\";import \"antd/dist/antd.css\"; import Player from \"../../components/Player/Player\";const { Title } = Typography; class Controller extends Component { state = { playerOne: { active: true, weapon: \"\", status: \"\" }, playerTwo: { active: false, weapon: \"\", status: \"\" } };", "e": 16832, "s": 16377, "text": null }, { "code": null, "e": 17211, "s": 16832, "text": "The core idea here is that on clicking weapon buttons corresponding player’s weapon in the state should get updated and the next player’s turn should come which is done here via toggleactive function. Also, if the second player’s weapon is updated then win/loose should be updated too which is done here via resultHandler function. For game logic it holds a bunch of functions :" }, { "code": null, "e": 17626, "s": 17211, "text": "WeaponUpdate: For updating a player’s weapon in the state. It takes two arguments first is playerId i.e playerOne or playerTwo since it’s a two-player game and the second is a weapon that is chosen by the player.JavascriptJavascriptweaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == \"playerTwo\") {this.resultHandler();} else {this.toggleActive();}};" }, { "code": null, "e": 17637, "s": 17626, "text": "Javascript" }, { "code": "weaponUpdate = (player, weapon) => {this.setState({[player]: {...this.state[player],weapon: weapon}});if (player == \"playerTwo\") {this.resultHandler();} else {this.toggleActive();}};", "e": 17820, "s": 17637, "text": null }, { "code": null, "e": 18287, "s": 17820, "text": "ToggleActive: For reversing active status of players once either of player selects a weapon. Active property in the state is a boolean variable, so we just have to use NOT operator to reverse the current state of each player.JavascriptJavascripttoggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});};" }, { "code": null, "e": 18298, "s": 18287, "text": "Javascript" }, { "code": "toggleActive = () => {this.setState(prevState => {return {...prevState,playerOne: {...prevState.playerOne,active: !prevState.playerOne.active},playerTwo: {...prevState.playerTwo,active: !prevState.playerTwo.active}};});};", "e": 18520, "s": 18298, "text": null }, { "code": null, "e": 19277, "s": 18520, "text": "ResultHandler: It contains the major game logic which decides which player has won. It uses a helper function called decision helper which takes two arguments that are each player’s weapon and returns an array containing two elements wherein the first element corresponds to the first player’s win/loose status and similarly the second element to the second player’s status. Then resulthandler updates state with values returned by decicerhelper function.JavascriptJavascriptresultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();};" }, { "code": null, "e": 19288, "s": 19277, "text": "Javascript" }, { "code": "resultHandler = () => {this.setState(prevState => {let [s1, s2] = this.deciderHelper(prevState.playerOne.weapon,prevState.playerTwo.weapon);return {...prevState,playerOne: {...prevState.playerOne,status: s1},playerTwo: {...prevState.playerTwo,status: s2}};});this.toggleActive();};", "e": 19570, "s": 19288, "text": null }, { "code": null, "e": 20590, "s": 19570, "text": "DeciderHelper: It is a helper function that takes two inputs that are weapons for each player and returns an array consisting of two elements each denoting the win/loose status of player 1 and player 2 respectively. Here ‘r’ stands for rock, ‘s’ stands for scissors, ‘p’ stands for the paper, ‘w’ for the win, and ‘l’ stands for loose. All possible combinations of rock, stone, scissors are considered in case of a tie both players with win status are returned.JavascriptJavascriptdeciderHelper = (p1, p2) => { if (p1 == \"r\" && p2 == \"s\") { return [\"w\", \"l\"]; } if (p1 == \"r\" && p2 == \"p\") { return [\"l\", \"w\"]; } if (p1 == \"r\" && p2 == \"r\") { return [\"w\", \"w\"]; } if (p1 == \"p\" && p2 == \"r\") { return [\"w\", \"l\"]; } if (p1 == \"p\" && p2 == \"s\") { return [\"l\", \"w\"]; } if (p1 == \"p\" && p2 == \"p\") { return [\"w\", \"w\"]; } if (p1 == \"s\" && p2 == \"r\") { return [\"l\", \"w\"]; } if (p1 == \"s\" && p2 == \"p\") { return [\"w\", \"l\"]; } if (p1 == \"s\" && p2 == \"s\") { return [\"w\", \"w\"]; }};" }, { "code": null, "e": 20601, "s": 20590, "text": "Javascript" }, { "code": "deciderHelper = (p1, p2) => { if (p1 == \"r\" && p2 == \"s\") { return [\"w\", \"l\"]; } if (p1 == \"r\" && p2 == \"p\") { return [\"l\", \"w\"]; } if (p1 == \"r\" && p2 == \"r\") { return [\"w\", \"w\"]; } if (p1 == \"p\" && p2 == \"r\") { return [\"w\", \"l\"]; } if (p1 == \"p\" && p2 == \"s\") { return [\"l\", \"w\"]; } if (p1 == \"p\" && p2 == \"p\") { return [\"w\", \"w\"]; } if (p1 == \"s\" && p2 == \"r\") { return [\"l\", \"w\"]; } if (p1 == \"s\" && p2 == \"p\") { return [\"w\", \"l\"]; } if (p1 == \"s\" && p2 == \"s\") { return [\"w\", \"w\"]; }};", "e": 21140, "s": 20601, "text": null }, { "code": null, "e": 22044, "s": 21140, "text": "Render Method:JavascriptJavascriptrender() { return ( <Row justify=\"space-around\" align=\"middle\"> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate(\"playerOne\", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate(\"playerTwo\", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller;" }, { "code": null, "e": 22055, "s": 22044, "text": "Javascript" }, { "code": "render() { return ( <Row justify=\"space-around\" align=\"middle\"> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player One</Title> <Player active={this.state.playerOne.active} weaponUpdate={weapon => this.weaponUpdate(\"playerOne\", weapon)} weapon={this.state.playerOne.weapon} status={this.state.playerOne.status} /> </Col> <Col className=\"gutter-row\" xs={15} sm={15} md={5} lg={5}> <Title level={3}>Player Two</Title> <Player active={this.state.playerTwo.active} weaponUpdate={weapon => this.weaponUpdate(\"playerTwo\", weapon)} weapon={this.state.playerTwo.weapon} status={this.state.playerTwo.status} /> </Col> </Row> ); }} export default Controller;", "e": 22925, "s": 22055, "text": null }, { "code": null, "e": 26486, "s": 22925, "text": "Coding the Components: Code is very simple in these. Just the representational logic resides here.Player.js: As mentioned earlier it’s a stateless component representing a player entity. It receives four props that are the active status of the player, current weapon, win/loose status, and functionHandler for updating weapon. It further uses two components GameControls and decision box which are discussed below. Also, if active props received are true then a CSS object called glowEffect is applied to the div.JavascriptJavascriptimport React from \"react\";import GameControls from \"../GameControls/GameControls\";import DecisionBox from \"../DecisionBox/DecisionBox\"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { \"-webkit-box-shadow\": \"0 0 20px blue\", \"-moz-box-shadow\": \"0 0 20px blue\", \"box-shadow\": \"0 0 20px blue\" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player;GameControls.js: It contains three buttons rock, stone, scissors. If the player is not active then the buttons are disabled. On button click weaponupdate function is called which takes one argument ‘p’ for paper, ‘r’ for rock, ‘s’ for scissors and state of corresponding gets updated.JavascriptJavascriptimport React from \"react\";import { Card } from \"antd\";import { Button } from \"antd\"; import \"antd/dist/antd.css\"; const GameControls = props => { return ( <Card title=\"Controls\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\" }} > <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"r\")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: \"center\" }}> {\" \"} <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"p\")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"s\")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls;DecisionBox.js: It displays two things player’s weapon and the player’s win/loose status. It receives two props weapon (‘r’ or ‘p’ or ‘s’ ) and status (‘w’ or ‘l’ ). Two objects weaponmap and status map are used for mapping shortforms to proper words that can be displayed on the screen.JavascriptJavascriptimport React from \"react\";import { Card } from \"antd\";import { Typography } from \"antd\"; const { Title } = Typography; const weaponMap = { s: \"Scissors\", p: \"Paper\", r: \"Rock\"};const statusMap = { w: \"Win\", l: \"Loose\"}; const DecisionBox = props => { return ( <Card title=\"Decision Box\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\", marginTop: \"15px\" }} bodyStyle={{ textAlign: \"center\" }} > <Title level={1} type=\"warning\"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type=\"secondary\"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox;" }, { "code": null, "e": 26585, "s": 26486, "text": "Coding the Components: Code is very simple in these. Just the representational logic resides here." }, { "code": null, "e": 27593, "s": 26585, "text": "Player.js: As mentioned earlier it’s a stateless component representing a player entity. It receives four props that are the active status of the player, current weapon, win/loose status, and functionHandler for updating weapon. It further uses two components GameControls and decision box which are discussed below. Also, if active props received are true then a CSS object called glowEffect is applied to the div.JavascriptJavascriptimport React from \"react\";import GameControls from \"../GameControls/GameControls\";import DecisionBox from \"../DecisionBox/DecisionBox\"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { \"-webkit-box-shadow\": \"0 0 20px blue\", \"-moz-box-shadow\": \"0 0 20px blue\", \"box-shadow\": \"0 0 20px blue\" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player;" }, { "code": null, "e": 27604, "s": 27593, "text": "Javascript" }, { "code": "import React from \"react\";import GameControls from \"../GameControls/GameControls\";import DecisionBox from \"../DecisionBox/DecisionBox\"; const Player = props => { let glowEffect = {}; if (props.active) { glowEffect = { \"-webkit-box-shadow\": \"0 0 20px blue\", \"-moz-box-shadow\": \"0 0 20px blue\", \"box-shadow\": \"0 0 20px blue\" }; } return ( <div style={glowEffect}> <GameControls wUpdate={props.weaponUpdate} isActive={props.active} /> <DecisionBox weapon={props.weapon} status={props.status} /> </div> );}; export default Player;", "e": 28177, "s": 27604, "text": null }, { "code": null, "e": 29631, "s": 28177, "text": "GameControls.js: It contains three buttons rock, stone, scissors. If the player is not active then the buttons are disabled. On button click weaponupdate function is called which takes one argument ‘p’ for paper, ‘r’ for rock, ‘s’ for scissors and state of corresponding gets updated.JavascriptJavascriptimport React from \"react\";import { Card } from \"antd\";import { Button } from \"antd\"; import \"antd/dist/antd.css\"; const GameControls = props => { return ( <Card title=\"Controls\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\" }} > <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"r\")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: \"center\" }}> {\" \"} <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"p\")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"s\")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls;" }, { "code": null, "e": 29642, "s": 29631, "text": "Javascript" }, { "code": "import React from \"react\";import { Card } from \"antd\";import { Button } from \"antd\"; import \"antd/dist/antd.css\"; const GameControls = props => { return ( <Card title=\"Controls\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\" }} > <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"r\")} disabled={!props.isActive} > Rock </Button> </p> <p style={{ alignItems: \"center\" }}> {\" \"} <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"p\")} disabled={!props.isActive} > Paper </Button> </p> <p style={{ alignItems: \"center\" }}> <Button type=\"dashed\" size=\"large\" shape=\"round\" block onClick={() => props.wUpdate(\"s\")} disabled={!props.isActive} > Scissors </Button> </p> </Card> );}; export default GameControls;", "e": 30792, "s": 29642, "text": null }, { "code": null, "e": 31795, "s": 30792, "text": "DecisionBox.js: It displays two things player’s weapon and the player’s win/loose status. It receives two props weapon (‘r’ or ‘p’ or ‘s’ ) and status (‘w’ or ‘l’ ). Two objects weaponmap and status map are used for mapping shortforms to proper words that can be displayed on the screen.JavascriptJavascriptimport React from \"react\";import { Card } from \"antd\";import { Typography } from \"antd\"; const { Title } = Typography; const weaponMap = { s: \"Scissors\", p: \"Paper\", r: \"Rock\"};const statusMap = { w: \"Win\", l: \"Loose\"}; const DecisionBox = props => { return ( <Card title=\"Decision Box\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\", marginTop: \"15px\" }} bodyStyle={{ textAlign: \"center\" }} > <Title level={1} type=\"warning\"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type=\"secondary\"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox;" }, { "code": null, "e": 31806, "s": 31795, "text": "Javascript" }, { "code": "import React from \"react\";import { Card } from \"antd\";import { Typography } from \"antd\"; const { Title } = Typography; const weaponMap = { s: \"Scissors\", p: \"Paper\", r: \"Rock\"};const statusMap = { w: \"Win\", l: \"Loose\"}; const DecisionBox = props => { return ( <Card title=\"Decision Box\" style={{ width: \"300px\", height: \"250px\", alignItems: \"center\", marginTop: \"15px\" }} bodyStyle={{ textAlign: \"center\" }} > <Title level={1} type=\"warning\"> {weaponMap[props.weapon]} </Title> <Title level={2} mark type=\"secondary\"> {statusMap[props.status]} </Title> </Card> );}; export default DecisionBox;", "e": 32502, "s": 31806, "text": null }, { "code": null, "e": 32510, "s": 32502, "text": "Output:" }, { "code": null, "e": 32519, "s": 32510, "text": "react-js" }, { "code": null, "e": 32536, "s": 32519, "text": "Web Technologies" } ]
Temporal Data and Temporal Consistency
28 Jun, 2022 Temporal Data is the temporary data that is valid only for a prescribed time. Temporal data becomes invalid or obsolete after a certain period of time. For example, the current temperature of a particular region is temporal data as it keeps on updating and the validity of this temporal data (current temperature) becomes obsolete. Also, the data for the current seat availability in flight booking keeps on changing every minute. Such type of temporary data is called as temporal data. Temporal Data is generally used in Real-time systems, for example, Railway Seat Reservation, Sensex, Weather forecasting, etc. Real-time Systems use temporal consistency constrains on the data objects. Temporal consistency ensures that the difference in the values which is stored in the database of the real-time systems and the real data is within some predefined limit. Absolute Validity makes sure that there must be some consistency in the real data and the data stored in the database. Relative Consistency makes sure that the set of data obtained when queried from the database of the real-time systems should lie within a certain fixed and predefined range. The relative values of the data obtained from the database should be close to each other and there must not be a huge difference in the values. In the above diagram: x arrives at 0 and becomes obsolete at 8, because the validity time is 8 y arrives at 6 and becomes obsolete at 13, because the validity time is 7 Data items in the Real-time System are stored in the form of a tuple: (value, avi, timestamp) value: It represents the data value. avi: It represents the validity time of the data. timestamp: It represents the generation time of the data instance. For example, (786.34, 8 ms, 800 ms): means that the data value is 786.34 and it is generated at 800 ms and is valid from 800ms to 804ms. Absolute Validity can be verified using the equation: ( current_time - dtimestamp ) <= davi Relative Validity can be verified using the equation: ∀d, ∀ d' ∈ R : |dts - d'ts| simmytarika5 Computer Subject 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, 2022" }, { "code": null, "e": 1327, "s": 28, "text": "Temporal Data is the temporary data that is valid only for a prescribed time. Temporal data becomes invalid or obsolete after a certain period of time. For example, the current temperature of a particular region is temporal data as it keeps on updating and the validity of this temporal data (current temperature) becomes obsolete. Also, the data for the current seat availability in flight booking keeps on changing every minute. Such type of temporary data is called as temporal data. Temporal Data is generally used in Real-time systems, for example, Railway Seat Reservation, Sensex, Weather forecasting, etc. Real-time Systems use temporal consistency constrains on the data objects. Temporal consistency ensures that the difference in the values which is stored in the database of the real-time systems and the real data is within some predefined limit. Absolute Validity makes sure that there must be some consistency in the real data and the data stored in the database. Relative Consistency makes sure that the set of data obtained when queried from the database of the real-time systems should lie within a certain fixed and predefined range. The relative values of the data obtained from the database should be close to each other and there must not be a huge difference in the values. " }, { "code": null, "e": 1349, "s": 1327, "text": "In the above diagram:" }, { "code": null, "e": 1422, "s": 1349, "text": "x arrives at 0 and becomes obsolete at 8, because the validity time is 8" }, { "code": null, "e": 1496, "s": 1422, "text": "y arrives at 6 and becomes obsolete at 13, because the validity time is 7" }, { "code": null, "e": 1566, "s": 1496, "text": "Data items in the Real-time System are stored in the form of a tuple:" }, { "code": null, "e": 1590, "s": 1566, "text": "(value, avi, timestamp)" }, { "code": null, "e": 1627, "s": 1590, "text": "value: It represents the data value." }, { "code": null, "e": 1677, "s": 1627, "text": "avi: It represents the validity time of the data." }, { "code": null, "e": 1744, "s": 1677, "text": "timestamp: It represents the generation time of the data instance." }, { "code": null, "e": 1935, "s": 1744, "text": "For example, (786.34, 8 ms, 800 ms): means that the data value is 786.34 and it is generated at 800 ms and is valid from 800ms to 804ms. Absolute Validity can be verified using the equation:" }, { "code": null, "e": 1973, "s": 1935, "text": "( current_time - dtimestamp ) <= davi" }, { "code": null, "e": 2027, "s": 1973, "text": "Relative Validity can be verified using the equation:" }, { "code": null, "e": 2055, "s": 2027, "text": "∀d, ∀ d' ∈ R : |dts - d'ts|" }, { "code": null, "e": 2068, "s": 2055, "text": "simmytarika5" }, { "code": null, "e": 2085, "s": 2068, "text": "Computer Subject" } ]
Word Ladder (Length of shortest chain to reach a target word)
24 Feb, 2022 Given a dictionary, and two words ‘start’ and ‘target’ (both of same length). Find length of the smallest chain from ‘start’ to ‘target’ if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the ‘target’ word exists in dictionary and length of all dictionary words is same. Example: Input: Dictionary = {POON, PLEE, SAME, POIE, PLEA, PLIE, POIN}, start = TOON, target = PLEAOutput: 7Explanation: TOON – POON – POIN – POIE – PLIE – PLEE – PLEA Input: Dictionary = {ABCD, EBAD, EBCD, XYZA}, start = ABCV, target = EBADOutput: 4Explanation: ABCV – ABCD – EBCD – EBAD Approach: The idea to solve the problem is to use BFS. To find the shortest path through BFS, start from the start word and push it in a queue. And once the target is found for the first time, then return that level of BFS traversal. In each step of BFS one can get all the words that can be formed using that many steps. So whenever the target word is found for the first time that will be the length of the shortest chain of words. 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. Start from the given start word.Push the word in the queueRun a loop until the queue is emptyTraverse all words that adjacent (differ by one character) to it and push the word in a queue (for BFS)Keep doing so until we find the target word or we have traversed all words. Start from the given start word. Push the word in the queue Run a loop until the queue is empty Traverse all words that adjacent (differ by one character) to it and push the word in a queue (for BFS) Keep doing so until we find the target word or we have traversed all words. Below are the implementations of the above idea. C++ Java Python3 C# Javascript // C++ program to find length// of the shortest chain// transformation from source// to target#include <bits/stdc++.h>using namespace std; // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent// moves. D is dictionaryint shortestChainLen(string start, string target,set<string>& D){ if(start == target) return 0; // If the target string is not // present in the dictionary if (D.find(target) == D.end()) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.size(); // Push the starting word into the queue queue<string> Q; Q.push(start); // While the queue is non-empty while (!Q.empty()) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.size(); // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue string word = Q.front(); Q.pop(); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (word == target) return level + 1; // Remove the word from the set // if it is found in it if (D.find(word) == D.end()) continue; D.erase(word); // And push the newly generated word // which will be a part of the chain Q.push(word); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0;} // Driver programint main(){ // make dictionary set<string> D; D.insert("poon"); D.insert("plee"); D.insert("same"); D.insert("poie"); D.insert("plie"); D.insert("poin"); D.insert("plea"); string start = "toon"; string target = "plea"; cout << "Length of shortest chain is: " << shortestChainLen(start, target, D); return 0;} // Java program to find length// of the shortest chain// transformation from source// to targetimport java.util.*; class GFG{ // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent moves.// D is dictionarystatic int shortestChainLen(String start, String target, Set<String> D){ if(start == target) return 0; // If the target String is not // present in the dictionary if (!D.contains(target)) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.length(); // Push the starting word into the queue Queue<String> Q = new LinkedList<>(); Q.add(start); // While the queue is non-empty while (!Q.isEmpty()) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.size(); // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue char []word = Q.peek().toCharArray(); Q.remove(); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (String.valueOf(word).equals(target)) return level + 1; // Remove the word from the set // if it is found in it if (!D.contains(String.valueOf(word))) continue; D.remove(String.valueOf(word)); // And push the newly generated word // which will be a part of the chain Q.add(String.valueOf(word)); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0;} // Driver codepublic static void main(String[] args){ // make dictionary Set<String> D = new HashSet<String>(); D.add("poon"); D.add("plee"); D.add("same"); D.add("poie"); D.add("plie"); D.add("poin"); D.add("plea"); String start = "toon"; String target = "plea"; System.out.print("Length of shortest chain is: " + shortestChainLen(start, target, D));}} // This code is contributed by PrinciRaj1992 # Python3 program to find length of the# shortest chain transformation from source# to targetfrom collections import deque # Returns length of shortest chain# to reach 'target' from 'start'# using minimum number of adjacent# moves. D is dictionarydef shortestChainLen(start, target, D): if start == target: return 0 # If the target is not # present in the dictionary if target not in D: return 0 # To store the current chain length # and the length of the words level, wordlength = 0, len(start) # Push the starting word into the queue Q = deque() Q.append(start) # While the queue is non-empty while (len(Q) > 0): # Increment the chain length level += 1 # Current size of the queue sizeofQ = len(Q) # Since the queue is being updated while # it is being traversed so only the # elements which were already present # in the queue before the start of this # loop will be traversed for now for i in range(sizeofQ): # Remove the first word from the queue word = [j for j in Q.popleft()] #Q.pop() # For every character of the word for pos in range(wordlength): # Retain the original character # at the current position orig_char = word[pos] # Replace the current character with # every possible lowercase alphabet for c in range(ord('a'), ord('z')+1): word[pos] = chr(c) # If the new word is equal # to the target word if ("".join(word) == target): return level + 1 # Remove the word from the set # if it is found in it if ("".join(word) not in D): continue del D["".join(word)] # And push the newly generated word # which will be a part of the chain Q.append("".join(word)) # Restore the original character # at the current position word[pos] = orig_char return 0 # Driver codeif __name__ == '__main__': # Make dictionary D = {} D["poon"] = 1 D["plee"] = 1 D["same"] = 1 D["poie"] = 1 D["plie"] = 1 D["poin"] = 1 D["plea"] = 1 start = "toon" target = "plea" print("Length of shortest chain is: ", shortestChainLen(start, target, D)) # This code is contributed by mohit kumar 29 // C# program to find length of the shortest chain// transformation from source to targetusing System;using System.Collections.Generic; class GFG{ // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent moves.// D is dictionarystatic int shortestChainLen(String start, String target, HashSet<String> D){ if(start == target) return 0; // If the target String is not // present in the dictionary if (!D.Contains(target)) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.Length; // Push the starting word into the queue List<String> Q = new List<String>(); Q.Add(start); // While the queue is non-empty while (Q.Count != 0) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.Count; // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue char []word = Q[0].ToCharArray(); Q.RemoveAt(0); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (String.Join("", word).Equals(target)) return level + 1; // Remove the word from the set // if it is found in it if (!D.Contains(String.Join("", word))) continue; D.Remove(String.Join("", word)); // And push the newly generated word // which will be a part of the chain Q.Add(String.Join("", word)); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0;} // Driver codepublic static void Main(String[] args){ // make dictionary HashSet<String> D = new HashSet<String>(); D.Add("poon"); D.Add("plee"); D.Add("same"); D.Add("poie"); D.Add("plie"); D.Add("poin"); D.Add("plea"); String start = "toon"; String target = "plea"; Console.Write("Length of shortest chain is: " + shortestChainLen(start, target, D));}} // This code is contributed by PrinciRaj1992 <script>// Javascript program to find length// of the shortest chain// transformation from source// to target // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent moves.// D is dictionary function shortestChainLen(start,target,D) { if(start == target) return 0; // If the target String is not // present in the dictionary if (!D.has(target)) return 0; // To store the current chain length // and the length of the words let level = 0, wordlength = start.length; // Push the starting word into the queue let Q = []; Q.push(start); // While the queue is non-empty while (Q.length != 0) { // Increment the chain length ++level; // Current size of the queue let sizeofQ = Q.length; // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (let i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue let word = Q[0].split(""); Q.shift(); // For every character of the word for (let pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position let orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (let c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); ++c) { word[pos] = String.fromCharCode(c); // If the new word is equal // to the target word if (word.join("") == target) return level + 1; // Remove the word from the set // if it is found in it if (!D.has(word.join(""))) continue; D.delete(word.join("")); // And push the newly generated word // which will be a part of the chain Q.push(word.join("")); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0; } // Driver code // make dictionary let D = new Set(); D.add("poon"); D.add("plee"); D.add("same"); D.add("poie"); D.add("plie"); D.add("poin"); D.add("plea"); let start = "toon"; let target = "plea"; document.write("Length of shortest chain is: " + shortestChainLen(start, target, D)); // This code is contributed by unknown2108</script> Length of shortest chain is: 7 Time Complexity: O(N2 * M), where M is the number of entries originally in the dictionary and N is the size of the string.Auxiliary Space: O(M * N) Alternate Implementation: (Maintaining the mapping of the intermediate words and the original word): Below is an alternative implementation to the above approach. Here, in this approach, we find out all the intermediate words of the start word and the words in the given list of dictionary and maintain a map of the intermediate word and a vector of the original word (map<string, vector<string>>). For instance, for the word “POON”, the intermediate words are “*OON” , “P*ON”, “PO*N”, “POO*”. Then, we perform BFS traversal starting with the start word and push a pair of start word and the distance (pair(word, distance)) to the queue until we reach the target word. Then, the distance is our answer. C++ Java // C++ program to find length// of the shortest chain// transformation from source// to target#include <bits/stdc++.h>using namespace std; // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent// moves. D is dictionaryint shortestChainLen(string start, string target,set<string>& D){ if(start == target) return 0; // Map of intermediate words and // the list of original words map<string, vector<string>> umap; // Find all the intermediate // words for the start word for(int i = 0; i < start.size(); i++) { string str = start.substr(0,i) + "*" + start.substr(i+1); umap[str].push_back(start); } // Find all the intermediate words for // the words in the given Set for(auto it = D.begin(); it != D.end(); it++) { string word = *it; for(int j = 0; j < word.size(); j++) { string str = word.substr(0,j) + "*" + word.substr(j+1); umap[str].push_back(word); } } // Perform BFS and push (word, distance) queue<pair<string, int>> q; map<string, int> visited; q.push(make_pair(start,1)); visited[start] = 1; // Traverse until queue is empty while(!q.empty()) { pair<string, int> p = q.front(); q.pop(); string word = p.first; int dist = p.second; // If target word is found if(word == target) { return dist; } // Finding intermediate words for // the word in front of queue for(int i = 0; i < word.size(); i++) { string str = word.substr(0,i) + "*" + word.substr(i+1); vector<string> vect = umap[str]; for(int j = 0; j < vect.size(); j++) { // If the word is not visited if(visited[vect[j]] == 0) { visited[vect[j]] = 1; q.push(make_pair(vect[j], dist + 1)); } } } } return 0;} // Driver codeint main(){ // Make dictionary set<string> D; D.insert("poon"); D.insert("plee"); D.insert("same"); D.insert("poie"); D.insert("plie"); D.insert("poin"); D.insert("plea"); string start = "toon"; string target = "plea"; cout << "Length of shortest chain is: " << shortestChainLen(start, target, D); return 0;} // Java program to find length// of the shortest chain// transformation from source// to targetimport java.util.*; class GFG{ static class pair { String first; int second; public pair(String first, int second) { this.first = first; this.second = second; } } // Returns length of shortest chain // to reach 'target' from 'start' // using minimum number of adjacent // moves. D is dictionary static int shortestChainLen( String start, String target, HashSet<String> D) { if(start == target) return 0; // Map of intermediate words and // the list of original words Map<String, Vector<String>> umap = new HashMap<>(); // Find all the intermediate // words for the start word for(int i = 0; i < start.length(); i++) { String str = start.substring(0,i) + "*" + start.substring(i+1); Vector<String> s = umap.get(str); if(s==null) s = new Vector<String>(); s.add(start); umap.put(str, s); } // Find all the intermediate words for // the words in the given Set for(String it : D) { String word = it; for(int j = 0; j < word.length(); j++) { String str = word.substring(0, j) + "*" + word.substring(j + 1); Vector<String> s = umap.get(str); if(s == null) s = new Vector<String>(); s.add(word); umap.put(str, s); } } // Perform BFS and push (word, distance) Queue<pair> q = new LinkedList<>(); Map<String, Integer> visited = new HashMap<String, Integer>(); q.add(new pair(start, 1)); visited.put(start, 1); // Traverse until queue is empty while(!q.isEmpty()) { pair p = q.peek(); q.remove(); String word = p.first; int dist = p.second; // If target word is found if(word == target) { return dist; } // Finding intermediate words for // the word in front of queue for(int i = 0; i < word.length(); i++) { String str = word.substring(0, i) + "*" + word.substring(i + 1); Vector<String> vect = umap.get(str); for(int j = 0; j < vect.size(); j++) { // If the word is not visited if(!visited.containsKey(vect.get(j)) ) { visited.put(vect.get(j), 1); q.add(new pair(vect.get(j), dist + 1)); } } } } return 0; } // Driver code public static void main(String[] args) { // Make dictionary HashSet<String> D = new HashSet<String>(); D.add("poon"); D.add("plee"); D.add("same"); D.add("poie"); D.add("plie"); D.add("poin"); D.add("plea"); String start = "toon"; String target = "plea"; System.out.print("Length of shortest chain is: " + shortestChainLen(start, target, D)); }} // This code is contributed by 29AjayKumar Length of shortest chain is: 7 Time Complexity: O(N2 * M), where M is the number of entries originally in the dictionary and N is the size of the string.Auxiliary Space: O(M * N) princiraj1992 andrew1234 ryadav2 mohit kumar 29 Codilis UtkarshPandey6 unknown2108 29AjayKumar nehakumariintern BFS Graph Graph BFS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Find if there is a path between two vertices in a directed graph Introduction to Data Structures Floyd Warshall Algorithm | DP-16 Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph) What is Data Structure: Types, Classifications and Applications Bellman–Ford Algorithm | DP-23 Find if there is a path between two vertices in an undirected graph Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Detect cycle in an undirected graph Minimum number of swaps required to sort an array
[ { "code": null, "e": 54, "s": 26, "text": "\n24 Feb, 2022" }, { "code": null, "e": 457, "s": 54, "text": "Given a dictionary, and two words ‘start’ and ‘target’ (both of same length). Find length of the smallest chain from ‘start’ to ‘target’ if it exists, such that adjacent words in the chain only differ by one character and each word in the chain is a valid word i.e., it exists in the dictionary. It may be assumed that the ‘target’ word exists in dictionary and length of all dictionary words is same. " }, { "code": null, "e": 467, "s": 457, "text": "Example: " }, { "code": null, "e": 627, "s": 467, "text": "Input: Dictionary = {POON, PLEE, SAME, POIE, PLEA, PLIE, POIN}, start = TOON, target = PLEAOutput: 7Explanation: TOON – POON – POIN – POIE – PLIE – PLEE – PLEA" }, { "code": null, "e": 748, "s": 627, "text": "Input: Dictionary = {ABCD, EBAD, EBCD, XYZA}, start = ABCV, target = EBADOutput: 4Explanation: ABCV – ABCD – EBCD – EBAD" }, { "code": null, "e": 1182, "s": 748, "text": "Approach: The idea to solve the problem is to use BFS. To find the shortest path through BFS, start from the start word and push it in a queue. And once the target is found for the first time, then return that level of BFS traversal. In each step of BFS one can get all the words that can be formed using that many steps. So whenever the target word is found for the first time that will be the length of the shortest chain of words." }, { "code": null, "e": 1191, "s": 1182, "text": "Chapters" }, { "code": null, "e": 1218, "s": 1191, "text": "descriptions off, selected" }, { "code": null, "e": 1268, "s": 1218, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 1291, "s": 1268, "text": "captions off, selected" }, { "code": null, "e": 1299, "s": 1291, "text": "English" }, { "code": null, "e": 1323, "s": 1299, "text": "This is a modal window." }, { "code": null, "e": 1392, "s": 1323, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 1414, "s": 1392, "text": "End of dialog window." }, { "code": null, "e": 1686, "s": 1414, "text": "Start from the given start word.Push the word in the queueRun a loop until the queue is emptyTraverse all words that adjacent (differ by one character) to it and push the word in a queue (for BFS)Keep doing so until we find the target word or we have traversed all words." }, { "code": null, "e": 1719, "s": 1686, "text": "Start from the given start word." }, { "code": null, "e": 1746, "s": 1719, "text": "Push the word in the queue" }, { "code": null, "e": 1782, "s": 1746, "text": "Run a loop until the queue is empty" }, { "code": null, "e": 1886, "s": 1782, "text": "Traverse all words that adjacent (differ by one character) to it and push the word in a queue (for BFS)" }, { "code": null, "e": 1962, "s": 1886, "text": "Keep doing so until we find the target word or we have traversed all words." }, { "code": null, "e": 2011, "s": 1962, "text": "Below are the implementations of the above idea." }, { "code": null, "e": 2015, "s": 2011, "text": "C++" }, { "code": null, "e": 2020, "s": 2015, "text": "Java" }, { "code": null, "e": 2028, "s": 2020, "text": "Python3" }, { "code": null, "e": 2031, "s": 2028, "text": "C#" }, { "code": null, "e": 2042, "s": 2031, "text": "Javascript" }, { "code": "// C++ program to find length// of the shortest chain// transformation from source// to target#include <bits/stdc++.h>using namespace std; // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent// moves. D is dictionaryint shortestChainLen(string start, string target,set<string>& D){ if(start == target) return 0; // If the target string is not // present in the dictionary if (D.find(target) == D.end()) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.size(); // Push the starting word into the queue queue<string> Q; Q.push(start); // While the queue is non-empty while (!Q.empty()) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.size(); // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue string word = Q.front(); Q.pop(); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (word == target) return level + 1; // Remove the word from the set // if it is found in it if (D.find(word) == D.end()) continue; D.erase(word); // And push the newly generated word // which will be a part of the chain Q.push(word); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0;} // Driver programint main(){ // make dictionary set<string> D; D.insert(\"poon\"); D.insert(\"plee\"); D.insert(\"same\"); D.insert(\"poie\"); D.insert(\"plie\"); D.insert(\"poin\"); D.insert(\"plea\"); string start = \"toon\"; string target = \"plea\"; cout << \"Length of shortest chain is: \" << shortestChainLen(start, target, D); return 0;}", "e": 4815, "s": 2042, "text": null }, { "code": "// Java program to find length// of the shortest chain// transformation from source// to targetimport java.util.*; class GFG{ // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent moves.// D is dictionarystatic int shortestChainLen(String start, String target, Set<String> D){ if(start == target) return 0; // If the target String is not // present in the dictionary if (!D.contains(target)) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.length(); // Push the starting word into the queue Queue<String> Q = new LinkedList<>(); Q.add(start); // While the queue is non-empty while (!Q.isEmpty()) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.size(); // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue char []word = Q.peek().toCharArray(); Q.remove(); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (String.valueOf(word).equals(target)) return level + 1; // Remove the word from the set // if it is found in it if (!D.contains(String.valueOf(word))) continue; D.remove(String.valueOf(word)); // And push the newly generated word // which will be a part of the chain Q.add(String.valueOf(word)); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0;} // Driver codepublic static void main(String[] args){ // make dictionary Set<String> D = new HashSet<String>(); D.add(\"poon\"); D.add(\"plee\"); D.add(\"same\"); D.add(\"poie\"); D.add(\"plie\"); D.add(\"poin\"); D.add(\"plea\"); String start = \"toon\"; String target = \"plea\"; System.out.print(\"Length of shortest chain is: \" + shortestChainLen(start, target, D));}} // This code is contributed by PrinciRaj1992", "e": 7835, "s": 4815, "text": null }, { "code": "# Python3 program to find length of the# shortest chain transformation from source# to targetfrom collections import deque # Returns length of shortest chain# to reach 'target' from 'start'# using minimum number of adjacent# moves. D is dictionarydef shortestChainLen(start, target, D): if start == target: return 0 # If the target is not # present in the dictionary if target not in D: return 0 # To store the current chain length # and the length of the words level, wordlength = 0, len(start) # Push the starting word into the queue Q = deque() Q.append(start) # While the queue is non-empty while (len(Q) > 0): # Increment the chain length level += 1 # Current size of the queue sizeofQ = len(Q) # Since the queue is being updated while # it is being traversed so only the # elements which were already present # in the queue before the start of this # loop will be traversed for now for i in range(sizeofQ): # Remove the first word from the queue word = [j for j in Q.popleft()] #Q.pop() # For every character of the word for pos in range(wordlength): # Retain the original character # at the current position orig_char = word[pos] # Replace the current character with # every possible lowercase alphabet for c in range(ord('a'), ord('z')+1): word[pos] = chr(c) # If the new word is equal # to the target word if (\"\".join(word) == target): return level + 1 # Remove the word from the set # if it is found in it if (\"\".join(word) not in D): continue del D[\"\".join(word)] # And push the newly generated word # which will be a part of the chain Q.append(\"\".join(word)) # Restore the original character # at the current position word[pos] = orig_char return 0 # Driver codeif __name__ == '__main__': # Make dictionary D = {} D[\"poon\"] = 1 D[\"plee\"] = 1 D[\"same\"] = 1 D[\"poie\"] = 1 D[\"plie\"] = 1 D[\"poin\"] = 1 D[\"plea\"] = 1 start = \"toon\" target = \"plea\" print(\"Length of shortest chain is: \", shortestChainLen(start, target, D)) # This code is contributed by mohit kumar 29", "e": 10495, "s": 7835, "text": null }, { "code": "// C# program to find length of the shortest chain// transformation from source to targetusing System;using System.Collections.Generic; class GFG{ // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent moves.// D is dictionarystatic int shortestChainLen(String start, String target, HashSet<String> D){ if(start == target) return 0; // If the target String is not // present in the dictionary if (!D.Contains(target)) return 0; // To store the current chain length // and the length of the words int level = 0, wordlength = start.Length; // Push the starting word into the queue List<String> Q = new List<String>(); Q.Add(start); // While the queue is non-empty while (Q.Count != 0) { // Increment the chain length ++level; // Current size of the queue int sizeofQ = Q.Count; // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (int i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue char []word = Q[0].ToCharArray(); Q.RemoveAt(0); // For every character of the word for (int pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position char orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (char c = 'a'; c <= 'z'; ++c) { word[pos] = c; // If the new word is equal // to the target word if (String.Join(\"\", word).Equals(target)) return level + 1; // Remove the word from the set // if it is found in it if (!D.Contains(String.Join(\"\", word))) continue; D.Remove(String.Join(\"\", word)); // And push the newly generated word // which will be a part of the chain Q.Add(String.Join(\"\", word)); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0;} // Driver codepublic static void Main(String[] args){ // make dictionary HashSet<String> D = new HashSet<String>(); D.Add(\"poon\"); D.Add(\"plee\"); D.Add(\"same\"); D.Add(\"poie\"); D.Add(\"plie\"); D.Add(\"poin\"); D.Add(\"plea\"); String start = \"toon\"; String target = \"plea\"; Console.Write(\"Length of shortest chain is: \" + shortestChainLen(start, target, D));}} // This code is contributed by PrinciRaj1992", "e": 13540, "s": 10495, "text": null }, { "code": "<script>// Javascript program to find length// of the shortest chain// transformation from source// to target // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent moves.// D is dictionary function shortestChainLen(start,target,D) { if(start == target) return 0; // If the target String is not // present in the dictionary if (!D.has(target)) return 0; // To store the current chain length // and the length of the words let level = 0, wordlength = start.length; // Push the starting word into the queue let Q = []; Q.push(start); // While the queue is non-empty while (Q.length != 0) { // Increment the chain length ++level; // Current size of the queue let sizeofQ = Q.length; // Since the queue is being updated while // it is being traversed so only the // elements which were already present // in the queue before the start of this // loop will be traversed for now for (let i = 0; i < sizeofQ; ++i) { // Remove the first word from the queue let word = Q[0].split(\"\"); Q.shift(); // For every character of the word for (let pos = 0; pos < wordlength; ++pos) { // Retain the original character // at the current position let orig_char = word[pos]; // Replace the current character with // every possible lowercase alphabet for (let c = 'a'.charCodeAt(0); c <= 'z'.charCodeAt(0); ++c) { word[pos] = String.fromCharCode(c); // If the new word is equal // to the target word if (word.join(\"\") == target) return level + 1; // Remove the word from the set // if it is found in it if (!D.has(word.join(\"\"))) continue; D.delete(word.join(\"\")); // And push the newly generated word // which will be a part of the chain Q.push(word.join(\"\")); } // Restore the original character // at the current position word[pos] = orig_char; } } } return 0; } // Driver code // make dictionary let D = new Set(); D.add(\"poon\"); D.add(\"plee\"); D.add(\"same\"); D.add(\"poie\"); D.add(\"plie\"); D.add(\"poin\"); D.add(\"plea\"); let start = \"toon\"; let target = \"plea\"; document.write(\"Length of shortest chain is: \" + shortestChainLen(start, target, D)); // This code is contributed by unknown2108</script>", "e": 16417, "s": 13540, "text": null }, { "code": null, "e": 16448, "s": 16417, "text": "Length of shortest chain is: 7" }, { "code": null, "e": 16596, "s": 16448, "text": "Time Complexity: O(N2 * M), where M is the number of entries originally in the dictionary and N is the size of the string.Auxiliary Space: O(M * N)" }, { "code": null, "e": 16697, "s": 16596, "text": "Alternate Implementation: (Maintaining the mapping of the intermediate words and the original word):" }, { "code": null, "e": 16760, "s": 16697, "text": "Below is an alternative implementation to the above approach. " }, { "code": null, "e": 17300, "s": 16760, "text": "Here, in this approach, we find out all the intermediate words of the start word and the words in the given list of dictionary and maintain a map of the intermediate word and a vector of the original word (map<string, vector<string>>). For instance, for the word “POON”, the intermediate words are “*OON” , “P*ON”, “PO*N”, “POO*”. Then, we perform BFS traversal starting with the start word and push a pair of start word and the distance (pair(word, distance)) to the queue until we reach the target word. Then, the distance is our answer." }, { "code": null, "e": 17304, "s": 17300, "text": "C++" }, { "code": null, "e": 17309, "s": 17304, "text": "Java" }, { "code": "// C++ program to find length// of the shortest chain// transformation from source// to target#include <bits/stdc++.h>using namespace std; // Returns length of shortest chain// to reach 'target' from 'start'// using minimum number of adjacent// moves. D is dictionaryint shortestChainLen(string start, string target,set<string>& D){ if(start == target) return 0; // Map of intermediate words and // the list of original words map<string, vector<string>> umap; // Find all the intermediate // words for the start word for(int i = 0; i < start.size(); i++) { string str = start.substr(0,i) + \"*\" + start.substr(i+1); umap[str].push_back(start); } // Find all the intermediate words for // the words in the given Set for(auto it = D.begin(); it != D.end(); it++) { string word = *it; for(int j = 0; j < word.size(); j++) { string str = word.substr(0,j) + \"*\" + word.substr(j+1); umap[str].push_back(word); } } // Perform BFS and push (word, distance) queue<pair<string, int>> q; map<string, int> visited; q.push(make_pair(start,1)); visited[start] = 1; // Traverse until queue is empty while(!q.empty()) { pair<string, int> p = q.front(); q.pop(); string word = p.first; int dist = p.second; // If target word is found if(word == target) { return dist; } // Finding intermediate words for // the word in front of queue for(int i = 0; i < word.size(); i++) { string str = word.substr(0,i) + \"*\" + word.substr(i+1); vector<string> vect = umap[str]; for(int j = 0; j < vect.size(); j++) { // If the word is not visited if(visited[vect[j]] == 0) { visited[vect[j]] = 1; q.push(make_pair(vect[j], dist + 1)); } } } } return 0;} // Driver codeint main(){ // Make dictionary set<string> D; D.insert(\"poon\"); D.insert(\"plee\"); D.insert(\"same\"); D.insert(\"poie\"); D.insert(\"plie\"); D.insert(\"poin\"); D.insert(\"plea\"); string start = \"toon\"; string target = \"plea\"; cout << \"Length of shortest chain is: \" << shortestChainLen(start, target, D); return 0;}", "e": 19567, "s": 17309, "text": null }, { "code": "// Java program to find length// of the shortest chain// transformation from source// to targetimport java.util.*; class GFG{ static class pair { String first; int second; public pair(String first, int second) { this.first = first; this.second = second; } } // Returns length of shortest chain // to reach 'target' from 'start' // using minimum number of adjacent // moves. D is dictionary static int shortestChainLen( String start, String target, HashSet<String> D) { if(start == target) return 0; // Map of intermediate words and // the list of original words Map<String, Vector<String>> umap = new HashMap<>(); // Find all the intermediate // words for the start word for(int i = 0; i < start.length(); i++) { String str = start.substring(0,i) + \"*\" + start.substring(i+1); Vector<String> s = umap.get(str); if(s==null) s = new Vector<String>(); s.add(start); umap.put(str, s); } // Find all the intermediate words for // the words in the given Set for(String it : D) { String word = it; for(int j = 0; j < word.length(); j++) { String str = word.substring(0, j) + \"*\" + word.substring(j + 1); Vector<String> s = umap.get(str); if(s == null) s = new Vector<String>(); s.add(word); umap.put(str, s); } } // Perform BFS and push (word, distance) Queue<pair> q = new LinkedList<>(); Map<String, Integer> visited = new HashMap<String, Integer>(); q.add(new pair(start, 1)); visited.put(start, 1); // Traverse until queue is empty while(!q.isEmpty()) { pair p = q.peek(); q.remove(); String word = p.first; int dist = p.second; // If target word is found if(word == target) { return dist; } // Finding intermediate words for // the word in front of queue for(int i = 0; i < word.length(); i++) { String str = word.substring(0, i) + \"*\" + word.substring(i + 1); Vector<String> vect = umap.get(str); for(int j = 0; j < vect.size(); j++) { // If the word is not visited if(!visited.containsKey(vect.get(j)) ) { visited.put(vect.get(j), 1); q.add(new pair(vect.get(j), dist + 1)); } } } } return 0; } // Driver code public static void main(String[] args) { // Make dictionary HashSet<String> D = new HashSet<String>(); D.add(\"poon\"); D.add(\"plee\"); D.add(\"same\"); D.add(\"poie\"); D.add(\"plie\"); D.add(\"poin\"); D.add(\"plea\"); String start = \"toon\"; String target = \"plea\"; System.out.print(\"Length of shortest chain is: \" + shortestChainLen(start, target, D)); }} // This code is contributed by 29AjayKumar", "e": 22452, "s": 19567, "text": null }, { "code": null, "e": 22483, "s": 22452, "text": "Length of shortest chain is: 7" }, { "code": null, "e": 22631, "s": 22483, "text": "Time Complexity: O(N2 * M), where M is the number of entries originally in the dictionary and N is the size of the string.Auxiliary Space: O(M * N)" }, { "code": null, "e": 22645, "s": 22631, "text": "princiraj1992" }, { "code": null, "e": 22656, "s": 22645, "text": "andrew1234" }, { "code": null, "e": 22664, "s": 22656, "text": "ryadav2" }, { "code": null, "e": 22679, "s": 22664, "text": "mohit kumar 29" }, { "code": null, "e": 22687, "s": 22679, "text": "Codilis" }, { "code": null, "e": 22702, "s": 22687, "text": "UtkarshPandey6" }, { "code": null, "e": 22714, "s": 22702, "text": "unknown2108" }, { "code": null, "e": 22726, "s": 22714, "text": "29AjayKumar" }, { "code": null, "e": 22743, "s": 22726, "text": "nehakumariintern" }, { "code": null, "e": 22747, "s": 22743, "text": "BFS" }, { "code": null, "e": 22753, "s": 22747, "text": "Graph" }, { "code": null, "e": 22759, "s": 22753, "text": "Graph" }, { "code": null, "e": 22763, "s": 22759, "text": "BFS" }, { "code": null, "e": 22861, "s": 22763, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 22926, "s": 22861, "text": "Find if there is a path between two vertices in a directed graph" }, { "code": null, "e": 22958, "s": 22926, "text": "Introduction to Data Structures" }, { "code": null, "e": 22991, "s": 22958, "text": "Floyd Warshall Algorithm | DP-16" }, { "code": null, "e": 23066, "s": 22991, "text": "Disjoint Set (Or Union-Find) | Set 1 (Detect Cycle in an Undirected Graph)" }, { "code": null, "e": 23130, "s": 23066, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 23161, "s": 23130, "text": "Bellman–Ford Algorithm | DP-23" }, { "code": null, "e": 23229, "s": 23161, "text": "Find if there is a path between two vertices in an undirected graph" }, { "code": null, "e": 23297, "s": 23229, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 23333, "s": 23297, "text": "Detect cycle in an undirected graph" } ]
Mean of range in array
31 May, 2022 Given an array of n integers. You are given q queries. Write a program to print floor value of mean in range l to r for each query in a new line. Examples : Input : arr[] = {1, 2, 3, 4, 5} q = 3 0 2 1 3 0 4 Output : 2 3 3 Here for 0 to 2 (1 + 2 + 3) / 3 = 2 Input : arr[] = {6, 7, 8, 10} q = 2 0 3 1 2 Output : 7 7 Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query. C++ C Java Python3 C# PHP Javascript // CPP program to find floor value// of mean in range l to r#include <bits/stdc++.h>using namespace std; // To find mean of range in l to rint findMean(int arr[], int l, int r){ // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = floor(sum / count); // Returns mean of array // in range l to r return mean;} // Driver program to test findMean()int main(){ int arr[] = { 1, 2, 3, 4, 5 }; cout << findMean(arr, 0, 2) << endl; cout << findMean(arr, 1, 3) << endl; cout << findMean(arr, 0, 4) << endl; return 0;} // C program to find floor value// of mean in range l to r#include <stdio.h>#include <math.h> // To find mean of range in l to rint findMean(int arr[], int l, int r){ // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = floor(sum / count); // Returns mean of array // in range l to r return mean;} // Driver program to test findMean()int main(){ int arr[] = { 1, 2, 3, 4, 5 }; printf("%d\n",findMean(arr, 0, 2)); printf("%d\n",findMean(arr, 1, 3)); printf("%d\n",findMean(arr, 0, 4)); return 0;} // This code is contributed by kothavvsaakash // Java program to find floor value// of mean in range l to rpublic class Main { // To find mean of range in l to r static int findMean(int arr[], int l, int r) { // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = (int)Math.floor(sum / count); // Returns mean of array // in range l to r return mean; } // Driver program to test findMean() public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; System.out.println(findMean(arr, 0, 2)); System.out.println(findMean(arr, 1, 3)); System.out.println(findMean(arr, 0, 4)); }} # Python 3 program to find floor value# of mean in range l to rimport math # To find mean of range in l to rdef findMean(arr, l, r): # Both sum and count are # initialize to 0 sum, count = 0, 0 # To calculate sum and number # of elements in range l to r for i in range(l, r + 1): sum += arr[i] count += 1 # Calculate floor value of mean mean = math.floor(sum / count) # Returns mean of array # in range l to r return mean # Driver Codearr = [ 1, 2, 3, 4, 5 ] print(findMean(arr, 0, 2))print(findMean(arr, 1, 3))print(findMean(arr, 0, 4)) # This code is contributed# by PrinciRaj1992 //C# program to find floor value// of mean in range l to rusing System; public class GFG { // To find mean of range in l to r static int findMean(int []arr, int l, int r) { // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = (int)Math.Floor((double)sum / count); // Returns mean of array // in range l to r return mean; } // Driver program to test findMean() public static void Main() { int []arr = { 1, 2, 3, 4, 5 }; Console.WriteLine(findMean(arr, 0, 2)); Console.WriteLine(findMean(arr, 1, 3)); Console.WriteLine(findMean(arr, 0, 4)); }} /*This code is contributed by PrinciRaj1992*/ <?php// PHP program to find floor// value of mean in range l to r // To find mean of// range in l to rfunction findMean($arr, $l, $r){ // Both sum and count // are initialize to 0 $sum = 0; $count = 0; // To calculate sum and // number of elements in // range l to r for ($i = $l; $i <= $r; $i++) { $sum += $arr[$i]; $count++; } // Calculate floor // value of mean $mean = floor($sum / $count); // Returns mean of array // in range l to r return $mean;} // Driver Code$arr = array(1, 2, 3, 4, 5);echo findMean($arr, 0, 2), "\n";echo findMean($arr, 1, 3), "\n";echo findMean($arr, 0, 4), "\n"; // This code is contributed by ajit?> <script> // Javascript program to find floor value // of mean in range l to r // To find mean of range in l to r function findMean(arr, l, r) { // Both sum and count are // initialize to 0 let sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (let i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean let mean = Math.floor(sum / count); // Returns mean of array // in range l to r return mean; } let arr = [ 1, 2, 3, 4, 5 ]; document.write(findMean(arr, 0, 2) + "</br>"); document.write(findMean(arr, 1, 3) + "</br>"); document.write(findMean(arr, 0, 4) + "</br>"); </script> Output : 2 3 3 Time complexity: O(n*q) where q is the number of queries and n is the size of the array. Here in the above code q is 3 as the findMean function is used 3 times.Auxiliary Space: O(1) Efficient Approach: We can find sum of numbers using numbers using prefix sum. The prefixSum[i] denotes the sum of first i elements. So sum of numbers in range l to r will be prefixSum[r] – prefixSum[l-1]. Number of elements in range l to r will be r – l + 1. So we can now print mean of range l to r in O(1). C++ Java Python3 C# Javascript C // CPP program to find floor value// of mean in range l to r#include <bits/stdc++.h>#define MAX 1000005using namespace std; int prefixSum[MAX]; // To calculate prefixSum of arrayvoid calculatePrefixSum(int arr[], int n){ // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // To return floor of mean// in range l to rint findMean(int l, int r){ if (l == 0) return floor(prefixSum[r]/(r+1)); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));} // Driver program to test above functionsint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); calculatePrefixSum(arr, n); cout << findMean(0, 2) << endl; cout << findMean(1, 3) << endl; cout << findMean(0, 4) << endl; return 0;} // Java program to find floor value// of mean in range l to rpublic class Main {public static final int MAX = 1000005; static int prefixSum[] = new int[MAX]; // To calculate prefixSum of array static void calculatePrefixSum(int arr[], int n) { // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // To return floor of mean // in range l to r static int findMean(int l, int r) { if (l == 0) return (int)Math.floor(prefixSum[r] / (r + 1)); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return (int)Math.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1)); } // Driver program to test above functions public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; calculatePrefixSum(arr, n); System.out.println(findMean(1, 2)); System.out.println(findMean(1, 3)); System.out.println(findMean(1, 4)); }} # Python3 program to find floor value# of mean in range l to rimport math as mt MAX = 1000005prefixSum = [0 for i in range(MAX)] # To calculate prefixSum of arraydef calculatePrefixSum(arr, n): # Calculate prefix sum of array prefixSum[0] = arr[0] for i in range(1,n): prefixSum[i] = prefixSum[i - 1] + arr[i] # To return floor of mean# in range l to rdef findMean(l, r): if (l == 0): return mt.floor(prefixSum[r] / (r + 1)) # Sum of elements in range l to # r is prefixSum[r] - prefixSum[l-1] # Number of elements in range # l to r is r - l + 1 return (mt.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1))) # Driver Codearr = [1, 2, 3, 4, 5] n = len(arr) calculatePrefixSum(arr, n)print(findMean(0, 2))print(findMean(1, 3))print(findMean(0, 4)) # This code is contributed by Mohit Kumar // C# program to find floor value// of mean in range l to rusing System; public class GFG {public static readonly int MAX = 1000005; static int []prefixSum = new int[MAX]; // To calculate prefixSum of array static void calculatePrefixSum(int []arr, int n) { // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // To return floor of mean // in range l to r static int findMean(int l, int r) { if (l == 0) return (int)Math.Floor((double)(prefixSum[r] / (r + 1))); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return (int)Math.Floor((double)(prefixSum[r] - prefixSum[l - 1]) / (r - l + 1)); } // Driver program to test above functions public static void Main() { int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; calculatePrefixSum(arr, n); Console.WriteLine(findMean(1, 2)); Console.WriteLine(findMean(1, 3)); Console.WriteLine(findMean(1, 4)); }} //This code is contributed by PrinciRaj1992 <script> // Javascript program to find floor value// of mean in range l to rlet MAX = 1000005;let prefixSum = new Array(MAX);prefixSum.fill(0); // To calculate prefixSum of arrayfunction calculatePrefixSum(arr, n){ // Calculate prefix sum of array prefixSum[0] = arr[0]; for(let i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // To return floor of mean// in range l to rfunction findMean(l, r){ if (l == 0) return parseInt(Math.floor(prefixSum[r] / (r + 1)), 10); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return parseInt(Math.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1)), 10);} // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let n = arr.length;calculatePrefixSum(arr, n); document.write(findMean(1, 2) + "</br>");document.write(findMean(1, 3) + "</br>");document.write(findMean(1, 4) + "</br>"); // This code is contributed by divyeshrabadiya07 </script> // C program to find floor value// of mean in range l to r#include <stdio.h>#include <math.h> #define MAX 1000005 int prefixSum[MAX]; // To calculate prefixSum of arrayvoid calculatePrefixSum(int arr[], int n){ // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // To return floor of mean// in range l to rint findMean(int l, int r){ if (l == 0) return floor(prefixSum[r]/(r+1)); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));} // Driver program to test above functionsint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); calculatePrefixSum(arr, n); printf("%d\n",findMean(0, 2)); printf("%d\n",findMean(1, 3)); printf("%d\n",findMean(0, 4)); return 0;} Output: 2 3 3 Time complexity: O(n+q) where q is the number of queries and n is the size of the array. Here in the above code q is 3 as the findMean function is used 3 times.Auxiliary Space: O(k) where k=1000005. This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. jit_t princiraj1992 gfg_sal_gfg mohit kumar 29 divyesh072019 divyeshrabadiya07 kothavvsaakash pushpeshrajdx01 array-range-queries prefix-sum Arrays prefix-sum Arrays Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Maximum and minimum of an array using minimum number of comparisons Top 50 Array Coding Problems for Interviews Multidimensional Arrays in Java Stack Data Structure (Introduction and Program) Linear Search Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum) Introduction to Arrays K'th Smallest/Largest Element in Unsorted Array | Set 1 Subset Sum Problem | DP-25 Introduction to Data Structures
[ { "code": null, "e": 52, "s": 24, "text": "\n31 May, 2022" }, { "code": null, "e": 198, "s": 52, "text": "Given an array of n integers. You are given q queries. Write a program to print floor value of mean in range l to r for each query in a new line." }, { "code": null, "e": 210, "s": 198, "text": "Examples : " }, { "code": null, "e": 452, "s": 210, "text": "Input : arr[] = {1, 2, 3, 4, 5}\n q = 3\n 0 2\n 1 3\n 0 4\nOutput : 2\n 3\n 3\nHere for 0 to 2 (1 + 2 + 3) / 3 = 2\n\nInput : arr[] = {6, 7, 8, 10}\n q = 2\n 0 3\n 1 2\nOutput : 7\n 7" }, { "code": null, "e": 608, "s": 452, "text": "Naive Approach: We can run loop for each query l to r and find sum and number of elements in range. After this we can print floor of mean for each query. " }, { "code": null, "e": 612, "s": 608, "text": "C++" }, { "code": null, "e": 614, "s": 612, "text": "C" }, { "code": null, "e": 619, "s": 614, "text": "Java" }, { "code": null, "e": 627, "s": 619, "text": "Python3" }, { "code": null, "e": 630, "s": 627, "text": "C#" }, { "code": null, "e": 634, "s": 630, "text": "PHP" }, { "code": null, "e": 645, "s": 634, "text": "Javascript" }, { "code": "// CPP program to find floor value// of mean in range l to r#include <bits/stdc++.h>using namespace std; // To find mean of range in l to rint findMean(int arr[], int l, int r){ // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = floor(sum / count); // Returns mean of array // in range l to r return mean;} // Driver program to test findMean()int main(){ int arr[] = { 1, 2, 3, 4, 5 }; cout << findMean(arr, 0, 2) << endl; cout << findMean(arr, 1, 3) << endl; cout << findMean(arr, 0, 4) << endl; return 0;}", "e": 1402, "s": 645, "text": null }, { "code": "// C program to find floor value// of mean in range l to r#include <stdio.h>#include <math.h> // To find mean of range in l to rint findMean(int arr[], int l, int r){ // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = floor(sum / count); // Returns mean of array // in range l to r return mean;} // Driver program to test findMean()int main(){ int arr[] = { 1, 2, 3, 4, 5 }; printf(\"%d\\n\",findMean(arr, 0, 2)); printf(\"%d\\n\",findMean(arr, 1, 3)); printf(\"%d\\n\",findMean(arr, 0, 4)); return 0;} // This code is contributed by kothavvsaakash", "e": 2191, "s": 1402, "text": null }, { "code": "// Java program to find floor value// of mean in range l to rpublic class Main { // To find mean of range in l to r static int findMean(int arr[], int l, int r) { // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = (int)Math.floor(sum / count); // Returns mean of array // in range l to r return mean; } // Driver program to test findMean() public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; System.out.println(findMean(arr, 0, 2)); System.out.println(findMean(arr, 1, 3)); System.out.println(findMean(arr, 0, 4)); }}", "e": 3073, "s": 2191, "text": null }, { "code": "# Python 3 program to find floor value# of mean in range l to rimport math # To find mean of range in l to rdef findMean(arr, l, r): # Both sum and count are # initialize to 0 sum, count = 0, 0 # To calculate sum and number # of elements in range l to r for i in range(l, r + 1): sum += arr[i] count += 1 # Calculate floor value of mean mean = math.floor(sum / count) # Returns mean of array # in range l to r return mean # Driver Codearr = [ 1, 2, 3, 4, 5 ] print(findMean(arr, 0, 2))print(findMean(arr, 1, 3))print(findMean(arr, 0, 4)) # This code is contributed# by PrinciRaj1992", "e": 3719, "s": 3073, "text": null }, { "code": "//C# program to find floor value// of mean in range l to rusing System; public class GFG { // To find mean of range in l to r static int findMean(int []arr, int l, int r) { // Both sum and count are // initialize to 0 int sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (int i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean int mean = (int)Math.Floor((double)sum / count); // Returns mean of array // in range l to r return mean; } // Driver program to test findMean() public static void Main() { int []arr = { 1, 2, 3, 4, 5 }; Console.WriteLine(findMean(arr, 0, 2)); Console.WriteLine(findMean(arr, 1, 3)); Console.WriteLine(findMean(arr, 0, 4)); }} /*This code is contributed by PrinciRaj1992*/", "e": 4654, "s": 3719, "text": null }, { "code": "<?php// PHP program to find floor// value of mean in range l to r // To find mean of// range in l to rfunction findMean($arr, $l, $r){ // Both sum and count // are initialize to 0 $sum = 0; $count = 0; // To calculate sum and // number of elements in // range l to r for ($i = $l; $i <= $r; $i++) { $sum += $arr[$i]; $count++; } // Calculate floor // value of mean $mean = floor($sum / $count); // Returns mean of array // in range l to r return $mean;} // Driver Code$arr = array(1, 2, 3, 4, 5);echo findMean($arr, 0, 2), \"\\n\";echo findMean($arr, 1, 3), \"\\n\";echo findMean($arr, 0, 4), \"\\n\"; // This code is contributed by ajit?>", "e": 5350, "s": 4654, "text": null }, { "code": "<script> // Javascript program to find floor value // of mean in range l to r // To find mean of range in l to r function findMean(arr, l, r) { // Both sum and count are // initialize to 0 let sum = 0, count = 0; // To calculate sum and number // of elements in range l to r for (let i = l; i <= r; i++) { sum += arr[i]; count++; } // Calculate floor value of mean let mean = Math.floor(sum / count); // Returns mean of array // in range l to r return mean; } let arr = [ 1, 2, 3, 4, 5 ]; document.write(findMean(arr, 0, 2) + \"</br>\"); document.write(findMean(arr, 1, 3) + \"</br>\"); document.write(findMean(arr, 0, 4) + \"</br>\"); </script>", "e": 6148, "s": 5350, "text": null }, { "code": null, "e": 6158, "s": 6148, "text": "Output : " }, { "code": null, "e": 6164, "s": 6158, "text": "2\n3\n3" }, { "code": null, "e": 6346, "s": 6164, "text": "Time complexity: O(n*q) where q is the number of queries and n is the size of the array. Here in the above code q is 3 as the findMean function is used 3 times.Auxiliary Space: O(1)" }, { "code": null, "e": 6657, "s": 6346, "text": "Efficient Approach: We can find sum of numbers using numbers using prefix sum. The prefixSum[i] denotes the sum of first i elements. So sum of numbers in range l to r will be prefixSum[r] – prefixSum[l-1]. Number of elements in range l to r will be r – l + 1. So we can now print mean of range l to r in O(1). " }, { "code": null, "e": 6661, "s": 6657, "text": "C++" }, { "code": null, "e": 6666, "s": 6661, "text": "Java" }, { "code": null, "e": 6674, "s": 6666, "text": "Python3" }, { "code": null, "e": 6677, "s": 6674, "text": "C#" }, { "code": null, "e": 6688, "s": 6677, "text": "Javascript" }, { "code": null, "e": 6690, "s": 6688, "text": "C" }, { "code": "// CPP program to find floor value// of mean in range l to r#include <bits/stdc++.h>#define MAX 1000005using namespace std; int prefixSum[MAX]; // To calculate prefixSum of arrayvoid calculatePrefixSum(int arr[], int n){ // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // To return floor of mean// in range l to rint findMean(int l, int r){ if (l == 0) return floor(prefixSum[r]/(r+1)); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));} // Driver program to test above functionsint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); calculatePrefixSum(arr, n); cout << findMean(0, 2) << endl; cout << findMean(1, 3) << endl; cout << findMean(0, 4) << endl; return 0;}", "e": 7672, "s": 6690, "text": null }, { "code": "// Java program to find floor value// of mean in range l to rpublic class Main {public static final int MAX = 1000005; static int prefixSum[] = new int[MAX]; // To calculate prefixSum of array static void calculatePrefixSum(int arr[], int n) { // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // To return floor of mean // in range l to r static int findMean(int l, int r) { if (l == 0) return (int)Math.floor(prefixSum[r] / (r + 1)); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return (int)Math.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1)); } // Driver program to test above functions public static void main(String[] args) { int arr[] = { 1, 2, 3, 4, 5 }; int n = arr.length; calculatePrefixSum(arr, n); System.out.println(findMean(1, 2)); System.out.println(findMean(1, 3)); System.out.println(findMean(1, 4)); }}", "e": 8854, "s": 7672, "text": null }, { "code": "# Python3 program to find floor value# of mean in range l to rimport math as mt MAX = 1000005prefixSum = [0 for i in range(MAX)] # To calculate prefixSum of arraydef calculatePrefixSum(arr, n): # Calculate prefix sum of array prefixSum[0] = arr[0] for i in range(1,n): prefixSum[i] = prefixSum[i - 1] + arr[i] # To return floor of mean# in range l to rdef findMean(l, r): if (l == 0): return mt.floor(prefixSum[r] / (r + 1)) # Sum of elements in range l to # r is prefixSum[r] - prefixSum[l-1] # Number of elements in range # l to r is r - l + 1 return (mt.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1))) # Driver Codearr = [1, 2, 3, 4, 5] n = len(arr) calculatePrefixSum(arr, n)print(findMean(0, 2))print(findMean(1, 3))print(findMean(0, 4)) # This code is contributed by Mohit Kumar", "e": 9738, "s": 8854, "text": null }, { "code": "// C# program to find floor value// of mean in range l to rusing System; public class GFG {public static readonly int MAX = 1000005; static int []prefixSum = new int[MAX]; // To calculate prefixSum of array static void calculatePrefixSum(int []arr, int n) { // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i]; } // To return floor of mean // in range l to r static int findMean(int l, int r) { if (l == 0) return (int)Math.Floor((double)(prefixSum[r] / (r + 1))); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return (int)Math.Floor((double)(prefixSum[r] - prefixSum[l - 1]) / (r - l + 1)); } // Driver program to test above functions public static void Main() { int []arr = { 1, 2, 3, 4, 5 }; int n = arr.Length; calculatePrefixSum(arr, n); Console.WriteLine(findMean(1, 2)); Console.WriteLine(findMean(1, 3)); Console.WriteLine(findMean(1, 4)); }} //This code is contributed by PrinciRaj1992", "e": 11004, "s": 9738, "text": null }, { "code": "<script> // Javascript program to find floor value// of mean in range l to rlet MAX = 1000005;let prefixSum = new Array(MAX);prefixSum.fill(0); // To calculate prefixSum of arrayfunction calculatePrefixSum(arr, n){ // Calculate prefix sum of array prefixSum[0] = arr[0]; for(let i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // To return floor of mean// in range l to rfunction findMean(l, r){ if (l == 0) return parseInt(Math.floor(prefixSum[r] / (r + 1)), 10); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return parseInt(Math.floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1)), 10);} // Driver codelet arr = [ 1, 2, 3, 4, 5 ];let n = arr.length;calculatePrefixSum(arr, n); document.write(findMean(1, 2) + \"</br>\");document.write(findMean(1, 3) + \"</br>\");document.write(findMean(1, 4) + \"</br>\"); // This code is contributed by divyeshrabadiya07 </script>", "e": 12097, "s": 11004, "text": null }, { "code": "// C program to find floor value// of mean in range l to r#include <stdio.h>#include <math.h> #define MAX 1000005 int prefixSum[MAX]; // To calculate prefixSum of arrayvoid calculatePrefixSum(int arr[], int n){ // Calculate prefix sum of array prefixSum[0] = arr[0]; for (int i = 1; i < n; i++) prefixSum[i] = prefixSum[i - 1] + arr[i];} // To return floor of mean// in range l to rint findMean(int l, int r){ if (l == 0) return floor(prefixSum[r]/(r+1)); // Sum of elements in range l to // r is prefixSum[r] - prefixSum[l-1] // Number of elements in range // l to r is r - l + 1 return floor((prefixSum[r] - prefixSum[l - 1]) / (r - l + 1));} // Driver program to test above functionsint main(){ int arr[] = { 1, 2, 3, 4, 5 }; int n = sizeof(arr) / sizeof(arr[0]); calculatePrefixSum(arr, n); printf(\"%d\\n\",findMean(0, 2)); printf(\"%d\\n\",findMean(1, 3)); printf(\"%d\\n\",findMean(0, 4)); return 0;}", "e": 13066, "s": 12097, "text": null }, { "code": null, "e": 13075, "s": 13066, "text": "Output: " }, { "code": null, "e": 13081, "s": 13075, "text": "2\n3\n3" }, { "code": null, "e": 13280, "s": 13081, "text": "Time complexity: O(n+q) where q is the number of queries and n is the size of the array. Here in the above code q is 3 as the findMean function is used 3 times.Auxiliary Space: O(k) where k=1000005." }, { "code": null, "e": 13696, "s": 13280, "text": "This article is contributed by nuclode. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. " }, { "code": null, "e": 13702, "s": 13696, "text": "jit_t" }, { "code": null, "e": 13716, "s": 13702, "text": "princiraj1992" }, { "code": null, "e": 13728, "s": 13716, "text": "gfg_sal_gfg" }, { "code": null, "e": 13743, "s": 13728, "text": "mohit kumar 29" }, { "code": null, "e": 13757, "s": 13743, "text": "divyesh072019" }, { "code": null, "e": 13775, "s": 13757, "text": "divyeshrabadiya07" }, { "code": null, "e": 13790, "s": 13775, "text": "kothavvsaakash" }, { "code": null, "e": 13806, "s": 13790, "text": "pushpeshrajdx01" }, { "code": null, "e": 13826, "s": 13806, "text": "array-range-queries" }, { "code": null, "e": 13837, "s": 13826, "text": "prefix-sum" }, { "code": null, "e": 13844, "s": 13837, "text": "Arrays" }, { "code": null, "e": 13855, "s": 13844, "text": "prefix-sum" }, { "code": null, "e": 13862, "s": 13855, "text": "Arrays" }, { "code": null, "e": 13960, "s": 13862, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 14028, "s": 13960, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 14072, "s": 14028, "text": "Top 50 Array Coding Problems for Interviews" }, { "code": null, "e": 14104, "s": 14072, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 14152, "s": 14104, "text": "Stack Data Structure (Introduction and Program)" }, { "code": null, "e": 14166, "s": 14152, "text": "Linear Search" }, { "code": null, "e": 14251, "s": 14166, "text": "Given an array A[] and a number x, check for pair in A[] with sum as x (aka Two Sum)" }, { "code": null, "e": 14274, "s": 14251, "text": "Introduction to Arrays" }, { "code": null, "e": 14330, "s": 14274, "text": "K'th Smallest/Largest Element in Unsorted Array | Set 1" }, { "code": null, "e": 14357, "s": 14330, "text": "Subset Sum Problem | DP-25" } ]
How to Skew Text on Hover using HTML and CSS?
15 Jul, 2020 Skewed text animation effect can be created using HTML and CSS, this animation looks very cool and can be used in websites to make them look more dynamic, the following sections will guide on how to create the desired animation effect. First Section: In this section we will create a basic div tag which consists of various span tags inside of it. HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Skew Text</title></head><body> <div> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> <span>F</span> <span>O</span> <span>R</span> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> </div></body></html> Second Section: In this section we will first design the span tags using basic CSS properties further we will use the nth-child() selector to select the element’s children and use the skewY() property to produce the desired effect on hover. CSS Code: CSS <style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 40px; width: 40px; margin-right: -2px; background-color: green; text-align: center; font-size: 2em; } div:hover span:nth-child(odd){ transform: skewY(-15deg); } div:hover span:nth-child(even){ transform: skewY(15deg); } </style> Final Code: It is the combination of the above two code sections HTML <!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Skew Text</title></head><style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 40px; width: 40px; margin-right: -2px; background-color: green; text-align: center; font-size: 2em; } div:hover span:nth-child(odd){ transform: skewY(-15deg); } div:hover span:nth-child(even){ transform: skewY(15deg); } </style> <body> <div> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> <span>F</span> <span>O</span> <span>R</span> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> </div></body></html> Output: CSS-Basics HTML-Basics CSS HTML Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? How to create footer to stay at the bottom of a Web page? CSS to put icon inside an input element in a form How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Jul, 2020" }, { "code": null, "e": 264, "s": 28, "text": "Skewed text animation effect can be created using HTML and CSS, this animation looks very cool and can be used in websites to make them look more dynamic, the following sections will guide on how to create the desired animation effect." }, { "code": null, "e": 376, "s": 264, "text": "First Section: In this section we will create a basic div tag which consists of various span tags inside of it." }, { "code": null, "e": 381, "s": 376, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Skew Text</title></head><body> <div> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> <span>F</span> <span>O</span> <span>R</span> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> </div></body></html>", "e": 831, "s": 381, "text": null }, { "code": null, "e": 1072, "s": 831, "text": "Second Section: In this section we will first design the span tags using basic CSS properties further we will use the nth-child() selector to select the element’s children and use the skewY() property to produce the desired effect on hover." }, { "code": null, "e": 1082, "s": 1072, "text": "CSS Code:" }, { "code": null, "e": 1086, "s": 1082, "text": "CSS" }, { "code": "<style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 40px; width: 40px; margin-right: -2px; background-color: green; text-align: center; font-size: 2em; } div:hover span:nth-child(odd){ transform: skewY(-15deg); } div:hover span:nth-child(even){ transform: skewY(15deg); } </style>", "e": 1572, "s": 1086, "text": null }, { "code": null, "e": 1637, "s": 1572, "text": "Final Code: It is the combination of the above two code sections" }, { "code": null, "e": 1642, "s": 1637, "text": "HTML" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"> <title>Skew Text</title></head><style> *{ margin: 0; padding: 0; } div{ position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); display: flex; align-items: center; } span{ height: 40px; width: 40px; margin-right: -2px; background-color: green; text-align: center; font-size: 2em; } div:hover span:nth-child(odd){ transform: skewY(-15deg); } div:hover span:nth-child(even){ transform: skewY(15deg); } </style> <body> <div> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> <span>F</span> <span>O</span> <span>R</span> <span>G</span> <span>E</span> <span>E</span> <span>K</span> <span>S</span> </div></body></html>", "e": 2579, "s": 1642, "text": null }, { "code": null, "e": 2587, "s": 2579, "text": "Output:" }, { "code": null, "e": 2598, "s": 2587, "text": "CSS-Basics" }, { "code": null, "e": 2610, "s": 2598, "text": "HTML-Basics" }, { "code": null, "e": 2614, "s": 2610, "text": "CSS" }, { "code": null, "e": 2619, "s": 2614, "text": "HTML" }, { "code": null, "e": 2636, "s": 2619, "text": "Web Technologies" }, { "code": null, "e": 2663, "s": 2636, "text": "Web technologies Questions" }, { "code": null, "e": 2668, "s": 2663, "text": "HTML" }, { "code": null, "e": 2766, "s": 2668, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2814, "s": 2766, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 2876, "s": 2814, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2926, "s": 2876, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 2984, "s": 2926, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 3034, "s": 2984, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 3082, "s": 3034, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 3144, "s": 3082, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3194, "s": 3144, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 3218, "s": 3194, "text": "REST API (Introduction)" } ]
Spring Boot - Admin Server
Monitoring your application by using Spring Boot Actuator Endpoint is slightly difficult. Because, if you have ‘n’ number of applications, every application has separate actuator endpoints, thus making monitoring difficult. Spring Boot Admin Server is an application used to manage and monitor your Microservice application. To handle such situations, CodeCentric Team provides a Spring Boot Admin UI to manage and monitor all your Spring Boot application Actuator endpoints at one place. For building a Spring Boot Admin Server we need to add the below dependencies in your build configuration file. Maven users can add the below dependencies in your pom.xml file − <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.5.5</version> </dependency> Gradle users can add the below dependencies in your build.gradle file − compile group: 'de.codecentric', name: 'spring-boot-admin-server', version: '1.5.5' compile group: 'de.codecentric', name: 'spring-boot-admin-server-ui', version: '1.5.5' Add the @EnableAdminServer annotation in your main Spring Boot application class file. The @EnableAdminServer annotation is used to make your as Admin Server to monitor all other microservices. package com.tutorialspoint.adminserver; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import de.codecentric.boot.admin.config.EnableAdminServer; @SpringBootApplication @EnableAdminServer public class AdminserverApplication { public static void main(String[] args) { SpringApplication.run(AdminserverApplication.class, args); } } Now, define the server.port and application name in application.properties file a shown − server.port = 9090 spring.application.name = adminserver For YAML users, use the following properties to define the port number and application name in application.yml file. server: port: 9090 spring: application: name: adminserver The build configuration file is given below. For Maven users – pom.xml <?xml version = "1.0" encoding = "UTF-8"?> <project xmlns = "http://maven.apache.org/POM/4.0.0" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tutorialspoint</groupId> <artifactId>adminserver</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>jar</packaging> <name>adminserver</name> <description>Demo project for Spring Boot</description> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.9.RELEASE</version> <relativePath /> <!-- lookup parent from repository --> </parent> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>de.codecentric</groupId> <artifactId>spring-boot-admin-server-ui</artifactId> <version>1.5.5</version> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-maven-plugin</artifactId> </plugin> </plugins> </build> </project> For Gradle users – build.gradle file buildscript { ext { springBootVersion = '1.5.9.RELEASE' } repositories { mavenCentral() } dependencies { classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}") } } apply plugin: 'java' apply plugin: 'eclipse' apply plugin: 'org.springframework.boot' group = 'com.tutorialspoint' version = '0.0.1-SNAPSHOT' sourceCompatibility = 1.8 repositories { mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter') compile group: 'de.codecentric', name: 'spring-boot-admin-server', version: '1.5.5' compile group: 'de.codecentric', name: 'spring-boot-admin-server-ui', version: '1.5.5' testCompile('org.springframework.boot:spring-boot-starter-test') } You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands − For Maven, use the command shown here − mvn clean install After “BUILD SUCCESS”, you can find the JAR file under target directory. For Gradle, use the command shown here − gradle clean build After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory. Now, run the JAR file by using the command given below − java –jar <JARFILE> Now, the application has started on the Tomcat port 9090 as shown here − Now hit the below URL from your web browser and see the Admin Server UI.
[ { "code": null, "e": 3484, "s": 3159, "text": "Monitoring your application by using Spring Boot Actuator Endpoint is slightly difficult. Because, if you have ‘n’ number of applications, every application has separate actuator endpoints, thus making monitoring difficult. Spring Boot Admin Server is an application used to manage and monitor your Microservice application." }, { "code": null, "e": 3648, "s": 3484, "text": "To handle such situations, CodeCentric Team provides a Spring Boot Admin UI to manage and monitor all your Spring Boot application Actuator endpoints at one place." }, { "code": null, "e": 3760, "s": 3648, "text": "For building a Spring Boot Admin Server we need to add the below dependencies in your build configuration file." }, { "code": null, "e": 3826, "s": 3760, "text": "Maven users can add the below dependencies in your pom.xml file −" }, { "code": null, "e": 4119, "s": 3826, "text": "<dependency>\n <groupId>de.codecentric</groupId>\n <artifactId>spring-boot-admin-server</artifactId>\n <version>1.5.5</version>\n</dependency>\n<dependency>\n <groupId>de.codecentric</groupId>\n <artifactId>spring-boot-admin-server-ui</artifactId>\n <version>1.5.5</version>\n</dependency>" }, { "code": null, "e": 4191, "s": 4119, "text": "Gradle users can add the below dependencies in your build.gradle file −" }, { "code": null, "e": 4362, "s": 4191, "text": "compile group: 'de.codecentric', name: 'spring-boot-admin-server', version: '1.5.5'\ncompile group: 'de.codecentric', name: 'spring-boot-admin-server-ui', version: '1.5.5'" }, { "code": null, "e": 4556, "s": 4362, "text": "Add the @EnableAdminServer annotation in your main Spring Boot application class file. The @EnableAdminServer annotation is used to make your as Admin Server to monitor all other microservices." }, { "code": null, "e": 4976, "s": 4556, "text": "package com.tutorialspoint.adminserver;\n\nimport org.springframework.boot.SpringApplication;\nimport org.springframework.boot.autoconfigure.SpringBootApplication;\nimport de.codecentric.boot.admin.config.EnableAdminServer;\n\n@SpringBootApplication\n@EnableAdminServer\npublic class AdminserverApplication { \n public static void main(String[] args) {\n SpringApplication.run(AdminserverApplication.class, args);\n }\n}" }, { "code": null, "e": 5066, "s": 4976, "text": "Now, define the server.port and application name in application.properties file a shown −" }, { "code": null, "e": 5123, "s": 5066, "text": "server.port = 9090\nspring.application.name = adminserver" }, { "code": null, "e": 5240, "s": 5123, "text": "For YAML users, use the following properties to define the port number and application name in application.yml file." }, { "code": null, "e": 5310, "s": 5240, "text": "server:\n port: 9090\nspring:\n application:\n name: adminserver" }, { "code": null, "e": 5355, "s": 5310, "text": "The build configuration file is given below." }, { "code": null, "e": 5381, "s": 5355, "text": "For Maven users – pom.xml" }, { "code": null, "e": 7339, "s": 5381, "text": "<?xml version = \"1.0\" encoding = \"UTF-8\"?>\n<project xmlns = \"http://maven.apache.org/POM/4.0.0\" \n xmlns:xsi = \"http://www.w3.org/2001/XMLSchema-instance\"\n xsi:schemaLocation = \"http://maven.apache.org/POM/4.0.0 \n http://maven.apache.org/xsd/maven-4.0.0.xsd\">\n \n <modelVersion>4.0.0</modelVersion>\n <groupId>com.tutorialspoint</groupId>\n <artifactId>adminserver</artifactId>\n <version>0.0.1-SNAPSHOT</version>\n <packaging>jar</packaging>\n\n <name>adminserver</name>\n <description>Demo project for Spring Boot</description>\n\n <parent>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-parent</artifactId>\n <version>1.5.9.RELEASE</version>\n <relativePath /> <!-- lookup parent from repository -->\n </parent>\n\n <properties>\n <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>\n <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>\n <java.version>1.8</java.version>\n </properties>\n\n <dependencies>\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter</artifactId>\n </dependency>\n\n <dependency>\n <groupId>de.codecentric</groupId>\n <artifactId>spring-boot-admin-server</artifactId>\n <version>1.5.5</version>\n </dependency>\n \n <dependency>\n <groupId>de.codecentric</groupId>\n <artifactId>spring-boot-admin-server-ui</artifactId>\n <version>1.5.5</version>\n </dependency>\n\n <dependency>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-starter-test</artifactId>\n <scope>test</scope>\n </dependency>\n </dependencies>\n\n <build>\n <plugins>\n <plugin>\n <groupId>org.springframework.boot</groupId>\n <artifactId>spring-boot-maven-plugin</artifactId>\n </plugin>\n </plugins>\n </build>\n \n</project>" }, { "code": null, "e": 7376, "s": 7339, "text": "For Gradle users – build.gradle file" }, { "code": null, "e": 8138, "s": 7376, "text": "buildscript {\n ext {\n springBootVersion = '1.5.9.RELEASE'\n }\n repositories {\n mavenCentral()\n }\n dependencies {\n classpath(\"org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}\")\n }\n}\n\napply plugin: 'java'\napply plugin: 'eclipse'\napply plugin: 'org.springframework.boot'\n\ngroup = 'com.tutorialspoint'\nversion = '0.0.1-SNAPSHOT'\nsourceCompatibility = 1.8\nrepositories { \n mavenCentral()\n}\ndependencies {\n compile('org.springframework.boot:spring-boot-starter')\n compile group: 'de.codecentric', name: 'spring-boot-admin-server', version: '1.5.5'\n compile group: 'de.codecentric', name: 'spring-boot-admin-server-ui', version: '1.5.5' \n testCompile('org.springframework.boot:spring-boot-starter-test')\n}" }, { "code": null, "e": 8263, "s": 8138, "text": "You can create an executable JAR file, and run the Spring Boot application by using the following Maven or Gradle commands −" }, { "code": null, "e": 8303, "s": 8263, "text": "For Maven, use the command shown here −" }, { "code": null, "e": 8322, "s": 8303, "text": "mvn clean install\n" }, { "code": null, "e": 8395, "s": 8322, "text": "After “BUILD SUCCESS”, you can find the JAR file under target directory." }, { "code": null, "e": 8436, "s": 8395, "text": "For Gradle, use the command shown here −" }, { "code": null, "e": 8456, "s": 8436, "text": "gradle clean build\n" }, { "code": null, "e": 8536, "s": 8456, "text": "After “BUILD SUCCESSFUL”, you can find the JAR file under build/libs directory." }, { "code": null, "e": 8593, "s": 8536, "text": "Now, run the JAR file by using the command given below −" }, { "code": null, "e": 8615, "s": 8593, "text": "java –jar <JARFILE> \n" }, { "code": null, "e": 8688, "s": 8615, "text": "Now, the application has started on the Tomcat port 9090 as shown here −" } ]
Python | Pandas dataframe.to_clipboard()
29 Jan, 2019 Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas dataframe.to_clipboard() function copy object to the system clipboard. This function writes a text representation of the object to the system clipboard. This could be easily pasted into excel or notepad++. Syntax: DataFrame.to_clipboard(excel=True, sep=None, **kwargs) Parameters :excel : True, use the provided separator, writing in a csv format for allowing easy pasting into excel. False, write a string representation of the object to the clipboard.sep : Field delimiter.**kwargs : These parameters will be passed to DataFrame.to_csv. Note : For link to the CSV file used in the code, click here Example #1: Use to_clipboard() function to copy the object to the clipboard in a non-excel format. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv('nba.csv') # Print the dataframedf Output : Now we will copy this object to clipboard in a non-excel format. # copy to clipboarddf.to_clipboard(excel = False, sep = ', ') Output :We have simply pasted, what got copied to the clipboard after executing the previous command. The software used was “Notepad++”. Example #2: Use to_clipboard() function to copy the object to the clipboard in an excel format. # importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv('nba.csv') # Print the dataframedf Output : Now we will copy this object to clipboard in an excel format. # copy to clipboarddf.to_clipboard(excel = True) Output : Python pandas-dataFrame Python pandas-dataFrame-methods Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? 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": 53, "s": 25, "text": "\n29 Jan, 2019" }, { "code": null, "e": 267, "s": 53, "text": "Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier." }, { "code": null, "e": 480, "s": 267, "text": "Pandas dataframe.to_clipboard() function copy object to the system clipboard. This function writes a text representation of the object to the system clipboard. This could be easily pasted into excel or notepad++." }, { "code": null, "e": 543, "s": 480, "text": "Syntax: DataFrame.to_clipboard(excel=True, sep=None, **kwargs)" }, { "code": null, "e": 813, "s": 543, "text": "Parameters :excel : True, use the provided separator, writing in a csv format for allowing easy pasting into excel. False, write a string representation of the object to the clipboard.sep : Field delimiter.**kwargs : These parameters will be passed to DataFrame.to_csv." }, { "code": null, "e": 874, "s": 813, "text": "Note : For link to the CSV file used in the code, click here" }, { "code": null, "e": 973, "s": 874, "text": "Example #1: Use to_clipboard() function to copy the object to the clipboard in a non-excel format." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv('nba.csv') # Print the dataframedf", "e": 1096, "s": 973, "text": null }, { "code": null, "e": 1105, "s": 1096, "text": "Output :" }, { "code": null, "e": 1170, "s": 1105, "text": "Now we will copy this object to clipboard in a non-excel format." }, { "code": "# copy to clipboarddf.to_clipboard(excel = False, sep = ', ')", "e": 1232, "s": 1170, "text": null }, { "code": null, "e": 1465, "s": 1232, "text": "Output :We have simply pasted, what got copied to the clipboard after executing the previous command. The software used was “Notepad++”. Example #2: Use to_clipboard() function to copy the object to the clipboard in an excel format." }, { "code": "# importing pandas as pdimport pandas as pd # Creating the dataframe df = pd.read_csv('nba.csv') # Print the dataframedf", "e": 1588, "s": 1465, "text": null }, { "code": null, "e": 1597, "s": 1588, "text": "Output :" }, { "code": null, "e": 1659, "s": 1597, "text": "Now we will copy this object to clipboard in an excel format." }, { "code": "# copy to clipboarddf.to_clipboard(excel = True)", "e": 1708, "s": 1659, "text": null }, { "code": null, "e": 1717, "s": 1708, "text": "Output :" }, { "code": null, "e": 1741, "s": 1717, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1773, "s": 1741, "text": "Python pandas-dataFrame-methods" }, { "code": null, "e": 1787, "s": 1773, "text": "Python-pandas" }, { "code": null, "e": 1794, "s": 1787, "text": "Python" }, { "code": null, "e": 1892, "s": 1794, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1924, "s": 1892, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1951, "s": 1924, "text": "Python Classes and Objects" }, { "code": null, "e": 1972, "s": 1951, "text": "Python OOPs Concepts" }, { "code": null, "e": 1995, "s": 1972, "text": "Introduction To PYTHON" }, { "code": null, "e": 2051, "s": 1995, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2082, "s": 2051, "text": "Python | os.path.join() method" }, { "code": null, "e": 2124, "s": 2082, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2166, "s": 2124, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2205, "s": 2166, "text": "Python | datetime.timedelta() function" } ]
TemplateView – Class Based Generic View Django
25 May, 2021 Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL. TemplateView should be used when you want to present some information on an HTML page. TemplateView shouldn’t be used when your page has forms and does creation or update of objects. In such cases, FormView, CreateView, or UpdateView is a better option. TemplateView is most suitable in the following cases: Showing ‘about us’ like pages that are static and hardly need any context. Though, it is easy to use context variables with TemplateView. Showing pages that work with GET requests and don’t have forms in them. Explanation : Illustration of How to use TemplateView 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 ? Let’s write a view using base class view View and then modify it to use TemplateView. TemplateView would help us avoid several lines of code. Enter the following code into views.py file of geeks app. Python3 from django.views.generic.base import Viewfrom django.shortcuts import render class AboutUs(View): def get(self, request, *args, **kwargs): return render(request, "aboutus.html") Create a folder named templates inside the geeks app and then create a file named aboutus.html inside templates folder. Enter the following code into aboutus.html file. HTML <!DOCTYPE html><html><head><title>AboutUs</title></head><body><h2>Welcome To GFG</h2></body></html> Enter the Following code into urls.py of geeksforgeeks project folder. Python3 from django.contrib import adminfrom django.urls import pathfrom geeks.views import AboutUs urlpatterns = [ path('admin/', admin.site.urls), path('',AboutUs.as_view(),name="aboutus")] Run below three commands to see the output. Python manage.py makemigrations Python manage.py migrate Python manage.py runserver Same output can be achieved using TemplateView , replace code of views.py file of geeks app by given below code. Python3 from django.views.generic.base import TemplateView class AboutUs(TemplateView): template_name = 'aboutus.html' Let’s check what is there on http://localhost:8000/ Output – Code_Mech Django-views Python Django 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": "\n25 May, 2021" }, { "code": null, "e": 236, "s": 28, "text": "Django provides several class based generic views to accomplish common tasks. The simplest among them is TemplateView. It Renders a given template, with the context containing parameters captured in the URL." }, { "code": null, "e": 490, "s": 236, "text": "TemplateView should be used when you want to present some information on an HTML page. TemplateView shouldn’t be used when your page has forms and does creation or update of objects. In such cases, FormView, CreateView, or UpdateView is a better option." }, { "code": null, "e": 544, "s": 490, "text": "TemplateView is most suitable in the following cases:" }, { "code": null, "e": 682, "s": 544, "text": "Showing ‘about us’ like pages that are static and hardly need any context. Though, it is easy to use context variables with TemplateView." }, { "code": null, "e": 754, "s": 682, "text": "Showing pages that work with GET requests and don’t have forms in them." }, { "code": null, "e": 768, "s": 754, "text": "Explanation :" }, { "code": null, "e": 892, "s": 768, "text": "Illustration of How to use TemplateView using an Example. Consider a project named geeksforgeeks having an app named geeks." }, { "code": null, "e": 982, "s": 892, "text": "Refer to the following articles to check how to create a project and an app in Django. " }, { "code": null, "e": 1037, "s": 982, "text": "How to Create a Basic Project using MVT in Django ? " }, { "code": null, "e": 1070, "s": 1037, "text": "How to Create an App in Django ?" }, { "code": null, "e": 1212, "s": 1070, "text": "Let’s write a view using base class view View and then modify it to use TemplateView. TemplateView would help us avoid several lines of code." }, { "code": null, "e": 1270, "s": 1212, "text": "Enter the following code into views.py file of geeks app." }, { "code": null, "e": 1278, "s": 1270, "text": "Python3" }, { "code": "from django.views.generic.base import Viewfrom django.shortcuts import render class AboutUs(View): def get(self, request, *args, **kwargs): return render(request, \"aboutus.html\")", "e": 1465, "s": 1278, "text": null }, { "code": null, "e": 1585, "s": 1465, "text": "Create a folder named templates inside the geeks app and then create a file named aboutus.html inside templates folder." }, { "code": null, "e": 1634, "s": 1585, "text": "Enter the following code into aboutus.html file." }, { "code": null, "e": 1639, "s": 1634, "text": "HTML" }, { "code": "<!DOCTYPE html><html><head><title>AboutUs</title></head><body><h2>Welcome To GFG</h2></body></html>", "e": 1739, "s": 1639, "text": null }, { "code": null, "e": 1810, "s": 1739, "text": "Enter the Following code into urls.py of geeksforgeeks project folder." }, { "code": null, "e": 1818, "s": 1810, "text": "Python3" }, { "code": "from django.contrib import adminfrom django.urls import pathfrom geeks.views import AboutUs urlpatterns = [ path('admin/', admin.site.urls), path('',AboutUs.as_view(),name=\"aboutus\")]", "e": 2010, "s": 1818, "text": null }, { "code": null, "e": 2057, "s": 2013, "text": "Run below three commands to see the output." }, { "code": null, "e": 2141, "s": 2057, "text": "Python manage.py makemigrations\nPython manage.py migrate\nPython manage.py runserver" }, { "code": null, "e": 2255, "s": 2141, "text": "Same output can be achieved using TemplateView , replace code of views.py file of geeks app by given below code." }, { "code": null, "e": 2265, "s": 2257, "text": "Python3" }, { "code": "from django.views.generic.base import TemplateView class AboutUs(TemplateView): template_name = 'aboutus.html'", "e": 2379, "s": 2265, "text": null }, { "code": null, "e": 2431, "s": 2379, "text": "Let’s check what is there on http://localhost:8000/" }, { "code": null, "e": 2441, "s": 2431, "text": "Output – " }, { "code": null, "e": 2451, "s": 2441, "text": "Code_Mech" }, { "code": null, "e": 2464, "s": 2451, "text": "Django-views" }, { "code": null, "e": 2478, "s": 2464, "text": "Python Django" }, { "code": null, "e": 2485, "s": 2478, "text": "Python" }, { "code": null, "e": 2583, "s": 2485, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2615, "s": 2583, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2642, "s": 2615, "text": "Python Classes and Objects" }, { "code": null, "e": 2673, "s": 2642, "text": "Python | os.path.join() method" }, { "code": null, "e": 2696, "s": 2673, "text": "Introduction To PYTHON" }, { "code": null, "e": 2717, "s": 2696, "text": "Python OOPs Concepts" }, { "code": null, "e": 2773, "s": 2717, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2815, "s": 2773, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2857, "s": 2815, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2896, "s": 2857, "text": "Python | Get unique values from a list" } ]
Python Program for Cocktail Sort
22 Jun, 2022 Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively. Algorithm: Each iteration of the algorithm is broken up into 2 stages: The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required. The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array. The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required. Python # Python program for implementation of Cocktail Sort def cocktailSort(a): n = len(a) swapped = True start = 0 end = n-1 while (swapped==True): # reset the swapped flag on entering the loop, # because it might be true from a previous # iteration. swapped = False # loop from left to right same as the bubble # sort for i in range (start, end): if (a[i] > a[i+1]) : a[i], a[i+1]= a[i+1], a[i] swapped=True # if nothing moved, then array is sorted. if (swapped==False): break # otherwise, reset the swapped flag so that it # can be used in the next stage swapped = False # move the end point back by one, because # item at the end is in its rightful spot end = end-1 # from right to left, doing the same # comparison as in the previous stage for i in range(end-1, start-1,-1): if (a[i] > a[i+1]): a[i], a[i+1] = a[i+1], a[i] swapped = True # increase the starting point, because # the last stage would have moved the next # smallest number to its rightful spot. start = start+1 # Driver code to test abovea = [5, 1, 4, 2, 8, 0, 2]cocktailSort(a)print("Sorted array is:")for i in range(len(a)): print ("%d" %a[i]), Output: Sorted array is: 0 1 2 2 4 5 8 Time Complexity : O(n2) for worst and average case and O(n) for best case. Auxiliary Space: O(1) Please refer complete article on Cocktail Sort for more details! chandramauliguptach python sorting-exercises 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": "\n22 Jun, 2022" }, { "code": null, "e": 409, "s": 28, "text": "Cocktail Sort is a variation of Bubble sort. The Bubble sort algorithm always traverses elements from left and moves the largest element to its correct position in first iteration and second largest in second iteration and so on. Cocktail Sort traverses through a given array in both directions alternatively. Algorithm: Each iteration of the algorithm is broken up into 2 stages:" }, { "code": null, "e": 954, "s": 409, "text": "The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array.The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required." }, { "code": null, "e": 1259, "s": 954, "text": "The first stage loops through the array from left to right, just like the Bubble Sort. During the loop, adjacent items are compared and if value on the left is greater than the value on the right, then values are swapped. At the end of first iteration, largest number will reside at the end of the array." }, { "code": null, "e": 1500, "s": 1259, "text": "The second stage loops through the array in opposite direction- starting from the item just before the most recently sorted item, and moving back to the start of the array. Here also, adjacent items are compared and are swapped if required." }, { "code": null, "e": 1507, "s": 1500, "text": "Python" }, { "code": "# Python program for implementation of Cocktail Sort def cocktailSort(a): n = len(a) swapped = True start = 0 end = n-1 while (swapped==True): # reset the swapped flag on entering the loop, # because it might be true from a previous # iteration. swapped = False # loop from left to right same as the bubble # sort for i in range (start, end): if (a[i] > a[i+1]) : a[i], a[i+1]= a[i+1], a[i] swapped=True # if nothing moved, then array is sorted. if (swapped==False): break # otherwise, reset the swapped flag so that it # can be used in the next stage swapped = False # move the end point back by one, because # item at the end is in its rightful spot end = end-1 # from right to left, doing the same # comparison as in the previous stage for i in range(end-1, start-1,-1): if (a[i] > a[i+1]): a[i], a[i+1] = a[i+1], a[i] swapped = True # increase the starting point, because # the last stage would have moved the next # smallest number to its rightful spot. start = start+1 # Driver code to test abovea = [5, 1, 4, 2, 8, 0, 2]cocktailSort(a)print(\"Sorted array is:\")for i in range(len(a)): print (\"%d\" %a[i]),", "e": 2890, "s": 1507, "text": null }, { "code": null, "e": 2898, "s": 2890, "text": "Output:" }, { "code": null, "e": 2929, "s": 2898, "text": "Sorted array is:\n0 1 2 2 4 5 8" }, { "code": null, "e": 3004, "s": 2929, "text": "Time Complexity : O(n2) for worst and average case and O(n) for best case." }, { "code": null, "e": 3027, "s": 3004, "text": "Auxiliary Space: O(1) " }, { "code": null, "e": 3092, "s": 3027, "text": "Please refer complete article on Cocktail Sort for more details!" }, { "code": null, "e": 3112, "s": 3092, "text": "chandramauliguptach" }, { "code": null, "e": 3137, "s": 3112, "text": "python sorting-exercises" }, { "code": null, "e": 3153, "s": 3137, "text": "Python Programs" } ]
Runs Test of Randomness in Python
08 Jun, 2020 Random numbers are an imperative part of many systems, including simulations, cryptography and much more. So the ability to produce values randomly, with no apparent logic and predictability, becomes a prime function. Since computers cannot produce values which are completely random, algorithms, known as pseudorandom number generators (PRNG) are used to accomplish this task. The values produced by PRNGs are not truly random and depend on the initial value provided to the algorithm, known as the seed value. The property of a pseudorandom sequence being reproducible, given it’s seed value is essential for its application in simulations, such as the Monte Carlo Simulation, where the system might need to be tested on the same sequence more than once. Some of the most popular and highly used PRNGs are: Mersenne Twister: Used as the default random number generator in Python, R, Excel, Matlab, Ruby and many more popular software systems.Linear Congruential Generator: Used in C++ and Java Wichmann-Hill Generator: Used in Excel and was the default in Python 2.2 Park-Miller Generator Middle Square Weyl Sequence Mersenne Twister: Used as the default random number generator in Python, R, Excel, Matlab, Ruby and many more popular software systems. Linear Congruential Generator: Used in C++ and Java Wichmann-Hill Generator: Used in Excel and was the default in Python 2.2 Park-Miller Generator Middle Square Weyl Sequence To ensure that the values generated by the PRNG are as close to random as possible, several statistical tests including the Diehard tests, TestU01 series, Chi-Square test and the Runs test of Randomness are used. This article focuses on the Runs Test of Randomness. Runs test of randomness is a statistical test that is used to check the randomness in data. It is a nonparametric test and uses runs of data to decide whether the presented data is random or tends to follow a pattern. A run is defined as a series of increasing values or decreasing values. The number of increasing, or decreasing, values is the length of the run. The first step in the runs test is to count the number of runs in the data sequence. There are several ways to define runs, however, in all cases the formulation must produce a dichotomous sequence of values. In our case, the values above the median are treated as positive and values below the median as negative. A run is defined as a series of consecutive positive or negative values. The first step in applying this test is to formulate the null and alternate hypothesis. Hnull : The sequence was produced in a random manner Halt : The sequence was not produced in a random manner Calculate the test statistic, Z as : Where, R = The number of observed runs R' = The number of expected runs, given as SR = Standard Deviation of the number of runs With n1 and n2 = the number of positive and negative values in the series Compare the value of the calculated Z-statistic with Zcritical for a given level of confidence (Zcritical =1.96 for confidence level of 95%) . The null hypothesis is rejected i.e. the numbers are declared not to be random, if |Z|>Zcritical . Example: Python3 # simple code to implement Runs # test of randomnes import randomimport mathimport statistics def runsTest(l, l_median): runs, n1, n2 = 0, 0, 0 # Checking for start of new run for i in range(len(l)): # no. of runs if (l[i] >= l_median and l[i-1] < l_median) or \ (l[i] < l_median and l[i-1] >= l_median): runs += 1 # no. of positive values if(l[i]) >= l_median: n1 += 1 # no. of negative values else: n2 += 1 runs_exp = ((2*n1*n2)/(n1+n2))+1 stan_dev = math.sqrt((2*n1*n2*(2*n1*n2-n1-n2))/ \ (((n1+n2)**2)*(n1+n2-1))) z = (runs-runs_exp)/stan_dev return z # Making a list of 100 random numbers l = []for i in range(100): l.append(random.random()) l_median= statistics.median(l) Z = abs(runsTest(l, l_median)) print('Z-statistic= ', Z) Output: Z-statistic= 1.809160364503323 ML Statistical-test Machine Learning Python Machine Learning Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ML | Linear Regression Getting started with Machine Learning Search Algorithms in AI Support Vector Machine Algorithm Introduction to Recurrent Neural Network Iterate over a list in Python Python map() function Read JSON file using Python How to iterate through Excel rows in Python? Enumerate() in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 406, "s": 28, "text": "Random numbers are an imperative part of many systems, including simulations, cryptography and much more. So the ability to produce values randomly, with no apparent logic and predictability, becomes a prime function. Since computers cannot produce values which are completely random, algorithms, known as pseudorandom number generators (PRNG) are used to accomplish this task." }, { "code": null, "e": 786, "s": 406, "text": "The values produced by PRNGs are not truly random and depend on the initial value provided to the algorithm, known as the seed value. The property of a pseudorandom sequence being reproducible, given it’s seed value is essential for its application in simulations, such as the Monte Carlo Simulation, where the system might need to be tested on the same sequence more than once." }, { "code": null, "e": 838, "s": 786, "text": "Some of the most popular and highly used PRNGs are:" }, { "code": null, "e": 1149, "s": 838, "text": "Mersenne Twister: Used as the default random number generator in Python, R, Excel, Matlab, Ruby and many more popular software systems.Linear Congruential Generator: Used in C++ and Java Wichmann-Hill Generator: Used in Excel and was the default in Python 2.2 Park-Miller Generator Middle Square Weyl Sequence" }, { "code": null, "e": 1286, "s": 1149, "text": "Mersenne Twister: Used as the default random number generator in Python, R, Excel, Matlab, Ruby and many more popular software systems." }, { "code": null, "e": 1338, "s": 1286, "text": "Linear Congruential Generator: Used in C++ and Java" }, { "code": null, "e": 1412, "s": 1338, "text": " Wichmann-Hill Generator: Used in Excel and was the default in Python 2.2" }, { "code": null, "e": 1435, "s": 1412, "text": " Park-Miller Generator" }, { "code": null, "e": 1464, "s": 1435, "text": " Middle Square Weyl Sequence" }, { "code": null, "e": 1730, "s": 1464, "text": "To ensure that the values generated by the PRNG are as close to random as possible, several statistical tests including the Diehard tests, TestU01 series, Chi-Square test and the Runs test of Randomness are used. This article focuses on the Runs Test of Randomness." }, { "code": null, "e": 2094, "s": 1730, "text": "Runs test of randomness is a statistical test that is used to check the randomness in data. It is a nonparametric test and uses runs of data to decide whether the presented data is random or tends to follow a pattern. A run is defined as a series of increasing values or decreasing values. The number of increasing, or decreasing, values is the length of the run." }, { "code": null, "e": 2482, "s": 2094, "text": "The first step in the runs test is to count the number of runs in the data sequence. There are several ways to define runs, however, in all cases the formulation must produce a dichotomous sequence of values. In our case, the values above the median are treated as positive and values below the median as negative. A run is defined as a series of consecutive positive or negative values." }, { "code": null, "e": 2570, "s": 2482, "text": "The first step in applying this test is to formulate the null and alternate hypothesis." }, { "code": null, "e": 2640, "s": 2570, "text": " Hnull : The sequence was produced in a random manner" }, { "code": null, "e": 2714, "s": 2640, "text": " Halt : The sequence was not produced in a random manner" }, { "code": null, "e": 2763, "s": 2714, "text": "Calculate the test statistic, Z as : " }, { "code": null, "e": 2976, "s": 2763, "text": "\n\nWhere, \nR = The number of observed runs\nR' = The number of expected runs, given as\n\n\n\nSR = Standard Deviation of the number of runs\n\n\n\nWith n1 and n2 = the number of positive and \nnegative values in the series" }, { "code": null, "e": 3229, "s": 2976, "text": "Compare the value of the calculated Z-statistic with Zcritical for a given level of confidence (Zcritical =1.96 for confidence level of 95%) . The null hypothesis is rejected i.e. the numbers are declared not to be random, if |Z|>Zcritical . " }, { "code": null, "e": 3242, "s": 3229, "text": "Example: " }, { "code": null, "e": 3250, "s": 3242, "text": "Python3" }, { "code": "# simple code to implement Runs # test of randomnes import randomimport mathimport statistics def runsTest(l, l_median): runs, n1, n2 = 0, 0, 0 # Checking for start of new run for i in range(len(l)): # no. of runs if (l[i] >= l_median and l[i-1] < l_median) or \\ (l[i] < l_median and l[i-1] >= l_median): runs += 1 # no. of positive values if(l[i]) >= l_median: n1 += 1 # no. of negative values else: n2 += 1 runs_exp = ((2*n1*n2)/(n1+n2))+1 stan_dev = math.sqrt((2*n1*n2*(2*n1*n2-n1-n2))/ \\ (((n1+n2)**2)*(n1+n2-1))) z = (runs-runs_exp)/stan_dev return z # Making a list of 100 random numbers l = []for i in range(100): l.append(random.random()) l_median= statistics.median(l) Z = abs(runsTest(l, l_median)) print('Z-statistic= ', Z)", "e": 4187, "s": 3250, "text": null }, { "code": null, "e": 4195, "s": 4187, "text": "Output:" }, { "code": null, "e": 4227, "s": 4195, "text": "Z-statistic= 1.809160364503323" }, { "code": null, "e": 4247, "s": 4227, "text": "ML Statistical-test" }, { "code": null, "e": 4264, "s": 4247, "text": "Machine Learning" }, { "code": null, "e": 4271, "s": 4264, "text": "Python" }, { "code": null, "e": 4288, "s": 4271, "text": "Machine Learning" }, { "code": null, "e": 4386, "s": 4288, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4409, "s": 4386, "text": "ML | Linear Regression" }, { "code": null, "e": 4447, "s": 4409, "text": "Getting started with Machine Learning" }, { "code": null, "e": 4471, "s": 4447, "text": "Search Algorithms in AI" }, { "code": null, "e": 4504, "s": 4471, "text": "Support Vector Machine Algorithm" }, { "code": null, "e": 4545, "s": 4504, "text": "Introduction to Recurrent Neural Network" }, { "code": null, "e": 4575, "s": 4545, "text": "Iterate over a list in Python" }, { "code": null, "e": 4597, "s": 4575, "text": "Python map() function" }, { "code": null, "e": 4625, "s": 4597, "text": "Read JSON file using Python" }, { "code": null, "e": 4670, "s": 4625, "text": "How to iterate through Excel rows in Python?" } ]
MongoDB - Rename Operator ($rename) - GeeksforGeeks
10 May, 2020 MongoDB provides different types of field update operators to update the values of the fields of the documents and $rename operator is one of them. This operator is used to update the names of the fields with new names. The new name of the field should be different from the existing name of the field. $rename operator logically first performs an $unset operation on both the old name and the new name and then performs an $set operation with the new name. If the document contains the field with the new name, then this operator will remove that field and renames the specified field to the new name. This operator can also work with embedded/nested documents or arrays. In embedded/nested documents, this operator can rename the specified field as well as move the fields in and out of the embedded documents You can use this operator in methods like update(), findAndModify(), etc., according to your requirements. If the specified field for renaming is not available, then this operator will do nothing. Syntax: {$rename: {<field1>:<newName1>, <field2>:<newName2>, ... } } Here, newName is the new name and it must be different from the existing name of the field. To specify field in embedded/nested documents with the help of dot notation. In the following examples, we are working with: Database: GeeksforGeeksCollection: EmployeeDocument: three documents that contain the details of the employees in the form of field-value pairs. In this example, we are renaming the name of experienceYear field to experience in the employee’s document whose first name is Amu. db.Employee.update({"name.first": "Amu"}, {$rename: {"experienceYear":"experience"}}) In this example, we are renaming the name of the department field to unit in all the documents present in the Employee collection. db.Employee.updateMany({}, {$rename: {"department":"unit"}}) In this example, we are renaming the name of personalDetails.contactInfo to personalDetails.phoneNumber field inan embedded/nested document of the employee whose name is Sumit. db.Employee.update({"name.first": "Sumit"}, {$rename: {"personalDetails.contactInfo":"personalDetails.phoneNumber"}}) MongoDB MongoDB-operators MongoDB Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to connect MongoDB with ReactJS ? MongoDB - limit() Method MongoDB - FindOne() Method Create user and add role in MongoDB MongoDB Cursor MongoDB insertMany() Method - db.Collection.insertMany() MongoDB updateOne() Method - db.Collection.updateOne() MongoDB - Map Reduce MongoDB - sort() Method MongoDB updateMany() Method - db.Collection.updateMany()
[ { "code": null, "e": 24192, "s": 24164, "text": "\n10 May, 2020" }, { "code": null, "e": 24495, "s": 24192, "text": "MongoDB provides different types of field update operators to update the values of the fields of the documents and $rename operator is one of them. This operator is used to update the names of the fields with new names. The new name of the field should be different from the existing name of the field." }, { "code": null, "e": 24650, "s": 24495, "text": "$rename operator logically first performs an $unset operation on both the old name and the new name and then performs an $set operation with the new name." }, { "code": null, "e": 24795, "s": 24650, "text": "If the document contains the field with the new name, then this operator will remove that field and renames the specified field to the new name." }, { "code": null, "e": 25004, "s": 24795, "text": "This operator can also work with embedded/nested documents or arrays. In embedded/nested documents, this operator can rename the specified field as well as move the fields in and out of the embedded documents" }, { "code": null, "e": 25111, "s": 25004, "text": "You can use this operator in methods like update(), findAndModify(), etc., according to your requirements." }, { "code": null, "e": 25201, "s": 25111, "text": "If the specified field for renaming is not available, then this operator will do nothing." }, { "code": null, "e": 25209, "s": 25201, "text": "Syntax:" }, { "code": null, "e": 25270, "s": 25209, "text": "{$rename: {<field1>:<newName1>, <field2>:<newName2>, ... } }" }, { "code": null, "e": 25439, "s": 25270, "text": "Here, newName is the new name and it must be different from the existing name of the field. To specify field in embedded/nested documents with the help of dot notation." }, { "code": null, "e": 25487, "s": 25439, "text": "In the following examples, we are working with:" }, { "code": null, "e": 25632, "s": 25487, "text": "Database: GeeksforGeeksCollection: EmployeeDocument: three documents that contain the details of the employees in the form of field-value pairs." }, { "code": null, "e": 25764, "s": 25632, "text": "In this example, we are renaming the name of experienceYear field to experience in the employee’s document whose first name is Amu." }, { "code": "db.Employee.update({\"name.first\": \"Amu\"}, {$rename: {\"experienceYear\":\"experience\"}})", "e": 25869, "s": 25764, "text": null }, { "code": null, "e": 26000, "s": 25869, "text": "In this example, we are renaming the name of the department field to unit in all the documents present in the Employee collection." }, { "code": "db.Employee.updateMany({}, {$rename: {\"department\":\"unit\"}})", "e": 26061, "s": 26000, "text": null }, { "code": null, "e": 26238, "s": 26061, "text": "In this example, we are renaming the name of personalDetails.contactInfo to personalDetails.phoneNumber field inan embedded/nested document of the employee whose name is Sumit." }, { "code": "db.Employee.update({\"name.first\": \"Sumit\"}, {$rename: {\"personalDetails.contactInfo\":\"personalDetails.phoneNumber\"}})", "e": 26374, "s": 26238, "text": null }, { "code": null, "e": 26382, "s": 26374, "text": "MongoDB" }, { "code": null, "e": 26400, "s": 26382, "text": "MongoDB-operators" }, { "code": null, "e": 26408, "s": 26400, "text": "MongoDB" }, { "code": null, "e": 26506, "s": 26408, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26515, "s": 26506, "text": "Comments" }, { "code": null, "e": 26528, "s": 26515, "text": "Old Comments" }, { "code": null, "e": 26566, "s": 26528, "text": "How to connect MongoDB with ReactJS ?" }, { "code": null, "e": 26591, "s": 26566, "text": "MongoDB - limit() Method" }, { "code": null, "e": 26618, "s": 26591, "text": "MongoDB - FindOne() Method" }, { "code": null, "e": 26654, "s": 26618, "text": "Create user and add role in MongoDB" }, { "code": null, "e": 26669, "s": 26654, "text": "MongoDB Cursor" }, { "code": null, "e": 26726, "s": 26669, "text": "MongoDB insertMany() Method - db.Collection.insertMany()" }, { "code": null, "e": 26781, "s": 26726, "text": "MongoDB updateOne() Method - db.Collection.updateOne()" }, { "code": null, "e": 26802, "s": 26781, "text": "MongoDB - Map Reduce" }, { "code": null, "e": 26826, "s": 26802, "text": "MongoDB - sort() Method" } ]
Python Program for Rat in a Maze | Backtracking-2 - GeeksforGeeks
22 Apr, 2022 We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking. A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves. Following is an example maze. Gray blocks are dead ends (value = 0). Following is binary matrix representation of the above maze. {1, 0, 0, 0} {1, 1, 0, 1} {0, 1, 0, 0} {1, 1, 1, 1} Following is a maze with highlighted solution path. Following is the solution matrix (output of program) for the above input matrix. {1, 0, 0, 0} {1, 1, 0, 0} {0, 1, 0, 0} {0, 1, 1, 1} All entries in solution path are marked as 1. Python3 # Python3 program to solve Rat in a Maze# problem using backtracking # Maze sizeN = 4 # A utility function to print solution matrix soldef printSolution( sol ): for i in sol: for j in i: print(str(j) + " ", end ="") print("") # A utility function to check if x, y is valid# index for N * N Mazedef isSafe( maze, x, y ): if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: return True return False """ This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions. """def solveMaze( maze ): # Creating a 4 * 4 2-D list sol = [ [ 0 for j in range(4) ] for i in range(4) ] if solveMazeUtil(maze, 0, 0, sol) == False: print("Solution doesn't exist"); return False printSolution(sol) return True # A recursive utility function to solve Maze problemdef solveMazeUtil(maze, x, y, sol): # if (x, y is goal) return True if x == N - 1 and y == N - 1: sol[x][y] = 1 return True # Check if maze[x][y] is valid if isSafe(maze, x, y) == True: # mark x, y as part of solution path sol[x][y] = 1 # Move forward in x direction if solveMazeUtil(maze, x + 1, y, sol) == True: return True # If moving in x direction doesn't give solution # then Move down in y direction if solveMazeUtil(maze, x, y + 1, sol) == True: return True # If none of the above movements work then # BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0 return False # Driver program to test above functionif __name__ == "__main__": # Initialising the maze maze = [ [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1] ] solveMaze(maze) # This code is contributed by Shiv Shankar 1 0 0 0 1 1 0 0 0 1 0 0 0 1 1 1 Please refer complete article on Rat in a Maze | Backtracking-2 for more details! abhishek0719kadiyan as5853535 sweetyty sumitgumber28 Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python | Convert a list to dictionary Python | Convert string dictionary to dictionary Python Program for Binary Search (Recursive and Iterative) Python program to check whether a number is Prime or not Python Program for Fibonacci numbers Iterate over characters of a string in Python Python Program for factorial of a number Python | Convert a list into a tuple Python | Check if a variable is string Python | Convert set into a list
[ { "code": null, "e": 26741, "s": 26713, "text": "\n22 Apr, 2022" }, { "code": null, "e": 26903, "s": 26741, "text": "We have discussed Backtracking and Knight’s tour problem in Set 1. Let us discuss Rat in a Maze as another example problem that can be solved using Backtracking." }, { "code": null, "e": 27538, "s": 26903, "text": "A Maze is given as N*N binary matrix of blocks where source block is the upper left most block i.e., maze[0][0] and destination block is lower rightmost block i.e., maze[N-1][N-1]. A rat starts from source and has to reach the destination. The rat can move only in two directions: forward and down.In the maze matrix, 0 means the block is a dead end and 1 means the block can be used in the path from source to destination. Note that this is a simple version of the typical Maze problem. For example, a more complex version can be that the rat can move in 4 directions and a more complex version can be with a limited number of moves." }, { "code": null, "e": 27568, "s": 27538, "text": "Following is an example maze." }, { "code": null, "e": 27609, "s": 27568, "text": " Gray blocks are dead ends (value = 0). " }, { "code": null, "e": 27670, "s": 27609, "text": "Following is binary matrix representation of the above maze." }, { "code": null, "e": 27787, "s": 27670, "text": " {1, 0, 0, 0}\n {1, 1, 0, 1}\n {0, 1, 0, 0}\n {1, 1, 1, 1}\n" }, { "code": null, "e": 27839, "s": 27787, "text": "Following is a maze with highlighted solution path." }, { "code": null, "e": 27920, "s": 27839, "text": "Following is the solution matrix (output of program) for the above input matrix." }, { "code": null, "e": 28084, "s": 27920, "text": " {1, 0, 0, 0}\n {1, 1, 0, 0}\n {0, 1, 0, 0}\n {0, 1, 1, 1}\n All entries in solution path are marked as 1.\n" }, { "code": null, "e": 28092, "s": 28084, "text": "Python3" }, { "code": "# Python3 program to solve Rat in a Maze# problem using backtracking # Maze sizeN = 4 # A utility function to print solution matrix soldef printSolution( sol ): for i in sol: for j in i: print(str(j) + \" \", end =\"\") print(\"\") # A utility function to check if x, y is valid# index for N * N Mazedef isSafe( maze, x, y ): if x >= 0 and x < N and y >= 0 and y < N and maze[x][y] == 1: return True return False \"\"\" This function solves the Maze problem using Backtracking. It mainly uses solveMazeUtil() to solve the problem. It returns false if no path is possible, otherwise return true and prints the path in the form of 1s. Please note that there may be more than one solutions, this function prints one of the feasible solutions. \"\"\"def solveMaze( maze ): # Creating a 4 * 4 2-D list sol = [ [ 0 for j in range(4) ] for i in range(4) ] if solveMazeUtil(maze, 0, 0, sol) == False: print(\"Solution doesn't exist\"); return False printSolution(sol) return True # A recursive utility function to solve Maze problemdef solveMazeUtil(maze, x, y, sol): # if (x, y is goal) return True if x == N - 1 and y == N - 1: sol[x][y] = 1 return True # Check if maze[x][y] is valid if isSafe(maze, x, y) == True: # mark x, y as part of solution path sol[x][y] = 1 # Move forward in x direction if solveMazeUtil(maze, x + 1, y, sol) == True: return True # If moving in x direction doesn't give solution # then Move down in y direction if solveMazeUtil(maze, x, y + 1, sol) == True: return True # If none of the above movements work then # BACKTRACK: unmark x, y as part of solution path sol[x][y] = 0 return False # Driver program to test above functionif __name__ == \"__main__\": # Initialising the maze maze = [ [1, 0, 0, 0], [1, 1, 0, 1], [0, 1, 0, 0], [1, 1, 1, 1] ] solveMaze(maze) # This code is contributed by Shiv Shankar", "e": 30251, "s": 28092, "text": null }, { "code": null, "e": 30287, "s": 30251, "text": "1 0 0 0 \n1 1 0 0 \n0 1 0 0 \n0 1 1 1\n" }, { "code": null, "e": 30369, "s": 30287, "text": "Please refer complete article on Rat in a Maze | Backtracking-2 for more details!" }, { "code": null, "e": 30389, "s": 30369, "text": "abhishek0719kadiyan" }, { "code": null, "e": 30399, "s": 30389, "text": "as5853535" }, { "code": null, "e": 30408, "s": 30399, "text": "sweetyty" }, { "code": null, "e": 30422, "s": 30408, "text": "sumitgumber28" }, { "code": null, "e": 30438, "s": 30422, "text": "Python Programs" }, { "code": null, "e": 30536, "s": 30438, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30574, "s": 30536, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 30623, "s": 30574, "text": "Python | Convert string dictionary to dictionary" }, { "code": null, "e": 30682, "s": 30623, "text": "Python Program for Binary Search (Recursive and Iterative)" }, { "code": null, "e": 30739, "s": 30682, "text": "Python program to check whether a number is Prime or not" }, { "code": null, "e": 30776, "s": 30739, "text": "Python Program for Fibonacci numbers" }, { "code": null, "e": 30822, "s": 30776, "text": "Iterate over characters of a string in Python" }, { "code": null, "e": 30863, "s": 30822, "text": "Python Program for factorial of a number" }, { "code": null, "e": 30900, "s": 30863, "text": "Python | Convert a list into a tuple" }, { "code": null, "e": 30939, "s": 30900, "text": "Python | Check if a variable is string" } ]
Level order traversal | Practice | GeeksforGeeks
Given a binary tree, find its level order traversal. Level order traversal of a tree is breadth-first traversal for the tree. Example 1: Input: 1 / \ 3 2 Output:1 3 2 Example 2: Input: 10 / \ 20 30 / \ 40 60 Output:10 20 30 40 60 Your Task: You don't have to take any input. Complete the function levelOrder() that takes the root node as input parameter and returns a list of integers containing the level order traversal of the given Binary Tree. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 1 ≤ Number of nodes ≤ 105 1 ≤ Data of a node ≤ 105 0 superrhitik4584 hours ago // Jai Shri Ram class Solution{ public: //Function to return the level order traversal of a tree vector<int> v; void order(Node* node) { queue<Node*> q; q.push(node); while(q.empty()==false) { Node* curr=q.front(); v.push_back(curr->data);//cout<<curr->data<<" "; q.pop(); if(curr->left!=NULL) q.push(curr->left); if(curr->right!=NULL) q.push(curr->right); } } vector<int> levelOrder(Node* node) { //Your code herevector<int> levelorder(Node* root,vector<int> v) order(node); vector<int> vi=v; v.clear(); return vi; }}; 0 shubham2110199715 hours ago static ArrayList <Integer> levelOrder(Node node) { ArrayList <Integer>arr=new ArrayList <Integer>(); Queue<Node>q=new LinkedList<>(); q.add(node); while(q.isEmpty()==false){ Node curr=q.poll(); arr.add(curr.data); if(curr.left!=null) q.add(curr.left); if(curr.right!=null) q.add(curr.right); } return arr; } 0 pc5173051 day ago vector<int> levelOrder(Node* node) { //Your code here vector<int>v; queue<Node*>q; // v.push_back(node->data); q.push(node); while(!q.empty()) { Node *p=q.front(); q.pop(); v.push_back(p->data); if(p->left) { q.push(p->left); } if(p->right) { q.push(p->right); } }return v; }}; 0 ayush94602461255 days ago Easy CPP solution: class Solution{ public: //Function to return the level order traversal of a tree. vector<int> levelOrder(Node* node) { //Your code here vector<int>ans; queue<Node*>q; q.push(node); q.push(NULL); while(!q.empty()){ Node* curNode=q.front(); q.pop(); if(curNode==NULL){ if(q.empty()){ break; }else{ q.push(NULL); } }else{ ans.push_back(curNode->data); if(curNode->left){ q.push(curNode->left); }if(curNode->right){ q.push(curNode->right); } } }return ans; }}; 0 ishitaamod1 week ago class Solution { static ArrayList <Integer> levelOrder(Node node) { // Your code here Queue<Node> queue=new LinkedList<>(); ArrayList<Integer> list = new ArrayList<>(); if(node==null) return list; queue.offer(node); while(!queue.isEmpty()) { if(queue.peek().left!=null) { queue.offer(queue.peek().left); } if(queue.peek().right!=null) { queue.offer(queue.peek().right); } list.add(queue.poll().data); } return list; } } 0 sibajit1176be201 week ago static void lebelorder() { if(root == null) return; Queue<Node> queue= new LinkedList<Node>(); queue.add(root); while(!queue.isEmpty()) { Node temp=queue.poll(); System.out.print(temp.data+" "); if(temp.left!=null) { queue.add(temp.left); } if(temp.right!=null) { queue.add(temp.right); } } } 0 gulshan991 week ago class Solution { public: //Function to return the level order traversal of a tree. vector<int> levelOrder(Node* node) { //Your code here vector<int>ans; queue<Node*>q; if(node){ q.push(node); } while(!q.empty()){ for(int i = 0 ;i<q.size();i++){ Node*temp = q.front(); ans.push_back(temp->data); if(temp->left){ q.push(temp->left); } if(temp->right){ q.push(temp->right); } q.pop(); } } return ans; } }; 0 rohanmeher1642 weeks ago //Java Solution class Solution{ //Function to return the level order traversal of a tree. static ArrayList <Integer> levelOrder(Node node) { ArrayList<Integer> list=new ArrayList<Integer>(); if(node==null) return new ArrayList<Integer>(); Queue<Node> q=new LinkedList<Node>(); q.add(node); while(!q.isEmpty()) { int n=q.size(); for(int i=1;i<=n;i++) { Node t=q.poll(); list.add(t.data); if(t.left!=null) q.add(t.left); if(t.right!=null) q.add(t.right); } } return list; }} 0 rimpisaksham2 weeks ago best cpp soln . runtime 0.1 sec class Solution{ public: //Function to return the level order traversal of a tree. vector<int> levelOrder(Node* node) { //Your code here vector<int> ans; queue<Node*>q; q.push(node); q.push(NULL); while(!q.empty()) { Node* ptr=q.front(); q.pop(); if(ptr!=NULL){ ans.push_back(ptr->data); if(ptr->left!=NULL){ q.push(ptr->left); } if(ptr->right!=NULL){ q.push(ptr->right); } } if(!q.empty()) { if(q.front()==NULL){ q.pop(); if(q.size()>0){ q.push(NULL); } } } } return ans; }}; 0 dipanshusharma93132 weeks ago // java solution class Solution{ //Function to return the level order traversal of a tree. static ArrayList <Integer> levelOrder(Node node) { // Your code here ArrayList <Integer> di = new ArrayList <>(); if(node == null){ return di; } Queue<Node> bh = new LinkedList<>(); bh.add(node); while(!bh.isEmpty()){ Node currno = bh.remove(); di.add(currno.data); if(currno.left != null){ bh.add(currno.left); } if(currno.right != null){ bh.add(currno.right); } } return di; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 364, "s": 238, "text": "Given a binary tree, find its level order traversal.\nLevel order traversal of a tree is breadth-first traversal for the tree." }, { "code": null, "e": 376, "s": 364, "text": "\nExample 1:" }, { "code": null, "e": 421, "s": 376, "text": "Input:\n 1\n / \\ \n 3 2\nOutput:1 3 2\n" }, { "code": null, "e": 432, "s": 421, "text": "Example 2:" }, { "code": null, "e": 520, "s": 432, "text": "Input:\n 10\n / \\\n 20 30\n / \\\n 40 60\nOutput:10 20 30 40 60\n" }, { "code": null, "e": 739, "s": 520, "text": "\nYour Task:\nYou don't have to take any input. Complete the function levelOrder() that takes the root node as input parameter and returns a list of integers containing the level order traversal of the given Binary Tree." }, { "code": null, "e": 802, "s": 739, "text": "\nExpected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 867, "s": 802, "text": "\nConstraints:\n1 ≤ Number of nodes ≤ 105\n1 ≤ Data of a node ≤ 105" }, { "code": null, "e": 869, "s": 867, "text": "0" }, { "code": null, "e": 895, "s": 869, "text": "superrhitik4584 hours ago" }, { "code": null, "e": 953, "s": 895, "text": "// Jai Shri Ram" }, { "code": null, "e": 1615, "s": 953, "text": "class Solution{ public: //Function to return the level order traversal of a tree vector<int> v; void order(Node* node) { queue<Node*> q; q.push(node); while(q.empty()==false) { Node* curr=q.front(); v.push_back(curr->data);//cout<<curr->data<<\" \"; q.pop(); if(curr->left!=NULL) q.push(curr->left); if(curr->right!=NULL) q.push(curr->right); } } vector<int> levelOrder(Node* node) { //Your code herevector<int> levelorder(Node* root,vector<int> v) order(node); vector<int> vi=v; v.clear(); return vi; }};" }, { "code": null, "e": 1617, "s": 1615, "text": "0" }, { "code": null, "e": 1645, "s": 1617, "text": "shubham2110199715 hours ago" }, { "code": null, "e": 2064, "s": 1645, "text": "static ArrayList <Integer> levelOrder(Node node) \n {\n ArrayList <Integer>arr=new ArrayList <Integer>();\n Queue<Node>q=new LinkedList<>();\n q.add(node);\n while(q.isEmpty()==false){\n Node curr=q.poll();\n arr.add(curr.data);\n if(curr.left!=null)\n q.add(curr.left);\n if(curr.right!=null)\n q.add(curr.right);\n }\n return arr;\n }" }, { "code": null, "e": 2066, "s": 2064, "text": "0" }, { "code": null, "e": 2084, "s": 2066, "text": "pc5173051 day ago" }, { "code": null, "e": 2543, "s": 2084, "text": "vector<int> levelOrder(Node* node) { //Your code here vector<int>v; queue<Node*>q; // v.push_back(node->data); q.push(node); while(!q.empty()) { Node *p=q.front(); q.pop(); v.push_back(p->data); if(p->left) { q.push(p->left); } if(p->right) { q.push(p->right); } }return v; }};" }, { "code": null, "e": 2545, "s": 2543, "text": "0" }, { "code": null, "e": 2571, "s": 2545, "text": "ayush94602461255 days ago" }, { "code": null, "e": 2590, "s": 2571, "text": "Easy CPP solution:" }, { "code": null, "e": 3275, "s": 2592, "text": "class Solution{ public: //Function to return the level order traversal of a tree. vector<int> levelOrder(Node* node) { //Your code here vector<int>ans; queue<Node*>q; q.push(node); q.push(NULL); while(!q.empty()){ Node* curNode=q.front(); q.pop(); if(curNode==NULL){ if(q.empty()){ break; }else{ q.push(NULL); } }else{ ans.push_back(curNode->data); if(curNode->left){ q.push(curNode->left); }if(curNode->right){ q.push(curNode->right); } } }return ans; }};" }, { "code": null, "e": 3277, "s": 3275, "text": "0" }, { "code": null, "e": 3298, "s": 3277, "text": "ishitaamod1 week ago" }, { "code": null, "e": 3987, "s": 3298, "text": "class Solution\n{\n static ArrayList <Integer> levelOrder(Node node) \n {\n // Your code here\n Queue<Node> queue=new LinkedList<>();\n ArrayList<Integer> list = new ArrayList<>();\n \n if(node==null)\n return list;\n \n queue.offer(node);\n while(!queue.isEmpty())\n {\n if(queue.peek().left!=null)\n {\n queue.offer(queue.peek().left);\n }\n if(queue.peek().right!=null)\n {\n queue.offer(queue.peek().right);\n }\n \n list.add(queue.poll().data);\n }\n \n \n return list;\n \n }\n}" }, { "code": null, "e": 3989, "s": 3987, "text": "0" }, { "code": null, "e": 4015, "s": 3989, "text": "sibajit1176be201 week ago" }, { "code": null, "e": 4353, "s": 4015, "text": " static void lebelorder() { if(root == null) return; Queue<Node> queue= new LinkedList<Node>(); queue.add(root); while(!queue.isEmpty()) { Node temp=queue.poll(); System.out.print(temp.data+\" \"); if(temp.left!=null) { queue.add(temp.left); } if(temp.right!=null) { queue.add(temp.right); } } }" }, { "code": null, "e": 4355, "s": 4353, "text": "0" }, { "code": null, "e": 4375, "s": 4355, "text": "gulshan991 week ago" }, { "code": null, "e": 5028, "s": 4375, "text": "class Solution\n{\n public:\n //Function to return the level order traversal of a tree.\n vector<int> levelOrder(Node* node)\n {\n //Your code here\n vector<int>ans;\n queue<Node*>q;\n if(node){\n q.push(node);\n }\n while(!q.empty()){\n \n for(int i = 0 ;i<q.size();i++){\n Node*temp = q.front();\n ans.push_back(temp->data);\n if(temp->left){\n q.push(temp->left);\n }\n if(temp->right){\n q.push(temp->right);\n }\n q.pop();\n }\n \n }\n return ans;\n }\n};" }, { "code": null, "e": 5030, "s": 5028, "text": "0" }, { "code": null, "e": 5055, "s": 5030, "text": "rohanmeher1642 weeks ago" }, { "code": null, "e": 5071, "s": 5055, "text": "//Java Solution" }, { "code": null, "e": 5716, "s": 5073, "text": "class Solution{ //Function to return the level order traversal of a tree. static ArrayList <Integer> levelOrder(Node node) { ArrayList<Integer> list=new ArrayList<Integer>(); if(node==null) return new ArrayList<Integer>(); Queue<Node> q=new LinkedList<Node>(); q.add(node); while(!q.isEmpty()) { int n=q.size(); for(int i=1;i<=n;i++) { Node t=q.poll(); list.add(t.data); if(t.left!=null) q.add(t.left); if(t.right!=null) q.add(t.right); } } return list; }} " }, { "code": null, "e": 5718, "s": 5716, "text": "0" }, { "code": null, "e": 5742, "s": 5718, "text": "rimpisaksham2 weeks ago" }, { "code": null, "e": 5774, "s": 5742, "text": "best cpp soln . runtime 0.1 sec" }, { "code": null, "e": 6604, "s": 5774, "text": "class Solution{ public: //Function to return the level order traversal of a tree. vector<int> levelOrder(Node* node) { //Your code here vector<int> ans; queue<Node*>q; q.push(node); q.push(NULL); while(!q.empty()) { Node* ptr=q.front(); q.pop(); if(ptr!=NULL){ ans.push_back(ptr->data); if(ptr->left!=NULL){ q.push(ptr->left); } if(ptr->right!=NULL){ q.push(ptr->right); } } if(!q.empty()) { if(q.front()==NULL){ q.pop(); if(q.size()>0){ q.push(NULL); } } } } return ans; }};" }, { "code": null, "e": 6606, "s": 6604, "text": "0" }, { "code": null, "e": 6636, "s": 6606, "text": "dipanshusharma93132 weeks ago" }, { "code": null, "e": 6653, "s": 6636, "text": "// java solution" }, { "code": null, "e": 7310, "s": 6653, "text": "class Solution{ //Function to return the level order traversal of a tree. static ArrayList <Integer> levelOrder(Node node) { // Your code here ArrayList <Integer> di = new ArrayList <>(); if(node == null){ return di; } Queue<Node> bh = new LinkedList<>(); bh.add(node); while(!bh.isEmpty()){ Node currno = bh.remove(); di.add(currno.data); if(currno.left != null){ bh.add(currno.left); } if(currno.right != null){ bh.add(currno.right); } } return di; }}" }, { "code": null, "e": 7456, "s": 7310, "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": 7492, "s": 7456, "text": " Login to access your submissions. " }, { "code": null, "e": 7502, "s": 7492, "text": "\nProblem\n" }, { "code": null, "e": 7512, "s": 7502, "text": "\nContest\n" }, { "code": null, "e": 7575, "s": 7512, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7723, "s": 7575, "text": "Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7931, "s": 7723, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints." }, { "code": null, "e": 8037, "s": 7931, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Sort Java Vector in Descending Order Using Comparator - GeeksforGeeks
27 Jan, 2021 The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of the List interface. There are two types of Sorting technique: First is internal sorting i.e that uses predefined sorting method ascending order Arrays.sort() for Primitive class arrays and wrapper class arrays and Collections.sort() for collections both methods sort the elements in ascending order. The second technique is passing the comparator or implement the comparator interface in the class as the second argument in both methods and change the sorting the order according to the requirements. Comparator only works for wrapper class type arrays and for collections like vector, ArrayList, etc. Input: vector [4,3,2,6,7] Output: vector [2,3,4,6,7] Approaches to sort vector in descending order using Comparator: Implement the comparator interface in the class and change the natural ordering of the elementsDirectly call the new comparator in the second argument of the Collections.sort() method and change the ordering of the element Implement the comparator interface in the class and change the natural ordering of the elements Directly call the new comparator in the second argument of the Collections.sort() method and change the ordering of the element Example 1: Overriding the compare method inside the class that implements the Comparator class and then creating and passing the object of that class as a second parameter while calling the Collections.sort() method. Java // Java program to Sort Java Vector in// descending order using comparator import java.io.*;import java.util.*; // Implement comparator of the Integer classclass GFG implements Comparator<Integer>{ // Function to print the elements of the vector static void print(Vector<Integer> Numbers) { for (Integer number : Numbers) { // Printing the elements System.out.print(number + " "); } } public static void main(String[] args) { // Implementing the vector class Vector<Integer> elements = new Vector<>(); // Adding elements in the vector class elements.add(4); elements.add(3); elements.add(2); elements.add(6); elements.add(7); // Before sorting the elements System.out.print("Before sorting elements "); print(elements); System.out.println(); // Sorting the vector elements in descending // order Collections.sort(elements, new GFG()); System.out.print("After sorting elements "); // Printing the elements print(elements); } // Implementing compare function @Override public int compare(Integer o1, Integer o2) { // Changing the order of the elements return o2 - o1; }} Before sorting elements 4 3 2 6 7 After sorting elements 7 6 4 3 2 Example 2: Overriding the compare function at the time of calling the Collections.sort() method there itself. Java // Java program to Sort Java Vector in// descending order using comparator import java.io.*;import java.util.*; class GFG { // Function to print the elements of the vector static void print(Vector<Integer> Numbers) { for (Integer number : Numbers) { // Printing the elements System.out.print(number + " "); } } public static void main(String[] args) { // Implementing the vector class Vector<Integer> elements = new Vector<>(); // Adding elements in the vector class elements.add(4); elements.add(3); elements.add(2); elements.add(6); elements.add(7); // Before sorting the elements System.out.print("Before sorting elements "); print(elements); System.out.println(); // Sorting the vector elements in descending // order Collections.sort( elements, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { // Changing the order of the elements return o2 - o1; } }); System.out.print("After sorting elements "); // Printing the elements print(elements); }} Before sorting elements 4 3 2 6 7 After sorting elements 7 6 4 3 2 zack_aayush Java-Comparator Java-Vector 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. Stream In Java Interfaces in Java ArrayList in Java Stack Class in Java Singleton Class in Java Initializing a List in Java Convert a String to Character Array in Java Java Programming Examples Convert Double to Integer in Java Implementing a Linked List in Java using Class
[ { "code": null, "e": 25561, "s": 25533, "text": "\n27 Jan, 2021" }, { "code": null, "e": 25829, "s": 25561, "text": "The Vector class implements a growable array of objects. Vectors basically fall in legacy classes but now it is fully compatible with collections. It is found in java.util package and implements the List interface, so we can use all the methods of the List interface." }, { "code": null, "e": 25871, "s": 25829, "text": "There are two types of Sorting technique:" }, { "code": null, "e": 26110, "s": 25871, "text": "First is internal sorting i.e that uses predefined sorting method ascending order Arrays.sort() for Primitive class arrays and wrapper class arrays and Collections.sort() for collections both methods sort the elements in ascending order." }, { "code": null, "e": 26412, "s": 26110, "text": "The second technique is passing the comparator or implement the comparator interface in the class as the second argument in both methods and change the sorting the order according to the requirements. Comparator only works for wrapper class type arrays and for collections like vector, ArrayList, etc." }, { "code": null, "e": 26419, "s": 26412, "text": "Input:" }, { "code": null, "e": 26438, "s": 26419, "text": "vector [4,3,2,6,7]" }, { "code": null, "e": 26446, "s": 26438, "text": "Output:" }, { "code": null, "e": 26465, "s": 26446, "text": "vector [2,3,4,6,7]" }, { "code": null, "e": 26529, "s": 26465, "text": "Approaches to sort vector in descending order using Comparator:" }, { "code": null, "e": 26752, "s": 26529, "text": "Implement the comparator interface in the class and change the natural ordering of the elementsDirectly call the new comparator in the second argument of the Collections.sort() method and change the ordering of the element" }, { "code": null, "e": 26848, "s": 26752, "text": "Implement the comparator interface in the class and change the natural ordering of the elements" }, { "code": null, "e": 26976, "s": 26848, "text": "Directly call the new comparator in the second argument of the Collections.sort() method and change the ordering of the element" }, { "code": null, "e": 27193, "s": 26976, "text": "Example 1: Overriding the compare method inside the class that implements the Comparator class and then creating and passing the object of that class as a second parameter while calling the Collections.sort() method." }, { "code": null, "e": 27198, "s": 27193, "text": "Java" }, { "code": "// Java program to Sort Java Vector in// descending order using comparator import java.io.*;import java.util.*; // Implement comparator of the Integer classclass GFG implements Comparator<Integer>{ // Function to print the elements of the vector static void print(Vector<Integer> Numbers) { for (Integer number : Numbers) { // Printing the elements System.out.print(number + \" \"); } } public static void main(String[] args) { // Implementing the vector class Vector<Integer> elements = new Vector<>(); // Adding elements in the vector class elements.add(4); elements.add(3); elements.add(2); elements.add(6); elements.add(7); // Before sorting the elements System.out.print(\"Before sorting elements \"); print(elements); System.out.println(); // Sorting the vector elements in descending // order Collections.sort(elements, new GFG()); System.out.print(\"After sorting elements \"); // Printing the elements print(elements); } // Implementing compare function @Override public int compare(Integer o1, Integer o2) { // Changing the order of the elements return o2 - o1; }}", "e": 28492, "s": 27198, "text": null }, { "code": null, "e": 28563, "s": 28495, "text": "Before sorting elements 4 3 2 6 7 \nAfter sorting elements 7 6 4 3 2" }, { "code": null, "e": 28675, "s": 28565, "text": "Example 2: Overriding the compare function at the time of calling the Collections.sort() method there itself." }, { "code": null, "e": 28682, "s": 28677, "text": "Java" }, { "code": "// Java program to Sort Java Vector in// descending order using comparator import java.io.*;import java.util.*; class GFG { // Function to print the elements of the vector static void print(Vector<Integer> Numbers) { for (Integer number : Numbers) { // Printing the elements System.out.print(number + \" \"); } } public static void main(String[] args) { // Implementing the vector class Vector<Integer> elements = new Vector<>(); // Adding elements in the vector class elements.add(4); elements.add(3); elements.add(2); elements.add(6); elements.add(7); // Before sorting the elements System.out.print(\"Before sorting elements \"); print(elements); System.out.println(); // Sorting the vector elements in descending // order Collections.sort( elements, new Comparator<Integer>() { @Override public int compare(Integer o1, Integer o2) { // Changing the order of the elements return o2 - o1; } }); System.out.print(\"After sorting elements \"); // Printing the elements print(elements); }}", "e": 29976, "s": 28682, "text": null }, { "code": null, "e": 30047, "s": 29979, "text": "Before sorting elements 4 3 2 6 7 \nAfter sorting elements 7 6 4 3 2" }, { "code": null, "e": 30061, "s": 30049, "text": "zack_aayush" }, { "code": null, "e": 30077, "s": 30061, "text": "Java-Comparator" }, { "code": null, "e": 30089, "s": 30077, "text": "Java-Vector" }, { "code": null, "e": 30096, "s": 30089, "text": "Picked" }, { "code": null, "e": 30120, "s": 30096, "text": "Technical Scripter 2020" }, { "code": null, "e": 30125, "s": 30120, "text": "Java" }, { "code": null, "e": 30139, "s": 30125, "text": "Java Programs" }, { "code": null, "e": 30158, "s": 30139, "text": "Technical Scripter" }, { "code": null, "e": 30163, "s": 30158, "text": "Java" }, { "code": null, "e": 30261, "s": 30163, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30276, "s": 30261, "text": "Stream In Java" }, { "code": null, "e": 30295, "s": 30276, "text": "Interfaces in Java" }, { "code": null, "e": 30313, "s": 30295, "text": "ArrayList in Java" }, { "code": null, "e": 30333, "s": 30313, "text": "Stack Class in Java" }, { "code": null, "e": 30357, "s": 30333, "text": "Singleton Class in Java" }, { "code": null, "e": 30385, "s": 30357, "text": "Initializing a List in Java" }, { "code": null, "e": 30429, "s": 30385, "text": "Convert a String to Character Array in Java" }, { "code": null, "e": 30455, "s": 30429, "text": "Java Programming Examples" }, { "code": null, "e": 30489, "s": 30455, "text": "Convert Double to Integer in Java" } ]
CGI Programming in Python - GeeksforGeeks
08 Dec, 2020 What is CGI?Common Gateway Interface (also known as CGI) is not a kind of language but just a specification(set of rules) that helps to establish a dynamic interaction between a web application and the browser (or the client application). The CGI programs make possible communication between client and web servers. Whenever the client browser sends a request to the webserver the CGI programs send the output back to the web server based on the input provided by the client-server. CGI is the standard for programs to interface with HTTP servers.CGI programming is written dynamically generating webpages that respond to user input or webpages that interact with software on the server CGI is the standard for programs to interface with HTTP servers. CGI programming is written dynamically generating webpages that respond to user input or webpages that interact with software on the server Working of CGIWhen a request is made by the client-server to the webserver, the CGI uses external script files to handle such requests. These files could be written in any language. The main objective of these script files is to retrieve the data from the database quickly and more efficiently. These scripts convert the retrieved data into an Html format that sends the data to these web servers in Html formatted page. Install apache2 on your system can we will run ‘hello.py’ on host ‘127.0.0.1’It is recommended to have basic knowledge of HTML before trying this example.hello.py #!/usr/bin/python3# Importing the 'cgi' moduleimport cgi print("Content-type: text/html\r\n\r\n")print("<html><body>")print("<h1> Hello Program! </h1>")# Using the inbuilt methods form = cgi.FieldStorage()if form.getvalue("name"): name = form.getvalue("name") print("<h1>Hello" +name+"! Thanks for using my script!</h1><br />")if form.getvalue("happy"): print("<p> Yayy! I'm happy too! </p>")if form.getvalue("sad"): print("<p> Oh no! Why are you sad? </p>") # Using HTML input and forms methodprint("<form method='post' action='hello2.py'>")print("<p>Name: <input type='text' name='name' /></p>")print("<input type='checkbox' name='happy' /> Happy")print("<input type='checkbox' name='sad' /> Sad")print("<input type='submit' value='Submit' />")print("</form")print("</body></html>") Some advantages of CGI are discussed as below:1 They are portable and can work on almost any web server and operating system.2 They are language-independent.3 They are quite scalable programs in nature which means they can perform both simple and complex tasks.4 CGIs enhance dynamic communication in web applications.5They also aid in making businesses more profitable by decreasing development and maintenance costs. Some disadvantages of CGI are as below:1 The interpreter has to evaluate a CGI script every time the program is initiated this creates a lot of traffic as there are too many requests from the side of the client-server.2 Programming and designing of CGI programs is very complex and ambiguous.3 CGI programs may compromise server security as most of them are free and easily available making them quite vulnerable. This article is contributed by Harsh Wardhan Chaudhary (Intern). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. nidhi_biet gaurisharma360 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() Create a Pandas DataFrame from Lists Python program to convert a list to string Selecting rows in pandas DataFrame based on conditions Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24258, "s": 24230, "text": "\n08 Dec, 2020" }, { "code": null, "e": 24741, "s": 24258, "text": "What is CGI?Common Gateway Interface (also known as CGI) is not a kind of language but just a specification(set of rules) that helps to establish a dynamic interaction between a web application and the browser (or the client application). The CGI programs make possible communication between client and web servers. Whenever the client browser sends a request to the webserver the CGI programs send the output back to the web server based on the input provided by the client-server." }, { "code": null, "e": 24945, "s": 24741, "text": "CGI is the standard for programs to interface with HTTP servers.CGI programming is written dynamically generating webpages that respond to user input or webpages that interact with software on the server" }, { "code": null, "e": 25010, "s": 24945, "text": "CGI is the standard for programs to interface with HTTP servers." }, { "code": null, "e": 25150, "s": 25010, "text": "CGI programming is written dynamically generating webpages that respond to user input or webpages that interact with software on the server" }, { "code": null, "e": 25571, "s": 25150, "text": "Working of CGIWhen a request is made by the client-server to the webserver, the CGI uses external script files to handle such requests. These files could be written in any language. The main objective of these script files is to retrieve the data from the database quickly and more efficiently. These scripts convert the retrieved data into an Html format that sends the data to these web servers in Html formatted page." }, { "code": null, "e": 25734, "s": 25571, "text": "Install apache2 on your system can we will run ‘hello.py’ on host ‘127.0.0.1’It is recommended to have basic knowledge of HTML before trying this example.hello.py" }, { "code": "#!/usr/bin/python3# Importing the 'cgi' moduleimport cgi print(\"Content-type: text/html\\r\\n\\r\\n\")print(\"<html><body>\")print(\"<h1> Hello Program! </h1>\")# Using the inbuilt methods form = cgi.FieldStorage()if form.getvalue(\"name\"): name = form.getvalue(\"name\") print(\"<h1>Hello\" +name+\"! Thanks for using my script!</h1><br />\")if form.getvalue(\"happy\"): print(\"<p> Yayy! I'm happy too! </p>\")if form.getvalue(\"sad\"): print(\"<p> Oh no! Why are you sad? </p>\") # Using HTML input and forms methodprint(\"<form method='post' action='hello2.py'>\")print(\"<p>Name: <input type='text' name='name' /></p>\")print(\"<input type='checkbox' name='happy' /> Happy\")print(\"<input type='checkbox' name='sad' /> Sad\")print(\"<input type='submit' value='Submit' />\")print(\"</form\")print(\"</body></html>\")", "e": 26536, "s": 25734, "text": null }, { "code": null, "e": 26955, "s": 26536, "text": "Some advantages of CGI are discussed as below:1 They are portable and can work on almost any web server and operating system.2 They are language-independent.3 They are quite scalable programs in nature which means they can perform both simple and complex tasks.4 CGIs enhance dynamic communication in web applications.5They also aid in making businesses more profitable by decreasing development and maintenance costs." }, { "code": null, "e": 27369, "s": 26955, "text": "Some disadvantages of CGI are as below:1 The interpreter has to evaluate a CGI script every time the program is initiated this creates a lot of traffic as there are too many requests from the side of the client-server.2 Programming and designing of CGI programs is very complex and ambiguous.3 CGI programs may compromise server security as most of them are free and easily available making them quite vulnerable." }, { "code": null, "e": 27689, "s": 27369, "text": "This article is contributed by Harsh Wardhan Chaudhary (Intern). If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27700, "s": 27689, "text": "nidhi_biet" }, { "code": null, "e": 27715, "s": 27700, "text": "gaurisharma360" }, { "code": null, "e": 27722, "s": 27715, "text": "Python" }, { "code": null, "e": 27820, "s": 27722, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27829, "s": 27820, "text": "Comments" }, { "code": null, "e": 27842, "s": 27829, "text": "Old Comments" }, { "code": null, "e": 27860, "s": 27842, "text": "Python Dictionary" }, { "code": null, "e": 27895, "s": 27860, "text": "Read a file line by line in Python" }, { "code": null, "e": 27927, "s": 27895, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27969, "s": 27927, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27995, "s": 27969, "text": "Python String | replace()" }, { "code": null, "e": 28032, "s": 27995, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 28075, "s": 28032, "text": "Python program to convert a list to string" }, { "code": null, "e": 28130, "s": 28075, "text": "Selecting rows in pandas DataFrame based on conditions" }, { "code": null, "e": 28174, "s": 28130, "text": "Reading and Writing to text files in Python" } ]
AngularJS | ng-value Directive - GeeksforGeeks
05 Apr, 2019 The ng-value Directive in AngularJS is used to specify the value of an input element. It is supported by <input> and <select> elements. Syntax: <element ng-value="expression"> Content ... </element> Example 1: <!DOCTYPE html><html> <head> <title>ng-value Directive</title> <script src= "https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js"> </script> </head> <body ng-app="app" style="padding:20px"> <h1 style="color:green;">GeeksforGeeks</h1> <h2 style="">ng-value Directive</h2> <p>Choose one:</p> <div ng-controller="geek"> <div ng-repeat="l in sort"> <input type="radio" ng-model="my.fav" ng-value="l" name="Sort"> {{l}} </div> <pre>Selected choice is: {{my.fav}}</pre> </div> <script> var app = angular.module("app", []); app.controller('geek', ['$scope', function ($scope) { $scope.sort = ['Merge Sort', 'Quick Sort', 'Bubble Sort']; $scope.my = { fav: 'Merge Sort' }; }]); </script> </body></html> Output: AngularJS-Directives AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Angular PrimeNG Dropdown Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Angular 10 (blur) Event How to create module with Routing in Angular 9 ? How to setup 404 page in angular routing ? Top 10 Front End Developer Skills That You Need in 2022 Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 24718, "s": 24690, "text": "\n05 Apr, 2019" }, { "code": null, "e": 24854, "s": 24718, "text": "The ng-value Directive in AngularJS is used to specify the value of an input element. It is supported by <input> and <select> elements." }, { "code": null, "e": 24862, "s": 24854, "text": "Syntax:" }, { "code": null, "e": 24919, "s": 24862, "text": "<element ng-value=\"expression\"> Content ... </element> \n" }, { "code": null, "e": 24930, "s": 24919, "text": "Example 1:" }, { "code": "<!DOCTYPE html><html> <head> <title>ng-value Directive</title> <script src= \"https://ajax.googleapis.com/ajax/libs/angularjs/1.4.2/angular.min.js\"> </script> </head> <body ng-app=\"app\" style=\"padding:20px\"> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h2 style=\"\">ng-value Directive</h2> <p>Choose one:</p> <div ng-controller=\"geek\"> <div ng-repeat=\"l in sort\"> <input type=\"radio\" ng-model=\"my.fav\" ng-value=\"l\" name=\"Sort\"> {{l}} </div> <pre>Selected choice is: {{my.fav}}</pre> </div> <script> var app = angular.module(\"app\", []); app.controller('geek', ['$scope', function ($scope) { $scope.sort = ['Merge Sort', 'Quick Sort', 'Bubble Sort']; $scope.my = { fav: 'Merge Sort' }; }]); </script> </body></html>", "e": 25797, "s": 24930, "text": null }, { "code": null, "e": 25805, "s": 25797, "text": "Output:" }, { "code": null, "e": 25826, "s": 25805, "text": "AngularJS-Directives" }, { "code": null, "e": 25836, "s": 25826, "text": "AngularJS" }, { "code": null, "e": 25853, "s": 25836, "text": "Web Technologies" }, { "code": null, "e": 25951, "s": 25853, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25960, "s": 25951, "text": "Comments" }, { "code": null, "e": 25973, "s": 25960, "text": "Old Comments" }, { "code": null, "e": 26008, "s": 25973, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 26061, "s": 26008, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 26085, "s": 26061, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 26134, "s": 26085, "text": "How to create module with Routing in Angular 9 ?" }, { "code": null, "e": 26177, "s": 26134, "text": "How to setup 404 page in angular routing ?" }, { "code": null, "e": 26233, "s": 26177, "text": "Top 10 Front End Developer Skills That You Need in 2022" }, { "code": null, "e": 26266, "s": 26233, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 26328, "s": 26266, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 26371, "s": 26328, "text": "How to fetch data from an API in ReactJS ?" } ]
SQL | MERGE Statement - GeeksforGeeks
31 Jan, 2019 Prerequisite – INSERT, UPDATE, DELETE The MERGE command in SQL is actually a combination of three SQL statements: INSERT, UPDATE and DELETE. In simple words, the MERGE statement in SQL provides a convenient way to perform all these three operations together which can be very helpful when it comes to handle the large running databases. But unlike INSERT, UPDATE and DELETE statements MERGE statement requires a source table to perform these operations on the required table which is called as target table. Now we know that the MERGE in SQL requires two tables : one the target table on which we want to perform INSERT, UPDATE and DELETE operations, and the other one is source table which contains the new modified and correct data for target table and is actually compared with the actual target table in order to modify it. In other words, the MERGE statement in SQL basically merges data from a source result set to a target table based on a condition that is specified. The syntax of MERGE statement can be complex to understand at first but its very easy once you know what it means.So,not to get confused first let’s discuss some basics. Suppose you have two tables: source and target, now think if you want to make changes in the required target table with the help of provided source table which consists of latest details. When will you need to insert the data in the target table?Obviously when there is data in source table and not in target table i.e when data not matched with target table. When will you need to update the data?When the data in source table is matched with target table but any entry other than the primary key is not matched. When will you need to delete the data?When there is data in target table and not in source table i.e when data not matched with source table. Now, we know when to use INSERT, UPDATE and DELETE statements in case we want to use MERGE statement so there should be no problem for you understanding the syntax given below : //.....syntax of MERGE statement....// //you can use any other name in place of target MERGE target_table_name AS TARGET //you can use any other name in place of source USING source_table_name AS SOURCE ON condition (for matching source and target table) WHEN MATCHED (another condition for updation) //now use update statement syntax accordingly THEN UPDATE WHEN NOT MATCHED BY TARGET //now use insert statement syntax accordingly THEN INSERT WHEN NOT MATCHED BY SOURCE THEN DELETE; That’s all about the MERGE statement and its syntax. References –MERGE – docs.microsoftMERGE – docs.oracle This article is contributed by Dimpy Varshni If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. EmmaGersten SQL-Clauses-Operators DBMS SQL DBMS SQL Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between Clustered and Non-clustered index CTE in SQL SQL | Views SQL Interview Questions Third Normal Form (3NF) How to find Nth highest salary from a table SQL | ALTER (RENAME) CTE in SQL SQL | Views How to Update Multiple Columns in Single Update Statement in SQL?
[ { "code": null, "e": 23994, "s": 23966, "text": "\n31 Jan, 2019" }, { "code": null, "e": 24032, "s": 23994, "text": "Prerequisite – INSERT, UPDATE, DELETE" }, { "code": null, "e": 24502, "s": 24032, "text": "The MERGE command in SQL is actually a combination of three SQL statements: INSERT, UPDATE and DELETE. In simple words, the MERGE statement in SQL provides a convenient way to perform all these three operations together which can be very helpful when it comes to handle the large running databases. But unlike INSERT, UPDATE and DELETE statements MERGE statement requires a source table to perform these operations on the required table which is called as target table." }, { "code": null, "e": 24822, "s": 24502, "text": "Now we know that the MERGE in SQL requires two tables : one the target table on which we want to perform INSERT, UPDATE and DELETE operations, and the other one is source table which contains the new modified and correct data for target table and is actually compared with the actual target table in order to modify it." }, { "code": null, "e": 25328, "s": 24822, "text": "In other words, the MERGE statement in SQL basically merges data from a source result set to a target table based on a condition that is specified. The syntax of MERGE statement can be complex to understand at first but its very easy once you know what it means.So,not to get confused first let’s discuss some basics. Suppose you have two tables: source and target, now think if you want to make changes in the required target table with the help of provided source table which consists of latest details." }, { "code": null, "e": 25500, "s": 25328, "text": "When will you need to insert the data in the target table?Obviously when there is data in source table and not in target table i.e when data not matched with target table." }, { "code": null, "e": 25654, "s": 25500, "text": "When will you need to update the data?When the data in source table is matched with target table but any entry other than the primary key is not matched." }, { "code": null, "e": 25796, "s": 25654, "text": "When will you need to delete the data?When there is data in target table and not in source table i.e when data not matched with source table." }, { "code": null, "e": 25974, "s": 25796, "text": "Now, we know when to use INSERT, UPDATE and DELETE statements in case we want to use MERGE statement so there should be no problem for you understanding the syntax given below :" }, { "code": null, "e": 26519, "s": 25974, "text": "//.....syntax of MERGE statement....//\n\n//you can use any other name in place of target\nMERGE target_table_name AS TARGET \n\n//you can use any other name in place of source \nUSING source_table_name AS SOURCE \nON condition (for matching source and target table)\nWHEN MATCHED (another condition for updation)\n\n //now use update statement syntax accordingly\nTHEN UPDATE \nWHEN NOT MATCHED BY TARGET \n\n//now use insert statement syntax accordingly\nTHEN INSERT \nWHEN NOT MATCHED BY SOURCE \nTHEN DELETE;\n" }, { "code": null, "e": 26572, "s": 26519, "text": "That’s all about the MERGE statement and its syntax." }, { "code": null, "e": 26626, "s": 26572, "text": "References –MERGE – docs.microsoftMERGE – docs.oracle" }, { "code": null, "e": 26926, "s": 26626, "text": "This article is contributed by Dimpy Varshni If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27051, "s": 26926, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27063, "s": 27051, "text": "EmmaGersten" }, { "code": null, "e": 27085, "s": 27063, "text": "SQL-Clauses-Operators" }, { "code": null, "e": 27090, "s": 27085, "text": "DBMS" }, { "code": null, "e": 27094, "s": 27090, "text": "SQL" }, { "code": null, "e": 27099, "s": 27094, "text": "DBMS" }, { "code": null, "e": 27103, "s": 27099, "text": "SQL" }, { "code": null, "e": 27201, "s": 27103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27254, "s": 27201, "text": "Difference between Clustered and Non-clustered index" }, { "code": null, "e": 27265, "s": 27254, "text": "CTE in SQL" }, { "code": null, "e": 27277, "s": 27265, "text": "SQL | Views" }, { "code": null, "e": 27301, "s": 27277, "text": "SQL Interview Questions" }, { "code": null, "e": 27325, "s": 27301, "text": "Third Normal Form (3NF)" }, { "code": null, "e": 27369, "s": 27325, "text": "How to find Nth highest salary from a table" }, { "code": null, "e": 27390, "s": 27369, "text": "SQL | ALTER (RENAME)" }, { "code": null, "e": 27401, "s": 27390, "text": "CTE in SQL" }, { "code": null, "e": 27413, "s": 27401, "text": "SQL | Views" } ]
PHP - Mutex Functions
Static methods contained in the Mutex class can provide direct access to Posix Mutex functionality. Mutex { /* Methods */ final public static long create([ boolean $lock ] ) final public static boolean destroy( long $mutex ) final public static boolean lock( long $mutex ) final public static boolean trylock( long $mutex ) final public static boolean unlock( long $mutex [, boolean $destroy ] ) } Mutex class removed in pthreads v3. Mutex::create Function can create a Mutex. Mutex::destroy() Function can destroy a Mutex. Mutex::lock() Function can acquire Mutex. Mutex::trylock() Function can attempt to acquire the Mutex. Mutex::unlock() Function can release the Mutex. 45 Lectures 9 hours Malhar Lathkar 34 Lectures 4 hours Syed Raza 84 Lectures 5.5 hours Frahaan Hussain 17 Lectures 1 hours Nivedita Jain 100 Lectures 34 hours Azaz Patel 43 Lectures 5.5 hours Vijay Kumar Parvatha Reddy Print Add Notes Bookmark this page
[ { "code": null, "e": 2857, "s": 2757, "text": "Static methods contained in the Mutex class can provide direct access to Posix Mutex functionality." }, { "code": null, "e": 3173, "s": 2857, "text": "Mutex {\n /* Methods */\n final public static long create([ boolean $lock ] )\n final public static boolean destroy( long $mutex )\n final public static boolean lock( long $mutex )\n final public static boolean trylock( long $mutex )\n final public static boolean unlock( long $mutex [, boolean $destroy ] )\n}" }, { "code": null, "e": 3209, "s": 3173, "text": "Mutex class removed in pthreads v3." }, { "code": null, "e": 3223, "s": 3209, "text": "Mutex::create" }, { "code": null, "e": 3252, "s": 3223, "text": "Function can create a Mutex." }, { "code": null, "e": 3269, "s": 3252, "text": "Mutex::destroy()" }, { "code": null, "e": 3299, "s": 3269, "text": "Function can destroy a Mutex." }, { "code": null, "e": 3313, "s": 3299, "text": "Mutex::lock()" }, { "code": null, "e": 3341, "s": 3313, "text": "Function can acquire Mutex." }, { "code": null, "e": 3358, "s": 3341, "text": "Mutex::trylock()" }, { "code": null, "e": 3401, "s": 3358, "text": "Function can attempt to acquire the Mutex." }, { "code": null, "e": 3417, "s": 3401, "text": "Mutex::unlock()" }, { "code": null, "e": 3449, "s": 3417, "text": "Function can release the Mutex." }, { "code": null, "e": 3482, "s": 3449, "text": "\n 45 Lectures \n 9 hours \n" }, { "code": null, "e": 3498, "s": 3482, "text": " Malhar Lathkar" }, { "code": null, "e": 3531, "s": 3498, "text": "\n 34 Lectures \n 4 hours \n" }, { "code": null, "e": 3542, "s": 3531, "text": " Syed Raza" }, { "code": null, "e": 3577, "s": 3542, "text": "\n 84 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3594, "s": 3577, "text": " Frahaan Hussain" }, { "code": null, "e": 3627, "s": 3594, "text": "\n 17 Lectures \n 1 hours \n" }, { "code": null, "e": 3642, "s": 3627, "text": " Nivedita Jain" }, { "code": null, "e": 3677, "s": 3642, "text": "\n 100 Lectures \n 34 hours \n" }, { "code": null, "e": 3689, "s": 3677, "text": " Azaz Patel" }, { "code": null, "e": 3724, "s": 3689, "text": "\n 43 Lectures \n 5.5 hours \n" }, { "code": null, "e": 3752, "s": 3724, "text": " Vijay Kumar Parvatha Reddy" }, { "code": null, "e": 3759, "s": 3752, "text": " Print" }, { "code": null, "e": 3770, "s": 3759, "text": " Add Notes" } ]
Android - Styles and Themes
A style resource defines the format and look for a UI. A style can be applied to an individual View (from within a layout file) or to an entire Activity or application (from within the manifest file). A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension. You can define multiple styles per file using <style> tag but each style will have its name that uniquely identifies the style. Android style attributes are set using <item> tag as shown below − <?xml version="1.0" encoding="utf-8"?> <resources> <style name="CustomFontStyle"> <item name="android:layout_width">fill_parent</item> <item name="android:layout_height">wrap_content</item> <item name="android:capitalize">characters</item> <item name="android:typeface">monospace</item> <item name="android:textSize">12pt</item> <item name="android:textColor">#00FF00</item>/> </style> </resources> Once your style is defined, you can use it in your XML Layout file using style attribute as follows − <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <TextView android:id="@+id/text_id" style="@style/CustomFontStyle" android:text="@string/hello_world" /> </LinearLayout> To understand the concept related to Android Style, you can check Style Demo Example. Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add. To implement a custom theme create or edit MyAndroidApp/res/values/themes.xml and add the following − <resources> ... <style name="MyCustomTheme" parent="android:style/Theme"> <item name="android:textColorPrimary">#ffff0000</item> </style> ... </resources> In your AndroidManifest.xml apply the theme to the activities you want to style − <activity android:name="com.myapp.MyActivity" ... android:theme="@style/MyCustomTheme" /> Your new theme will be applied to your activity, and text is now bright red. Your color resource can then be applied to some theme attributes, such as the window background and the primary text color, by adding <item> elements to your custom theme. These attributes are defined in your styles.xml file. For example, to apply the custom color to the window background, add the following two <item> elements to your custom theme, defined in MyAndroidApp/res/values/styles.xml file − <resources> ... <style name="MyCustomTheme" ...> <item name="android:windowBackground">@color/my_custom_color</item> <item name="android:colorBackgroundCacheHint">@color/my_custom_color</item> </style> ... </resources> A nine-patch drawable is a special kind of image which can be scaled in width and height while maintaining its visual integrity. Nine-patches are the most common way to specify the appearance of Android buttons, though any drawable type can be used. Save this bitmap as /res/drawable/my_nine_patch.9.png Define a new style Apply the new button style to the buttonStyle attribute of your custom theme Define a new Style <resources> ... <style name="MyCustomButton" parent="android:Widget.Button"> <item name="android:background">@drawable/my_nine_patch</item> </style> ... </resources> Apply the theme <resources> ... <style name="MyCustomTheme" parent=...> ... <item name="android:buttonStyle">@style/MyCustomButton</item> </style> ... </resources> Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View. Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font. To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name. For example − <application android:theme="@style/CustomFontStyle"> But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. For example − <activity android:theme="@style/CustomFontStyle"> There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows − <style name="CustomTheme" parent="android:Theme.Light"> ... </style> To understand the concept related to Android Theme, you can check Theme Demo Example. The layout design can implementable based on them based colours, for example as following design is designed based on them colour(blue) Above layout has designed based on style.xml file,Which has placed at res/values/ <resource> <style name="AppTheme" parent="android:Theme.Material"> <item name ="android:color/primary">@color/primary</item> <item name ="android:color/primaryDark">@color/primary_dark</item> <item name ="android:colorAccent/primary">@color/accent</item> </style> <resource> The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with "@android:style/Theme.NoTitleBar". You can see the following source code for Android styles and themes − Android Styles (styles.xml) Android Styles (styles.xml) Android Themes (themes.xml) Android Themes (themes.xml) 46 Lectures 7.5 hours Aditya Dua 32 Lectures 3.5 hours Sharad Kumar 9 Lectures 1 hours Abhilash Nelson 14 Lectures 1.5 hours Abhilash Nelson 15 Lectures 1.5 hours Abhilash Nelson 10 Lectures 1 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 3808, "s": 3607, "text": "A style resource defines the format and look for a UI. A style can be applied to an individual View (from within a layout file) or to an entire Activity or application (from within the manifest file)." }, { "code": null, "e": 4126, "s": 3808, "text": "A style is defined in an XML resource that is separate from the XML that specifies the layout. This XML file resides under res/values/ directory of your project and will have <resources> as the root node which is mandatory for the style file. The name of the XML file is arbitrary, but it must use the .xml extension." }, { "code": null, "e": 4321, "s": 4126, "text": "You can define multiple styles per file using <style> tag but each style will have its name that uniquely identifies the style. Android style attributes are set using <item> tag as shown below −" }, { "code": null, "e": 4763, "s": 4321, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <style name=\"CustomFontStyle\">\n <item name=\"android:layout_width\">fill_parent</item>\n <item name=\"android:layout_height\">wrap_content</item>\n <item name=\"android:capitalize\">characters</item>\n <item name=\"android:typeface\">monospace</item>\n <item name=\"android:textSize\">12pt</item>\n <item name=\"android:textColor\">#00FF00</item>/> \n </style>\n</resources>" }, { "code": null, "e": 4865, "s": 4763, "text": "Once your style is defined, you can use it in your XML Layout file using style attribute as follows −" }, { "code": null, "e": 5234, "s": 4865, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"vertical\" >\n\n <TextView\n android:id=\"@+id/text_id\"\n style=\"@style/CustomFontStyle\"\n android:text=\"@string/hello_world\" />\n\n</LinearLayout>" }, { "code": null, "e": 5320, "s": 5234, "text": "To understand the concept related to Android Style, you can check Style Demo Example." }, { "code": null, "e": 5550, "s": 5320, "text": "Android supports style Inheritance in very much similar way as cascading style sheet in web design. You can use this to inherit properties from an existing style and then define only the properties that you want to change or add." }, { "code": null, "e": 5652, "s": 5550, "text": "To implement a custom theme create or edit MyAndroidApp/res/values/themes.xml and add the following −" }, { "code": null, "e": 5822, "s": 5652, "text": "<resources>\n ...\n <style name=\"MyCustomTheme\" parent=\"android:style/Theme\">\n <item name=\"android:textColorPrimary\">#ffff0000</item>\n </style>\n ...\n</resources>" }, { "code": null, "e": 5904, "s": 5822, "text": "In your AndroidManifest.xml apply the theme to the activities you want to style −" }, { "code": null, "e": 6006, "s": 5904, "text": "<activity\n android:name=\"com.myapp.MyActivity\"\n ...\n android:theme=\"@style/MyCustomTheme\"\n />" }, { "code": null, "e": 6083, "s": 6006, "text": "Your new theme will be applied to your activity, and text is now bright red." }, { "code": null, "e": 6487, "s": 6083, "text": "Your color resource can then be applied to some theme attributes, such as the window background and the primary text color, by adding <item> elements to your custom theme. These attributes are defined in your styles.xml file. For example, to apply the custom color to the window background, add the following two <item> elements to your custom theme, defined in MyAndroidApp/res/values/styles.xml file −" }, { "code": null, "e": 6730, "s": 6487, "text": "<resources>\n ...\n <style name=\"MyCustomTheme\" ...>\n <item name=\"android:windowBackground\">@color/my_custom_color</item>\n <item name=\"android:colorBackgroundCacheHint\">@color/my_custom_color</item>\n </style>\n ...\n</resources>" }, { "code": null, "e": 6980, "s": 6730, "text": "A nine-patch drawable is a special kind of image which can be scaled in width and height while maintaining its visual integrity. Nine-patches are the most common way to specify the appearance of Android buttons, though any drawable type can be used." }, { "code": null, "e": 7034, "s": 6980, "text": "Save this bitmap as /res/drawable/my_nine_patch.9.png" }, { "code": null, "e": 7053, "s": 7034, "text": "Define a new style" }, { "code": null, "e": 7130, "s": 7053, "text": "Apply the new button style to the buttonStyle attribute of your custom theme" }, { "code": null, "e": 7149, "s": 7130, "text": "Define a new Style" }, { "code": null, "e": 7339, "s": 7149, "text": "<resources>\n ...\n <style name=\"MyCustomButton\" parent=\"android:Widget.Button\">\n <item name=\"android:background\">@drawable/my_nine_patch</item>\n </style>\n ...\n</resources>" }, { "code": null, "e": 7355, "s": 7339, "text": "Apply the theme" }, { "code": null, "e": 7539, "s": 7355, "text": "<resources>\n ...\n <style name=\"MyCustomTheme\" parent=...>\n ...\n <item name=\"android:buttonStyle\">@style/MyCustomButton</item>\n </style>\n ...\n</resources>" }, { "code": null, "e": 7747, "s": 7539, "text": "Hope you understood the concept of Style, so now let's try to understand what is a Theme. A theme is nothing but an Android style applied to an entire Activity or application, rather than an individual View." }, { "code": null, "e": 8036, "s": 7747, "text": "Thus, when a style is applied as a theme, every View in the Activity or application will apply each style property that it supports. For example, you can apply the same CustomFontStyle style as a theme for an Activity and then all text inside that Activity will have green monospace font." }, { "code": null, "e": 8234, "s": 8036, "text": "To set a theme for all the activities of your application, open the AndroidManifest.xml file and edit the <application> tag to include the android:theme attribute with the style name. For example −" }, { "code": null, "e": 8288, "s": 8234, "text": "<application android:theme=\"@style/CustomFontStyle\">\n" }, { "code": null, "e": 8441, "s": 8288, "text": "But if you want a theme applied to just one Activity in your application, then add the android:theme attribute to the <activity> tag only. For example −" }, { "code": null, "e": 8492, "s": 8441, "text": "<activity android:theme=\"@style/CustomFontStyle\">\n" }, { "code": null, "e": 8625, "s": 8492, "text": "There are number of default themes defined by Android which you can use directly or inherit them using parent attribute as follows −" }, { "code": null, "e": 8697, "s": 8625, "text": "<style name=\"CustomTheme\" parent=\"android:Theme.Light\">\n ...\n</style>" }, { "code": null, "e": 8784, "s": 8697, "text": "To understand the concept related to Android Theme, you can check Theme Demo Example." }, { "code": null, "e": 8920, "s": 8784, "text": "The layout design can implementable based on them based colours, for example as following design is designed based on them colour(blue)" }, { "code": null, "e": 9003, "s": 8920, "text": " Above layout has designed based on style.xml file,Which has placed at res/values/" }, { "code": null, "e": 9304, "s": 9003, "text": "<resource>\n <style name=\"AppTheme\" parent=\"android:Theme.Material\">\t\n <item name =\"android:color/primary\">@color/primary</item>\n <item name =\"android:color/primaryDark\">@color/primary_dark</item>\n <item name =\"android:colorAccent/primary\">@color/accent</item>\n </style>\n<resource>\t" }, { "code": null, "e": 9736, "s": 9304, "text": "The Android platform provides a large collection of styles and themes that you can use in your applications. You can find a reference of all available styles in the R.style class. To use the styles listed here, replace all underscores in the style name with a period. For example, you can apply the Theme_NoTitleBar theme with \"@android:style/Theme.NoTitleBar\". You can see the following source code for Android styles and themes −" }, { "code": null, "e": 9764, "s": 9736, "text": "Android Styles (styles.xml)" }, { "code": null, "e": 9792, "s": 9764, "text": "Android Styles (styles.xml)" }, { "code": null, "e": 9820, "s": 9792, "text": "Android Themes (themes.xml)" }, { "code": null, "e": 9848, "s": 9820, "text": "Android Themes (themes.xml)" }, { "code": null, "e": 9883, "s": 9848, "text": "\n 46 Lectures \n 7.5 hours \n" }, { "code": null, "e": 9895, "s": 9883, "text": " Aditya Dua" }, { "code": null, "e": 9930, "s": 9895, "text": "\n 32 Lectures \n 3.5 hours \n" }, { "code": null, "e": 9944, "s": 9930, "text": " Sharad Kumar" }, { "code": null, "e": 9976, "s": 9944, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 9993, "s": 9976, "text": " Abhilash Nelson" }, { "code": null, "e": 10028, "s": 9993, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10045, "s": 10028, "text": " Abhilash Nelson" }, { "code": null, "e": 10080, "s": 10045, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 10097, "s": 10080, "text": " Abhilash Nelson" }, { "code": null, "e": 10130, "s": 10097, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 10147, "s": 10130, "text": " Abhilash Nelson" }, { "code": null, "e": 10154, "s": 10147, "text": " Print" }, { "code": null, "e": 10165, "s": 10154, "text": " Add Notes" } ]
Count numbers in a given range whose count of prime factors is a Prime Number - GeeksforGeeks
17 May, 2021 Given a 2D array Q[][] of size N * 2 representing queries of the form {L, R}. For each query, the task is to print the count of numbers in the range [L, R] with a count of prime factors equal to a prime number. Examples: Input: Q[][] = {{4, 8}, {30, 32}} Output: 3 2 Explanation: Query 1: Prime factors of 4 = {2, 2} and count of prime factors = 2 Prime factors of 5 = {5} and count of prime factors = 1 Prime factors of 6 = {2, 3} and count of prime factors = 2 Prime factors of 7 = {7} and count of prime factors = 1 Prime factors of 8 = {2, 2, 2} and count of prime factors = 3 Therefore, the total count of numbers in the range [4, 8] having count of prime factors is a prime number is 3. Query 2: Prime factors of 30 = {2, 3, 5} and count of prime factors = 3 Prime factors of 31 = {31} and count of prime factors = 1 Prime factors of 32 = {2, 2, 2, 2, 2} and count of prime factors = 5 Therefore, the total count of numbers in the range [4, 8] having count of prime factors is a prime number is 2. Input: Q[][] = {{7, 12}, {10, 99}} Output: 4 Naive Approach: The simplest approach to solve this problem is to traverse all the numbers in the range [L, R], and for each number, check if the count of prime factors of the number is a prime number or not. If found to be true, increment the counter by 1. After traversing, print the value of counter for each query. Time Complexity: O(|Q| * (max(arr[i][1] – arr[i][0] + 1)) * sqrt(max(arr[i][1])) Auxiliary space: O (1) Efficient Approach: To optimize the above approach the idea is to precompute the smallest prime factor of each number in the range [Li, Ri] using Sieve of Eratosthenes. Follow the steps below to solve the problem: Generate and store the smallest prime factor of each element using Sieve of Eratosthenes. Find the count of prime factors for each number in the range [Li, Ri] using the Sieve. For each number, check if the total count of prime factors is a prime number or not. If found to be true then increment the counter. Create a prefix sum array, say sum[], where sum[i] will store the sum of elements from the range [0, i] whose count of prime factors is a prime number. Finally, for each query, print the value sum[arr[i][1]] – sum[arr[i][0] – 1]. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std;#define MAX 1001 // Function to find the smallest prime factor// of all the numbers in range [0, MAX]vector<int> sieve(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] vector<int> spf(MAX); // No smallest prime factor of // 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for (int i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for (int i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for (int i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers whose // smallest prime factor is i for (int j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numint countFactors(vector<int>& spf, int num){ // Stores count of // prime factor of num int count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numbervector<int> precalculateSum(vector<int>& spf){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number vector<int> sum(MAX); // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for (int i = 1; i < MAX; i++) { // Stores count of prime factor of i int prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver Codeint main(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] vector<int> spf = sieve(); // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number vector<int> sum = precalculateSum(spf); int Q[][2] = { { 4, 8 }, { 30, 32 } }; // int N = sizeof(Q) / sizeof(Q[0]); for (int i = 0; i < 2; i++) { cout << (sum[Q[i][1]] - sum[Q[i][0] - 1]) << " "; } return 0;} // Java program to implement// the above approachimport java.util.*; class GFG{ public static int MAX = 1001; // Function to find the smallest prime factor// of all the numbers in range [0, MAX]public static int[] sieve(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] int spf[] = new int[MAX]; // No smallest prime factor of // 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for(int i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for(int i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for(int i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers whose // smallest prime factor is i for(int j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numpublic static int countFactors(int spf[], int num){ // Stores count of // prime factor of num int count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numberpublic static int[] precalculateSum(int spf[]){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number int sum[] = new int[MAX]; // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for(int i = 1; i < MAX; i++) { // Stores count of prime factor of i int prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver codepublic static void main(String[] args){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] int spf[] = sieve(); // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number int sum[] = precalculateSum(spf); int Q[][] = { { 4, 8 }, { 30, 32 } }; // int N = sizeof(Q) / sizeof(Q[0]); for(int i = 0; i < 2; i++) { System.out.print((sum[Q[i][1]] - sum[Q[i][0] - 1]) + " "); }}} // This code is contributed by divyeshrabadiya07 # Python3 program to implement# the above approachMAX = 1001 # Function to find the smallest# prime factor of all the numbers# in range [0, MAX]def sieve(): # Stores smallest prime factor of all # the numbers in the range [0, MAX] global MAX spf = [0] * MAX # No smallest prime factor of # 0 and 1 exists spf[0] = spf[1] = -1 # Traverse all the numbers # in the range [1, MAX] for i in range(2, MAX): # Update spf[i] spf[i] = i # Update all the numbers whose # smallest prime factor is 2 for i in range(4, MAX, 2): spf[i] = 2 # Traverse all the numbers in # the range [1, sqrt(MAX)] for i in range(3, MAX): # Check if i is a prime number if (spf[i] == i): # Update all the numbers whose # smallest prime factor is i for j in range(i * i, MAX): # Check if j is # a prime number if (spf[j] == j): spf[j] = i return spf # Function to find count of# prime factor of numdef countFactors(spf, num): # Stores count of # prime factor of num count = 0 # Calculate count of # prime factor while (num > 1): # Update count count += 1 # Update num num = num // spf[num] return count # Function to precalculate the count of# numbers in the range [0, i] whose count# of prime factors is a prime numberdef precalculateSum(spf): # Stores the sum of all the numbers # in the range[0, i] count of # prime factor is a prime number sum = [0] * MAX # Traverse all the numbers in # the range [1, MAX] for i in range(1, MAX): # Stores count of prime factor of i prime_factor = countFactors(spf, i) # If count of prime factor is # a prime number if (spf[prime_factor] == prime_factor): # Update sum[i] sum[i] = sum[i - 1] + 1 else: # Update sum[i] sum[i] = sum[i - 1] return sum # Driver codeif __name__ == '__main__': # Stores smallest prime factor of all # the numbers in the range [0, MAX] spf = sieve() # Stores the sum of all the numbers # in the range[0, i] count of # prime factor is a prime number sum = precalculateSum(spf) Q = [ [ 4, 8 ], [ 30, 32 ] ] sum[Q[0][1]] += 1 # N = sizeof(Q) / sizeof(Q[0]); for i in range(0, 2): print((sum[Q[i][1]] - sum[Q[i][0]]), end = " ") # This code is contributed by Princi Singh // C# program to implement// the above approachusing System;class GFG{ public static int MAX = 1001; // Function to find the smallest// prime factor of all the numbers// in range [0, MAX]public static int[] sieve(){ // Stores smallest prime factor // of all the numbers in the // range [0, MAX] int []spf = new int[MAX]; // No smallest prime factor // of 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for(int i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for(int i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for(int i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers // whose smallest prime // factor is i for(int j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numpublic static int countFactors(int []spf, int num){ // Stores count of // prime factor of num int count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numberpublic static int[] precalculateSum(int []spf){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number int []sum = new int[MAX]; // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for(int i = 1; i < MAX; i++) { // Stores count of prime factor of i int prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver codepublic static void Main(String[] args){ // Stores smallest prime factor // of all the numbers in the // range [0, MAX] int []spf = sieve(); // Stores the sum of all the // numbers in the range[0, i] // count of prime factor is a // prime number int []sum = precalculateSum(spf); int [,]Q = {{4, 8}, {30, 32}}; // int N = sizeof(Q) / sizeof(Q[0]); for(int i = 0; i < 2; i++) { Console.Write((sum[Q[i, 1]] - sum[Q[i, 0] - 1]) + " "); }}} // This code is contributed by shikhasingrajput <script> // Javascript program to implement// the above approach let MAX = 1001 // Function to find the smallest prime factor// of all the numbers in range [0, MAX]function sieve(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] let spf = new Array(MAX); // No smallest prime factor of // 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for (let i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for (let i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for (let i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers whose // smallest prime factor is i for (let j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numfunction countFactors(spf, num){ // Stores count of // prime factor of num let count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numberfunction precalculateSum(spf){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number let sum = new Array(MAX); // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for (let i = 1; i < MAX; i++) { // Stores count of prime factor of i let prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver Code // Stores smallest prime factor of all // the numbers in the range [0, MAX] let spf = sieve(); // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number let sum = precalculateSum(spf); let Q = [ [ 4, 8 ], [ 30, 32 ] ]; // let N = sizeof(Q) / sizeof(Q[0]); for (let i = 0; i < 2; i++) { document.write((sum[Q[i][1]] - sum[Q[i][0] - 1]) + " "); } // This code is contributed by gfgking </script> 3 2 Time Complexity: O(|Q| + (MAX *log(log(MAX))))Auxiliary Space: O(MAX) divyeshrabadiya07 shikhasingrajput princi singh gfgking array-range-queries Prime Number prime-factor sieve Mathematical Searching Searching Mathematical Prime Number sieve Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Modulo Operator (%) in C/C++ with Examples Merge two sorted arrays Program to find sum of elements in a given array Program for factorial of a number Operators in C / C++ Binary Search Linear Search Maximum and minimum of an array using minimum number of comparisons Find the Missing Number K'th Smallest/Largest Element in Unsorted Array | Set 1
[ { "code": null, "e": 24894, "s": 24866, "text": "\n17 May, 2021" }, { "code": null, "e": 25105, "s": 24894, "text": "Given a 2D array Q[][] of size N * 2 representing queries of the form {L, R}. For each query, the task is to print the count of numbers in the range [L, R] with a count of prime factors equal to a prime number." }, { "code": null, "e": 25115, "s": 25105, "text": "Examples:" }, { "code": null, "e": 25898, "s": 25115, "text": "Input: Q[][] = {{4, 8}, {30, 32}} Output: 3 2 Explanation: Query 1: Prime factors of 4 = {2, 2} and count of prime factors = 2 Prime factors of 5 = {5} and count of prime factors = 1 Prime factors of 6 = {2, 3} and count of prime factors = 2 Prime factors of 7 = {7} and count of prime factors = 1 Prime factors of 8 = {2, 2, 2} and count of prime factors = 3 Therefore, the total count of numbers in the range [4, 8] having count of prime factors is a prime number is 3. Query 2: Prime factors of 30 = {2, 3, 5} and count of prime factors = 3 Prime factors of 31 = {31} and count of prime factors = 1 Prime factors of 32 = {2, 2, 2, 2, 2} and count of prime factors = 5 Therefore, the total count of numbers in the range [4, 8] having count of prime factors is a prime number is 2." }, { "code": null, "e": 25943, "s": 25898, "text": "Input: Q[][] = {{7, 12}, {10, 99}} Output: 4" }, { "code": null, "e": 26263, "s": 25943, "text": "Naive Approach: The simplest approach to solve this problem is to traverse all the numbers in the range [L, R], and for each number, check if the count of prime factors of the number is a prime number or not. If found to be true, increment the counter by 1. After traversing, print the value of counter for each query. " }, { "code": null, "e": 26367, "s": 26263, "text": "Time Complexity: O(|Q| * (max(arr[i][1] – arr[i][0] + 1)) * sqrt(max(arr[i][1])) Auxiliary space: O (1)" }, { "code": null, "e": 26581, "s": 26367, "text": "Efficient Approach: To optimize the above approach the idea is to precompute the smallest prime factor of each number in the range [Li, Ri] using Sieve of Eratosthenes. Follow the steps below to solve the problem:" }, { "code": null, "e": 26671, "s": 26581, "text": "Generate and store the smallest prime factor of each element using Sieve of Eratosthenes." }, { "code": null, "e": 26758, "s": 26671, "text": "Find the count of prime factors for each number in the range [Li, Ri] using the Sieve." }, { "code": null, "e": 26891, "s": 26758, "text": "For each number, check if the total count of prime factors is a prime number or not. If found to be true then increment the counter." }, { "code": null, "e": 27043, "s": 26891, "text": "Create a prefix sum array, say sum[], where sum[i] will store the sum of elements from the range [0, i] whose count of prime factors is a prime number." }, { "code": null, "e": 27121, "s": 27043, "text": "Finally, for each query, print the value sum[arr[i][1]] – sum[arr[i][0] – 1]." }, { "code": null, "e": 27172, "s": 27121, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 27176, "s": 27172, "text": "C++" }, { "code": null, "e": 27181, "s": 27176, "text": "Java" }, { "code": null, "e": 27189, "s": 27181, "text": "Python3" }, { "code": null, "e": 27192, "s": 27189, "text": "C#" }, { "code": null, "e": 27203, "s": 27192, "text": "Javascript" }, { "code": "// C++ program to implement// the above approach#include <bits/stdc++.h>using namespace std;#define MAX 1001 // Function to find the smallest prime factor// of all the numbers in range [0, MAX]vector<int> sieve(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] vector<int> spf(MAX); // No smallest prime factor of // 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for (int i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for (int i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for (int i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers whose // smallest prime factor is i for (int j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numint countFactors(vector<int>& spf, int num){ // Stores count of // prime factor of num int count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numbervector<int> precalculateSum(vector<int>& spf){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number vector<int> sum(MAX); // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for (int i = 1; i < MAX; i++) { // Stores count of prime factor of i int prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver Codeint main(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] vector<int> spf = sieve(); // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number vector<int> sum = precalculateSum(spf); int Q[][2] = { { 4, 8 }, { 30, 32 } }; // int N = sizeof(Q) / sizeof(Q[0]); for (int i = 0; i < 2; i++) { cout << (sum[Q[i][1]] - sum[Q[i][0] - 1]) << \" \"; } return 0;}", "e": 30069, "s": 27203, "text": null }, { "code": "// Java program to implement// the above approachimport java.util.*; class GFG{ public static int MAX = 1001; // Function to find the smallest prime factor// of all the numbers in range [0, MAX]public static int[] sieve(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] int spf[] = new int[MAX]; // No smallest prime factor of // 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for(int i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for(int i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for(int i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers whose // smallest prime factor is i for(int j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numpublic static int countFactors(int spf[], int num){ // Stores count of // prime factor of num int count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numberpublic static int[] precalculateSum(int spf[]){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number int sum[] = new int[MAX]; // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for(int i = 1; i < MAX; i++) { // Stores count of prime factor of i int prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver codepublic static void main(String[] args){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] int spf[] = sieve(); // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number int sum[] = precalculateSum(spf); int Q[][] = { { 4, 8 }, { 30, 32 } }; // int N = sizeof(Q) / sizeof(Q[0]); for(int i = 0; i < 2; i++) { System.out.print((sum[Q[i][1]] - sum[Q[i][0] - 1]) + \" \"); }}} // This code is contributed by divyeshrabadiya07", "e": 33201, "s": 30069, "text": null }, { "code": "# Python3 program to implement# the above approachMAX = 1001 # Function to find the smallest# prime factor of all the numbers# in range [0, MAX]def sieve(): # Stores smallest prime factor of all # the numbers in the range [0, MAX] global MAX spf = [0] * MAX # No smallest prime factor of # 0 and 1 exists spf[0] = spf[1] = -1 # Traverse all the numbers # in the range [1, MAX] for i in range(2, MAX): # Update spf[i] spf[i] = i # Update all the numbers whose # smallest prime factor is 2 for i in range(4, MAX, 2): spf[i] = 2 # Traverse all the numbers in # the range [1, sqrt(MAX)] for i in range(3, MAX): # Check if i is a prime number if (spf[i] == i): # Update all the numbers whose # smallest prime factor is i for j in range(i * i, MAX): # Check if j is # a prime number if (spf[j] == j): spf[j] = i return spf # Function to find count of# prime factor of numdef countFactors(spf, num): # Stores count of # prime factor of num count = 0 # Calculate count of # prime factor while (num > 1): # Update count count += 1 # Update num num = num // spf[num] return count # Function to precalculate the count of# numbers in the range [0, i] whose count# of prime factors is a prime numberdef precalculateSum(spf): # Stores the sum of all the numbers # in the range[0, i] count of # prime factor is a prime number sum = [0] * MAX # Traverse all the numbers in # the range [1, MAX] for i in range(1, MAX): # Stores count of prime factor of i prime_factor = countFactors(spf, i) # If count of prime factor is # a prime number if (spf[prime_factor] == prime_factor): # Update sum[i] sum[i] = sum[i - 1] + 1 else: # Update sum[i] sum[i] = sum[i - 1] return sum # Driver codeif __name__ == '__main__': # Stores smallest prime factor of all # the numbers in the range [0, MAX] spf = sieve() # Stores the sum of all the numbers # in the range[0, i] count of # prime factor is a prime number sum = precalculateSum(spf) Q = [ [ 4, 8 ], [ 30, 32 ] ] sum[Q[0][1]] += 1 # N = sizeof(Q) / sizeof(Q[0]); for i in range(0, 2): print((sum[Q[i][1]] - sum[Q[i][0]]), end = \" \") # This code is contributed by Princi Singh", "e": 35799, "s": 33201, "text": null }, { "code": "// C# program to implement// the above approachusing System;class GFG{ public static int MAX = 1001; // Function to find the smallest// prime factor of all the numbers// in range [0, MAX]public static int[] sieve(){ // Stores smallest prime factor // of all the numbers in the // range [0, MAX] int []spf = new int[MAX]; // No smallest prime factor // of 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for(int i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for(int i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for(int i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers // whose smallest prime // factor is i for(int j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numpublic static int countFactors(int []spf, int num){ // Stores count of // prime factor of num int count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numberpublic static int[] precalculateSum(int []spf){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number int []sum = new int[MAX]; // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for(int i = 1; i < MAX; i++) { // Stores count of prime factor of i int prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver codepublic static void Main(String[] args){ // Stores smallest prime factor // of all the numbers in the // range [0, MAX] int []spf = sieve(); // Stores the sum of all the // numbers in the range[0, i] // count of prime factor is a // prime number int []sum = precalculateSum(spf); int [,]Q = {{4, 8}, {30, 32}}; // int N = sizeof(Q) / sizeof(Q[0]); for(int i = 0; i < 2; i++) { Console.Write((sum[Q[i, 1]] - sum[Q[i, 0] - 1]) + \" \"); }}} // This code is contributed by shikhasingrajput", "e": 38564, "s": 35799, "text": null }, { "code": "<script> // Javascript program to implement// the above approach let MAX = 1001 // Function to find the smallest prime factor// of all the numbers in range [0, MAX]function sieve(){ // Stores smallest prime factor of all // the numbers in the range [0, MAX] let spf = new Array(MAX); // No smallest prime factor of // 0 and 1 exists spf[0] = spf[1] = -1; // Traverse all the numbers // in the range [1, MAX] for (let i = 2; i < MAX; i++) { // Update spf[i] spf[i] = i; } // Update all the numbers whose // smallest prime factor is 2 for (let i = 4; i < MAX; i = i + 2) { spf[i] = 2; } // Traverse all the numbers in // the range [1, sqrt(MAX)] for (let i = 3; i * i < MAX; i++) { // Check if i is a prime number if (spf[i] == i) { // Update all the numbers whose // smallest prime factor is i for (let j = i * i; j < MAX; j = j + i) { // Check if j is // a prime number if (spf[j] == j) { spf[j] = i; } } } } return spf;} // Function to find count of// prime factor of numfunction countFactors(spf, num){ // Stores count of // prime factor of num let count = 0; // Calculate count of // prime factor while (num > 1) { // Update count count++; // Update num num = num / spf[num]; } return count;} // Function to precalculate the count of// numbers in the range [0, i] whose count// of prime factors is a prime numberfunction precalculateSum(spf){ // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number let sum = new Array(MAX); // Update sum[0] sum[0] = 0; // Traverse all the numbers in // the range [1, MAX] for (let i = 1; i < MAX; i++) { // Stores count of prime factor of i let prime_factor = countFactors(spf, i); // If count of prime factor is // a prime number if (spf[prime_factor] == prime_factor) { // Update sum[i] sum[i] = sum[i - 1] + 1; } else { // Update sum[i] sum[i] = sum[i - 1]; } } return sum;} // Driver Code // Stores smallest prime factor of all // the numbers in the range [0, MAX] let spf = sieve(); // Stores the sum of all the numbers // in the range[0, i] count of // prime factor is a prime number let sum = precalculateSum(spf); let Q = [ [ 4, 8 ], [ 30, 32 ] ]; // let N = sizeof(Q) / sizeof(Q[0]); for (let i = 0; i < 2; i++) { document.write((sum[Q[i][1]] - sum[Q[i][0] - 1]) + \" \"); } // This code is contributed by gfgking </script>", "e": 41383, "s": 38564, "text": null }, { "code": null, "e": 41387, "s": 41383, "text": "3 2" }, { "code": null, "e": 41459, "s": 41389, "text": "Time Complexity: O(|Q| + (MAX *log(log(MAX))))Auxiliary Space: O(MAX)" }, { "code": null, "e": 41477, "s": 41459, "text": "divyeshrabadiya07" }, { "code": null, "e": 41494, "s": 41477, "text": "shikhasingrajput" }, { "code": null, "e": 41507, "s": 41494, "text": "princi singh" }, { "code": null, "e": 41515, "s": 41507, "text": "gfgking" }, { "code": null, "e": 41535, "s": 41515, "text": "array-range-queries" }, { "code": null, "e": 41548, "s": 41535, "text": "Prime Number" }, { "code": null, "e": 41561, "s": 41548, "text": "prime-factor" }, { "code": null, "e": 41567, "s": 41561, "text": "sieve" }, { "code": null, "e": 41580, "s": 41567, "text": "Mathematical" }, { "code": null, "e": 41590, "s": 41580, "text": "Searching" }, { "code": null, "e": 41600, "s": 41590, "text": "Searching" }, { "code": null, "e": 41613, "s": 41600, "text": "Mathematical" }, { "code": null, "e": 41626, "s": 41613, "text": "Prime Number" }, { "code": null, "e": 41632, "s": 41626, "text": "sieve" }, { "code": null, "e": 41730, "s": 41632, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 41773, "s": 41730, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 41797, "s": 41773, "text": "Merge two sorted arrays" }, { "code": null, "e": 41846, "s": 41797, "text": "Program to find sum of elements in a given array" }, { "code": null, "e": 41880, "s": 41846, "text": "Program for factorial of a number" }, { "code": null, "e": 41901, "s": 41880, "text": "Operators in C / C++" }, { "code": null, "e": 41915, "s": 41901, "text": "Binary Search" }, { "code": null, "e": 41929, "s": 41915, "text": "Linear Search" }, { "code": null, "e": 41997, "s": 41929, "text": "Maximum and minimum of an array using minimum number of comparisons" }, { "code": null, "e": 42021, "s": 41997, "text": "Find the Missing Number" } ]
C++ String Library - pop_back
It erases the last character of the string, effectively reducing its length by one. Following is the declaration for std::string::pop_back. void pop_back(); void pop_back(); void pop_back(); none none if an exception is thrown, there are no changes in the string. In below example for std::string::pop_back. #include <iostream> #include <string> int main () { std::string str ("sairamkrishna Mammahe"); str.pop_back(); std::cout << str << '\n'; return 0; } The sample output should be like this − sairamkrishna Mammah Print Add Notes Bookmark this page
[ { "code": null, "e": 2687, "s": 2603, "text": "It erases the last character of the string, effectively reducing its length by one." }, { "code": null, "e": 2743, "s": 2687, "text": "Following is the declaration for std::string::pop_back." }, { "code": null, "e": 2760, "s": 2743, "text": "void pop_back();" }, { "code": null, "e": 2777, "s": 2760, "text": "void pop_back();" }, { "code": null, "e": 2794, "s": 2777, "text": "void pop_back();" }, { "code": null, "e": 2799, "s": 2794, "text": "none" }, { "code": null, "e": 2804, "s": 2799, "text": "none" }, { "code": null, "e": 2867, "s": 2804, "text": "if an exception is thrown, there are no changes in the string." }, { "code": null, "e": 2911, "s": 2867, "text": "In below example for std::string::pop_back." }, { "code": null, "e": 3073, "s": 2911, "text": "#include <iostream>\n#include <string>\n\nint main () {\n std::string str (\"sairamkrishna Mammahe\");\n str.pop_back();\n std::cout << str << '\\n';\n return 0;\n}" }, { "code": null, "e": 3113, "s": 3073, "text": "The sample output should be like this −" }, { "code": null, "e": 3135, "s": 3113, "text": "sairamkrishna Mammah\n" }, { "code": null, "e": 3142, "s": 3135, "text": " Print" }, { "code": null, "e": 3153, "s": 3142, "text": " Add Notes" } ]
How to disable logging from imported modules in Python?
You can disable logging from imported modules using the logging module. You can configure it to not log messages unless they are at least warnings using the following code: import logging logging.getLogger("imported_module").setLevel(logging.WARNING) If you dont want to write the module name as a string, you can also use imported_module.__name__. If you want to go a level higher and only want to log messages when they are errors or critical, you can do replace logging.WARNING with logging.ERROR and logging.CRITICAL respectively.
[ { "code": null, "e": 1235, "s": 1062, "text": "You can disable logging from imported modules using the logging module. You can configure it to not log messages unless they are at least warnings using the following code:" }, { "code": null, "e": 1313, "s": 1235, "text": "import logging\nlogging.getLogger(\"imported_module\").setLevel(logging.WARNING)" }, { "code": null, "e": 1597, "s": 1313, "text": "If you dont want to write the module name as a string, you can also use imported_module.__name__. If you want to go a level higher and only want to log messages when they are errors or critical, you can do replace logging.WARNING with logging.ERROR and logging.CRITICAL respectively." } ]
SQL NULL Values - IS NULL and IS NOT NULL
A field with a NULL value is a field with no value. If a field in a table is optional, it is possible to insert a new record or update a record without adding a value to this field. Then, the field will be saved with a NULL value. Note: A NULL value is different from a zero value or a field that contains spaces. A field with a NULL value is one that has been left blank during record creation! It is not possible to test for NULL values with comparison operators, such as =, <, or <>. We will have to use the IS NULL and IS NOT NULL operators instead. Below is a selection from the "Customers" table in the Northwind sample database: The IS NULL operator is used to test for empty values (NULL values). The following SQL lists all customers with a NULL value in the "Address" field: Tip: Always use IS NULL to look for NULL values. The IS NOT NULL operator is used to test for non-empty values (NOT NULL values). The following SQL lists all customers with a value in the "Address" field: Select all records from the Customers where the PostalCode column is empty. SELECT * FROM Customers WHERE ; 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": 52, "s": 0, "text": "A field with a NULL value is a field with no value." }, { "code": null, "e": 233, "s": 52, "text": "If a field in a table is optional, it is possible to insert a new record or \nupdate a record without adding a value to this field. Then, the field will be \nsaved with a NULL value." }, { "code": null, "e": 400, "s": 233, "text": "Note: A NULL value is different from a zero value or a field that \ncontains spaces. A field with a NULL value is one that has been left blank \nduring record creation!" }, { "code": null, "e": 492, "s": 400, "text": "It is not possible to test for NULL values with comparison operators, such as \n=, <, or <>." }, { "code": null, "e": 560, "s": 492, "text": "We will have to use the IS NULL and \nIS NOT NULL operators instead." }, { "code": null, "e": 643, "s": 560, "text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:" }, { "code": null, "e": 712, "s": 643, "text": "The IS NULL operator is used to test for empty values (NULL values)." }, { "code": null, "e": 792, "s": 712, "text": "The following SQL lists all customers with a NULL value in the \"Address\" field:" }, { "code": null, "e": 841, "s": 792, "text": "Tip: Always use IS NULL to look for NULL values." }, { "code": null, "e": 923, "s": 841, "text": "The IS NOT NULL operator is used to test for non-empty values (NOT NULL \nvalues)." }, { "code": null, "e": 998, "s": 923, "text": "The following SQL lists all customers with a value in the \"Address\" field:" }, { "code": null, "e": 1075, "s": 998, "text": "Select all records from the Customers where \nthe PostalCode column is empty." }, { "code": null, "e": 1110, "s": 1075, "text": "SELECT * FROM Customers\nWHERE ;\n" }, { "code": null, "e": 1130, "s": 1110, "text": "Start the \nExercise" }, { "code": null, "e": 1163, "s": 1130, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 1205, "s": 1163, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1312, "s": 1205, "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": 1331, "s": 1312, "text": "[email protected]" } ]
Generate OneDrive Direct-Download Link with C# or Python | by Joe T. Santhanavanich | Towards Data Science
In many projects, you may need file hosting services to share a large number of datasets, scripts, or any files with the direct download option. You may already use the most popular hosting services such as Google Drive, Microsoft OneDrive, DropBox, and iCloud. In this article, I will focus on how to make a direct download link from the OneDrive.com. The direct download would let you flexibly use the file in any other software. For example, if you host the excel or csv table dataset with a direct download link, the receiver can directly load it to the Pandas dataframe in Python. I guess I do not have to introduce so much about the OneDrive. It offers 5 GB of storage space free of charge. That would be enough for any big dataset. If you have a really big dataset to share, please consider the database instead. Most of you even have Microsoft Office 365 which includes online space of 1 TB. Also, it is easy to use, share, edit online. You just need to go to OneDrive, drag and drop to upload any file there, click on the “share” button on the top of the page and click the copy link. That’s it! For example, I share the COVID-19 time-series dataset from CSSE as an excel table through the OneDrive. And when you access this dataset through the link you created, the browser will automatically open Excel Online for you to explore the dataset in table format. How convenient! But, unfortunately, it needs several clicks or redirects if your receiver wants to download the dataset. So, it is better for you to share a direct download link if your purpose is to let your receiver download the file. According to the OneDrive API docs, you can easily generate the OneDrive direct download link with this logic: First, use base64 to encode the URL.Convert the base64 encoded result to unpadded base64url format by removing = characters from the end of the value, replacing / with _ and + with -.)Append u! to be the beginning of the string. First, use base64 to encode the URL. Convert the base64 encoded result to unpadded base64url format by removing = characters from the end of the value, replacing / with _ and + with -.) Append u! to be the beginning of the string. To follow the above logic, the OneDrive API docs also provide an example script in C# for you as follows: string sharingUrl = "Your OneDrive Link here";string base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sharingUrl));string encodedUrl = "u!" + base64Value.TrimEnd('=').Replace('/','_').Replace('+','-'); You may try to run this script online in C# with the following link: rextester.com After opening the link, you just need to change the sharingUrl to any of your OneDrive links. Wait for some seconds, then you get the output direct OneDrive download link in the output console. Python is popular in many Data Science projects. So, you might want to generate a direct download link in Python directly before doing the data analysis with the dataset. If someone (or yourself) shares the OneDrive link, you may turn it to a downloadable link with the following Python script: For example, you can follow the script below to generate the direct download link from our COVID-19 dataset example in excel format. URL: https://1drv.ms/x/s!AmLiprCs46qqhMgFb5pcJisePNNlXw?e=ZgPsGZ then import it to the Pandas dataframe: import pandas as pd # Input any OneDrive URL onedrive_url = "https://1drv.ms/x/s!AmLiprCs46qqhMgFb5pcJisePNNlXw?e=ZgPsGZ"# Generate Direct Download URL from above Scriptdirect_download_url = create_onedrive_directdownload(onedrive_url)print(direct_download_url)# Load Dataset to the Dataframedf = pd.read_excel(direct_download_url)print(df.head())# Continue with your data analysis ... This article introduces how to share your files through the OneDrive and turn it to the direct downloadable link with C# or Python. Please, note that you may use apply this logic and rewrite it in any other programming language as well. I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments. About me & Check out all my blog contents: Link Be Safe and Healthy! 💪 Thank you for Reading. 📚
[ { "code": null, "e": 525, "s": 172, "text": "In many projects, you may need file hosting services to share a large number of datasets, scripts, or any files with the direct download option. You may already use the most popular hosting services such as Google Drive, Microsoft OneDrive, DropBox, and iCloud. In this article, I will focus on how to make a direct download link from the OneDrive.com." }, { "code": null, "e": 758, "s": 525, "text": "The direct download would let you flexibly use the file in any other software. For example, if you host the excel or csv table dataset with a direct download link, the receiver can directly load it to the Pandas dataframe in Python." }, { "code": null, "e": 1117, "s": 758, "text": "I guess I do not have to introduce so much about the OneDrive. It offers 5 GB of storage space free of charge. That would be enough for any big dataset. If you have a really big dataset to share, please consider the database instead. Most of you even have Microsoft Office 365 which includes online space of 1 TB. Also, it is easy to use, share, edit online." }, { "code": null, "e": 1277, "s": 1117, "text": "You just need to go to OneDrive, drag and drop to upload any file there, click on the “share” button on the top of the page and click the copy link. That’s it!" }, { "code": null, "e": 1557, "s": 1277, "text": "For example, I share the COVID-19 time-series dataset from CSSE as an excel table through the OneDrive. And when you access this dataset through the link you created, the browser will automatically open Excel Online for you to explore the dataset in table format. How convenient!" }, { "code": null, "e": 1778, "s": 1557, "text": "But, unfortunately, it needs several clicks or redirects if your receiver wants to download the dataset. So, it is better for you to share a direct download link if your purpose is to let your receiver download the file." }, { "code": null, "e": 1889, "s": 1778, "text": "According to the OneDrive API docs, you can easily generate the OneDrive direct download link with this logic:" }, { "code": null, "e": 2118, "s": 1889, "text": "First, use base64 to encode the URL.Convert the base64 encoded result to unpadded base64url format by removing = characters from the end of the value, replacing / with _ and + with -.)Append u! to be the beginning of the string." }, { "code": null, "e": 2155, "s": 2118, "text": "First, use base64 to encode the URL." }, { "code": null, "e": 2304, "s": 2155, "text": "Convert the base64 encoded result to unpadded base64url format by removing = characters from the end of the value, replacing / with _ and + with -.)" }, { "code": null, "e": 2349, "s": 2304, "text": "Append u! to be the beginning of the string." }, { "code": null, "e": 2455, "s": 2349, "text": "To follow the above logic, the OneDrive API docs also provide an example script in C# for you as follows:" }, { "code": null, "e": 2687, "s": 2455, "text": "string sharingUrl = \"Your OneDrive Link here\";string base64Value = System.Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(sharingUrl));string encodedUrl = \"u!\" + base64Value.TrimEnd('=').Replace('/','_').Replace('+','-');" }, { "code": null, "e": 2756, "s": 2687, "text": "You may try to run this script online in C# with the following link:" }, { "code": null, "e": 2770, "s": 2756, "text": "rextester.com" }, { "code": null, "e": 2964, "s": 2770, "text": "After opening the link, you just need to change the sharingUrl to any of your OneDrive links. Wait for some seconds, then you get the output direct OneDrive download link in the output console." }, { "code": null, "e": 3259, "s": 2964, "text": "Python is popular in many Data Science projects. So, you might want to generate a direct download link in Python directly before doing the data analysis with the dataset. If someone (or yourself) shares the OneDrive link, you may turn it to a downloadable link with the following Python script:" }, { "code": null, "e": 3497, "s": 3259, "text": "For example, you can follow the script below to generate the direct download link from our COVID-19 dataset example in excel format. URL: https://1drv.ms/x/s!AmLiprCs46qqhMgFb5pcJisePNNlXw?e=ZgPsGZ then import it to the Pandas dataframe:" }, { "code": null, "e": 3883, "s": 3497, "text": "import pandas as pd # Input any OneDrive URL onedrive_url = \"https://1drv.ms/x/s!AmLiprCs46qqhMgFb5pcJisePNNlXw?e=ZgPsGZ\"# Generate Direct Download URL from above Scriptdirect_download_url = create_onedrive_directdownload(onedrive_url)print(direct_download_url)# Load Dataset to the Dataframedf = pd.read_excel(direct_download_url)print(df.head())# Continue with your data analysis ..." }, { "code": null, "e": 4120, "s": 3883, "text": "This article introduces how to share your files through the OneDrive and turn it to the direct downloadable link with C# or Python. Please, note that you may use apply this logic and rewrite it in any other programming language as well." }, { "code": null, "e": 4273, "s": 4120, "text": "I hope you like this article and found it useful for your daily work or projects. Feel free to leave me a message if you have any questions or comments." }, { "code": null, "e": 4321, "s": 4273, "text": "About me & Check out all my blog contents: Link" }, { "code": null, "e": 4344, "s": 4321, "text": "Be Safe and Healthy! 💪" } ]
Introduction to Mesa: Agent-based Modeling in Python | by Ng Wai Foong | Towards Data Science
Python-based alternative to NetLogo, Repast, or MASON for agent-based modeling Agent-based modeling relies on simulating the actions and interactions of autonomous agents to evaluate their effects on the system. It is often used to predict the projections that we will obtain given a complex phenomena. The main purpose is to obtain explanatory insight on how the agents will behave given a particular set of rules. Agent-based modeling has been extensively used in numerous industry such as biology, social sciences, network and business. This article covers the necessary steps to kick-start your agent-based modeling project using an open-source python module called Mesa. There are 4 sections in this tutorial: SetupSchelling Segregation ModelVisualizationConclusion Setup Schelling Segregation Model Visualization Conclusion Setup is pretty straightforward for Mesa. Make sure to create a new virtual environment. I name the environment as mesaenv. Open up your terminal and change the directory to mesaenv and activate the virtual environment using the following code: Run the following command to activate the virtual environment depending on your use case. #Anacondaconda activate mesaenv#Terminalsource bin/activate This tutorial requires three modules: mesa matplotlib jupyter python3 -m pip install mesapython3 -m pip install matplotlibpython3 -m pip install jupyter Create a base folder called Mesa that you will use to store all the python files. You should have the following files in the base folder at the end of this sections: Model.pyRun.pyServer.py Model.py Run.py Server.py Feel free to download it in case you got lost somewhere in the tutorial. Once you are done, let’s proceed to the next section. We will be using the famous Schelling Segregation model as use case for this tutorial. Please be noted that the introductory tutorial on the official mesa site is based on Boltzmann Wealth model. Schelling Segregation model is a better use case to explain how we can use agent-based modeling to explain why racial segregation issue is difficult to be eradicated. Although the actual model is quite simple, it provides explanatory insights at how individuals might self-segregate even though when they have no explicit desire to do so. Let’s have a look at the explanation for this model provided by the Mesa official github page: The Schelling segregation model is a classic agent-based model, demonstrating how even a mild preference for similar neighbors can lead to a much higher degree of segregation than we would intuitively expect. The model consists of agents on a square grid, where each grid cell can contain at most one agent. Agents come in two colors: red and blue. They are happy if a certain number of their eight possible neighbors are of the same color, and unhappy otherwise. Unhappy agents will pick a random empty cell to move to each step, until they are happy. The model keeps running until there are no unhappy agents. By default, the number of similar neighbors the agents need to be happy is set to 3. That means the agents would be perfectly happy with a majority of their neighbors being of a different color (e.g. a Blue agent would be happy with five Red neighbors and three Blue ones). Despite this, the model consistently leads to a high degree of segregation, with most agents ending up with no neighbors of a different color. Create a new python file called model.py. Agent: We will start off with the single agent class. The code is quite straightforward: Initialize the Agent class.Create a step function.Calculate the number of similar neighbors.Move the agent to a empty location if the agent is unhappy. Initialize the Agent class. Create a step function. Calculate the number of similar neighbors. Move the agent to a empty location if the agent is unhappy. Model: For the model class. We will go through each part one-by-one to have a clearer understanding of how agent-based modeling works. First and foremost, create a Schelling class and define a init function as constructor. class Schelling(Model): def __init__(): Variables: The system will consists of at least a basic agent class and a model class. Let’s start by writing the model first. We will need to define 5 main variables: Width: Horizontal axis of the grid which is used together with Height to define the total number of agents in the system. Height: Vertical axis of the grid which is used together with Width to define the total number of agents in the system. Density: Define the population density of agent in the system. Floating value from 0 to 1. Fraction minority: The ratio between blue and red. Blue is represented as the minority while red is represented as the majority. Floating value from 0 to 1. If the value is higher than 0.5, blue will become the majority instead. Homophily: Define the number of similar neighbors required for the agents to be happy. Integer value range from 0 to 8 since you can only be surrounded by 8 neighbors. self.height = heightself.width = widthself.density = densityself.minority_pc = minority_pcself.homophily = homophily Remember to add the required parameters as input parameters in the init function. Grid: We will need to set the grid using the space module under mesa. from mesa.space import SingleGridself.grid = SingleGrid(height, width, torus=True) Scheduler: Next up, we will need to have a scheduler. The scheduler is a special model component which controls the order in which agents are activated. The most common scheduler is the random activation which activates all the agents once per step, in random order. There is also another type called Simultaneous activation. Check out the API reference to find out more. from mesa.time import RandomActivationself.schedule = RandomActivation(self) Data Collection: Data collection is essential to ensure that we obtained the necessary data after each step of the simulation. You can use the built-in datacollection module. In this case, we only need to know whether the agent is happy or not. from mesa.datacollection import DataCollectorself.happy = 0self.datacollector = DataCollector( {"happy": "happy"},{"x": lambda a: a.pos[0], "y": lambda a: a.pos[1]}) Agents Setup: We will now setup the agent using the following code: The last part of the init function is to set the following parameters: self.running = True self.datacollector.collect(self) The running variable enables conditional shut off of the model once a condition is met. We will set it to false once all the agent are happy. Step: This class requires a step function that represent each run. Reset the counter of happy agents at each step.Start to collect data and determine the number of agent that are happy.Stop the model once all agents are happy. Reset the counter of happy agents at each step. Start to collect data and determine the number of agent that are happy. Stop the model once all agents are happy. Create a new python file called run.py and type in the following code. Create a new python file called server.py. Import: Add the following import statement to the file: from mesa.visualization.ModularVisualization import ModularServerfrom mesa.visualization.modules import CanvasGrid, ChartModule, TextElementfrom mesa.visualization.UserParam import UserSettableParameter from model import Schelling HappyElement: Create a class called HappyElement and add two functions: Init Render Draw function: Define a function called schelling_draw. This part acts as the visualization part when running the server. First, we define the base potrayal. A portrayal is a dictionary (which can easily be turned into a JSON object) which tells the JavaScript side how to draw it.We change the color and stroke of the portrayal based on the type of the agent. In this case, we will have red and blue agent.Initialize the Canvas and chart.Set the parameters for the model. UserSettableParameter means that the user can modify this parameter in the web page. It takes 6 parameters (type, name, initial value, min value, max value, value per step).Finally, we initialize the server with all the configurations that we have defined above. First, we define the base potrayal. A portrayal is a dictionary (which can easily be turned into a JSON object) which tells the JavaScript side how to draw it. We change the color and stroke of the portrayal based on the type of the agent. In this case, we will have red and blue agent. Initialize the Canvas and chart. Set the parameters for the model. UserSettableParameter means that the user can modify this parameter in the web page. It takes 6 parameters (type, name, initial value, min value, max value, value per step). Finally, we initialize the server with all the configurations that we have defined above. Let’s test it out by running the following code at the terminal. Make sure that you are at the base folder (Mesa). mesa runserver A web browser will be launched and you should see the following ouput: The visualization of the canvas grid that we have defined earlier. Each dot represents an agent. You can modify the setting to test out how it will affects the simulation. Modify this will not affect the current simulation. Remember to click on the Reset button to make changes. You can define your own frame per second to speed up the simulation. You will have the following buttons at your disposal: Start/Stop: It will start the simulation. Once it is started, you can click on the same button to turn it off. Step: Run only a single step to see the changes. Reset: Reset the board based on the setting. If you use it while the simulation is running, the board will be reset and simulation will continue to run as usual. Click on the Start button and you should see the following changes to the canvas. There is a chart at the bottom to show the number of agents that are happy against the number of step. The model should stop at a certain point depends on the setting that you have set. You can noticed that the agents are pretty much segregated. Let’s recap on what we have learned today. We started off with some simple steps to setup and install the necessary python modules. Then, we learned about the Schelling Segregation Model and how we can model it easily using Mesa. We created 3 python files and explored further in-depth on the basic usage of components available in Mesa. After that, we ran the server to see the visualization. We modified some settings and play around with the simulation. In fact, the official Mesa github provided us with a lot more examples that we can explore. Check out the following link to find out more. Hope you enjoyed the tutorial. Have a great day and see you again in the next tutorial.
[ { "code": null, "e": 250, "s": 171, "text": "Python-based alternative to NetLogo, Repast, or MASON for agent-based modeling" }, { "code": null, "e": 886, "s": 250, "text": "Agent-based modeling relies on simulating the actions and interactions of autonomous agents to evaluate their effects on the system. It is often used to predict the projections that we will obtain given a complex phenomena. The main purpose is to obtain explanatory insight on how the agents will behave given a particular set of rules. Agent-based modeling has been extensively used in numerous industry such as biology, social sciences, network and business. This article covers the necessary steps to kick-start your agent-based modeling project using an open-source python module called Mesa. There are 4 sections in this tutorial:" }, { "code": null, "e": 942, "s": 886, "text": "SetupSchelling Segregation ModelVisualizationConclusion" }, { "code": null, "e": 948, "s": 942, "text": "Setup" }, { "code": null, "e": 976, "s": 948, "text": "Schelling Segregation Model" }, { "code": null, "e": 990, "s": 976, "text": "Visualization" }, { "code": null, "e": 1001, "s": 990, "text": "Conclusion" }, { "code": null, "e": 1246, "s": 1001, "text": "Setup is pretty straightforward for Mesa. Make sure to create a new virtual environment. I name the environment as mesaenv. Open up your terminal and change the directory to mesaenv and activate the virtual environment using the following code:" }, { "code": null, "e": 1336, "s": 1246, "text": "Run the following command to activate the virtual environment depending on your use case." }, { "code": null, "e": 1396, "s": 1336, "text": "#Anacondaconda activate mesaenv#Terminalsource bin/activate" }, { "code": null, "e": 1434, "s": 1396, "text": "This tutorial requires three modules:" }, { "code": null, "e": 1439, "s": 1434, "text": "mesa" }, { "code": null, "e": 1450, "s": 1439, "text": "matplotlib" }, { "code": null, "e": 1458, "s": 1450, "text": "jupyter" }, { "code": null, "e": 1549, "s": 1458, "text": "python3 -m pip install mesapython3 -m pip install matplotlibpython3 -m pip install jupyter" }, { "code": null, "e": 1715, "s": 1549, "text": "Create a base folder called Mesa that you will use to store all the python files. You should have the following files in the base folder at the end of this sections:" }, { "code": null, "e": 1739, "s": 1715, "text": "Model.pyRun.pyServer.py" }, { "code": null, "e": 1748, "s": 1739, "text": "Model.py" }, { "code": null, "e": 1755, "s": 1748, "text": "Run.py" }, { "code": null, "e": 1765, "s": 1755, "text": "Server.py" }, { "code": null, "e": 1892, "s": 1765, "text": "Feel free to download it in case you got lost somewhere in the tutorial. Once you are done, let’s proceed to the next section." }, { "code": null, "e": 2522, "s": 1892, "text": "We will be using the famous Schelling Segregation model as use case for this tutorial. Please be noted that the introductory tutorial on the official mesa site is based on Boltzmann Wealth model. Schelling Segregation model is a better use case to explain how we can use agent-based modeling to explain why racial segregation issue is difficult to be eradicated. Although the actual model is quite simple, it provides explanatory insights at how individuals might self-segregate even though when they have no explicit desire to do so. Let’s have a look at the explanation for this model provided by the Mesa official github page:" }, { "code": null, "e": 3134, "s": 2522, "text": "The Schelling segregation model is a classic agent-based model, demonstrating how even a mild preference for similar neighbors can lead to a much higher degree of segregation than we would intuitively expect. The model consists of agents on a square grid, where each grid cell can contain at most one agent. Agents come in two colors: red and blue. They are happy if a certain number of their eight possible neighbors are of the same color, and unhappy otherwise. Unhappy agents will pick a random empty cell to move to each step, until they are happy. The model keeps running until there are no unhappy agents." }, { "code": null, "e": 3551, "s": 3134, "text": "By default, the number of similar neighbors the agents need to be happy is set to 3. That means the agents would be perfectly happy with a majority of their neighbors being of a different color (e.g. a Blue agent would be happy with five Red neighbors and three Blue ones). Despite this, the model consistently leads to a high degree of segregation, with most agents ending up with no neighbors of a different color." }, { "code": null, "e": 3593, "s": 3551, "text": "Create a new python file called model.py." }, { "code": null, "e": 3647, "s": 3593, "text": "Agent: We will start off with the single agent class." }, { "code": null, "e": 3682, "s": 3647, "text": "The code is quite straightforward:" }, { "code": null, "e": 3834, "s": 3682, "text": "Initialize the Agent class.Create a step function.Calculate the number of similar neighbors.Move the agent to a empty location if the agent is unhappy." }, { "code": null, "e": 3862, "s": 3834, "text": "Initialize the Agent class." }, { "code": null, "e": 3886, "s": 3862, "text": "Create a step function." }, { "code": null, "e": 3929, "s": 3886, "text": "Calculate the number of similar neighbors." }, { "code": null, "e": 3989, "s": 3929, "text": "Move the agent to a empty location if the agent is unhappy." }, { "code": null, "e": 4212, "s": 3989, "text": "Model: For the model class. We will go through each part one-by-one to have a clearer understanding of how agent-based modeling works. First and foremost, create a Schelling class and define a init function as constructor." }, { "code": null, "e": 4255, "s": 4212, "text": "class Schelling(Model): def __init__():" }, { "code": null, "e": 4423, "s": 4255, "text": "Variables: The system will consists of at least a basic agent class and a model class. Let’s start by writing the model first. We will need to define 5 main variables:" }, { "code": null, "e": 4545, "s": 4423, "text": "Width: Horizontal axis of the grid which is used together with Height to define the total number of agents in the system." }, { "code": null, "e": 4665, "s": 4545, "text": "Height: Vertical axis of the grid which is used together with Width to define the total number of agents in the system." }, { "code": null, "e": 4756, "s": 4665, "text": "Density: Define the population density of agent in the system. Floating value from 0 to 1." }, { "code": null, "e": 4985, "s": 4756, "text": "Fraction minority: The ratio between blue and red. Blue is represented as the minority while red is represented as the majority. Floating value from 0 to 1. If the value is higher than 0.5, blue will become the majority instead." }, { "code": null, "e": 5153, "s": 4985, "text": "Homophily: Define the number of similar neighbors required for the agents to be happy. Integer value range from 0 to 8 since you can only be surrounded by 8 neighbors." }, { "code": null, "e": 5270, "s": 5153, "text": "self.height = heightself.width = widthself.density = densityself.minority_pc = minority_pcself.homophily = homophily" }, { "code": null, "e": 5352, "s": 5270, "text": "Remember to add the required parameters as input parameters in the init function." }, { "code": null, "e": 5422, "s": 5352, "text": "Grid: We will need to set the grid using the space module under mesa." }, { "code": null, "e": 5505, "s": 5422, "text": "from mesa.space import SingleGridself.grid = SingleGrid(height, width, torus=True)" }, { "code": null, "e": 5877, "s": 5505, "text": "Scheduler: Next up, we will need to have a scheduler. The scheduler is a special model component which controls the order in which agents are activated. The most common scheduler is the random activation which activates all the agents once per step, in random order. There is also another type called Simultaneous activation. Check out the API reference to find out more." }, { "code": null, "e": 5954, "s": 5877, "text": "from mesa.time import RandomActivationself.schedule = RandomActivation(self)" }, { "code": null, "e": 6199, "s": 5954, "text": "Data Collection: Data collection is essential to ensure that we obtained the necessary data after each step of the simulation. You can use the built-in datacollection module. In this case, we only need to know whether the agent is happy or not." }, { "code": null, "e": 6399, "s": 6199, "text": "from mesa.datacollection import DataCollectorself.happy = 0self.datacollector = DataCollector( {\"happy\": \"happy\"},{\"x\": lambda a: a.pos[0], \"y\": lambda a: a.pos[1]})" }, { "code": null, "e": 6467, "s": 6399, "text": "Agents Setup: We will now setup the agent using the following code:" }, { "code": null, "e": 6538, "s": 6467, "text": "The last part of the init function is to set the following parameters:" }, { "code": null, "e": 6621, "s": 6538, "text": "self.running = True self.datacollector.collect(self)" }, { "code": null, "e": 6763, "s": 6621, "text": "The running variable enables conditional shut off of the model once a condition is met. We will set it to false once all the agent are happy." }, { "code": null, "e": 6830, "s": 6763, "text": "Step: This class requires a step function that represent each run." }, { "code": null, "e": 6990, "s": 6830, "text": "Reset the counter of happy agents at each step.Start to collect data and determine the number of agent that are happy.Stop the model once all agents are happy." }, { "code": null, "e": 7038, "s": 6990, "text": "Reset the counter of happy agents at each step." }, { "code": null, "e": 7110, "s": 7038, "text": "Start to collect data and determine the number of agent that are happy." }, { "code": null, "e": 7152, "s": 7110, "text": "Stop the model once all agents are happy." }, { "code": null, "e": 7223, "s": 7152, "text": "Create a new python file called run.py and type in the following code." }, { "code": null, "e": 7266, "s": 7223, "text": "Create a new python file called server.py." }, { "code": null, "e": 7322, "s": 7266, "text": "Import: Add the following import statement to the file:" }, { "code": null, "e": 7599, "s": 7322, "text": "from mesa.visualization.ModularVisualization import ModularServerfrom mesa.visualization.modules import CanvasGrid, ChartModule, TextElementfrom mesa.visualization.UserParam import UserSettableParameter from model import Schelling" }, { "code": null, "e": 7671, "s": 7599, "text": "HappyElement: Create a class called HappyElement and add two functions:" }, { "code": null, "e": 7676, "s": 7671, "text": "Init" }, { "code": null, "e": 7683, "s": 7676, "text": "Render" }, { "code": null, "e": 7739, "s": 7683, "text": "Draw function: Define a function called schelling_draw." }, { "code": null, "e": 7805, "s": 7739, "text": "This part acts as the visualization part when running the server." }, { "code": null, "e": 8419, "s": 7805, "text": "First, we define the base potrayal. A portrayal is a dictionary (which can easily be turned into a JSON object) which tells the JavaScript side how to draw it.We change the color and stroke of the portrayal based on the type of the agent. In this case, we will have red and blue agent.Initialize the Canvas and chart.Set the parameters for the model. UserSettableParameter means that the user can modify this parameter in the web page. It takes 6 parameters (type, name, initial value, min value, max value, value per step).Finally, we initialize the server with all the configurations that we have defined above." }, { "code": null, "e": 8579, "s": 8419, "text": "First, we define the base potrayal. A portrayal is a dictionary (which can easily be turned into a JSON object) which tells the JavaScript side how to draw it." }, { "code": null, "e": 8706, "s": 8579, "text": "We change the color and stroke of the portrayal based on the type of the agent. In this case, we will have red and blue agent." }, { "code": null, "e": 8739, "s": 8706, "text": "Initialize the Canvas and chart." }, { "code": null, "e": 8947, "s": 8739, "text": "Set the parameters for the model. UserSettableParameter means that the user can modify this parameter in the web page. It takes 6 parameters (type, name, initial value, min value, max value, value per step)." }, { "code": null, "e": 9037, "s": 8947, "text": "Finally, we initialize the server with all the configurations that we have defined above." }, { "code": null, "e": 9152, "s": 9037, "text": "Let’s test it out by running the following code at the terminal. Make sure that you are at the base folder (Mesa)." }, { "code": null, "e": 9167, "s": 9152, "text": "mesa runserver" }, { "code": null, "e": 9238, "s": 9167, "text": "A web browser will be launched and you should see the following ouput:" }, { "code": null, "e": 9335, "s": 9238, "text": "The visualization of the canvas grid that we have defined earlier. Each dot represents an agent." }, { "code": null, "e": 9517, "s": 9335, "text": "You can modify the setting to test out how it will affects the simulation. Modify this will not affect the current simulation. Remember to click on the Reset button to make changes." }, { "code": null, "e": 9586, "s": 9517, "text": "You can define your own frame per second to speed up the simulation." }, { "code": null, "e": 9640, "s": 9586, "text": "You will have the following buttons at your disposal:" }, { "code": null, "e": 9751, "s": 9640, "text": "Start/Stop: It will start the simulation. Once it is started, you can click on the same button to turn it off." }, { "code": null, "e": 9800, "s": 9751, "text": "Step: Run only a single step to see the changes." }, { "code": null, "e": 9962, "s": 9800, "text": "Reset: Reset the board based on the setting. If you use it while the simulation is running, the board will be reset and simulation will continue to run as usual." }, { "code": null, "e": 10044, "s": 9962, "text": "Click on the Start button and you should see the following changes to the canvas." }, { "code": null, "e": 10147, "s": 10044, "text": "There is a chart at the bottom to show the number of agents that are happy against the number of step." }, { "code": null, "e": 10290, "s": 10147, "text": "The model should stop at a certain point depends on the setting that you have set. You can noticed that the agents are pretty much segregated." }, { "code": null, "e": 10333, "s": 10290, "text": "Let’s recap on what we have learned today." }, { "code": null, "e": 10422, "s": 10333, "text": "We started off with some simple steps to setup and install the necessary python modules." }, { "code": null, "e": 10628, "s": 10422, "text": "Then, we learned about the Schelling Segregation Model and how we can model it easily using Mesa. We created 3 python files and explored further in-depth on the basic usage of components available in Mesa." }, { "code": null, "e": 10886, "s": 10628, "text": "After that, we ran the server to see the visualization. We modified some settings and play around with the simulation. In fact, the official Mesa github provided us with a lot more examples that we can explore. Check out the following link to find out more." } ]
Making network graphs interactive with Python and Pyvis. | by JOSÉ MANUEL NÁPOLES DUARTE | Towards Data Science
For a while, I and others in the Streamlit community [1] have been seeking a tool to render interactive graphs, but until now this has been something only a few can achieve. This can be due to the fact that a level of expertise with javascript is required, something that many Streamlit users may want to avoid, as this is the promise of the project, deploy beautiful web apps from python, no javascript required!! (of course, mastering javascript is a big plus for making awesome streamlit apps). Recently I found Pyvis, after a few weeks looking for an alternative to other javascript based libraries used to make graphs interactive. I liked pyvis a lot and wanted to share in this post some tips I’ve learned. But if you want to see by yourself check the documentation page [2]: pyvis.readthedocs.io The rest of this post is as follows: First I will show a super simple example to do a small 3 nodes net. Second, I show how to fix the positions of nodes and how to preserve the shape for the graph of a molecule. The third case is devoted to building a network with Networkx. Finally, I show a Streamlit app working with Pyvis. I will start with a simple example, creating a Network object and adding 3 nodes (method add_node) labeled 1,2 and 3 with two edges (method add_edge) [1–2] and [2–3]. In order to deploy the graph for example in a Jupyter or Colab environment, pyvis “translates” the python code to html+javascript with the show method. Calling g.show(‘example.html’) writes to disk the html file which can be rendered with display: and here is the result, And that’s all easy, isn’t it? This basic recipe will be used in the following. I did a small function show_graph() to do the display in a single step that you could see in the snippets below. You can find this and all the code in a Colab notebook in the github repo at the bottom 🙌. The next case is something I figured out that it could be achieved combining pyvis with the chemoinformatics library RDKit 🤓 [3]. I assume this is not of general interest, so I will avoid the process to build up the molecule, and instead I will present just the resulting nodes and connectivity information of the atoms. This is shown here for caffeine molecule ☕️. As I want to preserve its shape, first I need the coordinates of the atoms, but also some very specific physics options. Let me explain in a simple way how this is accomplished: as there are 14 atoms I did a loop running on each atom number, assigning nodes with the add_node method. For each node I gave the atom symbol, and cartesian coordinates from three separated lists (which I got from RDKit preprocessing), ids, xs and ys: for atomo in range(14): g3.add_node(atomo,label=ids[atomo], x=int(100*xs[atomo]),y=int(100*ys[atomo]), physics=True,size=30) (xs and ys are arbitrarily multiplied by 100 just to make the graph more manageable ) The full snippet is hosted with ❤️ :) where you can see also the physics options: And this is what results, pretty much acceptable I think: I am sure this can be used mostly for presentations to catch eye attention or to design chemistry oriented web pages. But other uses could be envisioned as well. If you are familiar with Networkx [4], you should know that it is very popular because this library is easy to use and well documented, but as far as I know it lacks this feature of making the graph interactive. Fortunately, Pyvis accepts graph objects from Networkx beautifully. Networkx has prebuilt the Zachary’s Karate Club graph [5], where you have 34 members of the club, being 0 and 33 the President and the Sensei which have a conflict and they separate the club in two groups based on influence among members. Bellow is shown the piece of code needed for this graph in pyvis. First we got G with the graph from Networkx. Then we build the pyvis object g4, and method from_nx is used to get the graph into pyvis... as simple as that: Here I must highlight the show_buttons method in line 8, which is used to deploy the physics options allowing the user to change interactively the way the nodes interact each other as if they were connected by springs and having other physical interactions. That makes the dynamics of the graph look like more “natural” and visually is a joy. Of course there are other ways to make graphs interactive, using advanced libraries, but in general they are more complex. The simplicity offered by pyvis is something that is appreciated. Finally, I just show how these dynamic graphs look in a Streamlit web app. I am not going to discuss how to do the app, I let that as homework to the reader. hint: you can see the github repo below 😏 If you want you can play with the web app here: https://share.streamlit.io/napoles-uach/streamlit_network/main/app.py If you liked it, please star the github repo 🌟 https://github.com/napoles-uach/streamlit_network The code snippets presented here are part of a Colab Notebook that you can find here: https://github.com/napoles-uach/streamlit_network/blob/main/pyvis_sample.ipynb Follow me on twitter 👉 https://twitter.com/napoles3D 🙌
[ { "code": null, "e": 669, "s": 171, "text": "For a while, I and others in the Streamlit community [1] have been seeking a tool to render interactive graphs, but until now this has been something only a few can achieve. This can be due to the fact that a level of expertise with javascript is required, something that many Streamlit users may want to avoid, as this is the promise of the project, deploy beautiful web apps from python, no javascript required!! (of course, mastering javascript is a big plus for making awesome streamlit apps)." }, { "code": null, "e": 953, "s": 669, "text": "Recently I found Pyvis, after a few weeks looking for an alternative to other javascript based libraries used to make graphs interactive. I liked pyvis a lot and wanted to share in this post some tips I’ve learned. But if you want to see by yourself check the documentation page [2]:" }, { "code": null, "e": 974, "s": 953, "text": "pyvis.readthedocs.io" }, { "code": null, "e": 1302, "s": 974, "text": "The rest of this post is as follows: First I will show a super simple example to do a small 3 nodes net. Second, I show how to fix the positions of nodes and how to preserve the shape for the graph of a molecule. The third case is devoted to building a network with Networkx. Finally, I show a Streamlit app working with Pyvis." }, { "code": null, "e": 1717, "s": 1302, "text": "I will start with a simple example, creating a Network object and adding 3 nodes (method add_node) labeled 1,2 and 3 with two edges (method add_edge) [1–2] and [2–3]. In order to deploy the graph for example in a Jupyter or Colab environment, pyvis “translates” the python code to html+javascript with the show method. Calling g.show(‘example.html’) writes to disk the html file which can be rendered with display:" }, { "code": null, "e": 1741, "s": 1717, "text": "and here is the result," }, { "code": null, "e": 2025, "s": 1741, "text": "And that’s all easy, isn’t it? This basic recipe will be used in the following. I did a small function show_graph() to do the display in a single step that you could see in the snippets below. You can find this and all the code in a Colab notebook in the github repo at the bottom 🙌." }, { "code": null, "e": 2391, "s": 2025, "text": "The next case is something I figured out that it could be achieved combining pyvis with the chemoinformatics library RDKit 🤓 [3]. I assume this is not of general interest, so I will avoid the process to build up the molecule, and instead I will present just the resulting nodes and connectivity information of the atoms. This is shown here for caffeine molecule ☕️." }, { "code": null, "e": 2822, "s": 2391, "text": "As I want to preserve its shape, first I need the coordinates of the atoms, but also some very specific physics options. Let me explain in a simple way how this is accomplished: as there are 14 atoms I did a loop running on each atom number, assigning nodes with the add_node method. For each node I gave the atom symbol, and cartesian coordinates from three separated lists (which I got from RDKit preprocessing), ids, xs and ys:" }, { "code": null, "e": 2957, "s": 2822, "text": "for atomo in range(14): g3.add_node(atomo,label=ids[atomo], x=int(100*xs[atomo]),y=int(100*ys[atomo]), physics=True,size=30)" }, { "code": null, "e": 3043, "s": 2957, "text": "(xs and ys are arbitrarily multiplied by 100 just to make the graph more manageable )" }, { "code": null, "e": 3125, "s": 3043, "text": "The full snippet is hosted with ❤️ :) where you can see also the physics options:" }, { "code": null, "e": 3183, "s": 3125, "text": "And this is what results, pretty much acceptable I think:" }, { "code": null, "e": 3345, "s": 3183, "text": "I am sure this can be used mostly for presentations to catch eye attention or to design chemistry oriented web pages. But other uses could be envisioned as well." }, { "code": null, "e": 4087, "s": 3345, "text": "If you are familiar with Networkx [4], you should know that it is very popular because this library is easy to use and well documented, but as far as I know it lacks this feature of making the graph interactive. Fortunately, Pyvis accepts graph objects from Networkx beautifully. Networkx has prebuilt the Zachary’s Karate Club graph [5], where you have 34 members of the club, being 0 and 33 the President and the Sensei which have a conflict and they separate the club in two groups based on influence among members. Bellow is shown the piece of code needed for this graph in pyvis. First we got G with the graph from Networkx. Then we build the pyvis object g4, and method from_nx is used to get the graph into pyvis... as simple as that:" }, { "code": null, "e": 4430, "s": 4087, "text": "Here I must highlight the show_buttons method in line 8, which is used to deploy the physics options allowing the user to change interactively the way the nodes interact each other as if they were connected by springs and having other physical interactions. That makes the dynamics of the graph look like more “natural” and visually is a joy." }, { "code": null, "e": 4619, "s": 4430, "text": "Of course there are other ways to make graphs interactive, using advanced libraries, but in general they are more complex. The simplicity offered by pyvis is something that is appreciated." }, { "code": null, "e": 4777, "s": 4619, "text": "Finally, I just show how these dynamic graphs look in a Streamlit web app. I am not going to discuss how to do the app, I let that as homework to the reader." }, { "code": null, "e": 4819, "s": 4777, "text": "hint: you can see the github repo below 😏" }, { "code": null, "e": 4867, "s": 4819, "text": "If you want you can play with the web app here:" }, { "code": null, "e": 4937, "s": 4867, "text": "https://share.streamlit.io/napoles-uach/streamlit_network/main/app.py" }, { "code": null, "e": 4984, "s": 4937, "text": "If you liked it, please star the github repo 🌟" }, { "code": null, "e": 5034, "s": 4984, "text": "https://github.com/napoles-uach/streamlit_network" }, { "code": null, "e": 5120, "s": 5034, "text": "The code snippets presented here are part of a Colab Notebook that you can find here:" }, { "code": null, "e": 5199, "s": 5120, "text": "https://github.com/napoles-uach/streamlit_network/blob/main/pyvis_sample.ipynb" } ]
Lua - Arithmetic Operators
Following table shows all the arithmetic operators supported by Lua language. Assume variable A holds 10 and variable B holds 20, then − Try the following example to understand all the arithmetic operators available in the Lua programming language − a = 21 b = 10 c = a + b print("Line 1 - Value of c is ", c ) c = a - b print("Line 2 - Value of c is ", c ) c = a * b print("Line 3 - Value of c is ", c ) c = a / b print("Line 4 - Value of c is ", c ) c = a % b print("Line 5 - Value of c is ", c ) c = a^2 print("Line 6 - Value of c is ", c ) c = -a print("Line 7 - Value of c is ", c ) When you execute the above program, it produces the following result − Line 1 - Value of c is 31 Line 2 - Value of c is 11 Line 3 - Value of c is 210 Line 4 - Value of c is 2.1 Line 5 - Value of c is 1 Line 6 - Value of c is 441 Line 7 - Value of c is -21 12 Lectures 2 hours Manish Gupta 80 Lectures 3 hours Sanjeev Mittal 54 Lectures 3.5 hours Mehmet GOKTEPE Print Add Notes Bookmark this page
[ { "code": null, "e": 2240, "s": 2103, "text": "Following table shows all the arithmetic operators supported by Lua language. Assume variable A holds 10 and variable B holds 20, then −" }, { "code": null, "e": 2353, "s": 2240, "text": "Try the following example to understand all the arithmetic operators available in the Lua programming language −" }, { "code": null, "e": 2698, "s": 2353, "text": "a = 21\nb = 10\nc = a + b\n\nprint(\"Line 1 - Value of c is \", c )\nc = a - b\n\nprint(\"Line 2 - Value of c is \", c )\nc = a * b\n\nprint(\"Line 3 - Value of c is \", c )\nc = a / b\n\nprint(\"Line 4 - Value of c is \", c )\nc = a % b\n\nprint(\"Line 5 - Value of c is \", c )\nc = a^2\n\nprint(\"Line 6 - Value of c is \", c )\nc = -a\n\nprint(\"Line 7 - Value of c is \", c )" }, { "code": null, "e": 2769, "s": 2698, "text": "When you execute the above program, it produces the following result −" }, { "code": null, "e": 2962, "s": 2769, "text": "Line 1 - Value of c is \t31\nLine 2 - Value of c is \t11\nLine 3 - Value of c is \t210\nLine 4 - Value of c is \t2.1\nLine 5 - Value of c is \t1\nLine 6 - Value of c is \t441\nLine 7 - Value of c is \t-21\n" }, { "code": null, "e": 2995, "s": 2962, "text": "\n 12 Lectures \n 2 hours \n" }, { "code": null, "e": 3009, "s": 2995, "text": " Manish Gupta" }, { "code": null, "e": 3042, "s": 3009, "text": "\n 80 Lectures \n 3 hours \n" }, { "code": null, "e": 3058, "s": 3042, "text": " Sanjeev Mittal" }, { "code": null, "e": 3093, "s": 3058, "text": "\n 54 Lectures \n 3.5 hours \n" }, { "code": null, "e": 3109, "s": 3093, "text": " Mehmet GOKTEPE" }, { "code": null, "e": 3116, "s": 3109, "text": " Print" }, { "code": null, "e": 3127, "s": 3116, "text": " Add Notes" } ]
How to write a custom adapter for my list view on Android using Kotlin?
This example demonstrates how to write a custom adapter for my list view on Android using Kotlin. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="8dp" android:orientation="vertical"> <ListView android:id="@+id/listView" android:layout_width="match_parent" android:layout_height="wrap_content" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.kt import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ListView import android.widget.TextView import androidx.appcompat.app.AppCompatActivity class MainActivity : AppCompatActivity() { lateinit var listView: ListView var arrayList: ArrayList<MyData> = ArrayList() var adapter: MyAdapter? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) title = "KotlinApp" listView = findViewById(R.id.listView) arrayList.add(MyData(1, " Mashu", "987576443")) arrayList.add(MyData(2, " Azhar", "8787576768")) arrayList.add(MyData(3, " Niyaz", "65757657657")) adapter = MyAdapter(this, arrayList) listView.adapter = adapter } } //Class MyAdapter class MyAdapter(private val context: Context, private val arrayList: java.util.ArrayList<MyData>) : BaseAdapter() { private lateinit var serialNum: TextView private lateinit var name: TextView private lateinit var contactNum: TextView override fun getCount(): Int { return arrayList.size } override fun getItem(position: Int): Any { return position } override fun getItemId(position: Int): Long { return position.toLong() } override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? { var convertView = convertView convertView = LayoutInflater.from(context).inflate(R.layout.row, parent, false) serialNum = convertView.findViewById(R.id.serialNumber) name = convertView.findViewById(R.id.studentName) contactNum = convertView.findViewById(R.id.mobileNum) serialNum.text = " " + arrayList[position].num name.text = arrayList[position].name contactNum.text = arrayList[position].mobileNumber return convertView } } //Class MyData class MyData(var num: Int, var name: String, var mobileNumber: String) Step 4 − Create a layout resource file row.xml and add the following code <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="4dp"> <TextView android:id="@+id/serialNumber" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Number" android:textColor="@color/colorPrimary" android:textSize="16sp" /> <TextView android:id="@+id/studentName" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Name" android:textColor="#000000" android:textSize="16sp" /> <TextView android:id="@+id/mobileNum" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Mobile Number" android:textColor="@android:color/holo_purple" android:textSize="12sp" android:textStyle="bold" /> </LinearLayout> Step 5 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.q11"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen. Click here to download the project code.
[ { "code": null, "e": 1160, "s": 1062, "text": "This example demonstrates how to write a custom adapter for my list view on Android using Kotlin." }, { "code": null, "e": 1289, "s": 1160, "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": 1354, "s": 1289, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 1755, "s": 1354, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:padding=\"8dp\"\n android:orientation=\"vertical\">\n <ListView\n android:id=\"@+id/listView\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\" />\n</LinearLayout>" }, { "code": null, "e": 1810, "s": 1755, "text": "Step 3 − Add the following code to src/MainActivity.kt" }, { "code": null, "e": 3869, "s": 1810, "text": "import android.content.Context\nimport android.os.Bundle\nimport android.view.LayoutInflater\nimport android.view.View\nimport android.view.ViewGroup\nimport android.widget.BaseAdapter\nimport android.widget.ListView\nimport android.widget.TextView\nimport androidx.appcompat.app.AppCompatActivity\nclass MainActivity : AppCompatActivity() {\n lateinit var listView: ListView\n var arrayList: ArrayList<MyData> = ArrayList()\n var adapter: MyAdapter? = null\n override fun onCreate(savedInstanceState: Bundle?) {\n super.onCreate(savedInstanceState)\n setContentView(R.layout.activity_main)\n title = \"KotlinApp\"\n listView = findViewById(R.id.listView)\n arrayList.add(MyData(1, \" Mashu\", \"987576443\"))\n arrayList.add(MyData(2, \" Azhar\", \"8787576768\"))\n arrayList.add(MyData(3, \" Niyaz\", \"65757657657\"))\n adapter = MyAdapter(this, arrayList)\n listView.adapter = adapter\n }\n}\n//Class MyAdapter\nclass MyAdapter(private val context: Context, private val arrayList: java.util.ArrayList<MyData>) : BaseAdapter() {\n private lateinit var serialNum: TextView\n private lateinit var name: TextView\n private lateinit var contactNum: TextView\n override fun getCount(): Int {\n return arrayList.size\n }\n override fun getItem(position: Int): Any {\n return position\n }\n override fun getItemId(position: Int): Long {\n return position.toLong()\n }\n override fun getView(position: Int, convertView: View?, parent: ViewGroup): View? {\n var convertView = convertView\n convertView = LayoutInflater.from(context).inflate(R.layout.row, parent, false)\n serialNum = convertView.findViewById(R.id.serialNumber)\n name = convertView.findViewById(R.id.studentName)\n contactNum = convertView.findViewById(R.id.mobileNum)\n serialNum.text = \" \" + arrayList[position].num\n name.text = arrayList[position].name\n contactNum.text = arrayList[position].mobileNumber\n return convertView\n }\n}\n//Class MyData class MyData(var num: Int, var name: String, var mobileNumber: String)\n" }, { "code": null, "e": 3943, "s": 3869, "text": "Step 4 − Create a layout resource file row.xml and add the following code" }, { "code": null, "e": 4963, "s": 3943, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:orientation=\"vertical\"\n android:padding=\"4dp\">\n <TextView\n android:id=\"@+id/serialNumber\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Number\"\n android:textColor=\"@color/colorPrimary\"\n android:textSize=\"16sp\" />\n <TextView\n android:id=\"@+id/studentName\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Name\"\n android:textColor=\"#000000\"\n android:textSize=\"16sp\" />\n <TextView\n android:id=\"@+id/mobileNum\"\n android:layout_width=\"wrap_content\"\n android:layout_height=\"wrap_content\"\n android:text=\"Mobile Number\"\n android:textColor=\"@android:color/holo_purple\"\n android:textSize=\"12sp\"\n android:textStyle=\"bold\" />\n</LinearLayout>" }, { "code": null, "e": 5018, "s": 4963, "text": "Step 5 − Add the following code to androidManifest.xml" }, { "code": null, "e": 5692, "s": 5018, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"com.example.q11\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6042, "s": 5692, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and click the Run icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen." }, { "code": null, "e": 6083, "s": 6042, "text": "Click here to download the project code." } ]
Clojure - REPL
REPL (read-eval-print loop) is a tool for experimenting with Clojure code. It allows you to interact with a running program and quickly try out if things work out as they should. It does this by presenting you with a prompt where you can enter the code. It then reads your input, evaluates it, prints the result, and loops, presenting you with a prompt again. This process enables a quick feedback cycle that isn’t possible in most other languages. A REPL session can be started in Leiningen by typing the following command in the command line. lein repl This will start the following REPL window. You then start evaluating Clojure commands in the REPL window as required. To start a REPL session in Eclipse, click the Menu option, go to Run As → Clojure Application. This will start a new REPL session in a separate window along with the console output. Conceptually, REPL is similar to Secure Shell (SSH). In the same way that you can use SSH to interact with a remote server, Clojure REPL allows you to interact with a running Clojure process. This feature can be very powerful because you can even attach a REPL toa live production app and modify your program as it runs. REPL includes some useful variables, the one widely used is the special variable *1, *2, and *3. These are used to evaluate the results of the three most recent expressions. Following example shows how these variables can be used. user => "Hello" Hello user => "World" World user => (str *2 *1) HelloWorld In the above example, first two strings are being sent to the REPL output window as “Hello” and “World” respectively. Then the *2 and *1 variables are used to recall the last 2 evaluated expressions. Print Add Notes Bookmark this page
[ { "code": null, "e": 2734, "s": 2374, "text": "REPL (read-eval-print loop) is a tool for experimenting with Clojure code. It allows you to interact with a running program and quickly try out if things work out as they should. It does this by presenting you with a prompt where you can enter the code. It then reads your input, evaluates it, prints the result, and loops, presenting you with a prompt again." }, { "code": null, "e": 2823, "s": 2734, "text": "This process enables a quick feedback cycle that isn’t possible in most other languages." }, { "code": null, "e": 2919, "s": 2823, "text": "A REPL session can be started in Leiningen by typing the following command in the command line." }, { "code": null, "e": 2930, "s": 2919, "text": "lein repl\n" }, { "code": null, "e": 2973, "s": 2930, "text": "This will start the following REPL window." }, { "code": null, "e": 3048, "s": 2973, "text": "You then start evaluating Clojure commands in the REPL window as required." }, { "code": null, "e": 3143, "s": 3048, "text": "To start a REPL session in Eclipse, click the Menu option, go to Run As → Clojure Application." }, { "code": null, "e": 3230, "s": 3143, "text": "This will start a new REPL session in a separate window along with the console output." }, { "code": null, "e": 3551, "s": 3230, "text": "Conceptually, REPL is similar to Secure Shell (SSH). In the same way that you can use SSH to interact with a remote server, Clojure REPL allows you to interact with a running Clojure process. This feature can be very powerful because you can even attach a REPL toa live production app and modify your program as it runs." }, { "code": null, "e": 3725, "s": 3551, "text": "REPL includes some useful variables, the one widely used is the special variable *1, *2, and *3. These are used to evaluate the results of the three most recent expressions." }, { "code": null, "e": 3782, "s": 3725, "text": "Following example shows how these variables can be used." }, { "code": null, "e": 3857, "s": 3782, "text": "user => \"Hello\"\nHello\nuser => \"World\"\nWorld\nuser => (str *2 *1)\nHelloWorld" }, { "code": null, "e": 4057, "s": 3857, "text": "In the above example, first two strings are being sent to the REPL output window as “Hello” and “World” respectively. Then the *2 and *1 variables are used to recall the last 2 evaluated expressions." }, { "code": null, "e": 4064, "s": 4057, "text": " Print" }, { "code": null, "e": 4075, "s": 4064, "text": " Add Notes" } ]
Find maximum element of each column in a matrix - GeeksforGeeks
29 Aug, 2021 Given a matrix, the task is to find the maximum element of each column.Examples: Input: [1, 2, 3] [1, 4, 9] [76, 34, 21] Output: 76 34 21 Input: [1, 2, 3, 21] [12, 1, 65, 9] [1, 56, 34, 2] Output: 12 56 65 21 Approach: The idea is to run the loop for no_of_cols. Check each element inside the column and find the maximum element. Finally, print the element. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // C++ program to find the maximum// element of each column.#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to find the maximum// element of each column.void largestInColumn(int mat[][MAX], int rows, int cols){ for (int i = 0; i < cols; i++) { // initialize the maximum element // with 0 int maxm = mat[0][i]; // Run the inner loop for rows for (int j = 1; j < rows; j++) { // check if any element is greater // than the maximum element // of the column and replace it if (mat[j][i] > maxm) maxm = mat[j][i]; } // print the largest element of the column cout << maxm << endl; }} // Driver codeint main(){ int n = 4, m = 4; int mat[][MAX] = { { 3, 4, 1, 8 }, { 1, 4, 9, 11 }, { 76, 34, 21, 1 }, { 2, 1, 4, 5 } }; largestInColumn(mat, n, m); return 0;} // Java program to find maximum// element of each column in a matrixpublic class GFG { // Function to find the maximum // element of each column. public static void largestInColumn(int cols, int[][] arr) { for (int i = 0; i < cols; i++) { // Initialize max to 0 at beginning // of finding max element of each column int maxm = arr[0][i]; for (int j = 1; j < arr[i].length; j++) if (arr[j][i] > maxm) maxm = arr[j][i]; System.out.println(maxm); } } // Driver code public static void main(String[] args) { int[][] arr = new int[][] { { 3, 4, 1, 8 }, { 1, 4, 9, 11 }, { 76, 34, 21, 1 }, { 2, 1, 4, 5 } }; // Calling the function largestInColumn(4, arr); }} # Python3 program to find the maximum# element of each columnMAX = 100 # function to find the maximum# elements of each columndef largestInColumn(mat, rows, cols): for i in range(cols): # initialize the maximum element with 0 maxm = mat[0][i] # run the inner loop for news for j in range(rows): # check if any elements is greater # than the maximum elements # of the column and replace it if mat[j][i] > maxm: maxm = mat[j][i] # print the largest element # of the column print(maxm) # Driver coden, m = 4, 4mat = [[3, 4, 1, 8], [1, 4, 9, 11], [76, 34, 21, 1], [2, 1, 4, 5]] largestInColumn(mat, n, m); # This code is contributed# by Mohit kumar 29 (IIIT gwalior) // C# program to find maximum// element of each column in a matrixusing System; class GFG{ // Function to find the maximum// element of each column.public static void largestInColumn(int cols, int[, ] arr){ for (int i = 0; i < cols; i++) { // Initialize max to 0 at beginning // of finding max element of each column int maxm = arr[0, i]; for (int j = 1; j < arr.GetLength(0); j++) if (arr[j, i] > maxm) maxm = arr[j, i]; Console.WriteLine(maxm); }} // Driver codepublic static void Main(){ int[, ] arr = new int[, ] { { 3, 4, 1, 8 }, { 1, 4, 9, 11 }, { 76, 34, 21, 1 }, { 2, 1, 4, 5 } }; // Calling the function largestInColumn(4, arr);}} // This code is contributed// by Akanksha Rai <?php// PHP program to find the maximum// element of each column.$MAX = 100; // Function to find the maximum// element of each column.function largestInColumn($mat, $rows, $cols){ for ($i = 0; $i < $cols; $i++) { // initialize the maximum element // with 0 $maxm = $mat[0][$i]; // Run the inner loop for rows for ($j = 1; $j < $rows; $j++) { // check if any element is greater // than the maximum element // of the column and replace it if ($mat[$j][$i] > $maxm) $maxm = $mat[$j][$i]; } // print the largest element // of the column echo $maxm, "\n"; }} // Driver code$n = 4;$m = 4;$mat = array(array( 3, 4, 1, 8 ), array( 1, 4, 9, 11 ), array( 76, 34, 21, 1 ), array( 2, 1, 4, 5 )); largestInColumn($mat, $n, $m); // This code is contributed by Sach_Code?> <script> // Javascript program to find maximum// element of each column in a matrix // Function to find the maximum // element of each column. function largestInColumn(cols,arr) { for (let i = 0; i < cols; i++) { // Initialize max to 0 at beginning // of finding max element of each column let maxm = arr[0][i]; for (let j = 1; j < arr[i].length; j++) if (arr[j][i] > maxm) maxm = arr[j][i]; document.write(maxm+"<br>"); } } // Driver code let arr = [[ 3, 4, 1, 8 ], [ 1, 4, 9, 11 ], [ 76, 34, 21, 1 ], [ 2, 1, 4, 5 ]]; // Calling the function largestInColumn(4, arr); // This code is contributed by sravan kumar G </script> 76 34 21 11 Time Complexity: O(n * m), Here n is No. of Rows and m is No. of Column. Sach_Code Akanksha_Rai mohit kumar 29 VishalBachchas shubham_singh sravankumar8128 arorakashish0911 anikakapoor Technical Scripter 2018 Matrix School Programming Technical Scripter Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Sudoku | Backtracking-7 Divide and Conquer | Set 5 (Strassen's Matrix Multiplication) Efficiently compute sums of diagonals of a matrix Program to multiply two matrices Printing all solutions in N-Queen Problem Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 25000, "s": 24972, "text": "\n29 Aug, 2021" }, { "code": null, "e": 25083, "s": 25000, "text": "Given a matrix, the task is to find the maximum element of each column.Examples: " }, { "code": null, "e": 25248, "s": 25083, "text": "Input: [1, 2, 3]\n [1, 4, 9]\n [76, 34, 21]\n\nOutput:\n76\n34\n21\n\nInput: [1, 2, 3, 21]\n [12, 1, 65, 9]\n [1, 56, 34, 2]\nOutput:\n12\n56\n65\n21" }, { "code": null, "e": 25453, "s": 25250, "text": "Approach: The idea is to run the loop for no_of_cols. Check each element inside the column and find the maximum element. Finally, print the element. Below is the implementation of the above approach: " }, { "code": null, "e": 25457, "s": 25453, "text": "C++" }, { "code": null, "e": 25462, "s": 25457, "text": "Java" }, { "code": null, "e": 25470, "s": 25462, "text": "Python3" }, { "code": null, "e": 25473, "s": 25470, "text": "C#" }, { "code": null, "e": 25477, "s": 25473, "text": "PHP" }, { "code": null, "e": 25488, "s": 25477, "text": "Javascript" }, { "code": "// C++ program to find the maximum// element of each column.#include <bits/stdc++.h>using namespace std;const int MAX = 100; // Function to find the maximum// element of each column.void largestInColumn(int mat[][MAX], int rows, int cols){ for (int i = 0; i < cols; i++) { // initialize the maximum element // with 0 int maxm = mat[0][i]; // Run the inner loop for rows for (int j = 1; j < rows; j++) { // check if any element is greater // than the maximum element // of the column and replace it if (mat[j][i] > maxm) maxm = mat[j][i]; } // print the largest element of the column cout << maxm << endl; }} // Driver codeint main(){ int n = 4, m = 4; int mat[][MAX] = { { 3, 4, 1, 8 }, { 1, 4, 9, 11 }, { 76, 34, 21, 1 }, { 2, 1, 4, 5 } }; largestInColumn(mat, n, m); return 0;}", "e": 26471, "s": 25488, "text": null }, { "code": "// Java program to find maximum// element of each column in a matrixpublic class GFG { // Function to find the maximum // element of each column. public static void largestInColumn(int cols, int[][] arr) { for (int i = 0; i < cols; i++) { // Initialize max to 0 at beginning // of finding max element of each column int maxm = arr[0][i]; for (int j = 1; j < arr[i].length; j++) if (arr[j][i] > maxm) maxm = arr[j][i]; System.out.println(maxm); } } // Driver code public static void main(String[] args) { int[][] arr = new int[][] { { 3, 4, 1, 8 }, { 1, 4, 9, 11 }, { 76, 34, 21, 1 }, { 2, 1, 4, 5 } }; // Calling the function largestInColumn(4, arr); }}", "e": 27386, "s": 26471, "text": null }, { "code": "# Python3 program to find the maximum# element of each columnMAX = 100 # function to find the maximum# elements of each columndef largestInColumn(mat, rows, cols): for i in range(cols): # initialize the maximum element with 0 maxm = mat[0][i] # run the inner loop for news for j in range(rows): # check if any elements is greater # than the maximum elements # of the column and replace it if mat[j][i] > maxm: maxm = mat[j][i] # print the largest element # of the column print(maxm) # Driver coden, m = 4, 4mat = [[3, 4, 1, 8], [1, 4, 9, 11], [76, 34, 21, 1], [2, 1, 4, 5]] largestInColumn(mat, n, m); # This code is contributed# by Mohit kumar 29 (IIIT gwalior)", "e": 28213, "s": 27386, "text": null }, { "code": "// C# program to find maximum// element of each column in a matrixusing System; class GFG{ // Function to find the maximum// element of each column.public static void largestInColumn(int cols, int[, ] arr){ for (int i = 0; i < cols; i++) { // Initialize max to 0 at beginning // of finding max element of each column int maxm = arr[0, i]; for (int j = 1; j < arr.GetLength(0); j++) if (arr[j, i] > maxm) maxm = arr[j, i]; Console.WriteLine(maxm); }} // Driver codepublic static void Main(){ int[, ] arr = new int[, ] { { 3, 4, 1, 8 }, { 1, 4, 9, 11 }, { 76, 34, 21, 1 }, { 2, 1, 4, 5 } }; // Calling the function largestInColumn(4, arr);}} // This code is contributed// by Akanksha Rai", "e": 29107, "s": 28213, "text": null }, { "code": "<?php// PHP program to find the maximum// element of each column.$MAX = 100; // Function to find the maximum// element of each column.function largestInColumn($mat, $rows, $cols){ for ($i = 0; $i < $cols; $i++) { // initialize the maximum element // with 0 $maxm = $mat[0][$i]; // Run the inner loop for rows for ($j = 1; $j < $rows; $j++) { // check if any element is greater // than the maximum element // of the column and replace it if ($mat[$j][$i] > $maxm) $maxm = $mat[$j][$i]; } // print the largest element // of the column echo $maxm, \"\\n\"; }} // Driver code$n = 4;$m = 4;$mat = array(array( 3, 4, 1, 8 ), array( 1, 4, 9, 11 ), array( 76, 34, 21, 1 ), array( 2, 1, 4, 5 )); largestInColumn($mat, $n, $m); // This code is contributed by Sach_Code?>", "e": 30041, "s": 29107, "text": null }, { "code": "<script> // Javascript program to find maximum// element of each column in a matrix // Function to find the maximum // element of each column. function largestInColumn(cols,arr) { for (let i = 0; i < cols; i++) { // Initialize max to 0 at beginning // of finding max element of each column let maxm = arr[0][i]; for (let j = 1; j < arr[i].length; j++) if (arr[j][i] > maxm) maxm = arr[j][i]; document.write(maxm+\"<br>\"); } } // Driver code let arr = [[ 3, 4, 1, 8 ], [ 1, 4, 9, 11 ], [ 76, 34, 21, 1 ], [ 2, 1, 4, 5 ]]; // Calling the function largestInColumn(4, arr); // This code is contributed by sravan kumar G </script>", "e": 30859, "s": 30041, "text": null }, { "code": null, "e": 30871, "s": 30859, "text": "76\n34\n21\n11" }, { "code": null, "e": 30947, "s": 30873, "text": "Time Complexity: O(n * m), Here n is No. of Rows and m is No. of Column. " }, { "code": null, "e": 30957, "s": 30947, "text": "Sach_Code" }, { "code": null, "e": 30970, "s": 30957, "text": "Akanksha_Rai" }, { "code": null, "e": 30985, "s": 30970, "text": "mohit kumar 29" }, { "code": null, "e": 31000, "s": 30985, "text": "VishalBachchas" }, { "code": null, "e": 31014, "s": 31000, "text": "shubham_singh" }, { "code": null, "e": 31030, "s": 31014, "text": "sravankumar8128" }, { "code": null, "e": 31047, "s": 31030, "text": "arorakashish0911" }, { "code": null, "e": 31059, "s": 31047, "text": "anikakapoor" }, { "code": null, "e": 31083, "s": 31059, "text": "Technical Scripter 2018" }, { "code": null, "e": 31090, "s": 31083, "text": "Matrix" }, { "code": null, "e": 31109, "s": 31090, "text": "School Programming" }, { "code": null, "e": 31128, "s": 31109, "text": "Technical Scripter" }, { "code": null, "e": 31135, "s": 31128, "text": "Matrix" }, { "code": null, "e": 31233, "s": 31135, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31257, "s": 31233, "text": "Sudoku | Backtracking-7" }, { "code": null, "e": 31319, "s": 31257, "text": "Divide and Conquer | Set 5 (Strassen's Matrix Multiplication)" }, { "code": null, "e": 31369, "s": 31319, "text": "Efficiently compute sums of diagonals of a matrix" }, { "code": null, "e": 31402, "s": 31369, "text": "Program to multiply two matrices" }, { "code": null, "e": 31444, "s": 31402, "text": "Printing all solutions in N-Queen Problem" }, { "code": null, "e": 31462, "s": 31444, "text": "Python Dictionary" }, { "code": null, "e": 31478, "s": 31462, "text": "Arrays in C/C++" }, { "code": null, "e": 31497, "s": 31478, "text": "Inheritance in C++" }, { "code": null, "e": 31522, "s": 31497, "text": "Reverse a string in Java" } ]
Creating Interactive Data Tables in Plotly Dash | by Akash Kaul | Towards Data Science
Plotly Dash is an incredibly powerful framework that allows you to create fully functional data visualization dashboards. Using Dash, you can create a full front-end experience using only Python. The library does a great job of abstracting away from the complicated HTML, CSS, and JS associated with all of the different web app components. Check out this great article from Neptune.ai for a comprehensive overview of all the different visualizations available in Plotly. While this is very nice, it sometimes becomes confusing. For example, Dash provides the dash_table.DataTable component, which is a table that comes with lots of prebuilt, ready-to-use functionalities. However, some of these features are hard to find or understand, and so getting the table to work exactly as you imagined is very tricky. So, I decided to document two table features that are not very well advertised, but which I feel are extremely important to creating a truly dynamic table. Adding click events to your data table is a great way to make your dashboard more interactive. Thankfully, this one actually isn’t too difficult. Using the active_cell component of the DataTable, you can easily get the data of a cell the user clicks on. A callback using active_cell would look something like this: @app.callback( Output('output_div', 'children'), Input('data_table', 'active_cell'), State('data_table', 'data'))def getActiveCell(active_cell, data): if active_cell: col = active_cell['column_id'] row = active_cell['row'] cellData = data[row][col] return html.P(f'row: {row}, col: {col}, value: {cellData}') return html.P('no cell selected') The input is the active_cell component, which means selecting a cell is what causes this callback to fire. Also, note how the callback is sensitive to the data of the table. Without this, you can only access the row and column of the selected cell and not the actual value inside. Using this callback in a full app would look something like this: app = dash.Dash(__name__)app.layout = html.Div([ dash_table.DataTable( id='data_table', columns=[{ 'name': 'Column {}'.format(i), 'id': 'column-{}'.format(i), } for i in range(1, 5)], data=[ {'column-{}'.format(i): (j + (i-1)*5) for i in range(1, 5)} for j in range(5) ] ), html.Div(id='output_div')])@app.callback( Output('output_div', 'children'), Input('data_table', 'active_cell'), State('data_table', 'data'))def getActiveCell(active_cell, data): if active_cell: col = active_cell['column_id'] row = active_cell['row'] cellData = data[row][col] return html.P(f'row: {row}, col: {col}, value: {cellData}') return html.P('no cell selected')if __name__ == '__main__': app.run_server(debug=True) Here’s what the code looks like in action: This option is great for dashboards that need to display information in real-time (i.e. a dashboard that monitors the usage of some service). The live updates are divided into 2 main ideas. In order to update the table periodically, you have to set up an interval for how often the data should change. This is done with the dcc.Interval component from Dash. This component stores a value, n_intervals, which tracks how many intervals of some specified length have passed. You can see a full example of using the Interval for updates in the Dash documentation. The declaration for the dcc.Interval component looks like this: dcc.Interval( id='interval-component', interval=1*1000, # in milliseconds n_intervals=0 ) And the callback for the n_intervals component looks like this: @app.callback( Output('component-to-update', 'property'), Input('interval-component', 'n_intervals'))def update(n_intervals): if n_intervals > 0: # update table data Now that we have a way to periodically perform some action, we need to use this method to update the table data. We can do this by modifying the callback above. All we have to do is change the output to the data attribute of the table, as well as add a state for data. This new callback looks like this: @app.callback( Output('data_table', 'data'), Input('interval-component', 'n_intervals'), [State('data_table', 'data'), State('data_table', 'columns')])def updateData(n, data, columns): if n > 0: data.append({c['id']: n for c in columns}) return data This callback takes in the data already in the table and appends a new row. Adding this callback to the app detailed above, along with adding the dcc.Interval component to the layout creates the following dashboard. Note: It’s a good idea to have the interval controlled by a toggle or switch so that it doesn’t run forever. You can do this by updating the disabled attribute of the dcc.Interval in a callback. In this short blog, we saw two methods of adding extra functionality to a Dash DataTable. Adding click events and live updates are both awesome ways to make your data table more interactive, more flexible, and more powerful. Try out these features in your own dashboards to truly take your visualization to the next level. If you liked this blog, let me know! Connect with me on LinkedIn!
[ { "code": null, "e": 513, "s": 172, "text": "Plotly Dash is an incredibly powerful framework that allows you to create fully functional data visualization dashboards. Using Dash, you can create a full front-end experience using only Python. The library does a great job of abstracting away from the complicated HTML, CSS, and JS associated with all of the different web app components." }, { "code": null, "e": 644, "s": 513, "text": "Check out this great article from Neptune.ai for a comprehensive overview of all the different visualizations available in Plotly." }, { "code": null, "e": 1138, "s": 644, "text": "While this is very nice, it sometimes becomes confusing. For example, Dash provides the dash_table.DataTable component, which is a table that comes with lots of prebuilt, ready-to-use functionalities. However, some of these features are hard to find or understand, and so getting the table to work exactly as you imagined is very tricky. So, I decided to document two table features that are not very well advertised, but which I feel are extremely important to creating a truly dynamic table." }, { "code": null, "e": 1284, "s": 1138, "text": "Adding click events to your data table is a great way to make your dashboard more interactive. Thankfully, this one actually isn’t too difficult." }, { "code": null, "e": 1392, "s": 1284, "text": "Using the active_cell component of the DataTable, you can easily get the data of a cell the user clicks on." }, { "code": null, "e": 1453, "s": 1392, "text": "A callback using active_cell would look something like this:" }, { "code": null, "e": 1839, "s": 1453, "text": "@app.callback( Output('output_div', 'children'), Input('data_table', 'active_cell'), State('data_table', 'data'))def getActiveCell(active_cell, data): if active_cell: col = active_cell['column_id'] row = active_cell['row'] cellData = data[row][col] return html.P(f'row: {row}, col: {col}, value: {cellData}') return html.P('no cell selected')" }, { "code": null, "e": 2120, "s": 1839, "text": "The input is the active_cell component, which means selecting a cell is what causes this callback to fire. Also, note how the callback is sensitive to the data of the table. Without this, you can only access the row and column of the selected cell and not the actual value inside." }, { "code": null, "e": 2186, "s": 2120, "text": "Using this callback in a full app would look something like this:" }, { "code": null, "e": 3009, "s": 2186, "text": "app = dash.Dash(__name__)app.layout = html.Div([ dash_table.DataTable( id='data_table', columns=[{ 'name': 'Column {}'.format(i), 'id': 'column-{}'.format(i), } for i in range(1, 5)], data=[ {'column-{}'.format(i): (j + (i-1)*5) for i in range(1, 5)} for j in range(5) ] ), html.Div(id='output_div')])@app.callback( Output('output_div', 'children'), Input('data_table', 'active_cell'), State('data_table', 'data'))def getActiveCell(active_cell, data): if active_cell: col = active_cell['column_id'] row = active_cell['row'] cellData = data[row][col] return html.P(f'row: {row}, col: {col}, value: {cellData}') return html.P('no cell selected')if __name__ == '__main__': app.run_server(debug=True)" }, { "code": null, "e": 3052, "s": 3009, "text": "Here’s what the code looks like in action:" }, { "code": null, "e": 3194, "s": 3052, "text": "This option is great for dashboards that need to display information in real-time (i.e. a dashboard that monitors the usage of some service)." }, { "code": null, "e": 3242, "s": 3194, "text": "The live updates are divided into 2 main ideas." }, { "code": null, "e": 3410, "s": 3242, "text": "In order to update the table periodically, you have to set up an interval for how often the data should change. This is done with the dcc.Interval component from Dash." }, { "code": null, "e": 3524, "s": 3410, "text": "This component stores a value, n_intervals, which tracks how many intervals of some specified length have passed." }, { "code": null, "e": 3612, "s": 3524, "text": "You can see a full example of using the Interval for updates in the Dash documentation." }, { "code": null, "e": 3676, "s": 3612, "text": "The declaration for the dcc.Interval component looks like this:" }, { "code": null, "e": 3822, "s": 3676, "text": "dcc.Interval( id='interval-component', interval=1*1000, # in milliseconds n_intervals=0 )" }, { "code": null, "e": 3886, "s": 3822, "text": "And the callback for the n_intervals component looks like this:" }, { "code": null, "e": 4090, "s": 3886, "text": "@app.callback( Output('component-to-update', 'property'), Input('interval-component', 'n_intervals'))def update(n_intervals): if n_intervals > 0: # update table data" }, { "code": null, "e": 4203, "s": 4090, "text": "Now that we have a way to periodically perform some action, we need to use this method to update the table data." }, { "code": null, "e": 4359, "s": 4203, "text": "We can do this by modifying the callback above. All we have to do is change the output to the data attribute of the table, as well as add a state for data." }, { "code": null, "e": 4394, "s": 4359, "text": "This new callback looks like this:" }, { "code": null, "e": 4666, "s": 4394, "text": "@app.callback( Output('data_table', 'data'), Input('interval-component', 'n_intervals'), [State('data_table', 'data'), State('data_table', 'columns')])def updateData(n, data, columns): if n > 0: data.append({c['id']: n for c in columns}) return data" }, { "code": null, "e": 4742, "s": 4666, "text": "This callback takes in the data already in the table and appends a new row." }, { "code": null, "e": 4882, "s": 4742, "text": "Adding this callback to the app detailed above, along with adding the dcc.Interval component to the layout creates the following dashboard." }, { "code": null, "e": 5077, "s": 4882, "text": "Note: It’s a good idea to have the interval controlled by a toggle or switch so that it doesn’t run forever. You can do this by updating the disabled attribute of the dcc.Interval in a callback." }, { "code": null, "e": 5302, "s": 5077, "text": "In this short blog, we saw two methods of adding extra functionality to a Dash DataTable. Adding click events and live updates are both awesome ways to make your data table more interactive, more flexible, and more powerful." }, { "code": null, "e": 5400, "s": 5302, "text": "Try out these features in your own dashboards to truly take your visualization to the next level." }, { "code": null, "e": 5437, "s": 5400, "text": "If you liked this blog, let me know!" } ]
ConcurrentHashMap in Java - GeeksforGeeks
22 Mar, 2021 Prerequisites: ConcurrentMap The ConcurrentHashMap class is introduced in JDK 1.5 belongs to java.util.concurrent package, which implements ConcurrentMap as well as to Serializable interface also. ConcurrentHashMap is an enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance-wise HashMap is not up to the mark. Key points of ConcurrentHashMap: The underlined data structure for ConcurrentHashMap is Hashtable. ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications. At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap. In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level. The default concurrency-level of ConcurrentHashMap is 16. In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads. Inserting null objects is not possible in ConcurrentHashMap as a key or value. Declaration: public class ConcurrentHashMap<K,​V> extends AbstractMap<K,​V> implements ConcurrentMap<K,​V>, Serializable Here, K is the key Object type and V is the value Object type. The Hierarchy of ConcurrentHashMap It implements Serializable, ConcurrentMap<K,​ V>, Map<K,​ V> interfaces and extends AbstractMap<K, ​V> class. Constructors of ConcurrentHashMap Concurrency-Level: It is the number of threads concurrently updating the map. The implementation performs internal sizing to try to accommodate this many threads. Load-Factor: It’s a threshold, used to control resizing. Initial Capacity: Accommodation of a certain number of elements initially provided by the implementation. if the capacity of this map is 10. It means that it can store 10 entries. 1. ConcurrentHashMap(): Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16). ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(); 2. ConcurrentHashMap(int initialCapacity): Creates a new, empty map with the specified initial capacity, and with default load factor (0.75) and concurrencyLevel (16). ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity); 3. ConcurrentHashMap(int initialCapacity, float loadFactor): Creates a new, empty map with the specified initial capacity and load factor and with the default concurrencyLevel (16). ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity, float loadFactor); 4. ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel): Creates a new, empty map with the specified initial capacity, load factor, and concurrency level. ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity, float loadFactor, int concurrencyLevel); 5. ConcurrentHashMap(Map m): Creates a new map with the same mappings as the given map. ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(Map m); Example: Java // Java program to demonstrate working of ConcurrentHashMap import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { // create an instance of // ConcurrentHashMap ConcurrentHashMap<Integer, String> m = new ConcurrentHashMap<>(); // Insert mappings using // put method m.put(100, "Hello"); m.put(101, "Geeks"); m.put(102, "Geeks"); // Here we cant add Hello because 101 key // is already present in ConcurrentHashMap object m.putIfAbsent(101, "Hello"); // We can remove entry because 101 key // is associated with For value m.remove(101, "Geeks"); // Now we can add Hello m.putIfAbsent(103, "Hello"); // We cant replace Hello with For m.replace(101, "Hello", "For"); System.out.println(m); }} {100=Hello, 102=Geeks, 103=Hello} Basic Operations on ConcurrentHashMap 1. Adding Elements To insert mappings into a ConcurrentHashMap, we can use put() or putAll() methods. The below example code explains these two methods. Java // Java program to demonstrate adding// elements to the ConcurrentHashMap import java.util.*;import java.util.concurrent.ConcurrentHashMap; public class AddingElementsToConcuurentHashMap { public static void main(String[] args) { // Creating ConcurrentHashMap ConcurrentHashMap<String, String> my_cmmap = new ConcurrentHashMap<String, String>(); // Adding elements to the map // using put() method my_cmmap.put("1", "1"); my_cmmap.put("2", "1"); my_cmmap.put("3", "1"); my_cmmap.put("4", "1"); my_cmmap.put("5", "1"); my_cmmap.put("6", "1"); // Printing the map System.out.println("Mappings of my_cmmap : " + my_cmmap); // create another concurrentHashMap ConcurrentHashMap<String, String> new_chm = new ConcurrentHashMap<>(); // copy mappings from my_cmmap to new_chm new_chm.putAll(my_cmmap); // Displaying the new map System.out.println("New mappings are: " + new_chm); }} Mappings of my_cmmap : {1=1, 2=1, 3=1, 4=1, 5=1, 6=1} New mappings are: {1=1, 2=1, 3=1, 4=1, 5=1, 6=1} 2. Removing Elements To remove a mapping, we can use remove(Object key) method of class ConcurrentHashmap. If the key does not exist in the map, then this function does nothing. To clear the entire map, we can use the clear() method. Java // Java program to demonstrate removing// elements from ConcurrentHashMap import java.util.*;import java.util.concurrent.ConcurrentHashMap; public class RemoveElementsFromConcurrentHashMap { public static void main(String[] args) { // Creating ConcurrentHashMap Map<String, String> my_cmmap = new ConcurrentHashMap<String, String>(); // Adding elements to the map // using put() method my_cmmap.put("1", "1"); my_cmmap.put("2", "1"); my_cmmap.put("3", "1"); my_cmmap.put("4", "1"); my_cmmap.put("5", "1"); my_cmmap.put("6", "1"); // Printing the map System.out.println("Map: " + my_cmmap); System.out.println(); // Removing the mapping // with existing key 6 // using remove() method String valueRemoved = my_cmmap.remove("6"); // Printing the map after remove() System.out.println( "After removing mapping with key 6:"); System.out.println("Map: " + my_cmmap); System.out.println("Value removed: " + valueRemoved); System.out.println(); // Removing the mapping // with non-existing key 10 // using remove() method valueRemoved = my_cmmap.remove("10"); // Printing the map after remove() System.out.println( "After removing mapping with key 10:"); System.out.println("Map: " + my_cmmap); System.out.println("Value removed: " + valueRemoved); System.out.println(); // Now clear the map using clear() my_cmmap.clear(); // Print the clea Map System.out.println("Map after use of clear(): " + my_cmmap); }} Map: {1=1, 2=1, 3=1, 4=1, 5=1, 6=1} After removing mapping with key 6: Map: {1=1, 2=1, 3=1, 4=1, 5=1} Value removed: 1 After removing mapping with key 10: Map: {1=1, 2=1, 3=1, 4=1, 5=1} Value removed: null Map after use of clear(): {} 3. Accessing the Elements We can access the elements of a ConcurrentHashMap using the get() method, the example of this is given below. Java // Java Program Demonstrate accessing// elements of ConcurrentHashMap import java.util.concurrent.*; class AccessingElementsOfConcurrentHashMap { public static void main(String[] args) { // create an instance of ConcurrentHashMap ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); // insert mappings using put method chm.put(100, "Geeks"); chm.put(101, "for"); chm.put(102, "Geeks"); chm.put(103, "Contribute"); // Displaying the HashMap System.out.println("The Mappings are: "); System.out.println(chm); // Display the value of 100 System.out.println("The Value associated to " + "100 is : " + chm.get(100)); // Getting the value of 103 System.out.println("The Value associated to " + "103 is : " + chm.get(103)); }} The Mappings are: {100=Geeks, 101=for, 102=Geeks, 103=Contribute} The Value associated to 100 is : Geeks The Value associated to 103 is : Contribute 4. Traversing We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentHashMap. Java // Java Program for traversing a// ConcurrentHashMapimport java.util.*;import java.util.concurrent.*; public class TraversingConcurrentHashMap { public static void main(String[] args) { // create an instance of ConcurrentHashMap ConcurrentHashMap<Integer, String> chmap = new ConcurrentHashMap<Integer, String>(); // Add elements using put() chmap.put(8, "Third"); chmap.put(6, "Second"); chmap.put(3, "First"); chmap.put(11, "Fourth"); // Create an Iterator over the // ConcurrentHashMap Iterator<ConcurrentHashMap.Entry<Integer, String> > itr = chmap.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentHashMap.Entry<Integer, String> entry = itr.next(); System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue()); } }} Key = 3, Value = First Key = 6, Value = Second Key = 8, Value = Third Key = 11, Value = Fourth Methods of ConcurrentHashMap K – The type of the keys on the map. V – The type of values mapped in the map. METHOD DESCRIPTION Methods declared in class java.util.AbstractMap METHOD DESCRIPTION Methods declared in interface java.util.concurrent.ConcurrentMap METHOD DESCRIPTION Must Read: Difference between HashMap and ConcurrentHashMap ConcurrentHashMap vs Hashtable HashTable Hashtable is an implementation of Map data structure This is a legacy class in which all methods are synchronized on Hashtable instances using the synchronized keyword. Thread-safe as it’s method are synchronized ConcurrentHashMap ConcurrentHashMap implements Map data structure and also provide thread safety like Hashtable. It works by dividing complete hashtable array into segments or portions and allowing parallel access to those segments. The locking is at a much finer granularity at a hashmap bucket level. Use ConcurrentHashMap when you need very high concurrency in your application. It is a thread-safe without synchronizing the whole map. Reads can happen very fast while the write is done with a lock on segment level or bucket level. There is no locking at the object level. ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it. ConcurrentHashMap does not allow NULL values, so the key can not be null in ConcurrentHashMap ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it, while another is iterating over it. Map ht = new Hashtable(); Map chm = new ConcurrentHashMap(); No No No No (does not allow either null keys or values) Yes Slow due to synchronization overhead. Conclusion: If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable. Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html rclincal Ganeshchowdharysadanala shoryagoswami Java - util package Java-Collections Java-ConcurrentHashMap Java-HashMap Java Java Java-Collections Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Arrays in Java Split() String method in Java with examples For-each loop in Java Arrays.sort() in Java with examples Reverse a string in Java HashMap in Java with Examples Object Oriented Programming (OOPs) Concept in Java Initialize an ArrayList in Java Interfaces in Java ArrayList in Java
[ { "code": null, "e": 24112, "s": 24084, "text": "\n22 Mar, 2021" }, { "code": null, "e": 24141, "s": 24112, "text": "Prerequisites: ConcurrentMap" }, { "code": null, "e": 24503, "s": 24141, "text": "The ConcurrentHashMap class is introduced in JDK 1.5 belongs to java.util.concurrent package, which implements ConcurrentMap as well as to Serializable interface also. ConcurrentHashMap is an enhancement of HashMap as we know that while dealing with Threads in our application HashMap is not a good choice because performance-wise HashMap is not up to the mark." }, { "code": null, "e": 24538, "s": 24503, "text": "Key points of ConcurrentHashMap: " }, { "code": null, "e": 24604, "s": 24538, "text": "The underlined data structure for ConcurrentHashMap is Hashtable." }, { "code": null, "e": 24723, "s": 24604, "text": "ConcurrentHashMap class is thread-safe i.e. multiple threads can operate on a single object without any complications." }, { "code": null, "e": 24867, "s": 24723, "text": "At a time any number of threads are applicable for a read operation without locking the ConcurrentHashMap object which is not there in HashMap." }, { "code": null, "e": 24973, "s": 24867, "text": "In ConcurrentHashMap, the Object is divided into a number of segments according to the concurrency level." }, { "code": null, "e": 25031, "s": 24973, "text": "The default concurrency-level of ConcurrentHashMap is 16." }, { "code": null, "e": 25375, "s": 25031, "text": "In ConcurrentHashMap, at a time any number of threads can perform retrieval operation but for updated in the object, the thread must lock the particular segment in which the thread wants to operate. This type of locking mechanism is known as Segment locking or bucket locking. Hence at a time, 16 update operations can be performed by threads." }, { "code": null, "e": 25454, "s": 25375, "text": "Inserting null objects is not possible in ConcurrentHashMap as a key or value." }, { "code": null, "e": 25467, "s": 25454, "text": "Declaration:" }, { "code": null, "e": 25577, "s": 25467, "text": "public class ConcurrentHashMap<K,​V> extends AbstractMap<K,​V> implements ConcurrentMap<K,​V>, Serializable " }, { "code": null, "e": 25640, "s": 25577, "text": "Here, K is the key Object type and V is the value Object type." }, { "code": null, "e": 25675, "s": 25640, "text": "The Hierarchy of ConcurrentHashMap" }, { "code": null, "e": 25786, "s": 25675, "text": "It implements Serializable, ConcurrentMap<K,​ V>, Map<K,​ V> interfaces and extends AbstractMap<K, ​V> class." }, { "code": null, "e": 25820, "s": 25786, "text": "Constructors of ConcurrentHashMap" }, { "code": null, "e": 25983, "s": 25820, "text": "Concurrency-Level: It is the number of threads concurrently updating the map. The implementation performs internal sizing to try to accommodate this many threads." }, { "code": null, "e": 26040, "s": 25983, "text": "Load-Factor: It’s a threshold, used to control resizing." }, { "code": null, "e": 26220, "s": 26040, "text": "Initial Capacity: Accommodation of a certain number of elements initially provided by the implementation. if the capacity of this map is 10. It means that it can store 10 entries." }, { "code": null, "e": 26353, "s": 26220, "text": "1. ConcurrentHashMap(): Creates a new, empty map with a default initial capacity (16), load factor (0.75) and concurrencyLevel (16)." }, { "code": null, "e": 26410, "s": 26353, "text": "ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>();" }, { "code": null, "e": 26578, "s": 26410, "text": "2. ConcurrentHashMap(int initialCapacity): Creates a new, empty map with the specified initial capacity, and with default load factor (0.75) and concurrencyLevel (16)." }, { "code": null, "e": 26654, "s": 26578, "text": "ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity);" }, { "code": null, "e": 26836, "s": 26654, "text": "3. ConcurrentHashMap(int initialCapacity, float loadFactor): Creates a new, empty map with the specified initial capacity and load factor and with the default concurrencyLevel (16)." }, { "code": null, "e": 26930, "s": 26836, "text": "ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity, float loadFactor);" }, { "code": null, "e": 27111, "s": 26930, "text": "4. ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel): Creates a new, empty map with the specified initial capacity, load factor, and concurrency level." }, { "code": null, "e": 27227, "s": 27111, "text": "ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(int initialCapacity, float loadFactor, int concurrencyLevel);" }, { "code": null, "e": 27315, "s": 27227, "text": "5. ConcurrentHashMap(Map m): Creates a new map with the same mappings as the given map." }, { "code": null, "e": 27377, "s": 27315, "text": "ConcurrentHashMap<K, V> chm = new ConcurrentHashMap<>(Map m);" }, { "code": null, "e": 27386, "s": 27377, "text": "Example:" }, { "code": null, "e": 27391, "s": 27386, "text": "Java" }, { "code": "// Java program to demonstrate working of ConcurrentHashMap import java.util.concurrent.*; class ConcurrentHashMapDemo { public static void main(String[] args) { // create an instance of // ConcurrentHashMap ConcurrentHashMap<Integer, String> m = new ConcurrentHashMap<>(); // Insert mappings using // put method m.put(100, \"Hello\"); m.put(101, \"Geeks\"); m.put(102, \"Geeks\"); // Here we cant add Hello because 101 key // is already present in ConcurrentHashMap object m.putIfAbsent(101, \"Hello\"); // We can remove entry because 101 key // is associated with For value m.remove(101, \"Geeks\"); // Now we can add Hello m.putIfAbsent(103, \"Hello\"); // We cant replace Hello with For m.replace(101, \"Hello\", \"For\"); System.out.println(m); }}", "e": 28287, "s": 27391, "text": null }, { "code": null, "e": 28322, "s": 28287, "text": "{100=Hello, 102=Geeks, 103=Hello}\n" }, { "code": null, "e": 28360, "s": 28322, "text": "Basic Operations on ConcurrentHashMap" }, { "code": null, "e": 28379, "s": 28360, "text": "1. Adding Elements" }, { "code": null, "e": 28513, "s": 28379, "text": "To insert mappings into a ConcurrentHashMap, we can use put() or putAll() methods. The below example code explains these two methods." }, { "code": null, "e": 28518, "s": 28513, "text": "Java" }, { "code": "// Java program to demonstrate adding// elements to the ConcurrentHashMap import java.util.*;import java.util.concurrent.ConcurrentHashMap; public class AddingElementsToConcuurentHashMap { public static void main(String[] args) { // Creating ConcurrentHashMap ConcurrentHashMap<String, String> my_cmmap = new ConcurrentHashMap<String, String>(); // Adding elements to the map // using put() method my_cmmap.put(\"1\", \"1\"); my_cmmap.put(\"2\", \"1\"); my_cmmap.put(\"3\", \"1\"); my_cmmap.put(\"4\", \"1\"); my_cmmap.put(\"5\", \"1\"); my_cmmap.put(\"6\", \"1\"); // Printing the map System.out.println(\"Mappings of my_cmmap : \" + my_cmmap); // create another concurrentHashMap ConcurrentHashMap<String, String> new_chm = new ConcurrentHashMap<>(); // copy mappings from my_cmmap to new_chm new_chm.putAll(my_cmmap); // Displaying the new map System.out.println(\"New mappings are: \" + new_chm); }}", "e": 29583, "s": 28518, "text": null }, { "code": null, "e": 29687, "s": 29583, "text": "Mappings of my_cmmap : {1=1, 2=1, 3=1, 4=1, 5=1, 6=1}\nNew mappings are: {1=1, 2=1, 3=1, 4=1, 5=1, 6=1}\n" }, { "code": null, "e": 29708, "s": 29687, "text": "2. Removing Elements" }, { "code": null, "e": 29922, "s": 29708, "text": "To remove a mapping, we can use remove(Object key) method of class ConcurrentHashmap. If the key does not exist in the map, then this function does nothing. To clear the entire map, we can use the clear() method. " }, { "code": null, "e": 29927, "s": 29922, "text": "Java" }, { "code": "// Java program to demonstrate removing// elements from ConcurrentHashMap import java.util.*;import java.util.concurrent.ConcurrentHashMap; public class RemoveElementsFromConcurrentHashMap { public static void main(String[] args) { // Creating ConcurrentHashMap Map<String, String> my_cmmap = new ConcurrentHashMap<String, String>(); // Adding elements to the map // using put() method my_cmmap.put(\"1\", \"1\"); my_cmmap.put(\"2\", \"1\"); my_cmmap.put(\"3\", \"1\"); my_cmmap.put(\"4\", \"1\"); my_cmmap.put(\"5\", \"1\"); my_cmmap.put(\"6\", \"1\"); // Printing the map System.out.println(\"Map: \" + my_cmmap); System.out.println(); // Removing the mapping // with existing key 6 // using remove() method String valueRemoved = my_cmmap.remove(\"6\"); // Printing the map after remove() System.out.println( \"After removing mapping with key 6:\"); System.out.println(\"Map: \" + my_cmmap); System.out.println(\"Value removed: \" + valueRemoved); System.out.println(); // Removing the mapping // with non-existing key 10 // using remove() method valueRemoved = my_cmmap.remove(\"10\"); // Printing the map after remove() System.out.println( \"After removing mapping with key 10:\"); System.out.println(\"Map: \" + my_cmmap); System.out.println(\"Value removed: \" + valueRemoved); System.out.println(); // Now clear the map using clear() my_cmmap.clear(); // Print the clea Map System.out.println(\"Map after use of clear(): \" + my_cmmap); }}", "e": 31704, "s": 29927, "text": null }, { "code": null, "e": 31943, "s": 31704, "text": "Map: {1=1, 2=1, 3=1, 4=1, 5=1, 6=1}\n\nAfter removing mapping with key 6:\nMap: {1=1, 2=1, 3=1, 4=1, 5=1}\nValue removed: 1\n\nAfter removing mapping with key 10:\nMap: {1=1, 2=1, 3=1, 4=1, 5=1}\nValue removed: null\n\nMap after use of clear(): {}\n" }, { "code": null, "e": 31970, "s": 31943, "text": " 3. Accessing the Elements" }, { "code": null, "e": 32081, "s": 31970, "text": "We can access the elements of a ConcurrentHashMap using the get() method, the example of this is given below. " }, { "code": null, "e": 32086, "s": 32081, "text": "Java" }, { "code": "// Java Program Demonstrate accessing// elements of ConcurrentHashMap import java.util.concurrent.*; class AccessingElementsOfConcurrentHashMap { public static void main(String[] args) { // create an instance of ConcurrentHashMap ConcurrentHashMap<Integer, String> chm = new ConcurrentHashMap<Integer, String>(); // insert mappings using put method chm.put(100, \"Geeks\"); chm.put(101, \"for\"); chm.put(102, \"Geeks\"); chm.put(103, \"Contribute\"); // Displaying the HashMap System.out.println(\"The Mappings are: \"); System.out.println(chm); // Display the value of 100 System.out.println(\"The Value associated to \" + \"100 is : \" + chm.get(100)); // Getting the value of 103 System.out.println(\"The Value associated to \" + \"103 is : \" + chm.get(103)); }}", "e": 33012, "s": 32086, "text": null }, { "code": null, "e": 33163, "s": 33012, "text": "The Mappings are: \n{100=Geeks, 101=for, 102=Geeks, 103=Contribute}\nThe Value associated to 100 is : Geeks\nThe Value associated to 103 is : Contribute\n" }, { "code": null, "e": 33177, "s": 33163, "text": "4. Traversing" }, { "code": null, "e": 33474, "s": 33177, "text": "We can use the Iterator interface to traverse over any structure of the Collection Framework. Since Iterators work with one type of data we use Entry< ? , ? > to resolve the two separate types into a compatible format. Then using the next() method we print the elements of the ConcurrentHashMap. " }, { "code": null, "e": 33479, "s": 33474, "text": "Java" }, { "code": "// Java Program for traversing a// ConcurrentHashMapimport java.util.*;import java.util.concurrent.*; public class TraversingConcurrentHashMap { public static void main(String[] args) { // create an instance of ConcurrentHashMap ConcurrentHashMap<Integer, String> chmap = new ConcurrentHashMap<Integer, String>(); // Add elements using put() chmap.put(8, \"Third\"); chmap.put(6, \"Second\"); chmap.put(3, \"First\"); chmap.put(11, \"Fourth\"); // Create an Iterator over the // ConcurrentHashMap Iterator<ConcurrentHashMap.Entry<Integer, String> > itr = chmap.entrySet().iterator(); // The hasNext() method is used to check if there is // a next element The next() method is used to // retrieve the next element while (itr.hasNext()) { ConcurrentHashMap.Entry<Integer, String> entry = itr.next(); System.out.println(\"Key = \" + entry.getKey() + \", Value = \" + entry.getValue()); } }}", "e": 34593, "s": 33479, "text": null }, { "code": null, "e": 34689, "s": 34593, "text": "Key = 3, Value = First\nKey = 6, Value = Second\nKey = 8, Value = Third\nKey = 11, Value = Fourth\n" }, { "code": null, "e": 34718, "s": 34689, "text": "Methods of ConcurrentHashMap" }, { "code": null, "e": 34755, "s": 34718, "text": "K – The type of the keys on the map." }, { "code": null, "e": 34797, "s": 34755, "text": "V – The type of values mapped in the map." }, { "code": null, "e": 34804, "s": 34797, "text": "METHOD" }, { "code": null, "e": 34816, "s": 34804, "text": "DESCRIPTION" }, { "code": null, "e": 34864, "s": 34816, "text": "Methods declared in class java.util.AbstractMap" }, { "code": null, "e": 34871, "s": 34864, "text": "METHOD" }, { "code": null, "e": 34883, "s": 34871, "text": "DESCRIPTION" }, { "code": null, "e": 34948, "s": 34883, "text": "Methods declared in interface java.util.concurrent.ConcurrentMap" }, { "code": null, "e": 34955, "s": 34948, "text": "METHOD" }, { "code": null, "e": 34967, "s": 34955, "text": "DESCRIPTION" }, { "code": null, "e": 35027, "s": 34967, "text": "Must Read: Difference between HashMap and ConcurrentHashMap" }, { "code": null, "e": 35058, "s": 35027, "text": "ConcurrentHashMap vs Hashtable" }, { "code": null, "e": 35069, "s": 35058, "text": "HashTable " }, { "code": null, "e": 35122, "s": 35069, "text": "Hashtable is an implementation of Map data structure" }, { "code": null, "e": 35238, "s": 35122, "text": "This is a legacy class in which all methods are synchronized on Hashtable instances using the synchronized keyword." }, { "code": null, "e": 35282, "s": 35238, "text": "Thread-safe as it’s method are synchronized" }, { "code": null, "e": 35301, "s": 35282, "text": "ConcurrentHashMap " }, { "code": null, "e": 35396, "s": 35301, "text": "ConcurrentHashMap implements Map data structure and also provide thread safety like Hashtable." }, { "code": null, "e": 35516, "s": 35396, "text": "It works by dividing complete hashtable array into segments or portions and allowing parallel access to those segments." }, { "code": null, "e": 35586, "s": 35516, "text": "The locking is at a much finer granularity at a hashmap bucket level." }, { "code": null, "e": 35665, "s": 35586, "text": "Use ConcurrentHashMap when you need very high concurrency in your application." }, { "code": null, "e": 35722, "s": 35665, "text": "It is a thread-safe without synchronizing the whole map." }, { "code": null, "e": 35819, "s": 35722, "text": "Reads can happen very fast while the write is done with a lock on segment level or bucket level." }, { "code": null, "e": 35860, "s": 35819, "text": "There is no locking at the object level." }, { "code": null, "e": 35995, "s": 35860, "text": "ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it while another is iterating over it." }, { "code": null, "e": 36089, "s": 35995, "text": "ConcurrentHashMap does not allow NULL values, so the key can not be null in ConcurrentHashMap" }, { "code": null, "e": 36225, "s": 36089, "text": "ConcurrentHashMap doesn’t throw a ConcurrentModificationException if one thread tries to modify it, while another is iterating over it." }, { "code": null, "e": 36251, "s": 36225, "text": "Map ht = new Hashtable();" }, { "code": null, "e": 36286, "s": 36251, "text": "Map chm = new ConcurrentHashMap();" }, { "code": null, "e": 36289, "s": 36286, "text": "No" }, { "code": null, "e": 36292, "s": 36289, "text": "No" }, { "code": null, "e": 36295, "s": 36292, "text": "No" }, { "code": null, "e": 36342, "s": 36295, "text": "No (does not allow either null keys or values)" }, { "code": null, "e": 36346, "s": 36342, "text": "Yes" }, { "code": null, "e": 36384, "s": 36346, "text": "Slow due to synchronization overhead." }, { "code": null, "e": 36396, "s": 36384, "text": "Conclusion:" }, { "code": null, "e": 36529, "s": 36396, "text": "If a thread-safe highly-concurrent implementation is desired, then it is recommended to use ConcurrentHashMap in place of Hashtable." }, { "code": null, "e": 36645, "s": 36529, "text": "Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html" }, { "code": null, "e": 36654, "s": 36645, "text": "rclincal" }, { "code": null, "e": 36678, "s": 36654, "text": "Ganeshchowdharysadanala" }, { "code": null, "e": 36692, "s": 36678, "text": "shoryagoswami" }, { "code": null, "e": 36712, "s": 36692, "text": "Java - util package" }, { "code": null, "e": 36729, "s": 36712, "text": "Java-Collections" }, { "code": null, "e": 36752, "s": 36729, "text": "Java-ConcurrentHashMap" }, { "code": null, "e": 36765, "s": 36752, "text": "Java-HashMap" }, { "code": null, "e": 36770, "s": 36765, "text": "Java" }, { "code": null, "e": 36775, "s": 36770, "text": "Java" }, { "code": null, "e": 36792, "s": 36775, "text": "Java-Collections" }, { "code": null, "e": 36890, "s": 36792, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36899, "s": 36890, "text": "Comments" }, { "code": null, "e": 36912, "s": 36899, "text": "Old Comments" }, { "code": null, "e": 36927, "s": 36912, "text": "Arrays in Java" }, { "code": null, "e": 36971, "s": 36927, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36993, "s": 36971, "text": "For-each loop in Java" }, { "code": null, "e": 37029, "s": 36993, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 37054, "s": 37029, "text": "Reverse a string in Java" }, { "code": null, "e": 37084, "s": 37054, "text": "HashMap in Java with Examples" }, { "code": null, "e": 37135, "s": 37084, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 37167, "s": 37135, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 37186, "s": 37167, "text": "Interfaces in Java" } ]
What is Redux Toolkit and why it is more preferred? - GeeksforGeeks
27 Oct, 2020 While working as a Front-end Developer or Full Stack Developer, many engineers encountered Redux. But Recently Redux Team launched Redux Toolkit, an officially recommended and a SOPE library that stands for Simple, Opinionated, Powerful, and Effective state management library. It allows us to write more efficient code, speed up the development process, and automatically apply the best-recommended practices. It was mainly created to solve the THREE MAJOR ISSUES with Redux: Configuring a Redux store is too complicated Have to add a lot of packages to build a large scale application Redux requires too much boilerplate code which makes it cumbersome to write efficient and clean code. It also provides the automatic support for Redux Dev-tools Extension and for immer.js library which is a great tool to deal with immutable objects. You can also use the various predefined functions of Redux Toolkit which not only speeds up the process but also saves time. Dependencies that comes along with Redux Toolkit: immer redux redux-thunk reselect Install: # NPM npm install @reduxjs/toolkit # Yarn yarn add @reduxjs/toolkit What Extra Features Are Provided: A configureStore() function which provides automatic support for Redux-thunk, Redux DevTools Extension, and also passes the default middleware. A createReducer() utility which provides support for immer library that allows writing the immutable code mutably. A createAction() utility that returns an action creator function. A createSlice() function that comes in handy to replace create action and create Reducer functions with a single function. A createAsyncThunk() that takes Redux strings as arguments and returns a Promise. A createEntityAdapter() utility that helps to perform CRUD operations. A Basic Comparison Between Redux and Redux Toolkit(with React): Redux: Creating Store and reducers.JavascriptJavascriptconst addHandler=(state=0,action)=>{if(action.type==='ADD'){ return state+1;}return state;} const store = createStore(addHandler); store.dispatch({type:'ADD'});Redux Toolkit: Creating Store and reducers.JavascriptJavascript// Action Creatorsconst add = createAction('ADD'); const addHandler = createReducer(0, { [add]: state => state + 1}) const store = configureStore({ reducer: addHandler}) store.dispatch(add()); Redux: Creating Store and reducers.JavascriptJavascriptconst addHandler=(state=0,action)=>{if(action.type==='ADD'){ return state+1;}return state;} const store = createStore(addHandler); store.dispatch({type:'ADD'}); Redux: Creating Store and reducers. Javascript const addHandler=(state=0,action)=>{if(action.type==='ADD'){ return state+1;}return state;} const store = createStore(addHandler); store.dispatch({type:'ADD'}); Redux Toolkit: Creating Store and reducers.JavascriptJavascript// Action Creatorsconst add = createAction('ADD'); const addHandler = createReducer(0, { [add]: state => state + 1}) const store = configureStore({ reducer: addHandler}) store.dispatch(add()); Redux Toolkit: Creating Store and reducers. Javascript // Action Creatorsconst add = createAction('ADD'); const addHandler = createReducer(0, { [add]: state => state + 1}) const store = configureStore({ reducer: addHandler}) store.dispatch(add()); Using Redux DevTools Extension: React: You have to add a predefined statement while creating the store to access the Redux DevTools.JavascriptJavascriptconst store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());Redux Toolkit: It provides automatic support for Redux DevTools Extension.JavascriptJavascriptconst store = configureStore( reducer:rootReducer ); React: You have to add a predefined statement while creating the store to access the Redux DevTools.JavascriptJavascriptconst store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); React: You have to add a predefined statement while creating the store to access the Redux DevTools. Javascript const store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__()); Redux Toolkit: It provides automatic support for Redux DevTools Extension.JavascriptJavascriptconst store = configureStore( reducer:rootReducer ); Redux Toolkit: It provides automatic support for Redux DevTools Extension. Javascript const store = configureStore( reducer:rootReducer ); Modifying The State: Redux: We need to manually handle and change the state immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ ...state, counter:state.counter+1; } }Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ counter:state.counter+1; } } Redux: We need to manually handle and change the state immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ ...state, counter:state.counter+1; } } Redux: We need to manually handle and change the state immutably. Javascript const initialState={counter:0} const handler=(state=initialState,action){return{ ...state, counter:state.counter+1; } } Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ counter:state.counter+1; } } Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably. Javascript const initialState={counter:0} const handler=(state=initialState,action){return{ counter:state.counter+1; } } Conclusion: Redux Toolkit is beneficial to all Redux users regardless of skill level. It can be added as an internal part of the project at the start or can be added during the internal up-gradation in the existing one. But it is still preferred that you should have the basic knowledge of how to handle and change the state immutably and also should have a glimpse of what is happening under the hood before migrating from Redux to Redux Toolkit. Redux Toolkit is beneficial to all Redux users regardless of skill level. It can be added as an internal part of the project at the start or can be added during the internal up-gradation in the existing one. But it is still preferred that you should have the basic knowledge of how to handle and change the state immutably and also should have a glimpse of what is happening under the hood before migrating from Redux to Redux Toolkit. react-js Redux Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Difference Between PUT and PATCH Request REST API (Introduction) How to execute PHP code using command line ? HTML Cheat Sheet - A Basic Guide to HTML How to redirect to another page in ReactJS ?
[ { "code": null, "e": 26279, "s": 26251, "text": "\n27 Oct, 2020" }, { "code": null, "e": 26756, "s": 26279, "text": "While working as a Front-end Developer or Full Stack Developer, many engineers encountered Redux. But Recently Redux Team launched Redux Toolkit, an officially recommended and a SOPE library that stands for Simple, Opinionated, Powerful, and Effective state management library. It allows us to write more efficient code, speed up the development process, and automatically apply the best-recommended practices. It was mainly created to solve the THREE MAJOR ISSUES with Redux:" }, { "code": null, "e": 26801, "s": 26756, "text": "Configuring a Redux store is too complicated" }, { "code": null, "e": 26866, "s": 26801, "text": "Have to add a lot of packages to build a large scale application" }, { "code": null, "e": 26968, "s": 26866, "text": "Redux requires too much boilerplate code which makes it cumbersome to write efficient and clean code." }, { "code": null, "e": 27241, "s": 26968, "text": "It also provides the automatic support for Redux Dev-tools Extension and for immer.js library which is a great tool to deal with immutable objects. You can also use the various predefined functions of Redux Toolkit which not only speeds up the process but also saves time." }, { "code": null, "e": 27291, "s": 27241, "text": "Dependencies that comes along with Redux Toolkit:" }, { "code": null, "e": 27297, "s": 27291, "text": "immer" }, { "code": null, "e": 27303, "s": 27297, "text": "redux" }, { "code": null, "e": 27315, "s": 27303, "text": "redux-thunk" }, { "code": null, "e": 27324, "s": 27315, "text": "reselect" }, { "code": null, "e": 27333, "s": 27324, "text": "Install:" }, { "code": null, "e": 27402, "s": 27333, "text": "# NPM\nnpm install @reduxjs/toolkit\n\n# Yarn\nyarn add @reduxjs/toolkit" }, { "code": null, "e": 27436, "s": 27402, "text": "What Extra Features Are Provided:" }, { "code": null, "e": 27580, "s": 27436, "text": "A configureStore() function which provides automatic support for Redux-thunk, Redux DevTools Extension, and also passes the default middleware." }, { "code": null, "e": 27695, "s": 27580, "text": "A createReducer() utility which provides support for immer library that allows writing the immutable code mutably." }, { "code": null, "e": 27761, "s": 27695, "text": "A createAction() utility that returns an action creator function." }, { "code": null, "e": 27884, "s": 27761, "text": "A createSlice() function that comes in handy to replace create action and create Reducer functions with a single function." }, { "code": null, "e": 27966, "s": 27884, "text": "A createAsyncThunk() that takes Redux strings as arguments and returns a Promise." }, { "code": null, "e": 28037, "s": 27966, "text": "A createEntityAdapter() utility that helps to perform CRUD operations." }, { "code": null, "e": 28101, "s": 28037, "text": "A Basic Comparison Between Redux and Redux Toolkit(with React):" }, { "code": null, "e": 28585, "s": 28101, "text": "Redux: Creating Store and reducers.JavascriptJavascriptconst addHandler=(state=0,action)=>{if(action.type==='ADD'){ return state+1;}return state;} const store = createStore(addHandler); store.dispatch({type:'ADD'});Redux Toolkit: Creating Store and reducers.JavascriptJavascript// Action Creatorsconst add = createAction('ADD'); const addHandler = createReducer(0, { [add]: state => state + 1}) const store = configureStore({ reducer: addHandler}) store.dispatch(add());" }, { "code": null, "e": 28806, "s": 28585, "text": "Redux: Creating Store and reducers.JavascriptJavascriptconst addHandler=(state=0,action)=>{if(action.type==='ADD'){ return state+1;}return state;} const store = createStore(addHandler); store.dispatch({type:'ADD'});" }, { "code": null, "e": 28842, "s": 28806, "text": "Redux: Creating Store and reducers." }, { "code": null, "e": 28853, "s": 28842, "text": "Javascript" }, { "code": "const addHandler=(state=0,action)=>{if(action.type==='ADD'){ return state+1;}return state;} const store = createStore(addHandler); store.dispatch({type:'ADD'});", "e": 29019, "s": 28853, "text": null }, { "code": null, "e": 29283, "s": 29019, "text": "Redux Toolkit: Creating Store and reducers.JavascriptJavascript// Action Creatorsconst add = createAction('ADD'); const addHandler = createReducer(0, { [add]: state => state + 1}) const store = configureStore({ reducer: addHandler}) store.dispatch(add());" }, { "code": null, "e": 29327, "s": 29283, "text": "Redux Toolkit: Creating Store and reducers." }, { "code": null, "e": 29338, "s": 29327, "text": "Javascript" }, { "code": "// Action Creatorsconst add = createAction('ADD'); const addHandler = createReducer(0, { [add]: state => state + 1}) const store = configureStore({ reducer: addHandler}) store.dispatch(add());", "e": 29539, "s": 29338, "text": null }, { "code": null, "e": 29571, "s": 29539, "text": "Using Redux DevTools Extension:" }, { "code": null, "e": 29969, "s": 29571, "text": "React: You have to add a predefined statement while creating the store to access the Redux DevTools.JavascriptJavascriptconst store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());Redux Toolkit: It provides automatic support for Redux DevTools Extension.JavascriptJavascriptconst store = configureStore( reducer:rootReducer );" }, { "code": null, "e": 30220, "s": 29969, "text": "React: You have to add a predefined statement while creating the store to access the Redux DevTools.JavascriptJavascriptconst store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());" }, { "code": null, "e": 30321, "s": 30220, "text": "React: You have to add a predefined statement while creating the store to access the Redux DevTools." }, { "code": null, "e": 30332, "s": 30321, "text": "Javascript" }, { "code": "const store = createStore( reducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());", "e": 30463, "s": 30332, "text": null }, { "code": null, "e": 30611, "s": 30463, "text": "Redux Toolkit: It provides automatic support for Redux DevTools Extension.JavascriptJavascriptconst store = configureStore( reducer:rootReducer );" }, { "code": null, "e": 30686, "s": 30611, "text": "Redux Toolkit: It provides automatic support for Redux DevTools Extension." }, { "code": null, "e": 30697, "s": 30686, "text": "Javascript" }, { "code": "const store = configureStore( reducer:rootReducer );", "e": 30751, "s": 30697, "text": null }, { "code": null, "e": 30772, "s": 30751, "text": "Modifying The State:" }, { "code": null, "e": 31236, "s": 30772, "text": "Redux: We need to manually handle and change the state immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ ...state, counter:state.counter+1; } }Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ counter:state.counter+1; } }" }, { "code": null, "e": 31454, "s": 31236, "text": "Redux: We need to manually handle and change the state immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ ...state, counter:state.counter+1; } }" }, { "code": null, "e": 31520, "s": 31454, "text": "Redux: We need to manually handle and change the state immutably." }, { "code": null, "e": 31531, "s": 31520, "text": "Javascript" }, { "code": "const initialState={counter:0} const handler=(state=initialState,action){return{ ...state, counter:state.counter+1; } }", "e": 31664, "s": 31531, "text": null }, { "code": null, "e": 31911, "s": 31664, "text": "Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably.JavascriptJavascriptconst initialState={counter:0} const handler=(state=initialState,action){return{ counter:state.counter+1; } }" }, { "code": null, "e": 32019, "s": 31911, "text": "Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably." }, { "code": null, "e": 32030, "s": 32019, "text": "Javascript" }, { "code": "const initialState={counter:0} const handler=(state=initialState,action){return{ counter:state.counter+1; } }", "e": 32150, "s": 32030, "text": null }, { "code": null, "e": 32162, "s": 32150, "text": "Conclusion:" }, { "code": null, "e": 32598, "s": 32162, "text": "Redux Toolkit is beneficial to all Redux users regardless of skill level. It can be added as an internal part of the project at the start or can be added during the internal up-gradation in the existing one. But it is still preferred that you should have the basic knowledge of how to handle and change the state immutably and also should have a glimpse of what is happening under the hood before migrating from Redux to Redux Toolkit." }, { "code": null, "e": 32807, "s": 32598, "text": "Redux Toolkit is beneficial to all Redux users regardless of skill level. It can be added as an internal part of the project at the start or can be added during the internal up-gradation in the existing one. " }, { "code": null, "e": 33035, "s": 32807, "text": "But it is still preferred that you should have the basic knowledge of how to handle and change the state immutably and also should have a glimpse of what is happening under the hood before migrating from Redux to Redux Toolkit." }, { "code": null, "e": 33044, "s": 33035, "text": "react-js" }, { "code": null, "e": 33050, "s": 33044, "text": "Redux" }, { "code": null, "e": 33067, "s": 33050, "text": "Web Technologies" }, { "code": null, "e": 33165, "s": 33067, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33205, "s": 33165, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33250, "s": 33205, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 33293, "s": 33250, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 33354, "s": 33293, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33426, "s": 33354, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 33467, "s": 33426, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 33491, "s": 33467, "text": "REST API (Introduction)" }, { "code": null, "e": 33536, "s": 33491, "text": "How to execute PHP code using command line ?" }, { "code": null, "e": 33577, "s": 33536, "text": "HTML Cheat Sheet - A Basic Guide to HTML" } ]
How to change the color of the alert box in JavaScript?
You can try to run the following code to change the color of the alert box. To change the color of the alert box, use the following custom alert box. We’re using JavaScript library, jQuery to achieve this and will change the color of the alert box to “blue” − Live Demo <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"> </script> <script> function functionAlert(msg, myYes) { var confirmBox = $("#confirm"); confirmBox.find(".message").text(msg); confirmBox.find(".yes").unbind().click(function() { confirmBox.hide(); }); confirmBox.find(".yes").click(myYes); confirmBox.show(); } </script> <style> #confirm { display: none; background-color: #8416f9; color: #FCD116; border: 1px solid #aaa; position: fixed; width: 250px; left: 50%; margin-left: -100px; padding: 6px 8px 8px; box-sizing: border-box; text-align: center; } #confirm button { background-color: #48E5DA; display: inline-block; border-radius: 5px; border: 1px solid #aaa; padding: 5px; text-align: center; width: 80px; cursor: pointer; } #confirm .message { text-align: left; } </style> </head> <body> <div id="confirm"> <div class="message">This is a warning message.</div> <button class="yes">OK</button> </div> <input type="button" value="Click Me" onclick="functionAlert();" /> </body> </html>
[ { "code": null, "e": 1322, "s": 1062, "text": "You can try to run the following code to change the color of the alert box. To change the color of the alert box, use the following custom alert box. We’re using JavaScript library, jQuery to achieve this and will change the color of the alert box to “blue” −" }, { "code": null, "e": 1332, "s": 1322, "text": "Live Demo" }, { "code": null, "e": 2866, "s": 1332, "text": "<!DOCTYPE html>\n<html>\n <head>\n <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\">\n </script>\n <script>\n function functionAlert(msg, myYes) {\n var confirmBox = $(\"#confirm\");\n confirmBox.find(\".message\").text(msg);\n confirmBox.find(\".yes\").unbind().click(function() {\n confirmBox.hide();\n });\n confirmBox.find(\".yes\").click(myYes);\n confirmBox.show();\n }\n </script>\n <style>\n #confirm {\n display: none;\n background-color: #8416f9;\n color: #FCD116;\n border: 1px solid #aaa;\n position: fixed;\n width: 250px;\n left: 50%;\n margin-left: -100px;\n padding: 6px 8px 8px;\n box-sizing: border-box;\n text-align: center;\n }\n #confirm button {\n background-color: #48E5DA;\n display: inline-block;\n border-radius: 5px;\n border: 1px solid #aaa;\n padding: 5px;\n text-align: center;\n width: 80px;\n cursor: pointer;\n }\n #confirm .message {\n text-align: left;\n }\n </style>\n </head>\n <body>\n <div id=\"confirm\">\n <div class=\"message\">This is a warning message.</div>\n <button class=\"yes\">OK</button>\n </div>\n <input type=\"button\" value=\"Click Me\" onclick=\"functionAlert();\" />\n </body>\n</html>" } ]
Char.ConvertToUtf32(String, Int32) Method in C#
The Char.ConvertToUtf32(String, Int32) method in C# is used to convert the value of a UTF-16 encoded character or surrogate pair at a specified position in a string into a Unicode code point. Following is the syntax − public static int ConvertToUtf32 (string str, int index); Above, str is the string that contains a character or surrogate pair. The index parameter is the index position of the character or surrogate pair in str. Let us now see an example to implement the Char.ConvertToUtf32(String, Int32) method − using System; public class Demo { public static void Main(){ int utf = 0x046; string str = Char.ConvertFromUtf32(utf); Console.WriteLine("Final Value = "+str); int res = Char.ConvertToUtf32(str, 0); Console.WriteLine("Actual Value = 0x{0:X}", res); } } This will produce the following output − Final Value = F Actual Value = 0x46 Let us now see another example − using System; public class Demo { public static void Main(){ int utf = 0x057; string str = Char.ConvertFromUtf32(utf); Console.WriteLine("Final Value = "+str); int res = Char.ConvertToUtf32(str, 0); Console.WriteLine("Actual Value = 0x{0:X}", res); } } This will produce the following output − Final Value = W Actual Value = 0x57
[ { "code": null, "e": 1254, "s": 1062, "text": "The Char.ConvertToUtf32(String, Int32) method in C# is used to convert the value of a UTF-16 encoded character or surrogate pair at a specified position in a string into a Unicode code point." }, { "code": null, "e": 1280, "s": 1254, "text": "Following is the syntax −" }, { "code": null, "e": 1338, "s": 1280, "text": "public static int ConvertToUtf32 (string str, int index);" }, { "code": null, "e": 1493, "s": 1338, "text": "Above, str is the string that contains a character or surrogate pair. The index parameter is the index position of the character or surrogate pair in str." }, { "code": null, "e": 1580, "s": 1493, "text": "Let us now see an example to implement the Char.ConvertToUtf32(String, Int32) method −" }, { "code": null, "e": 1869, "s": 1580, "text": "using System;\npublic class Demo {\n public static void Main(){\n int utf = 0x046;\n string str = Char.ConvertFromUtf32(utf);\n Console.WriteLine(\"Final Value = \"+str);\n int res = Char.ConvertToUtf32(str, 0);\n Console.WriteLine(\"Actual Value = 0x{0:X}\", res);\n }\n}" }, { "code": null, "e": 1910, "s": 1869, "text": "This will produce the following output −" }, { "code": null, "e": 1946, "s": 1910, "text": "Final Value = F\nActual Value = 0x46" }, { "code": null, "e": 1979, "s": 1946, "text": "Let us now see another example −" }, { "code": null, "e": 2268, "s": 1979, "text": "using System;\npublic class Demo {\n public static void Main(){\n int utf = 0x057;\n string str = Char.ConvertFromUtf32(utf);\n Console.WriteLine(\"Final Value = \"+str);\n int res = Char.ConvertToUtf32(str, 0);\n Console.WriteLine(\"Actual Value = 0x{0:X}\", res);\n }\n}" }, { "code": null, "e": 2309, "s": 2268, "text": "This will produce the following output −" }, { "code": null, "e": 2345, "s": 2309, "text": "Final Value = W\nActual Value = 0x57" } ]
Addressing modes in 8086 microprocessor
In this section we will see the addressing modes of Intel 8086 microprocessor. There are eight addressing modes in 8086 MPU. These modes are: Immediate Addressing Mode Immediate Addressing Mode Register Addressing Mode Register Addressing Mode Direct Addressing Mode Direct Addressing Mode Register Indirect Addressing Mode Register Indirect Addressing Mode Based Addressing Mode Based Addressing Mode Indexed Addressing Mode Indexed Addressing Mode Based-Index Addressing Mode Based-Index Addressing Mode Based-Index with displacement addressing mode Based-Index with displacement addressing mode The addressing mode in which the data operand is a part of the instruction itself is known as immediate addressing mode. MOV CX, 4929 H, ADD AX, 2387 H, MOV AL, FFH MOV CX, 4929 H, ADD AX, 2387 H, MOV AL, FFH It means that the register is the source of an operand for an instruction. MOV CX, AX; copies the contents of the 16-bit AX register into; the 16-bit CX register),ADD BX, AX MOV CX, AX; copies the contents of the 16-bit AX register into ; the 16-bit CX register), ADD BX, AX The addressing mode in which the effective address of the memory location is written directly in the instruction. MOV AX, [1592H], MOV AL, [0300H] MOV AX, [1592H], MOV AL, [0300H] This addressing mode allows data to be addressed at any memory location through an offset address held in any of the following registers: BP, BX, DI & SI. MOV AX, [BX]; Suppose the register BX contains 4895H, then the contents ; 4895H are moved to AX ADD CX, {BX} MOV AX, [BX]; Suppose the register BX contains 4895H, then the contents ; 4895H are moved to AX ADD CX, {BX} In this addressing mode, the offset address of the operand is given by the sum of contents of the BX/BP registers and 8-bit/16-bit displacement. MOV DX, [BX+04], ADD CL, [BX+08] MOV DX, [BX+04], ADD CL, [BX+08] In this addressing mode, the operands offset address is found by adding the contents of SI or DI register and 8-bit/16-bit displacements. MOV BX, [SI+16], ADD AL, [DI+16] MOV BX, [SI+16], ADD AL, [DI+16] In this addressing mode, the offset address of the operand is computed by summing the base register to the contents of an Index register. ADD CX, [AX+SI], MOV AX, [AX+DI] ADD CX, [AX+SI], MOV AX, [AX+DI] In this addressing mode, the operands offset is computed by adding the base register contents. An Index registers contents and 8 or 16-bit displacement. MOV AX, [BX+DI+08], ADD CX, [BX+SI+16] MOV AX, [BX+DI+08], ADD CX, [BX+SI+16]
[ { "code": null, "e": 1141, "s": 1062, "text": "In this section we will see the addressing modes of Intel 8086 microprocessor." }, { "code": null, "e": 1204, "s": 1141, "text": "There are eight addressing modes in 8086 MPU. These modes are:" }, { "code": null, "e": 1230, "s": 1204, "text": "Immediate Addressing Mode" }, { "code": null, "e": 1256, "s": 1230, "text": "Immediate Addressing Mode" }, { "code": null, "e": 1281, "s": 1256, "text": "Register Addressing Mode" }, { "code": null, "e": 1306, "s": 1281, "text": "Register Addressing Mode" }, { "code": null, "e": 1329, "s": 1306, "text": "Direct Addressing Mode" }, { "code": null, "e": 1352, "s": 1329, "text": "Direct Addressing Mode" }, { "code": null, "e": 1386, "s": 1352, "text": "Register Indirect Addressing Mode" }, { "code": null, "e": 1420, "s": 1386, "text": "Register Indirect Addressing Mode" }, { "code": null, "e": 1442, "s": 1420, "text": "Based Addressing Mode" }, { "code": null, "e": 1464, "s": 1442, "text": "Based Addressing Mode" }, { "code": null, "e": 1488, "s": 1464, "text": "Indexed Addressing Mode" }, { "code": null, "e": 1512, "s": 1488, "text": "Indexed Addressing Mode" }, { "code": null, "e": 1540, "s": 1512, "text": "Based-Index Addressing Mode" }, { "code": null, "e": 1568, "s": 1540, "text": "Based-Index Addressing Mode" }, { "code": null, "e": 1614, "s": 1568, "text": "Based-Index with displacement addressing mode" }, { "code": null, "e": 1660, "s": 1614, "text": "Based-Index with displacement addressing mode" }, { "code": null, "e": 1781, "s": 1660, "text": "The addressing mode in which the data operand is a part of the instruction itself is known as immediate addressing mode." }, { "code": null, "e": 1826, "s": 1781, "text": "MOV CX, 4929 H, ADD AX, 2387 H, MOV AL, FFH\n" }, { "code": null, "e": 1870, "s": 1826, "text": "MOV CX, 4929 H, ADD AX, 2387 H, MOV AL, FFH" }, { "code": null, "e": 1947, "s": 1872, "text": "It means that the register is the source of an operand for an instruction." }, { "code": null, "e": 2047, "s": 1947, "text": "MOV CX, AX; copies the contents of the 16-bit AX register into; the 16-bit CX register),ADD BX, AX\n" }, { "code": null, "e": 2110, "s": 2047, "text": "MOV CX, AX; copies the contents of the 16-bit AX register into" }, { "code": null, "e": 2137, "s": 2110, "text": "; the 16-bit CX register)," }, { "code": null, "e": 2148, "s": 2137, "text": "ADD BX, AX" }, { "code": null, "e": 2264, "s": 2150, "text": "The addressing mode in which the effective address of the memory location is written directly in the instruction." }, { "code": null, "e": 2298, "s": 2264, "text": "MOV AX, [1592H], MOV AL, [0300H]\n" }, { "code": null, "e": 2331, "s": 2298, "text": "MOV AX, [1592H], MOV AL, [0300H]" }, { "code": null, "e": 2488, "s": 2333, "text": "This addressing mode allows data to be addressed at any memory location through an offset address held in any of the following registers: BP, BX, DI & SI." }, { "code": null, "e": 2598, "s": 2488, "text": "MOV AX, [BX]; Suppose the register BX contains 4895H, then the contents\n; 4895H are moved to AX\nADD CX, {BX}\n" }, { "code": null, "e": 2670, "s": 2598, "text": "MOV AX, [BX]; Suppose the register BX contains 4895H, then the contents" }, { "code": null, "e": 2694, "s": 2670, "text": "; 4895H are moved to AX" }, { "code": null, "e": 2707, "s": 2694, "text": "ADD CX, {BX}" }, { "code": null, "e": 2854, "s": 2709, "text": "In this addressing mode, the offset address of the operand is given by the sum of contents of the BX/BP registers and 8-bit/16-bit displacement." }, { "code": null, "e": 2888, "s": 2854, "text": "MOV DX, [BX+04], ADD CL, [BX+08]\n" }, { "code": null, "e": 2921, "s": 2888, "text": "MOV DX, [BX+04], ADD CL, [BX+08]" }, { "code": null, "e": 3061, "s": 2923, "text": "In this addressing mode, the operands offset address is found by adding the contents of SI or DI register and 8-bit/16-bit displacements." }, { "code": null, "e": 3095, "s": 3061, "text": "MOV BX, [SI+16], ADD AL, [DI+16]\n" }, { "code": null, "e": 3128, "s": 3095, "text": "MOV BX, [SI+16], ADD AL, [DI+16]" }, { "code": null, "e": 3268, "s": 3130, "text": "In this addressing mode, the offset address of the operand is computed by summing the base register to the contents of an Index register." }, { "code": null, "e": 3302, "s": 3268, "text": "ADD CX, [AX+SI], MOV AX, [AX+DI]\n" }, { "code": null, "e": 3335, "s": 3302, "text": "ADD CX, [AX+SI], MOV AX, [AX+DI]" }, { "code": null, "e": 3490, "s": 3337, "text": "In this addressing mode, the operands offset is computed by adding the base register contents. An Index registers contents and 8 or 16-bit displacement." }, { "code": null, "e": 3530, "s": 3490, "text": "MOV AX, [BX+DI+08], ADD CX, [BX+SI+16]\n" }, { "code": null, "e": 3569, "s": 3530, "text": "MOV AX, [BX+DI+08], ADD CX, [BX+SI+16]" } ]
How to rename all files of a folder using Java? - GeeksforGeeks
24 Mar, 2018 Often, when transferring files from the camera folder to a workspace where we would like to analyze the pictures, it becomes difficult to deal with long file and type them out again and again when testing them through a code. Also, the number of files might be too large to manually rename each one of them. Hence, it becomes a necessity to automate the renaming process. Examples: Input : Read 50 files from the folder "C:\Users\Anannya Uberoi\Desktop\myfolder": Snapshot 1 (12-05-2017 11-57).png Snapshot 2 (12-05-2017 11-57).png Snapshot 3 (12-05-2017 11-57).png Snapshot 4 (12-05-2017 11-57).png and so on. Output :Renamed to 1.png 2.png 3.png 4.png and so on. // Java program to illustrate// how to rename Multiple Files// together using single programimport java.io.File;import java.io.IOException; public class rename{ public static void main(String[] argv) throws IOException { // Path of folder where files are located String folder_path = "C:\\Users\\Anannya Uberoi\\Desktop\\myfolder"; // creating new folder File myfolder = new File(folder_path); File[] file_array = myfolder.listFiles(); for (int i = 0; i < file_array.length; i++) { if (file_array[i].isFile()) { File myfile = new File(folder_path + "\\" + file_array[i].getName()); String long_file_name = file_array[i].getName(); String[] tokens = long_file_name.split("\\s"); String new_file_name = tokens[1]; System.out.println(long_file_name); System.out.print(new_file_name); // file name format: "Snapshot 11 (12-05-2017 11-57).png" // To Shorten it to "11.png", get the substring which // starts after the first space character in the long // _file_name. myfile.renameTo(new File(folder_path + "\\" + new_file_name + ".png")); } } }} Output: The files get renamed successfully. Note: A double slash (\\) is required since one of the backslash (\) acts as an escape character and the other backslash (\) denotes directory change. This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. java-file-handling Java-I/O Java TechTips Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments HashMap in Java with Examples Interfaces in Java ArrayList in Java Initialize an ArrayList in Java Singleton Class in Java How to Find the Wi-Fi Password Using CMD in Windows? How to Run a Python Script using Docker? Setting up the environment in Java Running Python script on GPU. Docker - COPY Instruction
[ { "code": null, "e": 24840, "s": 24812, "text": "\n24 Mar, 2018" }, { "code": null, "e": 25212, "s": 24840, "text": "Often, when transferring files from the camera folder to a workspace where we would like to analyze the pictures, it becomes difficult to deal with long file and type them out again and again when testing them through a code. Also, the number of files might be too large to manually rename each one of them. Hence, it becomes a necessity to automate the renaming process." }, { "code": null, "e": 25222, "s": 25212, "text": "Examples:" }, { "code": null, "e": 25512, "s": 25222, "text": "Input : Read 50 files from the folder \n\"C:\\Users\\Anannya Uberoi\\Desktop\\myfolder\":\nSnapshot 1 (12-05-2017 11-57).png\nSnapshot 2 (12-05-2017 11-57).png\nSnapshot 3 (12-05-2017 11-57).png\nSnapshot 4 (12-05-2017 11-57).png and so on.\n\nOutput :Renamed to\n1.png\n2.png\n3.png\n4.png and so on.\n" }, { "code": "// Java program to illustrate// how to rename Multiple Files// together using single programimport java.io.File;import java.io.IOException; public class rename{ public static void main(String[] argv) throws IOException { // Path of folder where files are located String folder_path = \"C:\\\\Users\\\\Anannya Uberoi\\\\Desktop\\\\myfolder\"; // creating new folder File myfolder = new File(folder_path); File[] file_array = myfolder.listFiles(); for (int i = 0; i < file_array.length; i++) { if (file_array[i].isFile()) { File myfile = new File(folder_path + \"\\\\\" + file_array[i].getName()); String long_file_name = file_array[i].getName(); String[] tokens = long_file_name.split(\"\\\\s\"); String new_file_name = tokens[1]; System.out.println(long_file_name); System.out.print(new_file_name); // file name format: \"Snapshot 11 (12-05-2017 11-57).png\" // To Shorten it to \"11.png\", get the substring which // starts after the first space character in the long // _file_name. myfile.renameTo(new File(folder_path + \"\\\\\" + new_file_name + \".png\")); } } }}", "e": 26893, "s": 25512, "text": null }, { "code": null, "e": 26901, "s": 26893, "text": "Output:" }, { "code": null, "e": 26938, "s": 26901, "text": "The files get renamed successfully.\n" }, { "code": null, "e": 27089, "s": 26938, "text": "Note: A double slash (\\\\) is required since one of the backslash (\\) acts as an escape character and the other backslash (\\) denotes directory change." }, { "code": null, "e": 27391, "s": 27089, "text": "This article is contributed by Anannya Uberoi. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 27516, "s": 27391, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 27535, "s": 27516, "text": "java-file-handling" }, { "code": null, "e": 27544, "s": 27535, "text": "Java-I/O" }, { "code": null, "e": 27549, "s": 27544, "text": "Java" }, { "code": null, "e": 27558, "s": 27549, "text": "TechTips" }, { "code": null, "e": 27563, "s": 27558, "text": "Java" }, { "code": null, "e": 27661, "s": 27563, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27670, "s": 27661, "text": "Comments" }, { "code": null, "e": 27683, "s": 27670, "text": "Old Comments" }, { "code": null, "e": 27713, "s": 27683, "text": "HashMap in Java with Examples" }, { "code": null, "e": 27732, "s": 27713, "text": "Interfaces in Java" }, { "code": null, "e": 27750, "s": 27732, "text": "ArrayList in Java" }, { "code": null, "e": 27782, "s": 27750, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 27806, "s": 27782, "text": "Singleton Class in Java" }, { "code": null, "e": 27859, "s": 27806, "text": "How to Find the Wi-Fi Password Using CMD in Windows?" }, { "code": null, "e": 27900, "s": 27859, "text": "How to Run a Python Script using Docker?" }, { "code": null, "e": 27935, "s": 27900, "text": "Setting up the environment in Java" }, { "code": null, "e": 27965, "s": 27935, "text": "Running Python script on GPU." } ]
wxPython | Exit() function in wxPython - GeeksforGeeks
15 Jun, 2020 In this article we are going to learn about wx.Exit() which is a inbuilt parent function present in wxPython.Exit() function exits application after calling wx.App.OnExit . Should only be used in an emergency: normally the top-level frame should be deleted (after deleting all other frames) to terminate the application. See wx.CloseEvent and wx.App. Syntax:wx.Exit() Parameters:No parameters are required by Exit() function Coding Example: import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.panel = wx.Panel(self, pos =(100, 100), size =(100, 100)) self.btn = wx.Button(self.panel, id = 2, label ="Exit", pos = wx.DefaultPosition, size =(100, 20)) self.Bind(wx.EVT_BUTTON, self.onclick, self.btn) def onclick(self, e): # EXITS APPLICATION ON CLICKING EXIT BUTTON wx.Exit() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main() Output Window: 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 Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Different ways to create Pandas Dataframe Python String | replace() Python program to convert a list to string Reading and Writing to text files in Python sum() function in Python
[ { "code": null, "e": 24183, "s": 24155, "text": "\n15 Jun, 2020" }, { "code": null, "e": 24356, "s": 24183, "text": "In this article we are going to learn about wx.Exit() which is a inbuilt parent function present in wxPython.Exit() function exits application after calling wx.App.OnExit ." }, { "code": null, "e": 24534, "s": 24356, "text": "Should only be used in an emergency: normally the top-level frame should be deleted (after deleting all other frames) to terminate the application. See wx.CloseEvent and wx.App." }, { "code": null, "e": 24551, "s": 24534, "text": "Syntax:wx.Exit()" }, { "code": null, "e": 24608, "s": 24551, "text": "Parameters:No parameters are required by Exit() function" }, { "code": null, "e": 24624, "s": 24608, "text": "Coding Example:" }, { "code": "import wx class Example(wx.Frame): def __init__(self, *args, **kwargs): super(Example, self).__init__(*args, **kwargs) self.InitUI() def InitUI(self): self.locale = wx.Locale(wx.LANGUAGE_ENGLISH) self.panel = wx.Panel(self, pos =(100, 100), size =(100, 100)) self.btn = wx.Button(self.panel, id = 2, label =\"Exit\", pos = wx.DefaultPosition, size =(100, 20)) self.Bind(wx.EVT_BUTTON, self.onclick, self.btn) def onclick(self, e): # EXITS APPLICATION ON CLICKING EXIT BUTTON wx.Exit() def main(): app = wx.App() ex = Example(None) ex.Show() app.MainLoop() if __name__ == '__main__': main()", "e": 25311, "s": 24624, "text": null }, { "code": null, "e": 25326, "s": 25311, "text": "Output Window:" }, { "code": null, "e": 25333, "s": 25326, "text": "Python" }, { "code": null, "e": 25431, "s": 25333, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25440, "s": 25431, "text": "Comments" }, { "code": null, "e": 25453, "s": 25440, "text": "Old Comments" }, { "code": null, "e": 25471, "s": 25453, "text": "Python Dictionary" }, { "code": null, "e": 25506, "s": 25471, "text": "Read a file line by line in Python" }, { "code": null, "e": 25528, "s": 25506, "text": "Enumerate() in Python" }, { "code": null, "e": 25560, "s": 25528, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 25590, "s": 25560, "text": "Iterate over a list in Python" }, { "code": null, "e": 25632, "s": 25590, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 25658, "s": 25632, "text": "Python String | replace()" }, { "code": null, "e": 25701, "s": 25658, "text": "Python program to convert a list to string" }, { "code": null, "e": 25745, "s": 25701, "text": "Reading and Writing to text files in Python" } ]
Drawing borders around an image using OpenCV
In this program, we will draw borders around an image. We will use the copyMakeBorder() method in the openCV library. This function takes various parameters like image, top, bottom, left, right border values. Step 1: Import cv2. Step 2: Read the image. Step 3: Dall the cv2.copymakeborder() method. Step 4: Display the output. import cv2 image = cv2.imread('testimage.jpg') image = cv2.copyMakeBorder(image, 10,10,10,10, cv2.BORDER_CONSTANT) cv2.imshow('Border', image)
[ { "code": null, "e": 1271, "s": 1062, "text": "In this program, we will draw borders around an image. We will use the copyMakeBorder() method in the openCV library. This function takes various parameters like image, top, bottom, left, right border values." }, { "code": null, "e": 1389, "s": 1271, "text": "Step 1: Import cv2.\nStep 2: Read the image.\nStep 3: Dall the cv2.copymakeborder() method.\nStep 4: Display the output." }, { "code": null, "e": 1533, "s": 1389, "text": "import cv2\n\nimage = cv2.imread('testimage.jpg')\nimage = cv2.copyMakeBorder(image, 10,10,10,10, cv2.BORDER_CONSTANT)\ncv2.imshow('Border', image)" } ]
How to get the Tkinter widget's current x and y coordinates?
Tkinter is widely used to create GUI based applications. It has many toolkits and functions or modules available which can be used to define the different attributes of a particular application. For building GUI applications it provides some widgets including buttons, text boxes and labels. We can customize the position of the widget and its coordinates on the tkinter frame using other functions and libraries. Let us suppose that we have created a text label widget which is having some position in the tkinter frame. Now, to get the actual coordinates of the widget, we can use the geometry methods available in the tkinter’s library. We will use winfo_rootx() and winfo_rooty() functions which return the actual coordinates of the widget with respect to the frame or window. #Import the tkinter library from tkinter import * #Create an instance of the tkinter frame win = Tk() #Define the geometry of the frame win.geometry("600x400") #Define the text-widget my_text= Text(win, height = 5, width = 52) # Create label lab = Label(win, text ="TutorialsPoint.com") #Configure it using other properties lab.config(font =("Helvetica", 20)) #Create a button widget my_button = Button(text="Hello") #Define the position of the widget my_button.place(x=100, y=100) #Update the coordinates with respect to the tkinter frame win.update() #Get the coordinates of both text widget and button widget widget_x1, widget_y1 = my_button.winfo_rootx(), my_button.winfo_rooty() widget_x2, widget_y2 = my_text.winfo_rootx(), my_button.winfo_rooty() lab.pack() print(widget_x1, widget_y1) print(widget_x2, widget_y2) #Keep the window running win.mainloop() Running the above code snippet will print the current position of widget as, 134 157 0 157
[ { "code": null, "e": 1476, "s": 1062, "text": "Tkinter is widely used to create GUI based applications. It has many toolkits and\nfunctions or modules available which can be used to define the different attributes\nof a particular application. For building GUI applications it provides some widgets\nincluding buttons, text boxes and labels. We can customize the position of the\nwidget and its coordinates on the tkinter frame using other functions and libraries." }, { "code": null, "e": 1702, "s": 1476, "text": "Let us suppose that we have created a text label widget which is having some position in the tkinter frame. Now, to get the actual coordinates of the widget, we can use the geometry methods available in the tkinter’s library." }, { "code": null, "e": 1843, "s": 1702, "text": "We will use winfo_rootx() and winfo_rooty() functions which return the actual coordinates of the widget with respect to the frame or window." }, { "code": null, "e": 2716, "s": 1843, "text": "#Import the tkinter library\nfrom tkinter import *\n\n#Create an instance of the tkinter frame\nwin = Tk()\n\n#Define the geometry of the frame\nwin.geometry(\"600x400\")\n\n#Define the text-widget\nmy_text= Text(win, height = 5, width = 52)\n\n# Create label\nlab = Label(win, text =\"TutorialsPoint.com\")\n\n#Configure it using other properties\nlab.config(font =(\"Helvetica\", 20))\n\n#Create a button widget\nmy_button = Button(text=\"Hello\")\n\n#Define the position of the widget\nmy_button.place(x=100, y=100)\n\n#Update the coordinates with respect to the tkinter frame\nwin.update()\n\n#Get the coordinates of both text widget and button widget\nwidget_x1, widget_y1 = my_button.winfo_rootx(),\nmy_button.winfo_rooty()\nwidget_x2, widget_y2 = my_text.winfo_rootx(),\nmy_button.winfo_rooty()\n\nlab.pack()\n\nprint(widget_x1, widget_y1)\nprint(widget_x2, widget_y2)\n\n#Keep the window running\nwin.mainloop()" }, { "code": null, "e": 2793, "s": 2716, "text": "Running the above code snippet will print the current position of widget as," }, { "code": null, "e": 2807, "s": 2793, "text": "134 157\n0 157" } ]
C++ Stdexcept Library - invalid_argument
It is an invalid argument exception and this class defines the type of objects thrown as exceptions to report an invalid argument. Following is the declaration for std::invalid_argument. class invalid_argument; class invalid_argument; none none constructor − Here the string passed as what_arg has the same content as the value returned by member what. In below example for std::invalid_argument. #include <iostream> #include <stdexcept> #include <bitset> #include <string> int main (void) { try { std::bitset<5> mybitset (std::string("01203040")); } catch (const std::invalid_argument& ia) { std::cerr << "Invalid argument: " << ia.what() << '\n'; } return 0; } The output should be like this − Invalid argument: bitset::_M_copy_from_ptr Print Add Notes Bookmark this page
[ { "code": null, "e": 2734, "s": 2603, "text": "It is an invalid argument exception and this class defines the type of objects thrown as exceptions to report an invalid argument." }, { "code": null, "e": 2790, "s": 2734, "text": "Following is the declaration for std::invalid_argument." }, { "code": null, "e": 2814, "s": 2790, "text": "class invalid_argument;" }, { "code": null, "e": 2838, "s": 2814, "text": "class invalid_argument;" }, { "code": null, "e": 2843, "s": 2838, "text": "none" }, { "code": null, "e": 2848, "s": 2843, "text": "none" }, { "code": null, "e": 2956, "s": 2848, "text": "constructor − Here the string passed as what_arg has the same content as the value returned by member what." }, { "code": null, "e": 3000, "s": 2956, "text": "In below example for std::invalid_argument." }, { "code": null, "e": 3290, "s": 3000, "text": "#include <iostream>\n#include <stdexcept>\n#include <bitset>\n#include <string>\nint main (void) {\n try {\n std::bitset<5> mybitset (std::string(\"01203040\"));\n } catch (const std::invalid_argument& ia) {\n std::cerr << \"Invalid argument: \" << ia.what() << '\\n';\n }\n return 0;\n}" }, { "code": null, "e": 3323, "s": 3290, "text": "The output should be like this −" }, { "code": null, "e": 3367, "s": 3323, "text": "Invalid argument: bitset::_M_copy_from_ptr\n" }, { "code": null, "e": 3374, "s": 3367, "text": " Print" }, { "code": null, "e": 3385, "s": 3374, "text": " Add Notes" } ]