title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Understanding CSS Absolute and Relative Units
The absolute length units are fixed in relation to each other. These units are used when the output format is already known. Following are some of the Absolute Length Units − picas (1pc = 12 pt) Let us now see an example − Live Demo <!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; text-decoration-color: blue; font-size: 0.3in; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html> Relative length units in CSS is used to specify a length relative to another length property. Relative to the x-height of the current font Let us see an example using Relative Length Units − Live Demo <!DOCTYPE html> <html> <head> <style> .demo { text-decoration: overline underline; text-decoration-color: blue; font-size: 1.4em; } </style> </head> <body> <h1>Details</h1> <p class="demo">Examination Center near ABC College.</p> <p class="demo2">Exam begins at 9AM.</p> </body> </html>
[ { "code": null, "e": 1237, "s": 1062, "text": "The absolute length units are fixed in relation to each other. These units are used when the output format is already known. Following are some of the Absolute Length Units −" }, { "code": null, "e": 1257, "s": 1237, "text": "picas (1pc = 12 pt)" }, { "code": null, "e": 1285, "s": 1257, "text": "Let us now see an example −" }, { "code": null, "e": 1296, "s": 1285, "text": " Live Demo" }, { "code": null, "e": 1592, "s": 1296, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.demo {\n text-decoration: overline underline;\n text-decoration-color: blue;\n font-size: 0.3in;\n}\n</style>\n</head>\n<body>\n<h1>Details</h1>\n<p class=\"demo\">Examination Center near ABC College.</p>\n<p class=\"demo2\">Exam begins at 9AM.</p>\n</body>\n</html>" }, { "code": null, "e": 1686, "s": 1592, "text": "Relative length units in CSS is used to specify a length relative to another length property." }, { "code": null, "e": 1731, "s": 1686, "text": "Relative to the x-height of the current font" }, { "code": null, "e": 1783, "s": 1731, "text": "Let us see an example using Relative Length Units −" }, { "code": null, "e": 1794, "s": 1783, "text": " Live Demo" }, { "code": null, "e": 2090, "s": 1794, "text": "<!DOCTYPE html>\n<html>\n<head>\n<style>\n.demo {\n text-decoration: overline underline;\n text-decoration-color: blue;\n font-size: 1.4em;\n}\n</style>\n</head>\n<body>\n<h1>Details</h1>\n<p class=\"demo\">Examination Center near ABC College.</p>\n<p class=\"demo2\">Exam begins at 9AM.</p>\n</body>\n</html>" } ]
Java Program to Check if a Given Integer is Positive or Negative - GeeksforGeeks
14 Sep, 2021 Here, the task is to check whether the given integer number is positive or negative. Below are some basic properties of a number. If the Integer is greater than zero then it is a positive integer. If the number is less than zero then it is a negative integer. If the number is equal to zero then it is neither negative nor positive. Input: X = 12 Output: Positive Explanation: Value of X is greater than 0 so it is Positive. Input: x = -5 Output: Negative Explanation: Value of X less than 0 so it is negative. Approach 1: Using Relational operator we can check whether an integer is positive or negative. If number>0 then the number is positive. If number<0 then the number is negative. If a number is neither positive nor negative, the number is equal to 0. Below is the java implementation of the above approach: Java // Java Program to Check if a Given Integer// is Positive or Negative import java.io.*; class GFG { // Function to check positive and negative static String checkPosNeg(int x) { // checks the number is greater than 0 or not if (x > 0) return "Positive"; else if (x < 0) return "Negative"; else return "zero"; } // Driver Function public static void main(String[] args) { // number to be check int firstNumber = 912; System.out.println(firstNumber + " is " + checkPosNeg(firstNumber)); }} 912 is Positive Approach 2: Using Integer.signum() Method Java Integer class provides an inbuilt function signum() to check if a number is positive or negative. It is a static method that accepts a parameter of integer type. It returns 0, if the argument is 0. It returns 1, if the argument>0. It returns -1, if the argument<0. Syntax: public static int signum(int i) Below is the java implementation of the above method. Java // Java Program to Check if a Given// Integer is Positive or Negative import java.io.*; class GFG { // Function to check number is positive or negative static int checkPosNeg(int x) { // inbuilt signum function int ans = Integer.signum(x); return ans; } // Driver function public static void main(String[] args) { int secondNumber = -125; int result = checkPosNeg(secondNumber); if (result == 0) System.out.print(secondNumber + " is Zero"); else if (result == 1) System.out.print(secondNumber + " is Positive"); else System.out.print(secondNumber + " is Negative"); }} -125 is Negative Approach 3 : Using Bit Shift operator In Java, the integers are stored in the 2’s complement. We know that the highest bit of any negative number is 1, and the highest bit of any other number is 0. Bit shift operator (Val>>31) copies the highest bit to every other bit. Therefore, the negative number becomes 11111111 11111111 11111111 11111111, and the positive or zero numbers become 00000000 00000000 00000000 00000000. After this we can use & operator to check whether a number is positive or negative. If ((Val>>31) & 1) is 1 then the number will be negative. If ((Val>>31) & 1) is 0 then the number will be positive. Note: It considers 0 as a positive number. Below is the Java implementation of the above approach: Java // Java Program to Check if a Given// Integer is Positive or Negative import java.io.*; class GFG { // function to check positive and negative integer static String checkPosNeg(int val) { String[] result = { "Positive", "Negative" }; // checks if the number is positive or negative return result[(val >> 31) & 1]; } public static void main(String[] args) { int num; num = -15; System.out.println(num + " is " + checkPosNeg(num)); }} -15 is Negative sumitgumber28 simmytarika5 Java Java Programs Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Hashtable in Java Constructors in Java Different ways of Reading a text file in Java Comparator Interface in Java with Examples Java Math random() method with Examples Convert a String to Character array in Java Java Programming Examples How to Iterate HashMap in Java? Implementing a Linked List in Java using Class Min Heap in Java
[ { "code": null, "e": 23557, "s": 23529, "text": "\n14 Sep, 2021" }, { "code": null, "e": 23687, "s": 23557, "text": "Here, the task is to check whether the given integer number is positive or negative. Below are some basic properties of a number." }, { "code": null, "e": 23754, "s": 23687, "text": "If the Integer is greater than zero then it is a positive integer." }, { "code": null, "e": 23817, "s": 23754, "text": "If the number is less than zero then it is a negative integer." }, { "code": null, "e": 23890, "s": 23817, "text": "If the number is equal to zero then it is neither negative nor positive." }, { "code": null, "e": 24069, "s": 23890, "text": "Input: X = 12\nOutput: Positive\nExplanation: Value of X is greater than 0 so it is Positive.\n\nInput: x = -5\nOutput: Negative\nExplanation: Value of X less than 0 so it is negative." }, { "code": null, "e": 24164, "s": 24069, "text": "Approach 1: Using Relational operator we can check whether an integer is positive or negative." }, { "code": null, "e": 24205, "s": 24164, "text": "If number>0 then the number is positive." }, { "code": null, "e": 24246, "s": 24205, "text": "If number<0 then the number is negative." }, { "code": null, "e": 24318, "s": 24246, "text": "If a number is neither positive nor negative, the number is equal to 0." }, { "code": null, "e": 24374, "s": 24318, "text": "Below is the java implementation of the above approach:" }, { "code": null, "e": 24379, "s": 24374, "text": "Java" }, { "code": "// Java Program to Check if a Given Integer// is Positive or Negative import java.io.*; class GFG { // Function to check positive and negative static String checkPosNeg(int x) { // checks the number is greater than 0 or not if (x > 0) return \"Positive\"; else if (x < 0) return \"Negative\"; else return \"zero\"; } // Driver Function public static void main(String[] args) { // number to be check int firstNumber = 912; System.out.println(firstNumber + \" is \" + checkPosNeg(firstNumber)); }}", "e": 25004, "s": 24379, "text": null }, { "code": null, "e": 25020, "s": 25004, "text": "912 is Positive" }, { "code": null, "e": 25062, "s": 25020, "text": "Approach 2: Using Integer.signum() Method" }, { "code": null, "e": 25229, "s": 25062, "text": "Java Integer class provides an inbuilt function signum() to check if a number is positive or negative. It is a static method that accepts a parameter of integer type." }, { "code": null, "e": 25265, "s": 25229, "text": "It returns 0, if the argument is 0." }, { "code": null, "e": 25298, "s": 25265, "text": "It returns 1, if the argument>0." }, { "code": null, "e": 25332, "s": 25298, "text": "It returns -1, if the argument<0." }, { "code": null, "e": 25341, "s": 25332, "text": "Syntax: " }, { "code": null, "e": 25373, "s": 25341, "text": "public static int signum(int i)" }, { "code": null, "e": 25427, "s": 25373, "text": "Below is the java implementation of the above method." }, { "code": null, "e": 25432, "s": 25427, "text": "Java" }, { "code": "// Java Program to Check if a Given// Integer is Positive or Negative import java.io.*; class GFG { // Function to check number is positive or negative static int checkPosNeg(int x) { // inbuilt signum function int ans = Integer.signum(x); return ans; } // Driver function public static void main(String[] args) { int secondNumber = -125; int result = checkPosNeg(secondNumber); if (result == 0) System.out.print(secondNumber + \" is Zero\"); else if (result == 1) System.out.print(secondNumber + \" is Positive\"); else System.out.print(secondNumber + \" is Negative\"); }}", "e": 26117, "s": 25432, "text": null }, { "code": null, "e": 26134, "s": 26117, "text": "-125 is Negative" }, { "code": null, "e": 26172, "s": 26134, "text": "Approach 3 : Using Bit Shift operator" }, { "code": null, "e": 26332, "s": 26172, "text": "In Java, the integers are stored in the 2’s complement. We know that the highest bit of any negative number is 1, and the highest bit of any other number is 0." }, { "code": null, "e": 26558, "s": 26332, "text": "Bit shift operator (Val>>31) copies the highest bit to every other bit. Therefore, the negative number becomes 11111111 11111111 11111111 11111111, and the positive or zero numbers become 00000000 00000000 00000000 00000000. " }, { "code": null, "e": 26643, "s": 26558, "text": "After this we can use & operator to check whether a number is positive or negative. " }, { "code": null, "e": 26701, "s": 26643, "text": "If ((Val>>31) & 1) is 1 then the number will be negative." }, { "code": null, "e": 26759, "s": 26701, "text": "If ((Val>>31) & 1) is 0 then the number will be positive." }, { "code": null, "e": 26802, "s": 26759, "text": "Note: It considers 0 as a positive number." }, { "code": null, "e": 26858, "s": 26802, "text": "Below is the Java implementation of the above approach:" }, { "code": null, "e": 26863, "s": 26858, "text": "Java" }, { "code": "// Java Program to Check if a Given// Integer is Positive or Negative import java.io.*; class GFG { // function to check positive and negative integer static String checkPosNeg(int val) { String[] result = { \"Positive\", \"Negative\" }; // checks if the number is positive or negative return result[(val >> 31) & 1]; } public static void main(String[] args) { int num; num = -15; System.out.println(num + \" is \" + checkPosNeg(num)); }}", "e": 27363, "s": 26863, "text": null }, { "code": null, "e": 27379, "s": 27363, "text": "-15 is Negative" }, { "code": null, "e": 27393, "s": 27379, "text": "sumitgumber28" }, { "code": null, "e": 27406, "s": 27393, "text": "simmytarika5" }, { "code": null, "e": 27411, "s": 27406, "text": "Java" }, { "code": null, "e": 27425, "s": 27411, "text": "Java Programs" }, { "code": null, "e": 27430, "s": 27425, "text": "Java" }, { "code": null, "e": 27528, "s": 27430, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27537, "s": 27528, "text": "Comments" }, { "code": null, "e": 27550, "s": 27537, "text": "Old Comments" }, { "code": null, "e": 27568, "s": 27550, "text": "Hashtable in Java" }, { "code": null, "e": 27589, "s": 27568, "text": "Constructors in Java" }, { "code": null, "e": 27635, "s": 27589, "text": "Different ways of Reading a text file in Java" }, { "code": null, "e": 27678, "s": 27635, "text": "Comparator Interface in Java with Examples" }, { "code": null, "e": 27718, "s": 27678, "text": "Java Math random() method with Examples" }, { "code": null, "e": 27762, "s": 27718, "text": "Convert a String to Character array in Java" }, { "code": null, "e": 27788, "s": 27762, "text": "Java Programming Examples" }, { "code": null, "e": 27820, "s": 27788, "text": "How to Iterate HashMap in Java?" }, { "code": null, "e": 27867, "s": 27820, "text": "Implementing a Linked List in Java using Class" } ]
MLOps with Docker and Jenkins: Automating Machine Learning Pipelines | by Adrián González Carpintero | Towards Data Science
The purpose of this post is to provide an example of how we can use DevOps tools like Docker and Jenkins to automate a Machine Learning Pipeline. At the end of this post, you will know how to containerize a Machine Learning model with Docker and create a pipeline with Jenkins that automatically process raw data, trains a model and returns test accuracy every time we make a change in our repository. All the code needed for this post can be found in Github. For this task we will use the Adult census income Dataset. Target variable is income: a binary variable that indicates if an individual earns more than 50k a year or not. 📒 NOTE: As the purpose to this article is to automate a Machine Learning Pipeline, we won’t dive into EDA as is out of the scope. If you are curious about that you can check this Kaggle notebook, but is not mandatory in order to understand what is done here. Ok, so let’s start! Before starting to code, I think is important to understand what is the plan. If you look at the Github repository you will see three python scripts: is easy to figure out what they do by looking at their names :) . We also have the raw dataset: adult.csv, and a Dockerfile (we will talk about it later). But now I want you to understand the workflow of this project, and for that the first thing we need to do is to understand what are the inputs and outputs of our Python scripts: As we see in the image, preprocessing.py takes the raw data as input and outputs processed data split into train and test. train.py takes train processed data as input and outputs the model and a json file where we will store the validation accuracy. test.py takes test processed data and the model as inputs and outputs a json file with test accuracy. With this in mind, now we have a bunch of scripts that we have to run in a certain order, that create a bunch of files that we need to store and access. Furthermore, we want to automate all this process. Nowadays, the best way to manage this issue is using Docker: with this tool you can create an isolated environment with all the dependencies needed to run your code (solving the “it works in my machine” problem!) that makes it all easier. Once we have that, we will be able to automate all the process with Jenkins. There are 3 concepts on which Docker is based: Containers, Images and Dockerfiles. Is indispensable to understand what they do in order to work with Docker. If you are not familiar with them, here is an intuitive definition: Containers: A standard unit of software that packages everything you need to run your application (dependencies, environment variables...) Dockerfile: This is a file in which you define everything you want to be inside of a container. Image: This is the blueprint needed for running a container. You build an image by executing a Dockerfile. So, in order to use Docker, you will follow this steps: Define a DockerfileBuild the imageRun a containerRun commands inside the container Define a Dockerfile Build the image Run a container Run commands inside the container Let’s go step by step. Here we have to define everything we need to run the pipeline. You can have a look at the Dockerfile in the repository, but if you are not familiar with the syntax it may be overwhelming at first. So what we are going to do here is talk about what we want to specify in it and have a look at the syntax step by step. First, we need to specify where we want to run our pipeline. For most of the containerized applications people use to choose a light distribution of Linux, like alpine. However, for our pipeline we will just use an image of jupyter called jupyter/scipy-notebook. In the Dockerfile, we specify the following command: FROM jupyter/scipy-notebook Then, we have to install some packages. For this purpose we use the command RUN: USER root RUN apt-get update && apt-get install -y jq RUN pip install joblib 📒 NOTE: It may not make much sense now, but we will need jq in order to access values inside json files, and joblib in order to serialize and deserialize the model. Next thing we have to set is the distribution of the files inside the container. We want to build a container that has this structure inside: 📒 NOTE: “work” folder is autogenerated by Docker. We are not going to put anything inside. First we create the folders: RUN mkdir model raw_data processed_data results And then we set the directories as environment variables (so we don’t hard code paths all over the code) ENV MODEL_DIR=/home/jovyan/modelENV RAW_DATA_DIR=/home/jovyan/raw_dataENV PROCESSED_DATA_DIR=/home/jovyan/processed_dataENV RESULTS_DIR=/home/jovyan/resultsENV RAW_DATA_FILE=adult.csv Finally, we set the order to copy the scripts and the raw data from our repository. They will be pasted in our container once we create it. COPY adult.csv ./raw_data/adult.csv COPY preprocessing.py ./preprocessing.py COPY train.py ./train.py COPY test.py ./test.py Once we have our Dockerfile specified, we can build the image. The command to do this is: sudo -S docker build -t adult-model . We specify the name of the image with -t adult-model (-t stands for tag) and the path of the Dockerfile with .. Docker automatically picks the file named "Dockerfile". Now that we have an image (a blueprint for a container), we can build a container! 📒 NOTE: we are going to build just one container, but in case you don’t know, once we have an image we can build as many containers as we want! This opens up a wide range of possibilities. The command to run a container is the following: sudo -S docker run -d --name model adult-model where -d flag is for detached (runs the container in background). We name it “model” and we specify the image we use (adult-model). Now that we have our container running, we can run commands inside it by using docker exec. In this project, we need to execute the scripts in order and then show the results. We can do that by the following commands: Run preprocessing.py sudo -S docker container exec model python3 preprocessing.py Run train.py sudo -S docker container exec model python3 train.py Run test.py sudo -S docker container exec model python3 test.py Show validation accuracy and test accuracy sudo -S docker container exec model cat \/home/jovyan/results/train_metadata.json \/home/jovyan/results/test_metadata.json 📒 NOTE: If you are curious enough (I guess you are) you will want to know what each script actually does. Don’t worry, if you are familiar with basic Machine Learning tools (here I basically use Pandas and SKlearn libraries), you can open the scripts and have a look at the code. It’s not a big deal and most of the lines are commented. If you want a deep understanding or you are looking for more complex models than the one shown here, you can take a look at this notebook. When building pipelines is common to have a step dedicated to test if the application is well built and good enough to be deployed into production. In this project, we will use a conditional statement that tests if the validation accuracy is higher than a threshold. If it is, the model is deployed. If not, the process stops. The code for doing this is the following: val_acc=$(sudo -S docker container exec model jq .validation_acc \ /home/jovyan/results/train_metadata.json)threshold=0.8if echo "$threshold > $val_acc" | bc -l | grep -q 1then echo 'validation accuracy is lower than the threshold, process stopped'else echo 'validation accuracy is higher than the threshold' sudo -S docker container exec model python3 test.py sudo -S docker container exec model cat \ /home/jovyan/results/train_metadata.json \ /home/jovyan/results/test_metadata.json fi As you can see, first we set the two variables we want to compare (validation accuracy and the threshold) and then we pass them through a conditional statement. If the validation accuracy is higher than the threshold, we will execute the model for the test data and then we will show both test and validation results. If not, the process will stop. And there we have it! our model is fully containerized and we can run all the steps in our pipeline! If you are not familiar with Docker, now you might be asking: Ok, This is all good stuff, but at the end I just have my model and my predictions. I can also get them by running my Python code and with no need to learn Docker so, what’s the point of all this? I’m glad you asked 😎 . First, having your Machine Learning models in a Docker container is really useful in order to deploy that model into a production environment. As an example, How many times have you seen code on a tutorial or in a repository that you have tried to replicate, and when running the same code in your machine your screen has filled with red? If we don’t like to pass through that, imagine what our customers might feel. With Docker containers, this problem is solved. Another reason why Docker is really useful is probably the same reason why you are reading this: to help automating an entire pipeline. So, without any further ado, let’s get straight to the point! For this step we will use Jenkins, a widely famous open source automation server that provides an endless list of plugins to support building, deploying and automating any project. For this time, we will build the steps of the pipeline using a tool called jobs. Each job will be a step in our pipeline. 📒 NOTE: To keep things running smoothly, you will probably need to configure a few things: It is probable that you will experience some problems trying to connect Jenkins with Github if you use Jenkins in your localhost. If that is your case, consider creating a secure URL to your localhost. Best tool I have found to do so is ngrok. As Jenkins uses its own user (called jenkins), you may need to give it permissions to execute commands without password. You can do this by opening sudoers file with sudo visudo /etc/sudoers and pasting jenkins ALL=(ALL) NOPASSWD: ALL. That being said, let’s see what is the plan. We will create 4 jobs: The “github-to-container” job: In this job we will “connect” Jenkins with Github in a way that the job will be triggered everytime we do a commit in Github. We will also build the Docker image and run a container.The “preprocessing” job: In this step we will execute the preprocessing.py script. This Job will be triggered by the “github-to-container” job.The “train” job: In this job we will execute the train.py script. This Job will be triggered by the “preprocessing” job.The “test” job: In this job we will pass the validation score through our conditional statement. If it is higher than the threshold, we will execute the test.py script and show the metadata (the validation and test accuracy). If the validation score is lower than the threshold, the process will stop and no metadata will be provided. The “github-to-container” job: In this job we will “connect” Jenkins with Github in a way that the job will be triggered everytime we do a commit in Github. We will also build the Docker image and run a container. The “preprocessing” job: In this step we will execute the preprocessing.py script. This Job will be triggered by the “github-to-container” job. The “train” job: In this job we will execute the train.py script. This Job will be triggered by the “preprocessing” job. The “test” job: In this job we will pass the validation score through our conditional statement. If it is higher than the threshold, we will execute the test.py script and show the metadata (the validation and test accuracy). If the validation score is lower than the threshold, the process will stop and no metadata will be provided. Once we know what to do, let’s go for it! For the github-to-container job, first we need to create a “connection” between github and Jenkins. This is done using webhooks. To create the Webhook, go to your repository in Github, choose settings and select webhooks. Select add webhook. In the Payload URL, pass the URL where you run Jenkins and add “//github-webhook/”. For content type choose “application/json”. For the answer of “Which events would you like to trigger this webhook?”, choose “Just the push event”. At the bottom select Active. Select add webhook. Then, you will need to create a credential in Jenkins in order to access Github. In Jenkins, go to Manage Jenkins Then select Manage Credentials, In “Stores scoped to Jenkins” select Jenkins Then select “Global credentials (unrestricted)” and Add credentials Here, for Scope select “Global (Jenkins, nodes, items, all child items, etc)”, for username and password write your Github username and password. You can leave ID empty as it will be autogenerated. You can also add a description. Finally, click OK. Now let’s build the first job! In Jenkins, go to New Item, then give it a name and choose Freestyle project. Next step is to set the configuration. For this step, in Source Code Management choose Git, and then paste the URL of your repository and your Github credentials. Then, in Build Triggers select “GitHub hook trigger for GITScm polling”. Finally in the build section choose Add build step, then Execute shell, and then write the code to build the image and run the container (we have already talked about it): Choose save. For the “preprocessing” job, in Source Code Management leave it as None. In Build Triggers, select “Build after other projects are built”. Then in Projects to watch enter the name of the first job and select “Trigger only if build is stable”. In Build, choose Add build step, then execute shell, and write the code to run preprocessing.py: The “train” job has the same scheme as the “preprocessing” job, but with a few differences. As you might guess, you will need to write the name of the second job in the Build triggers section: And in the Build section write the code for running train.py. For the “test” job, select the “train” job for the Build Triggers section, and in the Build section write the following code: val_acc=$(sudo -S docker container exec model jq .validation_acc \ /home/jovyan/results/train_metadata.json)threshold=0.8if echo "$threshold > $val_acc" | bc -l | grep -q 1then echo 'validation accuracy is lower than the threshold, process stopped'else echo 'validation accuracy is higher than the threshold' sudo -S docker container exec model python3 test.py sudo -S docker container exec model cat \ /home/jovyan/results/train_metadata.json \ /home/jovyan/results/test_metadata.json fi sudo -S docker rm -f model I have written it just in case you want to copy paste, but in Jenkins it should look like this: Click save and there we have it! Our pipeline is now fully automated! You can now play with it: try making a commit in Github and see how every step goes automatically. At the end, if the model validation accuracy is higher than the threshold, the model will compute the test accuracy and give back the results. 📒 NOTE: In order to see the output of each step, select the step, click on the first number in the Build section at the bottom left and select Console Output. For the last step, you should see the validation and test accuracy. I hope you have learned a lot! Thanks for reading! Docker for Machine Learning — Part III From DevOps to MLOPS: Integrate Machine Learning Models using Jenkins and Docker From Naïve to XGBoost and ANN: Adult Census Income
[ { "code": null, "e": 574, "s": 172, "text": "The purpose of this post is to provide an example of how we can use DevOps tools like Docker and Jenkins to automate a Machine Learning Pipeline. At the end of this post, you will know how to containerize a Machine Learning model with Docker and create a pipeline with Jenkins that automatically process raw data, trains a model and returns test accuracy every time we make a change in our repository." }, { "code": null, "e": 632, "s": 574, "text": "All the code needed for this post can be found in Github." }, { "code": null, "e": 803, "s": 632, "text": "For this task we will use the Adult census income Dataset. Target variable is income: a binary variable that indicates if an individual earns more than 50k a year or not." }, { "code": null, "e": 1062, "s": 803, "text": "📒 NOTE: As the purpose to this article is to automate a Machine Learning Pipeline, we won’t dive into EDA as is out of the scope. If you are curious about that you can check this Kaggle notebook, but is not mandatory in order to understand what is done here." }, { "code": null, "e": 1082, "s": 1062, "text": "Ok, so let’s start!" }, { "code": null, "e": 1565, "s": 1082, "text": "Before starting to code, I think is important to understand what is the plan. If you look at the Github repository you will see three python scripts: is easy to figure out what they do by looking at their names :) . We also have the raw dataset: adult.csv, and a Dockerfile (we will talk about it later). But now I want you to understand the workflow of this project, and for that the first thing we need to do is to understand what are the inputs and outputs of our Python scripts:" }, { "code": null, "e": 1918, "s": 1565, "text": "As we see in the image, preprocessing.py takes the raw data as input and outputs processed data split into train and test. train.py takes train processed data as input and outputs the model and a json file where we will store the validation accuracy. test.py takes test processed data and the model as inputs and outputs a json file with test accuracy." }, { "code": null, "e": 2122, "s": 1918, "text": "With this in mind, now we have a bunch of scripts that we have to run in a certain order, that create a bunch of files that we need to store and access. Furthermore, we want to automate all this process." }, { "code": null, "e": 2438, "s": 2122, "text": "Nowadays, the best way to manage this issue is using Docker: with this tool you can create an isolated environment with all the dependencies needed to run your code (solving the “it works in my machine” problem!) that makes it all easier. Once we have that, we will be able to automate all the process with Jenkins." }, { "code": null, "e": 2663, "s": 2438, "text": "There are 3 concepts on which Docker is based: Containers, Images and Dockerfiles. Is indispensable to understand what they do in order to work with Docker. If you are not familiar with them, here is an intuitive definition:" }, { "code": null, "e": 2802, "s": 2663, "text": "Containers: A standard unit of software that packages everything you need to run your application (dependencies, environment variables...)" }, { "code": null, "e": 2898, "s": 2802, "text": "Dockerfile: This is a file in which you define everything you want to be inside of a container." }, { "code": null, "e": 3005, "s": 2898, "text": "Image: This is the blueprint needed for running a container. You build an image by executing a Dockerfile." }, { "code": null, "e": 3061, "s": 3005, "text": "So, in order to use Docker, you will follow this steps:" }, { "code": null, "e": 3144, "s": 3061, "text": "Define a DockerfileBuild the imageRun a containerRun commands inside the container" }, { "code": null, "e": 3164, "s": 3144, "text": "Define a Dockerfile" }, { "code": null, "e": 3180, "s": 3164, "text": "Build the image" }, { "code": null, "e": 3196, "s": 3180, "text": "Run a container" }, { "code": null, "e": 3230, "s": 3196, "text": "Run commands inside the container" }, { "code": null, "e": 3253, "s": 3230, "text": "Let’s go step by step." }, { "code": null, "e": 3570, "s": 3253, "text": "Here we have to define everything we need to run the pipeline. You can have a look at the Dockerfile in the repository, but if you are not familiar with the syntax it may be overwhelming at first. So what we are going to do here is talk about what we want to specify in it and have a look at the syntax step by step." }, { "code": null, "e": 3886, "s": 3570, "text": "First, we need to specify where we want to run our pipeline. For most of the containerized applications people use to choose a light distribution of Linux, like alpine. However, for our pipeline we will just use an image of jupyter called jupyter/scipy-notebook. In the Dockerfile, we specify the following command:" }, { "code": null, "e": 3914, "s": 3886, "text": "FROM jupyter/scipy-notebook" }, { "code": null, "e": 3995, "s": 3914, "text": "Then, we have to install some packages. For this purpose we use the command RUN:" }, { "code": null, "e": 4072, "s": 3995, "text": "USER root RUN apt-get update && apt-get install -y jq RUN pip install joblib" }, { "code": null, "e": 4237, "s": 4072, "text": "📒 NOTE: It may not make much sense now, but we will need jq in order to access values inside json files, and joblib in order to serialize and deserialize the model." }, { "code": null, "e": 4379, "s": 4237, "text": "Next thing we have to set is the distribution of the files inside the container. We want to build a container that has this structure inside:" }, { "code": null, "e": 4470, "s": 4379, "text": "📒 NOTE: “work” folder is autogenerated by Docker. We are not going to put anything inside." }, { "code": null, "e": 4499, "s": 4470, "text": "First we create the folders:" }, { "code": null, "e": 4547, "s": 4499, "text": "RUN mkdir model raw_data processed_data results" }, { "code": null, "e": 4652, "s": 4547, "text": "And then we set the directories as environment variables (so we don’t hard code paths all over the code)" }, { "code": null, "e": 4836, "s": 4652, "text": "ENV MODEL_DIR=/home/jovyan/modelENV RAW_DATA_DIR=/home/jovyan/raw_dataENV PROCESSED_DATA_DIR=/home/jovyan/processed_dataENV RESULTS_DIR=/home/jovyan/resultsENV RAW_DATA_FILE=adult.csv" }, { "code": null, "e": 4976, "s": 4836, "text": "Finally, we set the order to copy the scripts and the raw data from our repository. They will be pasted in our container once we create it." }, { "code": null, "e": 5101, "s": 4976, "text": "COPY adult.csv ./raw_data/adult.csv COPY preprocessing.py ./preprocessing.py COPY train.py ./train.py COPY test.py ./test.py" }, { "code": null, "e": 5191, "s": 5101, "text": "Once we have our Dockerfile specified, we can build the image. The command to do this is:" }, { "code": null, "e": 5229, "s": 5191, "text": "sudo -S docker build -t adult-model ." }, { "code": null, "e": 5397, "s": 5229, "text": "We specify the name of the image with -t adult-model (-t stands for tag) and the path of the Dockerfile with .. Docker automatically picks the file named \"Dockerfile\"." }, { "code": null, "e": 5480, "s": 5397, "text": "Now that we have an image (a blueprint for a container), we can build a container!" }, { "code": null, "e": 5669, "s": 5480, "text": "📒 NOTE: we are going to build just one container, but in case you don’t know, once we have an image we can build as many containers as we want! This opens up a wide range of possibilities." }, { "code": null, "e": 5718, "s": 5669, "text": "The command to run a container is the following:" }, { "code": null, "e": 5765, "s": 5718, "text": "sudo -S docker run -d --name model adult-model" }, { "code": null, "e": 5897, "s": 5765, "text": "where -d flag is for detached (runs the container in background). We name it “model” and we specify the image we use (adult-model)." }, { "code": null, "e": 6115, "s": 5897, "text": "Now that we have our container running, we can run commands inside it by using docker exec. In this project, we need to execute the scripts in order and then show the results. We can do that by the following commands:" }, { "code": null, "e": 6136, "s": 6115, "text": "Run preprocessing.py" }, { "code": null, "e": 6197, "s": 6136, "text": "sudo -S docker container exec model python3 preprocessing.py" }, { "code": null, "e": 6210, "s": 6197, "text": "Run train.py" }, { "code": null, "e": 6263, "s": 6210, "text": "sudo -S docker container exec model python3 train.py" }, { "code": null, "e": 6275, "s": 6263, "text": "Run test.py" }, { "code": null, "e": 6327, "s": 6275, "text": "sudo -S docker container exec model python3 test.py" }, { "code": null, "e": 6370, "s": 6327, "text": "Show validation accuracy and test accuracy" }, { "code": null, "e": 6493, "s": 6370, "text": "sudo -S docker container exec model cat \\/home/jovyan/results/train_metadata.json \\/home/jovyan/results/test_metadata.json" }, { "code": null, "e": 6969, "s": 6493, "text": "📒 NOTE: If you are curious enough (I guess you are) you will want to know what each script actually does. Don’t worry, if you are familiar with basic Machine Learning tools (here I basically use Pandas and SKlearn libraries), you can open the scripts and have a look at the code. It’s not a big deal and most of the lines are commented. If you want a deep understanding or you are looking for more complex models than the one shown here, you can take a look at this notebook." }, { "code": null, "e": 7338, "s": 6969, "text": "When building pipelines is common to have a step dedicated to test if the application is well built and good enough to be deployed into production. In this project, we will use a conditional statement that tests if the validation accuracy is higher than a threshold. If it is, the model is deployed. If not, the process stops. The code for doing this is the following:" }, { "code": null, "e": 7834, "s": 7338, "text": "val_acc=$(sudo -S docker container exec model jq .validation_acc \\ /home/jovyan/results/train_metadata.json)threshold=0.8if echo \"$threshold > $val_acc\" | bc -l | grep -q 1then\techo 'validation accuracy is lower than the threshold, process stopped'else echo 'validation accuracy is higher than the threshold' sudo -S docker container exec model python3 test.py sudo -S docker container exec model cat \\ /home/jovyan/results/train_metadata.json \\ /home/jovyan/results/test_metadata.json fi" }, { "code": null, "e": 8183, "s": 7834, "text": "As you can see, first we set the two variables we want to compare (validation accuracy and the threshold) and then we pass them through a conditional statement. If the validation accuracy is higher than the threshold, we will execute the model for the test data and then we will show both test and validation results. If not, the process will stop." }, { "code": null, "e": 8284, "s": 8183, "text": "And there we have it! our model is fully containerized and we can run all the steps in our pipeline!" }, { "code": null, "e": 8543, "s": 8284, "text": "If you are not familiar with Docker, now you might be asking: Ok, This is all good stuff, but at the end I just have my model and my predictions. I can also get them by running my Python code and with no need to learn Docker so, what’s the point of all this?" }, { "code": null, "e": 8566, "s": 8543, "text": "I’m glad you asked 😎 ." }, { "code": null, "e": 9031, "s": 8566, "text": "First, having your Machine Learning models in a Docker container is really useful in order to deploy that model into a production environment. As an example, How many times have you seen code on a tutorial or in a repository that you have tried to replicate, and when running the same code in your machine your screen has filled with red? If we don’t like to pass through that, imagine what our customers might feel. With Docker containers, this problem is solved." }, { "code": null, "e": 9167, "s": 9031, "text": "Another reason why Docker is really useful is probably the same reason why you are reading this: to help automating an entire pipeline." }, { "code": null, "e": 9229, "s": 9167, "text": "So, without any further ado, let’s get straight to the point!" }, { "code": null, "e": 9410, "s": 9229, "text": "For this step we will use Jenkins, a widely famous open source automation server that provides an endless list of plugins to support building, deploying and automating any project." }, { "code": null, "e": 9532, "s": 9410, "text": "For this time, we will build the steps of the pipeline using a tool called jobs. Each job will be a step in our pipeline." }, { "code": null, "e": 9623, "s": 9532, "text": "📒 NOTE: To keep things running smoothly, you will probably need to configure a few things:" }, { "code": null, "e": 9867, "s": 9623, "text": "It is probable that you will experience some problems trying to connect Jenkins with Github if you use Jenkins in your localhost. If that is your case, consider creating a secure URL to your localhost. Best tool I have found to do so is ngrok." }, { "code": null, "e": 10103, "s": 9867, "text": "As Jenkins uses its own user (called jenkins), you may need to give it permissions to execute commands without password. You can do this by opening sudoers file with sudo visudo /etc/sudoers and pasting jenkins ALL=(ALL) NOPASSWD: ALL." }, { "code": null, "e": 10171, "s": 10103, "text": "That being said, let’s see what is the plan. We will create 4 jobs:" }, { "code": null, "e": 10982, "s": 10171, "text": "The “github-to-container” job: In this job we will “connect” Jenkins with Github in a way that the job will be triggered everytime we do a commit in Github. We will also build the Docker image and run a container.The “preprocessing” job: In this step we will execute the preprocessing.py script. This Job will be triggered by the “github-to-container” job.The “train” job: In this job we will execute the train.py script. This Job will be triggered by the “preprocessing” job.The “test” job: In this job we will pass the validation score through our conditional statement. If it is higher than the threshold, we will execute the test.py script and show the metadata (the validation and test accuracy). If the validation score is lower than the threshold, the process will stop and no metadata will be provided." }, { "code": null, "e": 11196, "s": 10982, "text": "The “github-to-container” job: In this job we will “connect” Jenkins with Github in a way that the job will be triggered everytime we do a commit in Github. We will also build the Docker image and run a container." }, { "code": null, "e": 11340, "s": 11196, "text": "The “preprocessing” job: In this step we will execute the preprocessing.py script. This Job will be triggered by the “github-to-container” job." }, { "code": null, "e": 11461, "s": 11340, "text": "The “train” job: In this job we will execute the train.py script. This Job will be triggered by the “preprocessing” job." }, { "code": null, "e": 11796, "s": 11461, "text": "The “test” job: In this job we will pass the validation score through our conditional statement. If it is higher than the threshold, we will execute the test.py script and show the metadata (the validation and test accuracy). If the validation score is lower than the threshold, the process will stop and no metadata will be provided." }, { "code": null, "e": 11838, "s": 11796, "text": "Once we know what to do, let’s go for it!" }, { "code": null, "e": 12361, "s": 11838, "text": "For the github-to-container job, first we need to create a “connection” between github and Jenkins. This is done using webhooks. To create the Webhook, go to your repository in Github, choose settings and select webhooks. Select add webhook. In the Payload URL, pass the URL where you run Jenkins and add “//github-webhook/”. For content type choose “application/json”. For the answer of “Which events would you like to trigger this webhook?”, choose “Just the push event”. At the bottom select Active. Select add webhook." }, { "code": null, "e": 12475, "s": 12361, "text": "Then, you will need to create a credential in Jenkins in order to access Github. In Jenkins, go to Manage Jenkins" }, { "code": null, "e": 12507, "s": 12475, "text": "Then select Manage Credentials," }, { "code": null, "e": 12552, "s": 12507, "text": "In “Stores scoped to Jenkins” select Jenkins" }, { "code": null, "e": 12600, "s": 12552, "text": "Then select “Global credentials (unrestricted)”" }, { "code": null, "e": 12620, "s": 12600, "text": "and Add credentials" }, { "code": null, "e": 12869, "s": 12620, "text": "Here, for Scope select “Global (Jenkins, nodes, items, all child items, etc)”, for username and password write your Github username and password. You can leave ID empty as it will be autogenerated. You can also add a description. Finally, click OK." }, { "code": null, "e": 12900, "s": 12869, "text": "Now let’s build the first job!" }, { "code": null, "e": 12928, "s": 12900, "text": "In Jenkins, go to New Item," }, { "code": null, "e": 12978, "s": 12928, "text": "then give it a name and choose Freestyle project." }, { "code": null, "e": 13141, "s": 12978, "text": "Next step is to set the configuration. For this step, in Source Code Management choose Git, and then paste the URL of your repository and your Github credentials." }, { "code": null, "e": 13386, "s": 13141, "text": "Then, in Build Triggers select “GitHub hook trigger for GITScm polling”. Finally in the build section choose Add build step, then Execute shell, and then write the code to build the image and run the container (we have already talked about it):" }, { "code": null, "e": 13399, "s": 13386, "text": "Choose save." }, { "code": null, "e": 13642, "s": 13399, "text": "For the “preprocessing” job, in Source Code Management leave it as None. In Build Triggers, select “Build after other projects are built”. Then in Projects to watch enter the name of the first job and select “Trigger only if build is stable”." }, { "code": null, "e": 13739, "s": 13642, "text": "In Build, choose Add build step, then execute shell, and write the code to run preprocessing.py:" }, { "code": null, "e": 13932, "s": 13739, "text": "The “train” job has the same scheme as the “preprocessing” job, but with a few differences. As you might guess, you will need to write the name of the second job in the Build triggers section:" }, { "code": null, "e": 13994, "s": 13932, "text": "And in the Build section write the code for running train.py." }, { "code": null, "e": 14069, "s": 13994, "text": "For the “test” job, select the “train” job for the Build Triggers section," }, { "code": null, "e": 14120, "s": 14069, "text": "and in the Build section write the following code:" }, { "code": null, "e": 14646, "s": 14120, "text": "val_acc=$(sudo -S docker container exec model jq .validation_acc \\ /home/jovyan/results/train_metadata.json)threshold=0.8if echo \"$threshold > $val_acc\" | bc -l | grep -q 1then\techo 'validation accuracy is lower than the threshold, process stopped'else echo 'validation accuracy is higher than the threshold' sudo -S docker container exec model python3 test.py sudo -S docker container exec model cat \\ /home/jovyan/results/train_metadata.json \\ /home/jovyan/results/test_metadata.json fi sudo -S docker rm -f model" }, { "code": null, "e": 14742, "s": 14646, "text": "I have written it just in case you want to copy paste, but in Jenkins it should look like this:" }, { "code": null, "e": 14812, "s": 14742, "text": "Click save and there we have it! Our pipeline is now fully automated!" }, { "code": null, "e": 15054, "s": 14812, "text": "You can now play with it: try making a commit in Github and see how every step goes automatically. At the end, if the model validation accuracy is higher than the threshold, the model will compute the test accuracy and give back the results." }, { "code": null, "e": 15281, "s": 15054, "text": "📒 NOTE: In order to see the output of each step, select the step, click on the first number in the Build section at the bottom left and select Console Output. For the last step, you should see the validation and test accuracy." }, { "code": null, "e": 15332, "s": 15281, "text": "I hope you have learned a lot! Thanks for reading!" }, { "code": null, "e": 15371, "s": 15332, "text": "Docker for Machine Learning — Part III" }, { "code": null, "e": 15452, "s": 15371, "text": "From DevOps to MLOPS: Integrate Machine Learning Models using Jenkins and Docker" } ]
F# - Strings
In F#, the string type represents immutable text as a sequence of Unicode characters. String literals are delimited by the quotation mark (") character. Some special characters are there for special uses like newline, tab, etc. They are encoded using backslash (\) character. The backslash character and the related character make the escape sequence. The following table shows the escape sequence supported by F#. The following two ways makes the compiler ignore the escape sequence − Using the @ symbol. Enclosing the string in triple quotes. When a string literal is preceded by the @ symbol, it is called a verbatim string. In that way, all escape sequences in the string are ignored, except that two quotation mark characters are interpreted as one quotation mark character. When a string is enclosed by triple quotes, then also all escape sequences are ignored, including double quotation mark characters. The following example demonstrates this technique showing how to work with XML or other structures that include embedded quotation marks − // Using a verbatim string let xmldata = @"<book author = ""Lewis, C.S"" title = ""Narnia"">" printfn "%s" xmldata When you compile and execute the program, it yields the following output − <book author = "Lewis, C.S" title = "Narnia"> The following table shows the basic operations on strings − The following examples demonstrate the uses of some of the above functionalities − The String.collect function builds a new string whose characters are the results of applying a specified function to each of the characters of the input string and concatenating the resulting strings. let collectTesting inputS = String.collect (fun c -> sprintf "%c " c) inputS printfn "%s" (collectTesting "Happy New Year!") When you compile and execute the program, it yields the following output − H a p p y N e w Y e a r ! The String.concat function concatenates a given sequence of strings with a separator and returns a new string. let strings = [ "Tutorials Point"; "Coding Ground"; "Absolute Classes" ] let ourProducts = String.concat "\n" strings printfn "%s" ourProducts When you compile and execute the program, it yields the following output − Tutorials Point Coding Ground Absolute Classes The String.replicate method returns a string by concatenating a specified number of instances of a string. printfn "%s" <| String.replicate 10 "*! " When you compile and execute the program, it yields the following output − *! *! *! *! *! *! *! *! *! *! Print Add Notes Bookmark this page
[ { "code": null, "e": 2247, "s": 2161, "text": "In F#, the string type represents immutable text as a sequence of Unicode characters." }, { "code": null, "e": 2314, "s": 2247, "text": "String literals are delimited by the quotation mark (\") character." }, { "code": null, "e": 2576, "s": 2314, "text": "Some special characters are there for special uses like newline, tab, etc. They are encoded using backslash (\\) character. The backslash character and the related character make the escape sequence. The following table shows the escape sequence supported by F#." }, { "code": null, "e": 2647, "s": 2576, "text": "The following two ways makes the compiler ignore the escape sequence −" }, { "code": null, "e": 2667, "s": 2647, "text": "Using the @ symbol." }, { "code": null, "e": 2706, "s": 2667, "text": "Enclosing the string in triple quotes." }, { "code": null, "e": 2941, "s": 2706, "text": "When a string literal is preceded by the @ symbol, it is called a verbatim string. In that way, all escape sequences in the string are ignored, except that two quotation mark characters are interpreted as one quotation mark character." }, { "code": null, "e": 3073, "s": 2941, "text": "When a string is enclosed by triple quotes, then also all escape sequences are ignored, including double quotation mark characters." }, { "code": null, "e": 3212, "s": 3073, "text": "The following example demonstrates this technique showing how to work with XML or other structures that include embedded quotation marks −" }, { "code": null, "e": 3327, "s": 3212, "text": "// Using a verbatim string\nlet xmldata = @\"<book author = \"\"Lewis, C.S\"\" title = \"\"Narnia\"\">\"\nprintfn \"%s\" xmldata" }, { "code": null, "e": 3402, "s": 3327, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 3449, "s": 3402, "text": "<book author = \"Lewis, C.S\" title = \"Narnia\">\n" }, { "code": null, "e": 3509, "s": 3449, "text": "The following table shows the basic operations on strings −" }, { "code": null, "e": 3592, "s": 3509, "text": "The following examples demonstrate the uses of some of the above functionalities −" }, { "code": null, "e": 3793, "s": 3592, "text": "The String.collect function builds a new string whose characters are the results of applying a specified function to each of the characters of the input string and concatenating the resulting strings." }, { "code": null, "e": 3921, "s": 3793, "text": "let collectTesting inputS =\n String.collect (fun c -> sprintf \"%c \" c) inputS\nprintfn \"%s\" (collectTesting \"Happy New Year!\")" }, { "code": null, "e": 3996, "s": 3921, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4023, "s": 3996, "text": "H a p p y N e w Y e a r !\n" }, { "code": null, "e": 4134, "s": 4023, "text": "The String.concat function concatenates a given sequence of strings with a separator and returns a new string." }, { "code": null, "e": 4277, "s": 4134, "text": "let strings = [ \"Tutorials Point\"; \"Coding Ground\"; \"Absolute Classes\" ]\nlet ourProducts = String.concat \"\\n\" strings\nprintfn \"%s\" ourProducts" }, { "code": null, "e": 4352, "s": 4277, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4400, "s": 4352, "text": "Tutorials Point\nCoding Ground\nAbsolute Classes\n" }, { "code": null, "e": 4507, "s": 4400, "text": "The String.replicate method returns a string by concatenating a specified number of instances of a string." }, { "code": null, "e": 4549, "s": 4507, "text": "printfn \"%s\" <| String.replicate 10 \"*! \"" }, { "code": null, "e": 4624, "s": 4549, "text": "When you compile and execute the program, it yields the following output −" }, { "code": null, "e": 4655, "s": 4624, "text": "*! *! *! *! *! *! *! *! *! *!\n" }, { "code": null, "e": 4662, "s": 4655, "text": " Print" }, { "code": null, "e": 4673, "s": 4662, "text": " Add Notes" } ]
Tkinter - Button that changes its properties on hover - GeeksforGeeks
08 Dec, 2020 Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task. In this article, we are going to create a button that changes its properties on hover. Step-by-step Approach: Import tkinter module. Python3 # import required modulefrom tkinter import * Creating A Universal Function To Give Change On Hover Power To Every Button. The config() method is used to change the properties of any widget. Note that in config() method bg and background are two different options and background represents background-color. Syntax: widget.config(**options) Below is the implementation: Python3 # function to change properties of button on hoverdef changeOnHover(button, colorOnHover, colorOnLeave): # adjusting backgroung of the widget # background on entering widget button.bind("<Enter>", func=lambda e: button.config( background=colorOnHover)) # background color on leving widget button.bind("<Leave>", func=lambda e: button.config( background=colorOnLeave)) Create a button in driver code and call the explicit function. Python3 # Driver Coderoot = Tk() # create button# assign button text along# with background colormyButton = Button(root, text="On Hover - Background Change", bg="yellow")myButton.pack() # call function with background# colors as argumentchangeOnHover(myButton, "red", "yellow") root.mainloop() Below is the complete program based on the above approach: Python3 # import required modulefrom tkinter import * # function to change properties of button on hoverdef changeOnHover(button, colorOnHover, colorOnLeave): # adjusting backgroung of the widget # background on entering widget button.bind("<Enter>", func=lambda e: button.config( background=colorOnHover)) # background color on leving widget button.bind("<Leave>", func=lambda e: button.config( background=colorOnLeave)) # Driver Coderoot = Tk() # create button# assign button text along# with background colormyButton = Button(root, text="On Hover - Background Change", bg="yellow")myButton.pack() # call function with background# colors as argumentchangeOnHover(myButton, "red", "yellow") root.mainloop() Output: Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n08 Dec, 2020" }, { "code": null, "e": 25997, "s": 25647, "text": "Python offers multiple options for developing GUI (Graphical User Interface). Out of all the GUI methods, tkinter is the most commonly used method. It is a standard Python interface to the Tk GUI toolkit shipped with Python. Python with tkinter is the fastest and easiest way to create GUI applications. Creating a GUI using tkinter is an easy task." }, { "code": null, "e": 26084, "s": 25997, "text": "In this article, we are going to create a button that changes its properties on hover." }, { "code": null, "e": 26107, "s": 26084, "text": "Step-by-step Approach:" }, { "code": null, "e": 26130, "s": 26107, "text": "Import tkinter module." }, { "code": null, "e": 26138, "s": 26130, "text": "Python3" }, { "code": "# import required modulefrom tkinter import *", "e": 26184, "s": 26138, "text": null }, { "code": null, "e": 26261, "s": 26184, "text": "Creating A Universal Function To Give Change On Hover Power To Every Button." }, { "code": null, "e": 26446, "s": 26261, "text": "The config() method is used to change the properties of any widget. Note that in config() method bg and background are two different options and background represents background-color." }, { "code": null, "e": 26454, "s": 26446, "text": "Syntax:" }, { "code": null, "e": 26479, "s": 26454, "text": "widget.config(**options)" }, { "code": null, "e": 26508, "s": 26479, "text": "Below is the implementation:" }, { "code": null, "e": 26516, "s": 26508, "text": "Python3" }, { "code": "# function to change properties of button on hoverdef changeOnHover(button, colorOnHover, colorOnLeave): # adjusting backgroung of the widget # background on entering widget button.bind(\"<Enter>\", func=lambda e: button.config( background=colorOnHover)) # background color on leving widget button.bind(\"<Leave>\", func=lambda e: button.config( background=colorOnLeave))", "e": 26917, "s": 26516, "text": null }, { "code": null, "e": 26980, "s": 26917, "text": "Create a button in driver code and call the explicit function." }, { "code": null, "e": 26988, "s": 26980, "text": "Python3" }, { "code": "# Driver Coderoot = Tk() # create button# assign button text along# with background colormyButton = Button(root, text=\"On Hover - Background Change\", bg=\"yellow\")myButton.pack() # call function with background# colors as argumentchangeOnHover(myButton, \"red\", \"yellow\") root.mainloop()", "e": 27311, "s": 26988, "text": null }, { "code": null, "e": 27370, "s": 27311, "text": "Below is the complete program based on the above approach:" }, { "code": null, "e": 27378, "s": 27370, "text": "Python3" }, { "code": "# import required modulefrom tkinter import * # function to change properties of button on hoverdef changeOnHover(button, colorOnHover, colorOnLeave): # adjusting backgroung of the widget # background on entering widget button.bind(\"<Enter>\", func=lambda e: button.config( background=colorOnHover)) # background color on leving widget button.bind(\"<Leave>\", func=lambda e: button.config( background=colorOnLeave)) # Driver Coderoot = Tk() # create button# assign button text along# with background colormyButton = Button(root, text=\"On Hover - Background Change\", bg=\"yellow\")myButton.pack() # call function with background# colors as argumentchangeOnHover(myButton, \"red\", \"yellow\") root.mainloop()", "e": 28154, "s": 27378, "text": null }, { "code": null, "e": 28162, "s": 28154, "text": "Output:" }, { "code": null, "e": 28177, "s": 28162, "text": "Python-tkinter" }, { "code": null, "e": 28184, "s": 28177, "text": "Python" }, { "code": null, "e": 28282, "s": 28184, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28314, "s": 28282, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28356, "s": 28314, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 28398, "s": 28356, "text": "Check if element exists in list in Python" }, { "code": null, "e": 28454, "s": 28398, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 28481, "s": 28454, "text": "Python Classes and Objects" }, { "code": null, "e": 28512, "s": 28481, "text": "Python | os.path.join() method" }, { "code": null, "e": 28541, "s": 28512, "text": "Create a directory in Python" }, { "code": null, "e": 28563, "s": 28541, "text": "Defaultdict in Python" }, { "code": null, "e": 28599, "s": 28563, "text": "Python | Pandas dataframe.groupby()" } ]
set clear() in python
In this tutorial, we are going to learn about the clear method of set data structure. Let's see details about the clear method. The method clear is used to clear all the data from the set data structure. All elements from set will clear. And we will leave with an empty set. Follow the below steps to see clear method in action. Initialize a set. User the clear method and clear the set. Print the set and you will see an empty one. Live Demo # initialzing a set number_set = {1, 2, 3, 4, 5} # clearing the set number_set.clear() # printing the set print(number_set) If you run the above code, then you will get the following result. set() If you have any doubts in the tutorial, mention them in the comment section.
[ { "code": null, "e": 1190, "s": 1062, "text": "In this tutorial, we are going to learn about the clear method of set data structure. Let's see details about the clear method." }, { "code": null, "e": 1337, "s": 1190, "text": "The method clear is used to clear all the data from the set data structure. All elements from set will clear. And we will leave with an empty set." }, { "code": null, "e": 1391, "s": 1337, "text": "Follow the below steps to see clear method in action." }, { "code": null, "e": 1409, "s": 1391, "text": "Initialize a set." }, { "code": null, "e": 1450, "s": 1409, "text": "User the clear method and clear the set." }, { "code": null, "e": 1495, "s": 1450, "text": "Print the set and you will see an empty one." }, { "code": null, "e": 1506, "s": 1495, "text": " Live Demo" }, { "code": null, "e": 1630, "s": 1506, "text": "# initialzing a set\nnumber_set = {1, 2, 3, 4, 5}\n# clearing the set\nnumber_set.clear()\n# printing the set\nprint(number_set)" }, { "code": null, "e": 1697, "s": 1630, "text": "If you run the above code, then you will get the following result." }, { "code": null, "e": 1703, "s": 1697, "text": "set()" }, { "code": null, "e": 1780, "s": 1703, "text": "If you have any doubts in the tutorial, mention them in the comment section." } ]
Loading Excel spreadsheet as pandas DataFrame - GeeksforGeeks
08 Jan, 2019 Pandas is a very powerful and scalable tool for data analysis. It supports multiple file format as we might get the data in any format. Pandas also have support for excel file format. We first need to import Pandas and load excel file, and then parse excel file sheets as a Pandas dataframe. import pandas as pd # Import the excel file and call it xls_fileexcel_file = pd.ExcelFile('pandasEx.xlsx') # View the excel_file's sheet namesprint(excel_file.sheet_names) # Load the excel_file's Sheet1 as a dataframedf = excel_file.parse('Sheet1')print(df) Output: One can also read specific columns using ‘usecols‘ parameter of read_excel() method. # import pandas lib as pd import pandas as pd require_cols = [0, 3] # only read specific columns from an excel file required_df = pd.read_excel('SampleWork2.xlsx', usecols = require_cols) print(required_df) Output: Name Percentage 0 Ankit 95 1 Rahul 90 2 Shaurya 85 3 Aishwarya 80 4 Priyanka 75 For more examples, refer https://www.geeksforgeeks.org/creating-a-dataframe-using-excel-files/ pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Technical Scripter 2018 Python Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? How To Convert Python Dictionary To JSON? Check if element exists in list in Python How to drop one or multiple columns in Pandas Dataframe Python Classes and Objects Python | os.path.join() method Create a directory in Python Defaultdict in Python Python | Pandas dataframe.groupby() Python | Get unique values from a list
[ { "code": null, "e": 25647, "s": 25619, "text": "\n08 Jan, 2019" }, { "code": null, "e": 25831, "s": 25647, "text": "Pandas is a very powerful and scalable tool for data analysis. It supports multiple file format as we might get the data in any format. Pandas also have support for excel file format." }, { "code": null, "e": 25939, "s": 25831, "text": "We first need to import Pandas and load excel file, and then parse excel file sheets as a Pandas dataframe." }, { "code": "import pandas as pd # Import the excel file and call it xls_fileexcel_file = pd.ExcelFile('pandasEx.xlsx') # View the excel_file's sheet namesprint(excel_file.sheet_names) # Load the excel_file's Sheet1 as a dataframedf = excel_file.parse('Sheet1')print(df)", "e": 26200, "s": 25939, "text": null }, { "code": null, "e": 26208, "s": 26200, "text": "Output:" }, { "code": null, "e": 26293, "s": 26208, "text": "One can also read specific columns using ‘usecols‘ parameter of read_excel() method." }, { "code": "# import pandas lib as pd import pandas as pd require_cols = [0, 3] # only read specific columns from an excel file required_df = pd.read_excel('SampleWork2.xlsx', usecols = require_cols) print(required_df) ", "e": 26513, "s": 26293, "text": null }, { "code": null, "e": 26521, "s": 26513, "text": "Output:" }, { "code": null, "e": 26671, "s": 26521, "text": " Name Percentage\n0 Ankit 95\n1 Rahul 90\n2 Shaurya 85\n3 Aishwarya 80\n4 Priyanka 75" }, { "code": null, "e": 26766, "s": 26671, "text": "For more examples, refer https://www.geeksforgeeks.org/creating-a-dataframe-using-excel-files/" }, { "code": null, "e": 26791, "s": 26766, "text": "pandas-dataframe-program" }, { "code": null, "e": 26798, "s": 26791, "text": "Picked" }, { "code": null, "e": 26822, "s": 26798, "text": "Python pandas-dataFrame" }, { "code": null, "e": 26836, "s": 26822, "text": "Python-pandas" }, { "code": null, "e": 26860, "s": 26836, "text": "Technical Scripter 2018" }, { "code": null, "e": 26867, "s": 26860, "text": "Python" }, { "code": null, "e": 26886, "s": 26867, "text": "Technical Scripter" }, { "code": null, "e": 26984, "s": 26886, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27016, "s": 26984, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27058, "s": 27016, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 27100, "s": 27058, "text": "Check if element exists in list in Python" }, { "code": null, "e": 27156, "s": 27100, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 27183, "s": 27156, "text": "Python Classes and Objects" }, { "code": null, "e": 27214, "s": 27183, "text": "Python | os.path.join() method" }, { "code": null, "e": 27243, "s": 27214, "text": "Create a directory in Python" }, { "code": null, "e": 27265, "s": 27243, "text": "Defaultdict in Python" }, { "code": null, "e": 27301, "s": 27265, "text": "Python | Pandas dataframe.groupby()" } ]
Python Program to Count number of binary strings without consecutive 1's - GeeksforGeeks
02 Jan, 2019 Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s. Examples: Input: N = 2 Output: 3 // The 3 strings are 00, 01, 10 Input: N = 3 Output: 5 // The 5 strings are 000, 001, 010, 100, 101 Python3 # Python program to count# all distinct binary strings# without two consecutive 1's def countStrings(n): a =[0 for i in range(n)] b =[0 for i in range(n)] a[0] = b[0] = 1 for i in range(1, n): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[n-1] + b[n-1] # Driver program to test# above functions print(countStrings(3)) # This code is contributed# by Anant Agarwal. 5 Please refer complete article on Count number of binary strings without consecutive 1’s for more details! Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Appending to list in Python dictionary Python program to interchange first and last elements in a list How to inverse a matrix using NumPy Differences and Applications of List, Tuple, Set and Dictionary in Python Python | Get the first key in dictionary Python Program for Merge Sort Python | Find most frequent element in a list Python | Difference between two dates (in minutes) using datetime.timedelta() method Python - Convert JSON to string Python program to find smallest number in a list
[ { "code": null, "e": 26097, "s": 26069, "text": "\n02 Jan, 2019" }, { "code": null, "e": 26220, "s": 26097, "text": "Given a positive integer N, count all possible distinct binary strings of length N such that there are no consecutive 1’s." }, { "code": null, "e": 26230, "s": 26220, "text": "Examples:" }, { "code": null, "e": 26355, "s": 26230, "text": "Input: N = 2\nOutput: 3\n// The 3 strings are 00, 01, 10\n\nInput: N = 3\nOutput: 5\n// The 5 strings are 000, 001, 010, 100, 101" }, { "code": null, "e": 26363, "s": 26355, "text": "Python3" }, { "code": "# Python program to count# all distinct binary strings# without two consecutive 1's def countStrings(n): a =[0 for i in range(n)] b =[0 for i in range(n)] a[0] = b[0] = 1 for i in range(1, n): a[i] = a[i-1] + b[i-1] b[i] = a[i-1] return a[n-1] + b[n-1] # Driver program to test# above functions print(countStrings(3)) # This code is contributed# by Anant Agarwal.", "e": 26768, "s": 26363, "text": null }, { "code": null, "e": 26771, "s": 26768, "text": "5\n" }, { "code": null, "e": 26877, "s": 26771, "text": "Please refer complete article on Count number of binary strings without consecutive 1’s for more details!" }, { "code": null, "e": 26893, "s": 26877, "text": "Python Programs" }, { "code": null, "e": 26991, "s": 26893, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27030, "s": 26991, "text": "Appending to list in Python dictionary" }, { "code": null, "e": 27094, "s": 27030, "text": "Python program to interchange first and last elements in a list" }, { "code": null, "e": 27130, "s": 27094, "text": "How to inverse a matrix using NumPy" }, { "code": null, "e": 27204, "s": 27130, "text": "Differences and Applications of List, Tuple, Set and Dictionary in Python" }, { "code": null, "e": 27245, "s": 27204, "text": "Python | Get the first key in dictionary" }, { "code": null, "e": 27275, "s": 27245, "text": "Python Program for Merge Sort" }, { "code": null, "e": 27321, "s": 27275, "text": "Python | Find most frequent element in a list" }, { "code": null, "e": 27406, "s": 27321, "text": "Python | Difference between two dates (in minutes) using datetime.timedelta() method" }, { "code": null, "e": 27438, "s": 27406, "text": "Python - Convert JSON to string" } ]
JavaScript Math PI Property - GeeksforGeeks
24 Jan, 2022 Below is the example of the Math PI Property. Example: Javascript <script> // Here value of Math.PI is printed. document.write(Math.PI);</script> Output: 3.141592653589793 The Math.PI is a property in JavaScript which is simply used to find the value of Pi i.e, in symbolic form Π which is nothing but it is the ratio of the circumference of a circle to its diameter, whose value is approximately 3.141. It is mainly used in a mathematics problem. Syntax: Math.PI Return values: It simply returns the value of PI i.e, Π Below example illustrates the Math PI property in JavaScript. Example: Here simply value of PI i.e, Π is shown as output. Input : Math.PI Output : 3.141592653589793 More codes for the above property are as follows: Program 1:Value of PI i.e, Π can be printed as in the form of function as shown below. Javascript <script> // function is being called. function get_Value_of_PI() { return Math.PI; } // function is calling. document.write(get_Value_of_PI());</script> Output: 3.141592653589793 Program 2: Here we consider Math.PI as a function but in actual it is a property that is why error as output is being shown. Javascript <script> // Here we consider Math.PI as a function but // in actual it is a property that is why error // as output is being shown. document.write(Math.PI(12));</script> Output: Error: Math.PI is not a function Program 3: Whenever we need to find the value of anything related to PI that time we take the help of this property. In mathematics, it needed a lot. Here we are going to find the value of the area of a circle with the given value of its radius. Javascript <script> // function is being called with radius 5 as a parameter. function area_of_circle(radius_of_the_circle) { return Math.PI * radius_of_the_circle * radius_of_the_circle; } // Here area of the circle is 5 unit. document.write(area_of_circle(5));</script> Output: 78.53981633974483 Supported Browsers: Google Chrome 1 and above Edge 12 and above Internet Explorer 3 and above Firefox 1 and above Opera 3 and above Safari 1 and above nidhi_biet arorakashish0911 ysachin2314 javascript-math JavaScript-Properties JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Remove elements from a JavaScript Array Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request JavaScript | Promises How to get character array from string in JavaScript? Remove elements from a JavaScript Array Installation of Node.js on Linux How to fetch data from an API in ReactJS ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26545, "s": 26517, "text": "\n24 Jan, 2022" }, { "code": null, "e": 26592, "s": 26545, "text": "Below is the example of the Math PI Property. " }, { "code": null, "e": 26601, "s": 26592, "text": "Example:" }, { "code": null, "e": 26612, "s": 26601, "text": "Javascript" }, { "code": "<script> // Here value of Math.PI is printed. document.write(Math.PI);</script>", "e": 26694, "s": 26612, "text": null }, { "code": null, "e": 26703, "s": 26694, "text": "Output: " }, { "code": null, "e": 26721, "s": 26703, "text": "3.141592653589793" }, { "code": null, "e": 26997, "s": 26721, "text": "The Math.PI is a property in JavaScript which is simply used to find the value of Pi i.e, in symbolic form Π which is nothing but it is the ratio of the circumference of a circle to its diameter, whose value is approximately 3.141. It is mainly used in a mathematics problem." }, { "code": null, "e": 27007, "s": 26997, "text": "Syntax: " }, { "code": null, "e": 27015, "s": 27007, "text": "Math.PI" }, { "code": null, "e": 27071, "s": 27015, "text": "Return values: It simply returns the value of PI i.e, Π" }, { "code": null, "e": 27133, "s": 27071, "text": "Below example illustrates the Math PI property in JavaScript." }, { "code": null, "e": 27195, "s": 27133, "text": "Example: Here simply value of PI i.e, Π is shown as output. " }, { "code": null, "e": 27238, "s": 27195, "text": "Input : Math.PI\nOutput : 3.141592653589793" }, { "code": null, "e": 27288, "s": 27238, "text": "More codes for the above property are as follows:" }, { "code": null, "e": 27377, "s": 27288, "text": "Program 1:Value of PI i.e, Π can be printed as in the form of function as shown below. " }, { "code": null, "e": 27388, "s": 27377, "text": "Javascript" }, { "code": "<script> // function is being called. function get_Value_of_PI() { return Math.PI; } // function is calling. document.write(get_Value_of_PI());</script>", "e": 27553, "s": 27388, "text": null }, { "code": null, "e": 27562, "s": 27553, "text": "Output: " }, { "code": null, "e": 27580, "s": 27562, "text": "3.141592653589793" }, { "code": null, "e": 27706, "s": 27580, "text": "Program 2: Here we consider Math.PI as a function but in actual it is a property that is why error as output is being shown. " }, { "code": null, "e": 27717, "s": 27706, "text": "Javascript" }, { "code": "<script> // Here we consider Math.PI as a function but // in actual it is a property that is why error // as output is being shown. document.write(Math.PI(12));</script>", "e": 27891, "s": 27717, "text": null }, { "code": null, "e": 27900, "s": 27891, "text": "Output: " }, { "code": null, "e": 27933, "s": 27900, "text": "Error: Math.PI is not a function" }, { "code": null, "e": 28180, "s": 27933, "text": "Program 3: Whenever we need to find the value of anything related to PI that time we take the help of this property. In mathematics, it needed a lot. Here we are going to find the value of the area of a circle with the given value of its radius. " }, { "code": null, "e": 28191, "s": 28180, "text": "Javascript" }, { "code": "<script> // function is being called with radius 5 as a parameter. function area_of_circle(radius_of_the_circle) { return Math.PI * radius_of_the_circle * radius_of_the_circle; } // Here area of the circle is 5 unit. document.write(area_of_circle(5));</script>", "e": 28464, "s": 28191, "text": null }, { "code": null, "e": 28473, "s": 28464, "text": "Output: " }, { "code": null, "e": 28491, "s": 28473, "text": "78.53981633974483" }, { "code": null, "e": 28512, "s": 28491, "text": "Supported Browsers: " }, { "code": null, "e": 28538, "s": 28512, "text": "Google Chrome 1 and above" }, { "code": null, "e": 28556, "s": 28538, "text": "Edge 12 and above" }, { "code": null, "e": 28586, "s": 28556, "text": "Internet Explorer 3 and above" }, { "code": null, "e": 28606, "s": 28586, "text": "Firefox 1 and above" }, { "code": null, "e": 28624, "s": 28606, "text": "Opera 3 and above" }, { "code": null, "e": 28643, "s": 28624, "text": "Safari 1 and above" }, { "code": null, "e": 28656, "s": 28645, "text": "nidhi_biet" }, { "code": null, "e": 28673, "s": 28656, "text": "arorakashish0911" }, { "code": null, "e": 28685, "s": 28673, "text": "ysachin2314" }, { "code": null, "e": 28701, "s": 28685, "text": "javascript-math" }, { "code": null, "e": 28723, "s": 28701, "text": "JavaScript-Properties" }, { "code": null, "e": 28734, "s": 28723, "text": "JavaScript" }, { "code": null, "e": 28751, "s": 28734, "text": "Web Technologies" }, { "code": null, "e": 28849, "s": 28751, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28889, "s": 28849, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 28950, "s": 28889, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 28991, "s": 28950, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 29013, "s": 28991, "text": "JavaScript | Promises" }, { "code": null, "e": 29067, "s": 29013, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 29107, "s": 29067, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29140, "s": 29107, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29183, "s": 29140, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 29245, "s": 29183, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
GATE | GATE-CS-2004 | Question 11 - GeeksforGeeks
28 Jun, 2021 Consider the following statements with respect to user-level threads and kernel supported threads i. context switch is faster with kernel-supported threads ii. for user-level threads, a system call can block the entire process iii. Kernel supported threads can be scheduled independently iv. User level threads are transparent to the kernel Which of the above statements are true?(A) (ii), (iii) and (iv) only(B) (ii) and (iii) only(C) (i) and (iii) only(D) (i) and (ii) onlyAnswer: (A)Explanation: http://en.wikipedia.org/wiki/Thread_%28computer_science%29 https://www.geeksforgeeks.org/difference-between-user-level-thread-and-kernel-level-thread/Quiz of this Question GATE-CS-2004 GATE-GATE-CS-2004 GATE Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. GATE | Gate IT 2007 | Question 25 GATE | GATE-CS-2001 | Question 39 GATE | GATE-CS-2000 | Question 41 GATE | GATE-CS-2005 | Question 6 GATE | GATE MOCK 2017 | Question 21 GATE | GATE MOCK 2017 | Question 24 GATE | GATE-CS-2006 | Question 47 GATE | Gate IT 2008 | Question 43 GATE | GATE-CS-2009 | Question 38 GATE | GATE-CS-2003 | Question 90
[ { "code": null, "e": 25695, "s": 25667, "text": "\n28 Jun, 2021" }, { "code": null, "e": 25793, "s": 25695, "text": "Consider the following statements with respect to user-level threads and kernel supported threads" }, { "code": null, "e": 26048, "s": 25793, "text": " \ni. context switch is faster with kernel-supported threads\nii. for user-level threads, a system call can block the \n entire process\niii. Kernel supported threads can be scheduled independently\niv. User level threads are transparent to the kernel" }, { "code": null, "e": 26206, "s": 26048, "text": "Which of the above statements are true?(A) (ii), (iii) and (iv) only(B) (ii) and (iii) only(C) (i) and (iii) only(D) (i) and (ii) onlyAnswer: (A)Explanation:" }, { "code": null, "e": 26265, "s": 26206, "text": "http://en.wikipedia.org/wiki/Thread_%28computer_science%29" }, { "code": null, "e": 26378, "s": 26265, "text": "https://www.geeksforgeeks.org/difference-between-user-level-thread-and-kernel-level-thread/Quiz of this Question" }, { "code": null, "e": 26391, "s": 26378, "text": "GATE-CS-2004" }, { "code": null, "e": 26409, "s": 26391, "text": "GATE-GATE-CS-2004" }, { "code": null, "e": 26414, "s": 26409, "text": "GATE" }, { "code": null, "e": 26512, "s": 26414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26546, "s": 26512, "text": "GATE | Gate IT 2007 | Question 25" }, { "code": null, "e": 26580, "s": 26546, "text": "GATE | GATE-CS-2001 | Question 39" }, { "code": null, "e": 26614, "s": 26580, "text": "GATE | GATE-CS-2000 | Question 41" }, { "code": null, "e": 26647, "s": 26614, "text": "GATE | GATE-CS-2005 | Question 6" }, { "code": null, "e": 26683, "s": 26647, "text": "GATE | GATE MOCK 2017 | Question 21" }, { "code": null, "e": 26719, "s": 26683, "text": "GATE | GATE MOCK 2017 | Question 24" }, { "code": null, "e": 26753, "s": 26719, "text": "GATE | GATE-CS-2006 | Question 47" }, { "code": null, "e": 26787, "s": 26753, "text": "GATE | Gate IT 2008 | Question 43" }, { "code": null, "e": 26821, "s": 26787, "text": "GATE | GATE-CS-2009 | Question 38" } ]
How to install Python Pycharm on Windows? - GeeksforGeeks
28 Jan, 2020 Prerequisite: Python Language Introduction Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.Python is a programming language that lets you work quickly and integrate systems more efficiently.We need to have an interpreter to interpret and run our programs. There are certain online interpreters like GFG-IDE, IDEONE or CodePad, etc. Running Python codes on an offline interpreter is much more compatible than using an online IDE. PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides some very useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development in Python. Installing Python: Before, starting with the process of installing PyCharm in Windows, one must ensure that Python is installed on their system. To check if the system is equipped with Python, go to the Command line(search for cmd in the Run dialog( + R).Now run the following command: python --version If Python is already installed, it will generate a message with the Python version available. If Python is not present, go through How to install Python on Windows? and follow the instructions provided. Before beginning with the installation process, PyCharm needs to be downloaded. For that, PyCharm is available on jetbrains.com.Download the PyCharm and follow the further instructions for its installation. Beginning with the installation: Getting Started: Choose Installation Location: Installation Options: Selecting Start Menu Folder: Processing Installation: Finished Installation: Once the Installation is over, PyCharm can be searched and started from the Start Menu. Follow the steps given below to do the same: Searching from Start Menu: Getting done with License Agreement: Setting UI Theme: Downloading Plugins: Get Started with PyCharm: python-basics Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 25857, "s": 25829, "text": "\n28 Jan, 2020" }, { "code": null, "e": 26927, "s": 25857, "text": "Prerequisite: Python Language Introduction Python is a widely-used general-purpose, high-level programming language. It was initially designed by Guido van Rossum in 1991 and developed by Python Software Foundation. It was mainly developed for emphasis on code readability, and its syntax allows programmers to express concepts in fewer lines of code.Python is a programming language that lets you work quickly and integrate systems more efficiently.We need to have an interpreter to interpret and run our programs. There are certain online interpreters like GFG-IDE, IDEONE or CodePad, etc. Running Python codes on an offline interpreter is much more compatible than using an online IDE. PyCharm is one of the most popular Python-IDE developed by JetBrains used for performing scripting in Python language. PyCharm provides some very useful features like Code completion and inspection, Debugging process, support for various programming frameworks such as Flask and Django, Package Management, etc. PyCharm provides various tools for productive development in Python." }, { "code": null, "e": 27213, "s": 26927, "text": "Installing Python: Before, starting with the process of installing PyCharm in Windows, one must ensure that Python is installed on their system. To check if the system is equipped with Python, go to the Command line(search for cmd in the Run dialog( + R).Now run the following command:" }, { "code": null, "e": 27231, "s": 27213, "text": "python --version\n" }, { "code": null, "e": 27325, "s": 27231, "text": "If Python is already installed, it will generate a message with the Python version available." }, { "code": null, "e": 27434, "s": 27325, "text": "If Python is not present, go through How to install Python on Windows? and follow the instructions provided." }, { "code": null, "e": 27641, "s": 27434, "text": "Before beginning with the installation process, PyCharm needs to be downloaded. For that, PyCharm is available on jetbrains.com.Download the PyCharm and follow the further instructions for its installation." }, { "code": null, "e": 27674, "s": 27641, "text": "Beginning with the installation:" }, { "code": null, "e": 27691, "s": 27674, "text": "Getting Started:" }, { "code": null, "e": 27721, "s": 27691, "text": "Choose Installation Location:" }, { "code": null, "e": 27743, "s": 27721, "text": "Installation Options:" }, { "code": null, "e": 27772, "s": 27743, "text": "Selecting Start Menu Folder:" }, { "code": null, "e": 27797, "s": 27772, "text": "Processing Installation:" }, { "code": null, "e": 27820, "s": 27797, "text": "Finished Installation:" }, { "code": null, "e": 27953, "s": 27820, "text": "Once the Installation is over, PyCharm can be searched and started from the Start Menu. Follow the steps given below to do the same:" }, { "code": null, "e": 27980, "s": 27953, "text": "Searching from Start Menu:" }, { "code": null, "e": 28017, "s": 27980, "text": "Getting done with License Agreement:" }, { "code": null, "e": 28035, "s": 28017, "text": "Setting UI Theme:" }, { "code": null, "e": 28056, "s": 28035, "text": "Downloading Plugins:" }, { "code": null, "e": 28082, "s": 28056, "text": "Get Started with PyCharm:" }, { "code": null, "e": 28096, "s": 28082, "text": "python-basics" }, { "code": null, "e": 28103, "s": 28096, "text": "Python" }, { "code": null, "e": 28201, "s": 28103, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28219, "s": 28201, "text": "Python Dictionary" }, { "code": null, "e": 28254, "s": 28219, "text": "Read a file line by line in Python" }, { "code": null, "e": 28286, "s": 28254, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 28308, "s": 28286, "text": "Enumerate() in Python" }, { "code": null, "e": 28350, "s": 28308, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 28380, "s": 28350, "text": "Iterate over a list in Python" }, { "code": null, "e": 28406, "s": 28380, "text": "Python String | replace()" }, { "code": null, "e": 28435, "s": 28406, "text": "*args and **kwargs in Python" }, { "code": null, "e": 28479, "s": 28435, "text": "Reading and Writing to text files in Python" } ]
Reader reset() method in Java with Examples - GeeksforGeeks
13 Feb, 2019 The reset() method of Reader Class in Java is used to reset the stream. After reset, if the stream has been marked, then this method attempts to reposition it at the mark, else it will try to position it to the starting. Syntax: public void reset() Parameters: This method do not accepts any parameter. Return Value: This method do not returns any value. Exception: This method throws IOException: if some error occurs while input output if the stream has not been marked if the mark has been invalidated if the reset() method is not supported. Below methods illustrates the working of reset() method: Program 1: // Java program to demonstrate// Reader reset() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 10 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 10; i++) { ch = reader.read(); System.out.print((char)ch); } System.out.println(); // mark the stream for // 5 characters using reset() reader.mark(5); // reset the stream position reader.reset(); // Read the 5 characters from marked position // to this reader using read() method for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.print((char)ch); } } catch (Exception e) { System.out.println(e); } }} GeeksForGe eks?? Program 2: // Java program to demonstrate// Reader reset() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = "GeeksForGeeks"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 10 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 10; i++) { ch = reader.read(); System.out.print((char)ch); } System.out.println(); // reset the stream position reader.reset(); // Read the 5 characters from marked position // to this reader using read() method for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.print((char)ch); } } catch (Exception e) { System.out.println(e); } }} GeeksForGe Geeks Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#reset– Java-Functions Java-IO package Java-Reader Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java HashMap in Java with Examples Stream In Java Interfaces in Java How to iterate any Map in Java ArrayList in Java Initialize an ArrayList in Java Stack Class in Java Multidimensional Arrays in Java Singleton Class in Java
[ { "code": null, "e": 26161, "s": 26133, "text": "\n13 Feb, 2019" }, { "code": null, "e": 26382, "s": 26161, "text": "The reset() method of Reader Class in Java is used to reset the stream. After reset, if the stream has been marked, then this method attempts to reposition it at the mark, else it will try to position it to the starting." }, { "code": null, "e": 26390, "s": 26382, "text": "Syntax:" }, { "code": null, "e": 26410, "s": 26390, "text": "public void reset()" }, { "code": null, "e": 26464, "s": 26410, "text": "Parameters: This method do not accepts any parameter." }, { "code": null, "e": 26516, "s": 26464, "text": "Return Value: This method do not returns any value." }, { "code": null, "e": 26559, "s": 26516, "text": "Exception: This method throws IOException:" }, { "code": null, "e": 26599, "s": 26559, "text": "if some error occurs while input output" }, { "code": null, "e": 26633, "s": 26599, "text": "if the stream has not been marked" }, { "code": null, "e": 26666, "s": 26633, "text": "if the mark has been invalidated" }, { "code": null, "e": 26706, "s": 26666, "text": "if the reset() method is not supported." }, { "code": null, "e": 26763, "s": 26706, "text": "Below methods illustrates the working of reset() method:" }, { "code": null, "e": 26774, "s": 26763, "text": "Program 1:" }, { "code": "// Java program to demonstrate// Reader reset() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 10 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 10; i++) { ch = reader.read(); System.out.print((char)ch); } System.out.println(); // mark the stream for // 5 characters using reset() reader.mark(5); // reset the stream position reader.reset(); // Read the 5 characters from marked position // to this reader using read() method for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.print((char)ch); } } catch (Exception e) { System.out.println(e); } }}", "e": 28041, "s": 26774, "text": null }, { "code": null, "e": 28059, "s": 28041, "text": "GeeksForGe\neks??\n" }, { "code": null, "e": 28070, "s": 28059, "text": "Program 2:" }, { "code": "// Java program to demonstrate// Reader reset() method import java.io.*;import java.util.*; class GFG { public static void main(String[] args) { try { String str = \"GeeksForGeeks\"; // Create a Reader instance Reader reader = new StringReader(str); // Get the character // to be read from the stream int ch; // Read the first 10 characters // to this reader using read() method // This will put the str in the stream // till it is read by the reader for (int i = 0; i < 10; i++) { ch = reader.read(); System.out.print((char)ch); } System.out.println(); // reset the stream position reader.reset(); // Read the 5 characters from marked position // to this reader using read() method for (int i = 0; i < 5; i++) { ch = reader.read(); System.out.print((char)ch); } } catch (Exception e) { System.out.println(e); } }}", "e": 29231, "s": 28070, "text": null }, { "code": null, "e": 29249, "s": 29231, "text": "GeeksForGe\nGeeks\n" }, { "code": null, "e": 29329, "s": 29249, "text": "Reference: https://docs.oracle.com/javase/9/docs/api/java/io/Reader.html#reset–" }, { "code": null, "e": 29344, "s": 29329, "text": "Java-Functions" }, { "code": null, "e": 29360, "s": 29344, "text": "Java-IO package" }, { "code": null, "e": 29372, "s": 29360, "text": "Java-Reader" }, { "code": null, "e": 29377, "s": 29372, "text": "Java" }, { "code": null, "e": 29382, "s": 29377, "text": "Java" }, { "code": null, "e": 29480, "s": 29382, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29531, "s": 29480, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 29561, "s": 29531, "text": "HashMap in Java with Examples" }, { "code": null, "e": 29576, "s": 29561, "text": "Stream In Java" }, { "code": null, "e": 29595, "s": 29576, "text": "Interfaces in Java" }, { "code": null, "e": 29626, "s": 29595, "text": "How to iterate any Map in Java" }, { "code": null, "e": 29644, "s": 29626, "text": "ArrayList in Java" }, { "code": null, "e": 29676, "s": 29644, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 29696, "s": 29676, "text": "Stack Class in Java" }, { "code": null, "e": 29728, "s": 29696, "text": "Multidimensional Arrays in Java" } ]
Maximum length of all possible K equal length ropes generated by cutting N ropes - GeeksforGeeks
15 Jun, 2021 Given an array arr[] consisting of N positive integers representing the lengths of N ropes and a positive integer K, the task is to find the maximum length of the rope that has a frequency of at least K by cutting any ropes in any number of pieces. Examples: Input: arr[] = {5, 2, 7, 4, 9}, K = 5Output: 4Explanation:Below are the possible cutting of the ropes: arr[0](= 5) is cutted into {4, 1}.arr[2](= 7) is cutted into {4, 3}.arr[4](= 9) is cutted into {4, 4, 1}. arr[0](= 5) is cutted into {4, 1}. arr[2](= 7) is cutted into {4, 3}. arr[4](= 9) is cutted into {4, 4, 1}. After the above combinations of cuts, the maximum length is 4, which is of frequency at least(K = 5). Input: arr[] = {1, 2, 3, 4, 9}, K = 6Output: 2 Approach: The given problem can be solved by using the Binary Search. Follow the steps below to solve the problem: Initialize 3 variables, say low as 1, high as the maximum value of array arr[], and ans as -1, to store the left boundary right boundary for the binary search and to store the maximum possible length of K ropes. Iterate until low is less than or equal to high and perform the following steps:Find the mid-value of the range [low, high] and store it in a variable say mid.Traverse the array arr[] and find the count of ropes of length mid that can be obtained by cutting the ropes and store it in a variable say, count.If the value of count is at least K, then update the value of mid as ans and update the value of low as (mid + 1).Otherwise, update the value of high as (mid – 1). Find the mid-value of the range [low, high] and store it in a variable say mid. Traverse the array arr[] and find the count of ropes of length mid that can be obtained by cutting the ropes and store it in a variable say, count. If the value of count is at least K, then update the value of mid as ans and update the value of low as (mid + 1). Otherwise, update the value of high as (mid – 1). After completing the steps, print the value of ans as the result. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum size// of ropes having frequency at least// K by cutting the given ropesint maximumSize(int a[], int k, int n){ // Stores the left and // the right boundaries int low = 1; int high = *max_element(a, a + n); // Stores the maximum length // of rope possible int ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] int mid = low + (high - low) / 2; // Stores the count of ropes // of length mid int count = 0; // Traverse the array arr[] for (int c = 0; c < n; c++) { count += a / mid; } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 9 }; int K = 6; int n = sizeof(arr) / sizeof(arr[0]); cout << (maximumSize(arr, K, n));} // This code is contributed by ukasp // Java program for the above approach import java.util.*; class GFG { // Function to find the maximum size // of ropes having frequency at least // K by cutting the given ropes static int maximumSize(Integer[] a, int k) { // Stores the left and // the right boundaries int low = 1; int high = Collections.max( Arrays.asList(a)); // Stores the maximum length // of rope possible int ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] int mid = low + (high - low) / 2; // Stores the count of ropes // of length mid int count = 0; // Traverse the array arr[] for (int c = 0; c < a.length; c++) { count += a / mid; } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans; } // Driver Code public static void main(String[] args) { Integer[] arr = { 1, 2, 3, 4, 9 }; int K = 6; System.out.println( maximumSize(arr, K)); }} # Python program for the above approach # Function to find the maximum size# of ropes having frequency at least# K by cutting the given ropesdef maximumSize(a, k): # Stores the left and # the right boundaries low = 1 high = max(a) # Stores the maximum length # of rope possible ans = -1 # Iterate while low is less # than or equal to high while (low <= high): # Stores the mid value of # the range [low, high] mid = low + (high - low) // 2 # Stores the count of ropes # of length mid count = 0 # Traverse the array arr[] for c in range(len(a)): count += a // mid # If count is at least K if (count >= k): # Assign mid to ans ans = mid # Update the value # of low low = mid + 1 # Otherwise, update the # value of high else: high = mid - 1 # Return the value of ans return ans # Driver Codeif __name__ == '__main__': arr = [1, 2, 3, 4, 9] K = 6 print(maximumSize(arr, K)) # This code is contributed by mohit kumar 29. // C# program for the above approachusing System;using System.Linq; class GFG{ // Function to find the maximum size// of ropes having frequency at least// K by cutting the given ropesstatic int maximumSize(int[] a, int k){ // Stores the left and // the right boundaries int low = 1; int high = a.Max(); // Stores the maximum length // of rope possible int ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] int mid = low + (high - low) / 2; // Stores the count of ropes // of length mid int count = 0; // Traverse the array []arr for(int c = 0; c < a.Length; c++) { count += a / mid; } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans;} // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 2, 3, 4, 9 }; int K = 6; Console.WriteLine( maximumSize(arr, K));}} // This code is contributed by 29AjayKumar <script> // Javascript program for the above approach // Function to find the maximum size // of ropes having frequency at least // K by cutting the given ropes function maximumSize( a, k) { // Stores the left and // the right boundaries let low = 1; let high = Math.max.apply(Math, a); // Stores the maximum length // of rope possible let ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] let mid = Math.floor(low + (high - low) / 2); // Stores the count of ropes // of length mid let count = 0; // Traverse the array arr[] for (let c = 0; c < a.length; c++) { count += Math.floor(a / mid); } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans; } // Driver Code let arr = [ 1, 2, 3, 4, 9 ]; let K = 6; document.write(maximumSize(arr, K)) // This code is contributed by Hritik </script> 2 Time Complexity: O(N * log N)Auxiliary Space: O(1) mohit kumar 29 ukasp 29AjayKumar hritikrommie Amazon Binary Search interview-preparation Arrays Greedy Mathematical Amazon Arrays Greedy Mathematical Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Count pairs with given sum Chocolate Distribution Problem Window Sliding Technique Reversal algorithm for array rotation Next Greater Element Dijkstra's shortest path algorithm | Greedy Algo-7 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Write a program to print all permutations of a given string Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 26067, "s": 26039, "text": "\n15 Jun, 2021" }, { "code": null, "e": 26316, "s": 26067, "text": "Given an array arr[] consisting of N positive integers representing the lengths of N ropes and a positive integer K, the task is to find the maximum length of the rope that has a frequency of at least K by cutting any ropes in any number of pieces." }, { "code": null, "e": 26326, "s": 26316, "text": "Examples:" }, { "code": null, "e": 26429, "s": 26326, "text": "Input: arr[] = {5, 2, 7, 4, 9}, K = 5Output: 4Explanation:Below are the possible cutting of the ropes:" }, { "code": null, "e": 26535, "s": 26429, "text": "arr[0](= 5) is cutted into {4, 1}.arr[2](= 7) is cutted into {4, 3}.arr[4](= 9) is cutted into {4, 4, 1}." }, { "code": null, "e": 26570, "s": 26535, "text": "arr[0](= 5) is cutted into {4, 1}." }, { "code": null, "e": 26605, "s": 26570, "text": "arr[2](= 7) is cutted into {4, 3}." }, { "code": null, "e": 26643, "s": 26605, "text": "arr[4](= 9) is cutted into {4, 4, 1}." }, { "code": null, "e": 26745, "s": 26643, "text": "After the above combinations of cuts, the maximum length is 4, which is of frequency at least(K = 5)." }, { "code": null, "e": 26792, "s": 26745, "text": "Input: arr[] = {1, 2, 3, 4, 9}, K = 6Output: 2" }, { "code": null, "e": 26907, "s": 26792, "text": "Approach: The given problem can be solved by using the Binary Search. Follow the steps below to solve the problem:" }, { "code": null, "e": 27119, "s": 26907, "text": "Initialize 3 variables, say low as 1, high as the maximum value of array arr[], and ans as -1, to store the left boundary right boundary for the binary search and to store the maximum possible length of K ropes." }, { "code": null, "e": 27589, "s": 27119, "text": "Iterate until low is less than or equal to high and perform the following steps:Find the mid-value of the range [low, high] and store it in a variable say mid.Traverse the array arr[] and find the count of ropes of length mid that can be obtained by cutting the ropes and store it in a variable say, count.If the value of count is at least K, then update the value of mid as ans and update the value of low as (mid + 1).Otherwise, update the value of high as (mid – 1)." }, { "code": null, "e": 27669, "s": 27589, "text": "Find the mid-value of the range [low, high] and store it in a variable say mid." }, { "code": null, "e": 27817, "s": 27669, "text": "Traverse the array arr[] and find the count of ropes of length mid that can be obtained by cutting the ropes and store it in a variable say, count." }, { "code": null, "e": 27932, "s": 27817, "text": "If the value of count is at least K, then update the value of mid as ans and update the value of low as (mid + 1)." }, { "code": null, "e": 27982, "s": 27932, "text": "Otherwise, update the value of high as (mid – 1)." }, { "code": null, "e": 28048, "s": 27982, "text": "After completing the steps, print the value of ans as the result." }, { "code": null, "e": 28099, "s": 28048, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 28103, "s": 28099, "text": "C++" }, { "code": null, "e": 28108, "s": 28103, "text": "Java" }, { "code": null, "e": 28116, "s": 28108, "text": "Python3" }, { "code": null, "e": 28119, "s": 28116, "text": "C#" }, { "code": null, "e": 28130, "s": 28119, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the maximum size// of ropes having frequency at least// K by cutting the given ropesint maximumSize(int a[], int k, int n){ // Stores the left and // the right boundaries int low = 1; int high = *max_element(a, a + n); // Stores the maximum length // of rope possible int ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] int mid = low + (high - low) / 2; // Stores the count of ropes // of length mid int count = 0; // Traverse the array arr[] for (int c = 0; c < n; c++) { count += a / mid; } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans;} // Driver Codeint main(){ int arr[] = { 1, 2, 3, 4, 9 }; int K = 6; int n = sizeof(arr) / sizeof(arr[0]); cout << (maximumSize(arr, K, n));} // This code is contributed by ukasp", "e": 29476, "s": 28130, "text": null }, { "code": "// Java program for the above approach import java.util.*; class GFG { // Function to find the maximum size // of ropes having frequency at least // K by cutting the given ropes static int maximumSize(Integer[] a, int k) { // Stores the left and // the right boundaries int low = 1; int high = Collections.max( Arrays.asList(a)); // Stores the maximum length // of rope possible int ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] int mid = low + (high - low) / 2; // Stores the count of ropes // of length mid int count = 0; // Traverse the array arr[] for (int c = 0; c < a.length; c++) { count += a / mid; } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans; } // Driver Code public static void main(String[] args) { Integer[] arr = { 1, 2, 3, 4, 9 }; int K = 6; System.out.println( maximumSize(arr, K)); }}", "e": 31056, "s": 29476, "text": null }, { "code": "# Python program for the above approach # Function to find the maximum size# of ropes having frequency at least# K by cutting the given ropesdef maximumSize(a, k): # Stores the left and # the right boundaries low = 1 high = max(a) # Stores the maximum length # of rope possible ans = -1 # Iterate while low is less # than or equal to high while (low <= high): # Stores the mid value of # the range [low, high] mid = low + (high - low) // 2 # Stores the count of ropes # of length mid count = 0 # Traverse the array arr[] for c in range(len(a)): count += a // mid # If count is at least K if (count >= k): # Assign mid to ans ans = mid # Update the value # of low low = mid + 1 # Otherwise, update the # value of high else: high = mid - 1 # Return the value of ans return ans # Driver Codeif __name__ == '__main__': arr = [1, 2, 3, 4, 9] K = 6 print(maximumSize(arr, K)) # This code is contributed by mohit kumar 29.", "e": 32199, "s": 31056, "text": null }, { "code": "// C# program for the above approachusing System;using System.Linq; class GFG{ // Function to find the maximum size// of ropes having frequency at least// K by cutting the given ropesstatic int maximumSize(int[] a, int k){ // Stores the left and // the right boundaries int low = 1; int high = a.Max(); // Stores the maximum length // of rope possible int ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] int mid = low + (high - low) / 2; // Stores the count of ropes // of length mid int count = 0; // Traverse the array []arr for(int c = 0; c < a.Length; c++) { count += a / mid; } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans;} // Driver Codepublic static void Main(String[] args){ int[] arr = { 1, 2, 3, 4, 9 }; int K = 6; Console.WriteLine( maximumSize(arr, K));}} // This code is contributed by 29AjayKumar", "e": 33609, "s": 32199, "text": null }, { "code": "<script> // Javascript program for the above approach // Function to find the maximum size // of ropes having frequency at least // K by cutting the given ropes function maximumSize( a, k) { // Stores the left and // the right boundaries let low = 1; let high = Math.max.apply(Math, a); // Stores the maximum length // of rope possible let ans = -1; // Iterate while low is less // than or equal to high while (low <= high) { // Stores the mid value of // the range [low, high] let mid = Math.floor(low + (high - low) / 2); // Stores the count of ropes // of length mid let count = 0; // Traverse the array arr[] for (let c = 0; c < a.length; c++) { count += Math.floor(a / mid); } // If count is at least K if (count >= k) { // Assign mid to ans ans = mid; // Update the value // of low low = mid + 1; } // Otherwise, update the // value of high else { high = mid - 1; } } // Return the value of ans return ans; } // Driver Code let arr = [ 1, 2, 3, 4, 9 ]; let K = 6; document.write(maximumSize(arr, K)) // This code is contributed by Hritik </script>", "e": 35329, "s": 33609, "text": null }, { "code": null, "e": 35331, "s": 35329, "text": "2" }, { "code": null, "e": 35384, "s": 35333, "text": "Time Complexity: O(N * log N)Auxiliary Space: O(1)" }, { "code": null, "e": 35399, "s": 35384, "text": "mohit kumar 29" }, { "code": null, "e": 35405, "s": 35399, "text": "ukasp" }, { "code": null, "e": 35417, "s": 35405, "text": "29AjayKumar" }, { "code": null, "e": 35430, "s": 35417, "text": "hritikrommie" }, { "code": null, "e": 35437, "s": 35430, "text": "Amazon" }, { "code": null, "e": 35451, "s": 35437, "text": "Binary Search" }, { "code": null, "e": 35473, "s": 35451, "text": "interview-preparation" }, { "code": null, "e": 35480, "s": 35473, "text": "Arrays" }, { "code": null, "e": 35487, "s": 35480, "text": "Greedy" }, { "code": null, "e": 35500, "s": 35487, "text": "Mathematical" }, { "code": null, "e": 35507, "s": 35500, "text": "Amazon" }, { "code": null, "e": 35514, "s": 35507, "text": "Arrays" }, { "code": null, "e": 35521, "s": 35514, "text": "Greedy" }, { "code": null, "e": 35534, "s": 35521, "text": "Mathematical" }, { "code": null, "e": 35548, "s": 35534, "text": "Binary Search" }, { "code": null, "e": 35646, "s": 35548, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 35673, "s": 35646, "text": "Count pairs with given sum" }, { "code": null, "e": 35704, "s": 35673, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 35729, "s": 35704, "text": "Window Sliding Technique" }, { "code": null, "e": 35767, "s": 35729, "text": "Reversal algorithm for array rotation" }, { "code": null, "e": 35788, "s": 35767, "text": "Next Greater Element" }, { "code": null, "e": 35839, "s": 35788, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 35897, "s": 35839, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" }, { "code": null, "e": 35948, "s": 35897, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 36008, "s": 35948, "text": "Write a program to print all permutations of a given string" } ]
Python String isprintable() Method - GeeksforGeeks
12 Aug, 2021 Python String isprintable() is a built-in method used for string handling. The isprintable() method returns “True” if all characters in the string are printable or the string is empty, Otherwise, It returns “False”. This function is used to check if the argument contains any printable characters such as: Digits ( 0123456789 ) Uppercase letters ( ABCDEFGHIJKLMNOPQRSTUVWXYZ ) Lowercase letters ( abcdefghijklmnopqrstuvwxyz ) Punctuation characters ( !”#$%&'()*+, -./:;?@[\]^_`{ | }~ ) Space ( ) Syntax: string.isprintable() Parameters: isprintable() does not take any parameters Returns: True – If all characters in the string are printable or the string is empty. False – If the string contains 1 or more nonprintable characters. Errors Or Exceptions: The function does not take any arguments, therefore no parameters should be passed, otherwise, it returns an error.The only whitespace character which is printable is space or ” “, otherwise every whitespace character is non-printable and the function returns “False”.The empty string is considered printable and it returns “True”. The function does not take any arguments, therefore no parameters should be passed, otherwise, it returns an error. The only whitespace character which is printable is space or ” “, otherwise every whitespace character is non-printable and the function returns “False”. The empty string is considered printable and it returns “True”. Input : string = 'My name is Ayush' Output : True Input : string = 'My name is \n Ayush' Output : False Input : string = '' Output : True Python3 # Python code for implementation of isprintable() # checking for printable charactersstring = 'My name is Ayush'print(string.isprintable()) # checking if \n is a printable characterstring = 'My name is \n Ayush'print(string.isprintable()) # checking if space is a printable characterstring = ''print( string.isprintable()) Output: True False True Given a string in python, count the number of non-printable characters in the string and replace non-printable characters with a space. Input : string = 'My name is Ayush' Output : 0 My name is Ayush Input : string = 'My\nname\nis\nAyush' Output : 3 My name is Ayush Algorithm: Initialize an empty new string and a variable count = 0. Traverse the given string character by character up to its length, check if the character is a non-printable character. If it is a non-printable character, increment the counter by 1, and add a space to the new string. Else if it is a printable character, add it to the new string as it is.Print the value of the counter and the new string. Initialize an empty new string and a variable count = 0. Traverse the given string character by character up to its length, check if the character is a non-printable character. If it is a non-printable character, increment the counter by 1, and add a space to the new string. Else if it is a printable character, add it to the new string as it is. Print the value of the counter and the new string. Python3 # Python implementation to count # non-printable characters in a string # Given string and new stringstring ='GeeksforGeeks\nname\nis\nCS portal'newstring = '' # Initialising the counter to 0count = 0 # Iterating the string and # checking for non-printable characters# Incrementing the counter if a # non-printable character is found # and replacing it by space in the newstring # Finally printing the count and newstring for a in string: if (a.isprintable()) == False: count+= 1 newstring+=' ' else: newstring+= aprint(count)print(newstring) Output: 3 GeeksforGeeks name is CS portal AmiyaRanjanRout Python-Built-in-functions Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Read JSON file using Python Adding new column to existing DataFrame in Pandas Python map() function How to get column names in Pandas dataframe Python Dictionary Read a file line by line in Python Taking input in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe
[ { "code": null, "e": 25047, "s": 25019, "text": "\n12 Aug, 2021" }, { "code": null, "e": 25353, "s": 25047, "text": "Python String isprintable() is a built-in method used for string handling. The isprintable() method returns “True” if all characters in the string are printable or the string is empty, Otherwise, It returns “False”. This function is used to check if the argument contains any printable characters such as:" }, { "code": null, "e": 25375, "s": 25353, "text": "Digits ( 0123456789 )" }, { "code": null, "e": 25424, "s": 25375, "text": "Uppercase letters ( ABCDEFGHIJKLMNOPQRSTUVWXYZ )" }, { "code": null, "e": 25473, "s": 25424, "text": "Lowercase letters ( abcdefghijklmnopqrstuvwxyz )" }, { "code": null, "e": 25533, "s": 25473, "text": "Punctuation characters ( !”#$%&'()*+, -./:;?@[\\]^_`{ | }~ )" }, { "code": null, "e": 25543, "s": 25533, "text": "Space ( )" }, { "code": null, "e": 25552, "s": 25543, "text": "Syntax: " }, { "code": null, "e": 25573, "s": 25552, "text": "string.isprintable()" }, { "code": null, "e": 25585, "s": 25573, "text": "Parameters:" }, { "code": null, "e": 25628, "s": 25585, "text": "isprintable() does not take any parameters" }, { "code": null, "e": 25637, "s": 25628, "text": "Returns:" }, { "code": null, "e": 25714, "s": 25637, "text": "True – If all characters in the string are printable or the string is empty." }, { "code": null, "e": 25780, "s": 25714, "text": "False – If the string contains 1 or more nonprintable characters." }, { "code": null, "e": 25802, "s": 25780, "text": "Errors Or Exceptions:" }, { "code": null, "e": 26134, "s": 25802, "text": "The function does not take any arguments, therefore no parameters should be passed, otherwise, it returns an error.The only whitespace character which is printable is space or ” “, otherwise every whitespace character is non-printable and the function returns “False”.The empty string is considered printable and it returns “True”." }, { "code": null, "e": 26250, "s": 26134, "text": "The function does not take any arguments, therefore no parameters should be passed, otherwise, it returns an error." }, { "code": null, "e": 26404, "s": 26250, "text": "The only whitespace character which is printable is space or ” “, otherwise every whitespace character is non-printable and the function returns “False”." }, { "code": null, "e": 26468, "s": 26404, "text": "The empty string is considered printable and it returns “True”." }, { "code": null, "e": 26608, "s": 26468, "text": "Input : string = 'My name is Ayush'\nOutput : True\n\nInput : string = 'My name is \\n Ayush'\nOutput : False\n\nInput : string = ''\nOutput : True" }, { "code": null, "e": 26616, "s": 26608, "text": "Python3" }, { "code": "# Python code for implementation of isprintable() # checking for printable charactersstring = 'My name is Ayush'print(string.isprintable()) # checking if \\n is a printable characterstring = 'My name is \\n Ayush'print(string.isprintable()) # checking if space is a printable characterstring = ''print( string.isprintable())", "e": 26942, "s": 26616, "text": null }, { "code": null, "e": 26951, "s": 26942, "text": "Output: " }, { "code": null, "e": 26967, "s": 26951, "text": "True\nFalse\nTrue" }, { "code": null, "e": 27104, "s": 26967, "text": "Given a string in python, count the number of non-printable characters in the string and replace non-printable characters with a space. " }, { "code": null, "e": 27254, "s": 27104, "text": "Input : string = 'My name is Ayush'\nOutput : 0\n My name is Ayush\n\nInput : string = 'My\\nname\\nis\\nAyush'\nOutput : 3\n My name is Ayush" }, { "code": null, "e": 27266, "s": 27254, "text": "Algorithm: " }, { "code": null, "e": 27664, "s": 27266, "text": "Initialize an empty new string and a variable count = 0. Traverse the given string character by character up to its length, check if the character is a non-printable character. If it is a non-printable character, increment the counter by 1, and add a space to the new string. Else if it is a printable character, add it to the new string as it is.Print the value of the counter and the new string." }, { "code": null, "e": 27722, "s": 27664, "text": "Initialize an empty new string and a variable count = 0. " }, { "code": null, "e": 27843, "s": 27722, "text": "Traverse the given string character by character up to its length, check if the character is a non-printable character. " }, { "code": null, "e": 27943, "s": 27843, "text": "If it is a non-printable character, increment the counter by 1, and add a space to the new string. " }, { "code": null, "e": 28015, "s": 27943, "text": "Else if it is a printable character, add it to the new string as it is." }, { "code": null, "e": 28066, "s": 28015, "text": "Print the value of the counter and the new string." }, { "code": null, "e": 28074, "s": 28066, "text": "Python3" }, { "code": "# Python implementation to count # non-printable characters in a string # Given string and new stringstring ='GeeksforGeeks\\nname\\nis\\nCS portal'newstring = '' # Initialising the counter to 0count = 0 # Iterating the string and # checking for non-printable characters# Incrementing the counter if a # non-printable character is found # and replacing it by space in the newstring # Finally printing the count and newstring for a in string: if (a.isprintable()) == False: count+= 1 newstring+=' ' else: newstring+= aprint(count)print(newstring)", "e": 28661, "s": 28074, "text": null }, { "code": null, "e": 28670, "s": 28661, "text": "Output: " }, { "code": null, "e": 28704, "s": 28670, "text": "3\nGeeksforGeeks name is CS portal" }, { "code": null, "e": 28720, "s": 28704, "text": "AmiyaRanjanRout" }, { "code": null, "e": 28746, "s": 28720, "text": "Python-Built-in-functions" }, { "code": null, "e": 28753, "s": 28746, "text": "Python" }, { "code": null, "e": 28851, "s": 28753, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28879, "s": 28851, "text": "Read JSON file using Python" }, { "code": null, "e": 28929, "s": 28879, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 28951, "s": 28929, "text": "Python map() function" }, { "code": null, "e": 28995, "s": 28951, "text": "How to get column names in Pandas dataframe" }, { "code": null, "e": 29013, "s": 28995, "text": "Python Dictionary" }, { "code": null, "e": 29048, "s": 29013, "text": "Read a file line by line in Python" }, { "code": null, "e": 29071, "s": 29048, "text": "Taking input in Python" }, { "code": null, "e": 29103, "s": 29071, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29125, "s": 29103, "text": "Enumerate() in Python" } ]
Sending a Text Message Over the Phone Using SmsManager in Android - GeeksforGeeks
23 Dec, 2021 This article is about sending a text SMS over the phone using the SMSManager class in an Android application. For this, a basic knowledge of the fundamentals of android app development, creating a new project, running an android app, Views, and handling of click event buttons is required. SMSManager class manages operations like sending a text message, data message, and multimedia messages (MMS). For sending a text message method sendTextMessage() is used likewise for multimedia message sendMultimediaMessage() and for data message sendDataMessage() method is used. The details of each function are: Function Description Below is an example of a basic application that sends a text message. Step 1: Create a new Android Application. Step 2: Go to AndroidManifest.xml. app->Manifest->AndroidManifest.xml Step 3: In AndroidManifest.xml add the permission to send SMS. It will permit an android application to send SMS. <uses-permission android:name=” android.permission.SEND_SMS ” /> AndroidManifest.xml <?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" xmlns:dist="http://schemas.android.com/apk/distribution" package="com.example.gfg"> <uses-permission android:name="android.permission.SEND_SMS"/> <dist:module dist:instant="true" /> <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> Step 4: Open activity_main.xml from the following address and add the below code. Here, in a Linear Layout, two edittext for taking phone number and a text message and a button for sending the message is added. app->res->layout->activitymain.xml activity_main.xml <?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:orientation="vertical" android:layout_marginTop="140dp" android:layout_height="match_parent" tools:context=".MainActivity"> <EditText android:id="@+id/editText" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter number" android:inputType="textPersonName" /> <EditText android:id="@+id/editText2" android:layout_width="match_parent" android:layout_height="wrap_content" android:ems="10" android:hint="Enter message" android:inputType="textPersonName" /> <Button android:id="@+id/button" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="20dp" android:layout_marginLeft="60dp" android:layout_marginRight="60dp" android:text="SEND" /></LinearLayout> Step 5: Open MainActivity.java app->java->com.example.gfg->MainActivity Create objects for views used i.e., editTexts and button. In the onCreate method find all the views using the findViewById() method. Viewtype object =(ViewType)findViewById(R.id.IdOfView); Since the Send button is for sending the message so onClickListener is added with the button. Now create two string variables and store the value of editText phone number and message into them using method getText() (before assigning convert them to a string using toString() method). Now in try block create an instance of SMSManager class and get the SMSManager associated with the default subscription id. Now call method sendTextMessage() to send message. SmsManager smsManager=SmsManager.getDefault(); smsManager.sendTextMessage(number,null,msg,null,null); Then display the toast message as “Message sent ” and close the try block. At last in catch block display a toast message because the message was not sent if the compiler executes this block of the code. MainActivity.java package com.example.gfg; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText phonenumber,message; Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); send=findViewById(R.id.button); phonenumber=findViewById(R.id.editText); message=findViewById(R.id.editText2); send.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String number=phonenumber.getText().toString(); String msg=message.getText().toString(); try { SmsManager smsManager=SmsManager.getDefault(); smsManager.sendTextMessage(number,null,msg,null,null); Toast.makeText(getApplicationContext(),"Message Sent",Toast.LENGTH_LONG).show(); }catch (Exception e) { Toast.makeText(getApplicationContext(),"Some fiedls is Empty",Toast.LENGTH_LONG).show(); } } }); }} Note: For running application in Android device enable the SMS permission for the app. Goto permissions->SMS->YourApp and enable permission. Output: Sending the message Sent message in the messaging app android Android Java Java Android Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Create and Add Data to SQLite Database in Android? Resource Raw Folder in Android Studio Broadcast Receiver in Android With Example Services in Android with Example Android RecyclerView in Kotlin Arrays in Java Split() String method in Java with examples For-each loop in Java Object Oriented Programming (OOPs) Concept in Java Arrays.sort() in Java with examples
[ { "code": null, "e": 26049, "s": 26021, "text": "\n23 Dec, 2021" }, { "code": null, "e": 26341, "s": 26049, "text": "This article is about sending a text SMS over the phone using the SMSManager class in an Android application. For this, a basic knowledge of the fundamentals of android app development, creating a new project, running an android app, Views, and handling of click event buttons is required." }, { "code": null, "e": 26657, "s": 26341, "text": "SMSManager class manages operations like sending a text message, data message, and multimedia messages (MMS). For sending a text message method sendTextMessage() is used likewise for multimedia message sendMultimediaMessage() and for data message sendDataMessage() method is used. The details of each function are:" }, { "code": null, "e": 26666, "s": 26657, "text": "Function" }, { "code": null, "e": 26678, "s": 26666, "text": "Description" }, { "code": null, "e": 26749, "s": 26678, "text": "Below is an example of a basic application that sends a text message. " }, { "code": null, "e": 26793, "s": 26751, "text": "Step 1: Create a new Android Application." }, { "code": null, "e": 26828, "s": 26793, "text": "Step 2: Go to AndroidManifest.xml." }, { "code": null, "e": 26863, "s": 26828, "text": "app->Manifest->AndroidManifest.xml" }, { "code": null, "e": 26979, "s": 26865, "text": "Step 3: In AndroidManifest.xml add the permission to send SMS. It will permit an android application to send SMS." }, { "code": null, "e": 27045, "s": 26979, "text": "<uses-permission android:name=” android.permission.SEND_SMS ” /> " }, { "code": null, "e": 27065, "s": 27045, "text": "AndroidManifest.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:dist=\"http://schemas.android.com/apk/distribution\" package=\"com.example.gfg\"> <uses-permission android:name=\"android.permission.SEND_SMS\"/> <dist:module dist:instant=\"true\" /> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>", "e": 27925, "s": 27065, "text": null }, { "code": null, "e": 28137, "s": 27925, "text": " Step 4: Open activity_main.xml from the following address and add the below code. Here, in a Linear Layout, two edittext for taking phone number and a text message and a button for sending the message is added." }, { "code": null, "e": 28172, "s": 28137, "text": "app->res->layout->activitymain.xml" }, { "code": null, "e": 28190, "s": 28172, "text": "activity_main.xml" }, { "code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:orientation=\"vertical\" android:layout_marginTop=\"140dp\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <EditText android:id=\"@+id/editText\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:ems=\"10\" android:hint=\"Enter number\" android:inputType=\"textPersonName\" /> <EditText android:id=\"@+id/editText2\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:ems=\"10\" android:hint=\"Enter message\" android:inputType=\"textPersonName\" /> <Button android:id=\"@+id/button\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_marginTop=\"20dp\" android:layout_marginLeft=\"60dp\" android:layout_marginRight=\"60dp\" android:text=\"SEND\" /></LinearLayout>", "e": 29370, "s": 28190, "text": null }, { "code": null, "e": 29402, "s": 29370, "text": " Step 5: Open MainActivity.java" }, { "code": null, "e": 29443, "s": 29402, "text": "app->java->com.example.gfg->MainActivity" }, { "code": null, "e": 29578, "s": 29443, "text": "Create objects for views used i.e., editTexts and button. In the onCreate method find all the views using the findViewById() method. " }, { "code": null, "e": 29634, "s": 29578, "text": "Viewtype object =(ViewType)findViewById(R.id.IdOfView);" }, { "code": null, "e": 30094, "s": 29634, "text": "Since the Send button is for sending the message so onClickListener is added with the button. Now create two string variables and store the value of editText phone number and message into them using method getText() (before assigning convert them to a string using toString() method). Now in try block create an instance of SMSManager class and get the SMSManager associated with the default subscription id. Now call method sendTextMessage() to send message." }, { "code": null, "e": 30141, "s": 30094, "text": "SmsManager smsManager=SmsManager.getDefault();" }, { "code": null, "e": 30196, "s": 30141, "text": "smsManager.sendTextMessage(number,null,msg,null,null);" }, { "code": null, "e": 30401, "s": 30196, "text": "Then display the toast message as “Message sent ” and close the try block. At last in catch block display a toast message because the message was not sent if the compiler executes this block of the code. " }, { "code": null, "e": 30419, "s": 30401, "text": "MainActivity.java" }, { "code": "package com.example.gfg; import androidx.appcompat.app.AppCompatActivity; import android.os.Bundle;import android.telephony.SmsManager;import android.view.View;import android.widget.Button;import android.widget.EditText;import android.widget.Toast; public class MainActivity extends AppCompatActivity { EditText phonenumber,message; Button send; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); send=findViewById(R.id.button); phonenumber=findViewById(R.id.editText); message=findViewById(R.id.editText2); send.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { String number=phonenumber.getText().toString(); String msg=message.getText().toString(); try { SmsManager smsManager=SmsManager.getDefault(); smsManager.sendTextMessage(number,null,msg,null,null); Toast.makeText(getApplicationContext(),\"Message Sent\",Toast.LENGTH_LONG).show(); }catch (Exception e) { Toast.makeText(getApplicationContext(),\"Some fiedls is Empty\",Toast.LENGTH_LONG).show(); } } }); }}", "e": 31759, "s": 30419, "text": null }, { "code": null, "e": 31848, "s": 31761, "text": "Note: For running application in Android device enable the SMS permission for the app." }, { "code": null, "e": 31902, "s": 31848, "text": "Goto permissions->SMS->YourApp and enable permission." }, { "code": null, "e": 31910, "s": 31902, "text": "Output:" }, { "code": null, "e": 31930, "s": 31910, "text": "Sending the message" }, { "code": null, "e": 31964, "s": 31930, "text": "Sent message in the messaging app" }, { "code": null, "e": 31972, "s": 31964, "text": "android" }, { "code": null, "e": 31980, "s": 31972, "text": "Android" }, { "code": null, "e": 31985, "s": 31980, "text": "Java" }, { "code": null, "e": 31990, "s": 31985, "text": "Java" }, { "code": null, "e": 31998, "s": 31990, "text": "Android" }, { "code": null, "e": 32096, "s": 31998, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32154, "s": 32096, "text": "How to Create and Add Data to SQLite Database in Android?" }, { "code": null, "e": 32192, "s": 32154, "text": "Resource Raw Folder in Android Studio" }, { "code": null, "e": 32235, "s": 32192, "text": "Broadcast Receiver in Android With Example" }, { "code": null, "e": 32268, "s": 32235, "text": "Services in Android with Example" }, { "code": null, "e": 32299, "s": 32268, "text": "Android RecyclerView in Kotlin" }, { "code": null, "e": 32314, "s": 32299, "text": "Arrays in Java" }, { "code": null, "e": 32358, "s": 32314, "text": "Split() String method in Java with examples" }, { "code": null, "e": 32380, "s": 32358, "text": "For-each loop in Java" }, { "code": null, "e": 32431, "s": 32380, "text": "Object Oriented Programming (OOPs) Concept in Java" } ]
Replace NaN Values with Zeros in Pandas DataFrame - GeeksforGeeks
03 Jul, 2020 NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results. Methods to replace NaN values with zeros in Pandas DataFrame: fillna()The fillna() function is used to fill NA/NaN values using the specified method. replace()The dataframe.replace() function in Pandas can be defined as a simple method used to replace a string, regex, list, dictionary etc. in a DataFrame. Steps to replace NaN values: For one column using pandas:df['DataFrame Column'] = df['DataFrame Column'].fillna(0) df['DataFrame Column'] = df['DataFrame Column'].fillna(0) For one column using numpy:df['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0) df['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0) For the whole DataFrame using pandas:df.fillna(0) df.fillna(0) For the whole DataFrame using numpy:df.replace(np.nan, 0) df.replace(np.nan, 0) Method 1: Using fillna() function for a single column Example: # importing librariesimport pandas as pdimport numpy as np nums = {'Set_of_Numbers': [2, 3, 5, 7, 11, 13, np.nan, 19, 23, np.nan]} # Create the dataframedf = pd.DataFrame(nums, columns =['Set_of_Numbers']) # Apply the functiondf['Set_of_Numbers'] = df['Set_of_Numbers'].fillna(0) # print the DataFramedf Output: Example: # importing librariesimport pandas as pdimport numpy as np nums = {'Car Model Number': [223, np.nan, 237, 195, np.nan, 575, 110, 313, np.nan, 190, 143, np.nan], 'Engine Number': [4511, np.nan, 7570, 1565, 1450, 3786, 2995, 5345, 7777, 2323, 2785, 1120]} # Create the dataframedf = pd.DataFrame(nums, columns =['Car Model Number']) # Apply the functiondf['Car Model Number'] = df['Car Model Number'].replace(np.nan, 0) # print the DataFramedf Output: Example: # importing librariesimport pandas as pdimport numpy as np nums = {'Number_set_1': [0, 1, 1, 2, 3, 5, np.nan, 13, 21, np.nan], 'Number_set_2': [3, 7, np.nan, 23, 31, 41, np.nan, 59, 67, np.nan], 'Number_set_3': [2, 3, 5, np.nan, 11, 13, 17, 19, 23, np.nan]} # Create the dataframedf = pd.DataFrame(nums) # Apply the functiondf = df.fillna(0) # print the DataFramedf Output: Example: # importing librariesimport pandas as pdimport numpy as np nums = {'Student Name': [ 'Shrek', 'Shivansh', 'Ishdeep', 'Siddharth', 'Nakul', 'Prakhar', 'Yash', 'Srikar', 'Kaustubh', 'Aditya', 'Manav', 'Dubey'], 'Roll No.': [ 18229, 18232, np.nan, 18247, 18136, np.nan, 18283, 18310, 18102, 18012, 18121, 18168], 'Subject ID': [204, np.nan, 201, 105, np.nan, 204, 101, 101, np.nan, 165, 715, np.nan], 'Grade Point': [9, np.nan, 7, np.nan, 8, 7, 9, 10, np.nan, 9, 6, 8]} # Create the dataframedf = pd.DataFrame(nums) # Apply the functiondf = df.replace(np.nan, 0) # print the DataFramedf 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 Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Iterate over a list in Python Python String | replace() *args and **kwargs in Python Reading and Writing to text files in Python Create a Pandas DataFrame from Lists
[ { "code": null, "e": 26039, "s": 26011, "text": "\n03 Jul, 2020" }, { "code": null, "e": 26364, "s": 26039, "text": "NaN stands for Not A Number and is one of the common ways to represent the missing value in the data. It is a special floating-point value and cannot be converted to any other type than float. NaN value is one of the major problems in Data Analysis. It is very essential to deal with NaN in order to get the desired results." }, { "code": null, "e": 26426, "s": 26364, "text": "Methods to replace NaN values with zeros in Pandas DataFrame:" }, { "code": null, "e": 26514, "s": 26426, "text": "fillna()The fillna() function is used to fill NA/NaN values using the specified method." }, { "code": null, "e": 26671, "s": 26514, "text": "replace()The dataframe.replace() function in Pandas can be defined as a simple method used to replace a string, regex, list, dictionary etc. in a DataFrame." }, { "code": null, "e": 26700, "s": 26671, "text": "Steps to replace NaN values:" }, { "code": null, "e": 26787, "s": 26700, "text": "For one column using pandas:df['DataFrame Column'] = df['DataFrame Column'].fillna(0)\n" }, { "code": null, "e": 26846, "s": 26787, "text": "df['DataFrame Column'] = df['DataFrame Column'].fillna(0)\n" }, { "code": null, "e": 26941, "s": 26846, "text": "For one column using numpy:df['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0)\n" }, { "code": null, "e": 27009, "s": 26941, "text": "df['DataFrame Column'] = df['DataFrame Column'].replace(np.nan, 0)\n" }, { "code": null, "e": 27060, "s": 27009, "text": "For the whole DataFrame using pandas:df.fillna(0)\n" }, { "code": null, "e": 27074, "s": 27060, "text": "df.fillna(0)\n" }, { "code": null, "e": 27133, "s": 27074, "text": "For the whole DataFrame using numpy:df.replace(np.nan, 0)\n" }, { "code": null, "e": 27156, "s": 27133, "text": "df.replace(np.nan, 0)\n" }, { "code": null, "e": 27210, "s": 27156, "text": "Method 1: Using fillna() function for a single column" }, { "code": null, "e": 27219, "s": 27210, "text": "Example:" }, { "code": "# importing librariesimport pandas as pdimport numpy as np nums = {'Set_of_Numbers': [2, 3, 5, 7, 11, 13, np.nan, 19, 23, np.nan]} # Create the dataframedf = pd.DataFrame(nums, columns =['Set_of_Numbers']) # Apply the functiondf['Set_of_Numbers'] = df['Set_of_Numbers'].fillna(0) # print the DataFramedf", "e": 27554, "s": 27219, "text": null }, { "code": null, "e": 27562, "s": 27554, "text": "Output:" }, { "code": null, "e": 27571, "s": 27562, "text": "Example:" }, { "code": "# importing librariesimport pandas as pdimport numpy as np nums = {'Car Model Number': [223, np.nan, 237, 195, np.nan, 575, 110, 313, np.nan, 190, 143, np.nan], 'Engine Number': [4511, np.nan, 7570, 1565, 1450, 3786, 2995, 5345, 7777, 2323, 2785, 1120]} # Create the dataframedf = pd.DataFrame(nums, columns =['Car Model Number']) # Apply the functiondf['Car Model Number'] = df['Car Model Number'].replace(np.nan, 0) # print the DataFramedf", "e": 28105, "s": 27571, "text": null }, { "code": null, "e": 28113, "s": 28105, "text": "Output:" }, { "code": null, "e": 28122, "s": 28113, "text": "Example:" }, { "code": "# importing librariesimport pandas as pdimport numpy as np nums = {'Number_set_1': [0, 1, 1, 2, 3, 5, np.nan, 13, 21, np.nan], 'Number_set_2': [3, 7, np.nan, 23, 31, 41, np.nan, 59, 67, np.nan], 'Number_set_3': [2, 3, 5, np.nan, 11, 13, 17, 19, 23, np.nan]} # Create the dataframedf = pd.DataFrame(nums) # Apply the functiondf = df.fillna(0) # print the DataFramedf", "e": 28575, "s": 28122, "text": null }, { "code": null, "e": 28583, "s": 28575, "text": "Output:" }, { "code": null, "e": 28592, "s": 28583, "text": "Example:" }, { "code": "# importing librariesimport pandas as pdimport numpy as np nums = {'Student Name': [ 'Shrek', 'Shivansh', 'Ishdeep', 'Siddharth', 'Nakul', 'Prakhar', 'Yash', 'Srikar', 'Kaustubh', 'Aditya', 'Manav', 'Dubey'], 'Roll No.': [ 18229, 18232, np.nan, 18247, 18136, np.nan, 18283, 18310, 18102, 18012, 18121, 18168], 'Subject ID': [204, np.nan, 201, 105, np.nan, 204, 101, 101, np.nan, 165, 715, np.nan], 'Grade Point': [9, np.nan, 7, np.nan, 8, 7, 9, 10, np.nan, 9, 6, 8]} # Create the dataframedf = pd.DataFrame(nums) # Apply the functiondf = df.replace(np.nan, 0) # print the DataFramedf", "e": 29361, "s": 28592, "text": null }, { "code": null, "e": 29369, "s": 29361, "text": "Output:" }, { "code": null, "e": 29393, "s": 29369, "text": "Python pandas-dataFrame" }, { "code": null, "e": 29407, "s": 29393, "text": "Python-pandas" }, { "code": null, "e": 29414, "s": 29407, "text": "Python" }, { "code": null, "e": 29512, "s": 29414, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29530, "s": 29512, "text": "Python Dictionary" }, { "code": null, "e": 29565, "s": 29530, "text": "Read a file line by line in Python" }, { "code": null, "e": 29597, "s": 29565, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29619, "s": 29597, "text": "Enumerate() in Python" }, { "code": null, "e": 29661, "s": 29619, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29691, "s": 29661, "text": "Iterate over a list in Python" }, { "code": null, "e": 29717, "s": 29691, "text": "Python String | replace()" }, { "code": null, "e": 29746, "s": 29717, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29790, "s": 29746, "text": "Reading and Writing to text files in Python" } ]
Replace each Matrix element with its row product except that element - GeeksforGeeks
17 Jan, 2022 Given a 2D-array mat[][] of order M*N. The task is to replace every element of each row with the product of other elements of the same row. Examples: Input: mat[][] = {{3, 4, 1}, {6, 1, 7}, {2, 9, 8}}Output:4, 3, 127, 42, 672, 16, 18 Input: mat[][] = {{13, 4, 5}, {6, 11, 1}}Output:20, 65, 5211, 6, 66 Approach: The idea is straightforward. Traverse the matrix row-wise and find the product of each row. In the second traversal find the replacement value for each cell of the row. Follow the steps below to solve the problem: Initialize the variables mul, i and j. Iterate over the range [0, M) using the variable i and perform the following tasks:Set the value of mul as 1.Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mul as mul*mat[i][j].Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mat[i][j] as mul/mat[i][j]. Set the value of mul as 1. Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mul as mul*mat[i][j]. Set the value of mul as mul*mat[i][j]. Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mat[i][j] as mul/mat[i][j]. Set the value of mat[i][j] as mul/mat[i][j]. After performing the above steps, print the values of mat[][] as the answer. 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;const int M = 3, N = 3; // Show Matrix.void showMatrix(vector<vector<int> >& mat){ int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { cout << mat[i][j] << " "; } cout << endl; }} // Utility Functionvoid ReplaceWithProduct(vector<vector<int> >& mat){ int mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i][j]; for (j = 0; j < N; j++) mat[i][j] = mul / mat[i][j]; } showMatrix(mat);} // Utility Main function.int main(){ vector<vector<int> > mat = { { 3, 6, 2 }, { 1, 4, 9 }, { 5, 3, 8 } }; ReplaceWithProduct(mat); return 0;} // Java program for the above approachimport java.util.*;public class GFG{ static int M = 3, N = 3; // Show Matrix. static void showMatrix(int [][]mat) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { System.out.print(mat[i][j] + " "); } System.out.println(); } } // Utility Function static void ReplaceWithProduct(int [][]mat) { int mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i][j]; for (j = 0; j < N; j++) mat[i][j] = mul / mat[i][j]; } showMatrix(mat); } // Utility Main function. public static void main(String args[]) { int [][]mat = { { 3, 6, 2 }, { 1, 4, 9 }, { 5, 3, 8 } }; ReplaceWithProduct(mat); }} // This code is contributed by Samim Hossain Mondal. # python3 program for the above approachM = 3N = 3 # Show Matrix.def showMatrix(mat): for i in range(0, M): for j in range(0, N): print(mat[i][j], end=" ") print() # Utility Functiondef ReplaceWithProduct(mat): for i in range(0, M): mul = 1 for j in range(0, N): mul *= mat[i][j] for j in range(0, N): mat[i][j] = mul // mat[i][j] showMatrix(mat) # Utility Main function.if __name__ == "__main__": mat = [[3, 6, 2], [1, 4, 9], [5, 3, 8]] ReplaceWithProduct(mat) # This code is contributed by rakeshsahni // C# program for the above approachusing System;public class GFG{ static int M = 3, N = 3; // Show Matrix. static void showMatrix(int [,]mat) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { Console.Write(mat[i,j] + " "); } Console.WriteLine(); } } // Utility Function static void ReplaceWithProduct(int [,]mat) { int mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i,j]; for (j = 0; j < N; j++) mat[i,j] = mul / mat[i,j]; } showMatrix(mat); } // Utility Main function. public static void Main(String []args) { int [,]mat = { { 3, 6, 2 }, { 1, 4, 9 }, { 5, 3, 8 } }; ReplaceWithProduct(mat); }} // This code is contributed by 29AjayKumar <script> // JavaScript code for the above approach let M = 3, N = 3; // Show Matrix. function showMatrix(mat) { let i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { document.write(mat[i][j] + " "); } document.write('<br>') } } // Utility Function function ReplaceWithProduct(mat) { let mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i][j]; for (j = 0; j < N; j++) mat[i][j] = mul / mat[i][j]; } showMatrix(mat); } // Utility Main function. let mat = [[3, 6, 2], [1, 4, 9], [5, 3, 8]]; ReplaceWithProduct(mat); // This code is contributed by Potta Lokesh </script> 12 6 18 36 9 4 24 40 15 Time Complexity: O(N*N)Auxiliary Space: O(1) lokeshpotta20 samim2000 rakeshsahni 29AjayKumar Algo-Geek 2021 Algo Geek Matrix Matrix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Check if the given string is valid English word or not Sort strings on the basis of their numeric part Smallest set of vertices to visit all nodes of the given Graph Divide given number into two even parts Bit Manipulation technique to replace boolean arrays of fixed size less than 64 Program to find largest element in an array Matrix Chain Multiplication | DP-8 Rat in a Maze | Backtracking-2 Breadth First Traversal ( BFS ) on a 2D array Print a given matrix in spiral form
[ { "code": null, "e": 27533, "s": 27505, "text": "\n17 Jan, 2022" }, { "code": null, "e": 27673, "s": 27533, "text": "Given a 2D-array mat[][] of order M*N. The task is to replace every element of each row with the product of other elements of the same row." }, { "code": null, "e": 27684, "s": 27673, "text": "Examples: " }, { "code": null, "e": 27781, "s": 27684, "text": "Input: mat[][] = {{3, 4, 1}, {6, 1, 7}, {2, 9, 8}}Output:4, 3, 127, 42, 672, 16, 18 " }, { "code": null, "e": 27849, "s": 27781, "text": "Input: mat[][] = {{13, 4, 5}, {6, 11, 1}}Output:20, 65, 5211, 6, 66" }, { "code": null, "e": 28073, "s": 27849, "text": "Approach: The idea is straightforward. Traverse the matrix row-wise and find the product of each row. In the second traversal find the replacement value for each cell of the row. Follow the steps below to solve the problem:" }, { "code": null, "e": 28112, "s": 28073, "text": "Initialize the variables mul, i and j." }, { "code": null, "e": 28470, "s": 28112, "text": "Iterate over the range [0, M) using the variable i and perform the following tasks:Set the value of mul as 1.Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mul as mul*mat[i][j].Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mat[i][j] as mul/mat[i][j]." }, { "code": null, "e": 28497, "s": 28470, "text": "Set the value of mul as 1." }, { "code": null, "e": 28619, "s": 28497, "text": "Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mul as mul*mat[i][j]." }, { "code": null, "e": 28658, "s": 28619, "text": "Set the value of mul as mul*mat[i][j]." }, { "code": null, "e": 28786, "s": 28658, "text": "Iterate over the range [0, N) using the variable j and perform the following tasks:Set the value of mat[i][j] as mul/mat[i][j]." }, { "code": null, "e": 28831, "s": 28786, "text": "Set the value of mat[i][j] as mul/mat[i][j]." }, { "code": null, "e": 28908, "s": 28831, "text": "After performing the above steps, print the values of mat[][] as the answer." }, { "code": null, "e": 28959, "s": 28908, "text": "Below is the implementation of the above approach." }, { "code": null, "e": 28963, "s": 28959, "text": "C++" }, { "code": null, "e": 28968, "s": 28963, "text": "Java" }, { "code": null, "e": 28976, "s": 28968, "text": "Python3" }, { "code": null, "e": 28979, "s": 28976, "text": "C#" }, { "code": null, "e": 28990, "s": 28979, "text": "Javascript" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std;const int M = 3, N = 3; // Show Matrix.void showMatrix(vector<vector<int> >& mat){ int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { cout << mat[i][j] << \" \"; } cout << endl; }} // Utility Functionvoid ReplaceWithProduct(vector<vector<int> >& mat){ int mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i][j]; for (j = 0; j < N; j++) mat[i][j] = mul / mat[i][j]; } showMatrix(mat);} // Utility Main function.int main(){ vector<vector<int> > mat = { { 3, 6, 2 }, { 1, 4, 9 }, { 5, 3, 8 } }; ReplaceWithProduct(mat); return 0;}", "e": 29809, "s": 28990, "text": null }, { "code": "// Java program for the above approachimport java.util.*;public class GFG{ static int M = 3, N = 3; // Show Matrix. static void showMatrix(int [][]mat) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { System.out.print(mat[i][j] + \" \"); } System.out.println(); } } // Utility Function static void ReplaceWithProduct(int [][]mat) { int mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i][j]; for (j = 0; j < N; j++) mat[i][j] = mul / mat[i][j]; } showMatrix(mat); } // Utility Main function. public static void main(String args[]) { int [][]mat = { { 3, 6, 2 }, { 1, 4, 9 }, { 5, 3, 8 } }; ReplaceWithProduct(mat); }} // This code is contributed by Samim Hossain Mondal.", "e": 30656, "s": 29809, "text": null }, { "code": "# python3 program for the above approachM = 3N = 3 # Show Matrix.def showMatrix(mat): for i in range(0, M): for j in range(0, N): print(mat[i][j], end=\" \") print() # Utility Functiondef ReplaceWithProduct(mat): for i in range(0, M): mul = 1 for j in range(0, N): mul *= mat[i][j] for j in range(0, N): mat[i][j] = mul // mat[i][j] showMatrix(mat) # Utility Main function.if __name__ == \"__main__\": mat = [[3, 6, 2], [1, 4, 9], [5, 3, 8]] ReplaceWithProduct(mat) # This code is contributed by rakeshsahni", "e": 31268, "s": 30656, "text": null }, { "code": "// C# program for the above approachusing System;public class GFG{ static int M = 3, N = 3; // Show Matrix. static void showMatrix(int [,]mat) { int i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { Console.Write(mat[i,j] + \" \"); } Console.WriteLine(); } } // Utility Function static void ReplaceWithProduct(int [,]mat) { int mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i,j]; for (j = 0; j < N; j++) mat[i,j] = mul / mat[i,j]; } showMatrix(mat); } // Utility Main function. public static void Main(String []args) { int [,]mat = { { 3, 6, 2 }, { 1, 4, 9 }, { 5, 3, 8 } }; ReplaceWithProduct(mat); }} // This code is contributed by 29AjayKumar", "e": 32086, "s": 31268, "text": null }, { "code": "<script> // JavaScript code for the above approach let M = 3, N = 3; // Show Matrix. function showMatrix(mat) { let i, j; for (i = 0; i < M; i++) { for (j = 0; j < N; j++) { document.write(mat[i][j] + \" \"); } document.write('<br>') } } // Utility Function function ReplaceWithProduct(mat) { let mul, i, j; for (i = 0; i < M; i++) { mul = 1; for (j = 0; j < N; j++) mul *= mat[i][j]; for (j = 0; j < N; j++) mat[i][j] = mul / mat[i][j]; } showMatrix(mat); } // Utility Main function. let mat = [[3, 6, 2], [1, 4, 9], [5, 3, 8]]; ReplaceWithProduct(mat); // This code is contributed by Potta Lokesh </script>", "e": 32956, "s": 32086, "text": null }, { "code": null, "e": 32982, "s": 32956, "text": "12 6 18 \n36 9 4 \n24 40 15" }, { "code": null, "e": 33029, "s": 32984, "text": "Time Complexity: O(N*N)Auxiliary Space: O(1)" }, { "code": null, "e": 33043, "s": 33029, "text": "lokeshpotta20" }, { "code": null, "e": 33053, "s": 33043, "text": "samim2000" }, { "code": null, "e": 33065, "s": 33053, "text": "rakeshsahni" }, { "code": null, "e": 33077, "s": 33065, "text": "29AjayKumar" }, { "code": null, "e": 33092, "s": 33077, "text": "Algo-Geek 2021" }, { "code": null, "e": 33102, "s": 33092, "text": "Algo Geek" }, { "code": null, "e": 33109, "s": 33102, "text": "Matrix" }, { "code": null, "e": 33116, "s": 33109, "text": "Matrix" }, { "code": null, "e": 33214, "s": 33116, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33269, "s": 33214, "text": "Check if the given string is valid English word or not" }, { "code": null, "e": 33317, "s": 33269, "text": "Sort strings on the basis of their numeric part" }, { "code": null, "e": 33380, "s": 33317, "text": "Smallest set of vertices to visit all nodes of the given Graph" }, { "code": null, "e": 33420, "s": 33380, "text": "Divide given number into two even parts" }, { "code": null, "e": 33500, "s": 33420, "text": "Bit Manipulation technique to replace boolean arrays of fixed size less than 64" }, { "code": null, "e": 33544, "s": 33500, "text": "Program to find largest element in an array" }, { "code": null, "e": 33579, "s": 33544, "text": "Matrix Chain Multiplication | DP-8" }, { "code": null, "e": 33610, "s": 33579, "text": "Rat in a Maze | Backtracking-2" }, { "code": null, "e": 33656, "s": 33610, "text": "Breadth First Traversal ( BFS ) on a 2D array" } ]
How to upload files in firebase storage using ReactJS ? - GeeksforGeeks
13 Apr, 2021 The following approach covers how to send file to firebase storage in react. We have used the firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React myapp using the following command:npx create-react-app myapp Step 1: Create a React myapp using the following command: npx create-react-app myapp Step 2: After creating your project folder i.e. myapp, move to it using the following command:cd myapp Step 2: After creating your project folder i.e. myapp, move to it using the following command: cd myapp Project structure: Our project structure will look like this. Step 3: After creating the ReactJS application, Install the firebase module using the following command: npm install [email protected] --save Step 4: Go to your firebase dashboard and create a new project and copy your credentials. const firebaseConfig = { apiKey: "your api key", authDomain: "your credentials", projectId: "your credentials", storageBucket: "your credentials", messagingSenderId: "your credentials", appId: "your credentials" }; Step 5: Initialize the Firebase into your project by creating a firebase.js file with the following code. firebase.js import firebase from 'firebase';const firebaseConfig = { // Your Credentials };firebase.initializeApp(firebaseConfig);var storage = firebase.storage();export default storage; Step 6: Now go to your storage section in the firebase project and update your security rules. Here we are in testing mode, so we allow both read and write as true. After updating the code shown below. Click on publish. Step 7: Now create a basic UI for our project. Here we have created an input for selecting the file and a button that uploads the file on firebase storage. App.js function App() { return ( <div className="App"> <center> <input type="file"/> <button>Upload</button> </center> </div> );} export default App; Step 8: Now implement the uploading part. Here, We are going to use a method called put which helps us to send files to firebase storage. App.js import {useState} from 'react';import storage from './firebase';function App() {const [image , setImage] = useState('');const upload = ()=>{ if(image == null) return; storage.ref(`/images/${image.name}`).put(image) .on("state_changed" , alert("success") , alert);} return ( <div className="App"> <center> <input type="file" onChange={(e)=>{setImage(e.target.files[0])}}/> <button onClick={upload}>Upload</button> </center> </div> );} export default App; Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Here is the image in the firebase storage which we uploaded as shown below: Firebase React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. ReactJS useNavigate() Hook How to set background images in ReactJS ? Axios in React: A Guide for Beginners How to create a table in ReactJS ? How to navigate on path by button click in react router ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26095, "s": 26067, "text": "\n13 Apr, 2021" }, { "code": null, "e": 26220, "s": 26095, "text": "The following approach covers how to send file to firebase storage in react. We have used the firebase module to achieve so." }, { "code": null, "e": 26270, "s": 26220, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 26354, "s": 26270, "text": "Step 1: Create a React myapp using the following command:npx create-react-app myapp" }, { "code": null, "e": 26412, "s": 26354, "text": "Step 1: Create a React myapp using the following command:" }, { "code": null, "e": 26439, "s": 26412, "text": "npx create-react-app myapp" }, { "code": null, "e": 26542, "s": 26439, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:cd myapp" }, { "code": null, "e": 26637, "s": 26542, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:" }, { "code": null, "e": 26646, "s": 26637, "text": "cd myapp" }, { "code": null, "e": 26708, "s": 26646, "text": "Project structure: Our project structure will look like this." }, { "code": null, "e": 26813, "s": 26708, "text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command:" }, { "code": null, "e": 26847, "s": 26813, "text": "npm install [email protected] --save" }, { "code": null, "e": 26937, "s": 26847, "text": "Step 4: Go to your firebase dashboard and create a new project and copy your credentials." }, { "code": null, "e": 27188, "s": 26937, "text": "const firebaseConfig = {\n apiKey: \"your api key\",\n authDomain: \"your credentials\",\n projectId: \"your credentials\",\n storageBucket: \"your credentials\",\n messagingSenderId: \"your credentials\",\n appId: \"your credentials\"\n};" }, { "code": null, "e": 27294, "s": 27188, "text": "Step 5: Initialize the Firebase into your project by creating a firebase.js file with the following code." }, { "code": null, "e": 27306, "s": 27294, "text": "firebase.js" }, { "code": "import firebase from 'firebase';const firebaseConfig = { // Your Credentials };firebase.initializeApp(firebaseConfig);var storage = firebase.storage();export default storage;", "e": 27485, "s": 27306, "text": null }, { "code": null, "e": 27706, "s": 27485, "text": "Step 6: Now go to your storage section in the firebase project and update your security rules. Here we are in testing mode, so we allow both read and write as true. After updating the code shown below. Click on publish. " }, { "code": null, "e": 27862, "s": 27706, "text": "Step 7: Now create a basic UI for our project. Here we have created an input for selecting the file and a button that uploads the file on firebase storage." }, { "code": null, "e": 27869, "s": 27862, "text": "App.js" }, { "code": "function App() { return ( <div className=\"App\"> <center> <input type=\"file\"/> <button>Upload</button> </center> </div> );} export default App;", "e": 28041, "s": 27869, "text": null }, { "code": null, "e": 28179, "s": 28041, "text": "Step 8: Now implement the uploading part. Here, We are going to use a method called put which helps us to send files to firebase storage." }, { "code": null, "e": 28186, "s": 28179, "text": "App.js" }, { "code": "import {useState} from 'react';import storage from './firebase';function App() {const [image , setImage] = useState('');const upload = ()=>{ if(image == null) return; storage.ref(`/images/${image.name}`).put(image) .on(\"state_changed\" , alert(\"success\") , alert);} return ( <div className=\"App\"> <center> <input type=\"file\" onChange={(e)=>{setImage(e.target.files[0])}}/> <button onClick={upload}>Upload</button> </center> </div> );} export default App;", "e": 28677, "s": 28186, "text": null }, { "code": null, "e": 28790, "s": 28677, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 28800, "s": 28790, "text": "npm start" }, { "code": null, "e": 28899, "s": 28800, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 28975, "s": 28899, "text": "Here is the image in the firebase storage which we uploaded as shown below:" }, { "code": null, "e": 28984, "s": 28975, "text": "Firebase" }, { "code": null, "e": 29000, "s": 28984, "text": "React-Questions" }, { "code": null, "e": 29008, "s": 29000, "text": "ReactJS" }, { "code": null, "e": 29025, "s": 29008, "text": "Web Technologies" }, { "code": null, "e": 29123, "s": 29025, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29150, "s": 29123, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 29192, "s": 29150, "text": "How to set background images in ReactJS ?" }, { "code": null, "e": 29230, "s": 29192, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 29265, "s": 29230, "text": "How to create a table in ReactJS ?" }, { "code": null, "e": 29323, "s": 29265, "text": "How to navigate on path by button click in react router ?" }, { "code": null, "e": 29363, "s": 29323, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 29396, "s": 29363, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 29441, "s": 29396, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 29491, "s": 29441, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
C# | Using foreach loop in arrays - GeeksforGeeks
23 Jan, 2019 C# language provides several techniques to read a collection of items. One of which is foreach loop. The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or the collections in the program. Because the foreach loop can only iterate any array or any collections which previously declared. We cannot print a sequence of number or character using foreach loop like for loop, see below: for(i = 0; i <= 10; i++) // we cannot use foreach loop in this way to print 1 to 10 // to print 1 to 10 using foreach loop we need to declare // an array or a collection of size 10 and a variable that // can hold 1 to 10 integer Syntax of foreach Loop: foreach (Data_Type variable_name in Collection_or_array_Object_name) { //body of foreach loop } // here "in" is a keyword Here Data_Type is a data-type of the variable and variable_name is the variable which will iterate the loop condition (for example, for(int i=0; i<10;i++), here i is equivalent to variable_name). The in keyword used in foreach loop to iterate over the iterable-item(which is here the array or the collections). The in keyword selects an item from the iterable-item or the array or collection on each iteration and store it in the variable(here variable_name). Example 1: Below is the implementation of the “for” and “foreach” loop using arrays // C# program to show the use of// "for" loop and "foreach" loopusing System; class GFG { // Main Method public static void Main() { // initialize the array char[] arr = {'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; Console.Write("Array printing using for loop = "); // simple "for" loop for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i]); } Console.WriteLine(); Console.Write("Array printing using foreach loop = "); // "foreach" loop // "ch" is the variable // of type "char" // "arr" is the array // which is going to iterates foreach(char ch in arr) { Console.Write(ch); } }} Array printing using for loop = GeeksforGeeks Array printing using foreach loop = GeeksforGeeks Example 2: Traversing of an array using “foreach” loop // C# program to traverse an // array using "foreach" loopusing System; class GFG { // Main Method public static void Main() { char[] s = {'1', '4', '3', '1', '4', '3', '1', '4', '3'}; int m = 0, n = 0, p = 0; // here variable "g" is "char" type //'g' iterates through array "s" // and search for the numbers // according to below conditions foreach(char g in s) { if (g == '1') m++; else if (g == '4') n++; else p++; } Console.WriteLine("Number of '1' = {0}", m); Console.WriteLine("Number of '4' = {0}", n); Console.WriteLine("Number of '3' = {0}", p); }} Number of '1' = 3 Number of '4' = 3 Number of '3' = 3 Note: At anywhere within the scope of foreach loop, we can break out of the loop by using the break keyword, and can also go to the next iteration in the loop by using the continue keyword. Example: Using “continue” and “break” keyword in foreach loop // C# program to demonstrate the use // of continue and break statement// in foreach loopusing System; class GFG { // Main Method public static void Main() { // initialize the array int[] arr = {1, 3, 7, 5, 8, 6, 4, 2, 12}; Console.WriteLine("Using continue:"); foreach(int i in arr) { if (i == 7) continue; // here the control skips the next // line if the "i" value is 7 // this line executed because // of the "if" condition Console.Write(i + " "); } Console.WriteLine(); Console.WriteLine("Using break:"); foreach(int i in arr) { if(i == 7) // here if i become 7 then it will // skip all the further looping // statements break; Console.Write(i +" "); } }} Output: Using continue: 1 3 5 8 6 4 2 12 Using break: 1 3 CSharp-Arrays CSharp-ControlFlow Picked Technical Scripter 2018 C# Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# Convert String to Character Array in C# C# | How to insert an element in an Array? Linked List Implementation in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n23 Jan, 2019" }, { "code": null, "e": 26073, "s": 25547, "text": "C# language provides several techniques to read a collection of items. One of which is foreach loop. The foreach loop provides a simple, clean way to iterate through the elements of an collection or an array of items. One thing we must know that before using foreach loop we must declare the array or the collections in the program. Because the foreach loop can only iterate any array or any collections which previously declared. We cannot print a sequence of number or character using foreach loop like for loop, see below:" }, { "code": null, "e": 26305, "s": 26073, "text": "for(i = 0; i <= 10; i++)\n// we cannot use foreach loop in this way to print 1 to 10\n// to print 1 to 10 using foreach loop we need to declare \n// an array or a collection of size 10 and a variable that \n// can hold 1 to 10 integer\n" }, { "code": null, "e": 26329, "s": 26305, "text": "Syntax of foreach Loop:" }, { "code": null, "e": 26457, "s": 26329, "text": "foreach (Data_Type variable_name in Collection_or_array_Object_name)\n {\n //body of foreach loop\n }\n// here \"in\" is a keyword\n" }, { "code": null, "e": 26917, "s": 26457, "text": "Here Data_Type is a data-type of the variable and variable_name is the variable which will iterate the loop condition (for example, for(int i=0; i<10;i++), here i is equivalent to variable_name). The in keyword used in foreach loop to iterate over the iterable-item(which is here the array or the collections). The in keyword selects an item from the iterable-item or the array or collection on each iteration and store it in the variable(here variable_name)." }, { "code": null, "e": 27001, "s": 26917, "text": "Example 1: Below is the implementation of the “for” and “foreach” loop using arrays" }, { "code": "// C# program to show the use of// \"for\" loop and \"foreach\" loopusing System; class GFG { // Main Method public static void Main() { // initialize the array char[] arr = {'G', 'e', 'e', 'k', 's', 'f', 'o', 'r', 'G', 'e', 'e', 'k', 's'}; Console.Write(\"Array printing using for loop = \"); // simple \"for\" loop for (int i = 0; i < arr.Length; i++) { Console.Write(arr[i]); } Console.WriteLine(); Console.Write(\"Array printing using foreach loop = \"); // \"foreach\" loop // \"ch\" is the variable // of type \"char\" // \"arr\" is the array // which is going to iterates foreach(char ch in arr) { Console.Write(ch); } }}", "e": 27850, "s": 27001, "text": null }, { "code": null, "e": 27947, "s": 27850, "text": "Array printing using for loop = GeeksforGeeks\nArray printing using foreach loop = GeeksforGeeks\n" }, { "code": null, "e": 28002, "s": 27947, "text": "Example 2: Traversing of an array using “foreach” loop" }, { "code": "// C# program to traverse an // array using \"foreach\" loopusing System; class GFG { // Main Method public static void Main() { char[] s = {'1', '4', '3', '1', '4', '3', '1', '4', '3'}; int m = 0, n = 0, p = 0; // here variable \"g\" is \"char\" type //'g' iterates through array \"s\" // and search for the numbers // according to below conditions foreach(char g in s) { if (g == '1') m++; else if (g == '4') n++; else p++; } Console.WriteLine(\"Number of '1' = {0}\", m); Console.WriteLine(\"Number of '4' = {0}\", n); Console.WriteLine(\"Number of '3' = {0}\", p); }}", "e": 28792, "s": 28002, "text": null }, { "code": null, "e": 28847, "s": 28792, "text": "Number of '1' = 3\nNumber of '4' = 3\nNumber of '3' = 3\n" }, { "code": null, "e": 29037, "s": 28847, "text": "Note: At anywhere within the scope of foreach loop, we can break out of the loop by using the break keyword, and can also go to the next iteration in the loop by using the continue keyword." }, { "code": null, "e": 29099, "s": 29037, "text": "Example: Using “continue” and “break” keyword in foreach loop" }, { "code": "// C# program to demonstrate the use // of continue and break statement// in foreach loopusing System; class GFG { // Main Method public static void Main() { // initialize the array int[] arr = {1, 3, 7, 5, 8, 6, 4, 2, 12}; Console.WriteLine(\"Using continue:\"); foreach(int i in arr) { if (i == 7) continue; // here the control skips the next // line if the \"i\" value is 7 // this line executed because // of the \"if\" condition Console.Write(i + \" \"); } Console.WriteLine(); Console.WriteLine(\"Using break:\"); foreach(int i in arr) { if(i == 7) // here if i become 7 then it will // skip all the further looping // statements break; Console.Write(i +\" \"); } }}", "e": 30071, "s": 29099, "text": null }, { "code": null, "e": 30079, "s": 30071, "text": "Output:" }, { "code": null, "e": 30132, "s": 30079, "text": "Using continue:\n1 3 5 8 6 4 2 12 \nUsing break:\n1 3 \n" }, { "code": null, "e": 30146, "s": 30132, "text": "CSharp-Arrays" }, { "code": null, "e": 30165, "s": 30146, "text": "CSharp-ControlFlow" }, { "code": null, "e": 30172, "s": 30165, "text": "Picked" }, { "code": null, "e": 30196, "s": 30172, "text": "Technical Scripter 2018" }, { "code": null, "e": 30199, "s": 30196, "text": "C#" }, { "code": null, "e": 30218, "s": 30199, "text": "Technical Scripter" }, { "code": null, "e": 30316, "s": 30218, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30339, "s": 30316, "text": "Extension Method in C#" }, { "code": null, "e": 30367, "s": 30339, "text": "HashSet in C# with Examples" }, { "code": null, "e": 30384, "s": 30367, "text": "C# | Inheritance" }, { "code": null, "e": 30406, "s": 30384, "text": "Partial Classes in C#" }, { "code": null, "e": 30435, "s": 30406, "text": "C# | Generics - Introduction" }, { "code": null, "e": 30475, "s": 30435, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 30498, "s": 30475, "text": "Switch Statement in C#" }, { "code": null, "e": 30538, "s": 30498, "text": "Convert String to Character Array in C#" }, { "code": null, "e": 30581, "s": 30538, "text": "C# | How to insert an element in an Array?" } ]
Python | Scrollview widget in kivy - GeeksforGeeks
15 Sep, 2021 Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications. Kivy Tutorial – Learn Kivy with Examples. The ScrollView widget provides a scrollable/pannable viewport that is clipped at the scrollview’s bounding box. Scroll view accepts only one child and applies a window to it according to 2 properties: scroll_xscroll_y scroll_x scroll_y To determine if the interaction is a scrolling gesture, these properties are used: scroll_distance: the minimum distance to travel, defaults to 20 pixels. scroll_timeout: the maximum time period, defaults to 55 milliseconds. Note: To use the scrollview you must have to import it:from kivy.uix.scrollview import ScrollView Basic Approach: 1) import kivy 2) import kivyApp 3) import scroll view 4) import string property 5) Set minimum version(optional) 6) create the scroll view class 7) Build the .kv file within the .py file 8) Run an app Implementation of the code: Python3 # Program to explain how to use scroll view in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering textfrom kivy.uix.label import Label # The ScrollView widget provides a scrollable viewfrom kivy.uix.scrollview import ScrollView # Property that represents a string valuefrom kivy.properties import StringProperty # Static main function that starts the application loop.from kivy.base import runTouchApp # Builder is a global Kivy instance used in# widgets that you can use to load other# kv files in addition to the default ones.from kivy.lang import Builder # Build the .kv fileBuilder.load_string(''' # Define the scroll view<ScrollableLabel>: text: 'You are learning Kivy' * 500 Label: text: root.text font_size: 50 text_size: self.width, None size_hint_y: None height: self.texture_size[1]''') # Define scrollview classclass ScrollableLabel(ScrollView): text = StringProperty('') # run the ApprunTouchApp(ScrollableLabel()) Output: You can also change color of ScrollBar and its width as shown below code but for that, you have to use properties of ScrollView like bar_color: It requires a list in RGB format for specifying bar colorbar_width: It requires a number for specifying the bar size bar_color: It requires a list in RGB format for specifying bar color bar_width: It requires a number for specifying the bar size Code For Changing Bar Color and Bar width: Python3 from kivy.app import App # importing builder from kivyfrom kivy.lang import Builder # this is the main class which will# render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string( BoxLayout: size_hint: (1, 1) ScrollView: # here we can set bar color bar_color: [0, 0, 255, 1] # here we can set bar width bar_width: 12 BoxLayout: size: (self.parent.width, self.parent.height-1) id: container orientation: "vertical" size_hint_y: None height: self.minimum_height canvas.before: Color: rgba: rgba("#50C878") Rectangle: pos: self.pos size: self.size Label: size_hint: (1, None) height: 300 markup: True text: "[size=78]GeeksForGeeks[/size]" Label: size_hint: (1, None) height: 300 markup: True text: "[size=78]GeeksForGeeks[/size]" Label: size_hint: (1, None) height: 300 markup: True text: "[size=78]GeeksForGeeks[/size]" Label: size_hint: (1, None) height: 300 markup: True text: "[size=78]GeeksForGeeks[/size]" ) # running the applicationuiApp().run() yashmathur123123 barnabasgill Python-gui Python-kivy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Check if element exists in list in Python How To Convert Python Dictionary To JSON? Python Classes and Objects How to drop one or multiple columns in Pandas Dataframe Defaultdict in Python Python | Get unique values from a list Python | os.path.join() method Create a directory in Python Python | Pandas dataframe.groupby()
[ { "code": null, "e": 25537, "s": 25509, "text": "\n15 Sep, 2021" }, { "code": null, "e": 25774, "s": 25537, "text": "Kivy is a platform-independent GUI tool in Python. As it can be run on Android, IOS, Linux, and Windows, etc. It is basically used to develop the Android application, but it does not mean that it can not be used on Desktop applications." }, { "code": null, "e": 25817, "s": 25774, "text": " Kivy Tutorial – Learn Kivy with Examples." }, { "code": null, "e": 26019, "s": 25817, "text": "The ScrollView widget provides a scrollable/pannable viewport that is clipped at the scrollview’s bounding box. Scroll view accepts only one child and applies a window to it according to 2 properties: " }, { "code": null, "e": 26036, "s": 26019, "text": "scroll_xscroll_y" }, { "code": null, "e": 26045, "s": 26036, "text": "scroll_x" }, { "code": null, "e": 26054, "s": 26045, "text": "scroll_y" }, { "code": null, "e": 26137, "s": 26054, "text": "To determine if the interaction is a scrolling gesture, these properties are used:" }, { "code": null, "e": 26209, "s": 26137, "text": "scroll_distance: the minimum distance to travel, defaults to 20 pixels." }, { "code": null, "e": 26279, "s": 26209, "text": "scroll_timeout: the maximum time period, defaults to 55 milliseconds." }, { "code": null, "e": 26377, "s": 26279, "text": "Note: To use the scrollview you must have to import it:from kivy.uix.scrollview import ScrollView" }, { "code": null, "e": 26595, "s": 26377, "text": "Basic Approach:\n1) import kivy\n2) import kivyApp\n3) import scroll view\n4) import string property\n5) Set minimum version(optional)\n6) create the scroll view class\n7) Build the .kv file within the .py file\n8) Run an app" }, { "code": null, "e": 26623, "s": 26595, "text": "Implementation of the code:" }, { "code": null, "e": 26631, "s": 26623, "text": "Python3" }, { "code": "# Program to explain how to use scroll view in kivy # import kivy module import kivy # base Class of your App inherits from the App class. # app:always refers to the instance of your application from kivy.app import App # this restrict the kivy version i.e # below this kivy version you cannot # use the app or software kivy.require('1.9.0') # The Label widget is for rendering textfrom kivy.uix.label import Label # The ScrollView widget provides a scrollable viewfrom kivy.uix.scrollview import ScrollView # Property that represents a string valuefrom kivy.properties import StringProperty # Static main function that starts the application loop.from kivy.base import runTouchApp # Builder is a global Kivy instance used in# widgets that you can use to load other# kv files in addition to the default ones.from kivy.lang import Builder # Build the .kv fileBuilder.load_string(''' # Define the scroll view<ScrollableLabel>: text: 'You are learning Kivy' * 500 Label: text: root.text font_size: 50 text_size: self.width, None size_hint_y: None height: self.texture_size[1]''') # Define scrollview classclass ScrollableLabel(ScrollView): text = StringProperty('') # run the ApprunTouchApp(ScrollableLabel())", "e": 27922, "s": 26631, "text": null }, { "code": null, "e": 27931, "s": 27922, "text": "Output: " }, { "code": null, "e": 28066, "s": 27931, "text": "You can also change color of ScrollBar and its width as shown below code but for that, you have to use properties of ScrollView like " }, { "code": null, "e": 28194, "s": 28066, "text": "bar_color: It requires a list in RGB format for specifying bar colorbar_width: It requires a number for specifying the bar size" }, { "code": null, "e": 28263, "s": 28194, "text": "bar_color: It requires a list in RGB format for specifying bar color" }, { "code": null, "e": 28323, "s": 28263, "text": "bar_width: It requires a number for specifying the bar size" }, { "code": null, "e": 28366, "s": 28323, "text": "Code For Changing Bar Color and Bar width:" }, { "code": null, "e": 28374, "s": 28366, "text": "Python3" }, { "code": "from kivy.app import App # importing builder from kivyfrom kivy.lang import Builder # this is the main class which will# render the whole applicationclass uiApp(App): # method which will render our application def build(self): return Builder.load_string( BoxLayout: size_hint: (1, 1) ScrollView: # here we can set bar color bar_color: [0, 0, 255, 1] # here we can set bar width bar_width: 12 BoxLayout: size: (self.parent.width, self.parent.height-1) id: container orientation: \"vertical\" size_hint_y: None height: self.minimum_height canvas.before: Color: rgba: rgba(\"#50C878\") Rectangle: pos: self.pos size: self.size Label: size_hint: (1, None) height: 300 markup: True text: \"[size=78]GeeksForGeeks[/size]\" Label: size_hint: (1, None) height: 300 markup: True text: \"[size=78]GeeksForGeeks[/size]\" Label: size_hint: (1, None) height: 300 markup: True text: \"[size=78]GeeksForGeeks[/size]\" Label: size_hint: (1, None) height: 300 markup: True text: \"[size=78]GeeksForGeeks[/size]\" ) # running the applicationuiApp().run()", "e": 29865, "s": 28374, "text": null }, { "code": null, "e": 29884, "s": 29867, "text": "yashmathur123123" }, { "code": null, "e": 29897, "s": 29884, "text": "barnabasgill" }, { "code": null, "e": 29908, "s": 29897, "text": "Python-gui" }, { "code": null, "e": 29920, "s": 29908, "text": "Python-kivy" }, { "code": null, "e": 29927, "s": 29920, "text": "Python" }, { "code": null, "e": 30025, "s": 29927, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 30057, "s": 30025, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 30099, "s": 30057, "text": "Check if element exists in list in Python" }, { "code": null, "e": 30141, "s": 30099, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 30168, "s": 30141, "text": "Python Classes and Objects" }, { "code": null, "e": 30224, "s": 30168, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 30246, "s": 30224, "text": "Defaultdict in Python" }, { "code": null, "e": 30285, "s": 30246, "text": "Python | Get unique values from a list" }, { "code": null, "e": 30316, "s": 30285, "text": "Python | os.path.join() method" }, { "code": null, "e": 30345, "s": 30316, "text": "Create a directory in Python" } ]
Maximum XOR value of a pair from a range - GeeksforGeeks
05 Jan, 2022 Given a range [L, R], we need to find two integers in this range such that their XOR is maximum among all possible choices of two integers. More Formally, given [L, R], find max (A ^ B) where L <= A, B Examples : Input : L = 8 R = 20 Output : 31 31 is XOR of 15 and 16. Input : L = 1 R = 3 Output : 3 A simple solution is to generate all pairs, find their XOR values and finally return the maximum XOR value.An efficient solution is to consider pattern of binary values from L to R. We can see that first bit from L to R either changes from 0 to 1 or it stays 1 i.e. if we take the XOR of any two numbers for maximum value their first bit will be fixed which will be same as first bit of XOR of L and R itself. After observing the technique to get first bit, we can see that if we XOR L and R, the most significant bit of this XOR will tell us the maximum value we can achieve i.e. let XOR of L and R is 1xxx where x can be 0 or 1 then maximum XOR value we can get is 1111 because from L to R we have all possible combination of xxx and it is always possible to choose these bits in such a way from two numbers such that their XOR becomes all 1. It is explained below with some examples, Examples 1: L = 8 R = 20 L ^ R = (01000) ^ (10100) = (11100) Now as L ^ R is of form (1xxxx) we can get maximum XOR as (11111) by choosing A and B as 15 and 16 (01111 and 10000) Examples 2: L = 16 R = 20 L ^ R = (10000) ^ (10100) = (00100) Now as L ^ R is of form (1xx) we can get maximum xor as (111) by choosing A and B as 19 and 20 (10011 and 10100) So the solution of this problem depends on the value of (L ^ R) only. We will calculate the L^R value first and then from most significant bit of this value, we will add all 1s to get the final result. C++ Java Python3 C# PHP Javascript // C/C++ program to get maximum xor value// of two numbers in a range#include <bits/stdc++.h>using namespace std; // method to get maximum xor value in range [L, R]int maxXORInRange(int L, int R){ // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR) { msbPos++; LXR >>= 1; } // Simply return the required maximum value. return (pow(2, msbPos)-1);} // Driver code to test above methodsint main(){ int L = 8; int R = 20; cout << maxXORInRange(L, R) << endl; return 0;} // Java program to get maximum xor value// of two numbers in a range class Xor{ // method to get maximum xor value in range [L, R] static int maxXORInRange(int L, int R) { // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR > 0) { msbPos++; LXR >>= 1; } // construct result by adding 1, // msbPos times int maxXOR = 0; int two = 1; while (msbPos-- >0) { maxXOR += two; two <<= 1; } return maxXOR; } // main function public static void main (String[] args) { int L = 8; int R = 20; System.out.println(maxXORInRange(L, R)); }} # Python3 program to get maximum xor# value of two numbers in a range # Method to get maximum xor# value in range [L, R]def maxXORInRange(L, R): # get xor of limits LXR = L ^ R # loop to get msb position of L^R msbPos = 0 while(LXR): msbPos += 1 LXR >>= 1 # construct result by adding 1, # msbPos times maxXOR, two = 0, 1 while (msbPos): maxXOR += two two <<= 1 msbPos -= 1 return maxXOR # Driver codeL, R = 8, 20print(maxXORInRange(L, R)) # This code is contributed by Anant Agarwal. // C# program to get maximum xor// value of two numbers in a rangeusing System; class Xor{ // method to get maximum xor // value in range [L, R] static int maxXORInRange(int L, int R) { // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR > 0) { msbPos++; LXR >>= 1; } // construct result by // adding 1, msbPos times int maxXOR = 0; int two = 1; while (msbPos-- >0) { maxXOR += two; two <<= 1; } return maxXOR; } // Driver code public static void Main() { int L = 8; int R = 20; Console.WriteLine(maxXORInRange(L, R)); }} // This code is contributed by Anant Agarwal. <?php// PHP program to get maximum// xor value of two numbers// in a range // method to get maximum xor// value in range [L, R]function maxXORInRange($L, $R){ // get xor of limits $LXR = $L ^ $R; // loop to get msb // position of L^R $msbPos = 0; while ($LXR) { $msbPos++; $LXR >>= 1; } // construct result by // adding 1, msbPos times $maxXOR = 0; $two = 1; while ($msbPos--) { $maxXOR += $two; $two <<= 1; } return $maxXOR;} // Driver Code$L = 8;$R = 20;echo maxXORInRange($L, $R), "\n"; // This code is contributed by aj_36?> <script> // Javascript program to get maximum xor // value of two numbers in a range // method to get maximum xor // value in range [L, R] function maxXORInRange(L, R) { // get xor of limits let LXR = L ^ R; // loop to get msb position of L^R let msbPos = 0; while (LXR > 0) { msbPos++; LXR >>= 1; } // construct result by // adding 1, msbPos times let maxXOR = 0; let two = 1; while (msbPos-- > 0) { maxXOR += two; two <<= 1; } return maxXOR; } let L = 8; let R = 20; document.write(maxXORInRange(L, R)); </script> Output : 31 This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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 shaurya uppal mukesh07 yabhisekhmessi535 Bitwise-XOR Bit Magic Bit Magic Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Add two numbers without using arithmetic operators Set, Clear and Toggle a given bit of a number in C Bit Fields in C Bits manipulation (Important tactics) Find the element that appears once 1's and 2's complement of a Binary Number Divide two integers without using multiplication, division and mod operator C++ bitset and its application Check whether K-th bit is set or not Write an Efficient C Program to Reverse Bits of a Number
[ { "code": null, "e": 26321, "s": 26293, "text": "\n05 Jan, 2022" }, { "code": null, "e": 26536, "s": 26321, "text": "Given a range [L, R], we need to find two integers in this range such that their XOR is maximum among all possible choices of two integers. More Formally, given [L, R], find max (A ^ B) where L <= A, B Examples : " }, { "code": null, "e": 26647, "s": 26536, "text": "Input : L = 8\n R = 20\nOutput : 31\n31 is XOR of 15 and 16. \n\nInput : L = 1\n R = 3\nOutput : 3" }, { "code": null, "e": 27538, "s": 26649, "text": "A simple solution is to generate all pairs, find their XOR values and finally return the maximum XOR value.An efficient solution is to consider pattern of binary values from L to R. We can see that first bit from L to R either changes from 0 to 1 or it stays 1 i.e. if we take the XOR of any two numbers for maximum value their first bit will be fixed which will be same as first bit of XOR of L and R itself. After observing the technique to get first bit, we can see that if we XOR L and R, the most significant bit of this XOR will tell us the maximum value we can achieve i.e. let XOR of L and R is 1xxx where x can be 0 or 1 then maximum XOR value we can get is 1111 because from L to R we have all possible combination of xxx and it is always possible to choose these bits in such a way from two numbers such that their XOR becomes all 1. It is explained below with some examples, " }, { "code": null, "e": 27904, "s": 27538, "text": "Examples 1:\nL = 8 R = 20\nL ^ R = (01000) ^ (10100) = (11100)\nNow as L ^ R is of form (1xxxx) we\ncan get maximum XOR as (11111) by \nchoosing A and B as 15 and 16 (01111 \nand 10000)\n\nExamples 2:\nL = 16 R = 20\nL ^ R = (10000) ^ (10100) = (00100)\nNow as L ^ R is of form (1xx) we can \nget maximum xor as (111) by choosing \nA and B as 19 and 20 (10011 and 10100)" }, { "code": null, "e": 28108, "s": 27904, "text": "So the solution of this problem depends on the value of (L ^ R) only. We will calculate the L^R value first and then from most significant bit of this value, we will add all 1s to get the final result. " }, { "code": null, "e": 28112, "s": 28108, "text": "C++" }, { "code": null, "e": 28117, "s": 28112, "text": "Java" }, { "code": null, "e": 28125, "s": 28117, "text": "Python3" }, { "code": null, "e": 28128, "s": 28125, "text": "C#" }, { "code": null, "e": 28132, "s": 28128, "text": "PHP" }, { "code": null, "e": 28143, "s": 28132, "text": "Javascript" }, { "code": "// C/C++ program to get maximum xor value// of two numbers in a range#include <bits/stdc++.h>using namespace std; // method to get maximum xor value in range [L, R]int maxXORInRange(int L, int R){ // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR) { msbPos++; LXR >>= 1; } // Simply return the required maximum value. return (pow(2, msbPos)-1);} // Driver code to test above methodsint main(){ int L = 8; int R = 20; cout << maxXORInRange(L, R) << endl; return 0;}", "e": 28715, "s": 28143, "text": null }, { "code": "// Java program to get maximum xor value// of two numbers in a range class Xor{ // method to get maximum xor value in range [L, R] static int maxXORInRange(int L, int R) { // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR > 0) { msbPos++; LXR >>= 1; } // construct result by adding 1, // msbPos times int maxXOR = 0; int two = 1; while (msbPos-- >0) { maxXOR += two; two <<= 1; } return maxXOR; } // main function public static void main (String[] args) { int L = 8; int R = 20; System.out.println(maxXORInRange(L, R)); }}", "e": 29506, "s": 28715, "text": null }, { "code": "# Python3 program to get maximum xor# value of two numbers in a range # Method to get maximum xor# value in range [L, R]def maxXORInRange(L, R): # get xor of limits LXR = L ^ R # loop to get msb position of L^R msbPos = 0 while(LXR): msbPos += 1 LXR >>= 1 # construct result by adding 1, # msbPos times maxXOR, two = 0, 1 while (msbPos): maxXOR += two two <<= 1 msbPos -= 1 return maxXOR # Driver codeL, R = 8, 20print(maxXORInRange(L, R)) # This code is contributed by Anant Agarwal.", "e": 30080, "s": 29506, "text": null }, { "code": "// C# program to get maximum xor// value of two numbers in a rangeusing System; class Xor{ // method to get maximum xor // value in range [L, R] static int maxXORInRange(int L, int R) { // get xor of limits int LXR = L ^ R; // loop to get msb position of L^R int msbPos = 0; while (LXR > 0) { msbPos++; LXR >>= 1; } // construct result by // adding 1, msbPos times int maxXOR = 0; int two = 1; while (msbPos-- >0) { maxXOR += two; two <<= 1; } return maxXOR; } // Driver code public static void Main() { int L = 8; int R = 20; Console.WriteLine(maxXORInRange(L, R)); }} // This code is contributed by Anant Agarwal.", "e": 30934, "s": 30080, "text": null }, { "code": "<?php// PHP program to get maximum// xor value of two numbers// in a range // method to get maximum xor// value in range [L, R]function maxXORInRange($L, $R){ // get xor of limits $LXR = $L ^ $R; // loop to get msb // position of L^R $msbPos = 0; while ($LXR) { $msbPos++; $LXR >>= 1; } // construct result by // adding 1, msbPos times $maxXOR = 0; $two = 1; while ($msbPos--) { $maxXOR += $two; $two <<= 1; } return $maxXOR;} // Driver Code$L = 8;$R = 20;echo maxXORInRange($L, $R), \"\\n\"; // This code is contributed by aj_36?>", "e": 31542, "s": 30934, "text": null }, { "code": "<script> // Javascript program to get maximum xor // value of two numbers in a range // method to get maximum xor // value in range [L, R] function maxXORInRange(L, R) { // get xor of limits let LXR = L ^ R; // loop to get msb position of L^R let msbPos = 0; while (LXR > 0) { msbPos++; LXR >>= 1; } // construct result by // adding 1, msbPos times let maxXOR = 0; let two = 1; while (msbPos-- > 0) { maxXOR += two; two <<= 1; } return maxXOR; } let L = 8; let R = 20; document.write(maxXORInRange(L, R)); </script>", "e": 32289, "s": 31542, "text": null }, { "code": null, "e": 32300, "s": 32289, "text": "Output : " }, { "code": null, "e": 32303, "s": 32300, "text": "31" }, { "code": null, "e": 32727, "s": 32303, "text": "This article is contributed by Utkarsh Trivedi. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [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": 32733, "s": 32727, "text": "jit_t" }, { "code": null, "e": 32747, "s": 32733, "text": "shaurya uppal" }, { "code": null, "e": 32756, "s": 32747, "text": "mukesh07" }, { "code": null, "e": 32774, "s": 32756, "text": "yabhisekhmessi535" }, { "code": null, "e": 32786, "s": 32774, "text": "Bitwise-XOR" }, { "code": null, "e": 32796, "s": 32786, "text": "Bit Magic" }, { "code": null, "e": 32806, "s": 32796, "text": "Bit Magic" }, { "code": null, "e": 32904, "s": 32806, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 32955, "s": 32904, "text": "Add two numbers without using arithmetic operators" }, { "code": null, "e": 33006, "s": 32955, "text": "Set, Clear and Toggle a given bit of a number in C" }, { "code": null, "e": 33022, "s": 33006, "text": "Bit Fields in C" }, { "code": null, "e": 33060, "s": 33022, "text": "Bits manipulation (Important tactics)" }, { "code": null, "e": 33095, "s": 33060, "text": "Find the element that appears once" }, { "code": null, "e": 33137, "s": 33095, "text": "1's and 2's complement of a Binary Number" }, { "code": null, "e": 33213, "s": 33137, "text": "Divide two integers without using multiplication, division and mod operator" }, { "code": null, "e": 33244, "s": 33213, "text": "C++ bitset and its application" }, { "code": null, "e": 33281, "s": 33244, "text": "Check whether K-th bit is set or not" } ]
fmt.Sprintln() Function in Golang With Examples - GeeksforGeeks
05 May, 2020 In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprintln() function in Go language formats using the default formats for its operands and returns the resulting string. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions. Syntax: func Sprintln(a ...interface{}) string Here, “a ...interface{}” is containing some strings along with the specified constant variables. Returns: It returns the resulting string. Example 1: // Golang program to illustrate the usage of// fmt.Sprintln() function // Including the main packagepackage main // Importing fmt, io and osimport ( "fmt" "io" "os") // Calling mainfunc main() { // Declaring some const variables const name, dept = "GeeksforGeeks", "CS" // Calling Sprintln() function s := fmt.Sprintln(name, "is a", dept, "Portal.") // Calling WriteString() function to write the // contents of the string "s" to "os.Stdout" io.WriteString(os.Stdout, s) } Output: GeeksforGeeks is a CS Portal. Example 2: // Golang program to illustrate the usage of// fmt.Sprintln() function // Including the main packagepackage main // Importing fmt, io and osimport ( "fmt" "io" "os") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3, num4 = 5, 10, 15, 50 // Calling Sprintln() function s1 := fmt.Sprintln(num1, "+", num2, "=", num3) s2 := fmt.Sprintln(num1, "*", num2, "=", num4) // Calling WriteString() function to write the // contents of the string "s1" and "s2" to "os.Stdout" io.WriteString(os.Stdout, s1) io.WriteString(os.Stdout, s2) } Output: 5 + 10 = 15 5 * 10 = 50 In the above code, no new line or space is used still this function append new line and space between the operands that can be seen in the above output. Golang-fmt Go Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. 6 Best Books to Learn Go Programming Language How to Parse JSON in Golang? Strings in Golang Time Durations in Golang Structures in Golang How to iterate over an Array using for loop in Golang? Rune in Golang Loops in Go Language Defer Keyword in Golang Class and Object in Golang
[ { "code": null, "e": 25703, "s": 25675, "text": "\n05 May, 2020" }, { "code": null, "e": 26165, "s": 25703, "text": "In Go language, fmt package implements formatted I/O with functions analogous to C’s printf() and scanf() function. The fmt.Sprintln() function in Go language formats using the default formats for its operands and returns the resulting string. Here spaces are always added between operands and a newline is appended at the end. Moreover, this function is defined under the fmt package. Here, you need to import the “fmt” package in order to use these functions." }, { "code": null, "e": 26173, "s": 26165, "text": "Syntax:" }, { "code": null, "e": 26213, "s": 26173, "text": "func Sprintln(a ...interface{}) string\n" }, { "code": null, "e": 26310, "s": 26213, "text": "Here, “a ...interface{}” is containing some strings along with the specified constant variables." }, { "code": null, "e": 26352, "s": 26310, "text": "Returns: It returns the resulting string." }, { "code": null, "e": 26363, "s": 26352, "text": "Example 1:" }, { "code": "// Golang program to illustrate the usage of// fmt.Sprintln() function // Including the main packagepackage main // Importing fmt, io and osimport ( \"fmt\" \"io\" \"os\") // Calling mainfunc main() { // Declaring some const variables const name, dept = \"GeeksforGeeks\", \"CS\" // Calling Sprintln() function s := fmt.Sprintln(name, \"is a\", dept, \"Portal.\") // Calling WriteString() function to write the // contents of the string \"s\" to \"os.Stdout\" io.WriteString(os.Stdout, s) }", "e": 26876, "s": 26363, "text": null }, { "code": null, "e": 26884, "s": 26876, "text": "Output:" }, { "code": null, "e": 26915, "s": 26884, "text": "GeeksforGeeks is a CS Portal.\n" }, { "code": null, "e": 26926, "s": 26915, "text": "Example 2:" }, { "code": "// Golang program to illustrate the usage of// fmt.Sprintln() function // Including the main packagepackage main // Importing fmt, io and osimport ( \"fmt\" \"io\" \"os\") // Calling mainfunc main() { // Declaring some const variables const num1, num2, num3, num4 = 5, 10, 15, 50 // Calling Sprintln() function s1 := fmt.Sprintln(num1, \"+\", num2, \"=\", num3) s2 := fmt.Sprintln(num1, \"*\", num2, \"=\", num4) // Calling WriteString() function to write the // contents of the string \"s1\" and \"s2\" to \"os.Stdout\" io.WriteString(os.Stdout, s1) io.WriteString(os.Stdout, s2) }", "e": 27535, "s": 26926, "text": null }, { "code": null, "e": 27543, "s": 27535, "text": "Output:" }, { "code": null, "e": 27568, "s": 27543, "text": "5 + 10 = 15\n5 * 10 = 50\n" }, { "code": null, "e": 27721, "s": 27568, "text": "In the above code, no new line or space is used still this function append new line and space between the operands that can be seen in the above output." }, { "code": null, "e": 27732, "s": 27721, "text": "Golang-fmt" }, { "code": null, "e": 27744, "s": 27732, "text": "Go Language" }, { "code": null, "e": 27842, "s": 27744, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27888, "s": 27842, "text": "6 Best Books to Learn Go Programming Language" }, { "code": null, "e": 27917, "s": 27888, "text": "How to Parse JSON in Golang?" }, { "code": null, "e": 27935, "s": 27917, "text": "Strings in Golang" }, { "code": null, "e": 27960, "s": 27935, "text": "Time Durations in Golang" }, { "code": null, "e": 27981, "s": 27960, "text": "Structures in Golang" }, { "code": null, "e": 28036, "s": 27981, "text": "How to iterate over an Array using for loop in Golang?" }, { "code": null, "e": 28051, "s": 28036, "text": "Rune in Golang" }, { "code": null, "e": 28072, "s": 28051, "text": "Loops in Go Language" }, { "code": null, "e": 28096, "s": 28072, "text": "Defer Keyword in Golang" } ]
How to stretch flexbox to fill the entire container in Bootstrap ? - GeeksforGeeks
21 Dec, 2020 We are given an HTML document (linked with Bootstrap) with a flexbox and a container. The goal is to stretch the flexbox to fill the entire container. This can be achieved by two different approaches, using flex-fill or flex-grow classes in Bootstrap. Approach 1: Using flex-fill class: The .flex-fill class stretches the width of an element to fill the entire horizontal space. If there are multiple sibling elements on which this class is applied, the horizontal space is equally divided among them. Syntax: <div class="flex-fill"></div> Example: <!Doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"> </script> <title>GFG Bootstrap Flexbox</title></head> <body> <p>Single flexbox without .flex-fill</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border"> GFG Flexbox 1 </div> </div> <p>Single flexbox with .flex-fill</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border flex-fill"> GFG Flexbox 1 </div> </div> <p>Multiple flexbox without .flex-fill</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border"> GFG Flexbox 1 </div> <div class="bg-success p-2 border"> GFG Flexbox 2 </div> <div class="bg-success p-2 border"> GFG Flexbox 3 </div> </div> <p>Multiple flexbox with .flex-fill</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border flex-fill"> GFG Flexbox 1 </div> <div class="bg-success p-2 border flex-fill"> GFG Flexbox 2 </div> <div class="bg-success p-2 border flex-fill"> GFG Flexbox 3 </div> </div></body> </html> Output: Approach 2: Using flex-grow class: We can also alter the width of the flexbox by using Bootstrap’s flex-grow-* class. .flex-grow-1 stretch the element to its maximum width by giving the other elements (if any) only the necessary amount of space. Syntax: <div class="flex-grow-1"></div> Example: <!Doctype html><html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW" crossorigin="anonymous"> </script></head> <body> <p>Single flexbox without .flex-grow-1</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border"> GFG Flexbox 1 </div> </div> <p>Single flexbox with .flex-grow-1</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border flex-grow-1"> GFG Flexbox 1 </div> </div> <p>Multiple flexbox without .flex-grow-1</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border"> GFG Flexbox 1 </div> <div class="bg-success p-2 border"> GFG Flexbox 2 </div> <div class="bg-success p-2 border"> GFG Flexbox 3 </div> </div> <p>Multiple flexbox with .flex-grow-1</p> <div class="d-flex bg-danger container"> <div class="bg-success p-2 border flex-grow-1"> GFG Flexbox 1 </div> <div class="bg-success p-2 border"> GFG Flexbox 2 </div> <div class="bg-success p-2 border"> GFG Flexbox 3 </div> </div></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. Bootstrap-4 Bootstrap-Misc HTML-Misc Picked Bootstrap 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 Show Images on Click using HTML ? How to set Bootstrap Timepicker using datetimepicker library ? How to Use Bootstrap with React? How to keep gap between columns using Bootstrap? Tailwind CSS vs Bootstrap How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to update Node.js and NPM to next version ? How to set the default value for an HTML <select> element ? Hide or show elements in HTML using display property
[ { "code": null, "e": 26863, "s": 26835, "text": "\n21 Dec, 2020" }, { "code": null, "e": 27115, "s": 26863, "text": "We are given an HTML document (linked with Bootstrap) with a flexbox and a container. The goal is to stretch the flexbox to fill the entire container. This can be achieved by two different approaches, using flex-fill or flex-grow classes in Bootstrap." }, { "code": null, "e": 27365, "s": 27115, "text": "Approach 1: Using flex-fill class: The .flex-fill class stretches the width of an element to fill the entire horizontal space. If there are multiple sibling elements on which this class is applied, the horizontal space is equally divided among them." }, { "code": null, "e": 27373, "s": 27365, "text": "Syntax:" }, { "code": null, "e": 27403, "s": 27373, "text": "<div class=\"flex-fill\"></div>" }, { "code": null, "e": 27412, "s": 27403, "text": "Example:" }, { "code": "<!Doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW\" crossorigin=\"anonymous\"> </script> <title>GFG Bootstrap Flexbox</title></head> <body> <p>Single flexbox without .flex-fill</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border\"> GFG Flexbox 1 </div> </div> <p>Single flexbox with .flex-fill</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border flex-fill\"> GFG Flexbox 1 </div> </div> <p>Multiple flexbox without .flex-fill</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border\"> GFG Flexbox 1 </div> <div class=\"bg-success p-2 border\"> GFG Flexbox 2 </div> <div class=\"bg-success p-2 border\"> GFG Flexbox 3 </div> </div> <p>Multiple flexbox with .flex-fill</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border flex-fill\"> GFG Flexbox 1 </div> <div class=\"bg-success p-2 border flex-fill\"> GFG Flexbox 2 </div> <div class=\"bg-success p-2 border flex-fill\"> GFG Flexbox 3 </div> </div></body> </html>", "e": 29205, "s": 27412, "text": null }, { "code": null, "e": 29213, "s": 29205, "text": "Output:" }, { "code": null, "e": 29331, "s": 29213, "text": "Approach 2: Using flex-grow class: We can also alter the width of the flexbox by using Bootstrap’s flex-grow-* class." }, { "code": null, "e": 29459, "s": 29331, "text": ".flex-grow-1 stretch the element to its maximum width by giving the other elements (if any) only the necessary amount of space." }, { "code": null, "e": 29467, "s": 29459, "text": "Syntax:" }, { "code": null, "e": 29499, "s": 29467, "text": "<div class=\"flex-grow-1\"></div>" }, { "code": null, "e": 29508, "s": 29499, "text": "Example:" }, { "code": "<!Doctype html><html lang=\"en\"> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <link href=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css\" rel=\"stylesheet\" integrity=\"sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1\" crossorigin=\"anonymous\"> <script src=\"https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js\" integrity=\"sha384-ygbV9kiqUc6oa4msXn9868pTtWMgiQaeYH7/t7LECLbyPA2x65Kgf80OJFdroafW\" crossorigin=\"anonymous\"> </script></head> <body> <p>Single flexbox without .flex-grow-1</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border\"> GFG Flexbox 1 </div> </div> <p>Single flexbox with .flex-grow-1</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border flex-grow-1\"> GFG Flexbox 1 </div> </div> <p>Multiple flexbox without .flex-grow-1</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border\"> GFG Flexbox 1 </div> <div class=\"bg-success p-2 border\"> GFG Flexbox 2 </div> <div class=\"bg-success p-2 border\"> GFG Flexbox 3 </div> </div> <p>Multiple flexbox with .flex-grow-1</p> <div class=\"d-flex bg-danger container\"> <div class=\"bg-success p-2 border flex-grow-1\"> GFG Flexbox 1 </div> <div class=\"bg-success p-2 border\"> GFG Flexbox 2 </div> <div class=\"bg-success p-2 border\"> GFG Flexbox 3 </div> </div></body> </html>", "e": 31255, "s": 29508, "text": null }, { "code": null, "e": 31263, "s": 31255, "text": "Output:" }, { "code": null, "e": 31400, "s": 31263, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 31412, "s": 31400, "text": "Bootstrap-4" }, { "code": null, "e": 31427, "s": 31412, "text": "Bootstrap-Misc" }, { "code": null, "e": 31437, "s": 31427, "text": "HTML-Misc" }, { "code": null, "e": 31444, "s": 31437, "text": "Picked" }, { "code": null, "e": 31454, "s": 31444, "text": "Bootstrap" }, { "code": null, "e": 31459, "s": 31454, "text": "HTML" }, { "code": null, "e": 31476, "s": 31459, "text": "Web Technologies" }, { "code": null, "e": 31503, "s": 31476, "text": "Web technologies Questions" }, { "code": null, "e": 31508, "s": 31503, "text": "HTML" }, { "code": null, "e": 31606, "s": 31508, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31647, "s": 31606, "text": "How to Show Images on Click using HTML ?" }, { "code": null, "e": 31710, "s": 31647, "text": "How to set Bootstrap Timepicker using datetimepicker library ?" }, { "code": null, "e": 31743, "s": 31710, "text": "How to Use Bootstrap with React?" }, { "code": null, "e": 31792, "s": 31743, "text": "How to keep gap between columns using Bootstrap?" }, { "code": null, "e": 31818, "s": 31792, "text": "Tailwind CSS vs Bootstrap" }, { "code": null, "e": 31868, "s": 31818, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 31930, "s": 31868, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 31978, "s": 31930, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 32038, "s": 31978, "text": "How to set the default value for an HTML <select> element ?" } ]
Why integer size varies from computer to computer? - GeeksforGeeks
31 May, 2021 In a computer, memory is composed of digital memory that stores information binary format, and the lowest unit is called a bit (binary digit). The single-bit denotes a logical value that consists of two states, either o or 1. A bit is a part of the binary number system. Using the combination of these bits, any integer can be represented by the decimal number system. As digital information is stored in binary bits, computers use a binary number system to represent all numbers such as integers. A byte is a group of 8 bits. In programming languages like C, it is possible to declare variables using the type of that variable, so to store numeric values in computer memory, we use the number of bits internally to represent integers (int). How Integer Numbers Are Stored In Memory? In the above figure, it can be seen how the integer is stored in the main memory. The above figure gives how the decimal number, i.e., the base 10 number is converted to a binary, i.e., the base 2 number system, and how exactly it is stored in memory. Why Integer Size Varies From Computer To Computer? This section focuses on discussing some reasons why integer size varies from computer to computer. Below are the reasons- The aim of C and C++ is to supply in no-time code on all machines. If compilers had to make sure that an int may be an uncommon size for that machine, it might require extra instructions. For nearly all circumstances, that’s not required, all required is that it’s big enough for what the user intends to do with it.Among the benefits of C and C++ is that there are compilers that focus on a huge range of machines, from little 8-bit and 16-bit microcontrollers to large 64-bit multi-core processors. And in fact, some 18, 24, or 36-bit machines too. If some machine features a 36-bit native size, the user would not be very happy if, because some standard says so, you get half the performance in integer math thanks to extra instructions, and can’t use the highest 4 bits of an int.A small microprocessor with 8-bit registers often has support to try 16-bit additions and subtractions (and perhaps also multiplication and divide), but 32-bit math would involve doubling abreast of those instructions and also more work for multiplication and divide. So 16-bit integers (2 bytes) would make far more sense on such a small processor-particularly since memory is perhaps not very large either, so storing 4 bytes for each integer may be a little of a waste.For a 32- or 64-bit machine, the memory range is presumably tons larger, so having larger integers isn’t that much of a drawback, and 32-bit integer operations are an equivalent speed as smaller ones and in some cases “better”- for instance in x86, a 16-bit basic math operation like addition or subtraction requires an additional prefix byte to mention “make this 16-bit”, so math on 16-bit integers would take up more code-space. The aim of C and C++ is to supply in no-time code on all machines. If compilers had to make sure that an int may be an uncommon size for that machine, it might require extra instructions. For nearly all circumstances, that’s not required, all required is that it’s big enough for what the user intends to do with it. Among the benefits of C and C++ is that there are compilers that focus on a huge range of machines, from little 8-bit and 16-bit microcontrollers to large 64-bit multi-core processors. And in fact, some 18, 24, or 36-bit machines too. If some machine features a 36-bit native size, the user would not be very happy if, because some standard says so, you get half the performance in integer math thanks to extra instructions, and can’t use the highest 4 bits of an int. A small microprocessor with 8-bit registers often has support to try 16-bit additions and subtractions (and perhaps also multiplication and divide), but 32-bit math would involve doubling abreast of those instructions and also more work for multiplication and divide. So 16-bit integers (2 bytes) would make far more sense on such a small processor-particularly since memory is perhaps not very large either, so storing 4 bytes for each integer may be a little of a waste. For a 32- or 64-bit machine, the memory range is presumably tons larger, so having larger integers isn’t that much of a drawback, and 32-bit integer operations are an equivalent speed as smaller ones and in some cases “better”- for instance in x86, a 16-bit basic math operation like addition or subtraction requires an additional prefix byte to mention “make this 16-bit”, so math on 16-bit integers would take up more code-space. This is not universally true, but often true. It is not really useful to extend an int to 64 bits. It wastes space. If required, one can be 64 bits long and still have int be 32 bits. Otherwise, leave only long long for those cases where 64-bit integers are required. Most current implementations do the previous 64 bits long. So there are 16-bit integers (short), 32-bit integers (int), and 64-bit integers (long and long long), all of which are supported by the hardware (in the case of x86), allowing a user to select an appropriate type for every variable. Generally, unless there’s a good reason for the hardware, it is not useful to form kinds larger than their minimum size, since standards-compliant programs can’t expect them to be bigger anyway, and need to work correctly with the minimum size. Why Int Is Not 16-bits? They were 32 bits on the 32-bit platforms; the instruction coding for 16-bit operands (on both 32-bit and 64-bit) is one byte longer than that for 32-bit operands. And if a 16-bit value is stored during a register operation, the remainder of the register cannot be used, either on 32-bit or 64-bit, because there’s no instruction coding for “high half 32-bit register”. So 32 bits is kind of a natural size for an operand. Below is a C++ program to demonstrate the size of an integer in a 64-bit system: C++14 // C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // sizeof() operator is used to // give the size in bytes cout << sizeof(int); return 0;} 4 4 Below is a C++ program to demonstrate the size of an integer in a 32-bit (x86) system: C++14 // C++ program to implement// above approach#include <iostream>using namespace std; // Driver codeint main(){ // sizeof() operator is used // to give the size in bytes cout << sizeof(int); return 0;} 4 Output 2 Advantages of varying integer size: One of the benefits of varying the size is that fewer CPU cycles are required to read or write.Efficient use of a given architecture depends on 32-bit or 64-bit systems. One of the benefits of varying the size is that fewer CPU cycles are required to read or write. Efficient use of a given architecture depends on 32-bit or 64-bit systems. Disadvantages of varying integer size: Variation in different architectures does not give the programmer a clear view about the size of the integers to take type decisions for further calculation.It can cause various problems in memory if misused for bad purposes, leading to supporting some attacks such as buffer overflow.An integer overflow may occur if some program tries to store a value in an integer variable larger than the maximum value the variable can store.Different sizes can use multiple CPU registers. For example, if there is a need to store a number greater than 2^32 in a 32-bit machine, then two registers are required, the same for a 64-bit machine. Variation in different architectures does not give the programmer a clear view about the size of the integers to take type decisions for further calculation. It can cause various problems in memory if misused for bad purposes, leading to supporting some attacks such as buffer overflow. An integer overflow may occur if some program tries to store a value in an integer variable larger than the maximum value the variable can store. Different sizes can use multiple CPU registers. For example, if there is a need to store a number greater than 2^32 in a 32-bit machine, then two registers are required, the same for a 64-bit machine. Analysis Articles Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete Difference between Deterministic and Non-deterministic Algorithms Complexity analysis of various operations of Binary Min Heap Pseudo-polynomial Algorithms Proof that Hamiltonian Cycle is NP-Complete Tree Traversals (Inorder, Preorder and Postorder) SQL | Join (Inner, Left, Right and Full Joins) find command in Linux with examples How to write a Pseudo Code? SQL Interview Questions
[ { "code": null, "e": 26291, "s": 26263, "text": "\n31 May, 2021" }, { "code": null, "e": 26661, "s": 26291, "text": "In a computer, memory is composed of digital memory that stores information binary format, and the lowest unit is called a bit (binary digit). The single-bit denotes a logical value that consists of two states, either o or 1. A bit is a part of the binary number system. Using the combination of these bits, any integer can be represented by the decimal number system. " }, { "code": null, "e": 27034, "s": 26661, "text": "As digital information is stored in binary bits, computers use a binary number system to represent all numbers such as integers. A byte is a group of 8 bits. In programming languages like C, it is possible to declare variables using the type of that variable, so to store numeric values in computer memory, we use the number of bits internally to represent integers (int)." }, { "code": null, "e": 27076, "s": 27034, "text": "How Integer Numbers Are Stored In Memory?" }, { "code": null, "e": 27328, "s": 27076, "text": "In the above figure, it can be seen how the integer is stored in the main memory. The above figure gives how the decimal number, i.e., the base 10 number is converted to a binary, i.e., the base 2 number system, and how exactly it is stored in memory." }, { "code": null, "e": 27379, "s": 27328, "text": "Why Integer Size Varies From Computer To Computer?" }, { "code": null, "e": 27501, "s": 27379, "text": "This section focuses on discussing some reasons why integer size varies from computer to computer. Below are the reasons-" }, { "code": null, "e": 29189, "s": 27501, "text": "The aim of C and C++ is to supply in no-time code on all machines. If compilers had to make sure that an int may be an uncommon size for that machine, it might require extra instructions. For nearly all circumstances, that’s not required, all required is that it’s big enough for what the user intends to do with it.Among the benefits of C and C++ is that there are compilers that focus on a huge range of machines, from little 8-bit and 16-bit microcontrollers to large 64-bit multi-core processors. And in fact, some 18, 24, or 36-bit machines too. If some machine features a 36-bit native size, the user would not be very happy if, because some standard says so, you get half the performance in integer math thanks to extra instructions, and can’t use the highest 4 bits of an int.A small microprocessor with 8-bit registers often has support to try 16-bit additions and subtractions (and perhaps also multiplication and divide), but 32-bit math would involve doubling abreast of those instructions and also more work for multiplication and divide. So 16-bit integers (2 bytes) would make far more sense on such a small processor-particularly since memory is perhaps not very large either, so storing 4 bytes for each integer may be a little of a waste.For a 32- or 64-bit machine, the memory range is presumably tons larger, so having larger integers isn’t that much of a drawback, and 32-bit integer operations are an equivalent speed as smaller ones and in some cases “better”- for instance in x86, a 16-bit basic math operation like addition or subtraction requires an additional prefix byte to mention “make this 16-bit”, so math on 16-bit integers would take up more code-space." }, { "code": null, "e": 29506, "s": 29189, "text": "The aim of C and C++ is to supply in no-time code on all machines. If compilers had to make sure that an int may be an uncommon size for that machine, it might require extra instructions. For nearly all circumstances, that’s not required, all required is that it’s big enough for what the user intends to do with it." }, { "code": null, "e": 29975, "s": 29506, "text": "Among the benefits of C and C++ is that there are compilers that focus on a huge range of machines, from little 8-bit and 16-bit microcontrollers to large 64-bit multi-core processors. And in fact, some 18, 24, or 36-bit machines too. If some machine features a 36-bit native size, the user would not be very happy if, because some standard says so, you get half the performance in integer math thanks to extra instructions, and can’t use the highest 4 bits of an int." }, { "code": null, "e": 30448, "s": 29975, "text": "A small microprocessor with 8-bit registers often has support to try 16-bit additions and subtractions (and perhaps also multiplication and divide), but 32-bit math would involve doubling abreast of those instructions and also more work for multiplication and divide. So 16-bit integers (2 bytes) would make far more sense on such a small processor-particularly since memory is perhaps not very large either, so storing 4 bytes for each integer may be a little of a waste." }, { "code": null, "e": 30880, "s": 30448, "text": "For a 32- or 64-bit machine, the memory range is presumably tons larger, so having larger integers isn’t that much of a drawback, and 32-bit integer operations are an equivalent speed as smaller ones and in some cases “better”- for instance in x86, a 16-bit basic math operation like addition or subtraction requires an additional prefix byte to mention “make this 16-bit”, so math on 16-bit integers would take up more code-space." }, { "code": null, "e": 31686, "s": 30880, "text": "This is not universally true, but often true. It is not really useful to extend an int to 64 bits. It wastes space. If required, one can be 64 bits long and still have int be 32 bits. Otherwise, leave only long long for those cases where 64-bit integers are required. Most current implementations do the previous 64 bits long. So there are 16-bit integers (short), 32-bit integers (int), and 64-bit integers (long and long long), all of which are supported by the hardware (in the case of x86), allowing a user to select an appropriate type for every variable. Generally, unless there’s a good reason for the hardware, it is not useful to form kinds larger than their minimum size, since standards-compliant programs can’t expect them to be bigger anyway, and need to work correctly with the minimum size." }, { "code": null, "e": 31710, "s": 31686, "text": "Why Int Is Not 16-bits?" }, { "code": null, "e": 32133, "s": 31710, "text": "They were 32 bits on the 32-bit platforms; the instruction coding for 16-bit operands (on both 32-bit and 64-bit) is one byte longer than that for 32-bit operands. And if a 16-bit value is stored during a register operation, the remainder of the register cannot be used, either on 32-bit or 64-bit, because there’s no instruction coding for “high half 32-bit register”. So 32 bits is kind of a natural size for an operand." }, { "code": null, "e": 32214, "s": 32133, "text": "Below is a C++ program to demonstrate the size of an integer in a 64-bit system:" }, { "code": null, "e": 32220, "s": 32214, "text": "C++14" }, { "code": "// C++ program for the above approach#include <bits/stdc++.h>using namespace std; // Driver Codeint main(){ // sizeof() operator is used to // give the size in bytes cout << sizeof(int); return 0;}", "e": 32433, "s": 32220, "text": null }, { "code": null, "e": 32436, "s": 32433, "text": "4\n" }, { "code": null, "e": 32438, "s": 32436, "text": "4" }, { "code": null, "e": 32525, "s": 32438, "text": "Below is a C++ program to demonstrate the size of an integer in a 32-bit (x86) system:" }, { "code": null, "e": 32531, "s": 32525, "text": "C++14" }, { "code": "// C++ program to implement// above approach#include <iostream>using namespace std; // Driver codeint main(){ // sizeof() operator is used // to give the size in bytes cout << sizeof(int); return 0;}", "e": 32744, "s": 32531, "text": null }, { "code": null, "e": 32747, "s": 32744, "text": "4\n" }, { "code": null, "e": 32754, "s": 32747, "text": "Output" }, { "code": null, "e": 32756, "s": 32754, "text": "2" }, { "code": null, "e": 32792, "s": 32756, "text": "Advantages of varying integer size:" }, { "code": null, "e": 32962, "s": 32792, "text": "One of the benefits of varying the size is that fewer CPU cycles are required to read or write.Efficient use of a given architecture depends on 32-bit or 64-bit systems." }, { "code": null, "e": 33058, "s": 32962, "text": "One of the benefits of varying the size is that fewer CPU cycles are required to read or write." }, { "code": null, "e": 33133, "s": 33058, "text": "Efficient use of a given architecture depends on 32-bit or 64-bit systems." }, { "code": null, "e": 33172, "s": 33133, "text": "Disadvantages of varying integer size:" }, { "code": null, "e": 33803, "s": 33172, "text": "Variation in different architectures does not give the programmer a clear view about the size of the integers to take type decisions for further calculation.It can cause various problems in memory if misused for bad purposes, leading to supporting some attacks such as buffer overflow.An integer overflow may occur if some program tries to store a value in an integer variable larger than the maximum value the variable can store.Different sizes can use multiple CPU registers. For example, if there is a need to store a number greater than 2^32 in a 32-bit machine, then two registers are required, the same for a 64-bit machine." }, { "code": null, "e": 33961, "s": 33803, "text": "Variation in different architectures does not give the programmer a clear view about the size of the integers to take type decisions for further calculation." }, { "code": null, "e": 34090, "s": 33961, "text": "It can cause various problems in memory if misused for bad purposes, leading to supporting some attacks such as buffer overflow." }, { "code": null, "e": 34236, "s": 34090, "text": "An integer overflow may occur if some program tries to store a value in an integer variable larger than the maximum value the variable can store." }, { "code": null, "e": 34437, "s": 34236, "text": "Different sizes can use multiple CPU registers. For example, if there is a need to store a number greater than 2^32 in a 32-bit machine, then two registers are required, the same for a 64-bit machine." }, { "code": null, "e": 34446, "s": 34437, "text": "Analysis" }, { "code": null, "e": 34455, "s": 34446, "text": "Articles" }, { "code": null, "e": 34553, "s": 34455, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34620, "s": 34553, "text": "Types of Complexity Classes | P, NP, CoNP, NP hard and NP complete" }, { "code": null, "e": 34686, "s": 34620, "text": "Difference between Deterministic and Non-deterministic Algorithms" }, { "code": null, "e": 34747, "s": 34686, "text": "Complexity analysis of various operations of Binary Min Heap" }, { "code": null, "e": 34776, "s": 34747, "text": "Pseudo-polynomial Algorithms" }, { "code": null, "e": 34820, "s": 34776, "text": "Proof that Hamiltonian Cycle is NP-Complete" }, { "code": null, "e": 34870, "s": 34820, "text": "Tree Traversals (Inorder, Preorder and Postorder)" }, { "code": null, "e": 34917, "s": 34870, "text": "SQL | Join (Inner, Left, Right and Full Joins)" }, { "code": null, "e": 34953, "s": 34917, "text": "find command in Linux with examples" }, { "code": null, "e": 34981, "s": 34953, "text": "How to write a Pseudo Code?" } ]
iOS - Objective C
The language used in iOS development is objective C. It is an object-oriented language and hence, it would be easy for those who have some background in object-oriented programming languages. In Objective C, the file where the declaration of class is done is called the interface file and the file where the class is defined is called the implementation file. A simple interface file MyClass.h would look like the following − @interface MyClass:NSObject { // class variable declared here } // class properties declared here // class methods and instance methods declared here @end The implementation file MyClass.m would be as follows − @implementation MyClass // class methods defined here @end Object creation is done as follows − MyClass *objectName = [[MyClass alloc]init] ; Method is declared in Objective C as follows − -(returnType)methodName:(typeName) variable1 :(typeName)variable2; An example is shown below. -(void)calculateAreaForRectangleWithLength:(CGfloat)length andBreadth:(CGfloat)breadth; You might be wondering what the andBreadth string is for; actually it’s an optional string, which helps us read and understand the method easily, especially at the time of calling. To call this method in the same class, we use the following statement − [self calculateAreaForRectangleWithLength:30 andBreadth:20]; As said above, the use of andBreadth helps us understand that breadth is 20. Self is used to specify that it's a class method. Class methods can be accessed directly without creating objects for the class. They don't have any variables and objects associated with it. An example is shown below. +(void)simpleClassMethod; It can be accessed by using the class name (let's assume the class name as MyClass) as follows − [MyClass simpleClassMethod]; Instance methods can be accessed only after creating an object for the class. Memory is allocated to the instance variables. An example instance method is shown below. -(void)simpleInstanceMethod; It can be accessed after creating an object for the class as follows − MyClass *objectName = [[MyClass alloc]init] ; [objectName simpleInstanceMethod]; NSString It is used for representing a string. CGfloat It is used for representing a floating point value (normal float is also allowed but it's better to use CGfloat). NSInteger It is used for representing integer. BOOL It is used for representing Boolean (YES or NO are BOOL types allowed). NSLog - used for printing a statement. It will be printed in the device logs and debug console in release and debug modes respectively. For example, NSlog(@""); Most of the control structures are same as in C and C++, except for a few additions like for in statement. For an external class to access the class, variable properties are used. For example, @property(nonatomic , strong) NSString *myString; You can use dot operator to access properties. To access the above property, we will do the following. self.myString = @"Test"; You can also use the set method as follows − [self setMyString:@"Test"]; Categories are used to add methods to the existing classes. By this way, we can add method to classes for which we don't have even implementation files where the actual class is defined. A sample category for our class is as follows − @interface MyClass(customAdditions) - (void)sampleCategoryMethod; @end @implementation MyClass(categoryAdditions) -(void)sampleCategoryMethod { NSLog(@"Just a test category"); } NSMutableArray and NSArray are the array classes used in objective C. As the name suggests, the former is mutable and the latter is immutable. An example is shown below. NSMutableArray *aMutableArray = [[NSMutableArray alloc]init]; [anArray addObject:@"firstobject"]; NSArray *aImmutableArray = [[NSArray alloc] initWithObjects:@"firstObject",nil]; NSMutableDictionary and NSDictionary are the dictionary classes used in objective C. As the name suggests, the former is mutable and the latter is immutable. An example is shown below. NSMutableDictionary *aMutableDictionary = [[NSMutableArray alloc]init]; [aMutableDictionary setObject:@"firstobject" forKey:@"aKey"]; NSDictionary*aImmutableDictionary= [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects: @"firstObject",nil] forKeys:[ NSArray arrayWithObjects:@"aKey"]]; 23 Lectures 1.5 hours Ashish Sharma 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 69 Lectures 4 hours Frahaan Hussain Print Add Notes Bookmark this page
[ { "code": null, "e": 2283, "s": 2091, "text": "The language used in iOS development is objective C. It is an object-oriented language and hence, it would be easy for those who have some background in object-oriented programming languages." }, { "code": null, "e": 2451, "s": 2283, "text": "In Objective C, the file where the declaration of class is done is called the interface file and the file where the class is defined is called the implementation file." }, { "code": null, "e": 2517, "s": 2451, "text": "A simple interface file MyClass.h would look like the following −" }, { "code": null, "e": 2677, "s": 2517, "text": "@interface MyClass:NSObject { \n // class variable declared here\n}\n\n// class properties declared here\n// class methods and instance methods declared here\n@end" }, { "code": null, "e": 2733, "s": 2677, "text": "The implementation file MyClass.m would be as follows −" }, { "code": null, "e": 2795, "s": 2733, "text": "@implementation MyClass\n // class methods defined here\n@end" }, { "code": null, "e": 2832, "s": 2795, "text": "Object creation is done as follows −" }, { "code": null, "e": 2880, "s": 2832, "text": "MyClass *objectName = [[MyClass alloc]init] ;\n" }, { "code": null, "e": 2927, "s": 2880, "text": "Method is declared in Objective C as follows −" }, { "code": null, "e": 2995, "s": 2927, "text": "-(returnType)methodName:(typeName) variable1 :(typeName)variable2;\n" }, { "code": null, "e": 3022, "s": 2995, "text": "An example is shown below." }, { "code": null, "e": 3112, "s": 3022, "text": "-(void)calculateAreaForRectangleWithLength:(CGfloat)length \nandBreadth:(CGfloat)breadth;\n" }, { "code": null, "e": 3365, "s": 3112, "text": "You might be wondering what the andBreadth string is for; actually it’s an optional string, which helps us read and understand the method easily, especially at the time of calling. To call this method in the same class, we use the following statement −" }, { "code": null, "e": 3427, "s": 3365, "text": "[self calculateAreaForRectangleWithLength:30 andBreadth:20];\n" }, { "code": null, "e": 3554, "s": 3427, "text": "As said above, the use of andBreadth helps us understand that breadth is 20. Self is used to specify that it's a class method." }, { "code": null, "e": 3722, "s": 3554, "text": "Class methods can be accessed directly without creating objects for the class. They don't have any variables and objects associated with it. An example is shown below." }, { "code": null, "e": 3749, "s": 3722, "text": "+(void)simpleClassMethod;\n" }, { "code": null, "e": 3846, "s": 3749, "text": "It can be accessed by using the class name (let's assume the class name as MyClass) as follows −" }, { "code": null, "e": 3876, "s": 3846, "text": "[MyClass simpleClassMethod];\n" }, { "code": null, "e": 4044, "s": 3876, "text": "Instance methods can be accessed only after creating an object for the class. Memory is allocated to the instance variables. An example instance method is shown below." }, { "code": null, "e": 4075, "s": 4044, "text": "-(void)simpleInstanceMethod; \n" }, { "code": null, "e": 4146, "s": 4075, "text": "It can be accessed after creating an object for the class as follows −" }, { "code": null, "e": 4228, "s": 4146, "text": "MyClass *objectName = [[MyClass alloc]init] ;\n[objectName simpleInstanceMethod];" }, { "code": null, "e": 4237, "s": 4228, "text": "NSString" }, { "code": null, "e": 4275, "s": 4237, "text": "It is used for representing a string." }, { "code": null, "e": 4283, "s": 4275, "text": "CGfloat" }, { "code": null, "e": 4397, "s": 4283, "text": "It is used for representing a floating point value (normal float is also allowed but it's better to use CGfloat)." }, { "code": null, "e": 4407, "s": 4397, "text": "NSInteger" }, { "code": null, "e": 4444, "s": 4407, "text": "It is used for representing integer." }, { "code": null, "e": 4449, "s": 4444, "text": "BOOL" }, { "code": null, "e": 4521, "s": 4449, "text": "It is used for representing Boolean (YES or NO are BOOL types allowed)." }, { "code": null, "e": 4670, "s": 4521, "text": "NSLog - used for printing a statement. It will be printed in the device logs and debug console in release and debug modes respectively. For example," }, { "code": null, "e": 4683, "s": 4670, "text": "NSlog(@\"\");\n" }, { "code": null, "e": 4790, "s": 4683, "text": "Most of the control structures are same as in C and C++, except for a few additions like for in statement." }, { "code": null, "e": 4876, "s": 4790, "text": "For an external class to access the class, variable properties are used. For example," }, { "code": null, "e": 4927, "s": 4876, "text": "@property(nonatomic , strong) NSString *myString;\n" }, { "code": null, "e": 5030, "s": 4927, "text": "You can use dot operator to access properties. To access the above property, we will do the following." }, { "code": null, "e": 5056, "s": 5030, "text": "self.myString = @\"Test\";\n" }, { "code": null, "e": 5101, "s": 5056, "text": "You can also use the set method as follows −" }, { "code": null, "e": 5130, "s": 5101, "text": "[self setMyString:@\"Test\"];\n" }, { "code": null, "e": 5365, "s": 5130, "text": "Categories are used to add methods to the existing classes. By this way, we can add method to classes for which we don't have even implementation files where the actual class is defined. A sample category for our class is as follows −" }, { "code": null, "e": 5548, "s": 5365, "text": "@interface MyClass(customAdditions)\n- (void)sampleCategoryMethod;\n@end\n\n@implementation MyClass(categoryAdditions)\n\n-(void)sampleCategoryMethod {\n NSLog(@\"Just a test category\");\n}" }, { "code": null, "e": 5718, "s": 5548, "text": "NSMutableArray and NSArray are the array classes used in objective C. As the name suggests, the former is mutable and the latter is immutable. An example is shown below." }, { "code": null, "e": 5897, "s": 5718, "text": "NSMutableArray *aMutableArray = [[NSMutableArray alloc]init];\n[anArray addObject:@\"firstobject\"];\nNSArray *aImmutableArray = [[NSArray alloc]\ninitWithObjects:@\"firstObject\",nil];" }, { "code": null, "e": 6082, "s": 5897, "text": "NSMutableDictionary and NSDictionary are the dictionary classes used in objective C. As the name suggests, the former is mutable and the latter is immutable. An example is shown below." }, { "code": null, "e": 6381, "s": 6082, "text": "NSMutableDictionary *aMutableDictionary = [[NSMutableArray alloc]init];\n[aMutableDictionary setObject:@\"firstobject\" forKey:@\"aKey\"];\nNSDictionary*aImmutableDictionary= [[NSDictionary alloc]initWithObjects:[NSArray arrayWithObjects:\n@\"firstObject\",nil] forKeys:[ NSArray arrayWithObjects:@\"aKey\"]];" }, { "code": null, "e": 6416, "s": 6381, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6431, "s": 6416, "text": " Ashish Sharma" }, { "code": null, "e": 6463, "s": 6431, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 6480, "s": 6463, "text": " Abhilash Nelson" }, { "code": null, "e": 6515, "s": 6480, "text": "\n 14 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6532, "s": 6515, "text": " Abhilash Nelson" }, { "code": null, "e": 6567, "s": 6532, "text": "\n 15 Lectures \n 1.5 hours \n" }, { "code": null, "e": 6584, "s": 6567, "text": " Abhilash Nelson" }, { "code": null, "e": 6617, "s": 6584, "text": "\n 10 Lectures \n 1 hours \n" }, { "code": null, "e": 6634, "s": 6617, "text": " Abhilash Nelson" }, { "code": null, "e": 6667, "s": 6634, "text": "\n 69 Lectures \n 4 hours \n" }, { "code": null, "e": 6684, "s": 6667, "text": " Frahaan Hussain" }, { "code": null, "e": 6691, "s": 6684, "text": " Print" }, { "code": null, "e": 6702, "s": 6691, "text": " Add Notes" } ]
Program to find maximum k-repeating substring from sequence in Python
Suppose we have a sequence of characters called s, we say a string w is k-repeating string if w is concatenated k times is a substring of sequence. The w's maximum k-repeating value will be the highest value k where w is k-repeating in sequence. And if w is not a substring of the given sequence, w's maximum k-repeating value is 0. So if we have s and w we have to find the maximum k-repeating value of w in sequence. So, if the input is like s = "papaya" w = "pa", then the output will be 2 as w = "pa" is present twice in "papaya". To solve this, we will follow these steps − Count:= number of w present in s Count:= number of w present in s if Count is same as 0, thenreturn 0 if Count is same as 0, then return 0 return 0 for i in range Count to 0, decrease by 1, doif i repetition of w is present in s, thenreturn i for i in range Count to 0, decrease by 1, do if i repetition of w is present in s, thenreturn i if i repetition of w is present in s, then return i return i Let us see the following implementation to get better understanding − Live Demo def solve(s, w): Count=s.count(w) if Count==0: return 0 for i in range(Count,0,-1): if w*i in s: return i s = "papaya" w = "pa" print(solve(s, w)) "papaya", "pa" 2
[ { "code": null, "e": 1481, "s": 1062, "text": "Suppose we have a sequence of characters called s, we say a string w is k-repeating string if w is concatenated k times is a substring of sequence. The w's maximum k-repeating value will be the highest value k where w is k-repeating in sequence. And if w is not a substring of the given sequence, w's maximum k-repeating value is 0. So if we have s and w we have to find the maximum k-repeating value of w in sequence." }, { "code": null, "e": 1597, "s": 1481, "text": "So, if the input is like s = \"papaya\" w = \"pa\", then the output will be 2 as w = \"pa\" is present twice in \"papaya\"." }, { "code": null, "e": 1641, "s": 1597, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1674, "s": 1641, "text": "Count:= number of w present in s" }, { "code": null, "e": 1707, "s": 1674, "text": "Count:= number of w present in s" }, { "code": null, "e": 1743, "s": 1707, "text": "if Count is same as 0, thenreturn 0" }, { "code": null, "e": 1771, "s": 1743, "text": "if Count is same as 0, then" }, { "code": null, "e": 1780, "s": 1771, "text": "return 0" }, { "code": null, "e": 1789, "s": 1780, "text": "return 0" }, { "code": null, "e": 1884, "s": 1789, "text": "for i in range Count to 0, decrease by 1, doif i repetition of w is present in s, thenreturn i" }, { "code": null, "e": 1929, "s": 1884, "text": "for i in range Count to 0, decrease by 1, do" }, { "code": null, "e": 1980, "s": 1929, "text": "if i repetition of w is present in s, thenreturn i" }, { "code": null, "e": 2023, "s": 1980, "text": "if i repetition of w is present in s, then" }, { "code": null, "e": 2032, "s": 2023, "text": "return i" }, { "code": null, "e": 2041, "s": 2032, "text": "return i" }, { "code": null, "e": 2111, "s": 2041, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2122, "s": 2111, "text": " Live Demo" }, { "code": null, "e": 2301, "s": 2122, "text": "def solve(s, w):\n Count=s.count(w)\n if Count==0:\n return 0\n for i in range(Count,0,-1):\n\n if w*i in s:\n return i\n\ns = \"papaya\"\nw = \"pa\"\nprint(solve(s, w))" }, { "code": null, "e": 2316, "s": 2301, "text": "\"papaya\", \"pa\"" }, { "code": null, "e": 2318, "s": 2316, "text": "2" } ]
Delete all the even nodes from a Doubly Linked List - GeeksforGeeks
11 Feb, 2022 Given a doubly linked list containing N nodes, the task is to delete all the even nodes from the list. Examples: Input: Initial List = 15 <=> 16 <=> 6 <=> 7 <=> 17 Output: Final List = 15 <=> 7 <=> 17Explanation: 16 and 6 are even nodes. So we need to delete them. Input: Initial List = 5 <=> 3 <=> 6 <=> 8 <=> 4 <=> 1 <=> 2 <=> 9 Output: Final List = 5 <=> 3 <=> 1 <=> 9 The idea is to traverse the nodes of the doubly linked list one by one and get the pointer of the nodes having data even. Delete those nodes by following the approach used in this post. Below is the implementation of above idea: C++ Java Python3 C# Javascript // C++ implementation to delete all// the even nodes from the doubly// linked list#include <bits/stdc++.h> using namespace std; // Node of the doubly linked liststruct Node { int data; Node *prev, *next;}; // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // allocate node Node* new_node = new Node(); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to delete a node in a Doubly Linked List.// head_ref --> pointer to head node pointer.// del --> pointer to node to be deletedvoid deleteNode(Node** head_ref, Node* del){ // base case if (*head_ref == NULL || del == NULL) return; // If node to be deleted is head node if (*head_ref == del) *head_ref = del->next; // Change next only if node to be // deleted is NOT the last node if (del->next != NULL) del->next->prev = del->prev; // Change prev only if node to be // deleted is NOT the first node if (del->prev != NULL) del->prev->next = del->next; // Finally, free the memory occupied by del free(del); return;} // function to delete all the even nodes// from the doubly linked listvoid deleteEvenNodes(Node** head_ref){ Node* ptr = *head_ref; Node* next; while (ptr != NULL) { next = ptr->next; // if true, delete node 'ptr' if (ptr->data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; }} // function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << " "; head = head->next; }} // Driver programint main(){ // start with the empty list Node* head = NULL; // create the doubly linked list // 15 <-> 16 <-> 7 <-> 6 <-> 17 push(&head, 17); push(&head, 6); push(&head, 7); push(&head, 16); push(&head, 15); cout << "Original List: "; printList(head); deleteEvenNodes(&head); cout << "\nModified List: "; printList(head);} // Java implementation to delete all// the even nodes from the doubly// linked listclass GFG{ // Node of the doubly linked liststatic class Node{ int data; Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to delete a node in a Doubly Linked List.// head_ref -. pointer to head node pointer.// del -. pointer to node to be deletedstatic Node deleteNode(Node head_ref, Node del){ // base case if (head_ref == null || del == null) return null; // If node to be deleted is head node if (head_ref == del) head_ref = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; return head_ref;} // function to delete all the even nodes// from the doubly linked liststatic Node deleteEvenNodes(Node head_ref){ Node ptr = head_ref; Node next; while (ptr != null) { next = ptr.next; // if true, delete node 'ptr' if (ptr.data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; } return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print( head.data + " "); head = head.next; }} // Driver codepublic static void main(String args[]){ // start with the empty list Node head = null; // create the doubly linked list // 15 <. 16 <. 7 <. 6 <. 17 head = push(head, 17); head = push(head, 6); head = push(head, 7); head = push(head, 16); head = push(head, 15); System.out.print("Original List: "); printList(head); head=deleteEvenNodes(head); System.out.print( "\nModified List: "); printList(head);}} // This code is contributed by Arnab Kundu # Python3 implementation to delete all# the even nodes from the doubly# linked listimport math # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref!= None): head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # function to delete a node in a Doubly Linked List.# head_ref --> pointer to head node pointer.# del --> pointer to node to be deleteddef deleteNode(head_ref, delete): # base case if (head_ref == None or delete == None): return # If node to be deleted is head node if (head_ref == delete): head_ref = delete.next # Change next only if node to be # deleted is NOT the last node if (delete.next != None): delete.next.prev = delete.prev # Change prev only if node to be # deleted is NOT the first node if (delete.prev != None): delete.prev.next = delete.next # Finally, free the memory occupied by del return head_ref # function to delete all the even nodes# from the doubly linked listdef deleteEvenNodes(head_ref): ptr = head_ref next = None while (ptr != None): next = ptr.next # if true, delete node 'ptr' if (ptr.data % 2 == 0): deleteNode(head_ref, ptr) ptr = next # function to print nodes in a# given doubly linked listdef printList(head): while (head != None) : print(head.data, end = " ") head = head.next # Driver Codeif __name__=='__main__': # start with the empty list head = None # create the doubly linked list # 15 <-> 16 <-> 7 <-> 6 <-> 17 head = push(head, 17) head = push(head, 6) head = push(head, 7) head = push(head, 16) head = push(head, 15) print("Original List: ", end = "") printList(head) deleteEvenNodes(head) print("\nModified List: ", end = "") printList(head) # This code is contributed by Srathore // C# implementation to delete all// the even nodes from the doubly// linked listusing System; class GFG{ // Node of the doubly linked listpublic class Node{ public int data; public Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to delete a node in a Doubly Linked List.// head_ref -. pointer to head node pointer.// del -. pointer to node to be deletedstatic Node deleteNode(Node head_ref, Node del){ // base case if (head_ref == null || del == null) return null; // If node to be deleted is head node if (head_ref == del) head_ref = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; return head_ref;} // function to delete all the even nodes// from the doubly linked liststatic Node deleteEvenNodes(Node head_ref){ Node ptr = head_ref; Node next; while (ptr != null) { next = ptr.next; // if true, delete node 'ptr' if (ptr.data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; } return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write( head.data + " "); head = head.next; }} // Driver codepublic static void Main(String []args){ // start with the empty list Node head = null; // create the doubly linked list // 15 <. 16 <. 7 <. 6 <. 17 head = push(head, 17); head = push(head, 6); head = push(head, 7); head = push(head, 16); head = push(head, 15); Console.Write("Original List: "); printList(head); head=deleteEvenNodes(head); Console.Write( "\nModified List: "); printList(head);}} /* This code is contributed by PrinciRaj1992 */ <script>// javascript implementation to delete all// the even nodes from the doubly// linked list // Node of the doubly linked listclass Node { constructor(val) { this.data = val; this.prev = null; this.next = null; }}// function to insert a node at the beginning// of the Doubly Linked Listfunction push(head_ref , new_data){ // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to delete a node in a Doubly Linked List.// head_ref -. pointer to head node pointer.// del -. pointer to node to be deletedfunction deleteNode(head_ref, del){ // base case if (head_ref == null || del == null) return null; // If node to be deleted is head node if (head_ref == del) head_ref = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; return head_ref;} // function to delete all the even nodes// from the doubly linked listfunction deleteEvenNodes(head_ref){ var ptr = head_ref; var next; while (ptr != null) { next = ptr.next; // if true, delete node 'ptr' if (ptr.data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; } return head_ref;} // function to print nodes in a// given doubly linked listfunction printList(head){ while (head != null) { document.write( head.data + " "); head = head.next; }} // Driver code // start with the empty list var head = null; // create the doubly linked list // 15 <. 16 <. 7 <. 6 <. 17 head = push(head, 17); head = push(head, 6); head = push(head, 7); head = push(head, 16); head = push(head, 15); document.write("Original List: "); printList(head); head=deleteEvenNodes(head); document.write( "<br/>Modified List: "); printList(head);// This code contributed by Rajput-Ji</script> Original List: 15 16 7 6 17 Modified List: 15 7 17 Time Complexity: O(N), where N is the total number of nodes. Auxiliary Space: O(1) andrew1234 princiraj1992 Akanksha_Rai sapnasingh4991 Rajput-Ji pankajsharmagfg surindertarika1234 simmytarika5 ashutoshsinghgeeksforgeeks doubly linked list Technical Scripter 2018 Traversal Data Structures Linked List Technical Scripter Data Structures Linked List Traversal Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments SDE SHEET - A Complete Guide for SDE Preparation DSA Sheet by Love Babbar Introduction to Algorithms Hash Map in Python Introduction to Tree Data Structure Linked List | Set 1 (Introduction) Linked List | Set 2 (Inserting a node) Reverse a linked list Stack Data Structure (Introduction and Program) Linked List | Set 3 (Deleting a node)
[ { "code": null, "e": 24977, "s": 24949, "text": "\n11 Feb, 2022" }, { "code": null, "e": 25081, "s": 24977, "text": "Given a doubly linked list containing N nodes, the task is to delete all the even nodes from the list. " }, { "code": null, "e": 25093, "s": 25081, "text": "Examples: " }, { "code": null, "e": 25245, "s": 25093, "text": "Input: Initial List = 15 <=> 16 <=> 6 <=> 7 <=> 17 Output: Final List = 15 <=> 7 <=> 17Explanation: 16 and 6 are even nodes. So we need to delete them." }, { "code": null, "e": 25353, "s": 25245, "text": "Input: Initial List = 5 <=> 3 <=> 6 <=> 8 <=> 4 <=> 1 <=> 2 <=> 9 Output: Final List = 5 <=> 3 <=> 1 <=> 9 " }, { "code": null, "e": 25539, "s": 25353, "text": "The idea is to traverse the nodes of the doubly linked list one by one and get the pointer of the nodes having data even. Delete those nodes by following the approach used in this post." }, { "code": null, "e": 25584, "s": 25539, "text": "Below is the implementation of above idea: " }, { "code": null, "e": 25588, "s": 25584, "text": "C++" }, { "code": null, "e": 25593, "s": 25588, "text": "Java" }, { "code": null, "e": 25601, "s": 25593, "text": "Python3" }, { "code": null, "e": 25604, "s": 25601, "text": "C#" }, { "code": null, "e": 25615, "s": 25604, "text": "Javascript" }, { "code": "// C++ implementation to delete all// the even nodes from the doubly// linked list#include <bits/stdc++.h> using namespace std; // Node of the doubly linked liststruct Node { int data; Node *prev, *next;}; // function to insert a node at the beginning// of the Doubly Linked Listvoid push(Node** head_ref, int new_data){ // allocate node Node* new_node = new Node(); // put in the data new_node->data = new_data; // since we are adding at the beginning, // prev is always NULL new_node->prev = NULL; // link the old list off the new node new_node->next = (*head_ref); // change prev of head node to new node if ((*head_ref) != NULL) (*head_ref)->prev = new_node; // move the head to point to the new node (*head_ref) = new_node;} // function to delete a node in a Doubly Linked List.// head_ref --> pointer to head node pointer.// del --> pointer to node to be deletedvoid deleteNode(Node** head_ref, Node* del){ // base case if (*head_ref == NULL || del == NULL) return; // If node to be deleted is head node if (*head_ref == del) *head_ref = del->next; // Change next only if node to be // deleted is NOT the last node if (del->next != NULL) del->next->prev = del->prev; // Change prev only if node to be // deleted is NOT the first node if (del->prev != NULL) del->prev->next = del->next; // Finally, free the memory occupied by del free(del); return;} // function to delete all the even nodes// from the doubly linked listvoid deleteEvenNodes(Node** head_ref){ Node* ptr = *head_ref; Node* next; while (ptr != NULL) { next = ptr->next; // if true, delete node 'ptr' if (ptr->data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; }} // function to print nodes in a// given doubly linked listvoid printList(Node* head){ while (head != NULL) { cout << head->data << \" \"; head = head->next; }} // Driver programint main(){ // start with the empty list Node* head = NULL; // create the doubly linked list // 15 <-> 16 <-> 7 <-> 6 <-> 17 push(&head, 17); push(&head, 6); push(&head, 7); push(&head, 16); push(&head, 15); cout << \"Original List: \"; printList(head); deleteEvenNodes(&head); cout << \"\\nModified List: \"; printList(head);}", "e": 27996, "s": 25615, "text": null }, { "code": "// Java implementation to delete all// the even nodes from the doubly// linked listclass GFG{ // Node of the doubly linked liststatic class Node{ int data; Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to delete a node in a Doubly Linked List.// head_ref -. pointer to head node pointer.// del -. pointer to node to be deletedstatic Node deleteNode(Node head_ref, Node del){ // base case if (head_ref == null || del == null) return null; // If node to be deleted is head node if (head_ref == del) head_ref = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; return head_ref;} // function to delete all the even nodes// from the doubly linked liststatic Node deleteEvenNodes(Node head_ref){ Node ptr = head_ref; Node next; while (ptr != null) { next = ptr.next; // if true, delete node 'ptr' if (ptr.data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; } return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { System.out.print( head.data + \" \"); head = head.next; }} // Driver codepublic static void main(String args[]){ // start with the empty list Node head = null; // create the doubly linked list // 15 <. 16 <. 7 <. 6 <. 17 head = push(head, 17); head = push(head, 6); head = push(head, 7); head = push(head, 16); head = push(head, 15); System.out.print(\"Original List: \"); printList(head); head=deleteEvenNodes(head); System.out.print( \"\\nModified List: \"); printList(head);}} // This code is contributed by Arnab Kundu", "e": 30477, "s": 27996, "text": null }, { "code": "# Python3 implementation to delete all# the even nodes from the doubly# linked listimport math # Node of the doubly linked listclass Node: def __init__(self, data): self.data = data self.next = None # function to insert a node at the beginning# of the Doubly Linked Listdef push(head_ref, new_data): # allocate node new_node = Node(new_data) # put in the data new_node.data = new_data # since we are adding at the beginning, # prev is always None new_node.prev = None # link the old list off the new node new_node.next = head_ref # change prev of head node to new node if (head_ref!= None): head_ref.prev = new_node # move the head to point to the new node head_ref = new_node return head_ref # function to delete a node in a Doubly Linked List.# head_ref --> pointer to head node pointer.# del --> pointer to node to be deleteddef deleteNode(head_ref, delete): # base case if (head_ref == None or delete == None): return # If node to be deleted is head node if (head_ref == delete): head_ref = delete.next # Change next only if node to be # deleted is NOT the last node if (delete.next != None): delete.next.prev = delete.prev # Change prev only if node to be # deleted is NOT the first node if (delete.prev != None): delete.prev.next = delete.next # Finally, free the memory occupied by del return head_ref # function to delete all the even nodes# from the doubly linked listdef deleteEvenNodes(head_ref): ptr = head_ref next = None while (ptr != None): next = ptr.next # if true, delete node 'ptr' if (ptr.data % 2 == 0): deleteNode(head_ref, ptr) ptr = next # function to print nodes in a# given doubly linked listdef printList(head): while (head != None) : print(head.data, end = \" \") head = head.next # Driver Codeif __name__=='__main__': # start with the empty list head = None # create the doubly linked list # 15 <-> 16 <-> 7 <-> 6 <-> 17 head = push(head, 17) head = push(head, 6) head = push(head, 7) head = push(head, 16) head = push(head, 15) print(\"Original List: \", end = \"\") printList(head) deleteEvenNodes(head) print(\"\\nModified List: \", end = \"\") printList(head) # This code is contributed by Srathore", "e": 32881, "s": 30477, "text": null }, { "code": "// C# implementation to delete all// the even nodes from the doubly// linked listusing System; class GFG{ // Node of the doubly linked listpublic class Node{ public int data; public Node prev, next;}; // function to insert a node at the beginning// of the Doubly Linked Liststatic Node push(Node head_ref, int new_data){ // allocate node Node new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to delete a node in a Doubly Linked List.// head_ref -. pointer to head node pointer.// del -. pointer to node to be deletedstatic Node deleteNode(Node head_ref, Node del){ // base case if (head_ref == null || del == null) return null; // If node to be deleted is head node if (head_ref == del) head_ref = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; return head_ref;} // function to delete all the even nodes// from the doubly linked liststatic Node deleteEvenNodes(Node head_ref){ Node ptr = head_ref; Node next; while (ptr != null) { next = ptr.next; // if true, delete node 'ptr' if (ptr.data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; } return head_ref;} // function to print nodes in a// given doubly linked liststatic void printList(Node head){ while (head != null) { Console.Write( head.data + \" \"); head = head.next; }} // Driver codepublic static void Main(String []args){ // start with the empty list Node head = null; // create the doubly linked list // 15 <. 16 <. 7 <. 6 <. 17 head = push(head, 17); head = push(head, 6); head = push(head, 7); head = push(head, 16); head = push(head, 15); Console.Write(\"Original List: \"); printList(head); head=deleteEvenNodes(head); Console.Write( \"\\nModified List: \"); printList(head);}} /* This code is contributed by PrinciRaj1992 */", "e": 35384, "s": 32881, "text": null }, { "code": "<script>// javascript implementation to delete all// the even nodes from the doubly// linked list // Node of the doubly linked listclass Node { constructor(val) { this.data = val; this.prev = null; this.next = null; }}// function to insert a node at the beginning// of the Doubly Linked Listfunction push(head_ref , new_data){ // allocate node var new_node = new Node(); // put in the data new_node.data = new_data; // since we are adding at the beginning, // prev is always null new_node.prev = null; // link the old list off the new node new_node.next = (head_ref); // change prev of head node to new node if ((head_ref) != null) (head_ref).prev = new_node; // move the head to point to the new node (head_ref) = new_node; return head_ref;} // function to delete a node in a Doubly Linked List.// head_ref -. pointer to head node pointer.// del -. pointer to node to be deletedfunction deleteNode(head_ref, del){ // base case if (head_ref == null || del == null) return null; // If node to be deleted is head node if (head_ref == del) head_ref = del.next; // Change next only if node to be // deleted is NOT the last node if (del.next != null) del.next.prev = del.prev; // Change prev only if node to be // deleted is NOT the first node if (del.prev != null) del.prev.next = del.next; return head_ref;} // function to delete all the even nodes// from the doubly linked listfunction deleteEvenNodes(head_ref){ var ptr = head_ref; var next; while (ptr != null) { next = ptr.next; // if true, delete node 'ptr' if (ptr.data % 2 == 0) deleteNode(head_ref, ptr); ptr = next; } return head_ref;} // function to print nodes in a// given doubly linked listfunction printList(head){ while (head != null) { document.write( head.data + \" \"); head = head.next; }} // Driver code // start with the empty list var head = null; // create the doubly linked list // 15 <. 16 <. 7 <. 6 <. 17 head = push(head, 17); head = push(head, 6); head = push(head, 7); head = push(head, 16); head = push(head, 15); document.write(\"Original List: \"); printList(head); head=deleteEvenNodes(head); document.write( \"<br/>Modified List: \"); printList(head);// This code contributed by Rajput-Ji</script>", "e": 37851, "s": 35384, "text": null }, { "code": null, "e": 37903, "s": 37851, "text": "Original List: 15 16 7 6 17 \nModified List: 15 7 17" }, { "code": null, "e": 37989, "s": 37905, "text": "Time Complexity: O(N), where N is the total number of nodes. Auxiliary Space: O(1) " }, { "code": null, "e": 38000, "s": 37989, "text": "andrew1234" }, { "code": null, "e": 38014, "s": 38000, "text": "princiraj1992" }, { "code": null, "e": 38027, "s": 38014, "text": "Akanksha_Rai" }, { "code": null, "e": 38042, "s": 38027, "text": "sapnasingh4991" }, { "code": null, "e": 38052, "s": 38042, "text": "Rajput-Ji" }, { "code": null, "e": 38068, "s": 38052, "text": "pankajsharmagfg" }, { "code": null, "e": 38087, "s": 38068, "text": "surindertarika1234" }, { "code": null, "e": 38100, "s": 38087, "text": "simmytarika5" }, { "code": null, "e": 38127, "s": 38100, "text": "ashutoshsinghgeeksforgeeks" }, { "code": null, "e": 38146, "s": 38127, "text": "doubly linked list" }, { "code": null, "e": 38170, "s": 38146, "text": "Technical Scripter 2018" }, { "code": null, "e": 38180, "s": 38170, "text": "Traversal" }, { "code": null, "e": 38196, "s": 38180, "text": "Data Structures" }, { "code": null, "e": 38208, "s": 38196, "text": "Linked List" }, { "code": null, "e": 38227, "s": 38208, "text": "Technical Scripter" }, { "code": null, "e": 38243, "s": 38227, "text": "Data Structures" }, { "code": null, "e": 38255, "s": 38243, "text": "Linked List" }, { "code": null, "e": 38265, "s": 38255, "text": "Traversal" }, { "code": null, "e": 38363, "s": 38265, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 38372, "s": 38363, "text": "Comments" }, { "code": null, "e": 38385, "s": 38372, "text": "Old Comments" }, { "code": null, "e": 38434, "s": 38385, "text": "SDE SHEET - A Complete Guide for SDE Preparation" }, { "code": null, "e": 38459, "s": 38434, "text": "DSA Sheet by Love Babbar" }, { "code": null, "e": 38486, "s": 38459, "text": "Introduction to Algorithms" }, { "code": null, "e": 38505, "s": 38486, "text": "Hash Map in Python" }, { "code": null, "e": 38541, "s": 38505, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 38576, "s": 38541, "text": "Linked List | Set 1 (Introduction)" }, { "code": null, "e": 38615, "s": 38576, "text": "Linked List | Set 2 (Inserting a node)" }, { "code": null, "e": 38637, "s": 38615, "text": "Reverse a linked list" }, { "code": null, "e": 38685, "s": 38637, "text": "Stack Data Structure (Introduction and Program)" } ]
How to suppress Matplotlib warning?
Let's take an example. We create a set of data points such that it would generate some warnings. We will create data points x from −1 to 1 and try to find log in that range, which means it will throw an error at value 0, while calculating logs. Create data points for x and calculate log(x), using numpy. Plot x and y using plot() method. Use warnings.filterwarnings("ignore") to suppress the warning. To display the figure, use show() method. import numpy as np from matplotlib import pyplot as plt import warnings plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True warnings.filterwarnings("ignore") x = np.linspace(-1, 1, 10) y = np.log(x) plt.plot(x, y) plt.show() When we execute the code, it will suppress the warning and display the following plot. Now, remove the line, warnings.filterwarnings("ignore") and execute the code again. It will display the plot, but with a runtime warning. RuntimeWarning: invalid value encountered in log
[ { "code": null, "e": 1307, "s": 1062, "text": "Let's take an example. We create a set of data points such that it would generate some warnings. We will create data points x from −1 to 1 and try to find log in that range, which means it will throw an error at value 0, while calculating logs." }, { "code": null, "e": 1367, "s": 1307, "text": "Create data points for x and calculate log(x), using numpy." }, { "code": null, "e": 1401, "s": 1367, "text": "Plot x and y using plot() method." }, { "code": null, "e": 1464, "s": 1401, "text": "Use warnings.filterwarnings(\"ignore\") to suppress the warning." }, { "code": null, "e": 1506, "s": 1464, "text": "To display the figure, use show() method." }, { "code": null, "e": 1766, "s": 1506, "text": "import numpy as np\nfrom matplotlib import pyplot as plt\nimport warnings\nplt.rcParams[\"figure.figsize\"] = [7.00, 3.50]\nplt.rcParams[\"figure.autolayout\"] = True\nwarnings.filterwarnings(\"ignore\")\nx = np.linspace(-1, 1, 10)\ny = np.log(x)\nplt.plot(x, y)\nplt.show()" }, { "code": null, "e": 1853, "s": 1766, "text": "When we execute the code, it will suppress the warning and display the following plot." }, { "code": null, "e": 1991, "s": 1853, "text": "Now, remove the line, warnings.filterwarnings(\"ignore\") and execute the code again. It will display the plot, but with a runtime warning." }, { "code": null, "e": 2040, "s": 1991, "text": "RuntimeWarning: invalid value encountered in log" } ]
Creating a Spell Checker with TensorFlow | by David Currie | Towards Data Science
One of the most important aspects of machine learning is working with good, clean data. Natural Language Progressing projects have the issue of using text that is written by humans, and we are unfortunately bad at writing. Just think about the many spelling mistakes that would be in a dataset about posts and comments from Reddit. For this reason, I thought a very worthwhile project would be to make a spell checker, which would help alleviate some of these problems. The model that we will use for this project is very similar to the one I wrote about in my article, “Text Summarization with Amazon Reviews” (both are seq2seq models), but I have added some extra lines of code so that the architecture and hyperparameters can be tuned using grid search, and the results can be analyzed with TensorBoard. If you would like a more detailed walkthrough about how to add TensorBoard to your code, then check out “Predicting Movie Review Sentiment with TensorFlow and TensorBoard”. The main focus of this article will be how to prepare the data for the model, and I will also talk about a few other features of the model. We will be using Python 3 and TensorFlow 1.1 in this project. The data is composed of twenty popular books from Project Gutenberg. If you are interested in scaling up this project to make it more accurate, there are hundreds of books that you can download on Project Gutenberg. Plus, it would be really interesting to see how good of a spell checker someone could make with this model. To see the full code, here is its GitHub page. To give you a preview of what this model is capable of, here are some curated examples: Spellin is difficult, whch is wyh you need to study everyday. Spelling is difficult, which is why you need to study everyday. The first days of her existence in th country were vrey hard for Dolly. The first days of her existence in the country were very hard for Dolly. Thi is really something impressiv thaat we should look into right away! This is really something impressive that we should look into right away! To make things a little more organized, I have put all of the books that we will use in their own folder, called “books”. Here is the function that we will use to load all of the books: def load_book(path): input_file = os.path.join(path) with open(input_file) as f: book = f.read() return book We will also need the unique file name for each of the books. path = './books/'book_files = [f for f in listdir(path) if isfile(join(path, f))]book_files = book_files[1:] When we put these two code blocks together, we will be able to load the text from all of our books into a list. books = []for book in book_files: books.append(load_book(path+book)) If you are interested in knowing how many words are in each book, you can use these lines of code: for i in range(len(books)): print("There are {} words in {}.".format(len(books[i].split()), book_files[i])) Note: If you do not include .split(), it will return the number of characters in each book. To clean the text of these books is rather simple. Since we will be using characters instead of words as the input to our model, we do not need to worry about removing stop words, or shorten words down to their stems. We only need to remove the characters that we do not want to include and extra spaces. def clean_text(text): '''Remove unwanted characters and extra spaces from the text''' text = re.sub(r'\n', ' ', text) text = re.sub(r'[{}@_*>()\\#%+=\[\]]','', text) text = re.sub('a0','', text) text = re.sub('\'92t','\'t', text) text = re.sub('\'92s','\'s', text) text = re.sub('\'92m','\'m', text) text = re.sub('\'92ll','\'ll', text) text = re.sub('\'91','', text) text = re.sub('\'92','', text) text = re.sub('\'93','', text) text = re.sub('\'94','', text) text = re.sub('\.','. ', text) text = re.sub('\!','! ', text) text = re.sub('\?','? ', text) text = re.sub(' +',' ', text) # Removes extra spaces return text I’m going to skip over how to make the vocab_to_int and int_to_vocab dictionaries, since that’s pretty standard stuff and you can find it on this project’s GitHub page. However, I think it’s worth showing you the characters that are included in the input data: The vocabulary contains 78 characters.[' ', '!', '"', '$', '&', "'", ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<EOS>', '<GO>', '<PAD>', '?', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] We could have removed some more of the special characters, or made the text all lower case, but I wanted to make this spell checker as useful as possible. The data will be organized into sentences before it is fed into the model. We will split the data at each period that is followed by a space (“. ”). One issue with this is that some sentences end in a question mark or exclamation mark, but we are not accounting for that. Fortunately, our model will still be able to learn about the use of question marks and exclamation marks, just as long as that and the following sentence, combined, are not as long as the maximum sentence length. Just to give an example: Today is a lovely day. I want to go to the beach. (This would be split into two input sentences) Is today a lovely day? I want to go to the beach. (This would be one long input sentence) sentences = []for book in clean_books: for sentence in book.split('. '): sentences.append(sentence + '.') I used a GPU on floydhub.com to train my model (I highly recommend their services), which saved me hours training time. Nonetheless, to properly tune this model, it still takes 30–60 minutes to run an iteration, which is why I am limiting the data, so that it does not take even longer. This will of course reduce the accuracy of our model, but since this is just a personal project, I don’t mind the trade-off. max_length = 92min_length = 10good_sentences = []for sentence in int_sentences: if len(sentence) <= max_length and len(sentence) >= min_length: good_sentences.append(sentence) To track the performance of this model, I will be spliting the data into a training and testing set. The testing set will be composed of 15% of the data. training, testing = train_test_split(good_sentences, test_size = 0.15, random_state = 2) Just like with some of my recent projects, I will be sorting the data by length. This results in sentences of a batch being of similar length, thus less padding is used, and the model will train faster. training_sorted = []testing_sorted = []for i in range(min_length, max_length+1): for sentence in training: if len(sentence) == i: training_sorted.append(sentence) for sentence in testing: if len(sentence) == i: testing_sorted.append(sentence) Perhaps the most interesting/important part of this project is the function that will convert the sentences to sentences with mistakes, which will be used as the input data. Mistakes are created within this function in one of three ways: the order of two characters will be swapped (hlelo ~hello) an extra letter will be added (heljlo ~ hello) a character will not be typed (helo ~hello) The likelihood of either of the three errors occurring is equal, and the likelihood of any error occurring is 5%. Therefore, one in every 20 characters, on average, will include a mistake. letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z',]def noise_maker(sentence, threshold): noisy_sentence = [] i = 0 while i < len(sentence): random = np.random.uniform(0,1,1) if random < threshold: noisy_sentence.append(sentence[i]) else: new_random = np.random.uniform(0,1,1) if new_random > 0.67: if i == (len(sentence) - 1): continue else: noisy_sentence.append(sentence[i+1]) noisy_sentence.append(sentence[i]) i += 1 elif new_random < 0.33: random_letter = np.random.choice(letters, 1)[0] noisy_sentence.append(vocab_to_int[random_letter]) noisy_sentence.append(sentence[i]) else: pass i += 1 return noisy_sentence The last thing that I want to show you in this article is how to create the batches. Typically one would create their input data before training their model, which would mean they have a fixed amount of training data. However, we are going to be creating new input data as we train our model, by applying noise_maker to each batch. This means that for every epoch the target (correct) sentence will be fed back through noise_maker and should receive a new input sentence. Using this method, we have, in a slightly exaggerated sense, an infinite amount of training data. def get_batches(sentences, batch_size, threshold): for batch_i in range(0, len(sentences)//batch_size): start_i = batch_i * batch_size sentences_batch = sentences[start_i:start_i + batch_size] sentences_batch_noisy = [] for sentence in sentences_batch: sentences_batch_noisy.append( noise_maker(sentence, threshold)) sentences_batch_eos = [] for sentence in sentences_batch: sentence.append(vocab_to_int['<EOS>']) sentences_batch_eos.append(sentence) pad_sentences_batch = np.array( pad_sentence_batch(sentences_batch_eos)) pad_sentences_noisy_batch = np.array( pad_sentence_batch(sentences_batch_noisy)) pad_sentences_lengths = [] for sentence in pad_sentences_batch: pad_sentences_lengths.append(len(sentence)) pad_sentences_noisy_lengths = [] for sentence in pad_sentences_noisy_batch: pad_sentences_noisy_lengths.append(len(sentence)) yield (pad_sentences_noisy_batch, pad_sentences_batch, pad_sentences_noisy_lengths, pad_sentences_lengths) That’s all for this project! Although the results are encouraging, there are still limitations to this model. I would really appreciate if someone would scale this model up or improve upon its design! Please post about it in the comments if you do. One thought for new design would be to apply FAIR’s new CNN model (it achieves state-of-the-art results for translation). Thanks for reading and I hope that you learned something new!
[ { "code": null, "e": 642, "s": 172, "text": "One of the most important aspects of machine learning is working with good, clean data. Natural Language Progressing projects have the issue of using text that is written by humans, and we are unfortunately bad at writing. Just think about the many spelling mistakes that would be in a dataset about posts and comments from Reddit. For this reason, I thought a very worthwhile project would be to make a spell checker, which would help alleviate some of these problems." }, { "code": null, "e": 1152, "s": 642, "text": "The model that we will use for this project is very similar to the one I wrote about in my article, “Text Summarization with Amazon Reviews” (both are seq2seq models), but I have added some extra lines of code so that the architecture and hyperparameters can be tuned using grid search, and the results can be analyzed with TensorBoard. If you would like a more detailed walkthrough about how to add TensorBoard to your code, then check out “Predicting Movie Review Sentiment with TensorFlow and TensorBoard”." }, { "code": null, "e": 1678, "s": 1152, "text": "The main focus of this article will be how to prepare the data for the model, and I will also talk about a few other features of the model. We will be using Python 3 and TensorFlow 1.1 in this project. The data is composed of twenty popular books from Project Gutenberg. If you are interested in scaling up this project to make it more accurate, there are hundreds of books that you can download on Project Gutenberg. Plus, it would be really interesting to see how good of a spell checker someone could make with this model." }, { "code": null, "e": 1725, "s": 1678, "text": "To see the full code, here is its GitHub page." }, { "code": null, "e": 1813, "s": 1725, "text": "To give you a preview of what this model is capable of, here are some curated examples:" }, { "code": null, "e": 1875, "s": 1813, "text": "Spellin is difficult, whch is wyh you need to study everyday." }, { "code": null, "e": 1939, "s": 1875, "text": "Spelling is difficult, which is why you need to study everyday." }, { "code": null, "e": 2011, "s": 1939, "text": "The first days of her existence in th country were vrey hard for Dolly." }, { "code": null, "e": 2084, "s": 2011, "text": "The first days of her existence in the country were very hard for Dolly." }, { "code": null, "e": 2156, "s": 2084, "text": "Thi is really something impressiv thaat we should look into right away!" }, { "code": null, "e": 2229, "s": 2156, "text": "This is really something impressive that we should look into right away!" }, { "code": null, "e": 2415, "s": 2229, "text": "To make things a little more organized, I have put all of the books that we will use in their own folder, called “books”. Here is the function that we will use to load all of the books:" }, { "code": null, "e": 2540, "s": 2415, "text": "def load_book(path): input_file = os.path.join(path) with open(input_file) as f: book = f.read() return book" }, { "code": null, "e": 2602, "s": 2540, "text": "We will also need the unique file name for each of the books." }, { "code": null, "e": 2711, "s": 2602, "text": "path = './books/'book_files = [f for f in listdir(path) if isfile(join(path, f))]book_files = book_files[1:]" }, { "code": null, "e": 2823, "s": 2711, "text": "When we put these two code blocks together, we will be able to load the text from all of our books into a list." }, { "code": null, "e": 2895, "s": 2823, "text": "books = []for book in book_files: books.append(load_book(path+book))" }, { "code": null, "e": 2994, "s": 2895, "text": "If you are interested in knowing how many words are in each book, you can use these lines of code:" }, { "code": null, "e": 3105, "s": 2994, "text": "for i in range(len(books)): print(\"There are {} words in {}.\".format(len(books[i].split()), book_files[i]))" }, { "code": null, "e": 3197, "s": 3105, "text": "Note: If you do not include .split(), it will return the number of characters in each book." }, { "code": null, "e": 3502, "s": 3197, "text": "To clean the text of these books is rather simple. Since we will be using characters instead of words as the input to our model, we do not need to worry about removing stop words, or shorten words down to their stems. We only need to remove the characters that we do not want to include and extra spaces." }, { "code": null, "e": 4173, "s": 3502, "text": "def clean_text(text): '''Remove unwanted characters and extra spaces from the text''' text = re.sub(r'\\n', ' ', text) text = re.sub(r'[{}@_*>()\\\\#%+=\\[\\]]','', text) text = re.sub('a0','', text) text = re.sub('\\'92t','\\'t', text) text = re.sub('\\'92s','\\'s', text) text = re.sub('\\'92m','\\'m', text) text = re.sub('\\'92ll','\\'ll', text) text = re.sub('\\'91','', text) text = re.sub('\\'92','', text) text = re.sub('\\'93','', text) text = re.sub('\\'94','', text) text = re.sub('\\.','. ', text) text = re.sub('\\!','! ', text) text = re.sub('\\?','? ', text) text = re.sub(' +',' ', text) # Removes extra spaces return text" }, { "code": null, "e": 4434, "s": 4173, "text": "I’m going to skip over how to make the vocab_to_int and int_to_vocab dictionaries, since that’s pretty standard stuff and you can find it on this project’s GitHub page. However, I think it’s worth showing you the characters that are included in the input data:" }, { "code": null, "e": 4874, "s": 4434, "text": "The vocabulary contains 78 characters.[' ', '!', '\"', '$', '&', \"'\", ',', '-', '.', '/', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', ':', ';', '<EOS>', '<GO>', '<PAD>', '?', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']" }, { "code": null, "e": 5029, "s": 4874, "text": "We could have removed some more of the special characters, or made the text all lower case, but I wanted to make this spell checker as useful as possible." }, { "code": null, "e": 5514, "s": 5029, "text": "The data will be organized into sentences before it is fed into the model. We will split the data at each period that is followed by a space (“. ”). One issue with this is that some sentences end in a question mark or exclamation mark, but we are not accounting for that. Fortunately, our model will still be able to learn about the use of question marks and exclamation marks, just as long as that and the following sentence, combined, are not as long as the maximum sentence length." }, { "code": null, "e": 5539, "s": 5514, "text": "Just to give an example:" }, { "code": null, "e": 5636, "s": 5539, "text": "Today is a lovely day. I want to go to the beach. (This would be split into two input sentences)" }, { "code": null, "e": 5726, "s": 5636, "text": "Is today a lovely day? I want to go to the beach. (This would be one long input sentence)" }, { "code": null, "e": 5842, "s": 5726, "text": "sentences = []for book in clean_books: for sentence in book.split('. '): sentences.append(sentence + '.')" }, { "code": null, "e": 6254, "s": 5842, "text": "I used a GPU on floydhub.com to train my model (I highly recommend their services), which saved me hours training time. Nonetheless, to properly tune this model, it still takes 30–60 minutes to run an iteration, which is why I am limiting the data, so that it does not take even longer. This will of course reduce the accuracy of our model, but since this is just a personal project, I don’t mind the trade-off." }, { "code": null, "e": 6440, "s": 6254, "text": "max_length = 92min_length = 10good_sentences = []for sentence in int_sentences: if len(sentence) <= max_length and len(sentence) >= min_length: good_sentences.append(sentence)" }, { "code": null, "e": 6594, "s": 6440, "text": "To track the performance of this model, I will be spliting the data into a training and testing set. The testing set will be composed of 15% of the data." }, { "code": null, "e": 6757, "s": 6594, "text": "training, testing = train_test_split(good_sentences, test_size = 0.15, random_state = 2)" }, { "code": null, "e": 6960, "s": 6757, "text": "Just like with some of my recent projects, I will be sorting the data by length. This results in sentences of a batch being of similar length, thus less padding is used, and the model will train faster." }, { "code": null, "e": 7245, "s": 6960, "text": "training_sorted = []testing_sorted = []for i in range(min_length, max_length+1): for sentence in training: if len(sentence) == i: training_sorted.append(sentence) for sentence in testing: if len(sentence) == i: testing_sorted.append(sentence)" }, { "code": null, "e": 7483, "s": 7245, "text": "Perhaps the most interesting/important part of this project is the function that will convert the sentences to sentences with mistakes, which will be used as the input data. Mistakes are created within this function in one of three ways:" }, { "code": null, "e": 7542, "s": 7483, "text": "the order of two characters will be swapped (hlelo ~hello)" }, { "code": null, "e": 7589, "s": 7542, "text": "an extra letter will be added (heljlo ~ hello)" }, { "code": null, "e": 7633, "s": 7589, "text": "a character will not be typed (helo ~hello)" }, { "code": null, "e": 7822, "s": 7633, "text": "The likelihood of either of the three errors occurring is equal, and the likelihood of any error occurring is 5%. Therefore, one in every 20 characters, on average, will include a mistake." }, { "code": null, "e": 8787, "s": 7822, "text": "letters = ['a','b','c','d','e','f','g','h','i','j','k','l','m', 'n','o','p','q','r','s','t','u','v','w','x','y','z',]def noise_maker(sentence, threshold): noisy_sentence = [] i = 0 while i < len(sentence): random = np.random.uniform(0,1,1) if random < threshold: noisy_sentence.append(sentence[i]) else: new_random = np.random.uniform(0,1,1) if new_random > 0.67: if i == (len(sentence) - 1): continue else: noisy_sentence.append(sentence[i+1]) noisy_sentence.append(sentence[i]) i += 1 elif new_random < 0.33: random_letter = np.random.choice(letters, 1)[0] noisy_sentence.append(vocab_to_int[random_letter]) noisy_sentence.append(sentence[i]) else: pass i += 1 return noisy_sentence" }, { "code": null, "e": 9357, "s": 8787, "text": "The last thing that I want to show you in this article is how to create the batches. Typically one would create their input data before training their model, which would mean they have a fixed amount of training data. However, we are going to be creating new input data as we train our model, by applying noise_maker to each batch. This means that for every epoch the target (correct) sentence will be fed back through noise_maker and should receive a new input sentence. Using this method, we have, in a slightly exaggerated sense, an infinite amount of training data." }, { "code": null, "e": 10594, "s": 9357, "text": "def get_batches(sentences, batch_size, threshold): for batch_i in range(0, len(sentences)//batch_size): start_i = batch_i * batch_size sentences_batch = sentences[start_i:start_i + batch_size] sentences_batch_noisy = [] for sentence in sentences_batch: sentences_batch_noisy.append( noise_maker(sentence, threshold)) sentences_batch_eos = [] for sentence in sentences_batch: sentence.append(vocab_to_int['<EOS>']) sentences_batch_eos.append(sentence) pad_sentences_batch = np.array( pad_sentence_batch(sentences_batch_eos)) pad_sentences_noisy_batch = np.array( pad_sentence_batch(sentences_batch_noisy)) pad_sentences_lengths = [] for sentence in pad_sentences_batch: pad_sentences_lengths.append(len(sentence)) pad_sentences_noisy_lengths = [] for sentence in pad_sentences_noisy_batch: pad_sentences_noisy_lengths.append(len(sentence)) yield (pad_sentences_noisy_batch, pad_sentences_batch, pad_sentences_noisy_lengths, pad_sentences_lengths)" }, { "code": null, "e": 10965, "s": 10594, "text": "That’s all for this project! Although the results are encouraging, there are still limitations to this model. I would really appreciate if someone would scale this model up or improve upon its design! Please post about it in the comments if you do. One thought for new design would be to apply FAIR’s new CNN model (it achieves state-of-the-art results for translation)." } ]
What is difference between instantiating a C++ object using new vs. without new?
In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object. This will be stored at the stack section. This will be destroyed when the scope ends. But for the case when we want to allocate the space for the item dynamically, then we can create pointer of that class, and instantiate using new operator. In C++, the new is used to dynamically allocate memory. #include <iostream> using namespace std; class Point { int x, y, z; public: Point(int x, int y, int z) { this->x = x; this->y = y; this->z = z; } void display() { cout << "(" << x << ", " << y << ", " << z << ")" << endl; } }; int main() { Point p1(10, 15, 20); p1.display(); Point *ptr; ptr = new Point(50, 60, 70); ptr->display(); } (10, 15, 20) (50, 60, 70)
[ { "code": null, "e": 1449, "s": 1062, "text": "In C++, we can instantiate the class object with or without using the new keyword. If the new keyword is not use, then it is like normal object. This will be stored at the stack section. This will be destroyed when the scope ends. But for the case when we want to allocate the space for the item dynamically, then we can create pointer of that class, and instantiate using new operator." }, { "code": null, "e": 1505, "s": 1449, "text": "In C++, the new is used to dynamically allocate memory." }, { "code": null, "e": 1921, "s": 1505, "text": "#include <iostream>\nusing namespace std;\nclass Point {\n int x, y, z;\n public:\n Point(int x, int y, int z) {\n this->x = x;\n this->y = y;\n this->z = z;\n }\n void display() {\n cout << \"(\" << x << \", \" << y << \", \" << z << \")\" << endl;\n }\n};\nint main() {\n Point p1(10, 15, 20);\n p1.display();\n Point *ptr;\n ptr = new Point(50, 60, 70);\n ptr->display();\n}" }, { "code": null, "e": 1947, "s": 1921, "text": "(10, 15, 20)\n(50, 60, 70)" } ]
Genetic Algorithm to Optimize Machine Learning Hyperparameters | by Marcos del Cueto | Towards Data Science
Hyperparameter tuning is critical for the correct functioning of Machine Learning models. You can check Timo Böhm’s article to see an overview of hyperparameter tuning. Genetic algorithms provide a powerful technique for hyperparameter tuning, but they are quite often overlooked. In this article, I will show an overview of genetic algorithms. I will also offer a detailed step-by-step guide on exploiting available libraries to use genetic algorithms to optimize the hyperparameters of a Machine Learning model. Genetic algorithms make use of basic concepts from evolution by natural selection to optimize arbitrary functions. This short article will introduce Differential Evolution and teach how to exploit it to optimize the hyperparameters used in Kernel Ridge Regression. I provide snippets of code to show how to use a Differential Evolution algorithm in Python. Complete codes and figures are also provided in a GitHub repository, so anyone can dive into the details. Genetic algorithms, such as Differential Evolution, make use of basic concepts from evolution by natural selection. In our case, we have a population formed by vectors that contain parameters with distinct values. Parameters are equivalent to genes in biological systems. Their exact value differs between different vectors. Different combinations of parameters cause vectors to display different fitness values. Random parameter mutations are introduced in the population, and vectors with a larger fitness outlive other vectors. Using an iterative process, Differential Evolution can minimize a function following steps: 1 — Initialization: create an initial population with NP vectors with random parameter values within boundaries. 2 — Initial evaluation: calculate function value for the NP vectors. 3 — For each vector in the population: 3.1 — Mutation: we build a mutant vector, where each parameter’s value is calculated as a mutation of the parameters of other vectors randomly chosen from the population. A common strategy to calculate this mutant vector is best1bin, where each parameter pi of the mutant vector is calculated as shown in the Equation below. The mutant parameter is a variation of the pi parameter of the best vector (vector with the lowest value) plus a mutation rate (F) times the pi-difference of two vectors randomly chosen, r1 and r2. 3.2 — Recombination: a trial vector is created by selecting each of its parameters as either the value of the current vector or the value of the mutant vector. For each parameter, we generate a random uniform number R in the (0,1) interval. If R is lower than a recombination rate, then we accept the mutant parameter; otherwise, we use the parameter of the current parameter. 3.3 — Replacement: evaluate the function of the trial vector. If it’s more stable than the current one, substitute the current vector by the trial vector. 4 — Repeat Step 3 until population convergence: iteration stops when the standard deviation of the function within the population is smaller than a specific percentage of the mean value of the function. Loop also stops if convergence is not reached after a maximum number of iterations. All this process is already implemented in several libraries in the main programming languages. Here, we will be using Scipy’s implementation in Python, which lets us do everything we want by using just a few lines of code. As an example, we will use data that follows the two-dimensional function f(x1,x2)=sin(x1)+cos(x2), plus a small random variation in the interval (-2,2) to spice things up. Therefore, our data will follow the expression: In the figure below, we show in grayscale the value of sin(x1)+cos(x2) as a reference. Then, we show colored points to indicate our 441 points (21x21 grid), calculated with the expression above in the interval x1:(-10,10) and x2:(-10,10). We offer below a code snippet with the function used to generate our data: Our goal is to use the data generated previously to train an ML model that will be able to predict the value of the function f(x1,x2) at different configurations. In this article, I will be using Kernel Ridge Regression (KRR). We will be using a radial basis function kernel for KRR, which depends on the Gaussian kernel variance γ. With KRR, we also need to optimize the regularization hyperparameter α. If you want more details on KRR and its implementation, feel free to check out my recent tutorial on this topic. Here we use a 10-fold cross-validation, where our data is split into a training set used to optimize the model, and a test set used to measure the model accuracy. As an accuracy metric, we will use the root-mean-square error (RMSE), which represents the average error between the f(x1,x2) values in the test set and those predicted by our model. As an optional first step, we can perform a grid-search to see how the RMSE changes with the value of our two hyperparameters: α and γ. We show below how this grid looks, and the code used to perform the hyperparameter grid search. The Figure below gives us an initial idea of what hyperparameter values return a smaller RMSE. Finally, we can use the Differential Evolution algorithm provided by Scipy to optimize the hyperparameters by minimizing the RMSE of our model. Scipy’s differential_evolution function needs as input: KRR_function. This is the function whose output (RMSE) will be minimized. It needs as input: i) tuple with hyperparameters to optimize (α and γ) and ii) X, y variables containing our data. Define boundaries of possible values of hyperparameters. Extra variables used by KRR_function. In our case, this will be given as a tuple containing X and y. Other relevant options for the Differential Evolution algorithm are : Strategy. In our case, the default strategy=’best1bin’ is good enough. With this strategy, the value of each parameter of the mutant vectors is obtained as a variation of the best vector’s value for that parameter, proportionally to the difference of two other random vectors.Population size. This selects how many vectors we will consider. A larger number will slow down progress but will make it more likely to discover the global minimum. Here, we use the default value of popsize=15.Mutation constant. This value controls how much the parameters change during the mutation stage. A larger value means a larger search radius but slows down convergence. We use the default value of mutation=0.5.Recombination constant. This constant controls how likely the parameters of trial vectors are to change during the recombination stage. Larger values mean that mutations are more likely to be accepted, which may accelerate convergence at the risk of causing population instability. We use the default value of recombination=0.7.Tolerance. This value controls when the algorithm is considered to converge. We will use tol=0.01, meaning that the algorithm is considered to be converged when the standard deviation of the RMSE of all vectors in the population is smaller than 1% of the average RMSE. Strategy. In our case, the default strategy=’best1bin’ is good enough. With this strategy, the value of each parameter of the mutant vectors is obtained as a variation of the best vector’s value for that parameter, proportionally to the difference of two other random vectors. Population size. This selects how many vectors we will consider. A larger number will slow down progress but will make it more likely to discover the global minimum. Here, we use the default value of popsize=15. Mutation constant. This value controls how much the parameters change during the mutation stage. A larger value means a larger search radius but slows down convergence. We use the default value of mutation=0.5. Recombination constant. This constant controls how likely the parameters of trial vectors are to change during the recombination stage. Larger values mean that mutations are more likely to be accepted, which may accelerate convergence at the risk of causing population instability. We use the default value of recombination=0.7. Tolerance. This value controls when the algorithm is considered to converge. We will use tol=0.01, meaning that the algorithm is considered to be converged when the standard deviation of the RMSE of all vectors in the population is smaller than 1% of the average RMSE. This code returns the converged hyperparameter values that result in the minimized RMSE: Converged hyperparameters: alpha= 0.347294, gamma= 3.342522Minimum rmse: 1.140462 We can uncomment the last line of the function KRR_function to print all intermediate values: alpha: 63.925979 . gamma: 19.290688 . rmse: 1.411122alpha: 59.527726 . gamma: 2.228886 . rmse: 1.421191alpha: 24.470318 . gamma: 3.838062 . rmse: 1.379171alpha: 61.944876 . gamma: 15.703799 . rmse: 1.407040alpha: 68.141245 . gamma: 0.847900 . rmse: 1.431469 [...]alpha: 0.347408 . gamma: 3.342461 . rmse: 1.140462alpha: 0.347294 . gamma: 3.342522 . rmse: 1.140462alpha: 0.347294 . gamma: 3.342522 . rmse: 1.140462alpha: 0.347294 . gamma: 3.342522 . rmse: 1.140462 We can take these configurations explored by the Differential Evolution algorithm, and plot them on top of our previous hyperparameter grid search: In addition to all the intermediate values explored, we also plotted in red the converged value. This way, we can observe how the algorithm has been exploring different configurations within the set boundaries and it has eventually converged into an (α,γ) combination that minimizes the RMSE. We have covered how to generate a simple two-dimensional dataset and how to fit it with a Kernel Ridge Regression. We have covered the basics of Differential Evolution and how to use this algorithm to optimize the hyperparameters of a Machine Learning model. Remember that the dataset presented here, codes, images, etc. are provided in this GitHub repository. If you are curious about more complex applications of genetic algorithms to optimize Machine Learning hyperparameters, feel free to check our recent work at the University of Liverpool, in collaboration with the Northeast Normal University. In this work, we used a Differential Evolution algorithm to optimize several Machine Learning models to predict the efficiency of organic solar cells. Was this article helpful to you? Let me know if you were able to successfully use a Differential Evolution algorithm to optimize the hyperparameters of your Machine Learning model!
[ { "code": null, "e": 342, "s": 172, "text": "Hyperparameter tuning is critical for the correct functioning of Machine Learning models. You can check Timo Böhm’s article to see an overview of hyperparameter tuning." }, { "code": null, "e": 454, "s": 342, "text": "Genetic algorithms provide a powerful technique for hyperparameter tuning, but they are quite often overlooked." }, { "code": null, "e": 687, "s": 454, "text": "In this article, I will show an overview of genetic algorithms. I will also offer a detailed step-by-step guide on exploiting available libraries to use genetic algorithms to optimize the hyperparameters of a Machine Learning model." }, { "code": null, "e": 802, "s": 687, "text": "Genetic algorithms make use of basic concepts from evolution by natural selection to optimize arbitrary functions." }, { "code": null, "e": 952, "s": 802, "text": "This short article will introduce Differential Evolution and teach how to exploit it to optimize the hyperparameters used in Kernel Ridge Regression." }, { "code": null, "e": 1150, "s": 952, "text": "I provide snippets of code to show how to use a Differential Evolution algorithm in Python. Complete codes and figures are also provided in a GitHub repository, so anyone can dive into the details." }, { "code": null, "e": 1364, "s": 1150, "text": "Genetic algorithms, such as Differential Evolution, make use of basic concepts from evolution by natural selection. In our case, we have a population formed by vectors that contain parameters with distinct values." }, { "code": null, "e": 1563, "s": 1364, "text": "Parameters are equivalent to genes in biological systems. Their exact value differs between different vectors. Different combinations of parameters cause vectors to display different fitness values." }, { "code": null, "e": 1681, "s": 1563, "text": "Random parameter mutations are introduced in the population, and vectors with a larger fitness outlive other vectors." }, { "code": null, "e": 1773, "s": 1681, "text": "Using an iterative process, Differential Evolution can minimize a function following steps:" }, { "code": null, "e": 1886, "s": 1773, "text": "1 — Initialization: create an initial population with NP vectors with random parameter values within boundaries." }, { "code": null, "e": 1955, "s": 1886, "text": "2 — Initial evaluation: calculate function value for the NP vectors." }, { "code": null, "e": 1994, "s": 1955, "text": "3 — For each vector in the population:" }, { "code": null, "e": 2517, "s": 1994, "text": "3.1 — Mutation: we build a mutant vector, where each parameter’s value is calculated as a mutation of the parameters of other vectors randomly chosen from the population. A common strategy to calculate this mutant vector is best1bin, where each parameter pi of the mutant vector is calculated as shown in the Equation below. The mutant parameter is a variation of the pi parameter of the best vector (vector with the lowest value) plus a mutation rate (F) times the pi-difference of two vectors randomly chosen, r1 and r2." }, { "code": null, "e": 2894, "s": 2517, "text": "3.2 — Recombination: a trial vector is created by selecting each of its parameters as either the value of the current vector or the value of the mutant vector. For each parameter, we generate a random uniform number R in the (0,1) interval. If R is lower than a recombination rate, then we accept the mutant parameter; otherwise, we use the parameter of the current parameter." }, { "code": null, "e": 3049, "s": 2894, "text": "3.3 — Replacement: evaluate the function of the trial vector. If it’s more stable than the current one, substitute the current vector by the trial vector." }, { "code": null, "e": 3336, "s": 3049, "text": "4 — Repeat Step 3 until population convergence: iteration stops when the standard deviation of the function within the population is smaller than a specific percentage of the mean value of the function. Loop also stops if convergence is not reached after a maximum number of iterations." }, { "code": null, "e": 3560, "s": 3336, "text": "All this process is already implemented in several libraries in the main programming languages. Here, we will be using Scipy’s implementation in Python, which lets us do everything we want by using just a few lines of code." }, { "code": null, "e": 3781, "s": 3560, "text": "As an example, we will use data that follows the two-dimensional function f(x1,x2)=sin(x1)+cos(x2), plus a small random variation in the interval (-2,2) to spice things up. Therefore, our data will follow the expression:" }, { "code": null, "e": 4020, "s": 3781, "text": "In the figure below, we show in grayscale the value of sin(x1)+cos(x2) as a reference. Then, we show colored points to indicate our 441 points (21x21 grid), calculated with the expression above in the interval x1:(-10,10) and x2:(-10,10)." }, { "code": null, "e": 4095, "s": 4020, "text": "We offer below a code snippet with the function used to generate our data:" }, { "code": null, "e": 4258, "s": 4095, "text": "Our goal is to use the data generated previously to train an ML model that will be able to predict the value of the function f(x1,x2) at different configurations." }, { "code": null, "e": 4613, "s": 4258, "text": "In this article, I will be using Kernel Ridge Regression (KRR). We will be using a radial basis function kernel for KRR, which depends on the Gaussian kernel variance γ. With KRR, we also need to optimize the regularization hyperparameter α. If you want more details on KRR and its implementation, feel free to check out my recent tutorial on this topic." }, { "code": null, "e": 4959, "s": 4613, "text": "Here we use a 10-fold cross-validation, where our data is split into a training set used to optimize the model, and a test set used to measure the model accuracy. As an accuracy metric, we will use the root-mean-square error (RMSE), which represents the average error between the f(x1,x2) values in the test set and those predicted by our model." }, { "code": null, "e": 5095, "s": 4959, "text": "As an optional first step, we can perform a grid-search to see how the RMSE changes with the value of our two hyperparameters: α and γ." }, { "code": null, "e": 5286, "s": 5095, "text": "We show below how this grid looks, and the code used to perform the hyperparameter grid search. The Figure below gives us an initial idea of what hyperparameter values return a smaller RMSE." }, { "code": null, "e": 5430, "s": 5286, "text": "Finally, we can use the Differential Evolution algorithm provided by Scipy to optimize the hyperparameters by minimizing the RMSE of our model." }, { "code": null, "e": 5486, "s": 5430, "text": "Scipy’s differential_evolution function needs as input:" }, { "code": null, "e": 5675, "s": 5486, "text": "KRR_function. This is the function whose output (RMSE) will be minimized. It needs as input: i) tuple with hyperparameters to optimize (α and γ) and ii) X, y variables containing our data." }, { "code": null, "e": 5732, "s": 5675, "text": "Define boundaries of possible values of hyperparameters." }, { "code": null, "e": 5833, "s": 5732, "text": "Extra variables used by KRR_function. In our case, this will be given as a tuple containing X and y." }, { "code": null, "e": 5903, "s": 5833, "text": "Other relevant options for the Differential Evolution algorithm are :" }, { "code": null, "e": 7197, "s": 5903, "text": "Strategy. In our case, the default strategy=’best1bin’ is good enough. With this strategy, the value of each parameter of the mutant vectors is obtained as a variation of the best vector’s value for that parameter, proportionally to the difference of two other random vectors.Population size. This selects how many vectors we will consider. A larger number will slow down progress but will make it more likely to discover the global minimum. Here, we use the default value of popsize=15.Mutation constant. This value controls how much the parameters change during the mutation stage. A larger value means a larger search radius but slows down convergence. We use the default value of mutation=0.5.Recombination constant. This constant controls how likely the parameters of trial vectors are to change during the recombination stage. Larger values mean that mutations are more likely to be accepted, which may accelerate convergence at the risk of causing population instability. We use the default value of recombination=0.7.Tolerance. This value controls when the algorithm is considered to converge. We will use tol=0.01, meaning that the algorithm is considered to be converged when the standard deviation of the RMSE of all vectors in the population is smaller than 1% of the average RMSE." }, { "code": null, "e": 7474, "s": 7197, "text": "Strategy. In our case, the default strategy=’best1bin’ is good enough. With this strategy, the value of each parameter of the mutant vectors is obtained as a variation of the best vector’s value for that parameter, proportionally to the difference of two other random vectors." }, { "code": null, "e": 7686, "s": 7474, "text": "Population size. This selects how many vectors we will consider. A larger number will slow down progress but will make it more likely to discover the global minimum. Here, we use the default value of popsize=15." }, { "code": null, "e": 7897, "s": 7686, "text": "Mutation constant. This value controls how much the parameters change during the mutation stage. A larger value means a larger search radius but slows down convergence. We use the default value of mutation=0.5." }, { "code": null, "e": 8226, "s": 7897, "text": "Recombination constant. This constant controls how likely the parameters of trial vectors are to change during the recombination stage. Larger values mean that mutations are more likely to be accepted, which may accelerate convergence at the risk of causing population instability. We use the default value of recombination=0.7." }, { "code": null, "e": 8495, "s": 8226, "text": "Tolerance. This value controls when the algorithm is considered to converge. We will use tol=0.01, meaning that the algorithm is considered to be converged when the standard deviation of the RMSE of all vectors in the population is smaller than 1% of the average RMSE." }, { "code": null, "e": 8584, "s": 8495, "text": "This code returns the converged hyperparameter values that result in the minimized RMSE:" }, { "code": null, "e": 8666, "s": 8584, "text": "Converged hyperparameters: alpha= 0.347294, gamma= 3.342522Minimum rmse: 1.140462" }, { "code": null, "e": 8760, "s": 8666, "text": "We can uncomment the last line of the function KRR_function to print all intermediate values:" }, { "code": null, "e": 9258, "s": 8760, "text": "alpha: 63.925979 . gamma: 19.290688 . rmse: 1.411122alpha: 59.527726 . gamma: 2.228886 . rmse: 1.421191alpha: 24.470318 . gamma: 3.838062 . rmse: 1.379171alpha: 61.944876 . gamma: 15.703799 . rmse: 1.407040alpha: 68.141245 . gamma: 0.847900 . rmse: 1.431469 [...]alpha: 0.347408 . gamma: 3.342461 . rmse: 1.140462alpha: 0.347294 . gamma: 3.342522 . rmse: 1.140462alpha: 0.347294 . gamma: 3.342522 . rmse: 1.140462alpha: 0.347294 . gamma: 3.342522 . rmse: 1.140462" }, { "code": null, "e": 9406, "s": 9258, "text": "We can take these configurations explored by the Differential Evolution algorithm, and plot them on top of our previous hyperparameter grid search:" }, { "code": null, "e": 9699, "s": 9406, "text": "In addition to all the intermediate values explored, we also plotted in red the converged value. This way, we can observe how the algorithm has been exploring different configurations within the set boundaries and it has eventually converged into an (α,γ) combination that minimizes the RMSE." }, { "code": null, "e": 9958, "s": 9699, "text": "We have covered how to generate a simple two-dimensional dataset and how to fit it with a Kernel Ridge Regression. We have covered the basics of Differential Evolution and how to use this algorithm to optimize the hyperparameters of a Machine Learning model." }, { "code": null, "e": 10060, "s": 9958, "text": "Remember that the dataset presented here, codes, images, etc. are provided in this GitHub repository." }, { "code": null, "e": 10452, "s": 10060, "text": "If you are curious about more complex applications of genetic algorithms to optimize Machine Learning hyperparameters, feel free to check our recent work at the University of Liverpool, in collaboration with the Northeast Normal University. In this work, we used a Differential Evolution algorithm to optimize several Machine Learning models to predict the efficiency of organic solar cells." } ]
SQL GROUP BY Statement
The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country". The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns. Below is a selection from the "Customers" table in the Northwind sample database: The following SQL statement lists the number of customers in each country: The following SQL statement lists the number of customers in each country, sorted high to low: Below is a selection from the "Orders" table in the Northwind sample database: And a selection from the "Shippers" table: The following SQL statement lists the number of orders sent by each shipper: List the number of customers in each country. SELECT (CustomerID), Country FROM Customers ; 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": 134, "s": 0, "text": "The GROUP BY statement groups rows that have the same values into summary \nrows, like \"find the number of customers in each country\"." }, { "code": null, "e": 285, "s": 134, "text": "The GROUP BY statement is often used with aggregate functions (COUNT(), \nMAX(), \nMIN(), SUM(), \nAVG()) to group the result-set by one or more columns." }, { "code": null, "e": 368, "s": 285, "text": "Below is a selection from the \"Customers\" table in the Northwind sample \ndatabase:" }, { "code": null, "e": 443, "s": 368, "text": "The following SQL statement lists the number of customers in each country:" }, { "code": null, "e": 539, "s": 443, "text": "The following SQL statement lists the number of customers in each country, \nsorted high to low:" }, { "code": null, "e": 618, "s": 539, "text": "Below is a selection from the \"Orders\" table in the Northwind sample database:" }, { "code": null, "e": 661, "s": 618, "text": "And a selection from the \"Shippers\" table:" }, { "code": null, "e": 738, "s": 661, "text": "The following SQL statement lists the number of orders sent by each shipper:" }, { "code": null, "e": 784, "s": 738, "text": "List the number of customers in each country." }, { "code": null, "e": 831, "s": 784, "text": "SELECT (CustomerID),\nCountry\nFROM Customers\n;\n" }, { "code": null, "e": 850, "s": 831, "text": "Start the Exercise" }, { "code": null, "e": 883, "s": 850, "text": "We just launchedW3Schools videos" }, { "code": null, "e": 925, "s": 883, "text": "Get certifiedby completinga course today!" }, { "code": null, "e": 1032, "s": 925, "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": 1051, "s": 1032, "text": "[email protected]" } ]
Learning from Audio: Spectrograms | by mlearnere | Towards Data Science
When it comes to Machine Learning, or even Deep Learning, how the data is processed is fundamental to the model’s training and testing performance. When working in the domain of audio, there are a few steps to understand before getting to this stage, but once you get there, learning from audio becomes a quite easy task. Make sure to understand the concepts linked below before going through this article. Learning from Audio: Wave Forms Learning from Audio: Time Domain Features Learning from Audio: Fourier Transformation Learning from Audio: The Mel Scale, Mel Spectrograms, and Mel Frequency Cepstral Coefficients Learning from Audio: Pitch and Chromagrams In this article I aim to break down what exactly a spectrogram is, how it is used in the field Machine Learning, and how you can use them for whatever problem you are attempting to solve. As always, if you would like to view the code, as well as the files needed to follow along, you can find everything on my GitHub. You can think of spectrograms as pictures of audio. Kind of weird, I know, but you should strengthen this intuition as much as you can. The spec portion in spectrogram comes from spectrum and the color-bar you see on the right of the figure is just that. What is the spectrum of? The frequencies in which the audio has. With all of this information in mind, let me formalize the definition. A spectrogram is a figure which represents the spectrum of frequencies of a recorded audio over time. This means that as we get brighter in color in the figure, the sound is heavily concentrated around those specific frequencies, and as we get darker in color, the sound is close to empty/dead sound. This allows us to get a good understanding of the shape and structure of the audio without even listening to it! This is where the power of spectrograms come into play for various ML/DL models. Now a question arises, how do we calculate the spectrograms? The answer to this question is much simpler than expected. Split the audio into overlapping chunks, or windows. Perform the Short Time Fourier Transformation on each window. Remember to take its absolute value! Each resulting window has a vertical line representing the magnitude vs frequency. Take the resulting window and convert to decibels. This gives us a rich image of the sound’s structure. Finally, we lay out these windows back into the length of the original song and display the output. Now that we have a decent understanding of what spectrograms are exactly, let’s learn how to retrieve them from sounds in Python! Using functions in librosa, we can have this be done for us with little to no effort. First, let’s import the needed packages and load in the audio. Second, I am going to define two functions; one that will perform all the necessary steps and output the processed signal, and another that will plot the spectrogram. Make sure to read through the comments and lines to understand the process in which this is done. Now, with our functions defined, we can simply use plot_spec to graph the results! plot_spec(to_decibles(guitar), sr, 'Guitar') plot_spec(to_decibles(kick), sr, 'Kick') plot_spec(to_decibles(snare), sr, 'Snare') By now, you should be able to understand how spectrograms are created using the Short Time Fourier Transformation, as well as how to create them in Python. These representations of audio allow for various Deep Learning architectures to extract features much easier than wave form and even Fourier representations. Stay tuned for even more spectrogram representations of audio. Thank you for reading.
[ { "code": null, "e": 579, "s": 172, "text": "When it comes to Machine Learning, or even Deep Learning, how the data is processed is fundamental to the model’s training and testing performance. When working in the domain of audio, there are a few steps to understand before getting to this stage, but once you get there, learning from audio becomes a quite easy task. Make sure to understand the concepts linked below before going through this article." }, { "code": null, "e": 611, "s": 579, "text": "Learning from Audio: Wave Forms" }, { "code": null, "e": 653, "s": 611, "text": "Learning from Audio: Time Domain Features" }, { "code": null, "e": 697, "s": 653, "text": "Learning from Audio: Fourier Transformation" }, { "code": null, "e": 791, "s": 697, "text": "Learning from Audio: The Mel Scale, Mel Spectrograms, and Mel Frequency Cepstral Coefficients" }, { "code": null, "e": 834, "s": 791, "text": "Learning from Audio: Pitch and Chromagrams" }, { "code": null, "e": 1022, "s": 834, "text": "In this article I aim to break down what exactly a spectrogram is, how it is used in the field Machine Learning, and how you can use them for whatever problem you are attempting to solve." }, { "code": null, "e": 1152, "s": 1022, "text": "As always, if you would like to view the code, as well as the files needed to follow along, you can find everything on my GitHub." }, { "code": null, "e": 1472, "s": 1152, "text": "You can think of spectrograms as pictures of audio. Kind of weird, I know, but you should strengthen this intuition as much as you can. The spec portion in spectrogram comes from spectrum and the color-bar you see on the right of the figure is just that. What is the spectrum of? The frequencies in which the audio has." }, { "code": null, "e": 1543, "s": 1472, "text": "With all of this information in mind, let me formalize the definition." }, { "code": null, "e": 1645, "s": 1543, "text": "A spectrogram is a figure which represents the spectrum of frequencies of a recorded audio over time." }, { "code": null, "e": 2038, "s": 1645, "text": "This means that as we get brighter in color in the figure, the sound is heavily concentrated around those specific frequencies, and as we get darker in color, the sound is close to empty/dead sound. This allows us to get a good understanding of the shape and structure of the audio without even listening to it! This is where the power of spectrograms come into play for various ML/DL models." }, { "code": null, "e": 2158, "s": 2038, "text": "Now a question arises, how do we calculate the spectrograms? The answer to this question is much simpler than expected." }, { "code": null, "e": 2211, "s": 2158, "text": "Split the audio into overlapping chunks, or windows." }, { "code": null, "e": 2310, "s": 2211, "text": "Perform the Short Time Fourier Transformation on each window. Remember to take its absolute value!" }, { "code": null, "e": 2393, "s": 2310, "text": "Each resulting window has a vertical line representing the magnitude vs frequency." }, { "code": null, "e": 2497, "s": 2393, "text": "Take the resulting window and convert to decibels. This gives us a rich image of the sound’s structure." }, { "code": null, "e": 2597, "s": 2497, "text": "Finally, we lay out these windows back into the length of the original song and display the output." }, { "code": null, "e": 2813, "s": 2597, "text": "Now that we have a decent understanding of what spectrograms are exactly, let’s learn how to retrieve them from sounds in Python! Using functions in librosa, we can have this be done for us with little to no effort." }, { "code": null, "e": 2876, "s": 2813, "text": "First, let’s import the needed packages and load in the audio." }, { "code": null, "e": 3141, "s": 2876, "text": "Second, I am going to define two functions; one that will perform all the necessary steps and output the processed signal, and another that will plot the spectrogram. Make sure to read through the comments and lines to understand the process in which this is done." }, { "code": null, "e": 3224, "s": 3141, "text": "Now, with our functions defined, we can simply use plot_spec to graph the results!" }, { "code": null, "e": 3269, "s": 3224, "text": "plot_spec(to_decibles(guitar), sr, 'Guitar')" }, { "code": null, "e": 3310, "s": 3269, "text": "plot_spec(to_decibles(kick), sr, 'Kick')" }, { "code": null, "e": 3353, "s": 3310, "text": "plot_spec(to_decibles(snare), sr, 'Snare')" }, { "code": null, "e": 3667, "s": 3353, "text": "By now, you should be able to understand how spectrograms are created using the Short Time Fourier Transformation, as well as how to create them in Python. These representations of audio allow for various Deep Learning architectures to extract features much easier than wave form and even Fourier representations." }, { "code": null, "e": 3730, "s": 3667, "text": "Stay tuned for even more spectrogram representations of audio." } ]
Named arguments in JavaScript.
Following is the code for using named arguments in JavaScript functions − Live Demo <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> body { font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif; } .sample,.result { font-size: 18px; font-weight: 500; color: red; } .result { color: rebeccapurple; } </style> </head> <body> <h1>Named arguments in JavaScript functions</h1> <div class="sample"></div> <div class="result"></div> <button class="Btn">CLICK HERE</button> <h3> Click on the above button to call a function and pass above object to it as argument </h3> <script> let sampleEle = document.querySelector(".sample"); let resultEle = document.querySelector(".result"); sampleEle.innerHTML = "{a:22,b:44,c:55,d:99}"; function add({ a = 0, b = 0, c = 0, d = 0 }) { return a + b + c + d; } document.querySelector(".Btn").addEventListener("click", () => { resultEle.innerHTML += "Sum = " + add({ a: 22, b: 44, c: 55, d: 99 }); }); </script> </body> </html> The above code will produce the following output − On clicking the ‘CLICK HERE’ button −
[ { "code": null, "e": 1136, "s": 1062, "text": "Following is the code for using named arguments in JavaScript functions −" }, { "code": null, "e": 1147, "s": 1136, "text": " Live Demo" }, { "code": null, "e": 2228, "s": 1147, "text": "<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n<meta charset=\"UTF-8\" />\n<meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" />\n<title>Document</title>\n<style>\n body {\n font-family: \"Segoe UI\", Tahoma, Geneva, Verdana, sans-serif;\n }\n .sample,.result {\n font-size: 18px;\n font-weight: 500;\n color: red;\n }\n .result {\n color: rebeccapurple;\n }\n</style>\n</head>\n<body>\n<h1>Named arguments in JavaScript functions</h1>\n<div class=\"sample\"></div>\n<div class=\"result\"></div>\n<button class=\"Btn\">CLICK HERE</button>\n<h3>\nClick on the above button to call a function and pass above object to it\nas argument\n</h3>\n<script>\n let sampleEle = document.querySelector(\".sample\");\n let resultEle = document.querySelector(\".result\");\n sampleEle.innerHTML = \"{a:22,b:44,c:55,d:99}\";\n function add({ a = 0, b = 0, c = 0, d = 0 }) {\n return a + b + c + d;\n }\n document.querySelector(\".Btn\").addEventListener(\"click\", () => {\n resultEle.innerHTML += \"Sum = \" + add({ a: 22, b: 44, c: 55, d: 99 });\n });\n</script>\n</body>\n</html>" }, { "code": null, "e": 2279, "s": 2228, "text": "The above code will produce the following output −" }, { "code": null, "e": 2317, "s": 2279, "text": "On clicking the ‘CLICK HERE’ button −" } ]
Generative Adversarial Networks GANs: A Beginner’s Guide | by Mohammed Alhamid | Towards Data Science
The hypothetical example of Machine Learning is imagined around having a machine that is able to think and mimic passing a test with some degree of intelligent. Although this the ultimate goal, we are not there yet, and we still have a long way to go. In the past few years, many models have been developed to learn in an unsupervised mode attempting to engage in a competitive settings against another computer or human to perform a certain task. This article shed some light on the use of Generative Adversarial Networks (GANs) and how they can be used in today’s world. Machine Learning has shown some power to recognize patterns such as data distribution, images, and sequence of events to solve classification and regression problems. Ian Goodfellow et al. in 2014 [1] published an article using two separate neural networks to generate synthetic data that has similar properties as the real ones. This work has made the research community more interested in generating realistic images, videos, and generic synthetic structural data. GANs are unsupervised deep learning techniques. Usually, it is implemented using two neural networks: Generator and Discriminator. These two models compete with each other in a form of a game setting. The GAN model would be trained on real data and data generated by the generator. The discriminator’s job is to determine fake from real data. The generator is a learning model, so initially, it is likely to produce low or even completely noisy data that does not reflect the real distribution or the properties of the real data. The generator model’s primary goal is generating artificial data that can pass the discriminator successfully. The model starts taking some noise, usually Gaussian noise and produces an image formatted as a vector of pixels. The generator must learn how to trick the discriminator and win a positive classification (produced image classified as real). The generation step’s loss is computed whenever any of those generated images detected successfully as “fake”. The discriminator has to learn how to identify those fake images progressively. Negative loss is given to the discriminator whenever the model fails to recognize a fake image. The key concept is the simultaneous training of the generator and the discriminator at the same time. The research community has many interesting datasets to measure the accuracy of a GAN model. In this article, we would use a few of those datasets in details, starting with MNIST. MNIST is one of the most significant examples of explaining the generative models’ theory used widely for image processing. A sample from the MNIST dataset is shown in Figure 2. To generate artificial handwritten images, we need to implement two models: one to generate fake images and another to classify fake from real ones. The overall pipleline of training a GAN model is shown in Figure 3. There are many architectures to consider for building the discriminator and the generator. We could build a deep neural network or Convolutional Neural Network (CNN) and some other options. We will go over the types of GAN models shortly, but first, let’s pick CNN for now. The source code of this example is available on my Github. The discriminator model architecture start by recieving an image (28 x 28 x 1) and pass it through two convolutional layers with 64 filters in each. Alternatively, we could use 128 filters, which represents the number of hidden nodes in each layer. We can make the neural network architecture denser by using three layers with 64, 128, and 256 hidden nodes. To simplify how GAN networks work, we will use simple architecture in this tutorial, which still gives high accuracy. Figure 4 shows the overall architecture of the discriminator. The generator model learns how to generate realistic images, but it needs to start from some random points in the latent space. If you compare the generator architecture in Figure 5 with the discriminator architecture in Figure 4, you would realize they look almost identical. It is essential to know that it is not necessary to flip the discrinmiator when building the generator network. The generator’s architecture can have a different number of layers, filters, and higher overall complexity. Another main difference between the discriminator and the generator is the use of an activation function. The discrminator uses a sigmoid in the output layer. It is a boolean classification problem, and this will ensure the output would be either 0 or 1. The generator, on the other hand, has no loss function or any optimization algorithm to be used. It uses transpose convolution layers to upsample the low-resolution dense layer from the latent space to build a higher resolution images. The trick when building the generator model is that we don’t need to compile it. The GAN model now would combine the full framework, which combines the generator, the discriminator, and compile the model. We will discuss those aspects in detail in the following section. def building_gan(generator, discriminator): GAN = Sequential() discriminator.trainable = False # Adding the generator and the discriminator GAN.add(generator) GAN.add(discriminator) # Optimization function opt = tf.keras.optimizers.Adam(lr=2e-4, beta_1=0.5) # Compile the model GAN.compile(loss='binary_crossentropy', optimizer=opt) return GAN The next animation shows how the generator is improving in each set of epochs during the training: (false trainable) One of the critical issues is approximating the quality of the generated data, whether it is an image, a text, or a song, and the diversity of those produced articles. The discriminator helps us to check whether the generated data is real or fake. However, the generated samples might look realistic from the discriminator point of view, but might be too obvious for the human eyes to notice. Hence, we need evaluation metrics that correlate with subjective evaluation. One way to look into this problem is by analyzing the distribution properties between the real and generated data. Two evaluation metrics can statistically help measure the quality of the generated data: Inception Score [3] and Frechet Inception [4]. Both fo these objective metrics are widely adopted by the research community, especially for measuring the quality of produced images. Since this tutorial is an introduction, we will not detail how these metrics work. As we discussed earlier, the GAN model has a unique property of simultaneously training the generator and the discriminator at the same time. This requires loss functions that balance the training on one side (discriminator) while also improving the training on the other side of (generator). When building the discriminator model, we explicitly define the loss function just like any other neural network architecture. # Defining the discriminator model def building_discriminator(): # The image dimensions provided as inputs image_shape = (28, 28, 1) disModel = Sequential() disModel.add(Conv2D(64, 3, strides=2, input_shape=image_shape)) disModel.add(LeakyReLU()) disModel.add(Dropout(0.4)) # Second layer disModel.add(Conv2D(64, 3, strides=2)) disModel.add(LeakyReLU()) disModel.add(Dropout(0.4)) # Flatten the output disModel.add(Flatten()) disModel.add(Dense(1, activation='sigmoid')) # Optimization function opt = tf.keras.optimizers.Adam(lr=2e-4, beta_1=0.5) # Compile the model disModel.compile(loss='binary_crossentropy', optimizer=opt, metrics = ['accuracy']) return disModel The generator model, on the other hand, does not have the loss function explicitly defined. It is based on the training of the discriminator and the generator updated according to its loss function. # Defining the generator model def building_generator(noise_dim): genModel = Sequential() genModel.add(Dense(128 * 6 * 6, input_dim=noise_dim)) genModel.add(LeakyReLU()) genModel.add(Reshape((6,6,128))) # Second layer genModel.add(Conv2DTranspose(128, (4,4), strides=(2,2))) genModel.add(LeakyReLU()) # Third layer genModel.add(Conv2DTranspose(128, (4,4), strides=(2,2))) genModel.add(LeakyReLU()) genModel.add(Conv2D(1, (3,3), activation='sigmoid')) return genModel There are few options for choosing the loss functions, such as: Least squares. Wasserstein loss function. One of the key issues associated with GAN models is the determination of when the model is converged. The competition between the discriminator and generator makes the game hard to reach a final winner. Both models are optimally want to maximize their gain and minimizes their loss. In our situation, we want both models to reach the point where they almost make a complete guess whether an image is fake or real and whether the generated image will pass the discriminator successfully. The 50–50 chance is the perfect ideal case inherited from the game theory, where both models are good hard to win over. GAN models are known to have the problem of slow convergence. Similar to other unsupervised models, the absence of true labels increase the challenge for determining when the training can stop. We need to make sure to balance between the training time and the produced quality. Several factors contribute to slow or speed up the training process, such as normalization of inputs, batch normalization, gradient penalties, and training the discriminator well before training the GAN model. GAN models are known to have a limited capabilities when it comes to the size of the generated images. The images size that we have seen in the MNIST examples are only 28 x 28 pixels. These are pretty small images to use in a real application. If we want to generate a bigger images, let us say 1024 x 1024, we will need a more scalable model. The research community has been interested in improving GAN capabilities. For instance, in 2017, T Karras et al. propose a novel model called Progressive Growing GANs to solve such problem [2]. Some of the challenges introduced in the previous sections made the research community expand the GAN models’ idea to tackle one or more of the issues mentioned above. This section covers some popular extensions and optimized GAN architectures to scale up the original GAN capabilities. Deep Convolutional GAN (DCGAN): This an extension to replace the feed forward neural network with a CNN architecture proposed by A. Radford et al. [5]. The idea of using a CNN architecture and learning through filters have improved the accuracy of GAN models. Wasserstein GAN (WGAN): WGAN is designed by M. Arjovsky et al. [6]. WGAN focuses on defining the distance between the generated distribution and the real distribution, which determines the model’s convergence. They propose the use of Earth Mover (EM) distance to approximate the differences between those distributions effectively. Progressive GAN: ProgressiveGAN is designed by T. Karras et al. [7] and presented at ICLR conference. This work bough high contributions to the generator and discriminator to grow progressively from lower-resolution to higher-resolution layers. The technique requires reducing the size of the mini-batches while computing the mini-batch standard deviation. ProgressiveGan also uses equalized learning rate, and pixel-wise feature normalization. The research has evolved from previous types to introduce semi-supervised learning models. Instead of having the discriminator classify whether a given image is real or fake, the model can be turned into a multiclass classifier. For instance, in MNIST, we have ten classes that represent the ten handwritten digits. The discriminator would have ten plus one class, where the additional class represents the fake images to classify. In this situation, the discriminator is learning not only fake from real images but also classifying each real image to its corresponding class. This would stretch the objective function with two kinds of losses (Softmax and Sigmoid) to make the discriminator more efficient into classifying images correctly ( see Figure 7). The remaining types from our list (cGAN, CycleGAN) introduce similar new objectives. Conditional GAN (cGAN): cGAN was published in 2014 by M. Mehdi and S. Osindero [8]. It supports the idea of having labels for each image and the generator learns how to generate realistic images for each label. The discriminator learns to distinguish the fake images while also making sure they carry the correct labels. If we apply the cGAN on the learning framework on Figure 3, would need to make the following changes: Pix2pix: The Pix2pix model applies a special case of conditional GAN models’ concepts by considering the translation of images to another set of images. P. Isola et al. [9] proposed this idea in 2017. The labels and the produced outputs are sets of pairs of images. Like translating a portion of textual contents, we can translate an image to another image with certain properties (see Figure 9). Later, the research community proposes a more efficient approach like Cycle GAN as we will discuss next. Cycle GAN: The unique idea of Cycle GAN is the use of multiple generators and discriminators instead of one-to-one architecture. Pix2pix let the model learns from a pair of images. That condition was relaxed later by a proposal from J-Y. Zhu et al. [10]. The novelity of thier idea comes to a create accyle where the generated translation is looped back again to produce the original image. If there any loss during the translation, the difference is what we need to optimize. Two generators and discriminators can be used to translate input to “domain A” and then translate to “domain B”. This structured is referred to in the paper as forward-backward consistency (back translation and reconsiliation). The two discriminators examine the generated output for both domains. This concenpt is very similar to the basic idea of auto-encoders. Auto-encoders are composed of two parts: encoders and decoders. These models are out of this article’s scope as they represent a separate category of learners using a single model. Auto-encoders constructs the inputs in a compressed encoded format. The decoders, then, reconstruct the input from the generated compressed form. We have discussed how to build a GAN model using pretty small images from the MNIST dataset. The image size is only 128 x 128 pixels. As discussed earlier, the Progressive GAN models can grow from low-resolution layers to high-resolution layers, making it possible to scale up the model outputs. We will see in the following example how to go from 64 x 64 pixels to generate 1024 x 1024 pixels. The model is designed on two main concepts: fade-in and fine-tuning. The model goes from simple resolution 4 x 4 and progress towards higher resolution. it provides the ability to grow after training each layer and we would be able to monitor the output as we train progressively (as shown in Figure 10). The alpha parmeter is scaled to have values between 0 and 1. It determines whether we should use previous trained layers or the scaling up. The discriminator This article gives a brief overview of how amazing the GAN models are. We have just touched some basics understanding of how GAN models work. I will later expand on some related topics in separate threads. However, if you are curious to learn more, I recommend two places to go from here: “GANs in Action” by Jakub Langr and Vladimir Bok is a great book that teaches how to build GAN models and cover in details the aspects introduced in this blog. “The-gan-zoo” is a Github repository that tracks all the recent research artciles published in this field. You can go from this repo to visit your paper of interest and navigate to other list of interesting work. [1] Goodfellow, Ian, et al. “Generative adversarial nets.” Advances in neural information processing systems. 2014. [2] Karras, Tero, et al. “Progressive growing of gans for improved quality, stability, and variation.” arXiv preprint arXiv:1710.10196. 2017. [3] Salimans, Tim, et al. “Improved techniques for training gans.” Advances in neural information processing systems. 2016. [4] Heusel, Martin, et al. “Gans trained by a two time-scale update rule converge to a local nash equilibrium.” Advances in neural information processing systems. 2017. [5] Radford, Alec, Luke Metz, and Soumith Chintala. “Unsupervised representation learning with deep convolutional generative adversarial networks.” arXiv preprint arXiv:1511.06434 (2015). [6] Arjovsky, Martin, Soumith Chintala, and Léon Bottou. “Wasserstein gan.” arXiv preprint arXiv:1701.07875 (2017). [7] Karras, Tero, et al. “Progressive growing of gans for improved quality, stability, and variation.” arXiv preprint arXiv:1710.10196 (2017). [8] Mirza, Mehdi, and Simon Osindero. “Conditional generative adversarial nets.” arXiv preprint arXiv:1411.1784 (2014). [9] Isola, Phillip, et al. “Image-to-image translation with conditional adversarial networks.” Proceedings of the IEEE conference on computer vision and pattern recognition. 2017. [10] Zhu, Jun-Yan, et al. “Unpaired image-to-image translation using cycle-consistent adversarial networks.” Proceedings of the IEEE international conference on computer vision. 2017.
[ { "code": null, "e": 745, "s": 172, "text": "The hypothetical example of Machine Learning is imagined around having a machine that is able to think and mimic passing a test with some degree of intelligent. Although this the ultimate goal, we are not there yet, and we still have a long way to go. In the past few years, many models have been developed to learn in an unsupervised mode attempting to engage in a competitive settings against another computer or human to perform a certain task. This article shed some light on the use of Generative Adversarial Networks (GANs) and how they can be used in today’s world." }, { "code": null, "e": 1212, "s": 745, "text": "Machine Learning has shown some power to recognize patterns such as data distribution, images, and sequence of events to solve classification and regression problems. Ian Goodfellow et al. in 2014 [1] published an article using two separate neural networks to generate synthetic data that has similar properties as the real ones. This work has made the research community more interested in generating realistic images, videos, and generic synthetic structural data." }, { "code": null, "e": 1742, "s": 1212, "text": "GANs are unsupervised deep learning techniques. Usually, it is implemented using two neural networks: Generator and Discriminator. These two models compete with each other in a form of a game setting. The GAN model would be trained on real data and data generated by the generator. The discriminator’s job is to determine fake from real data. The generator is a learning model, so initially, it is likely to produce low or even completely noisy data that does not reflect the real distribution or the properties of the real data." }, { "code": null, "e": 2483, "s": 1742, "text": "The generator model’s primary goal is generating artificial data that can pass the discriminator successfully. The model starts taking some noise, usually Gaussian noise and produces an image formatted as a vector of pixels. The generator must learn how to trick the discriminator and win a positive classification (produced image classified as real). The generation step’s loss is computed whenever any of those generated images detected successfully as “fake”. The discriminator has to learn how to identify those fake images progressively. Negative loss is given to the discriminator whenever the model fails to recognize a fake image. The key concept is the simultaneous training of the generator and the discriminator at the same time." }, { "code": null, "e": 2841, "s": 2483, "text": "The research community has many interesting datasets to measure the accuracy of a GAN model. In this article, we would use a few of those datasets in details, starting with MNIST. MNIST is one of the most significant examples of explaining the generative models’ theory used widely for image processing. A sample from the MNIST dataset is shown in Figure 2." }, { "code": null, "e": 3058, "s": 2841, "text": "To generate artificial handwritten images, we need to implement two models: one to generate fake images and another to classify fake from real ones. The overall pipleline of training a GAN model is shown in Figure 3." }, { "code": null, "e": 3332, "s": 3058, "text": "There are many architectures to consider for building the discriminator and the generator. We could build a deep neural network or Convolutional Neural Network (CNN) and some other options. We will go over the types of GAN models shortly, but first, let’s pick CNN for now." }, { "code": null, "e": 3391, "s": 3332, "text": "The source code of this example is available on my Github." }, { "code": null, "e": 3929, "s": 3391, "text": "The discriminator model architecture start by recieving an image (28 x 28 x 1) and pass it through two convolutional layers with 64 filters in each. Alternatively, we could use 128 filters, which represents the number of hidden nodes in each layer. We can make the neural network architecture denser by using three layers with 64, 128, and 256 hidden nodes. To simplify how GAN networks work, we will use simple architecture in this tutorial, which still gives high accuracy. Figure 4 shows the overall architecture of the discriminator." }, { "code": null, "e": 4426, "s": 3929, "text": "The generator model learns how to generate realistic images, but it needs to start from some random points in the latent space. If you compare the generator architecture in Figure 5 with the discriminator architecture in Figure 4, you would realize they look almost identical. It is essential to know that it is not necessary to flip the discrinmiator when building the generator network. The generator’s architecture can have a different number of layers, filters, and higher overall complexity." }, { "code": null, "e": 5188, "s": 4426, "text": "Another main difference between the discriminator and the generator is the use of an activation function. The discrminator uses a sigmoid in the output layer. It is a boolean classification problem, and this will ensure the output would be either 0 or 1. The generator, on the other hand, has no loss function or any optimization algorithm to be used. It uses transpose convolution layers to upsample the low-resolution dense layer from the latent space to build a higher resolution images. The trick when building the generator model is that we don’t need to compile it. The GAN model now would combine the full framework, which combines the generator, the discriminator, and compile the model. We will discuss those aspects in detail in the following section." }, { "code": null, "e": 5563, "s": 5188, "text": "def building_gan(generator, discriminator): GAN = Sequential() discriminator.trainable = False # Adding the generator and the discriminator GAN.add(generator) GAN.add(discriminator) # Optimization function opt = tf.keras.optimizers.Adam(lr=2e-4, beta_1=0.5) # Compile the model GAN.compile(loss='binary_crossentropy', optimizer=opt) return GAN" }, { "code": null, "e": 5662, "s": 5563, "text": "The next animation shows how the generator is improving in each set of epochs during the training:" }, { "code": null, "e": 5680, "s": 5662, "text": "(false trainable)" }, { "code": null, "e": 6265, "s": 5680, "text": "One of the critical issues is approximating the quality of the generated data, whether it is an image, a text, or a song, and the diversity of those produced articles. The discriminator helps us to check whether the generated data is real or fake. However, the generated samples might look realistic from the discriminator point of view, but might be too obvious for the human eyes to notice. Hence, we need evaluation metrics that correlate with subjective evaluation. One way to look into this problem is by analyzing the distribution properties between the real and generated data." }, { "code": null, "e": 6619, "s": 6265, "text": "Two evaluation metrics can statistically help measure the quality of the generated data: Inception Score [3] and Frechet Inception [4]. Both fo these objective metrics are widely adopted by the research community, especially for measuring the quality of produced images. Since this tutorial is an introduction, we will not detail how these metrics work." }, { "code": null, "e": 7039, "s": 6619, "text": "As we discussed earlier, the GAN model has a unique property of simultaneously training the generator and the discriminator at the same time. This requires loss functions that balance the training on one side (discriminator) while also improving the training on the other side of (generator). When building the discriminator model, we explicitly define the loss function just like any other neural network architecture." }, { "code": null, "e": 7762, "s": 7039, "text": "# Defining the discriminator model def building_discriminator(): # The image dimensions provided as inputs image_shape = (28, 28, 1) disModel = Sequential() disModel.add(Conv2D(64, 3, strides=2, input_shape=image_shape)) disModel.add(LeakyReLU()) disModel.add(Dropout(0.4)) # Second layer disModel.add(Conv2D(64, 3, strides=2)) disModel.add(LeakyReLU()) disModel.add(Dropout(0.4)) # Flatten the output disModel.add(Flatten()) disModel.add(Dense(1, activation='sigmoid')) # Optimization function opt = tf.keras.optimizers.Adam(lr=2e-4, beta_1=0.5) # Compile the model disModel.compile(loss='binary_crossentropy', optimizer=opt, metrics = ['accuracy']) return disModel" }, { "code": null, "e": 7961, "s": 7762, "text": "The generator model, on the other hand, does not have the loss function explicitly defined. It is based on the training of the discriminator and the generator updated according to its loss function." }, { "code": null, "e": 8464, "s": 7961, "text": "# Defining the generator model def building_generator(noise_dim): genModel = Sequential() genModel.add(Dense(128 * 6 * 6, input_dim=noise_dim)) genModel.add(LeakyReLU()) genModel.add(Reshape((6,6,128))) # Second layer genModel.add(Conv2DTranspose(128, (4,4), strides=(2,2))) genModel.add(LeakyReLU()) # Third layer genModel.add(Conv2DTranspose(128, (4,4), strides=(2,2))) genModel.add(LeakyReLU()) genModel.add(Conv2D(1, (3,3), activation='sigmoid')) return genModel" }, { "code": null, "e": 8528, "s": 8464, "text": "There are few options for choosing the loss functions, such as:" }, { "code": null, "e": 8543, "s": 8528, "text": "Least squares." }, { "code": null, "e": 8570, "s": 8543, "text": "Wasserstein loss function." }, { "code": null, "e": 9177, "s": 8570, "text": "One of the key issues associated with GAN models is the determination of when the model is converged. The competition between the discriminator and generator makes the game hard to reach a final winner. Both models are optimally want to maximize their gain and minimizes their loss. In our situation, we want both models to reach the point where they almost make a complete guess whether an image is fake or real and whether the generated image will pass the discriminator successfully. The 50–50 chance is the perfect ideal case inherited from the game theory, where both models are good hard to win over." }, { "code": null, "e": 9665, "s": 9177, "text": "GAN models are known to have the problem of slow convergence. Similar to other unsupervised models, the absence of true labels increase the challenge for determining when the training can stop. We need to make sure to balance between the training time and the produced quality. Several factors contribute to slow or speed up the training process, such as normalization of inputs, batch normalization, gradient penalties, and training the discriminator well before training the GAN model." }, { "code": null, "e": 10203, "s": 9665, "text": "GAN models are known to have a limited capabilities when it comes to the size of the generated images. The images size that we have seen in the MNIST examples are only 28 x 28 pixels. These are pretty small images to use in a real application. If we want to generate a bigger images, let us say 1024 x 1024, we will need a more scalable model. The research community has been interested in improving GAN capabilities. For instance, in 2017, T Karras et al. propose a novel model called Progressive Growing GANs to solve such problem [2]." }, { "code": null, "e": 10490, "s": 10203, "text": "Some of the challenges introduced in the previous sections made the research community expand the GAN models’ idea to tackle one or more of the issues mentioned above. This section covers some popular extensions and optimized GAN architectures to scale up the original GAN capabilities." }, { "code": null, "e": 10750, "s": 10490, "text": "Deep Convolutional GAN (DCGAN): This an extension to replace the feed forward neural network with a CNN architecture proposed by A. Radford et al. [5]. The idea of using a CNN architecture and learning through filters have improved the accuracy of GAN models." }, { "code": null, "e": 11082, "s": 10750, "text": "Wasserstein GAN (WGAN): WGAN is designed by M. Arjovsky et al. [6]. WGAN focuses on defining the distance between the generated distribution and the real distribution, which determines the model’s convergence. They propose the use of Earth Mover (EM) distance to approximate the differences between those distributions effectively." }, { "code": null, "e": 11527, "s": 11082, "text": "Progressive GAN: ProgressiveGAN is designed by T. Karras et al. [7] and presented at ICLR conference. This work bough high contributions to the generator and discriminator to grow progressively from lower-resolution to higher-resolution layers. The technique requires reducing the size of the mini-batches while computing the mini-batch standard deviation. ProgressiveGan also uses equalized learning rate, and pixel-wise feature normalization." }, { "code": null, "e": 12370, "s": 11527, "text": "The research has evolved from previous types to introduce semi-supervised learning models. Instead of having the discriminator classify whether a given image is real or fake, the model can be turned into a multiclass classifier. For instance, in MNIST, we have ten classes that represent the ten handwritten digits. The discriminator would have ten plus one class, where the additional class represents the fake images to classify. In this situation, the discriminator is learning not only fake from real images but also classifying each real image to its corresponding class. This would stretch the objective function with two kinds of losses (Softmax and Sigmoid) to make the discriminator more efficient into classifying images correctly ( see Figure 7). The remaining types from our list (cGAN, CycleGAN) introduce similar new objectives." }, { "code": null, "e": 12793, "s": 12370, "text": "Conditional GAN (cGAN): cGAN was published in 2014 by M. Mehdi and S. Osindero [8]. It supports the idea of having labels for each image and the generator learns how to generate realistic images for each label. The discriminator learns to distinguish the fake images while also making sure they carry the correct labels. If we apply the cGAN on the learning framework on Figure 3, would need to make the following changes:" }, { "code": null, "e": 13295, "s": 12793, "text": "Pix2pix: The Pix2pix model applies a special case of conditional GAN models’ concepts by considering the translation of images to another set of images. P. Isola et al. [9] proposed this idea in 2017. The labels and the produced outputs are sets of pairs of images. Like translating a portion of textual contents, we can translate an image to another image with certain properties (see Figure 9). Later, the research community proposes a more efficient approach like Cycle GAN as we will discuss next." }, { "code": null, "e": 14136, "s": 13295, "text": "Cycle GAN: The unique idea of Cycle GAN is the use of multiple generators and discriminators instead of one-to-one architecture. Pix2pix let the model learns from a pair of images. That condition was relaxed later by a proposal from J-Y. Zhu et al. [10]. The novelity of thier idea comes to a create accyle where the generated translation is looped back again to produce the original image. If there any loss during the translation, the difference is what we need to optimize. Two generators and discriminators can be used to translate input to “domain A” and then translate to “domain B”. This structured is referred to in the paper as forward-backward consistency (back translation and reconsiliation). The two discriminators examine the generated output for both domains. This concenpt is very similar to the basic idea of auto-encoders." }, { "code": null, "e": 14463, "s": 14136, "text": "Auto-encoders are composed of two parts: encoders and decoders. These models are out of this article’s scope as they represent a separate category of learners using a single model. Auto-encoders constructs the inputs in a compressed encoded format. The decoders, then, reconstruct the input from the generated compressed form." }, { "code": null, "e": 14858, "s": 14463, "text": "We have discussed how to build a GAN model using pretty small images from the MNIST dataset. The image size is only 128 x 128 pixels. As discussed earlier, the Progressive GAN models can grow from low-resolution layers to high-resolution layers, making it possible to scale up the model outputs. We will see in the following example how to go from 64 x 64 pixels to generate 1024 x 1024 pixels." }, { "code": null, "e": 15321, "s": 14858, "text": "The model is designed on two main concepts: fade-in and fine-tuning. The model goes from simple resolution 4 x 4 and progress towards higher resolution. it provides the ability to grow after training each layer and we would be able to monitor the output as we train progressively (as shown in Figure 10). The alpha parmeter is scaled to have values between 0 and 1. It determines whether we should use previous trained layers or the scaling up. The discriminator" }, { "code": null, "e": 15610, "s": 15321, "text": "This article gives a brief overview of how amazing the GAN models are. We have just touched some basics understanding of how GAN models work. I will later expand on some related topics in separate threads. However, if you are curious to learn more, I recommend two places to go from here:" }, { "code": null, "e": 15770, "s": 15610, "text": "“GANs in Action” by Jakub Langr and Vladimir Bok is a great book that teaches how to build GAN models and cover in details the aspects introduced in this blog." }, { "code": null, "e": 15983, "s": 15770, "text": "“The-gan-zoo” is a Github repository that tracks all the recent research artciles published in this field. You can go from this repo to visit your paper of interest and navigate to other list of interesting work." }, { "code": null, "e": 16099, "s": 15983, "text": "[1] Goodfellow, Ian, et al. “Generative adversarial nets.” Advances in neural information processing systems. 2014." }, { "code": null, "e": 16241, "s": 16099, "text": "[2] Karras, Tero, et al. “Progressive growing of gans for improved quality, stability, and variation.” arXiv preprint arXiv:1710.10196. 2017." }, { "code": null, "e": 16365, "s": 16241, "text": "[3] Salimans, Tim, et al. “Improved techniques for training gans.” Advances in neural information processing systems. 2016." }, { "code": null, "e": 16534, "s": 16365, "text": "[4] Heusel, Martin, et al. “Gans trained by a two time-scale update rule converge to a local nash equilibrium.” Advances in neural information processing systems. 2017." }, { "code": null, "e": 16722, "s": 16534, "text": "[5] Radford, Alec, Luke Metz, and Soumith Chintala. “Unsupervised representation learning with deep convolutional generative adversarial networks.” arXiv preprint arXiv:1511.06434 (2015)." }, { "code": null, "e": 16839, "s": 16722, "text": "[6] Arjovsky, Martin, Soumith Chintala, and Léon Bottou. “Wasserstein gan.” arXiv preprint arXiv:1701.07875 (2017)." }, { "code": null, "e": 16982, "s": 16839, "text": "[7] Karras, Tero, et al. “Progressive growing of gans for improved quality, stability, and variation.” arXiv preprint arXiv:1710.10196 (2017)." }, { "code": null, "e": 17102, "s": 16982, "text": "[8] Mirza, Mehdi, and Simon Osindero. “Conditional generative adversarial nets.” arXiv preprint arXiv:1411.1784 (2014)." }, { "code": null, "e": 17282, "s": 17102, "text": "[9] Isola, Phillip, et al. “Image-to-image translation with conditional adversarial networks.” Proceedings of the IEEE conference on computer vision and pattern recognition. 2017." } ]
Python - Fetch columns between two Pandas DataFrames by Intersection
To fetch columns between two DataFrames by Intersection, use the intersection() method. Let us create two DataFrames − # creating dataframe1 dataFrame1 = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000], }) # creating dataframe2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] }) Fetch common columns − dataFrame2.columns.intersection(dataFrame1.columns) Following is the complete code − import pandas as pd # creating dataframe1 dataFrame1 = pd.DataFrame({"Car": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Cubic_Capacity": [2000, 1800, 1500, 2500, 2200, 3000],"Reg_Price": [7000, 1500, 5000, 8000, 9000, 6000], }) print"Dataframe1...\n",dataFrame1 # creating dataframe2 dataFrame2 = pd.DataFrame({"Car": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],"Units_Sold": [ 100, 110, 150, 80, 200, 90] }) print"Dataframe2...\n",dataFrame2 # getting common columns using intersection() res = dataFrame2.columns.intersection(dataFrame1.columns) print"\nCommon columns...\n",res This will produce the following output − Dataframe1... Car Cubic_Capacity Reg_Price 0 Bentley 2000 7000 1 Lexus 1800 1500 2 Tesla 1500 5000 3 Mustang 2500 8000 4 Mercedes 2200 9000 5 Jaguar 3000 6000 Dataframe2... Car Units_Sold 0 BMW 100 1 Lexus 110 2 Tesla 150 3 Mustang 80 4 Mercedes 200 5 Jaguar 90 Common columns... Index([u'Car'], dtype='object')
[ { "code": null, "e": 1181, "s": 1062, "text": "To fetch columns between two DataFrames by Intersection, use the intersection() method. Let us create two DataFrames −" }, { "code": null, "e": 1572, "s": 1181, "text": "# creating dataframe1\ndataFrame1 = pd.DataFrame({\"Car\": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\n})\n\n# creating dataframe2\ndataFrame2 = pd.DataFrame({\"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Units_Sold\": [ 100, 110, 150, 80, 200, 90]\n})" }, { "code": null, "e": 1595, "s": 1572, "text": "Fetch common columns −" }, { "code": null, "e": 1648, "s": 1595, "text": "dataFrame2.columns.intersection(dataFrame1.columns)\n" }, { "code": null, "e": 1681, "s": 1648, "text": "Following is the complete code −" }, { "code": null, "e": 2302, "s": 1681, "text": "import pandas as pd\n\n# creating dataframe1\ndataFrame1 = pd.DataFrame({\"Car\": ['Bentley', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Cubic_Capacity\": [2000, 1800, 1500, 2500, 2200, 3000],\"Reg_Price\": [7000, 1500, 5000, 8000, 9000, 6000],\n})\n\nprint\"Dataframe1...\\n\",dataFrame1\n\n# creating dataframe2\ndataFrame2 = pd.DataFrame({\"Car\": ['BMW', 'Lexus', 'Tesla', 'Mustang', 'Mercedes', 'Jaguar'],\"Units_Sold\": [ 100, 110, 150, 80, 200, 90]\n})\n\nprint\"Dataframe2...\\n\",dataFrame2\n\n# getting common columns using intersection()\nres = dataFrame2.columns.intersection(dataFrame1.columns)\n\nprint\"\\nCommon columns...\\n\",res" }, { "code": null, "e": 2343, "s": 2302, "text": "This will produce the following output −" }, { "code": null, "e": 2884, "s": 2343, "text": "Dataframe1...\n Car Cubic_Capacity Reg_Price\n0 Bentley 2000 7000\n1 Lexus 1800 1500\n2 Tesla 1500 5000\n3 Mustang 2500 8000\n4 Mercedes 2200 9000\n5 Jaguar 3000 6000\nDataframe2...\n Car Units_Sold\n0 BMW 100\n1 Lexus 110\n2 Tesla 150\n3 Mustang 80\n4 Mercedes 200\n5 Jaguar 90\n\nCommon columns...\nIndex([u'Car'], dtype='object')" } ]
How to create Accordion in ReactJS ? - GeeksforGeeks
12 Feb, 2021 Accordions contain creation flows and allow lightweight editing of an element. Material UI for React has this component available for us, and it is very easy to integrate. We can create it in ReactJS using the following approach. Creating React Application and Installing Module: Step 1: Create a React application using the following command. npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command. cd foldername Step 3: After creating the ReactJS application, Install the material-ui modules using the following command. npm install @material-ui/core npm install @material-ui/icons App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. Javascript import React from "react";import ExpandMoreIcon from "@material-ui/icons/ExpandMore";import Accordion from "@material-ui/core/Accordion";import AccordionDetails from "@material-ui/core/AccordionDetails";import Typography from "@material-ui/core/Typography";import AccordionSummary from "@material-ui/core/AccordionSummary"; export default function App() { return ( <div stlye={{}}> <h4>How to create Accordion in ReactJS?</h4> <Accordion style={{ width: 400 }}> <AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls="panel1a-content" > <Typography style={{ fontWeight: 10, }} > Accordion Demo </Typography> </AccordionSummary> <AccordionDetails> <Typography>Greetings of the day :)</Typography> </AccordionDetails> </Accordion> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project. npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output. React-Questions JavaScript ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to detect browser or tab closing in JavaScript ? How to get character array from string in JavaScript? How to filter object array based on attributes? How to fetch data from an API in ReactJS ? How to redirect to another page in ReactJS ? How to pass data from child component to its parent in ReactJS ? How to pass data from one component to other component in ReactJS ? ReactJS Functional Components
[ { "code": null, "e": 25232, "s": 25204, "text": "\n12 Feb, 2021" }, { "code": null, "e": 25462, "s": 25232, "text": "Accordions contain creation flows and allow lightweight editing of an element. Material UI for React has this component available for us, and it is very easy to integrate. We can create it in ReactJS using the following approach." }, { "code": null, "e": 25512, "s": 25462, "text": "Creating React Application and Installing Module:" }, { "code": null, "e": 25576, "s": 25512, "text": "Step 1: Create a React application using the following command." }, { "code": null, "e": 25608, "s": 25576, "text": "npx create-react-app foldername" }, { "code": null, "e": 25708, "s": 25608, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command." }, { "code": null, "e": 25722, "s": 25708, "text": "cd foldername" }, { "code": null, "e": 25831, "s": 25722, "text": "Step 3: After creating the ReactJS application, Install the material-ui modules using the following command." }, { "code": null, "e": 25892, "s": 25831, "text": "npm install @material-ui/core\nnpm install @material-ui/icons" }, { "code": null, "e": 26021, "s": 25892, "text": "App.js: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 26032, "s": 26021, "text": "Javascript" }, { "code": "import React from \"react\";import ExpandMoreIcon from \"@material-ui/icons/ExpandMore\";import Accordion from \"@material-ui/core/Accordion\";import AccordionDetails from \"@material-ui/core/AccordionDetails\";import Typography from \"@material-ui/core/Typography\";import AccordionSummary from \"@material-ui/core/AccordionSummary\"; export default function App() { return ( <div stlye={{}}> <h4>How to create Accordion in ReactJS?</h4> <Accordion style={{ width: 400 }}> <AccordionSummary expandIcon={<ExpandMoreIcon />} aria-controls=\"panel1a-content\" > <Typography style={{ fontWeight: 10, }} > Accordion Demo </Typography> </AccordionSummary> <AccordionDetails> <Typography>Greetings of the day :)</Typography> </AccordionDetails> </Accordion> </div> );}", "e": 26940, "s": 26032, "text": null }, { "code": null, "e": 27053, "s": 26940, "text": "Step to Run Application: Run the application using the following command from the root directory of the project." }, { "code": null, "e": 27063, "s": 27053, "text": "npm start" }, { "code": null, "e": 27162, "s": 27063, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output." }, { "code": null, "e": 27178, "s": 27162, "text": "React-Questions" }, { "code": null, "e": 27189, "s": 27178, "text": "JavaScript" }, { "code": null, "e": 27197, "s": 27189, "text": "ReactJS" }, { "code": null, "e": 27214, "s": 27197, "text": "Web Technologies" }, { "code": null, "e": 27312, "s": 27214, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27321, "s": 27312, "text": "Comments" }, { "code": null, "e": 27334, "s": 27321, "text": "Old Comments" }, { "code": null, "e": 27395, "s": 27334, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 27436, "s": 27395, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 27489, "s": 27436, "text": "How to detect browser or tab closing in JavaScript ?" }, { "code": null, "e": 27543, "s": 27489, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 27591, "s": 27543, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 27634, "s": 27591, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 27679, "s": 27634, "text": "How to redirect to another page in ReactJS ?" }, { "code": null, "e": 27744, "s": 27679, "text": "How to pass data from child component to its parent in ReactJS ?" }, { "code": null, "e": 27812, "s": 27744, "text": "How to pass data from one component to other component in ReactJS ?" } ]
How to download a file from a URL in C#?
A file can be downloaded from a URL using web client. It is available in System.Net namespace. The WebClient class provides common methods for sending data to or receiving data from any local, intranet, or Internet resource identified by a URI. The web client can be said as an application or web browser (like Google Chrome, Internet Explorer, Opera, Firefox, Safari) which is installed in a computer and used to interact with Web servers upon user’s request. It is basically a consumer application which collects processed data from servers. A Client and a Server are two parts of a connection, these are two distinct machines, web client requests information, and the web server is basically a PC that is designed to accept requests from remote computers and send on the information requested. Web server is responsible for storing the information in order to be viewed by the clients and is also usually a Web Host. A Web host allows connections to the server to view said stored info. The WebClient class in C# uses the WebRequest class to provide access to resources. WebClient instances can access data with any WebRequest descendant registered with the WebRequest.RegisterPrefix method. The DownloadFile is used to download a file. WebClient Client = new WebClient (); client.DownloadFile("url","path"); Say we want to download an image from the path "https://downloadfreeimages.jpg" and save it the computer local directory, below is the code. using System; using System.Net; namespace DemoApplication{ public class Program{ public static void Main(){ string url = "https://downloadfreeimages.jpg"; string savePath = @"D:\Demo\FreeImages.jpg"; WebClient client = new WebClient(); client.DownloadFile(url, savePath); Console.ReadLine(); } } } The above example will download the image from the URL provided and saves it to the given path. D:\Demo
[ { "code": null, "e": 1157, "s": 1062, "text": "A file can be downloaded from a URL using web client. It is available in System.Net\nnamespace." }, { "code": null, "e": 1307, "s": 1157, "text": "The WebClient class provides common methods for sending data to or receiving data\nfrom any local, intranet, or Internet resource identified by a URI." }, { "code": null, "e": 1606, "s": 1307, "text": "The web client can be said as an application or web browser (like Google Chrome,\nInternet Explorer, Opera, Firefox, Safari) which is installed in a computer and used to\ninteract with Web servers upon user’s request. It is basically a consumer application\nwhich collects processed data from servers." }, { "code": null, "e": 2052, "s": 1606, "text": "A Client and a Server are two parts of a connection, these are two distinct machines,\nweb client requests information, and the web server is basically a PC that is designed\nto accept requests from remote computers and send on the information requested.\nWeb server is responsible for storing the information in order to be viewed by the\nclients and is also usually a Web Host. A Web host allows connections to the server\nto view said stored info." }, { "code": null, "e": 2214, "s": 2052, "text": "The WebClient class in C# uses the WebRequest class to provide access to resources.\nWebClient instances can access data with any WebRequest descendant registered" }, { "code": null, "e": 2302, "s": 2214, "text": "with the WebRequest.RegisterPrefix method. The DownloadFile is used to\ndownload a file." }, { "code": null, "e": 2374, "s": 2302, "text": "WebClient Client = new WebClient ();\nclient.DownloadFile(\"url\",\"path\");" }, { "code": null, "e": 2515, "s": 2374, "text": "Say we want to download an image from the path \"https://downloadfreeimages.jpg\"\nand save it the computer local directory, below is the code." }, { "code": null, "e": 2876, "s": 2515, "text": "using System;\nusing System.Net;\nnamespace DemoApplication{\n public class Program{\n public static void Main(){\n string url = \"https://downloadfreeimages.jpg\";\n string savePath = @\"D:\\Demo\\FreeImages.jpg\";\n WebClient client = new WebClient();\n client.DownloadFile(url, savePath);\n Console.ReadLine();\n }\n }\n}" }, { "code": null, "e": 2972, "s": 2876, "text": "The above example will download the image from the URL provided and saves it to\nthe given path." }, { "code": null, "e": 2980, "s": 2972, "text": "D:\\Demo" } ]
Python Blockchain - Block Class
A block consists of a varying number of transactions. For simplicity, in our case we will assume that the block consists of a fixed number of transactions, which is three in this case. As the block needs to store the list of these three transactions, we will declare an instance variable called verified_transactions as follows − self.verified_transactions = [] We have named this variable as verified_transactions to indicate that only the verified valid transactions will be added to the block. Each block also holds the hash value of the previous block, so that the chain of blocks becomes immutable. To store the previous hash, we declare an instance variable as follows − self.previous_block_hash = "" Finally, we declare one more variable called Nonce for storing the nonce created by the miner during the mining process. self.Nonce = "" The full definition of the Block class is given below − class Block: def __init__(self): self.verified_transactions = [] self.previous_block_hash = "" self.Nonce = "" As each block needs the value of the previous block’s hash we declare a global variable called last_block_hash as follows − last_block_hash = "" Now let us create our first block in the blockchain. 187 Lectures 17.5 hours Malhar Lathkar 55 Lectures 8 hours Arnab Chakraborty 136 Lectures 11 hours In28Minutes Official 75 Lectures 13 hours Eduonix Learning Solutions 70 Lectures 8.5 hours Lets Kode It 63 Lectures 6 hours Abhilash Nelson Print Add Notes Bookmark this page
[ { "code": null, "e": 2325, "s": 1995, "text": "A block consists of a varying number of transactions. For simplicity, in our case we will assume that the block consists of a fixed number of transactions, which is three in this case. As the block needs to store the list of these three transactions, we will declare an instance variable called verified_transactions as follows −" }, { "code": null, "e": 2358, "s": 2325, "text": "self.verified_transactions = []\n" }, { "code": null, "e": 2600, "s": 2358, "text": "We have named this variable as verified_transactions to indicate that only the verified valid transactions will be added to the block. Each block also holds the hash value of the previous block, so that the chain of blocks becomes immutable." }, { "code": null, "e": 2673, "s": 2600, "text": "To store the previous hash, we declare an instance variable as follows −" }, { "code": null, "e": 2704, "s": 2673, "text": "self.previous_block_hash = \"\"\n" }, { "code": null, "e": 2825, "s": 2704, "text": "Finally, we declare one more variable called Nonce for storing the nonce created by the miner during the mining process." }, { "code": null, "e": 2842, "s": 2825, "text": "self.Nonce = \"\"\n" }, { "code": null, "e": 2898, "s": 2842, "text": "The full definition of the Block class is given below −" }, { "code": null, "e": 3031, "s": 2898, "text": "class Block:\n def __init__(self):\n self.verified_transactions = []\n self.previous_block_hash = \"\"\n self.Nonce = \"\"\n" }, { "code": null, "e": 3155, "s": 3031, "text": "As each block needs the value of the previous block’s hash we declare a global variable called last_block_hash as follows −" }, { "code": null, "e": 3177, "s": 3155, "text": "last_block_hash = \"\"\n" }, { "code": null, "e": 3230, "s": 3177, "text": "Now let us create our first block in the blockchain." }, { "code": null, "e": 3267, "s": 3230, "text": "\n 187 Lectures \n 17.5 hours \n" }, { "code": null, "e": 3283, "s": 3267, "text": " Malhar Lathkar" }, { "code": null, "e": 3316, "s": 3283, "text": "\n 55 Lectures \n 8 hours \n" }, { "code": null, "e": 3335, "s": 3316, "text": " Arnab Chakraborty" }, { "code": null, "e": 3370, "s": 3335, "text": "\n 136 Lectures \n 11 hours \n" }, { "code": null, "e": 3392, "s": 3370, "text": " In28Minutes Official" }, { "code": null, "e": 3426, "s": 3392, "text": "\n 75 Lectures \n 13 hours \n" }, { "code": null, "e": 3454, "s": 3426, "text": " Eduonix Learning Solutions" }, { "code": null, "e": 3489, "s": 3454, "text": "\n 70 Lectures \n 8.5 hours \n" }, { "code": null, "e": 3503, "s": 3489, "text": " Lets Kode It" }, { "code": null, "e": 3536, "s": 3503, "text": "\n 63 Lectures \n 6 hours \n" }, { "code": null, "e": 3553, "s": 3536, "text": " Abhilash Nelson" }, { "code": null, "e": 3560, "s": 3553, "text": " Print" }, { "code": null, "e": 3571, "s": 3560, "text": " Add Notes" } ]
How can we minimize/maximize a JFrame programmatically in Java?
A JFrame class is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. A JFrame contains a window with title, border, (optional) menu bar and user-specific components. By default, we can minimize a JFrame by clicking on minimize button and maximize a JFrame by clicking on maximize button at the top-right position of the screen. We can also do programmatically by using setState(JFrame.ICONIFIED) to minimize a JFrame and setState(JFrame.MAXIMIZED_BOTH) to maximize a JFrame. import java.awt.*; import java.awt.event.*; import javax.swing.*; public class JFrameIconifiedTest extends JFrame implements ActionListener { private JButton iconifyButton, maximizeButton; public JFrameIconifiedTest() { setTitle("JFrameIconified Test"); iconifyButton = new JButton("JFrame Iconified"); add(iconifyButton, BorderLayout.NORTH); iconifyButton.addActionListener(this); maximizeButton = new JButton("JFrame Maximized"); add(maximizeButton, BorderLayout.SOUTH); maximizeButton.addActionListener(this); setSize(400, 275); setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); setLocationRelativeTo(null); setVisible(true); } public void actionPerformed(ActionEvent ae) { if(ae.getSource().equals(iconifyButton)) { setState(JFrame.ICONIFIED); // To minimize a frame } else if(ae.getSource().equals(maximizeButton)) { setExtendedState(JFrame.MAXIMIZED_BOTH); // To maximize a frame } } public static void main(String args[]) { new JFrameIconifiedTest(); } } In the above program, if we click on "JFrame Iconified" button, the frame is minimized and click on "JFrame Maximized" button, the frame is maximized.
[ { "code": null, "e": 1619, "s": 1062, "text": "A JFrame class is a subclass of Frame class and the components added to a frame are referred to as its contents, these are managed by the contentPane. A JFrame contains a window with title, border, (optional) menu bar and user-specific components. By default, we can minimize a JFrame by clicking on minimize button and maximize a JFrame by clicking on maximize button at the top-right position of the screen. We can also do programmatically by using setState(JFrame.ICONIFIED) to minimize a JFrame and setState(JFrame.MAXIMIZED_BOTH) to maximize a JFrame." }, { "code": null, "e": 2708, "s": 1619, "text": "import java.awt.*;\nimport java.awt.event.*;\nimport javax.swing.*;\npublic class JFrameIconifiedTest extends JFrame implements ActionListener {\n private JButton iconifyButton, maximizeButton;\n public JFrameIconifiedTest() {\n setTitle(\"JFrameIconified Test\");\n iconifyButton = new JButton(\"JFrame Iconified\");\n add(iconifyButton, BorderLayout.NORTH);\n iconifyButton.addActionListener(this);\n maximizeButton = new JButton(\"JFrame Maximized\");\n add(maximizeButton, BorderLayout.SOUTH);\n maximizeButton.addActionListener(this);\n setSize(400, 275);\n setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n setLocationRelativeTo(null);\n setVisible(true);\n }\n public void actionPerformed(ActionEvent ae) {\n if(ae.getSource().equals(iconifyButton)) {\n setState(JFrame.ICONIFIED); // To minimize a frame\n } else if(ae.getSource().equals(maximizeButton)) {\n setExtendedState(JFrame.MAXIMIZED_BOTH); // To maximize a frame\n }\n }\n public static void main(String args[]) {\n new JFrameIconifiedTest();\n }\n}" }, { "code": null, "e": 2859, "s": 2708, "text": "In the above program, if we click on \"JFrame Iconified\" button, the frame is minimized and click on \"JFrame Maximized\" button, the frame is maximized." } ]
How to get the disk information using PowerShell?
To get the Windows disk information using PowerShell, we can use the WMI command or the CIM class command. With the WMI command, Gwmi Win32_LogicalDisk With the CIM instance method, Get−CimInstance Win32_LogicalDisk You can see both the outputs are identical. Let’s use one of them. DeviceID DriveType ProviderName VolumeName Size FreeSpace -------- --------- ------------ ---------- ---- --------- C: 3 53317988352 44027125760 D: 5 HRM_SSS_X64FREE_EN-US_DV5 3694962688 0 E: 3 Temporary Storage 10734268416 10238513152 Now there are different drive types associated with Windows and they each have an identical number. For example, Drive Type ‘3’ mentions the logical disk. The other types are as below. 2 = "Removable disk" 3="Fixed local disk" 4="Network disk" 5 = "Compact disk" Here, we will filter only logical system disks. For that, we can use the below command. Get−CimInstance Win32_LogicalDisk | where{$_.DriveType −eq '3'} DeviceID DriveType ProviderName VolumeName Size FreeSpace -------- --------- ------------ ---------- ---- --------- C: 3 53317988352 44027023360 E: 3 Temporary Storage 10734268416 10238513152 The above size is displayed in bytes. You can convert it to GB using an expression. Use the below command, to convert the Size and FreeSpace into GB. Get−CimInstance Win32_LogicalDisk | where{$_.DriveType −eq '3'} ` | Select DeviceID, DriveType,VolumeName, @{N='TotalSize(GB)';E={[Math]::Ceiling($_.Size/1GB)}}, @{N='FreeSize(GB)';E={[Math]::Ceiling($_.FreeSpace/1GB)}} | ft −AutoSize DeviceID DriveType VolumeName TotalSize(GB) FreeSize(GB) -------- --------- ---------- ------------- ------------ C: 3 50 42 E: 3 Temporary Storage 10 10
[ { "code": null, "e": 1169, "s": 1062, "text": "To get the Windows disk information using PowerShell, we can use the WMI command or the CIM class command." }, { "code": null, "e": 1191, "s": 1169, "text": "With the WMI command," }, { "code": null, "e": 1214, "s": 1191, "text": "Gwmi Win32_LogicalDisk" }, { "code": null, "e": 1244, "s": 1214, "text": "With the CIM instance method," }, { "code": null, "e": 1279, "s": 1244, "text": "Get−CimInstance Win32_LogicalDisk\n" }, { "code": null, "e": 1346, "s": 1279, "text": "You can see both the outputs are identical. Let’s use one of them." }, { "code": null, "e": 1582, "s": 1346, "text": "DeviceID DriveType ProviderName VolumeName Size FreeSpace\n-------- --------- ------------ ---------- ---- ---------\nC: 3 53317988352 44027125760\nD: 5 HRM_SSS_X64FREE_EN-US_DV5 3694962688 0\nE: 3 Temporary Storage 10734268416 10238513152" }, { "code": null, "e": 1767, "s": 1582, "text": "Now there are different drive types associated with Windows and they each have an identical number. For example, Drive Type ‘3’ mentions the logical disk. The other types are as below." }, { "code": null, "e": 1788, "s": 1767, "text": "2 = \"Removable disk\"" }, { "code": null, "e": 1809, "s": 1788, "text": "3=\"Fixed local disk\"" }, { "code": null, "e": 1826, "s": 1809, "text": "4=\"Network disk\"" }, { "code": null, "e": 1845, "s": 1826, "text": "5 = \"Compact disk\"" }, { "code": null, "e": 1933, "s": 1845, "text": "Here, we will filter only logical system disks. For that, we can use the below command." }, { "code": null, "e": 1998, "s": 1933, "text": "Get−CimInstance Win32_LogicalDisk | where{$_.DriveType −eq '3'}\n" }, { "code": null, "e": 2190, "s": 1998, "text": "DeviceID DriveType ProviderName VolumeName Size FreeSpace\n-------- --------- ------------ ---------- ---- ---------\nC: 3 53317988352 44027023360\nE: 3 Temporary Storage 10734268416 10238513152" }, { "code": null, "e": 2340, "s": 2190, "text": "The above size is displayed in bytes. You can convert it to GB using an expression. Use the below command, to convert the Size and FreeSpace into GB." }, { "code": null, "e": 2575, "s": 2340, "text": "Get−CimInstance Win32_LogicalDisk | where{$_.DriveType −eq '3'} `\n| Select DeviceID, DriveType,VolumeName,\n@{N='TotalSize(GB)';E={[Math]::Ceiling($_.Size/1GB)}}, @{N='FreeSize(GB)';E={[Math]::Ceiling($_.FreeSpace/1GB)}} |\nft −AutoSize" }, { "code": null, "e": 2729, "s": 2575, "text": "DeviceID DriveType VolumeName TotalSize(GB) FreeSize(GB)\n-------- --------- ---------- ------------- ------------\nC: 3 50 42\nE: 3 Temporary Storage 10 10" } ]
Size of a Three-dimensional array in C#
To get the size of a 3D array in C#, use the GetLength() method with parameter as the index of the dimensions. GetLength(dimensionIndex) To get the size. arr.GetLength(0) arr.GetLength(1) arr.GetLength(2) Live Demo using System; class Program { static void Main() { int[,,] arr = new int[3,4,5]; // length of a dimension Console.WriteLine(arr.GetLength(0)); Console.WriteLine(arr.GetLength(1)); Console.WriteLine(arr.GetLength(2)); // length Console.WriteLine(arr.Length); } } 3 4 5 60
[ { "code": null, "e": 1173, "s": 1062, "text": "To get the size of a 3D array in C#, use the GetLength() method with parameter as the index of the dimensions." }, { "code": null, "e": 1199, "s": 1173, "text": "GetLength(dimensionIndex)" }, { "code": null, "e": 1216, "s": 1199, "text": "To get the size." }, { "code": null, "e": 1267, "s": 1216, "text": "arr.GetLength(0)\narr.GetLength(1)\narr.GetLength(2)" }, { "code": null, "e": 1278, "s": 1267, "text": " Live Demo" }, { "code": null, "e": 1588, "s": 1278, "text": "using System;\nclass Program {\n static void Main() {\n int[,,] arr = new int[3,4,5];\n // length of a dimension\n Console.WriteLine(arr.GetLength(0));\n Console.WriteLine(arr.GetLength(1));\n Console.WriteLine(arr.GetLength(2));\n // length\n Console.WriteLine(arr.Length);\n }\n}" }, { "code": null, "e": 1597, "s": 1588, "text": "3\n4\n5\n60" } ]
Difference between Abstract Class and Interface in Java - GeeksforGeeks
28 Feb, 2022 As we know that abstraction refers to hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction, henceforth Interface and Abstract Class are required prerequisites Type of methods: Interface can have only abstract methods. An abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also. Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables. Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables. Implementation: Abstract class can provide the implementation of the interface. Interface can’t provide the implementation of an abstract class. Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”. Multiple implementations: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces. Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc. Example 1-A: Java // Java Program to Illustrate Concept of// Abstract Class // Importing required classesimport java.io.*; // Class 1// Helper abstract classabstract class Shape { // Declare fields String objectName = " "; // Constructor of this class Shape(String name) { this.objectName = name; } // Method // Non-abstract methods // Having as default implementation public void moveTo(int x, int y) { System.out.println(this.objectName + " " + "has been moved to" + " x = " + x + " and y = " + y); } // Method 2 // Abstract methods which will be // implemented by its subclass(es) abstract public double area(); abstract public void draw();} // Class 2// Helper class extending Class 1class Rectangle extends Shape { // Attributes of rectangle int length, width; // Constructor Rectangle(int length, int width, String name) { // Super keyword refers to current instance itself super(name); // this keyword refers to current instance itself this.length = length; this.width = width; } // Method 1 // To draw rectangle @Override public void draw() { System.out.println("Rectangle has been drawn "); } // Method 2 // To compute rectangle area @Override public double area() { // Length * Breadth return (double)(length * width); }} // Class 3// Helper class extending Class 1class Circle extends Shape { // Attributes of a Circle double pi = 3.14; int radius; // Constructor Circle(int radius, String name) { // Super keyword refers to parent class super(name); // This keyword refers to current instance itself this.radius = radius; } // Method 1 // To draw circle @Override public void draw() { // Print statement System.out.println("Circle has been drawn "); } // Method 2 // To compute circle area @Override public double area() { return (double)((pi * radius * radius)); }} // Class 4// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating the Object of Rectangle class // and using shape class reference. Shape rect = new Rectangle(2, 3, "Rectangle"); System.out.println("Area of rectangle: " + rect.area()); rect.moveTo(1, 2); System.out.println(" "); // Creating the Objects of circle class Shape circle = new Circle(2, "Circle"); System.out.println("Area of circle: " + circle.area()); circle.moveTo(2, 4); }} Area of rectangle: 6.0 Rectangle has been moved to x = 1 and y = 2 Area of circle: 12.56 Circle has been moved to x = 2 and y = 4 What if we don’t have any common code between rectangle and circle then go with the interface. Example 1-B: Java // Java Program to Illustrate Concept of Interface // Importing I/O classesimport java.io.*; // Interfaceinterface Shape { // Abstract method void draw(); double area();} // Class 1// Helper classclass Rectangle implements Shape { int length, width; // constructor Rectangle(int length, int width) { this.length = length; this.width = width; } @Override public void draw() { System.out.println("Rectangle has been drawn "); } @Override public double area() { return (double)(length * width); }} // Class 2// Helper classclass Circle implements Shape { double pi = 3.14; int radius; // constructor Circle(int radius) { this.radius = radius; } @Override public void draw() { System.out.println("Circle has been drawn "); } @Override public double area() { return (double)((pi * radius * radius)); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating the Object of Rectangle class // and using shape interface reference. Shape rect = new Rectangle(2, 3); System.out.println("Area of rectangle: " + rect.area()); // Creating the Objects of circle class Shape circle = new Circle(2); System.out.println("Area of circle: " + circle.area()); }} Area of rectangle: 6.0 Area of circle: 12.56 When to use what? Consider using abstract classes if any of these statements apply to your situation: In the java application, there are some related classes that need to share some lines of code then you can put these lines of code within the abstract class and this abstract class should be extended by all these related classes. You can define the non-static or non-final field(s) in the abstract class so that via a method you can access and modify the state of the object to which they belong. You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private). Consider using interfaces if any of these statements apply to your situation: It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface. A class can implement more than one interface. It is called multiple inheritances. You want to specify the behavior of a particular data type but are not concerned about who implements its behavior. You can also go for Quiz on this topic. This article is contributed by Nitsdheerendra. 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. KhushbooGupta2 surindertarika1234 solankimayank simmytarika5 Java School Programming 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 Initialize an ArrayList in Java How to iterate any Map in Java Python Dictionary Arrays in C/C++ Inheritance in C++ Reverse a string in Java C++ Classes and Objects
[ { "code": null, "e": 28950, "s": 28922, "text": "\n28 Feb, 2022" }, { "code": null, "e": 29268, "s": 28950, "text": "As we know that abstraction refers to hiding the internal implementation of the feature and only showing the functionality to the users. i.e. what it works (showing), how it works (hiding). Both abstract class and interface are used for abstraction, henceforth Interface and Abstract Class are required prerequisites " }, { "code": null, "e": 29447, "s": 29268, "text": "Type of methods: Interface can have only abstract methods. An abstract class can have abstract and non-abstract methods. From Java 8, it can have default and static methods also." }, { "code": null, "e": 29576, "s": 29447, "text": "Final Variables: Variables declared in a Java interface are by default final. An abstract class may contain non-final variables." }, { "code": null, "e": 29721, "s": 29576, "text": "Type of variables: Abstract class can have final, non-final, static and non-static variables. The interface has only static and final variables." }, { "code": null, "e": 29866, "s": 29721, "text": "Implementation: Abstract class can provide the implementation of the interface. Interface can’t provide the implementation of an abstract class." }, { "code": null, "e": 30028, "s": 29866, "text": "Inheritance vs Abstraction: A Java interface can be implemented using the keyword “implements” and an abstract class can be extended using the keyword “extends”." }, { "code": null, "e": 30195, "s": 30028, "text": "Multiple implementations: An interface can extend another Java interface only, an abstract class can extend another Java class and implement multiple Java interfaces." }, { "code": null, "e": 30352, "s": 30195, "text": "Accessibility of Data Members: Members of a Java interface are public by default. A Java abstract class can have class members like private, protected, etc." }, { "code": null, "e": 30365, "s": 30352, "text": "Example 1-A:" }, { "code": null, "e": 30370, "s": 30365, "text": "Java" }, { "code": "// Java Program to Illustrate Concept of// Abstract Class // Importing required classesimport java.io.*; // Class 1// Helper abstract classabstract class Shape { // Declare fields String objectName = \" \"; // Constructor of this class Shape(String name) { this.objectName = name; } // Method // Non-abstract methods // Having as default implementation public void moveTo(int x, int y) { System.out.println(this.objectName + \" \" + \"has been moved to\" + \" x = \" + x + \" and y = \" + y); } // Method 2 // Abstract methods which will be // implemented by its subclass(es) abstract public double area(); abstract public void draw();} // Class 2// Helper class extending Class 1class Rectangle extends Shape { // Attributes of rectangle int length, width; // Constructor Rectangle(int length, int width, String name) { // Super keyword refers to current instance itself super(name); // this keyword refers to current instance itself this.length = length; this.width = width; } // Method 1 // To draw rectangle @Override public void draw() { System.out.println(\"Rectangle has been drawn \"); } // Method 2 // To compute rectangle area @Override public double area() { // Length * Breadth return (double)(length * width); }} // Class 3// Helper class extending Class 1class Circle extends Shape { // Attributes of a Circle double pi = 3.14; int radius; // Constructor Circle(int radius, String name) { // Super keyword refers to parent class super(name); // This keyword refers to current instance itself this.radius = radius; } // Method 1 // To draw circle @Override public void draw() { // Print statement System.out.println(\"Circle has been drawn \"); } // Method 2 // To compute circle area @Override public double area() { return (double)((pi * radius * radius)); }} // Class 4// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating the Object of Rectangle class // and using shape class reference. Shape rect = new Rectangle(2, 3, \"Rectangle\"); System.out.println(\"Area of rectangle: \" + rect.area()); rect.moveTo(1, 2); System.out.println(\" \"); // Creating the Objects of circle class Shape circle = new Circle(2, \"Circle\"); System.out.println(\"Area of circle: \" + circle.area()); circle.moveTo(2, 4); }}", "e": 33078, "s": 30370, "text": null }, { "code": null, "e": 33210, "s": 33078, "text": "Area of rectangle: 6.0\nRectangle has been moved to x = 1 and y = 2\n \nArea of circle: 12.56\nCircle has been moved to x = 2 and y = 4" }, { "code": null, "e": 33306, "s": 33210, "text": "What if we don’t have any common code between rectangle and circle then go with the interface. " }, { "code": null, "e": 33319, "s": 33306, "text": "Example 1-B:" }, { "code": null, "e": 33324, "s": 33319, "text": "Java" }, { "code": "// Java Program to Illustrate Concept of Interface // Importing I/O classesimport java.io.*; // Interfaceinterface Shape { // Abstract method void draw(); double area();} // Class 1// Helper classclass Rectangle implements Shape { int length, width; // constructor Rectangle(int length, int width) { this.length = length; this.width = width; } @Override public void draw() { System.out.println(\"Rectangle has been drawn \"); } @Override public double area() { return (double)(length * width); }} // Class 2// Helper classclass Circle implements Shape { double pi = 3.14; int radius; // constructor Circle(int radius) { this.radius = radius; } @Override public void draw() { System.out.println(\"Circle has been drawn \"); } @Override public double area() { return (double)((pi * radius * radius)); }} // Class 3// Main classclass GFG { // Main driver method public static void main(String[] args) { // Creating the Object of Rectangle class // and using shape interface reference. Shape rect = new Rectangle(2, 3); System.out.println(\"Area of rectangle: \" + rect.area()); // Creating the Objects of circle class Shape circle = new Circle(2); System.out.println(\"Area of circle: \" + circle.area()); }}", "e": 34763, "s": 33324, "text": null }, { "code": null, "e": 34808, "s": 34763, "text": "Area of rectangle: 6.0\nArea of circle: 12.56" }, { "code": null, "e": 34826, "s": 34808, "text": "When to use what?" }, { "code": null, "e": 34912, "s": 34826, "text": "Consider using abstract classes if any of these statements apply to your situation: " }, { "code": null, "e": 35142, "s": 34912, "text": "In the java application, there are some related classes that need to share some lines of code then you can put these lines of code within the abstract class and this abstract class should be extended by all these related classes." }, { "code": null, "e": 35309, "s": 35142, "text": "You can define the non-static or non-final field(s) in the abstract class so that via a method you can access and modify the state of the object to which they belong." }, { "code": null, "e": 35486, "s": 35309, "text": "You can expect that the classes that extend an abstract class have many common methods or fields, or require access modifiers other than public (such as protected and private)." }, { "code": null, "e": 35566, "s": 35486, "text": "Consider using interfaces if any of these statements apply to your situation: " }, { "code": null, "e": 35701, "s": 35566, "text": "It is total abstraction, All methods declared within an interface must be implemented by the class(es) that implements this interface." }, { "code": null, "e": 35784, "s": 35701, "text": "A class can implement more than one interface. It is called multiple inheritances." }, { "code": null, "e": 35900, "s": 35784, "text": "You want to specify the behavior of a particular data type but are not concerned about who implements its behavior." }, { "code": null, "e": 35940, "s": 35900, "text": "You can also go for Quiz on this topic." }, { "code": null, "e": 36363, "s": 35940, "text": "This article is contributed by Nitsdheerendra. 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": 36378, "s": 36363, "text": "KhushbooGupta2" }, { "code": null, "e": 36397, "s": 36378, "text": "surindertarika1234" }, { "code": null, "e": 36411, "s": 36397, "text": "solankimayank" }, { "code": null, "e": 36424, "s": 36411, "text": "simmytarika5" }, { "code": null, "e": 36429, "s": 36424, "text": "Java" }, { "code": null, "e": 36448, "s": 36429, "text": "School Programming" }, { "code": null, "e": 36453, "s": 36448, "text": "Java" }, { "code": null, "e": 36551, "s": 36453, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36595, "s": 36551, "text": "Split() String method in Java with examples" }, { "code": null, "e": 36631, "s": 36595, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 36656, "s": 36631, "text": "Reverse a string in Java" }, { "code": null, "e": 36688, "s": 36656, "text": "Initialize an ArrayList in Java" }, { "code": null, "e": 36719, "s": 36688, "text": "How to iterate any Map in Java" }, { "code": null, "e": 36737, "s": 36719, "text": "Python Dictionary" }, { "code": null, "e": 36753, "s": 36737, "text": "Arrays in C/C++" }, { "code": null, "e": 36772, "s": 36753, "text": "Inheritance in C++" }, { "code": null, "e": 36797, "s": 36772, "text": "Reverse a string in Java" } ]
How To Make Boxplots with Text as Points in R using ggplot2? - GeeksforGeeks
03 Dec, 2021 In this article, we will discuss how to make boxplots with text as points using the ggplot2 package in the R Programming language. A box plot is a chart that shows data from a five-number summary including one of the measures of central tendency. These five summary numbers are Minimum, First Quartile, Median, Third Quartile, and Maximum which helps us in analyzing different statistical measures through visual representation. To import & install ggplot2 package, we need to follow the below syntax: install.package('ggplot2') # To install import('ggplot2') # To import We can create a basic boxplot by using the geom_boxplot() function of the ggplot2 package in the R Language. Syntax: ggplot(dataframe, aes( x, y, color ) ) + geom_boxplot() Example: In this example, a basic boxplot is made using the geom_boxplot function of the ggplot2 package. The CSV file used in the example can be downloaded here. R # Load library ggplot2library(ggplot2) # read sample_data from csv as a dataframesample_data <- read.csv("df.csv") # use sample_data to plot a boxplot# Color the plot by group using color parameterggplot(sample_data, aes(x=group, y=value, color=group))+ geom_boxplot() Output: To add jittered data points as an overlay to the boxplot, we will use the geom_jitter() function of the ggplot2 package. This function adds a layer over the boxplot with actual points plotted over it. Syntax: ggplot(dataframe, aes( x, y, color ) ) + geom_boxplot() + geom_jitter() Parameters: x is categorical variable y is quantitative variable z is categorical variable used in the color plot by the group. Example: In this example, a boxplot is made using the geom_boxplot function of the ggplot2 package. The actual data points are overlayed to boxplot using geom_jitter() function. R # Load library ggplot2library(ggplot2) # read sample_data from csv as a dataframesample_data <- read.csv("df.csv") # use sample_data to plot a boxplot# Add jitter points to boxplot using# geom_jitter() functionggplot(sample_data, aes(x=group, y=value, color=group))+ geom_boxplot()+ geom_jitter() Output: Now to analyze the data we will replace the data points with their respective labels using the geom_text() function with parameter position. The geom_text() function replaces the data points with data labels but all labels come in a straight line. To make it jittered, we use the position parameter as position_jitter(). Syntax: ggplot(dataframe, aes( x, y, color ) ) + geom_boxplot() + geom_text( position= position_jitter() ) Example: Here, The actual data points are overlayed to boxplot as the label text using geom_text() function. R # Load library tidyverselibrary(tidyverse) # read sample_data from csv as a dataframesample_data <- read.csv("df.csv") # use sample_data to plot a boxplot# Add jitter points to boxplot using geom_jitter()# functionggplot(sample_data, aes(x=group,y=value, label = Label, color=group))+ geom_boxplot()+ geom_text(check_overlap = TRUE, position=position_jitter(width=0.15)) Output: surindertarika1234 Picked R-ggplot R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? How to change the order of bars in bar chart in R ?
[ { "code": null, "e": 24851, "s": 24823, "text": "\n03 Dec, 2021" }, { "code": null, "e": 24982, "s": 24851, "text": "In this article, we will discuss how to make boxplots with text as points using the ggplot2 package in the R Programming language." }, { "code": null, "e": 25280, "s": 24982, "text": "A box plot is a chart that shows data from a five-number summary including one of the measures of central tendency. These five summary numbers are Minimum, First Quartile, Median, Third Quartile, and Maximum which helps us in analyzing different statistical measures through visual representation." }, { "code": null, "e": 25353, "s": 25280, "text": "To import & install ggplot2 package, we need to follow the below syntax:" }, { "code": null, "e": 25423, "s": 25353, "text": "install.package('ggplot2') # To install\nimport('ggplot2') # To import" }, { "code": null, "e": 25532, "s": 25423, "text": "We can create a basic boxplot by using the geom_boxplot() function of the ggplot2 package in the R Language." }, { "code": null, "e": 25540, "s": 25532, "text": "Syntax:" }, { "code": null, "e": 25597, "s": 25540, "text": "ggplot(dataframe, aes( x, y, color ) ) + geom_boxplot()" }, { "code": null, "e": 25606, "s": 25597, "text": "Example:" }, { "code": null, "e": 25704, "s": 25606, "text": "In this example, a basic boxplot is made using the geom_boxplot function of the ggplot2 package. " }, { "code": null, "e": 25761, "s": 25704, "text": "The CSV file used in the example can be downloaded here." }, { "code": null, "e": 25763, "s": 25761, "text": "R" }, { "code": "# Load library ggplot2library(ggplot2) # read sample_data from csv as a dataframesample_data <- read.csv(\"df.csv\") # use sample_data to plot a boxplot# Color the plot by group using color parameterggplot(sample_data, aes(x=group, y=value, color=group))+ geom_boxplot()", "e": 26033, "s": 25763, "text": null }, { "code": null, "e": 26041, "s": 26033, "text": "Output:" }, { "code": null, "e": 26242, "s": 26041, "text": "To add jittered data points as an overlay to the boxplot, we will use the geom_jitter() function of the ggplot2 package. This function adds a layer over the boxplot with actual points plotted over it." }, { "code": null, "e": 26250, "s": 26242, "text": "Syntax:" }, { "code": null, "e": 26323, "s": 26250, "text": "ggplot(dataframe, aes( x, y, color ) ) + geom_boxplot() + geom_jitter()" }, { "code": null, "e": 26335, "s": 26323, "text": "Parameters:" }, { "code": null, "e": 26361, "s": 26335, "text": "x is categorical variable" }, { "code": null, "e": 26388, "s": 26361, "text": "y is quantitative variable" }, { "code": null, "e": 26451, "s": 26388, "text": "z is categorical variable used in the color plot by the group." }, { "code": null, "e": 26460, "s": 26451, "text": "Example:" }, { "code": null, "e": 26630, "s": 26460, "text": "In this example, a boxplot is made using the geom_boxplot function of the ggplot2 package. The actual data points are overlayed to boxplot using geom_jitter() function. " }, { "code": null, "e": 26632, "s": 26630, "text": "R" }, { "code": "# Load library ggplot2library(ggplot2) # read sample_data from csv as a dataframesample_data <- read.csv(\"df.csv\") # use sample_data to plot a boxplot# Add jitter points to boxplot using# geom_jitter() functionggplot(sample_data, aes(x=group, y=value, color=group))+ geom_boxplot()+ geom_jitter()", "e": 26931, "s": 26632, "text": null }, { "code": null, "e": 26939, "s": 26931, "text": "Output:" }, { "code": null, "e": 27260, "s": 26939, "text": "Now to analyze the data we will replace the data points with their respective labels using the geom_text() function with parameter position. The geom_text() function replaces the data points with data labels but all labels come in a straight line. To make it jittered, we use the position parameter as position_jitter()." }, { "code": null, "e": 27268, "s": 27260, "text": "Syntax:" }, { "code": null, "e": 27368, "s": 27268, "text": "ggplot(dataframe, aes( x, y, color ) ) + geom_boxplot() + geom_text( position= position_jitter() )" }, { "code": null, "e": 27377, "s": 27368, "text": "Example:" }, { "code": null, "e": 27478, "s": 27377, "text": "Here, The actual data points are overlayed to boxplot as the label text using geom_text() function. " }, { "code": null, "e": 27480, "s": 27478, "text": "R" }, { "code": "# Load library tidyverselibrary(tidyverse) # read sample_data from csv as a dataframesample_data <- read.csv(\"df.csv\") # use sample_data to plot a boxplot# Add jitter points to boxplot using geom_jitter()# functionggplot(sample_data, aes(x=group,y=value, label = Label, color=group))+ geom_boxplot()+ geom_text(check_overlap = TRUE, position=position_jitter(width=0.15))", "e": 27853, "s": 27480, "text": null }, { "code": null, "e": 27861, "s": 27853, "text": "Output:" }, { "code": null, "e": 27880, "s": 27861, "text": "surindertarika1234" }, { "code": null, "e": 27887, "s": 27880, "text": "Picked" }, { "code": null, "e": 27896, "s": 27887, "text": "R-ggplot" }, { "code": null, "e": 27907, "s": 27896, "text": "R Language" }, { "code": null, "e": 28005, "s": 27907, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28014, "s": 28005, "text": "Comments" }, { "code": null, "e": 28027, "s": 28014, "text": "Old Comments" }, { "code": null, "e": 28079, "s": 28027, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 28117, "s": 28079, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 28152, "s": 28117, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 28210, "s": 28152, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 28259, "s": 28210, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 28302, "s": 28259, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 28352, "s": 28302, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 28369, "s": 28352, "text": "R - if statement" }, { "code": null, "e": 28406, "s": 28369, "text": "How to import an Excel File into R ?" } ]
Neural Network from Scratch With Python | by Angela Shi | Towards Data Science
Neural Network is often considered a black-box algorithm. Data visualization can help us better understand the principles of this algorithm. Since standard packages don’t give all details of how the parameters are found, we will code a neural network from scratch. And in order to visualize simply the results, we have chosen a simple dataset. Let’s use this simple dataset with only one feature X. import numpy as npX=np.array([[-1.51], [-1.29], [-1.18], [-0.64],[-0.53], [-0.09], [0.13], [0.35],[0.89], [1.11], [1.33], [1.44]])y=np.array([[0], [0], [0], [0],[1], [1], [1], [1],[0], [0], [0], [0]]) X is a single column vector with 12 observations, and y is also a column vector with 12 values that represent the target. We can visualize this dataset. import matplotlib.pyplot as pltplt.scatter(X,y) For those of you who already know how a neural network works, you should be able to find a simple structure by seeing this graph. In the next part, the activation function will be the sigmoid function. So the question is: how many layers and neurons do we need in order to build a neural network that would fit the dataset above? If we use only one neuron it will be the same thing as doing a Logistic Regression because the activation function is the sigmoid function. And we know that it won’t work because the dataset is not linearly separable, and Simple Logistic Regression doesn’t work with not linearly separable data. So we have to add a hidden layer. Each neuron in the hidden layer will result in a linear decision boundary. In general, a Logistic Regression creates a hyperplane as a decision boundary. Since here we only have one feature, then this hyperplane is only a dot. Visually, we can see that we would need two dots to separate one class from the other. And their values would be around for one -0.5 and the other 0.5. So a neural network with the following structure would be a good classifier for our dataset. If it is not clear for you, you can read this article. towardsdatascience.com Before building the neural network from scratch, let’s first use algorithms already built to confirm that such a neural network is suitable, and visualize the results. We can use the MLPClassifier in scikit learn. In the following code, we specify the number of hidden layers and the number of neurons with the argument hidden_layer_sizes. from sklearn.neural_network import MLPClassifierclf = MLPClassifier(solver=’lbfgs’,hidden_layer_sizes=(2,), activation=”logistic”,max_iter=1000)clf.fit(X, y) Then we can calculate the score. (You should get 1.0, otherwise, you may have to run the code again because of local minimums). clf.score(X,y) So great, how can we visualize the results of the algorithm? Since we know that this neural network is made by 2+1 Logistic Regression, we can get the parameters with the following code. clf.coefs_clf.intercepts_ How do we interpret the results? For clf.coefs_, you will get (for example): [array([[-20.89123833, -8.09121263]]), array([[-20.19430919], [ 17.74430684]])] And for clf.intercepts_ [array([-12.35004862, 4.62846821]), array([-8.19425129])] The first items of the lists contain the parameters for the hidden layer, and the second items contain the parameters for the output layer. With these parameters, we can plot the curves: def sigmoid(x): return 1.0/(1+ np.exp(-x))plt.scatter(X,y)a1_1=sigmoid(xseq*clf.coefs_[0][0,0]+clf.intercepts_[0][0])a1_2=sigmoid(xseq*clf.coefs_[0][0,1]+clf.intercepts_[0][1])output=sigmoid(a1_1*clf.coefs_[1][0]+a1_2*clf.coefs_[1][1]+clf.intercepts_[1])plt.plot(xseq,a1_1,c=”red”)plt.plot(xseq,a1_2,c=”blue”)plt.plot(xseq,output,c=”black”) And we can get the following graph: The red one is the result of the neuron 1 of the hidden layer The blue one is the result of the neuron 2 of the hidden layer The black one is the output If you run the code, you may get another result, because the loss function has several global minimums. In keras, it is of course also possible to create the same structure: from keras.models import Sequentialfrom keras.layers import Densemodel = Sequential()model.add(Dense(2, activation=’sigmoid’))model.add(Dense(1, activation=’sigmoid’))model.compile(loss=’binary_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])model.fit(X_train, y_train, epochs=300) Now the question is how are all the seven parameters found? One method is to use gradient descent. First, let’s do the forward propagation. For each neuron, we have to find the weight w and the bias b. Let’s try some random values. plt.scatter(X,y)plt.plot(xseq,sigmoid(xseq*(-11)-11),c="red") Since there are two neurons, we can do a matrice multiplication by creating matrices for the parameters: the weight matrix should have two columns. (Since here the input data has one column, then the weight matrix should have one row and two columns). We can do a random initialization, and choose some values. the bias should have the same structure. w1=np.random.rand(X.shape[1],2) # random initializationw1=np.array([[-1,9]])b1=np.array([[-1,5]])z1=np.dot(X, w1)+b1a1=sigmoid(z1) If you are just reading and not running a notebook at the same time, one exercise to do is to answer the following questions: What is the dimension of np.dot(X, w1)? What is the dimension of z1? Why is it OK to do addition? What if b1 is a simple 1d-array? What is the dimension of a1? If we replace the input X by xseq created before, we can plot the curves: a1_seq=sigmoid(np.dot(xseq.reshape(-1,1), w1)+b1)plt.scatter(X,y)plt.plot(xseq,a1_seq[:,0],c="red")plt.plot(xseq,a1_seq[:,1],c="blue") Now for the output, it is a very similar calculation. The weight matrix has now the rows because the hidden layer results in a matrix of two columns. The bias matrix is a scalar w2 = np.random.rand(2,1)b2=0output=sigmoid(np.dot(a1,w2)+b2) Then we can plot the output, with the other curves output_seq=sigmoid(np.dot(a1_seq,w2)+b2)plt.scatter(X,y)plt.plot(xseq,a1_seq[:,0],c=”red”)plt.plot(xseq,a1_seq[:,1],c=”blue”)plt.plot(xseq,output_seq,c=”black”) As you can see, the randomly chosen parameters are not good. Just to sum up the forward propagation: def feedforward(input,w1,w2,b1,b2): a1 = sigmoid(np.dot(input, w1)+b1) output = sigmoid(np.dot(a1, w2)+b2) return output The suitable parameters are those which minimize the cost function. We can use the cross-entropy: The function can coded as below: def cost(y,output): return -np.sum(y*np.log(output)+(1-y)*np.log(1-output))/12 Since there are 7 parameters, visualizing the cost function is not easy. Let’s just choose one of them to vary. For example the first weight in w1. b1=np.array([[16.81,-23.41]])w2= np.array([28.8,-52.89])b2=-17.53p = np.linspace(-100,100,10000)for i in range(len(p)): w1=np.array([[p[i],-37.94]]) output=feedforward(X,w1,w2,b1,b2) cost_seq[i]=cost(y,output) And you can see that it is not convex at all. And it is also possible to vary two parameters. In order to better visualize the cost function, we can also make an animation. Now let find some suitable global minimums of this cost function using gradient descent which is call backpropagation. Partial derivatives can be ugly, but fortunately, with the cross-entropy as a loss function, there are some simplifications in the final results. Here is the cost function again: Please note that when you use the cost function to calculate the cost of a model, then the input variables for this function are the output of the model and the real value of the target variable. If we try to find the optimum parameters of the model, then we consider that the input variables for this cost function are these parameters. And we are going to calculate the partial derivatives of the cost function with respect to every parameter. For the partial derivative with respect to w1, using the chain rule, we have: First, for the sigmoid function, the derivative can be written as: (Please note that the cost function is a sum of functions, and the partial derivative of a sum of functions is the sum the partial derivates of the functions, so in order to simplify the notation, we will drop the sum symbol, or to be exact, the mean calculation). Let’s first calculate the first two items as below: And we can notice that they can be simplified to (yhat-y). Then we have the final result for the w1: For b1, the expression is quite similar, as the only difference is the last partial derivative: We are going to code the computation with matrix multiplication. Before coding, we can ask ourselves some questions (and answer them): What is the dimension of the residuals (yhat — y)? It is a column vector and the number of rows is equal to the number of total observations. What is the dimension of w2? It is a matrix of two rows and one column. Remember, it is the weight matrix for the two hidden neurons, to compute the output. What is the dimension of (yhat — y)*w2? Since the dimension w2 is (2,1), we can not do a simple multiplication. What should we do? We can transpose the w1 matrix. Then (yhat — y)*w2 will give us a matrix of two columns and 12 observations. It is perfect because we want to do the computation for each of the weights. What is the dimension of a1? It is the results of the hidden layer. Since we have two neurons, a1 has two columns and 12 observations. And the multiplication with the previous matrix will be element-wise multiplication. All this is very consistent because, in the end, we will get a matrix of 2 columns and 12 observations. And the first column is associated with the weight of the first neuron, and the second column is associated with the weight of the second neuron in the hidden layer. Let’s do some coding: d_b1_v=np.dot((output-y), w2.T) * a1*(1-a1) What does this matrix represent? We can show the partial derivative with respect to b1 again. The matrix d_b1_v is the partial derivative for all observations. And to get the final derivatives, we have to calculate the sum of those associated with all observations (remember, L is a sum of functions), and calculate the average value. d_b1=np.mean(d_b1_v,axis=0) For w1, we have to take x into account. For each observation, we have to multiply the value obtained by previous partial derivatives by the value of x, then sum them all. This is exactly a dot product. And to obtain the average value, we have to divide by the number of observations. d_w1 = np.dot(X.T, d_b1_v)/12 Now, let continue for the parameters of the output layer. It will be much easier. We already have: So the derivatives with respect to w2 and b2 are: For b2, we just have to sum the residuals np.sum(output-y)/12 For w2, it is the dot product between a1 (results of layer 1) and the residuals. np.dot(a1.T, (output-y))/12 Now we can create a class to include the two steps of forward propagation and backward propagation. I used the python code based on this very popular article. You may already have read it. The differences are the loss function (cross-entropy instead of MSE) adding a learning rate class NeuralNetwork: def __init__(self, x, y): self.input = x self.w1 = np.random.rand(self.input.shape[1],2) self.w2 = np.random.rand(2,1) self.b1 = np.zeros(2) self.b2 = 0.0 self.y = y self.output = np.zeros(self.y.shape) def feedforward(self): self.a1 = sigmoid(np.dot(self.input, self.w1)+self.b1) self.output = sigmoid(np.dot(self.a1, self.w2)+self.b2) def backprop(self): lr=0.1 res=self.output-self.y d_w2 = np.dot(self.a1.T, res) d_b2 = np.sum(res) d_b1_v=np.dot(res, self.w2.T) * self.a1*(1-self.a1) d_b1 = np.sum(d_b1_v,axis=0) d_w1 = np.dot(self.input.T, d_b1_v) self.w1 -= d_w1*lr self.w2 -= d_w2*lr self.b1 -= d_b1*lr self.b2 -= d_b2*lr It is then possible to store the intermediate values of the 7 parameters during the gradient descent and plot the curves. The animation is made with graphs from R code. So if you are interested in R code of the neural network from scratch, please comment. If you the code is difficult for you to understand, I also created an Excel (Google Sheet) file to do the gradient descent. If you are interested, please let me know in the comments. Yes, you may think that is it crazy to do machine learning in Excel, and I agree with you, especially after having done all the steps of gradient descent for all the seven parameters. But the objective is to better understand. And for that, Excel is an excellent tool.
[ { "code": null, "e": 515, "s": 171, "text": "Neural Network is often considered a black-box algorithm. Data visualization can help us better understand the principles of this algorithm. Since standard packages don’t give all details of how the parameters are found, we will code a neural network from scratch. And in order to visualize simply the results, we have chosen a simple dataset." }, { "code": null, "e": 570, "s": 515, "text": "Let’s use this simple dataset with only one feature X." }, { "code": null, "e": 771, "s": 570, "text": "import numpy as npX=np.array([[-1.51], [-1.29], [-1.18], [-0.64],[-0.53], [-0.09], [0.13], [0.35],[0.89], [1.11], [1.33], [1.44]])y=np.array([[0], [0], [0], [0],[1], [1], [1], [1],[0], [0], [0], [0]])" }, { "code": null, "e": 924, "s": 771, "text": "X is a single column vector with 12 observations, and y is also a column vector with 12 values that represent the target. We can visualize this dataset." }, { "code": null, "e": 972, "s": 924, "text": "import matplotlib.pyplot as pltplt.scatter(X,y)" }, { "code": null, "e": 1174, "s": 972, "text": "For those of you who already know how a neural network works, you should be able to find a simple structure by seeing this graph. In the next part, the activation function will be the sigmoid function." }, { "code": null, "e": 1302, "s": 1174, "text": "So the question is: how many layers and neurons do we need in order to build a neural network that would fit the dataset above?" }, { "code": null, "e": 1707, "s": 1302, "text": "If we use only one neuron it will be the same thing as doing a Logistic Regression because the activation function is the sigmoid function. And we know that it won’t work because the dataset is not linearly separable, and Simple Logistic Regression doesn’t work with not linearly separable data. So we have to add a hidden layer. Each neuron in the hidden layer will result in a linear decision boundary." }, { "code": null, "e": 2011, "s": 1707, "text": "In general, a Logistic Regression creates a hyperplane as a decision boundary. Since here we only have one feature, then this hyperplane is only a dot. Visually, we can see that we would need two dots to separate one class from the other. And their values would be around for one -0.5 and the other 0.5." }, { "code": null, "e": 2104, "s": 2011, "text": "So a neural network with the following structure would be a good classifier for our dataset." }, { "code": null, "e": 2159, "s": 2104, "text": "If it is not clear for you, you can read this article." }, { "code": null, "e": 2182, "s": 2159, "text": "towardsdatascience.com" }, { "code": null, "e": 2350, "s": 2182, "text": "Before building the neural network from scratch, let’s first use algorithms already built to confirm that such a neural network is suitable, and visualize the results." }, { "code": null, "e": 2522, "s": 2350, "text": "We can use the MLPClassifier in scikit learn. In the following code, we specify the number of hidden layers and the number of neurons with the argument hidden_layer_sizes." }, { "code": null, "e": 2680, "s": 2522, "text": "from sklearn.neural_network import MLPClassifierclf = MLPClassifier(solver=’lbfgs’,hidden_layer_sizes=(2,), activation=”logistic”,max_iter=1000)clf.fit(X, y)" }, { "code": null, "e": 2808, "s": 2680, "text": "Then we can calculate the score. (You should get 1.0, otherwise, you may have to run the code again because of local minimums)." }, { "code": null, "e": 2823, "s": 2808, "text": "clf.score(X,y)" }, { "code": null, "e": 3010, "s": 2823, "text": "So great, how can we visualize the results of the algorithm? Since we know that this neural network is made by 2+1 Logistic Regression, we can get the parameters with the following code." }, { "code": null, "e": 3036, "s": 3010, "text": "clf.coefs_clf.intercepts_" }, { "code": null, "e": 3069, "s": 3036, "text": "How do we interpret the results?" }, { "code": null, "e": 3113, "s": 3069, "text": "For clf.coefs_, you will get (for example):" }, { "code": null, "e": 3193, "s": 3113, "text": "[array([[-20.89123833, -8.09121263]]), array([[-20.19430919], [ 17.74430684]])]" }, { "code": null, "e": 3217, "s": 3193, "text": "And for clf.intercepts_" }, { "code": null, "e": 3275, "s": 3217, "text": "[array([-12.35004862, 4.62846821]), array([-8.19425129])]" }, { "code": null, "e": 3415, "s": 3275, "text": "The first items of the lists contain the parameters for the hidden layer, and the second items contain the parameters for the output layer." }, { "code": null, "e": 3462, "s": 3415, "text": "With these parameters, we can plot the curves:" }, { "code": null, "e": 3806, "s": 3462, "text": "def sigmoid(x): return 1.0/(1+ np.exp(-x))plt.scatter(X,y)a1_1=sigmoid(xseq*clf.coefs_[0][0,0]+clf.intercepts_[0][0])a1_2=sigmoid(xseq*clf.coefs_[0][0,1]+clf.intercepts_[0][1])output=sigmoid(a1_1*clf.coefs_[1][0]+a1_2*clf.coefs_[1][1]+clf.intercepts_[1])plt.plot(xseq,a1_1,c=”red”)plt.plot(xseq,a1_2,c=”blue”)plt.plot(xseq,output,c=”black”)" }, { "code": null, "e": 3842, "s": 3806, "text": "And we can get the following graph:" }, { "code": null, "e": 3904, "s": 3842, "text": "The red one is the result of the neuron 1 of the hidden layer" }, { "code": null, "e": 3967, "s": 3904, "text": "The blue one is the result of the neuron 2 of the hidden layer" }, { "code": null, "e": 3995, "s": 3967, "text": "The black one is the output" }, { "code": null, "e": 4099, "s": 3995, "text": "If you run the code, you may get another result, because the loss function has several global minimums." }, { "code": null, "e": 4169, "s": 4099, "text": "In keras, it is of course also possible to create the same structure:" }, { "code": null, "e": 4457, "s": 4169, "text": "from keras.models import Sequentialfrom keras.layers import Densemodel = Sequential()model.add(Dense(2, activation=’sigmoid’))model.add(Dense(1, activation=’sigmoid’))model.compile(loss=’binary_crossentropy’, optimizer=’adam’, metrics=[‘accuracy’])model.fit(X_train, y_train, epochs=300)" }, { "code": null, "e": 4556, "s": 4457, "text": "Now the question is how are all the seven parameters found? One method is to use gradient descent." }, { "code": null, "e": 4597, "s": 4556, "text": "First, let’s do the forward propagation." }, { "code": null, "e": 4689, "s": 4597, "text": "For each neuron, we have to find the weight w and the bias b. Let’s try some random values." }, { "code": null, "e": 4751, "s": 4689, "text": "plt.scatter(X,y)plt.plot(xseq,sigmoid(xseq*(-11)-11),c=\"red\")" }, { "code": null, "e": 4856, "s": 4751, "text": "Since there are two neurons, we can do a matrice multiplication by creating matrices for the parameters:" }, { "code": null, "e": 5062, "s": 4856, "text": "the weight matrix should have two columns. (Since here the input data has one column, then the weight matrix should have one row and two columns). We can do a random initialization, and choose some values." }, { "code": null, "e": 5103, "s": 5062, "text": "the bias should have the same structure." }, { "code": null, "e": 5234, "s": 5103, "text": "w1=np.random.rand(X.shape[1],2) # random initializationw1=np.array([[-1,9]])b1=np.array([[-1,5]])z1=np.dot(X, w1)+b1a1=sigmoid(z1)" }, { "code": null, "e": 5360, "s": 5234, "text": "If you are just reading and not running a notebook at the same time, one exercise to do is to answer the following questions:" }, { "code": null, "e": 5400, "s": 5360, "text": "What is the dimension of np.dot(X, w1)?" }, { "code": null, "e": 5429, "s": 5400, "text": "What is the dimension of z1?" }, { "code": null, "e": 5491, "s": 5429, "text": "Why is it OK to do addition? What if b1 is a simple 1d-array?" }, { "code": null, "e": 5520, "s": 5491, "text": "What is the dimension of a1?" }, { "code": null, "e": 5594, "s": 5520, "text": "If we replace the input X by xseq created before, we can plot the curves:" }, { "code": null, "e": 5729, "s": 5594, "text": "a1_seq=sigmoid(np.dot(xseq.reshape(-1,1), w1)+b1)plt.scatter(X,y)plt.plot(xseq,a1_seq[:,0],c=\"red\")plt.plot(xseq,a1_seq[:,1],c=\"blue\")" }, { "code": null, "e": 5783, "s": 5729, "text": "Now for the output, it is a very similar calculation." }, { "code": null, "e": 5879, "s": 5783, "text": "The weight matrix has now the rows because the hidden layer results in a matrix of two columns." }, { "code": null, "e": 5907, "s": 5879, "text": "The bias matrix is a scalar" }, { "code": null, "e": 5968, "s": 5907, "text": "w2 = np.random.rand(2,1)b2=0output=sigmoid(np.dot(a1,w2)+b2)" }, { "code": null, "e": 6019, "s": 5968, "text": "Then we can plot the output, with the other curves" }, { "code": null, "e": 6180, "s": 6019, "text": "output_seq=sigmoid(np.dot(a1_seq,w2)+b2)plt.scatter(X,y)plt.plot(xseq,a1_seq[:,0],c=”red”)plt.plot(xseq,a1_seq[:,1],c=”blue”)plt.plot(xseq,output_seq,c=”black”)" }, { "code": null, "e": 6241, "s": 6180, "text": "As you can see, the randomly chosen parameters are not good." }, { "code": null, "e": 6281, "s": 6241, "text": "Just to sum up the forward propagation:" }, { "code": null, "e": 6411, "s": 6281, "text": "def feedforward(input,w1,w2,b1,b2): a1 = sigmoid(np.dot(input, w1)+b1) output = sigmoid(np.dot(a1, w2)+b2) return output" }, { "code": null, "e": 6509, "s": 6411, "text": "The suitable parameters are those which minimize the cost function. We can use the cross-entropy:" }, { "code": null, "e": 6542, "s": 6509, "text": "The function can coded as below:" }, { "code": null, "e": 6624, "s": 6542, "text": "def cost(y,output): return -np.sum(y*np.log(output)+(1-y)*np.log(1-output))/12" }, { "code": null, "e": 6772, "s": 6624, "text": "Since there are 7 parameters, visualizing the cost function is not easy. Let’s just choose one of them to vary. For example the first weight in w1." }, { "code": null, "e": 6991, "s": 6772, "text": "b1=np.array([[16.81,-23.41]])w2= np.array([28.8,-52.89])b2=-17.53p = np.linspace(-100,100,10000)for i in range(len(p)): w1=np.array([[p[i],-37.94]]) output=feedforward(X,w1,w2,b1,b2) cost_seq[i]=cost(y,output)" }, { "code": null, "e": 7037, "s": 6991, "text": "And you can see that it is not convex at all." }, { "code": null, "e": 7085, "s": 7037, "text": "And it is also possible to vary two parameters." }, { "code": null, "e": 7164, "s": 7085, "text": "In order to better visualize the cost function, we can also make an animation." }, { "code": null, "e": 7283, "s": 7164, "text": "Now let find some suitable global minimums of this cost function using gradient descent which is call backpropagation." }, { "code": null, "e": 7429, "s": 7283, "text": "Partial derivatives can be ugly, but fortunately, with the cross-entropy as a loss function, there are some simplifications in the final results." }, { "code": null, "e": 7462, "s": 7429, "text": "Here is the cost function again:" }, { "code": null, "e": 7658, "s": 7462, "text": "Please note that when you use the cost function to calculate the cost of a model, then the input variables for this function are the output of the model and the real value of the target variable." }, { "code": null, "e": 7908, "s": 7658, "text": "If we try to find the optimum parameters of the model, then we consider that the input variables for this cost function are these parameters. And we are going to calculate the partial derivatives of the cost function with respect to every parameter." }, { "code": null, "e": 7986, "s": 7908, "text": "For the partial derivative with respect to w1, using the chain rule, we have:" }, { "code": null, "e": 8053, "s": 7986, "text": "First, for the sigmoid function, the derivative can be written as:" }, { "code": null, "e": 8318, "s": 8053, "text": "(Please note that the cost function is a sum of functions, and the partial derivative of a sum of functions is the sum the partial derivates of the functions, so in order to simplify the notation, we will drop the sum symbol, or to be exact, the mean calculation)." }, { "code": null, "e": 8370, "s": 8318, "text": "Let’s first calculate the first two items as below:" }, { "code": null, "e": 8429, "s": 8370, "text": "And we can notice that they can be simplified to (yhat-y)." }, { "code": null, "e": 8471, "s": 8429, "text": "Then we have the final result for the w1:" }, { "code": null, "e": 8567, "s": 8471, "text": "For b1, the expression is quite similar, as the only difference is the last partial derivative:" }, { "code": null, "e": 8702, "s": 8567, "text": "We are going to code the computation with matrix multiplication. Before coding, we can ask ourselves some questions (and answer them):" }, { "code": null, "e": 8844, "s": 8702, "text": "What is the dimension of the residuals (yhat — y)? It is a column vector and the number of rows is equal to the number of total observations." }, { "code": null, "e": 9001, "s": 8844, "text": "What is the dimension of w2? It is a matrix of two rows and one column. Remember, it is the weight matrix for the two hidden neurons, to compute the output." }, { "code": null, "e": 9318, "s": 9001, "text": "What is the dimension of (yhat — y)*w2? Since the dimension w2 is (2,1), we can not do a simple multiplication. What should we do? We can transpose the w1 matrix. Then (yhat — y)*w2 will give us a matrix of two columns and 12 observations. It is perfect because we want to do the computation for each of the weights." }, { "code": null, "e": 9538, "s": 9318, "text": "What is the dimension of a1? It is the results of the hidden layer. Since we have two neurons, a1 has two columns and 12 observations. And the multiplication with the previous matrix will be element-wise multiplication." }, { "code": null, "e": 9808, "s": 9538, "text": "All this is very consistent because, in the end, we will get a matrix of 2 columns and 12 observations. And the first column is associated with the weight of the first neuron, and the second column is associated with the weight of the second neuron in the hidden layer." }, { "code": null, "e": 9830, "s": 9808, "text": "Let’s do some coding:" }, { "code": null, "e": 9874, "s": 9830, "text": "d_b1_v=np.dot((output-y), w2.T) * a1*(1-a1)" }, { "code": null, "e": 9968, "s": 9874, "text": "What does this matrix represent? We can show the partial derivative with respect to b1 again." }, { "code": null, "e": 10209, "s": 9968, "text": "The matrix d_b1_v is the partial derivative for all observations. And to get the final derivatives, we have to calculate the sum of those associated with all observations (remember, L is a sum of functions), and calculate the average value." }, { "code": null, "e": 10237, "s": 10209, "text": "d_b1=np.mean(d_b1_v,axis=0)" }, { "code": null, "e": 10521, "s": 10237, "text": "For w1, we have to take x into account. For each observation, we have to multiply the value obtained by previous partial derivatives by the value of x, then sum them all. This is exactly a dot product. And to obtain the average value, we have to divide by the number of observations." }, { "code": null, "e": 10551, "s": 10521, "text": "d_w1 = np.dot(X.T, d_b1_v)/12" }, { "code": null, "e": 10633, "s": 10551, "text": "Now, let continue for the parameters of the output layer. It will be much easier." }, { "code": null, "e": 10650, "s": 10633, "text": "We already have:" }, { "code": null, "e": 10700, "s": 10650, "text": "So the derivatives with respect to w2 and b2 are:" }, { "code": null, "e": 10742, "s": 10700, "text": "For b2, we just have to sum the residuals" }, { "code": null, "e": 10762, "s": 10742, "text": "np.sum(output-y)/12" }, { "code": null, "e": 10843, "s": 10762, "text": "For w2, it is the dot product between a1 (results of layer 1) and the residuals." }, { "code": null, "e": 10871, "s": 10843, "text": "np.dot(a1.T, (output-y))/12" }, { "code": null, "e": 10971, "s": 10871, "text": "Now we can create a class to include the two steps of forward propagation and backward propagation." }, { "code": null, "e": 11080, "s": 10971, "text": "I used the python code based on this very popular article. You may already have read it. The differences are" }, { "code": null, "e": 11129, "s": 11080, "text": "the loss function (cross-entropy instead of MSE)" }, { "code": null, "e": 11152, "s": 11129, "text": "adding a learning rate" }, { "code": null, "e": 11951, "s": 11152, "text": "class NeuralNetwork: def __init__(self, x, y): self.input = x self.w1 = np.random.rand(self.input.shape[1],2) self.w2 = np.random.rand(2,1) self.b1 = np.zeros(2) self.b2 = 0.0 self.y = y self.output = np.zeros(self.y.shape) def feedforward(self): self.a1 = sigmoid(np.dot(self.input, self.w1)+self.b1) self.output = sigmoid(np.dot(self.a1, self.w2)+self.b2) def backprop(self): lr=0.1 res=self.output-self.y d_w2 = np.dot(self.a1.T, res) d_b2 = np.sum(res) d_b1_v=np.dot(res, self.w2.T) * self.a1*(1-self.a1) d_b1 = np.sum(d_b1_v,axis=0) d_w1 = np.dot(self.input.T, d_b1_v) self.w1 -= d_w1*lr self.w2 -= d_w2*lr self.b1 -= d_b1*lr self.b2 -= d_b2*lr" }, { "code": null, "e": 12073, "s": 11951, "text": "It is then possible to store the intermediate values of the 7 parameters during the gradient descent and plot the curves." }, { "code": null, "e": 12207, "s": 12073, "text": "The animation is made with graphs from R code. So if you are interested in R code of the neural network from scratch, please comment." } ]
The Nth Fibonnaci | Practice | GeeksforGeeks
Given a positive integer N, find the last digit of the Nth term from the Fibonacci series. Note: For N=0 you have to return 0. Example 1: Input: N = 5 Output: 5 Explanation: 5th Fibonacci number is 5 Example 2: Input: N = 14 Output: 7 Explanation: 14th Fibonacci number is 377 It's last digit is 7 Your Task: You don't need to read input or print anything. Your task is to complete the function fib() which takes an integer N as input parameter and returns the last digit of Nth Fibonacci number. Expected Time Complexity: O(N) Expected Space Complexity: O(1) Constraints: 0 <= N <= 1000 0 rohitsinha9692 weeks ago JAVA Solution in 0.12 secs class Solution{ static int fib(int N){ //code here if(N==0){ return 0; } else { int n1=0,n2=1,n3=0; for(int i=0;i<N;i++){ n3=(n1+n2)%10; n2=n1; n1=n3; } return n3; } }} 0 imabhishek023 weeks ago int fib(int n){ if(n==0) return 0; if(n==1) return 1; // if(n==2) //return 1; int a=0; int b=1; int c; for(int i=2;i<=n;i++) { c=(a+b)%10; a=b,b=c; }return c; } 0 imabhishek023 weeks ago whats wrong ,output showing time limit exceed? int fibo(int N){ if(N==0) { return 0; } if(N==1) return 1; int ans=fib(N-2)+fib(N-1); return ans; } int fib(int N){ int k=fibo(N); return k%10; } }; 0 bahubuli1 month ago best optimized approach with time complexity = O(min(N , 61)) space complexity = O(61)... using the concept that after every 60th fibonacci number last digit repeated int fib(int N) { int fib[61]; fib[0] = 0; fib[1] = 1; for(int i=2;i<=min(60,N);i++) { fib[i] = fib[i-1]+fib[i-2]; fib[i] = fib[i]%10; } return fib[N%60]; } 0 moaslam8261 month ago c++ easy soln int fib(int n){ if(n==0) return 0; if(n==1) return 1; if(n==2) return 1; int a=1,b=1,c; for(int i=3;i<=n;i++){ c=(a+b)%10; a=b; b=c; } return c; } +1 badgujarsachin835 months ago int fib(int N){ //code here if(N==1){ return 1; } int a=0,b=1,c=0; int count=2; while(count<=N){ c=(a+b)%10; a=b; b=c; count++; } return c%10; } +1 badgujarsachin835 months ago int fib(int N){ //code here int a=0,b=1,c=0; for(int i=0;i<N;i++){ c=(a+b)%10; b=a; a=c; } return c; } -1 geeknobita7 months ago static int fib(int N){ int n1=0; int n2=1; int n3=0; for(int i=1;i<=N;i++) { n3=(n1+n2)%10; n2=n1; n1=n3; } return n3; } -1 ankitsinha1112008 months ago 0 ankitsinha111200 This comment was deleted. 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": 329, "s": 238, "text": "Given a positive integer N, find the last digit of the Nth term from the Fibonacci series." }, { "code": null, "e": 367, "s": 329, "text": "Note: For N=0 you have to return 0.\n " }, { "code": null, "e": 378, "s": 367, "text": "Example 1:" }, { "code": null, "e": 440, "s": 378, "text": "Input:\nN = 5\nOutput:\n5\nExplanation:\n5th Fibonacci number is 5" }, { "code": null, "e": 451, "s": 440, "text": "Example 2:" }, { "code": null, "e": 539, "s": 451, "text": "Input:\nN = 14\nOutput:\n7\nExplanation:\n14th Fibonacci number is 377\nIt's last digit is 7\n" }, { "code": null, "e": 805, "s": 539, "text": "\nYour Task:\nYou don't need to read input or print anything. Your task is to complete the function fib() which takes an integer N as input parameter and returns the last digit of Nth Fibonacci number.\n\nExpected Time Complexity: O(N)\nExpected Space Complexity: O(1)\n " }, { "code": null, "e": 833, "s": 805, "text": "Constraints:\n0 <= N <= 1000" }, { "code": null, "e": 835, "s": 833, "text": "0" }, { "code": null, "e": 860, "s": 835, "text": "rohitsinha9692 weeks ago" }, { "code": null, "e": 887, "s": 860, "text": "JAVA Solution in 0.12 secs" }, { "code": null, "e": 1158, "s": 887, "text": "class Solution{ static int fib(int N){ //code here if(N==0){ return 0; } else { int n1=0,n2=1,n3=0; for(int i=0;i<N;i++){ n3=(n1+n2)%10; n2=n1; n1=n3; } return n3; } }}" }, { "code": null, "e": 1160, "s": 1158, "text": "0" }, { "code": null, "e": 1184, "s": 1160, "text": "imabhishek023 weeks ago" }, { "code": null, "e": 1493, "s": 1184, "text": " int fib(int n){\n if(n==0)\n return 0;\n \n if(n==1)\n return 1;\n \n // if(n==2)\n //return 1;\n \n int a=0;\n int b=1;\n int c;\n \n for(int i=2;i<=n;i++)\n {\n c=(a+b)%10;\n a=b,b=c;\n }return c;\n }" }, { "code": null, "e": 1495, "s": 1493, "text": "0" }, { "code": null, "e": 1519, "s": 1495, "text": "imabhishek023 weeks ago" }, { "code": null, "e": 1566, "s": 1519, "text": "whats wrong ,output showing time limit exceed?" }, { "code": null, "e": 1788, "s": 1566, "text": "int fibo(int N){\n if(N==0)\n {\n return 0;\n }\n if(N==1)\n return 1;\n \n int ans=fib(N-2)+fib(N-1);\n return ans;\n}\n\n int fib(int N){\n \n int k=fibo(N);\n \n return k%10;\n \n }\n};" }, { "code": null, "e": 1790, "s": 1788, "text": "0" }, { "code": null, "e": 1810, "s": 1790, "text": "bahubuli1 month ago" }, { "code": null, "e": 1980, "s": 1810, "text": "best optimized approach with \ntime complexity = O(min(N , 61))\nspace complexity = O(61)...\nusing the concept that after every 60th \nfibonacci number last digit repeated " }, { "code": null, "e": 2242, "s": 1980, "text": " int fib(int N)\n {\n int fib[61];\n fib[0] = 0;\n fib[1] = 1;\n \n for(int i=2;i<=min(60,N);i++)\n {\n fib[i] = fib[i-1]+fib[i-2];\n fib[i] = fib[i]%10;\n }\n \n return fib[N%60];\n }" }, { "code": null, "e": 2249, "s": 2247, "text": "0" }, { "code": null, "e": 2271, "s": 2249, "text": "moaslam8261 month ago" }, { "code": null, "e": 2285, "s": 2271, "text": "c++ easy soln" }, { "code": null, "e": 2516, "s": 2285, "text": "int fib(int n){\n if(n==0) return 0;\n if(n==1) return 1;\n if(n==2) return 1;\n int a=1,b=1,c;\n for(int i=3;i<=n;i++){\n c=(a+b)%10;\n a=b; b=c;\n }\n return c;\n }" }, { "code": null, "e": 2519, "s": 2516, "text": "+1" }, { "code": null, "e": 2548, "s": 2519, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 2809, "s": 2548, "text": "int fib(int N){\n //code here\n if(N==1){\n return 1;\n }\n int a=0,b=1,c=0;\n int count=2;\n while(count<=N){\n c=(a+b)%10;\n a=b;\n b=c;\n count++;\n }\n return c%10;\n }" }, { "code": null, "e": 2812, "s": 2809, "text": "+1" }, { "code": null, "e": 2841, "s": 2812, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 3024, "s": 2841, "text": "int fib(int N){\n //code here\n int a=0,b=1,c=0;\n for(int i=0;i<N;i++){\n c=(a+b)%10;\n b=a;\n a=c;\n }\n return c;\n }" }, { "code": null, "e": 3027, "s": 3024, "text": "-1" }, { "code": null, "e": 3050, "s": 3027, "text": "geeknobita7 months ago" }, { "code": null, "e": 3267, "s": 3050, "text": "static int fib(int N){\n int n1=0;\n int n2=1;\n int n3=0;\n for(int i=1;i<=N;i++)\n {\n n3=(n1+n2)%10;\n n2=n1;\n n1=n3;\n }\n return n3;\n }" }, { "code": null, "e": 3270, "s": 3267, "text": "-1" }, { "code": null, "e": 3299, "s": 3270, "text": "ankitsinha1112008 months ago" }, { "code": null, "e": 3301, "s": 3299, "text": "0" }, { "code": null, "e": 3318, "s": 3301, "text": "ankitsinha111200" }, { "code": null, "e": 3344, "s": 3318, "text": "This comment was deleted." }, { "code": null, "e": 3490, "s": 3344, "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": 3526, "s": 3490, "text": " Login to access your submissions. " }, { "code": null, "e": 3536, "s": 3526, "text": "\nProblem\n" }, { "code": null, "e": 3546, "s": 3536, "text": "\nContest\n" }, { "code": null, "e": 3609, "s": 3546, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 3757, "s": 3609, "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": 3965, "s": 3757, "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": 4071, "s": 3965, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
Python | Sort list of dates given as strings
14 Dec, 2018 Given a list of dates in string format, write a Python program to sort the list of dates in ascending order. Examples: Input : dates = [“24 Jul 2017”, “25 Jul 2017”, “11 Jun 1996”, “01 Jan 2019”, “12 Aug 2005”, “01 Jan 1997”] Output : 01 Jan 200710 Jul 20162 Dec 201711 Jun 201823 Jun 201801 Jan 2019 Approach:In Python, we can use sort() (for in-place sorting) and sorted() (returns a new sorted list) functions for sorting lists. But by default, these in-built sorting functions will sort the list of strings in alphabetical order which would result in a wrong order in our case. Hence, we need to pass a key argument to tell the sorting function that we need to compare the list items in a particular way and sort them accordingly. In Python, we have the datetime module which makes date based comparison easier. The datetime.strptime() function is used to convert a given string into datetime object. It accepts two arguments: date (string) and format (used to specify the format. for eg: %Y is used for specifying year) and returns a datetime object. Syntax: datetime.strptime(date, format) The formatting that we require for this problem is as follows: %d ---> for Day %b ---> for Month %Y ---> for Year Hence, we need to pass the datetime object as the key argument in the sorting function to tell the sorting function that it needs to compare the strings by converting them into dates and sort them in the increasing order. Below is the implementation of the above approach: # Python3 program to sort the list of dates# given in string format # Import the datetime modulefrom datetime import datetime # Function to print the data stored in the list def printDates(dates): for i in range(len(dates)): print(dates[i]) if __name__ == "__main__": dates = ["23 Jun 2018", "2 Dec 2017", "11 Jun 2018", "01 Jan 2019", "10 Jul 2016", "01 Jan 2007"] # Sort the list in ascending order of dates dates.sort(key = lambda date: datetime.strptime(date, '%d %b %Y')) # Print the dates in a sorted order printDates(dates) 01 Jan 2007 10 Jul 2016 2 Dec 2017 11 Jun 2018 23 Jun 2018 01 Jan 2019 Python string-programs python-string Technical Scripter 2018 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Dec, 2018" }, { "code": null, "e": 137, "s": 28, "text": "Given a list of dates in string format, write a Python program to sort the list of dates in ascending order." }, { "code": null, "e": 147, "s": 137, "text": "Examples:" }, { "code": null, "e": 254, "s": 147, "text": "Input : dates = [“24 Jul 2017”, “25 Jul 2017”, “11 Jun 1996”, “01 Jan 2019”, “12 Aug 2005”, “01 Jan 1997”]" }, { "code": null, "e": 329, "s": 254, "text": "Output : 01 Jan 200710 Jul 20162 Dec 201711 Jun 201823 Jun 201801 Jan 2019" }, { "code": null, "e": 764, "s": 329, "text": " Approach:In Python, we can use sort() (for in-place sorting) and sorted() (returns a new sorted list) functions for sorting lists. But by default, these in-built sorting functions will sort the list of strings in alphabetical order which would result in a wrong order in our case. Hence, we need to pass a key argument to tell the sorting function that we need to compare the list items in a particular way and sort them accordingly." }, { "code": null, "e": 1085, "s": 764, "text": "In Python, we have the datetime module which makes date based comparison easier. The datetime.strptime() function is used to convert a given string into datetime object. It accepts two arguments: date (string) and format (used to specify the format. for eg: %Y is used for specifying year) and returns a datetime object." }, { "code": null, "e": 1093, "s": 1085, "text": "Syntax:" }, { "code": null, "e": 1125, "s": 1093, "text": "datetime.strptime(date, format)" }, { "code": null, "e": 1188, "s": 1125, "text": "The formatting that we require for this problem is as follows:" }, { "code": null, "e": 1240, "s": 1188, "text": "%d ---> for Day\n%b ---> for Month\n%Y ---> for Year\n" }, { "code": null, "e": 1462, "s": 1240, "text": "Hence, we need to pass the datetime object as the key argument in the sorting function to tell the sorting function that it needs to compare the strings by converting them into dates and sort them in the increasing order." }, { "code": null, "e": 1513, "s": 1462, "text": "Below is the implementation of the above approach:" }, { "code": "# Python3 program to sort the list of dates# given in string format # Import the datetime modulefrom datetime import datetime # Function to print the data stored in the list def printDates(dates): for i in range(len(dates)): print(dates[i]) if __name__ == \"__main__\": dates = [\"23 Jun 2018\", \"2 Dec 2017\", \"11 Jun 2018\", \"01 Jan 2019\", \"10 Jul 2016\", \"01 Jan 2007\"] # Sort the list in ascending order of dates dates.sort(key = lambda date: datetime.strptime(date, '%d %b %Y')) # Print the dates in a sorted order printDates(dates) ", "e": 2127, "s": 1513, "text": null }, { "code": null, "e": 2199, "s": 2127, "text": "01 Jan 2007\n10 Jul 2016\n2 Dec 2017\n11 Jun 2018\n23 Jun 2018\n01 Jan 2019\n" }, { "code": null, "e": 2222, "s": 2199, "text": "Python string-programs" }, { "code": null, "e": 2236, "s": 2222, "text": "python-string" }, { "code": null, "e": 2260, "s": 2236, "text": "Technical Scripter 2018" }, { "code": null, "e": 2267, "s": 2260, "text": "Python" }, { "code": null, "e": 2283, "s": 2267, "text": "Python Programs" }, { "code": null, "e": 2302, "s": 2283, "text": "Technical Scripter" } ]
ReadWriteLock Interface in Java
28 Jan, 2021 A lock is a device for commanding access to an assigned resource by multiple threads. Usually, a lock grants exclusive access to a shared resource: just one thread at a flash can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. Though, some locks may allow side-by-side access to a shared resource, as the read lock of a ReadWriteLock. ReadWriteLock is an interface. ReadWriteLock is implemented by ReentrantReadWriteLock Class which is in java.util.concurrent.locks package. So, to use a ReadWriteLock we have to use ReentrantReadWriteLock. A java.util.concurrent.locks.ReadWriteLock is a high-level thread lock tool. It allows various threads to read a specific resource but allows only one to write it, at a time. The approach is, that multiple threads can read from a shared resource without causing concurrency errors. The concurrency errors first occur when writes and reads to a shared resource occur simultaneously, or if multiple writes take place simultaneously. Rules: Read lock and Write lock which allows a thread to lock the ReadWriteLock either for reading or writing. Read lock: If there is no thread that has requested the write lock and the lock for writing, then multiple threads can lock the lock for reading. It means multiple threads can read the data at the very moment, as long as there’s no thread to write the data or to update the data.Write Lock: If no threads are writing or reading, only one thread at a moment can lock the lock for writing. Other threads have to wait until the lock gets released. It means, only one thread can write the data at the very moment, and other threads have to wait. Read lock: If there is no thread that has requested the write lock and the lock for writing, then multiple threads can lock the lock for reading. It means multiple threads can read the data at the very moment, as long as there’s no thread to write the data or to update the data. Write Lock: If no threads are writing or reading, only one thread at a moment can lock the lock for writing. Other threads have to wait until the lock gets released. It means, only one thread can write the data at the very moment, and other threads have to wait. Methods: There are two methods that ReadWritelock provides: Lock readLock()Lock writeLock() Lock readLock() Lock writeLock() Their work is similar to their name. readLock() used to acquire the lock while reading: Lock readLock = rwLock.readLock(); Use the read lock over a code block that performs read operation: Java readLock.lock();try { // statements } finally { readLock.unlock();} And, writeLock() used to acquire the lock while writing: Lock writeLock = rwLock.writeLock(); Use write lock over a code block that performs write operation: Java writeLock.lock();try { statements to write the data} finally { writeLock.unlock();} Implementation: Java // Implementation of ReadWriteLock in Javaimport java.io.*;import java.util.ArrayList;import java.util.List;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;class GFG<O> { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock writeLock = readWriteLock.writeLock(); private final Lock readLock = readWriteLock.readLock(); private final List<O> list = new ArrayList<>(); // setElement function sets // i.e., write the element to the thread public void setElement(O o) { // acquire the thread for writing writeLock.lock(); try { list.add(o); System.out.println( "Element by thread " + Thread.currentThread().getName() + " is added"); } finally { // To unlock the acquired write thread writeLock.unlock(); } } // getElement function prints // i.e., read the element from the thread public O getElement(int i) { // acquire the thread for reading readLock.lock(); try { System.out.println( "Elements by thread " + Thread.currentThread().getName() + " is printed"); return list.get(i); } finally { // To unlock the acquired read thread readLock.unlock(); } } public static void main(String[] args) { GFG<String> gfg = new GFG<>(); gfg.setElement("Hi"); gfg.setElement("Hey"); gfg.setElement("Hello"); System.out.println("Printing the last element : " + gfg.getElement(2)); }} Element by thread main is added Element by thread main is added Element by thread main is added Elements by thread main is printed Printing the last element : Hello Java-concurrent-package java-interfaces Picked Technical Scripter 2020 Java Technical Scripter Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n28 Jan, 2021" }, { "code": null, "e": 445, "s": 54, "text": "A lock is a device for commanding access to an assigned resource by multiple threads. Usually, a lock grants exclusive access to a shared resource: just one thread at a flash can acquire the lock and everyone accesses to the shared resource requires that the lock be acquired first. Though, some locks may allow side-by-side access to a shared resource, as the read lock of a ReadWriteLock." }, { "code": null, "e": 651, "s": 445, "text": "ReadWriteLock is an interface. ReadWriteLock is implemented by ReentrantReadWriteLock Class which is in java.util.concurrent.locks package. So, to use a ReadWriteLock we have to use ReentrantReadWriteLock." }, { "code": null, "e": 826, "s": 651, "text": "A java.util.concurrent.locks.ReadWriteLock is a high-level thread lock tool. It allows various threads to read a specific resource but allows only one to write it, at a time." }, { "code": null, "e": 1082, "s": 826, "text": "The approach is, that multiple threads can read from a shared resource without causing concurrency errors. The concurrency errors first occur when writes and reads to a shared resource occur simultaneously, or if multiple writes take place simultaneously." }, { "code": null, "e": 1089, "s": 1082, "text": "Rules:" }, { "code": null, "e": 1194, "s": 1089, "text": "Read lock and Write lock which allows a thread to lock the ReadWriteLock either for reading or writing. " }, { "code": null, "e": 1736, "s": 1194, "text": "Read lock: If there is no thread that has requested the write lock and the lock for writing, then multiple threads can lock the lock for reading. It means multiple threads can read the data at the very moment, as long as there’s no thread to write the data or to update the data.Write Lock: If no threads are writing or reading, only one thread at a moment can lock the lock for writing. Other threads have to wait until the lock gets released. It means, only one thread can write the data at the very moment, and other threads have to wait." }, { "code": null, "e": 2016, "s": 1736, "text": "Read lock: If there is no thread that has requested the write lock and the lock for writing, then multiple threads can lock the lock for reading. It means multiple threads can read the data at the very moment, as long as there’s no thread to write the data or to update the data." }, { "code": null, "e": 2279, "s": 2016, "text": "Write Lock: If no threads are writing or reading, only one thread at a moment can lock the lock for writing. Other threads have to wait until the lock gets released. It means, only one thread can write the data at the very moment, and other threads have to wait." }, { "code": null, "e": 2339, "s": 2279, "text": "Methods: There are two methods that ReadWritelock provides:" }, { "code": null, "e": 2371, "s": 2339, "text": "Lock readLock()Lock writeLock()" }, { "code": null, "e": 2387, "s": 2371, "text": "Lock readLock()" }, { "code": null, "e": 2404, "s": 2387, "text": "Lock writeLock()" }, { "code": null, "e": 2492, "s": 2404, "text": "Their work is similar to their name. readLock() used to acquire the lock while reading:" }, { "code": null, "e": 2527, "s": 2492, "text": "Lock readLock = rwLock.readLock();" }, { "code": null, "e": 2593, "s": 2527, "text": "Use the read lock over a code block that performs read operation:" }, { "code": null, "e": 2598, "s": 2593, "text": "Java" }, { "code": "readLock.lock();try { // statements } finally { readLock.unlock();}", "e": 2670, "s": 2598, "text": null }, { "code": null, "e": 2729, "s": 2672, "text": "And, writeLock() used to acquire the lock while writing:" }, { "code": null, "e": 2766, "s": 2729, "text": "Lock writeLock = rwLock.writeLock();" }, { "code": null, "e": 2830, "s": 2766, "text": "Use write lock over a code block that performs write operation:" }, { "code": null, "e": 2835, "s": 2830, "text": "Java" }, { "code": "writeLock.lock();try { statements to write the data} finally { writeLock.unlock();}", "e": 2925, "s": 2835, "text": null }, { "code": null, "e": 2943, "s": 2927, "text": "Implementation:" }, { "code": null, "e": 2948, "s": 2943, "text": "Java" }, { "code": "// Implementation of ReadWriteLock in Javaimport java.io.*;import java.util.ArrayList;import java.util.List;import java.util.concurrent.locks.Lock;import java.util.concurrent.locks.ReadWriteLock;import java.util.concurrent.locks.ReentrantReadWriteLock;class GFG<O> { private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock(); private final Lock writeLock = readWriteLock.writeLock(); private final Lock readLock = readWriteLock.readLock(); private final List<O> list = new ArrayList<>(); // setElement function sets // i.e., write the element to the thread public void setElement(O o) { // acquire the thread for writing writeLock.lock(); try { list.add(o); System.out.println( \"Element by thread \" + Thread.currentThread().getName() + \" is added\"); } finally { // To unlock the acquired write thread writeLock.unlock(); } } // getElement function prints // i.e., read the element from the thread public O getElement(int i) { // acquire the thread for reading readLock.lock(); try { System.out.println( \"Elements by thread \" + Thread.currentThread().getName() + \" is printed\"); return list.get(i); } finally { // To unlock the acquired read thread readLock.unlock(); } } public static void main(String[] args) { GFG<String> gfg = new GFG<>(); gfg.setElement(\"Hi\"); gfg.setElement(\"Hey\"); gfg.setElement(\"Hello\"); System.out.println(\"Printing the last element : \" + gfg.getElement(2)); }}", "e": 4749, "s": 2948, "text": null }, { "code": null, "e": 4914, "s": 4749, "text": "Element by thread main is added\nElement by thread main is added\nElement by thread main is added\nElements by thread main is printed\nPrinting the last element : Hello" }, { "code": null, "e": 4938, "s": 4914, "text": "Java-concurrent-package" }, { "code": null, "e": 4954, "s": 4938, "text": "java-interfaces" }, { "code": null, "e": 4961, "s": 4954, "text": "Picked" }, { "code": null, "e": 4985, "s": 4961, "text": "Technical Scripter 2020" }, { "code": null, "e": 4990, "s": 4985, "text": "Java" }, { "code": null, "e": 5009, "s": 4990, "text": "Technical Scripter" }, { "code": null, "e": 5014, "s": 5009, "text": "Java" } ]
Prove that every subgroup of a cyclic group is cyclic
05 Mar, 2021 To Prove :Every subgroup of a cyclic group is cyclic. Cyclic Group :It is a group generated by a single element, and that element is called a generator of that cyclic group, or a cyclic group G is one in which every element is a power of a particular element g, in the group. That is, every element of G can be written as gn for some integer n for a multiplicative group, or ng for some integer n for an additive group. So, g is a generator of group G. Proof :Let us suppose that G is a cyclic group generated by a i.e. G = {a}.If another group H is equal to G or H = {a}, then obviously H is cyclic.So let H be a proper subgroup of G. Therefore, the elements of H will be the integral powers of a.If as ∈ H, then the inverse of as i.e; a-s ∈ H Therefore, H contains elements that are positive as well as negative integral powers of a.Now, let m be the least positive integer such that am ∈ H Then we shall prove that : H = { am } i.e., H is cyclic and is generated by am .Let at be any arbitrary element of H.By division algorithm, there exists integers q and r, such that : t = mq + r, 0 ≤ r <m. Now, am ∈ H ⇢(am)q ∈ H ⇢ amq ∈ H ⇢(amq)-1 ∈ H ⇢a-mq ∈ H. Also, at ∈ H a-mq ∈ H ⇢ at a-mq ∈ H ⇢ at-mq ∈ H ⇢ ar ∈ H. (Since, r = t- mq) Now m is the least positive integer, such that : am ∈ H, 0 ≤ r <m. Therefore, r must be equal to 0.Hence, t = mq Therefore, at = amq =(am)q . Hence, every element at ∈ H is of the form ( am )q .Therefore, H is cyclic and am is a generate of H.Hence, it is proved that every subgroup ( in this case H) of a cyclic group ( G ) is cyclic. Engineering Mathematics GATE CS Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Mar, 2021" }, { "code": null, "e": 82, "s": 28, "text": "To Prove :Every subgroup of a cyclic group is cyclic." }, { "code": null, "e": 481, "s": 82, "text": "Cyclic Group :It is a group generated by a single element, and that element is called a generator of that cyclic group, or a cyclic group G is one in which every element is a power of a particular element g, in the group. That is, every element of G can be written as gn for some integer n for a multiplicative group, or ng for some integer n for an additive group. So, g is a generator of group G." }, { "code": null, "e": 765, "s": 481, "text": "Proof :Let us suppose that G is a cyclic group generated by a i.e. G = {a}.If another group H is equal to G or H = {a}, then obviously H is cyclic.So let H be a proper subgroup of G. Therefore, the elements of H will be the integral powers of a.If as ∈ H, then the inverse of as i.e;" }, { "code": null, "e": 773, "s": 765, "text": "a-s ∈ H" }, { "code": null, "e": 914, "s": 773, "text": "Therefore, H contains elements that are positive as well as negative integral powers of a.Now, let m be the least positive integer such that" }, { "code": null, "e": 921, "s": 914, "text": "am ∈ H" }, { "code": null, "e": 948, "s": 921, "text": "Then we shall prove that :" }, { "code": null, "e": 959, "s": 948, "text": "H = { am }" }, { "code": null, "e": 1104, "s": 959, "text": "i.e., H is cyclic and is generated by am .Let at be any arbitrary element of H.By division algorithm, there exists integers q and r, such that :" }, { "code": null, "e": 1129, "s": 1104, "text": "t = mq + r, 0 ≤ r <m." }, { "code": null, "e": 1134, "s": 1129, "text": "Now," }, { "code": null, "e": 1191, "s": 1134, "text": " am ∈ H \n⇢(am)q ∈ H \n⇢ amq ∈ H\n⇢(amq)-1 ∈ H\n⇢a-mq ∈ H." }, { "code": null, "e": 1214, "s": 1191, "text": "Also, " }, { "code": null, "e": 1295, "s": 1214, "text": "at ∈ H\na-mq ∈ H ⇢ at a-mq ∈ H\n⇢ at-mq ∈ H\n⇢ ar ∈ H. (Since, r = t- mq)" }, { "code": null, "e": 1344, "s": 1295, "text": "Now m is the least positive integer, such that :" }, { "code": null, "e": 1367, "s": 1344, "text": "am ∈ H, 0 ≤ r <m." }, { "code": null, "e": 1407, "s": 1367, "text": "Therefore, r must be equal to 0.Hence, " }, { "code": null, "e": 1435, "s": 1407, "text": " t = mq " }, { "code": null, "e": 1446, "s": 1435, "text": "Therefore," }, { "code": null, "e": 1464, "s": 1446, "text": "at = amq =(am)q ." }, { "code": null, "e": 1660, "s": 1464, "text": "Hence, every element at ∈ H is of the form ( am )q .Therefore, H is cyclic and am is a generate of H.Hence, it is proved that every subgroup ( in this case H) of a cyclic group ( G ) is cyclic. " }, { "code": null, "e": 1684, "s": 1660, "text": "Engineering Mathematics" }, { "code": null, "e": 1692, "s": 1684, "text": "GATE CS" } ]
Matplotlib.pyplot.yscale() in Python
12 Nov, 2020 Matplotlib Is a library in Python and it is a numerical – mathematical extension for the NumPy library. Pyplot Is a state-based interface to a Matplotlib module which provides a MATLAB-like interface. The matplotlib.pyplot.yscale() function in pyplot module of matplotlib library is used to set the y-axis scale. Syntax: matplotlib.pyplot.yscale(value, **kwargs) Parameters: value = { “linear”, “log”, “symlog”, “logit”, ... } These are various axis scale to apply. **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale) Example 1: Python3 import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport time%matplotlib inline # Example 1y = np.random.randn(50)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y)) # plot with various axes scalesplt.figure() # linearplt.subplot(221)plt.plot(x, y)plt.yscale('linear')plt.title('linear')plt.grid(True) # logplt.subplot(222)plt.plot(x, y)plt.yscale('log')plt.title('log')plt.grid(True) plt.show() Output: yscale plots for linear and log Example 2: Python3 import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport time%matplotlib inline # Example 2# useful for `logit` scalefrom matplotlib.ticker import NullFormatter # Fixing random state for reproducibilitynp.random.seed(100) # make up some data in the# interval ]0, 1[y = np.random.normal(loc=0.5, scale=0.4, size=1000)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y)) # plot with various axes scalesplt.figure() # symmetric logplt.subplot(221)plt.plot(x, y - y.mean())plt.yscale('symlog', linthreshy=0.01)plt.title('symlog')plt.grid(True) # logitplt.subplot(222)plt.plot(x, y)plt.yscale('logit')plt.title('logit')plt.grid(True) plt.gca().yaxis.set_minor_formatter(NullFormatter()) # Adjust the subplot layout, because# the logit one may take more space# than usual, due to y-tick labels like "1 - 10^{-3}"plt.subplots_adjust(top=0.80, bottom=0.03, left=0.15, right=0.92, hspace=0.34,wspace=0.45) plt.show() Output: yscale plots for symlog and logit Matplotlib Pyplot-class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n12 Nov, 2020" }, { "code": null, "e": 229, "s": 28, "text": "Matplotlib Is a library in Python and it is a numerical – mathematical extension for the NumPy library. Pyplot Is a state-based interface to a Matplotlib module which provides a MATLAB-like interface." }, { "code": null, "e": 341, "s": 229, "text": "The matplotlib.pyplot.yscale() function in pyplot module of matplotlib library is used to set the y-axis scale." }, { "code": null, "e": 391, "s": 341, "text": "Syntax: matplotlib.pyplot.yscale(value, **kwargs)" }, { "code": null, "e": 403, "s": 391, "text": "Parameters:" }, { "code": null, "e": 455, "s": 403, "text": "value = { “linear”, “log”, “symlog”, “logit”, ... }" }, { "code": null, "e": 494, "s": 455, "text": "These are various axis scale to apply." }, { "code": null, "e": 645, "s": 494, "text": " **kwargs = Different keyword arguments are accepted, depending on the scale (matplotlib.scale.LinearScale, LogScale, SymmetricalLogScale, LogitScale)" }, { "code": null, "e": 656, "s": 645, "text": "Example 1:" }, { "code": null, "e": 664, "s": 656, "text": "Python3" }, { "code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport time%matplotlib inline # Example 1y = np.random.randn(50)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y)) # plot with various axes scalesplt.figure() # linearplt.subplot(221)plt.plot(x, y)plt.yscale('linear')plt.title('linear')plt.grid(True) # logplt.subplot(222)plt.plot(x, y)plt.yscale('log')plt.title('log')plt.grid(True) plt.show()", "e": 1089, "s": 664, "text": null }, { "code": null, "e": 1097, "s": 1089, "text": "Output:" }, { "code": null, "e": 1129, "s": 1097, "text": "yscale plots for linear and log" }, { "code": null, "e": 1140, "s": 1129, "text": "Example 2:" }, { "code": null, "e": 1148, "s": 1140, "text": "Python3" }, { "code": "import numpy as npimport pandas as pdimport matplotlib.pyplot as pltimport time%matplotlib inline # Example 2# useful for `logit` scalefrom matplotlib.ticker import NullFormatter # Fixing random state for reproducibilitynp.random.seed(100) # make up some data in the# interval ]0, 1[y = np.random.normal(loc=0.5, scale=0.4, size=1000)y = y[(y > 0) & (y < 1)]y.sort()x = np.arange(len(y)) # plot with various axes scalesplt.figure() # symmetric logplt.subplot(221)plt.plot(x, y - y.mean())plt.yscale('symlog', linthreshy=0.01)plt.title('symlog')plt.grid(True) # logitplt.subplot(222)plt.plot(x, y)plt.yscale('logit')plt.title('logit')plt.grid(True) plt.gca().yaxis.set_minor_formatter(NullFormatter()) # Adjust the subplot layout, because# the logit one may take more space# than usual, due to y-tick labels like \"1 - 10^{-3}\"plt.subplots_adjust(top=0.80, bottom=0.03, left=0.15, right=0.92, hspace=0.34,wspace=0.45) plt.show()", "e": 2144, "s": 1148, "text": null }, { "code": null, "e": 2152, "s": 2144, "text": "Output:" }, { "code": null, "e": 2186, "s": 2152, "text": "yscale plots for symlog and logit" }, { "code": null, "e": 2210, "s": 2186, "text": "Matplotlib Pyplot-class" }, { "code": null, "e": 2228, "s": 2210, "text": "Python-matplotlib" }, { "code": null, "e": 2235, "s": 2228, "text": "Python" } ]
Python program to find the power of a number using recursion
09 Jun, 2022 Given a number N and power P. The task is to write a Python program to find the power of a number using recursion. Definition: The power of a number can be defined as multiplication of the number repetitively the number of times of its power. Example: Input: N=2 , P=3 Output: 8 Input: N=5 , P=2 Output: 25 Approach: The idea is to calculate power of a number ‘N’ is to multiply that number ‘P’ times i.e In first example N=2 and P=3, we are getting the result by multiplying 2 three times repetitively which gives us output 8. Below is the implementation: Python def power(N, P): # if power is 0 then return 1 # if condition is true # only then it will enter it, # otherwise not if P == 0: # base condition return 1 # recurrence relation return (N*power(N, P-1)) # Driver program N = 5 P = 0 print(power(N, P)) 1 subhajitghosh1997 williammxh simmytarika5 Python function-programs Technical Scripter 2020 Python Python Programs Technical Scripter Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 31, "s": 0, "text": " \n09 Jun, 2022\n" }, { "code": null, "e": 146, "s": 31, "text": "Given a number N and power P. The task is to write a Python program to find the power of a number using recursion." }, { "code": null, "e": 274, "s": 146, "text": "Definition: The power of a number can be defined as multiplication of the number repetitively the number of times of its power." }, { "code": null, "e": 284, "s": 274, "text": "Example: " }, { "code": null, "e": 301, "s": 284, "text": "Input: N=2 , P=3" }, { "code": null, "e": 311, "s": 301, "text": "Output: 8" }, { "code": null, "e": 328, "s": 311, "text": "Input: N=5 , P=2" }, { "code": null, "e": 339, "s": 328, "text": "Output: 25" }, { "code": null, "e": 560, "s": 339, "text": "Approach: The idea is to calculate power of a number ‘N’ is to multiply that number ‘P’ times i.e In first example N=2 and P=3, we are getting the result by multiplying 2 three times repetitively which gives us output 8." }, { "code": null, "e": 589, "s": 560, "text": "Below is the implementation:" }, { "code": null, "e": 596, "s": 589, "text": "Python" }, { "code": "\n\n\n\n\n\n\ndef power(N, P):\n \n # if power is 0 then return 1\n # if condition is true\n # only then it will enter it,\n # otherwise not\n if P == 0: # base condition\n return 1\n \n # recurrence relation\n return (N*power(N, P-1)) \n \n# Driver program\nN = 5\nP = 0\n \nprint(power(N, P))\n\n\n\n\n\n", "e": 918, "s": 606, "text": null }, { "code": null, "e": 920, "s": 918, "text": "1" }, { "code": null, "e": 938, "s": 920, "text": "subhajitghosh1997" }, { "code": null, "e": 949, "s": 938, "text": "williammxh" }, { "code": null, "e": 962, "s": 949, "text": "simmytarika5" }, { "code": null, "e": 989, "s": 962, "text": "\nPython function-programs\n" }, { "code": null, "e": 1015, "s": 989, "text": "\nTechnical Scripter 2020\n" }, { "code": null, "e": 1024, "s": 1015, "text": "\nPython\n" }, { "code": null, "e": 1042, "s": 1024, "text": "\nPython Programs\n" }, { "code": null, "e": 1063, "s": 1042, "text": "\nTechnical Scripter\n" } ]
Python | Pandas Timestamp.days_in_month
08 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 Timestamp.days_in_month attribute return the number of days in the month for the given date in the Timestamp object. Syntax : Timestamp.days_in_month Parameters : None Return : number of days in month Example #1: Use Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(2017, 2, 15, 12) # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object. # return the number of days in monthts.days_in_month Output : As we can see in the output, the Timestamp.days_in_month attribute has returned 28 indicating that there are 28 days in the month of the given Timestamp object. Example #2: Use Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object. # importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 10, day = 21, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts) Output : Now we will use the Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object. # return the number of days in monthts.days_in_month Output : As we can see in the output, the Timestamp.days_in_month attribute has returned 31 indicating that there are 31 days in the month of the given Timestamp object. Python Pandas-Timestamp Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jan, 2019" }, { "code": null, "e": 242, "s": 28, "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": 366, "s": 242, "text": "Pandas Timestamp.days_in_month attribute return the number of days in the month for the given date in the Timestamp object." }, { "code": null, "e": 399, "s": 366, "text": "Syntax : Timestamp.days_in_month" }, { "code": null, "e": 417, "s": 399, "text": "Parameters : None" }, { "code": null, "e": 450, "s": 417, "text": "Return : number of days in month" }, { "code": null, "e": 562, "s": 450, "text": "Example #1: Use Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(2017, 2, 15, 12) # Print the Timestamp objectprint(ts)", "e": 710, "s": 562, "text": null }, { "code": null, "e": 719, "s": 710, "text": "Output :" }, { "code": null, "e": 835, "s": 719, "text": "Now we will use the Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object." }, { "code": "# return the number of days in monthts.days_in_month", "e": 888, "s": 835, "text": null }, { "code": null, "e": 897, "s": 888, "text": "Output :" }, { "code": null, "e": 1058, "s": 897, "text": "As we can see in the output, the Timestamp.days_in_month attribute has returned 28 indicating that there are 28 days in the month of the given Timestamp object." }, { "code": null, "e": 1170, "s": 1058, "text": "Example #2: Use Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object." }, { "code": "# importing pandas as pdimport pandas as pd # Create the Timestamp objectts = pd.Timestamp(year = 2009, month = 10, day = 21, tz = 'Europe/Berlin') # Print the Timestamp objectprint(ts)", "e": 1369, "s": 1170, "text": null }, { "code": null, "e": 1378, "s": 1369, "text": "Output :" }, { "code": null, "e": 1494, "s": 1378, "text": "Now we will use the Timestamp.days_in_month attribute to find out the number of days in the given Timestamp object." }, { "code": "# return the number of days in monthts.days_in_month", "e": 1547, "s": 1494, "text": null }, { "code": null, "e": 1556, "s": 1547, "text": "Output :" }, { "code": null, "e": 1717, "s": 1556, "text": "As we can see in the output, the Timestamp.days_in_month attribute has returned 31 indicating that there are 31 days in the month of the given Timestamp object." }, { "code": null, "e": 1741, "s": 1717, "text": "Python Pandas-Timestamp" }, { "code": null, "e": 1755, "s": 1741, "text": "Python-pandas" }, { "code": null, "e": 1762, "s": 1755, "text": "Python" } ]
How to generate a random, unique, alphanumeric string in PHP
18 Feb, 2022 There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter. Example: PHP <?php // This function will return a random// string of specified lengthfunction random_strings($length_of_string){ // String of all alphanumeric character $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; // Shuffle the $str_result and returns substring // of specified length return substr(str_shuffle($str_result), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo "\n"; // This function will generate// Random string of length 8echo random_strings(8); ?> hnQVgxd4FE 6EsbCc53 Using md5() Function: The md5() function is used to calculate the MD5 hash of a string. Pass timestamp as a argument and md5 function will convert them into 32 bit characters Example: PHP <?php // This function will return a random// string of specified lengthfunction random_strings($length_of_string) { // md5 the timestamps and returns substring // of specified length return substr(md5(time()), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo "\n"; // This function will generate// Random string of length 8echo random_strings(8); ?> 12945f0845 12945f08 Using sha1() Function: This function calculates the sha-1 hash of a string. Pass timestamps as a argument and sha1() function will convert them into sha1- hash.Example: PHP <?php // This function will return // A random string of specified length function random_strings($length_of_string) { // sha1 the timestamps and returns substring // of specified length return substr(sha1(time()), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo "\n"; // This function will generate// Random string of length 8echo random_strings(8); ?> 643f60c52d 643f60c5 Using randon_bytes() Function: This function generates cryptographically secure pseudo-random bytes. It returns a string containing the requested number of cryptographically secure random bytes. Use binehex () function to convert bytes into hexadecimal format.Example: PHP <?php // This function will return// A random string of specified lengthfunction random_strings($length_of_string) { // random_bytes returns number of bytes // bin2hex converts them into hexadecimal format return substr(bin2hex(random_bytes($length_of_string)), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo "\n"; // This function will generate// Random string of length 8echo random_strings(8); ?> 64713970f3 67b575a3 saurabh1990aror surinderdawra388 PHP-string PHP PHP Programs Web Technologies PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to convert array to string in PHP ? PHP | Converting string to Date and DateTime Comparing two dates in PHP Download file from URL using PHP Split a comma delimited string into an array in PHP How to convert array to string in PHP ? How to call PHP function on the click of a Button ? Comparing two dates in PHP Split a comma delimited string into an array in PHP How to fetch data from localserver database and display on HTML table using PHP ?
[ { "code": null, "e": 28, "s": 0, "text": "\n18 Feb, 2022" }, { "code": null, "e": 129, "s": 28, "text": "There are many ways to generate a random, unique, alphanumeric string in PHP which are given below: " }, { "code": null, "e": 631, "s": 129, "text": "Using str_shuffle() Function: The str_shuffle() function is an inbuilt function in PHP and is used to randomly shuffle all the characters of a string passed to the function as a parameter. When a number is passed, it treats the number as the string and shuffles it. This function does not make any change in the original string or the number passed to it as a parameter. Instead, it returns a new string which is one of the possible permutations of the string passed to it in the parameter. Example: " }, { "code": null, "e": 635, "s": 631, "text": "PHP" }, { "code": "<?php // This function will return a random// string of specified lengthfunction random_strings($length_of_string){ // String of all alphanumeric character $str_result = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'; // Shuffle the $str_result and returns substring // of specified length return substr(str_shuffle($str_result), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo \"\\n\"; // This function will generate// Random string of length 8echo random_strings(8); ?>", "e": 1226, "s": 635, "text": null }, { "code": null, "e": 1248, "s": 1228, "text": "hnQVgxd4FE\n6EsbCc53" }, { "code": null, "e": 1436, "s": 1250, "text": "Using md5() Function: The md5() function is used to calculate the MD5 hash of a string. Pass timestamp as a argument and md5 function will convert them into 32 bit characters Example: " }, { "code": null, "e": 1440, "s": 1436, "text": "PHP" }, { "code": "<?php // This function will return a random// string of specified lengthfunction random_strings($length_of_string) { // md5 the timestamps and returns substring // of specified length return substr(md5(time()), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo \"\\n\"; // This function will generate// Random string of length 8echo random_strings(8); ?>", "e": 1869, "s": 1440, "text": null }, { "code": null, "e": 1891, "s": 1871, "text": "12945f0845\n12945f08" }, { "code": null, "e": 2064, "s": 1893, "text": "Using sha1() Function: This function calculates the sha-1 hash of a string. Pass timestamps as a argument and sha1() function will convert them into sha1- hash.Example: " }, { "code": null, "e": 2068, "s": 2064, "text": "PHP" }, { "code": "<?php // This function will return // A random string of specified length function random_strings($length_of_string) { // sha1 the timestamps and returns substring // of specified length return substr(sha1(time()), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo \"\\n\"; // This function will generate// Random string of length 8echo random_strings(8); ?>", "e": 2513, "s": 2068, "text": null }, { "code": null, "e": 2535, "s": 2515, "text": "643f60c52d\n643f60c5" }, { "code": null, "e": 2808, "s": 2537, "text": "Using randon_bytes() Function: This function generates cryptographically secure pseudo-random bytes. It returns a string containing the requested number of cryptographically secure random bytes. Use binehex () function to convert bytes into hexadecimal format.Example: " }, { "code": null, "e": 2812, "s": 2808, "text": "PHP" }, { "code": "<?php // This function will return// A random string of specified lengthfunction random_strings($length_of_string) { // random_bytes returns number of bytes // bin2hex converts them into hexadecimal format return substr(bin2hex(random_bytes($length_of_string)), 0, $length_of_string);} // This function will generate// Random string of length 10echo random_strings(10); echo \"\\n\"; // This function will generate// Random string of length 8echo random_strings(8); ?>", "e": 3325, "s": 2812, "text": null }, { "code": null, "e": 3347, "s": 3327, "text": "64713970f3\n67b575a3" }, { "code": null, "e": 3367, "s": 3351, "text": "saurabh1990aror" }, { "code": null, "e": 3384, "s": 3367, "text": "surinderdawra388" }, { "code": null, "e": 3395, "s": 3384, "text": "PHP-string" }, { "code": null, "e": 3399, "s": 3395, "text": "PHP" }, { "code": null, "e": 3412, "s": 3399, "text": "PHP Programs" }, { "code": null, "e": 3429, "s": 3412, "text": "Web Technologies" }, { "code": null, "e": 3433, "s": 3429, "text": "PHP" }, { "code": null, "e": 3531, "s": 3433, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3571, "s": 3531, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3616, "s": 3571, "text": "PHP | Converting string to Date and DateTime" }, { "code": null, "e": 3643, "s": 3616, "text": "Comparing two dates in PHP" }, { "code": null, "e": 3676, "s": 3643, "text": "Download file from URL using PHP" }, { "code": null, "e": 3728, "s": 3676, "text": "Split a comma delimited string into an array in PHP" }, { "code": null, "e": 3768, "s": 3728, "text": "How to convert array to string in PHP ?" }, { "code": null, "e": 3820, "s": 3768, "text": "How to call PHP function on the click of a Button ?" }, { "code": null, "e": 3847, "s": 3820, "text": "Comparing two dates in PHP" }, { "code": null, "e": 3899, "s": 3847, "text": "Split a comma delimited string into an array in PHP" } ]
Matplotlib.axis.Axis.set_data_interval() function in Python
08 Jun, 2020 Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack. The Axis.set_data_interval() function in axis module of matplotlib library is used to set the axis data limits. This method is for internal use. Syntax: Axis.set_data_interval(self, vmin, vmax, ignore=False) Parameters: This method accepts the following parameters. vmin: This parameter is the minimum data limit. vmax: This parameter is the maximum data limit. Return value: This method returns does not any value. Below examples illustrate the matplotlib.axis.Axis.set_data_interval() function in matplotlib.axis: Example 1: Python3 # Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure() x = np.linspace(0,4*np.pi,100)y = 2*np.sin(x) ax = fig.add_subplot()ax.plot(x,y) ax.xaxis.set_data_interval(2, 4 ,True) ax.grid() fig.suptitle("""matplotlib.axis.Axis.set_data_interval()function Example\n""", fontweight ="bold") plt.show() Output: Example 2: Python3 # Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7) geeks = np.random.randn(40) fig, ax = plt.subplots() ax.acorr(geeks, usevlines = True, normed = True,lw = 3) ax.grid(True) ax.xaxis.set_data_interval(-10 , 10) fig.suptitle("""matplotlib.axis.Axis.set_data_interval()function Example\n""", fontweight ="bold") plt.show() Output: Matplotlib-Axis Class Python-matplotlib Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n08 Jun, 2020" }, { "code": null, "e": 249, "s": 28, "text": "Matplotlib is a library in Python and it is numerical – mathematical extension for NumPy library. It is an amazing visualization library in Python for 2D plots of arrays and used for working with the broader SciPy stack." }, { "code": null, "e": 395, "s": 249, "text": "The Axis.set_data_interval() function in axis module of matplotlib library is used to set the axis data limits. This method is for internal use. " }, { "code": null, "e": 460, "s": 395, "text": "Syntax: Axis.set_data_interval(self, vmin, vmax, ignore=False) " }, { "code": null, "e": 519, "s": 460, "text": "Parameters: This method accepts the following parameters. " }, { "code": null, "e": 567, "s": 519, "text": "vmin: This parameter is the minimum data limit." }, { "code": null, "e": 615, "s": 567, "text": "vmax: This parameter is the maximum data limit." }, { "code": null, "e": 670, "s": 615, "text": "Return value: This method returns does not any value. " }, { "code": null, "e": 771, "s": 670, "text": "Below examples illustrate the matplotlib.axis.Axis.set_data_interval() function in matplotlib.axis: " }, { "code": null, "e": 782, "s": 771, "text": "Example 1:" }, { "code": null, "e": 790, "s": 782, "text": "Python3" }, { "code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np fig = plt.figure() x = np.linspace(0,4*np.pi,100)y = 2*np.sin(x) ax = fig.add_subplot()ax.plot(x,y) ax.xaxis.set_data_interval(2, 4 ,True) ax.grid() fig.suptitle(\"\"\"matplotlib.axis.Axis.set_data_interval()function Example\\n\"\"\", fontweight =\"bold\") plt.show()", "e": 1189, "s": 790, "text": null }, { "code": null, "e": 1199, "s": 1189, "text": "Output: " }, { "code": null, "e": 1210, "s": 1199, "text": "Example 2:" }, { "code": null, "e": 1218, "s": 1210, "text": "Python3" }, { "code": "# Implementation of matplotlib functionfrom matplotlib.axis import Axisimport matplotlib.pyplot as pltimport numpy as np np.random.seed(10**7) geeks = np.random.randn(40) fig, ax = plt.subplots() ax.acorr(geeks, usevlines = True, normed = True,lw = 3) ax.grid(True) ax.xaxis.set_data_interval(-10 , 10) fig.suptitle(\"\"\"matplotlib.axis.Axis.set_data_interval()function Example\\n\"\"\", fontweight =\"bold\") plt.show()", "e": 1672, "s": 1218, "text": null }, { "code": null, "e": 1682, "s": 1672, "text": "Output: " }, { "code": null, "e": 1706, "s": 1684, "text": "Matplotlib-Axis Class" }, { "code": null, "e": 1724, "s": 1706, "text": "Python-matplotlib" }, { "code": null, "e": 1731, "s": 1724, "text": "Python" } ]
Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
28 Jun, 2021 Pointers store address of variables or a memory location. // General syntax datatype *var_name; // An example pointer "ptr" that holds // address of an integer variable or holds // address of a memory whose value(s) can // be accessed as integer values through "ptr" int *ptr; Using a Pointer: To use pointers in C, we must understand below two operators. To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x. C // The output of this program can be different// in different runs. Note that the program// prints address of a variable and a variable// can be assigned different address in different// runs.#include <stdio.h> int main(){ int x; // Prints address of x printf("%p", &x); return 0;} One more operator is unary * (Asterisk) which is used for two things : To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name. To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name. C // C program to demonstrate declaration of// pointer variables.#include <stdio.h>int main(){ int x = 10; // 1) Since there is * in declaration, ptr // becomes a pointer variable (a variable // that stores address of another variable) // 2) Since there is int before *, ptr is // pointer to an integer type variable int *ptr; // & operator before x is used to get address // of x. The address of x is assigned to ptr. ptr = &x; return 0;} To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing. C++ C // C++ program to demonstrate use of * for pointers in C++#include <iostream>using namespace std; int main(){ // A normal integer variable int Var = 10; // A pointer variable that holds address of var. int *ptr = &Var; // This line prints value at address stored in ptr. // Value stored is value of variable "var" cout << "Value of Var = "<< *ptr << endl; // The output of this line may be different in different // runs even on same machine. cout << "Address of Var = " << ptr << endl; // We can also use ptr as lvalue (Left hand // side of assignment) *ptr = 20; // Value at address is now 20 // This prints 20 cout << "After doing *ptr = 20, *ptr is "<< *ptr << endl; return 0;} // This code is contributed by// shubhamsingh10 // C program to demonstrate use of * for pointers in C#include <stdio.h> int main(){ // A normal integer variable int Var = 10; // A pointer variable that holds address of var. int *ptr = &Var; // This line prints value at address stored in ptr. // Value stored is value of variable "var" printf("Value of Var = %d\n", *ptr); // The output of this line may be different in different // runs even on same machine. printf("Address of Var = %p\n", ptr); // We can also use ptr as lvalue (Left hand // side of assignment) *ptr = 20; // Value at address is now 20 // This prints 20 printf("After doing *ptr = 20, *ptr is %d\n", *ptr); return 0;} Output : Value of Var = 10 Address of Var = 0x7fffa057dd4 After doing *ptr = 20, *ptr is 20 Below is pictorial representation of above program: 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. Pointer Expressions and Pointer Arithmetic A limited set of arithmetic operations can be performed on pointers. A pointer may be: incremented ( ++ ) decremented ( — ) an integer may be added to a pointer ( + or += ) an integer may be subtracted from a pointer ( – or -= ) Pointer arithmetic is meaningless unless performed on an array. Note : Pointers contain addresses. Adding two addresses makes no sense, because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between these two addresses. CPP // C++ program to illustrate Pointer Arithmetic// in C/C++#include <bits/stdc++.h> // Driver programint main(){ // Declare an array int v[3] = {10, 100, 200}; // Declare pointer variable int *ptr; // Assign the address of v[0] to ptr ptr = v; for (int i = 0; i < 3; i++) { printf("Value of *ptr = %d\n", *ptr); printf("Value of ptr = %p\n\n", ptr); // Increment pointer ptr by 1 ptr++; }} Output:Value of *ptr = 10 Value of ptr = 0x7ffcae30c710 Value of *ptr = 100 Value of ptr = 0x7ffcae30c714 Value of *ptr = 200 Value of ptr = 0x7ffcae30c718 Array Name as Pointers An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably. CPP // C++ program to illustrate Array Name as Pointers in C++#include <bits/stdc++.h>using namespace std; void geeks(){ // Declare an array int val[3] = { 5, 10, 15}; // Declare pointer variable int *ptr; // Assign address of val[0] to ptr. // We can use ptr=&val[0];(both are same) ptr = val ; cout << "Elements of the array are: "; cout << ptr[0] << " " << ptr[1] << " " << ptr[2]; return;} // Driver programint main(){ geeks(); return 0;} Output: Elements of the array are: 5 10 15 Now if this ptr is sent to a function as an argument then the array val can be accessed in a similar fashion. Pointers and Multidimensional Arrays Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration int nums[2][3] = { {16, 18, 20}, {25, 26, 27} }; In general, nums[i][j] is equivalent to *(*(nums+i)+j) Applications of pointers in C/C++. Quizzes – Quiz on Pointer Basics , Quiz on Advanced PointerReference: https://www.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReference.htmlThis article is contributed by Abhirav Kariya. 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. SagarUdasi Prasant Nair Cricket Research SHUBHAMSINGH10 rutujak arorakashish0911 C-Pointers CPP-Basics cpp-pointer Pointers C Language C++ School Programming Pointers CPP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2021" }, { "code": null, "e": 112, "s": 52, "text": "Pointers store address of variables or a memory location. " }, { "code": null, "e": 335, "s": 112, "text": "// General syntax\ndatatype *var_name; \n\n// An example pointer \"ptr\" that holds\n// address of an integer variable or holds\n// address of a memory whose value(s) can\n// be accessed as integer values through \"ptr\"\nint *ptr; " }, { "code": null, "e": 353, "s": 335, "text": "Using a Pointer: " }, { "code": null, "e": 417, "s": 353, "text": "To use pointers in C, we must understand below two operators. " }, { "code": null, "e": 595, "s": 417, "text": "To access address of a variable to a pointer, we use the unary operator & (ampersand) that returns the address of that variable. For example &x gives us address of variable x. " }, { "code": null, "e": 597, "s": 595, "text": "C" }, { "code": "// The output of this program can be different// in different runs. Note that the program// prints address of a variable and a variable// can be assigned different address in different// runs.#include <stdio.h> int main(){ int x; // Prints address of x printf(\"%p\", &x); return 0;}", "e": 893, "s": 597, "text": null }, { "code": null, "e": 1080, "s": 895, "text": "One more operator is unary * (Asterisk) which is used for two things : To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name. " }, { "code": null, "e": 1194, "s": 1080, "text": "To declare a pointer variable: When a pointer variable is declared in C/C++, there must be a * before its name. " }, { "code": null, "e": 1196, "s": 1194, "text": "C" }, { "code": "// C program to demonstrate declaration of// pointer variables.#include <stdio.h>int main(){ int x = 10; // 1) Since there is * in declaration, ptr // becomes a pointer variable (a variable // that stores address of another variable) // 2) Since there is int before *, ptr is // pointer to an integer type variable int *ptr; // & operator before x is used to get address // of x. The address of x is assigned to ptr. ptr = &x; return 0;}", "e": 1670, "s": 1196, "text": null }, { "code": null, "e": 1866, "s": 1670, "text": "To access the value stored in the address we use the unary operator (*) that returns the value of the variable located at the address specified by its operand. This is also called Dereferencing. " }, { "code": null, "e": 1870, "s": 1866, "text": "C++" }, { "code": null, "e": 1872, "s": 1870, "text": "C" }, { "code": "// C++ program to demonstrate use of * for pointers in C++#include <iostream>using namespace std; int main(){ // A normal integer variable int Var = 10; // A pointer variable that holds address of var. int *ptr = &Var; // This line prints value at address stored in ptr. // Value stored is value of variable \"var\" cout << \"Value of Var = \"<< *ptr << endl; // The output of this line may be different in different // runs even on same machine. cout << \"Address of Var = \" << ptr << endl; // We can also use ptr as lvalue (Left hand // side of assignment) *ptr = 20; // Value at address is now 20 // This prints 20 cout << \"After doing *ptr = 20, *ptr is \"<< *ptr << endl; return 0;} // This code is contributed by// shubhamsingh10", "e": 2657, "s": 1872, "text": null }, { "code": "// C program to demonstrate use of * for pointers in C#include <stdio.h> int main(){ // A normal integer variable int Var = 10; // A pointer variable that holds address of var. int *ptr = &Var; // This line prints value at address stored in ptr. // Value stored is value of variable \"var\" printf(\"Value of Var = %d\\n\", *ptr); // The output of this line may be different in different // runs even on same machine. printf(\"Address of Var = %p\\n\", ptr); // We can also use ptr as lvalue (Left hand // side of assignment) *ptr = 20; // Value at address is now 20 // This prints 20 printf(\"After doing *ptr = 20, *ptr is %d\\n\", *ptr); return 0;}", "e": 3352, "s": 2657, "text": null }, { "code": null, "e": 3362, "s": 3352, "text": "Output : " }, { "code": null, "e": 3445, "s": 3362, "text": "Value of Var = 10\nAddress of Var = 0x7fffa057dd4\nAfter doing *ptr = 20, *ptr is 20" }, { "code": null, "e": 3499, "s": 3445, "text": "Below is pictorial representation of above program: " }, { "code": null, "e": 3508, "s": 3499, "text": "Chapters" }, { "code": null, "e": 3535, "s": 3508, "text": "descriptions off, selected" }, { "code": null, "e": 3585, "s": 3535, "text": "captions settings, opens captions settings dialog" }, { "code": null, "e": 3608, "s": 3585, "text": "captions off, selected" }, { "code": null, "e": 3616, "s": 3608, "text": "English" }, { "code": null, "e": 3640, "s": 3616, "text": "This is a modal window." }, { "code": null, "e": 3709, "s": 3640, "text": "Beginning of dialog window. Escape will cancel and close the window." }, { "code": null, "e": 3731, "s": 3709, "text": "End of dialog window." }, { "code": null, "e": 3864, "s": 3731, "text": " Pointer Expressions and Pointer Arithmetic A limited set of arithmetic operations can be performed on pointers. A pointer may be: " }, { "code": null, "e": 3883, "s": 3864, "text": "incremented ( ++ )" }, { "code": null, "e": 3901, "s": 3883, "text": "decremented ( — )" }, { "code": null, "e": 3950, "s": 3901, "text": "an integer may be added to a pointer ( + or += )" }, { "code": null, "e": 4006, "s": 3950, "text": "an integer may be subtracted from a pointer ( – or -= )" }, { "code": null, "e": 4275, "s": 4006, "text": "Pointer arithmetic is meaningless unless performed on an array. Note : Pointers contain addresses. Adding two addresses makes no sense, because there is no idea what it would point to. Subtracting two addresses lets you compute the offset between these two addresses. " }, { "code": null, "e": 4279, "s": 4275, "text": "CPP" }, { "code": "// C++ program to illustrate Pointer Arithmetic// in C/C++#include <bits/stdc++.h> // Driver programint main(){ // Declare an array int v[3] = {10, 100, 200}; // Declare pointer variable int *ptr; // Assign the address of v[0] to ptr ptr = v; for (int i = 0; i < 3; i++) { printf(\"Value of *ptr = %d\\n\", *ptr); printf(\"Value of ptr = %p\\n\\n\", ptr); // Increment pointer ptr by 1 ptr++; }}", "e": 4727, "s": 4279, "text": null }, { "code": null, "e": 4885, "s": 4727, "text": "Output:Value of *ptr = 10\nValue of ptr = 0x7ffcae30c710\n\nValue of *ptr = 100\nValue of ptr = 0x7ffcae30c714\n\nValue of *ptr = 200\nValue of ptr = 0x7ffcae30c718" }, { "code": null, "e": 5120, "s": 4885, "text": " Array Name as Pointers An array name acts like a pointer constant. The value of this pointer constant is the address of the first element. For example, if we have an array named val then val and &val[0] can be used interchangeably. " }, { "code": null, "e": 5124, "s": 5120, "text": "CPP" }, { "code": "// C++ program to illustrate Array Name as Pointers in C++#include <bits/stdc++.h>using namespace std; void geeks(){ // Declare an array int val[3] = { 5, 10, 15}; // Declare pointer variable int *ptr; // Assign address of val[0] to ptr. // We can use ptr=&val[0];(both are same) ptr = val ; cout << \"Elements of the array are: \"; cout << ptr[0] << \" \" << ptr[1] << \" \" << ptr[2]; return;} // Driver programint main(){ geeks(); return 0;}", "e": 5602, "s": 5124, "text": null }, { "code": null, "e": 5645, "s": 5602, "text": "Output:\nElements of the array are: 5 10 15" }, { "code": null, "e": 5896, "s": 5645, "text": "Now if this ptr is sent to a function as an argument then the array val can be accessed in a similar fashion. Pointers and Multidimensional Arrays Consider pointer notation for the two-dimensional numeric arrays. consider the following declaration " }, { "code": null, "e": 5947, "s": 5896, "text": "int nums[2][3] = { {16, 18, 20}, {25, 26, 27} };" }, { "code": null, "e": 6002, "s": 5947, "text": "In general, nums[i][j] is equivalent to *(*(nums+i)+j)" }, { "code": null, "e": 6611, "s": 6006, "text": "Applications of pointers in C/C++. Quizzes – Quiz on Pointer Basics , Quiz on Advanced PointerReference: https://www.ntu.edu.sg/home/ehchua/programming/cpp/cp4_PointerReference.htmlThis article is contributed by Abhirav Kariya. 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": 6624, "s": 6613, "text": "SagarUdasi" }, { "code": null, "e": 6654, "s": 6624, "text": "Prasant Nair Cricket Research" }, { "code": null, "e": 6669, "s": 6654, "text": "SHUBHAMSINGH10" }, { "code": null, "e": 6677, "s": 6669, "text": "rutujak" }, { "code": null, "e": 6694, "s": 6677, "text": "arorakashish0911" }, { "code": null, "e": 6705, "s": 6694, "text": "C-Pointers" }, { "code": null, "e": 6716, "s": 6705, "text": "CPP-Basics" }, { "code": null, "e": 6728, "s": 6716, "text": "cpp-pointer" }, { "code": null, "e": 6737, "s": 6728, "text": "Pointers" }, { "code": null, "e": 6748, "s": 6737, "text": "C Language" }, { "code": null, "e": 6752, "s": 6748, "text": "C++" }, { "code": null, "e": 6771, "s": 6752, "text": "School Programming" }, { "code": null, "e": 6780, "s": 6771, "text": "Pointers" }, { "code": null, "e": 6784, "s": 6780, "text": "CPP" } ]
HashMap forEach(BiConsumer) method in Java with Examples
11 Oct, 2019 The forEach(BiConsumer) method of HashMap class perform the BiConsumer operation on each entry of hashmap until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of the key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until all elements have been processed by the method or an exception occurs. Exceptions thrown by the Operation are passed to the caller. Syntax: public void forEach(BiConsumer action) Parameters: This method accepts a parameter action of BiConsumer type that represents what action are to be performed on the HashMap elements. Returns: This method do not return anything. Exceptions: This method throws NullPointerException if the action is null. Below programs illustrate the forEach(BiConsumer) method: Program 1: to traverse a hashmap using action // Java program to demonstrate// forEach(BiConsumer) method. import java.util.HashMap;import java.util.Map;import java.util.function.BiConsumer; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values Map<String, Integer> map = new HashMap<>(); map.put("geeks", 55); map.put("for", 13); map.put("geeks", 22); map.put("is", 11); map.put("heaven", 90); map.put("for", 100); map.put("geekies like us", 96); // creating a custom action BiConsumer<String, Integer> action = new MyBiConsumer(); // calling forEach method map.forEach(action); }} // Defining Our Action in MyBiConsumer classclass MyBiConsumer implements BiConsumer<String, Integer> { public void accept(String k, Integer v) { System.out.print("Key = " + k); System.out.print("\t Value = " + v); System.out.println(); }} Key = geeks Value = 22 Key = for Value = 100 Key = is Value = 11 Key = heaven Value = 90 Key = geekies like us Value = 96 Program 2: // Java program to demonstrate// forEach(BiConsumer) method. import java.util.HashMap;import java.util.Map;import java.util.function.BiConsumer; public class GFG { // Main method public static void main(String[] args) { // Create a HashMap // and add some values Map<String, Integer> map = new HashMap<>(); map.put("geeks", 55); map.put("for", 13); map.put("geeks", 22); map.put("is", 11); map.put("heaven", 90); map.put("for", 100); map.put("geekies like us", 96); // creating an action BiConsumer<String, Integer> action = new MyBiConsumer(); // calling forEach method map.forEach(action); }} // Defining Our Action in MyBiConsumer classclass MyBiConsumer implements BiConsumer<String, Integer> { public void accept(String k, Integer v) { System.out.println("Key: " + k + "\tValue: " + v); if ("for".equals(k)) { System.out.println("Its the " + "highest value\n"); } }} Key: geeks Value: 22 Key: for Value: 100 Its the highest value Key: is Value: 11 Key: heaven Value: 90 Key: geekies like us Value: 96 Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#forEach-java.util.function.BiConsumer- Java - util package Java-Functions Java-HashMap Picked Java Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Object Oriented Programming (OOPs) Concept in Java How to iterate any Map in Java Interfaces in Java HashMap in Java with Examples ArrayList in Java Collections in Java Multidimensional Arrays in Java Singleton Class in Java Set in Java Initializing a List in Java
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Oct, 2019" }, { "code": null, "e": 509, "s": 28, "text": "The forEach(BiConsumer) method of HashMap class perform the BiConsumer operation on each entry of hashmap until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of the key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until all elements have been processed by the method or an exception occurs. Exceptions thrown by the Operation are passed to the caller." }, { "code": null, "e": 517, "s": 509, "text": "Syntax:" }, { "code": null, "e": 556, "s": 517, "text": "public void forEach(BiConsumer action)" }, { "code": null, "e": 699, "s": 556, "text": "Parameters: This method accepts a parameter action of BiConsumer type that represents what action are to be performed on the HashMap elements." }, { "code": null, "e": 744, "s": 699, "text": "Returns: This method do not return anything." }, { "code": null, "e": 819, "s": 744, "text": "Exceptions: This method throws NullPointerException if the action is null." }, { "code": null, "e": 877, "s": 819, "text": "Below programs illustrate the forEach(BiConsumer) method:" }, { "code": null, "e": 923, "s": 877, "text": "Program 1: to traverse a hashmap using action" }, { "code": "// Java program to demonstrate// forEach(BiConsumer) method. import java.util.HashMap;import java.util.Map;import java.util.function.BiConsumer; public class GFG { // Main method public static void main(String[] args) { // create a HashMap and add some values Map<String, Integer> map = new HashMap<>(); map.put(\"geeks\", 55); map.put(\"for\", 13); map.put(\"geeks\", 22); map.put(\"is\", 11); map.put(\"heaven\", 90); map.put(\"for\", 100); map.put(\"geekies like us\", 96); // creating a custom action BiConsumer<String, Integer> action = new MyBiConsumer(); // calling forEach method map.forEach(action); }} // Defining Our Action in MyBiConsumer classclass MyBiConsumer implements BiConsumer<String, Integer> { public void accept(String k, Integer v) { System.out.print(\"Key = \" + k); System.out.print(\"\\t Value = \" + v); System.out.println(); }}", "e": 1931, "s": 923, "text": null }, { "code": null, "e": 2074, "s": 1931, "text": "Key = geeks Value = 22\nKey = for Value = 100\nKey = is Value = 11\nKey = heaven Value = 90\nKey = geekies like us Value = 96\n" }, { "code": null, "e": 2085, "s": 2074, "text": "Program 2:" }, { "code": "// Java program to demonstrate// forEach(BiConsumer) method. import java.util.HashMap;import java.util.Map;import java.util.function.BiConsumer; public class GFG { // Main method public static void main(String[] args) { // Create a HashMap // and add some values Map<String, Integer> map = new HashMap<>(); map.put(\"geeks\", 55); map.put(\"for\", 13); map.put(\"geeks\", 22); map.put(\"is\", 11); map.put(\"heaven\", 90); map.put(\"for\", 100); map.put(\"geekies like us\", 96); // creating an action BiConsumer<String, Integer> action = new MyBiConsumer(); // calling forEach method map.forEach(action); }} // Defining Our Action in MyBiConsumer classclass MyBiConsumer implements BiConsumer<String, Integer> { public void accept(String k, Integer v) { System.out.println(\"Key: \" + k + \"\\tValue: \" + v); if (\"for\".equals(k)) { System.out.println(\"Its the \" + \"highest value\\n\"); } }}", "e": 3203, "s": 2085, "text": null }, { "code": null, "e": 3354, "s": 3203, "text": "Key: geeks Value: 22\nKey: for Value: 100\nIts the highest value\n\nKey: is Value: 11\nKey: heaven Value: 90\nKey: geekies like us Value: 96\n" }, { "code": null, "e": 3469, "s": 3354, "text": "Reference: https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html#forEach-java.util.function.BiConsumer-" }, { "code": null, "e": 3489, "s": 3469, "text": "Java - util package" }, { "code": null, "e": 3504, "s": 3489, "text": "Java-Functions" }, { "code": null, "e": 3517, "s": 3504, "text": "Java-HashMap" }, { "code": null, "e": 3524, "s": 3517, "text": "Picked" }, { "code": null, "e": 3529, "s": 3524, "text": "Java" }, { "code": null, "e": 3534, "s": 3529, "text": "Java" }, { "code": null, "e": 3632, "s": 3534, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3683, "s": 3632, "text": "Object Oriented Programming (OOPs) Concept in Java" }, { "code": null, "e": 3714, "s": 3683, "text": "How to iterate any Map in Java" }, { "code": null, "e": 3733, "s": 3714, "text": "Interfaces in Java" }, { "code": null, "e": 3763, "s": 3733, "text": "HashMap in Java with Examples" }, { "code": null, "e": 3781, "s": 3763, "text": "ArrayList in Java" }, { "code": null, "e": 3801, "s": 3781, "text": "Collections in Java" }, { "code": null, "e": 3833, "s": 3801, "text": "Multidimensional Arrays in Java" }, { "code": null, "e": 3857, "s": 3833, "text": "Singleton Class in Java" }, { "code": null, "e": 3869, "s": 3857, "text": "Set in Java" } ]
Working with zip files in Python
22 Jul, 2021 This article explains how one can perform various operations on a zip file using a simple python program. What is a zip file? ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together. Why do we need zip files? To reduce storage requirements. To improve transfer speed over standard connections. To work on zip files using python, we will use an inbuilt python module called zipfile. 1. Extracting a zip file # importing required modulesfrom zipfile import ZipFile # specifying the zip file namefile_name = "my_python_files.zip" # opening the zip file in READ modewith ZipFile(file_name, 'r') as zip: # printing all the contents of the zip file zip.printdir() # extracting all the files print('Extracting all the files now...') zip.extractall() print('Done!') The above program extracts a zip file named “my_python_files.zip” in the same directory as of this python script.The output of above program may look like this: Let us try to understand the above code in pieces: from zipfile import ZipFileZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module. from zipfile import ZipFile ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module. with ZipFile(file_name, 'r') as zip:Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in READ mode and name it as zip. with ZipFile(file_name, 'r') as zip: Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in READ mode and name it as zip. zip.printdir()printdir() method prints a table of contents for the archive. zip.printdir() printdir() method prints a table of contents for the archive. zip.extractall()extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.For example:zip.extract('python_files/python_wiki.txt')This will extract only the specified file.If you want to read some specific file, you can go like this:data = zip.read(name_of_file_to_read) zip.extractall() extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.For example: zip.extract('python_files/python_wiki.txt') This will extract only the specified file. If you want to read some specific file, you can go like this: data = zip.read(name_of_file_to_read) 2. Writing to a zip file Consider a directory (folder) with such a format: Here, we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file.The following program does this by crawling the directory to be zipped: # importing required modulesfrom zipfile import ZipFileimport os def get_all_file_paths(directory): # initializing empty file paths list file_paths = [] # crawling through directory and subdirectories for root, directories, files in os.walk(directory): for filename in files: # join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # returning all file paths return file_paths def main(): # path to folder which needs to be zipped directory = './python_files' # calling function to get all file paths in the directory file_paths = get_all_file_paths(directory) # printing the list of all files to be zipped print('Following files will be zipped:') for file_name in file_paths: print(file_name) # writing files to a zipfile with ZipFile('my_python_files.zip','w') as zip: # writing each file one by one for file in file_paths: zip.write(file) print('All files zipped successfully!') if __name__ == "__main__": main() The output of above program looks like this: Let us try to understand above code by dividing into fragments: def get_all_file_paths(directory): file_paths = [] for root, directories, files in os.walk(directory): for filename in files: filepath = os.path.join(root, filename) file_paths.append(filepath) return file_pathsFirst of all, to get all file paths in our directory, we have created this function which uses the os.walk() method. In each iteration, all files present in that directory are appended to a list called file_paths.In the end, we return all the file paths. def get_all_file_paths(directory): file_paths = [] for root, directories, files in os.walk(directory): for filename in files: filepath = os.path.join(root, filename) file_paths.append(filepath) return file_paths First of all, to get all file paths in our directory, we have created this function which uses the os.walk() method. In each iteration, all files present in that directory are appended to a list called file_paths.In the end, we return all the file paths. file_paths = get_all_file_paths(directory)Here we pass the directory to be zipped to the get_all_file_paths() function and obtain a list containing all file paths. file_paths = get_all_file_paths(directory) Here we pass the directory to be zipped to the get_all_file_paths() function and obtain a list containing all file paths. with ZipFile('my_python_files.zip','w') as zip:Here, we create a ZipFile object in WRITE mode this time. with ZipFile('my_python_files.zip','w') as zip: Here, we create a ZipFile object in WRITE mode this time. for file in file_paths: zip.write(file)Here, we write all the files to the zip file one by one using write method. for file in file_paths: zip.write(file) Here, we write all the files to the zip file one by one using write method. 3. Getting all information about a zip file # importing required modulesfrom zipfile import ZipFileimport datetime # specifying the zip file namefile_name = "example.zip" # opening the zip file in READ modewith ZipFile(file_name, 'r') as zip: for info in zip.infolist(): print(info.filename) print('\tModified:\t' + str(datetime.datetime(*info.date_time))) print('\tSystem:\t\t' + str(info.create_system) + '(0 = Windows, 3 = Unix)') print('\tZIP version:\t' + str(info.create_version)) print('\tCompressed:\t' + str(info.compress_size) + ' bytes') print('\tUncompressed:\t' + str(info.file_size) + ' bytes') The output of above program may look like this: for info in zip.infolist(): Here, infolist() method creates an instance of ZipInfo class which contains all the information about the zip file.We can access all information like last modification date of files, file names, system on which files were created, Zip version, size of files in compressed and uncompressed form, etc. This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. Project Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Implementing Web Scraping in Python with BeautifulSoup OpenCV C++ Program for Face Detection Simple Chat Room using Python 10 Best Web Development Projects For Your Resume Student Information Management System 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": 52, "s": 24, "text": "\n22 Jul, 2021" }, { "code": null, "e": 158, "s": 52, "text": "This article explains how one can perform various operations on a zip file using a simple python program." }, { "code": null, "e": 178, "s": 158, "text": "What is a zip file?" }, { "code": null, "e": 550, "s": 178, "text": "ZIP is an archive file format that supports lossless data compression. By lossless compression, we mean that the compression algorithm allows the original data to be perfectly reconstructed from the compressed data. So, a ZIP file is a single file containing one or more compressed files, offering an ideal way to make large files smaller and keep related files together." }, { "code": null, "e": 576, "s": 550, "text": "Why do we need zip files?" }, { "code": null, "e": 608, "s": 576, "text": "To reduce storage requirements." }, { "code": null, "e": 661, "s": 608, "text": "To improve transfer speed over standard connections." }, { "code": null, "e": 749, "s": 661, "text": "To work on zip files using python, we will use an inbuilt python module called zipfile." }, { "code": null, "e": 774, "s": 749, "text": "1. Extracting a zip file" }, { "code": "# importing required modulesfrom zipfile import ZipFile # specifying the zip file namefile_name = \"my_python_files.zip\" # opening the zip file in READ modewith ZipFile(file_name, 'r') as zip: # printing all the contents of the zip file zip.printdir() # extracting all the files print('Extracting all the files now...') zip.extractall() print('Done!')", "e": 1147, "s": 774, "text": null }, { "code": null, "e": 1308, "s": 1147, "text": "The above program extracts a zip file named “my_python_files.zip” in the same directory as of this python script.The output of above program may look like this:" }, { "code": null, "e": 1359, "s": 1308, "text": "Let us try to understand the above code in pieces:" }, { "code": null, "e": 1513, "s": 1359, "text": "from zipfile import ZipFileZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module." }, { "code": null, "e": 1541, "s": 1513, "text": "from zipfile import ZipFile" }, { "code": null, "e": 1668, "s": 1541, "text": "ZipFile is a class of zipfile module for reading and writing zip files. Here we import only class ZipFile from zipfile module." }, { "code": null, "e": 1875, "s": 1668, "text": "with ZipFile(file_name, 'r') as zip:Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in READ mode and name it as zip." }, { "code": null, "e": 1912, "s": 1875, "text": "with ZipFile(file_name, 'r') as zip:" }, { "code": null, "e": 2083, "s": 1912, "text": "Here, a ZipFile object is made by calling ZipFile constructor which accepts zip file name and mode parameters. We create a ZipFile object in READ mode and name it as zip." }, { "code": null, "e": 2159, "s": 2083, "text": "zip.printdir()printdir() method prints a table of contents for the archive." }, { "code": null, "e": 2174, "s": 2159, "text": "zip.printdir()" }, { "code": null, "e": 2236, "s": 2174, "text": "printdir() method prints a table of contents for the archive." }, { "code": null, "e": 2642, "s": 2236, "text": "zip.extractall()extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.For example:zip.extract('python_files/python_wiki.txt')This will extract only the specified file.If you want to read some specific file, you can go like this:data = zip.read(name_of_file_to_read)" }, { "code": null, "e": 2659, "s": 2642, "text": "zip.extractall()" }, { "code": null, "e": 2866, "s": 2659, "text": "extractall() method will extract all the contents of the zip file to the current working directory. You can also call extract() method to extract any file by specifying its path in the zip file.For example:" }, { "code": null, "e": 2910, "s": 2866, "text": "zip.extract('python_files/python_wiki.txt')" }, { "code": null, "e": 2953, "s": 2910, "text": "This will extract only the specified file." }, { "code": null, "e": 3015, "s": 2953, "text": "If you want to read some specific file, you can go like this:" }, { "code": null, "e": 3053, "s": 3015, "text": "data = zip.read(name_of_file_to_read)" }, { "code": null, "e": 3078, "s": 3053, "text": "2. Writing to a zip file" }, { "code": null, "e": 3128, "s": 3078, "text": "Consider a directory (folder) with such a format:" }, { "code": null, "e": 3347, "s": 3128, "text": "Here, we will need to crawl the whole directory and its sub-directories in order to get a list of all file paths before writing them to a zip file.The following program does this by crawling the directory to be zipped:" }, { "code": "# importing required modulesfrom zipfile import ZipFileimport os def get_all_file_paths(directory): # initializing empty file paths list file_paths = [] # crawling through directory and subdirectories for root, directories, files in os.walk(directory): for filename in files: # join the two strings in order to form the full filepath. filepath = os.path.join(root, filename) file_paths.append(filepath) # returning all file paths return file_paths def main(): # path to folder which needs to be zipped directory = './python_files' # calling function to get all file paths in the directory file_paths = get_all_file_paths(directory) # printing the list of all files to be zipped print('Following files will be zipped:') for file_name in file_paths: print(file_name) # writing files to a zipfile with ZipFile('my_python_files.zip','w') as zip: # writing each file one by one for file in file_paths: zip.write(file) print('All files zipped successfully!') if __name__ == \"__main__\": main()", "e": 4492, "s": 3347, "text": null }, { "code": null, "e": 4537, "s": 4492, "text": "The output of above program looks like this:" }, { "code": null, "e": 4601, "s": 4537, "text": "Let us try to understand above code by dividing into fragments:" }, { "code": null, "e": 5113, "s": 4601, "text": "def get_all_file_paths(directory):\n file_paths = []\n\n for root, directories, files in os.walk(directory):\n for filename in files:\n filepath = os.path.join(root, filename)\n file_paths.append(filepath)\n\n return file_pathsFirst of all, to get all file paths in our directory, we have created this function which uses the os.walk() method. In each iteration, all files present in that directory are appended to a list called file_paths.In the end, we return all the file paths." }, { "code": null, "e": 5371, "s": 5113, "text": "def get_all_file_paths(directory):\n file_paths = []\n\n for root, directories, files in os.walk(directory):\n for filename in files:\n filepath = os.path.join(root, filename)\n file_paths.append(filepath)\n\n return file_paths" }, { "code": null, "e": 5626, "s": 5371, "text": "First of all, to get all file paths in our directory, we have created this function which uses the os.walk() method. In each iteration, all files present in that directory are appended to a list called file_paths.In the end, we return all the file paths." }, { "code": null, "e": 5790, "s": 5626, "text": "file_paths = get_all_file_paths(directory)Here we pass the directory to be zipped to the get_all_file_paths() function and obtain a list containing all file paths." }, { "code": null, "e": 5833, "s": 5790, "text": "file_paths = get_all_file_paths(directory)" }, { "code": null, "e": 5955, "s": 5833, "text": "Here we pass the directory to be zipped to the get_all_file_paths() function and obtain a list containing all file paths." }, { "code": null, "e": 6060, "s": 5955, "text": "with ZipFile('my_python_files.zip','w') as zip:Here, we create a ZipFile object in WRITE mode this time." }, { "code": null, "e": 6108, "s": 6060, "text": "with ZipFile('my_python_files.zip','w') as zip:" }, { "code": null, "e": 6166, "s": 6108, "text": "Here, we create a ZipFile object in WRITE mode this time." }, { "code": null, "e": 6293, "s": 6166, "text": "for file in file_paths:\n zip.write(file)Here, we write all the files to the zip file one by one using write method." }, { "code": null, "e": 6345, "s": 6293, "text": "for file in file_paths:\n zip.write(file)" }, { "code": null, "e": 6421, "s": 6345, "text": "Here, we write all the files to the zip file one by one using write method." }, { "code": null, "e": 6465, "s": 6421, "text": "3. Getting all information about a zip file" }, { "code": "# importing required modulesfrom zipfile import ZipFileimport datetime # specifying the zip file namefile_name = \"example.zip\" # opening the zip file in READ modewith ZipFile(file_name, 'r') as zip: for info in zip.infolist(): print(info.filename) print('\\tModified:\\t' + str(datetime.datetime(*info.date_time))) print('\\tSystem:\\t\\t' + str(info.create_system) + '(0 = Windows, 3 = Unix)') print('\\tZIP version:\\t' + str(info.create_version)) print('\\tCompressed:\\t' + str(info.compress_size) + ' bytes') print('\\tUncompressed:\\t' + str(info.file_size) + ' bytes')", "e": 7101, "s": 6465, "text": null }, { "code": null, "e": 7149, "s": 7101, "text": "The output of above program may look like this:" }, { "code": null, "e": 7177, "s": 7149, "text": "for info in zip.infolist():" }, { "code": null, "e": 7477, "s": 7177, "text": "Here, infolist() method creates an instance of ZipInfo class which contains all the information about the zip file.We can access all information like last modification date of files, file names, system on which files were created, Zip version, size of files in compressed and uncompressed form, etc." }, { "code": null, "e": 7773, "s": 7477, "text": "This article is contributed by Nikhil Kumar. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks." }, { "code": null, "e": 7898, "s": 7773, "text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above." }, { "code": null, "e": 7906, "s": 7898, "text": "Project" }, { "code": null, "e": 7913, "s": 7906, "text": "Python" }, { "code": null, "e": 8011, "s": 7913, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 8066, "s": 8011, "text": "Implementing Web Scraping in Python with BeautifulSoup" }, { "code": null, "e": 8104, "s": 8066, "text": "OpenCV C++ Program for Face Detection" }, { "code": null, "e": 8134, "s": 8104, "text": "Simple Chat Room using Python" }, { "code": null, "e": 8183, "s": 8134, "text": "10 Best Web Development Projects For Your Resume" }, { "code": null, "e": 8221, "s": 8183, "text": "Student Information Management System" }, { "code": null, "e": 8249, "s": 8221, "text": "Read JSON file using Python" }, { "code": null, "e": 8271, "s": 8249, "text": "Python map() function" }, { "code": null, "e": 8321, "s": 8271, "text": "Adding new column to existing DataFrame in Pandas" }, { "code": null, "e": 8339, "s": 8321, "text": "Python Dictionary" } ]
Interquartile Range (IQR)
21 May, 2021 The quartiles of a ranked set of data values are three points which divide the data into exactly four equal parts, each part comprising of quarter data. Q1 is defined as the middle number between the smallest number and the median of the data set.Q2 is the median of the data.Q3 is the middle value between the median and the highest value of the data set. Q1 is defined as the middle number between the smallest number and the median of the data set. Q2 is the median of the data. Q3 is the middle value between the median and the highest value of the data set. The interquartile range IQR tells us the range where the bulk of the values lie. The interquartile range is calculated by subtracting the first quartile from the third quartile. IQR = Q3 - Q1 Uses 1. Unlike range, IQR tells where the majority of data lies and is thus preferred over range. 2. IQR can be used to identify outliers in a data set. 3. Gives the central tendency of the data. Examples: Input : 1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15 Output : 13 The data set after being sorted is 1, 2, 5, 6, 7, 9, 12, 15, 18, 19, 27 As mentioned above Q2 is the median of the data. Hence Q2 = 9 Q1 is the median of lower half, taking Q2 as pivot. So Q1 = 5 Q3 is the median of upper half talking Q2 as pivot. So Q3 = 18 Therefore IQR for given data=Q3-Q1=18-5=13 Input : 1, 3, 4, 5, 5, 6, 7, 11 Output : 3 C++ Java Python3 C# PHP Javascript // CPP program to find IQR of a data set#include <bits/stdc++.h>using namespace std; // Function to give index of the medianint median(int* a, int l, int r){ int n = r - l + 1; n = (n + 1) / 2 - 1; return n + l;} // Function to calculate IQRint IQR(int* a, int n){ sort(a, a + n); // Index of median of entire data int mid_index = median(a, 0, n); // Median of first half int Q1 = a[median(a, 0, mid_index)]; // Median of second half int Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Functionint main(){ int a[] = { 1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15 }; int n = sizeof(a)/sizeof(a[0]); cout << IQR(a, n); return 0;} // Java program to find// IQR of a data setimport java.io.*;import java .util.*; class GFG{ // Function to give// index of the medianstatic int median(int a[], int l, int r){ int n = r - l + 1; n = (n + 1) / 2 - 1; return n + l;} // Function to// calculate IQRstatic int IQR(int [] a, int n){ Arrays.sort(a); // Index of median // of entire data int mid_index = median(a, 0, n); // Median of first half int Q1 = a[median(a, 0, mid_index)]; // Median of second half int Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Codepublic static void main (String[] args){ int []a = {1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15}; int n = a.length; System.out.println(IQR(a, n));}} // This code is contributed// by anuj_67. # Python3 program to find IQR of# a data set # Function to give index of the mediandef median(a, l, r): n = r - l + 1 n = (n + 1) // 2 - 1 return n + l # Function to calculate IQRdef IQR(a, n): a.sort() # Index of median of entire data mid_index = median(a, 0, n) # Median of first half Q1 = a[median(a, 0, mid_index)] # Median of second half Q3 = a[mid_index + median(a, mid_index + 1, n)] # IQR calculation return (Q3 - Q1) # Driver Functionif __name__=='__main__': a = [1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15] n = len(a) print(IQR(a, n)) # This code is contributed by# Sanjit_Prasad // C# program to find// IQR of a data setusing System; class GFG{ // Function to give// index of the medianstatic int median(int []a, int l, int r){ int n = r - l + 1; n = (n + 1) / 2 - 1; return n + l;} // Function to// calculate IQRstatic int IQR(int [] a, int n){ Array.Sort(a); // Index of median // of entire data int mid_index = median(a, 0, n); // Median of first half int Q1 = a[median(a, 0, mid_index)]; // Median of second half int Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Codepublic static void Main (){ int []a = {1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15}; int n = a.Length; Console.WriteLine(IQR(a, n));}} // This code is contributed// by anuj_67. <?php// PHP program to find IQR of a data set // Function to give index of the medianfunction median($a, $l, $r){ $n = $r - $l + 1; $n = (int)(($n + 1) / 2) - 1; return $n + $l;} // Function to calculate IQRfunction IQR($a, $n){ sort($a); // Index of median of entire data $mid_index = median($a, 0, $n); // Median of first half $Q1 = $a[median($a, 0, $mid_index)]; // Median of second half $Q3 = $a[$mid_index + median($a, $mid_index + 1, $n)]; // IQR calculation return ($Q3 - $Q1);} // Driver Function$a = array( 1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15 );$n = count($a);echo IQR($a, $n); // This code is contributed by mits?> <script> // javascript program to find// IQR of a data set // Function to give// index of the medianfunction median(a, l , r){ var n = r - l + 1; n = parseInt((n + 1) / 2) - 1; return parseInt(n + l);} // Function to// calculate IQRfunction IQR(a , n){ a.sort((a,b)=>a-b); // Index of median // of entire data var mid_index = median(a, 0, n); // Median of first half var Q1 = a[median(a, 0, mid_index)]; // Median of second half var Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Codevar a = [1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15];var n = a.length;document.write(IQR(a, n)); // This code contributed by Princi Singh</script> Output: 13 Reference https://en.wikipedia.org/wiki/Interquartile_rangeThis article is contributed by Vineet Joshi. 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. vt_m Sanjit_Prasad Mithun Kumar AarohGala princi singh statistical-algorithms Mathematical Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n21 May, 2021" }, { "code": null, "e": 207, "s": 52, "text": "The quartiles of a ranked set of data values are three points which divide the data into exactly four equal parts, each part comprising of quarter data. " }, { "code": null, "e": 411, "s": 207, "text": "Q1 is defined as the middle number between the smallest number and the median of the data set.Q2 is the median of the data.Q3 is the middle value between the median and the highest value of the data set." }, { "code": null, "e": 506, "s": 411, "text": "Q1 is defined as the middle number between the smallest number and the median of the data set." }, { "code": null, "e": 536, "s": 506, "text": "Q2 is the median of the data." }, { "code": null, "e": 617, "s": 536, "text": "Q3 is the middle value between the median and the highest value of the data set." }, { "code": null, "e": 814, "s": 619, "text": "The interquartile range IQR tells us the range \nwhere the bulk of the values lie. The interquartile \nrange is calculated by subtracting the first quartile\nfrom the third quartile. \nIQR = Q3 - Q1" }, { "code": null, "e": 1022, "s": 814, "text": "Uses 1. Unlike range, IQR tells where the majority of data lies and is thus preferred over range. 2. IQR can be used to identify outliers in a data set. 3. Gives the central tendency of the data. Examples: " }, { "code": null, "e": 1429, "s": 1022, "text": "Input : 1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15\nOutput : 13\nThe data set after being sorted is \n1, 2, 5, 6, 7, 9, 12, 15, 18, 19, 27\nAs mentioned above Q2 is the median of the data. \nHence Q2 = 9\nQ1 is the median of lower half, taking Q2 as pivot.\nSo Q1 = 5\nQ3 is the median of upper half talking Q2 as pivot. \nSo Q3 = 18\nTherefore IQR for given data=Q3-Q1=18-5=13 \n\nInput : 1, 3, 4, 5, 5, 6, 7, 11\nOutput : 3" }, { "code": null, "e": 1435, "s": 1431, "text": "C++" }, { "code": null, "e": 1440, "s": 1435, "text": "Java" }, { "code": null, "e": 1448, "s": 1440, "text": "Python3" }, { "code": null, "e": 1451, "s": 1448, "text": "C#" }, { "code": null, "e": 1455, "s": 1451, "text": "PHP" }, { "code": null, "e": 1466, "s": 1455, "text": "Javascript" }, { "code": "// CPP program to find IQR of a data set#include <bits/stdc++.h>using namespace std; // Function to give index of the medianint median(int* a, int l, int r){ int n = r - l + 1; n = (n + 1) / 2 - 1; return n + l;} // Function to calculate IQRint IQR(int* a, int n){ sort(a, a + n); // Index of median of entire data int mid_index = median(a, 0, n); // Median of first half int Q1 = a[median(a, 0, mid_index)]; // Median of second half int Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Functionint main(){ int a[] = { 1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15 }; int n = sizeof(a)/sizeof(a[0]); cout << IQR(a, n); return 0;}", "e": 2187, "s": 1466, "text": null }, { "code": "// Java program to find// IQR of a data setimport java.io.*;import java .util.*; class GFG{ // Function to give// index of the medianstatic int median(int a[], int l, int r){ int n = r - l + 1; n = (n + 1) / 2 - 1; return n + l;} // Function to// calculate IQRstatic int IQR(int [] a, int n){ Arrays.sort(a); // Index of median // of entire data int mid_index = median(a, 0, n); // Median of first half int Q1 = a[median(a, 0, mid_index)]; // Median of second half int Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Codepublic static void main (String[] args){ int []a = {1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15}; int n = a.length; System.out.println(IQR(a, n));}} // This code is contributed// by anuj_67.", "e": 3063, "s": 2187, "text": null }, { "code": "# Python3 program to find IQR of# a data set # Function to give index of the mediandef median(a, l, r): n = r - l + 1 n = (n + 1) // 2 - 1 return n + l # Function to calculate IQRdef IQR(a, n): a.sort() # Index of median of entire data mid_index = median(a, 0, n) # Median of first half Q1 = a[median(a, 0, mid_index)] # Median of second half Q3 = a[mid_index + median(a, mid_index + 1, n)] # IQR calculation return (Q3 - Q1) # Driver Functionif __name__=='__main__': a = [1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15] n = len(a) print(IQR(a, n)) # This code is contributed by# Sanjit_Prasad", "e": 3697, "s": 3063, "text": null }, { "code": "// C# program to find// IQR of a data setusing System; class GFG{ // Function to give// index of the medianstatic int median(int []a, int l, int r){ int n = r - l + 1; n = (n + 1) / 2 - 1; return n + l;} // Function to// calculate IQRstatic int IQR(int [] a, int n){ Array.Sort(a); // Index of median // of entire data int mid_index = median(a, 0, n); // Median of first half int Q1 = a[median(a, 0, mid_index)]; // Median of second half int Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Codepublic static void Main (){ int []a = {1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15}; int n = a.Length; Console.WriteLine(IQR(a, n));}} // This code is contributed// by anuj_67.", "e": 4522, "s": 3697, "text": null }, { "code": "<?php// PHP program to find IQR of a data set // Function to give index of the medianfunction median($a, $l, $r){ $n = $r - $l + 1; $n = (int)(($n + 1) / 2) - 1; return $n + $l;} // Function to calculate IQRfunction IQR($a, $n){ sort($a); // Index of median of entire data $mid_index = median($a, 0, $n); // Median of first half $Q1 = $a[median($a, 0, $mid_index)]; // Median of second half $Q3 = $a[$mid_index + median($a, $mid_index + 1, $n)]; // IQR calculation return ($Q3 - $Q1);} // Driver Function$a = array( 1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15 );$n = count($a);echo IQR($a, $n); // This code is contributed by mits?>", "e": 5199, "s": 4522, "text": null }, { "code": "<script> // javascript program to find// IQR of a data set // Function to give// index of the medianfunction median(a, l , r){ var n = r - l + 1; n = parseInt((n + 1) / 2) - 1; return parseInt(n + l);} // Function to// calculate IQRfunction IQR(a , n){ a.sort((a,b)=>a-b); // Index of median // of entire data var mid_index = median(a, 0, n); // Median of first half var Q1 = a[median(a, 0, mid_index)]; // Median of second half var Q3 = a[mid_index + median(a, mid_index + 1, n)]; // IQR calculation return (Q3 - Q1);} // Driver Codevar a = [1, 19, 7, 6, 5, 9, 12, 27, 18, 2, 15];var n = a.length;document.write(IQR(a, n)); // This code contributed by Princi Singh</script>", "e": 5961, "s": 5199, "text": null }, { "code": null, "e": 5971, "s": 5961, "text": "Output: " }, { "code": null, "e": 5974, "s": 5971, "text": "13" }, { "code": null, "e": 6453, "s": 5974, "text": "Reference https://en.wikipedia.org/wiki/Interquartile_rangeThis article is contributed by Vineet Joshi. 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": 6458, "s": 6453, "text": "vt_m" }, { "code": null, "e": 6472, "s": 6458, "text": "Sanjit_Prasad" }, { "code": null, "e": 6485, "s": 6472, "text": "Mithun Kumar" }, { "code": null, "e": 6495, "s": 6485, "text": "AarohGala" }, { "code": null, "e": 6508, "s": 6495, "text": "princi singh" }, { "code": null, "e": 6531, "s": 6508, "text": "statistical-algorithms" }, { "code": null, "e": 6544, "s": 6531, "text": "Mathematical" }, { "code": null, "e": 6557, "s": 6544, "text": "Mathematical" } ]
Implementing Byte Stuffing using Java
19 Nov, 2021 At Sender Side Enter the Message to be Sent : DDEDFFDE The data being sent (with byte stuffed) is : FDDEEDEFEFDEEF Sending Message.... Thanks for the Feedback Server!! At Receiver Side Message Received...Successfully!!! The Stuffed Message is : FDDEEDEFEFDEEF The Destuffed Message is : DDEDFFDE Messaging is over.....EXITING From the above example we can see how the original data is recovered at the receiver end. ApproachAt Sender (Client) Side Data of each frame at the sender side, is first stuffed with 8-bit flag sequence (‘F’) at the beginning and end of each frame.Next, the data is scanned to see if any similar flag sequence (‘F’) forms a part of it or not. If yes, then before each such flag sequence, an extra escape sequence (‘E’) is stuffed.Now, if any similar escape sequence (‘E’) is found to form a part of the data to be sent, then an extra escape sequence (‘E’) is stuffed before the occurrence of each such escape sequence.Finally, this stuffed data is sent by the sender.The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data.From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed.This strategy helps the receiver recover the actual sent data, accurately. Data of each frame at the sender side, is first stuffed with 8-bit flag sequence (‘F’) at the beginning and end of each frame. Next, the data is scanned to see if any similar flag sequence (‘F’) forms a part of it or not. If yes, then before each such flag sequence, an extra escape sequence (‘E’) is stuffed. Now, if any similar escape sequence (‘E’) is found to form a part of the data to be sent, then an extra escape sequence (‘E’) is stuffed before the occurrence of each such escape sequence. Finally, this stuffed data is sent by the sender.The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data.From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed.This strategy helps the receiver recover the actual sent data, accurately. The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data.From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed.This strategy helps the receiver recover the actual sent data, accurately. The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data. From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed. This strategy helps the receiver recover the actual sent data, accurately. kapoorsagar226 Computer Networks Java Programs Computer Networks Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n19 Nov, 2021" }, { "code": null, "e": 382, "s": 54, "text": "At Sender Side\nEnter the Message to be Sent : \nDDEDFFDE\nThe data being sent (with byte stuffed) is : FDDEEDEFEFDEEF\nSending Message....\nThanks for the Feedback Server!!\n\nAt Receiver Side\nMessage Received...Successfully!!!\nThe Stuffed Message is : FDDEEDEFEFDEEF\nThe Destuffed Message is : DDEDFFDE\nMessaging is over.....EXITING" }, { "code": null, "e": 506, "s": 382, "text": "From the above example we can see how the original data is recovered at the receiver end. ApproachAt Sender (Client) Side " }, { "code": null, "e": 1539, "s": 506, "text": "Data of each frame at the sender side, is first stuffed with 8-bit flag sequence (‘F’) at the beginning and end of each frame.Next, the data is scanned to see if any similar flag sequence (‘F’) forms a part of it or not. If yes, then before each such flag sequence, an extra escape sequence (‘E’) is stuffed.Now, if any similar escape sequence (‘E’) is found to form a part of the data to be sent, then an extra escape sequence (‘E’) is stuffed before the occurrence of each such escape sequence.Finally, this stuffed data is sent by the sender.The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data.From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed.This strategy helps the receiver recover the actual sent data, accurately." }, { "code": null, "e": 1666, "s": 1539, "text": "Data of each frame at the sender side, is first stuffed with 8-bit flag sequence (‘F’) at the beginning and end of each frame." }, { "code": null, "e": 1849, "s": 1666, "text": "Next, the data is scanned to see if any similar flag sequence (‘F’) forms a part of it or not. If yes, then before each such flag sequence, an extra escape sequence (‘E’) is stuffed." }, { "code": null, "e": 2038, "s": 1849, "text": "Now, if any similar escape sequence (‘E’) is found to form a part of the data to be sent, then an extra escape sequence (‘E’) is stuffed before the occurrence of each such escape sequence." }, { "code": null, "e": 2575, "s": 2038, "text": "Finally, this stuffed data is sent by the sender.The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data.From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed.This strategy helps the receiver recover the actual sent data, accurately." }, { "code": null, "e": 3063, "s": 2575, "text": "The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data.From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed.This strategy helps the receiver recover the actual sent data, accurately." }, { "code": null, "e": 3249, "s": 3063, "text": "The receiver skips over the first and last bytes of data received, as they are merely for signalling the beginning and end of one frame, respectively and does not carry any useful data." }, { "code": null, "e": 3478, "s": 3249, "text": "From the next byte on wards data is scanned and if two escape sequences (‘E’) are found in succession, the first one is de-stuffed. Similarly, if an escape sequence is followed by a flag sequence (‘F’), the former is de-stuffed." }, { "code": null, "e": 3553, "s": 3478, "text": "This strategy helps the receiver recover the actual sent data, accurately." }, { "code": null, "e": 3568, "s": 3553, "text": "kapoorsagar226" }, { "code": null, "e": 3586, "s": 3568, "text": "Computer Networks" }, { "code": null, "e": 3600, "s": 3586, "text": "Java Programs" }, { "code": null, "e": 3618, "s": 3600, "text": "Computer Networks" } ]
The magic behind Recommendation Systems | by Anthony Figueroa | Towards Data Science
Oftentimes, we are surprised by the accuracy of recommendations on what to buy on Amazon, watch on Netflix, or listen on Spotify. We feel that somehow these companies know how our brain works and monetizing this magical guessing game. They have a deep foundation on behavioral sciences, and our job is to make all these concepts real in a way that is both easy to understand and covers the most important concepts. Remember: People are extremely predictable. Behavior indicates personality. Personality builds our conduct and our conduct determines our decisions. More formally, recommendation systems are a subclass of information filtering systems. In short words, information filtering systems remove redundant or unwanted data from a data stream. They reduce noise at a semantic level. There’s plenty of literature around this topic, from astronomy to financial risk analysis. There are two main types of recommendations systems: Collaborative Filtering (CF) Content-Based Filtering We’ll explore both types, with examples, pros, and cons. There isn’t a perfect system, but there are solutions better-suited for specific needs, as well as different levels of complexity. The cornerstone of this filtering type is the user/item feedback loops. This feedback can be user ratings, thumbs up and down, or even how much a user engages with specific content. Collaborative filtering has two senses, a narrow one and a more general one. Within the narrower sense, collaborative filtering is a method of constructing automatic predictions (filtering) regarding the interests of a user, by aggregation preferences or data collection from several users (collaborating). The underlying assumption of the collaborative filtering approach is that if person A has the same opinion as a person B on an issue, A is more likely to have B’s opinion on a different issue than that of a randomly chosen person. Netflix could use collaborative filtering to predict which TV show a user will like, given a partial list of that user’s tastes (likes or dislikes). Note that these predictions are specific to the user, but use information gleaned from many users. A collaborative filtering formula represents a client as an N-dimensional vector N, wherever N is that the variety of distinct catalog data. The elements of the vector are positive for accessed or positively rated content and negative for negatively rated information. Computationally speaking, collaborative filtering is O(MN) within the worst case, where M is the number of customers and N the number of product catalog data. In practice, since the average client vector is very thin, performance tends to be nearer O(M+N). In a more general sense, collaborative filtering is the process of filtering for information or patterns using techniques involving collaboration among multiple agents, viewpoints, data sources, etc. It typically involves very large data sets. Some public ones can be found here. We have different types of Collaborative filtering: User-User Item-Item User Item User-User: The most commonly used recommendation algorithm follows the “people like you like that” logic. It recommends items that similar users liked before. The similarity between two users is computed from the number of items they have in common in the dataset. This algorithm is efficient when the number of users is smaller than the number of items. A good example is a medium-sized e-commerce website with millions of products. The major disadvantage is that adding new users is expensive since it requires updating all similarities between users. Item-Item: It uses the same approach but reverses the view between users and items. It follows the logic “if you like this you might also like that”. In other words, it recommends items that are similar to the ones you previously liked. As before the similarity between two items is computed using the number of users they have in common in the dataset. This algorithm is better when the number of items is much smaller than the number of users. An example could be a large-scale online shop when your items don’t change too often. The main disadvantage is that item-item similarity tables have to be precomputed. Updating this table when adding a new item is expensive. User-Item: It combines both approaches to generate recommendations. The simplest ones are based on matrix decomposition techniques. The goal is to create low-dimensional vectors (“embeddings”) for all users and all items, such that multiplying them together can uncover if a user likes an item or not. The user-item matrix is a basic foundation of traditional collaborative filtering techniques, and it suffers from a data sparsity problem. Matrix decomposition can be done using SVD, but it’s computationally expensive and doesn’t scale well. For medium-sized datasets, ALS could be a good alternative. For a large dataset, only the SGD algorithm will be able to scale, but always needing considerable computational power. Once the users’ embeddings and the items’ embeddings have been pre-computed recommendations can be served in real-time. Another benefit of this approach is that you can learn more about users and items using their embeddings. User-Item algorithms share the drawback that there is no efficient method to update the embeddings after adding a new item or a new user. As in the personalized recommendation scenario, the introduction of new users or new items can cause the cold-start problem, as there will be insufficient data on these new entries for the collaborative filtering to work accurately. In order to make appropriate recommendations for a new user, the system must first learn the user’s preferences by analyzing past voting or rating activities. The collaborative filtering system requires a substantial number of users to rate a new item before that item can be recommended. In a further article we can dive deeper into the two main types of collaborative filtering systems: Model-Based: Uses different techniques, like, data mining, machine learning algorithms to predict users’ ratings of unrated items. Typically uses clustering-based algorithms (k-nearest neighbors or KNN), Matrix factorization techniques (SVD), Probabilistic Factorization or Deep learning (Neural Nets). Memory-Based: Uses user rating data to compute the similarity. It typically finds similarity using cosines or Pearson correlations and takes a weighted average of ratings. This approach has easier explainability but doesn’t scale well. All the previous models suffer from what is called the cold-start problem. Content-based filtering methods are based on a description of the item and a profile of the user’s preferences. These methods are best suited to situations where there is known data on an item (name, location, description, etc.), but not on the user. Content-based recommenders treat recommendation as a user-specific classification problem and learn a classifier for the user’s likes and dislikes based on product features. In this system, keywords are used to describe the items and a profile is built to indicate the type of item this user likes. The algorithms try to recommend items that are similar to those that a user liked in the past, or is examining in the present. This approach has its roots in information retrieval and information filtering research. The recent progress of pattern recognition in machine learning unlocked great improvements in a content-based model using information extracted from images or text descriptions. The approach is identical to the previous User-User or Item-Item algorithms, except that the similarities are computed using only content-based features. For the following case studies, we’ll use Python and a public dataset. Specifically, we’ll use MovieLens dataset collected by GroupLens Research. A file containing MovieLens 100k dataset is a stable benchmark dataset with 100,000 ratings given by 943 users for 1682 movies, with each user having rated at least 20 movies. This dataset consists of many files that contain information about the movies, the users, and the ratings given by users to the movies they have watched. The ones that are of interest are the following: u.item: the list of movies u.data: the list of ratings given by users The first five lines of the file look like this: The file contains what rating a user gave to a particular movie. This file contains 100,000 ratings, which will be used to predict the ratings of the movies not seen by the users. On this variation, statistical techniques are applied to the entire dataset to calculate the predictions. To find the rating R that a user U would give to an item I, the approach includes: Finding users similar to U who have rated the item I Calculating the rating R based the ratings of users found in the previous step Considering that each user is a vector, scikit has a function that calculates the cosine distance for each vector. >>> from scipy import spatial>>> a = [1, 2]>>> b = [2, 4]>>> c = [2.5, 4]>>> d = [4.5, 5]>>> spatial.distance.cosine(c,a)0.004504527406047898>>> spatial.distance.cosine(c,b)0.004504527406047898>>> spatial.distance.cosine(c,d)0.015137225946083022>>> spatial.distance.cosine(a,b)0.0 The lower angle between the vectors of C and A gives a lower cosine distance value. Note that users A and B are considered absolutely similar in the cosine similarity metric despite having different ratings. This is actually a common occurrence in the real world, and the users like the user A are what you can call tough raters. An example would be a movie critic who always gives out ratings lower than the average, but the rankings of the items in their list would be similar to the Average raters like B. To factor in such individual user preferences, we can normalize ratings to remove their biases. We can do this by subtracting the average rating given by that user to all items from each item rated by that user. Here’s what this normalization would look like: For user A, the rating vector [1, 2] has the average 1.5. Subtracting 1.5 from every rating would give you the vector [-0.5, 0.5]. For user B, the rating vector [2, 4] has the average 3. Subtracting 3 from every rating would give you the vector [-1, 1]. Doing the same for users C and D, we can see that the ratings are now adjusted to give an average of 0 for all users, which brings them all to the same level and removes their biases. The cosine of the angle between the adjusted vectors is called centered cosine. This approach is normally used when there are a lot of missing values in the vectors, and you need to place a common value to fill up the missing values. A good choice to fill the missing values could be the average rating of each user, but the original averages of user A and B are 1.5 and 3 respectively, and filling up all the empty values of A with 1.5 and those of B with 3 would make them dissimilar users. This problem is solved by our normalization because the centered average of both users is 0, which brings the idea that all missing values are 0. After we have determined a list of users similar to a user U, we can calculate R that U would give to a certain item I. We can do this in multiple ways. We can predict that a user’s rating R for an item I will be close to the average of the ratings given to I by the top 5 or top 10 users most similar to U. The mathematical formula for the average rating given by n users would look like this: This formula shows that the average rating given by the n similar users is equal to the sum of the ratings given by them divided by the number of similar users, which is n. There will be situations where the n similar users that you found are not equally similar to the target user U. The top 3 of them might be very similar, and the rest might not be as similar to U as the top 3. In that case, you could consider an approach where the rating of the most similar user matters more than the second most similar user and so on. The weighted average can help us achieve that. In the weighted average approach, you multiply each rating by a similarity factor(which tells how similar the users are). By multiplying with the similarity factor, you add weights to the ratings. The heavier the weight, the more the rating would matter. The similarity factor, which would act as weights, should be the inverse of the distance discussed above because less distance implies higher similarity. For example, you can subtract the cosine distance from 1 to get a cosine similarity. With the similarity factor S for each user similar to the target user U, we can calculate the weighted average using the following formula: In the above formula, every rating is multiplied by the similarity factor of the user who gave the rating. The final predicted rating by user U will be equal to the sum of the weighted ratings divided by the sum of the weights. With a weighted average, we give more consideration to the ratings of similar users in order of their similarity. This technique is an example of User-User CF. If we use the rating matrix to find similar items based on the ratings given to them by users, then the approach would be Item-Item CF. Although, the Item-Item approach performs poorly for datasets with browsing or entertainment-related items such as MovieLens. Such datasets see better results with matrix factorization techniques, which we’ll see in the Model-based CF section. In the user-item matrix, there are two dimensions: The number of usersThe number of items The number of users The number of items If the matrix is mostly empty (sparse), reducing dimensions can improve the performance of the algorithm in terms of both space and time. One of the most common methods for this is called matrix factorization. Matrix factorization can be seen as breaking down a large matrix into a product of smaller ones. This is similar to the factorization of integers, where 12 can be written as 6 x 2 or 4 x 3. In the case of matrices, a matrix A with dimensions m x n can be reduced to a product of two matrices X and Y with dimensions m x p and p x n respectively. Depending on the algorithm used for dimensionality reduction, the number of reduced matrices can be more than two as well. The reduced matrices actually represent the users and items individually. The m rows in the first matrix represent the m users, and the p columns tell you about the features or characteristics of the users. The same goes for the item matrix with n items and p characteristics. Here’s an example of how matrix factorization looks: In the image above, the matrix is reduced into two matrices. The one on the left is the user matrix with m users, and the one on top is the item matrix with n items. The rating 4 is reduced or factorized into: A user vector (2, -1)An item vector (2.5, 1) A user vector (2, -1) An item vector (2.5, 1) The two columns in the user matrix and the two rows in the item matrix are called latent factors and are an indication of hidden characteristics about the users or the items. A possible interpretation of the factorization could look like this: Assume that in a user vector (u, v), u represents how much a user likes the Horror genre, and v represents how much they like the Romance genre. The user vector (2, -1) thus represents a user who likes horror movies and rates them positively and dislikes movies that have romance and rates them negatively. Assume that in an item vector (i, j), i represents how much a movie belongs to the Horror genre, and j represents how much that movie belongs to the Romance genre. The movie (2.5, 1) has a Horror rating of 2.5 and a Romance rating of 1. Multiplying it by the user vector using matrix multiplication rules gives you (2 * 2.5) + (-1 * 1) = 4. So, the movie belonged to the Horror genre, and the user could have rated it 5, but the slight inclusion of Romance caused the final rating to drop to 4. The factor matrices can provide such insights about users and items, but in reality, they are usually much more complex. The number of such factors can be anything from one to hundreds or even thousands. This number is one of the things that need to be optimized during the training of the model. In the example, you had two latent factors for movie genres, but in real scenarios, these latent factors need not be analyzed too much. These are patterns in the data that will play their part automatically whether you decipher their underlying meaning or not. The number of latent factors affects the recommendations in a manner where the greater the number of factors, the more personalized the recommendations become. But too many factors can lead to overfitting in the model. # load_data.pyimport pandas as pdfrom surprise import Datasetfrom surprise import Reader# This is the same data that was plotted for similarity earlier# with one new user "E" who has rated only movie 1ratings_dict = { "item": [1, 2, 1, 2, 1, 2, 1, 2, 1], "user": ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E'], "rating": [1, 2, 2, 4, 2.5, 4, 4.5, 5, 3],}df = pd.DataFrame(ratings_dict)reader = Reader(rating_scale=(1, 5))# Loads Pandas dataframedata = Dataset.load_from_df(df[["user", "item", "rating"]], reader)# Loads the builtin Movielens-100k datamovielens = Dataset.load_builtin('ml-100k') Surprise library has many algorithms that we can use very easily, k-NN. # recommender.pyfrom surprise import KNNWithMeans# To use item-based cosine similaritysim_options = { "name": "cosine", "user_based": False, # Compute similarities between items}algo = KNNWithMeans(sim_options=sim_options) That we can train and predict using k-NN. >>> from load_data import data>>> from recommender import algo>>> trainingSet = data.build_full_trainset()>>> algo.fit(trainingSet)Computing the cosine similarity matrix...Done computing similarity matrix.<surprise.prediction_algorithms.knns.KNNWithMeans object at 0x7f04fec56898>>>> prediction = algo.predict('E', 2)>>> prediction.est4.15 And finally, we can finetune our hyperparameters and root mean square error. from surprise import KNNWithMeansfrom surprise import Datasetfrom surprise.model_selection import GridSearchCVdata = Dataset.load_builtin("ml-100k")sim_options = { "name": ["msd", "cosine"], "min_support": [3, 4, 5], "user_based": [False, True],}param_grid = {"sim_options": sim_options}gs = GridSearchCV(KNNWithMeans, param_grid, measures=["rmse", "mae"], cv=3)gs.fit(data)print(gs.best_score["rmse"])print(gs.best_params["rmse"]) As a variation, we can run a recommender algorithm using SVD, instead of k-NN. from surprise import SVDfrom surprise import Datasetfrom surprise.model_selection import GridSearchCVdata = Dataset.load_builtin("ml-100k")param_grid = { "n_epochs": [5, 10], "lr_all": [0.002, 0.005], "reg_all": [0.4, 0.6]}gs = GridSearchCV(SVD, param_grid, measures=["rmse", "mae"], cv=3)gs.fit(data)print(gs.best_score["rmse"])print(gs.best_params["rmse"]) The output of the above program is as follows: 0.9642278631521038{'n_epochs': 10, 'lr_all': 0.005, 'reg_all': 0.4} Suresh Chandra Satapathy, Vikrant Bhateja, Amit Joshi. “Proceedings of the International Conference on Data Engineering and Communication Technology”. 2016. realpython.com Terveen, Loren; Hill, Will (2001). “Beyond Recommender Systems: Helping People Help Each Other”. Addison-Wesley. p. 6. Badrul Sarwar, George Karypis, Joseph Konstan, and John Riedl (2001). “Item-Based Collaborative Filtering Recommendation Algorithms”. GroupLens Research Group/Army HPC Research Centre. The first paper published on item-based recommenders. David A. Goldberg, David A. Nichols, Douglas B. Terry. “Using collaborative filtering to weave an information tapestry”. Communications of The ACM. 1991. The first use of the term collaborative filtering. Library LightFM: a hybrid recommendation algorithm in Python. Library Python-recsys: a Python library for implementing a recommender system. Library Surprise: a Python scikit building and analyzing recommender systems that deal with explicit rating data. Aggarwal, Charu C. (2016). “Recommender Systems: The Textbook”. Springer. Peter Brusilovsky (2007). “The Adaptive Web.” p. 325. Aditya, P. & Budi, Indra & Munajat, Qorib. (2016). “A comparative analysis of memory-based and model-based collaborative filtering on the implementation of recommender system for E-commerce in Indonesia: A case study PT X”. p. 303–308 InCubeGroup. Recommender Systems for Private Banking. Referenced 3/18/2020.
[ { "code": null, "e": 587, "s": 172, "text": "Oftentimes, we are surprised by the accuracy of recommendations on what to buy on Amazon, watch on Netflix, or listen on Spotify. We feel that somehow these companies know how our brain works and monetizing this magical guessing game. They have a deep foundation on behavioral sciences, and our job is to make all these concepts real in a way that is both easy to understand and covers the most important concepts." }, { "code": null, "e": 736, "s": 587, "text": "Remember: People are extremely predictable. Behavior indicates personality. Personality builds our conduct and our conduct determines our decisions." }, { "code": null, "e": 1053, "s": 736, "text": "More formally, recommendation systems are a subclass of information filtering systems. In short words, information filtering systems remove redundant or unwanted data from a data stream. They reduce noise at a semantic level. There’s plenty of literature around this topic, from astronomy to financial risk analysis." }, { "code": null, "e": 1106, "s": 1053, "text": "There are two main types of recommendations systems:" }, { "code": null, "e": 1135, "s": 1106, "text": "Collaborative Filtering (CF)" }, { "code": null, "e": 1159, "s": 1135, "text": "Content-Based Filtering" }, { "code": null, "e": 1347, "s": 1159, "text": "We’ll explore both types, with examples, pros, and cons. There isn’t a perfect system, but there are solutions better-suited for specific needs, as well as different levels of complexity." }, { "code": null, "e": 1419, "s": 1347, "text": "The cornerstone of this filtering type is the user/item feedback loops." }, { "code": null, "e": 1606, "s": 1419, "text": "This feedback can be user ratings, thumbs up and down, or even how much a user engages with specific content. Collaborative filtering has two senses, a narrow one and a more general one." }, { "code": null, "e": 1836, "s": 1606, "text": "Within the narrower sense, collaborative filtering is a method of constructing automatic predictions (filtering) regarding the interests of a user, by aggregation preferences or data collection from several users (collaborating)." }, { "code": null, "e": 2315, "s": 1836, "text": "The underlying assumption of the collaborative filtering approach is that if person A has the same opinion as a person B on an issue, A is more likely to have B’s opinion on a different issue than that of a randomly chosen person. Netflix could use collaborative filtering to predict which TV show a user will like, given a partial list of that user’s tastes (likes or dislikes). Note that these predictions are specific to the user, but use information gleaned from many users." }, { "code": null, "e": 2584, "s": 2315, "text": "A collaborative filtering formula represents a client as an N-dimensional vector N, wherever N is that the variety of distinct catalog data. The elements of the vector are positive for accessed or positively rated content and negative for negatively rated information." }, { "code": null, "e": 2841, "s": 2584, "text": "Computationally speaking, collaborative filtering is O(MN) within the worst case, where M is the number of customers and N the number of product catalog data. In practice, since the average client vector is very thin, performance tends to be nearer O(M+N)." }, { "code": null, "e": 3121, "s": 2841, "text": "In a more general sense, collaborative filtering is the process of filtering for information or patterns using techniques involving collaboration among multiple agents, viewpoints, data sources, etc. It typically involves very large data sets. Some public ones can be found here." }, { "code": null, "e": 3173, "s": 3121, "text": "We have different types of Collaborative filtering:" }, { "code": null, "e": 3183, "s": 3173, "text": "User-User" }, { "code": null, "e": 3193, "s": 3183, "text": "Item-Item" }, { "code": null, "e": 3203, "s": 3193, "text": "User Item" }, { "code": null, "e": 3757, "s": 3203, "text": "User-User: The most commonly used recommendation algorithm follows the “people like you like that” logic. It recommends items that similar users liked before. The similarity between two users is computed from the number of items they have in common in the dataset. This algorithm is efficient when the number of users is smaller than the number of items. A good example is a medium-sized e-commerce website with millions of products. The major disadvantage is that adding new users is expensive since it requires updating all similarities between users." }, { "code": null, "e": 4428, "s": 3757, "text": "Item-Item: It uses the same approach but reverses the view between users and items. It follows the logic “if you like this you might also like that”. In other words, it recommends items that are similar to the ones you previously liked. As before the similarity between two items is computed using the number of users they have in common in the dataset. This algorithm is better when the number of items is much smaller than the number of users. An example could be a large-scale online shop when your items don’t change too often. The main disadvantage is that item-item similarity tables have to be precomputed. Updating this table when adding a new item is expensive." }, { "code": null, "e": 4730, "s": 4428, "text": "User-Item: It combines both approaches to generate recommendations. The simplest ones are based on matrix decomposition techniques. The goal is to create low-dimensional vectors (“embeddings”) for all users and all items, such that multiplying them together can uncover if a user likes an item or not." }, { "code": null, "e": 4869, "s": 4730, "text": "The user-item matrix is a basic foundation of traditional collaborative filtering techniques, and it suffers from a data sparsity problem." }, { "code": null, "e": 5152, "s": 4869, "text": "Matrix decomposition can be done using SVD, but it’s computationally expensive and doesn’t scale well. For medium-sized datasets, ALS could be a good alternative. For a large dataset, only the SGD algorithm will be able to scale, but always needing considerable computational power." }, { "code": null, "e": 5378, "s": 5152, "text": "Once the users’ embeddings and the items’ embeddings have been pre-computed recommendations can be served in real-time. Another benefit of this approach is that you can learn more about users and items using their embeddings." }, { "code": null, "e": 5516, "s": 5378, "text": "User-Item algorithms share the drawback that there is no efficient method to update the embeddings after adding a new item or a new user." }, { "code": null, "e": 6038, "s": 5516, "text": "As in the personalized recommendation scenario, the introduction of new users or new items can cause the cold-start problem, as there will be insufficient data on these new entries for the collaborative filtering to work accurately. In order to make appropriate recommendations for a new user, the system must first learn the user’s preferences by analyzing past voting or rating activities. The collaborative filtering system requires a substantial number of users to rate a new item before that item can be recommended." }, { "code": null, "e": 6138, "s": 6038, "text": "In a further article we can dive deeper into the two main types of collaborative filtering systems:" }, { "code": null, "e": 6441, "s": 6138, "text": "Model-Based: Uses different techniques, like, data mining, machine learning algorithms to predict users’ ratings of unrated items. Typically uses clustering-based algorithms (k-nearest neighbors or KNN), Matrix factorization techniques (SVD), Probabilistic Factorization or Deep learning (Neural Nets)." }, { "code": null, "e": 6677, "s": 6441, "text": "Memory-Based: Uses user rating data to compute the similarity. It typically finds similarity using cosines or Pearson correlations and takes a weighted average of ratings. This approach has easier explainability but doesn’t scale well." }, { "code": null, "e": 6752, "s": 6677, "text": "All the previous models suffer from what is called the cold-start problem." }, { "code": null, "e": 7177, "s": 6752, "text": "Content-based filtering methods are based on a description of the item and a profile of the user’s preferences. These methods are best suited to situations where there is known data on an item (name, location, description, etc.), but not on the user. Content-based recommenders treat recommendation as a user-specific classification problem and learn a classifier for the user’s likes and dislikes based on product features." }, { "code": null, "e": 7518, "s": 7177, "text": "In this system, keywords are used to describe the items and a profile is built to indicate the type of item this user likes. The algorithms try to recommend items that are similar to those that a user liked in the past, or is examining in the present. This approach has its roots in information retrieval and information filtering research." }, { "code": null, "e": 7696, "s": 7518, "text": "The recent progress of pattern recognition in machine learning unlocked great improvements in a content-based model using information extracted from images or text descriptions." }, { "code": null, "e": 7850, "s": 7696, "text": "The approach is identical to the previous User-User or Item-Item algorithms, except that the similarities are computed using only content-based features." }, { "code": null, "e": 7921, "s": 7850, "text": "For the following case studies, we’ll use Python and a public dataset." }, { "code": null, "e": 8172, "s": 7921, "text": "Specifically, we’ll use MovieLens dataset collected by GroupLens Research. A file containing MovieLens 100k dataset is a stable benchmark dataset with 100,000 ratings given by 943 users for 1682 movies, with each user having rated at least 20 movies." }, { "code": null, "e": 8375, "s": 8172, "text": "This dataset consists of many files that contain information about the movies, the users, and the ratings given by users to the movies they have watched. The ones that are of interest are the following:" }, { "code": null, "e": 8402, "s": 8375, "text": "u.item: the list of movies" }, { "code": null, "e": 8445, "s": 8402, "text": "u.data: the list of ratings given by users" }, { "code": null, "e": 8494, "s": 8445, "text": "The first five lines of the file look like this:" }, { "code": null, "e": 8674, "s": 8494, "text": "The file contains what rating a user gave to a particular movie. This file contains 100,000 ratings, which will be used to predict the ratings of the movies not seen by the users." }, { "code": null, "e": 8780, "s": 8674, "text": "On this variation, statistical techniques are applied to the entire dataset to calculate the predictions." }, { "code": null, "e": 8863, "s": 8780, "text": "To find the rating R that a user U would give to an item I, the approach includes:" }, { "code": null, "e": 8916, "s": 8863, "text": "Finding users similar to U who have rated the item I" }, { "code": null, "e": 8995, "s": 8916, "text": "Calculating the rating R based the ratings of users found in the previous step" }, { "code": null, "e": 9110, "s": 8995, "text": "Considering that each user is a vector, scikit has a function that calculates the cosine distance for each vector." }, { "code": null, "e": 9391, "s": 9110, "text": ">>> from scipy import spatial>>> a = [1, 2]>>> b = [2, 4]>>> c = [2.5, 4]>>> d = [4.5, 5]>>> spatial.distance.cosine(c,a)0.004504527406047898>>> spatial.distance.cosine(c,b)0.004504527406047898>>> spatial.distance.cosine(c,d)0.015137225946083022>>> spatial.distance.cosine(a,b)0.0" }, { "code": null, "e": 9475, "s": 9391, "text": "The lower angle between the vectors of C and A gives a lower cosine distance value." }, { "code": null, "e": 9900, "s": 9475, "text": "Note that users A and B are considered absolutely similar in the cosine similarity metric despite having different ratings. This is actually a common occurrence in the real world, and the users like the user A are what you can call tough raters. An example would be a movie critic who always gives out ratings lower than the average, but the rankings of the items in their list would be similar to the Average raters like B." }, { "code": null, "e": 10112, "s": 9900, "text": "To factor in such individual user preferences, we can normalize ratings to remove their biases. We can do this by subtracting the average rating given by that user to all items from each item rated by that user." }, { "code": null, "e": 10160, "s": 10112, "text": "Here’s what this normalization would look like:" }, { "code": null, "e": 10291, "s": 10160, "text": "For user A, the rating vector [1, 2] has the average 1.5. Subtracting 1.5 from every rating would give you the vector [-0.5, 0.5]." }, { "code": null, "e": 10414, "s": 10291, "text": "For user B, the rating vector [2, 4] has the average 3. Subtracting 3 from every rating would give you the vector [-1, 1]." }, { "code": null, "e": 10598, "s": 10414, "text": "Doing the same for users C and D, we can see that the ratings are now adjusted to give an average of 0 for all users, which brings them all to the same level and removes their biases." }, { "code": null, "e": 10832, "s": 10598, "text": "The cosine of the angle between the adjusted vectors is called centered cosine. This approach is normally used when there are a lot of missing values in the vectors, and you need to place a common value to fill up the missing values." }, { "code": null, "e": 11237, "s": 10832, "text": "A good choice to fill the missing values could be the average rating of each user, but the original averages of user A and B are 1.5 and 3 respectively, and filling up all the empty values of A with 1.5 and those of B with 3 would make them dissimilar users. This problem is solved by our normalization because the centered average of both users is 0, which brings the idea that all missing values are 0." }, { "code": null, "e": 11390, "s": 11237, "text": "After we have determined a list of users similar to a user U, we can calculate R that U would give to a certain item I. We can do this in multiple ways." }, { "code": null, "e": 11632, "s": 11390, "text": "We can predict that a user’s rating R for an item I will be close to the average of the ratings given to I by the top 5 or top 10 users most similar to U. The mathematical formula for the average rating given by n users would look like this:" }, { "code": null, "e": 11805, "s": 11632, "text": "This formula shows that the average rating given by the n similar users is equal to the sum of the ratings given by them divided by the number of similar users, which is n." }, { "code": null, "e": 12206, "s": 11805, "text": "There will be situations where the n similar users that you found are not equally similar to the target user U. The top 3 of them might be very similar, and the rest might not be as similar to U as the top 3. In that case, you could consider an approach where the rating of the most similar user matters more than the second most similar user and so on. The weighted average can help us achieve that." }, { "code": null, "e": 12461, "s": 12206, "text": "In the weighted average approach, you multiply each rating by a similarity factor(which tells how similar the users are). By multiplying with the similarity factor, you add weights to the ratings. The heavier the weight, the more the rating would matter." }, { "code": null, "e": 12700, "s": 12461, "text": "The similarity factor, which would act as weights, should be the inverse of the distance discussed above because less distance implies higher similarity. For example, you can subtract the cosine distance from 1 to get a cosine similarity." }, { "code": null, "e": 12840, "s": 12700, "text": "With the similarity factor S for each user similar to the target user U, we can calculate the weighted average using the following formula:" }, { "code": null, "e": 13068, "s": 12840, "text": "In the above formula, every rating is multiplied by the similarity factor of the user who gave the rating. The final predicted rating by user U will be equal to the sum of the weighted ratings divided by the sum of the weights." }, { "code": null, "e": 13182, "s": 13068, "text": "With a weighted average, we give more consideration to the ratings of similar users in order of their similarity." }, { "code": null, "e": 13364, "s": 13182, "text": "This technique is an example of User-User CF. If we use the rating matrix to find similar items based on the ratings given to them by users, then the approach would be Item-Item CF." }, { "code": null, "e": 13608, "s": 13364, "text": "Although, the Item-Item approach performs poorly for datasets with browsing or entertainment-related items such as MovieLens. Such datasets see better results with matrix factorization techniques, which we’ll see in the Model-based CF section." }, { "code": null, "e": 13659, "s": 13608, "text": "In the user-item matrix, there are two dimensions:" }, { "code": null, "e": 13698, "s": 13659, "text": "The number of usersThe number of items" }, { "code": null, "e": 13718, "s": 13698, "text": "The number of users" }, { "code": null, "e": 13738, "s": 13718, "text": "The number of items" }, { "code": null, "e": 13948, "s": 13738, "text": "If the matrix is mostly empty (sparse), reducing dimensions can improve the performance of the algorithm in terms of both space and time. One of the most common methods for this is called matrix factorization." }, { "code": null, "e": 14294, "s": 13948, "text": "Matrix factorization can be seen as breaking down a large matrix into a product of smaller ones. This is similar to the factorization of integers, where 12 can be written as 6 x 2 or 4 x 3. In the case of matrices, a matrix A with dimensions m x n can be reduced to a product of two matrices X and Y with dimensions m x p and p x n respectively." }, { "code": null, "e": 14417, "s": 14294, "text": "Depending on the algorithm used for dimensionality reduction, the number of reduced matrices can be more than two as well." }, { "code": null, "e": 14747, "s": 14417, "text": "The reduced matrices actually represent the users and items individually. The m rows in the first matrix represent the m users, and the p columns tell you about the features or characteristics of the users. The same goes for the item matrix with n items and p characteristics. Here’s an example of how matrix factorization looks:" }, { "code": null, "e": 14957, "s": 14747, "text": "In the image above, the matrix is reduced into two matrices. The one on the left is the user matrix with m users, and the one on top is the item matrix with n items. The rating 4 is reduced or factorized into:" }, { "code": null, "e": 15002, "s": 14957, "text": "A user vector (2, -1)An item vector (2.5, 1)" }, { "code": null, "e": 15024, "s": 15002, "text": "A user vector (2, -1)" }, { "code": null, "e": 15048, "s": 15024, "text": "An item vector (2.5, 1)" }, { "code": null, "e": 15292, "s": 15048, "text": "The two columns in the user matrix and the two rows in the item matrix are called latent factors and are an indication of hidden characteristics about the users or the items. A possible interpretation of the factorization could look like this:" }, { "code": null, "e": 15437, "s": 15292, "text": "Assume that in a user vector (u, v), u represents how much a user likes the Horror genre, and v represents how much they like the Romance genre." }, { "code": null, "e": 15599, "s": 15437, "text": "The user vector (2, -1) thus represents a user who likes horror movies and rates them positively and dislikes movies that have romance and rates them negatively." }, { "code": null, "e": 15763, "s": 15599, "text": "Assume that in an item vector (i, j), i represents how much a movie belongs to the Horror genre, and j represents how much that movie belongs to the Romance genre." }, { "code": null, "e": 15940, "s": 15763, "text": "The movie (2.5, 1) has a Horror rating of 2.5 and a Romance rating of 1. Multiplying it by the user vector using matrix multiplication rules gives you (2 * 2.5) + (-1 * 1) = 4." }, { "code": null, "e": 16094, "s": 15940, "text": "So, the movie belonged to the Horror genre, and the user could have rated it 5, but the slight inclusion of Romance caused the final rating to drop to 4." }, { "code": null, "e": 16391, "s": 16094, "text": "The factor matrices can provide such insights about users and items, but in reality, they are usually much more complex. The number of such factors can be anything from one to hundreds or even thousands. This number is one of the things that need to be optimized during the training of the model." }, { "code": null, "e": 16652, "s": 16391, "text": "In the example, you had two latent factors for movie genres, but in real scenarios, these latent factors need not be analyzed too much. These are patterns in the data that will play their part automatically whether you decipher their underlying meaning or not." }, { "code": null, "e": 16871, "s": 16652, "text": "The number of latent factors affects the recommendations in a manner where the greater the number of factors, the more personalized the recommendations become. But too many factors can lead to overfitting in the model." }, { "code": null, "e": 17474, "s": 16871, "text": "# load_data.pyimport pandas as pdfrom surprise import Datasetfrom surprise import Reader# This is the same data that was plotted for similarity earlier# with one new user \"E\" who has rated only movie 1ratings_dict = { \"item\": [1, 2, 1, 2, 1, 2, 1, 2, 1], \"user\": ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E'], \"rating\": [1, 2, 2, 4, 2.5, 4, 4.5, 5, 3],}df = pd.DataFrame(ratings_dict)reader = Reader(rating_scale=(1, 5))# Loads Pandas dataframedata = Dataset.load_from_df(df[[\"user\", \"item\", \"rating\"]], reader)# Loads the builtin Movielens-100k datamovielens = Dataset.load_builtin('ml-100k')" }, { "code": null, "e": 17546, "s": 17474, "text": "Surprise library has many algorithms that we can use very easily, k-NN." }, { "code": null, "e": 17777, "s": 17546, "text": "# recommender.pyfrom surprise import KNNWithMeans# To use item-based cosine similaritysim_options = { \"name\": \"cosine\", \"user_based\": False, # Compute similarities between items}algo = KNNWithMeans(sim_options=sim_options)" }, { "code": null, "e": 17819, "s": 17777, "text": "That we can train and predict using k-NN." }, { "code": null, "e": 18159, "s": 17819, "text": ">>> from load_data import data>>> from recommender import algo>>> trainingSet = data.build_full_trainset()>>> algo.fit(trainingSet)Computing the cosine similarity matrix...Done computing similarity matrix.<surprise.prediction_algorithms.knns.KNNWithMeans object at 0x7f04fec56898>>>> prediction = algo.predict('E', 2)>>> prediction.est4.15" }, { "code": null, "e": 18236, "s": 18159, "text": "And finally, we can finetune our hyperparameters and root mean square error." }, { "code": null, "e": 18677, "s": 18236, "text": "from surprise import KNNWithMeansfrom surprise import Datasetfrom surprise.model_selection import GridSearchCVdata = Dataset.load_builtin(\"ml-100k\")sim_options = { \"name\": [\"msd\", \"cosine\"], \"min_support\": [3, 4, 5], \"user_based\": [False, True],}param_grid = {\"sim_options\": sim_options}gs = GridSearchCV(KNNWithMeans, param_grid, measures=[\"rmse\", \"mae\"], cv=3)gs.fit(data)print(gs.best_score[\"rmse\"])print(gs.best_params[\"rmse\"])" }, { "code": null, "e": 18756, "s": 18677, "text": "As a variation, we can run a recommender algorithm using SVD, instead of k-NN." }, { "code": null, "e": 19124, "s": 18756, "text": "from surprise import SVDfrom surprise import Datasetfrom surprise.model_selection import GridSearchCVdata = Dataset.load_builtin(\"ml-100k\")param_grid = { \"n_epochs\": [5, 10], \"lr_all\": [0.002, 0.005], \"reg_all\": [0.4, 0.6]}gs = GridSearchCV(SVD, param_grid, measures=[\"rmse\", \"mae\"], cv=3)gs.fit(data)print(gs.best_score[\"rmse\"])print(gs.best_params[\"rmse\"])" }, { "code": null, "e": 19171, "s": 19124, "text": "The output of the above program is as follows:" }, { "code": null, "e": 19239, "s": 19171, "text": "0.9642278631521038{'n_epochs': 10, 'lr_all': 0.005, 'reg_all': 0.4}" }, { "code": null, "e": 19396, "s": 19239, "text": "Suresh Chandra Satapathy, Vikrant Bhateja, Amit Joshi. “Proceedings of the International Conference on Data Engineering and Communication Technology”. 2016." }, { "code": null, "e": 19411, "s": 19396, "text": "realpython.com" }, { "code": null, "e": 19530, "s": 19411, "text": "Terveen, Loren; Hill, Will (2001). “Beyond Recommender Systems: Helping People Help Each Other”. Addison-Wesley. p. 6." }, { "code": null, "e": 19769, "s": 19530, "text": "Badrul Sarwar, George Karypis, Joseph Konstan, and John Riedl (2001). “Item-Based Collaborative Filtering Recommendation Algorithms”. GroupLens Research Group/Army HPC Research Centre. The first paper published on item-based recommenders." }, { "code": null, "e": 19974, "s": 19769, "text": "David A. Goldberg, David A. Nichols, Douglas B. Terry. “Using collaborative filtering to weave an information tapestry”. Communications of The ACM. 1991. The first use of the term collaborative filtering." }, { "code": null, "e": 20036, "s": 19974, "text": "Library LightFM: a hybrid recommendation algorithm in Python." }, { "code": null, "e": 20115, "s": 20036, "text": "Library Python-recsys: a Python library for implementing a recommender system." }, { "code": null, "e": 20229, "s": 20115, "text": "Library Surprise: a Python scikit building and analyzing recommender systems that deal with explicit rating data." }, { "code": null, "e": 20303, "s": 20229, "text": "Aggarwal, Charu C. (2016). “Recommender Systems: The Textbook”. Springer." }, { "code": null, "e": 20357, "s": 20303, "text": "Peter Brusilovsky (2007). “The Adaptive Web.” p. 325." }, { "code": null, "e": 20592, "s": 20357, "text": "Aditya, P. & Budi, Indra & Munajat, Qorib. (2016). “A comparative analysis of memory-based and model-based collaborative filtering on the implementation of recommender system for E-commerce in Indonesia: A case study PT X”. p. 303–308" } ]
How to find the count of duplicate rows if they are greater than n in R data frame?
To find the count of duplicate rows if they are greater than n in R data frame, we can follow the below steps − First of all, create a data frame. Then, count the duplicate rows if they are greater than a certain number using group_by_all, count, and filter function of dplyr package. Let's create a data frame as shown below − Live Demo x<-rpois(30,1) y<-rpois(30,1) df<-data.frame(x,y) df On executing, the above script generates the below output(this output will vary on your system due to randomization) − x y 1 1 3 2 0 2 3 0 2 4 0 2 5 2 1 6 1 0 7 0 0 8 1 2 9 1 2 10 2 1 11 0 3 12 1 1 13 1 1 14 0 0 15 0 0 16 0 1 17 0 0 18 0 1 19 0 1 20 2 0 21 1 2 22 3 1 23 1 0 24 1 0 25 1 3 26 1 0 27 1 1 28 2 1 29 1 2 30 0 4 Loading dplyr package and using group_by_all, count, and filter function to find the count of duplicate rows if they are greater than 2 − x<-rpois(30,1) y<-rpois(30,1) df<-data.frame(x,y) library(dplyr) df%>%group_by_all()%>%count()%>%filter(n>2) # A tibble: 7 x 3 # Groups: x, y [7] x y n <int> <int> <int> 1 0 0 4 2 0 1 3 3 0 2 3 4 1 0 4 5 1 1 3 6 1 2 4 7 2 1 3
[ { "code": null, "e": 1174, "s": 1062, "text": "To find the count of duplicate rows if they are greater than n in R data frame, we can follow the below steps −" }, { "code": null, "e": 1209, "s": 1174, "text": "First of all, create a data frame." }, { "code": null, "e": 1347, "s": 1209, "text": "Then, count the duplicate rows if they are greater than a certain number using group_by_all, count, and filter function of dplyr package." }, { "code": null, "e": 1390, "s": 1347, "text": "Let's create a data frame as shown below −" }, { "code": null, "e": 1401, "s": 1390, "text": " Live Demo" }, { "code": null, "e": 1454, "s": 1401, "text": "x<-rpois(30,1)\ny<-rpois(30,1)\ndf<-data.frame(x,y)\ndf" }, { "code": null, "e": 1573, "s": 1454, "text": "On executing, the above script generates the below output(this output will vary on your system due to randomization) −" }, { "code": null, "e": 1780, "s": 1573, "text": " x y\n1 1 3\n2 0 2\n3 0 2\n4 0 2\n5 2 1\n6 1 0\n7 0 0\n8 1 2\n9 1 2\n10 2 1\n11 0 3\n12 1 1\n13 1 1\n14 0 0\n15 0 0\n16 0 1\n17 0 0\n18 0 1\n19 0 1\n20 2 0\n21 1 2\n22 3 1\n23 1 0\n24 1 0\n25 1 3\n26 1 0\n27 1 1\n28 2 1\n29 1 2\n30 0 4" }, { "code": null, "e": 1918, "s": 1780, "text": "Loading dplyr package and using group_by_all, count, and filter function to find the\ncount of duplicate rows if they are greater than 2 −" }, { "code": null, "e": 2027, "s": 1918, "text": "x<-rpois(30,1)\ny<-rpois(30,1)\ndf<-data.frame(x,y)\nlibrary(dplyr)\ndf%>%group_by_all()%>%count()%>%filter(n>2)" }, { "code": null, "e": 2222, "s": 2027, "text": "# A tibble: 7 x 3\n# Groups: x, y [7]\n x y n\n <int> <int> <int>\n1 0 0 4\n2 0 1 3\n3 0 2 3\n4 1 0 4\n5 1 1 3\n6 1 2 4\n7 2 1 3" } ]
How to specify an input field must be filled out before submitting the form in HTML ? - GeeksforGeeks
25 Dec, 2020 In this article, we will specify an input field that must be filled out before submitting the form. The HTML required attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the form. This attribute works with other types of input like radio, checkbox, number, text, etc. Syntax: <input required> Example: This example that illustrates the use of required attribute in input field. HTML <!DOCTYPE html><html> <head> <title> How to specify an input field must be filled out before submitting the form in HTML? </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> How to specify an input field must be filled <br>out before submitting the form in HTML? </h2> <form action=""> Username: <input type="text" name="usrname" required> <br><br> Password: <input type="password" name="password" required> <br><br> <input type="submit"> </form></body> </html> Output: Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course. CSS-Misc HTML-Misc CSS HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a web page using HTML and CSS Form validation using jQuery How to set space between the flexbox ? Search Bar using HTML, CSS and JavaScript How to style a checkbox using CSS? How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Hide or show elements in HTML using display property How to Insert Form Data into Database using PHP ? REST API (Introduction)
[ { "code": null, "e": 25376, "s": 25348, "text": "\n25 Dec, 2020" }, { "code": null, "e": 25710, "s": 25376, "text": "In this article, we will specify an input field that must be filled out before submitting the form. The HTML required attribute is a Boolean attribute which is used to specify that the input element must be filled out before submitting the form. This attribute works with other types of input like radio, checkbox, number, text, etc." }, { "code": null, "e": 25718, "s": 25710, "text": "Syntax:" }, { "code": null, "e": 25735, "s": 25718, "text": "<input required>" }, { "code": null, "e": 25820, "s": 25735, "text": "Example: This example that illustrates the use of required attribute in input field." }, { "code": null, "e": 25825, "s": 25820, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title> How to specify an input field must be filled out before submitting the form in HTML? </title> <style> h1 { color: green; } body { text-align: center; } </style></head> <body> <h1>GeeksforGeeks</h1> <h2> How to specify an input field must be filled <br>out before submitting the form in HTML? </h2> <form action=\"\"> Username: <input type=\"text\" name=\"usrname\" required> <br><br> Password: <input type=\"password\" name=\"password\" required> <br><br> <input type=\"submit\"> </form></body> </html>", "e": 26544, "s": 25825, "text": null }, { "code": null, "e": 26552, "s": 26544, "text": "Output:" }, { "code": null, "e": 26689, "s": 26552, "text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course." }, { "code": null, "e": 26698, "s": 26689, "text": "CSS-Misc" }, { "code": null, "e": 26708, "s": 26698, "text": "HTML-Misc" }, { "code": null, "e": 26712, "s": 26708, "text": "CSS" }, { "code": null, "e": 26717, "s": 26712, "text": "HTML" }, { "code": null, "e": 26734, "s": 26717, "text": "Web Technologies" }, { "code": null, "e": 26739, "s": 26734, "text": "HTML" }, { "code": null, "e": 26837, "s": 26739, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26874, "s": 26837, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 26903, "s": 26874, "text": "Form validation using jQuery" }, { "code": null, "e": 26942, "s": 26903, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 26984, "s": 26942, "text": "Search Bar using HTML, CSS and JavaScript" }, { "code": null, "e": 27019, "s": 26984, "text": "How to style a checkbox using CSS?" }, { "code": null, "e": 27079, "s": 27019, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 27140, "s": 27079, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" }, { "code": null, "e": 27193, "s": 27140, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 27243, "s": 27193, "text": "How to Insert Form Data into Database using PHP ?" } ]
MySQL status in terms of active or total connections?
The active or total connection can be known with the help of threads_connected variable. The variable tells about the number of currently open connections. The query is as follows − mysql> show status where `variable_name` = 'Threads_connected'; Here is the output. +-------------------+-------+ | Variable_name | Value | +-------------------+-------+ | Threads_connected | 1 | +-------------------+-------+ 1 row in set (0.06 sec) We can check the same with the help of show command. The query is as follows − mysql> show processlist; Here is the output. +----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+ | Id | User | Host | db | Command | Time | State | Info | +----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+ | 4 | event_scheduler | localhost | NULL | Daemon | 349012 | Waiting on empty queue | NULL | | 11 | root | localhost:54746 | business | Query | 1 | starting | show processlist | +----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+ 2 rows in set (0.31 sec)
[ { "code": null, "e": 1218, "s": 1062, "text": "The active or total connection can be known with the help of threads_connected variable. The variable tells about the number of currently open connections." }, { "code": null, "e": 1244, "s": 1218, "text": "The query is as follows −" }, { "code": null, "e": 1308, "s": 1244, "text": "mysql> show status where `variable_name` = 'Threads_connected';" }, { "code": null, "e": 1328, "s": 1308, "text": "Here is the output." }, { "code": null, "e": 1503, "s": 1328, "text": "+-------------------+-------+\n| Variable_name | Value |\n+-------------------+-------+\n| Threads_connected | 1 |\n+-------------------+-------+\n1 row in set (0.06 sec)\n" }, { "code": null, "e": 1582, "s": 1503, "text": "We can check the same with the help of show command. The query is as follows −" }, { "code": null, "e": 1607, "s": 1582, "text": "mysql> show processlist;" }, { "code": null, "e": 1627, "s": 1607, "text": "Here is the output." }, { "code": null, "e": 2355, "s": 1627, "text": "+----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+\n| Id | User | Host | db | Command | Time | State | Info |\n+----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+\n| 4 | event_scheduler | localhost | NULL | Daemon | 349012 | Waiting on empty queue | NULL |\n| 11 | root | localhost:54746 | business | Query | 1 | starting | show processlist |\n+----+-----------------+-----------------+----------+---------+--------+------------------------+------------------+\n2 rows in set (0.31 sec)\n" } ]
Trim (Remove leading and trailing spaces) a string in C#
To trim a string in C#, use regular expression. Firstly, set the pattern for regex − string pattern = "\\s+"; Let’s say the following is our string with leading and trailing spaces − string input = " Welcome User "; Now using Regex, set the pattern and get the result in a new string in C#. Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); The following is the complete example − using System; using System.Text.RegularExpressions; namespace Demo { class Program { static void Main(string[] args) { string input = " Welcome User "; string pattern = "\\s+"; string replacement = " "; Regex rgx = new Regex(pattern); string result = rgx.Replace(input, replacement); Console.WriteLine("Original String: {0}", input); Console.WriteLine("Replacement String:{0}", result); Console.ReadKey(); } } }
[ { "code": null, "e": 1110, "s": 1062, "text": "To trim a string in C#, use regular expression." }, { "code": null, "e": 1147, "s": 1110, "text": "Firstly, set the pattern for regex −" }, { "code": null, "e": 1172, "s": 1147, "text": "string pattern = \"\\\\s+\";" }, { "code": null, "e": 1245, "s": 1172, "text": "Let’s say the following is our string with leading and trailing spaces −" }, { "code": null, "e": 1278, "s": 1245, "text": "string input = \" Welcome User \";" }, { "code": null, "e": 1353, "s": 1278, "text": "Now using Regex, set the pattern and get the result in a new string in C#." }, { "code": null, "e": 1434, "s": 1353, "text": "Regex rgx = new Regex(pattern);\nstring result = rgx.Replace(input, replacement);" }, { "code": null, "e": 1474, "s": 1434, "text": "The following is the complete example −" }, { "code": null, "e": 1979, "s": 1474, "text": "using System;\nusing System.Text.RegularExpressions;\n\nnamespace Demo {\n class Program {\n static void Main(string[] args) {\n string input = \" Welcome User \";\n string pattern = \"\\\\s+\";\n string replacement = \" \";\n\n Regex rgx = new Regex(pattern);\n string result = rgx.Replace(input, replacement);\n\n Console.WriteLine(\"Original String: {0}\", input);\n Console.WriteLine(\"Replacement String:{0}\", result);\n Console.ReadKey();\n }\n }\n}" } ]
How can I save a HashMap to Shared Preferences in Android?
This example demonstrates about How can I save a HashMap to Shared Preferences in Android. Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main.xml. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/rlMain" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_margin="16dp" android:orientation="vertical"> <EditText android:id="@+id/etName" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Name" android:inputType="text" /> <EditText android:id="@+id/etAge" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Age" android:inputType="number" /> <EditText android:id="@+id/etGame" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="Favourite game" android:inputType="text" /> <Button android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="16dp" android:onClick="saveLocal" android:text="save local" /> </LinearLayout> Step 3 − Add the following code to src/MainActivity.java package app.com.sample; import android.content.Context; import android.content.SharedPreferences; import android.os.Bundle; import android.view.View; import android.widget.EditText; import android.widget.Toast; import androidx.appcompat.app.AppCompatActivity; import org.json.JSONObject; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Objects; public class MainActivity extends AppCompatActivity { final String mapKey = "map"; EditText etName, etAge, etGame; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); etName = findViewById(R.id.etName); etAge = findViewById(R.id.etAge); etGame = findViewById(R.id.etGame); Map<String, Object> outputMap = loadMap(); if (outputMap.containsKey("name")) etName.setText(Objects.requireNonNull(outputMap.get("name")).toString()); if (outputMap.containsKey("age")) etAge.setText(Objects.requireNonNull(outputMap.get("age")).toString()); if (outputMap.containsKey("game")) etGame.setText(Objects.requireNonNull(outputMap.get("game")).toString()); } public void saveLocal(View view) { String name = etName.getText().toString().trim(); String age = etAge.getText().toString().trim(); String game = etGame.getText().toString().trim(); if (name.isEmpty()) { etName.setError("*required"); etName.requestFocus(); } else if (age.isEmpty()) { etAge.setError("*required"); etAge.requestFocus(); } else if (game.isEmpty()) { etGame.setError("*required"); etGame.requestFocus(); } else { Map<String, Object> inputMap = new HashMap<>(); inputMap.put("name", name); inputMap.put("age", age); inputMap.put("game", game); saveMap(inputMap); Toast.makeText(getApplicationContext(), "Saved Locally!", Toast.LENGTH_SHORT).show(); } } private void saveMap(Map<String, Object> inputMap) { SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE); if (pSharedPref != null) { JSONObject jsonObject = new JSONObject(inputMap); String jsonString = jsonObject.toString(); SharedPreferences.Editor editor = pSharedPref.edit(); editor.remove(mapKey).apply(); editor.putString(mapKey, jsonString); editor.commit(); } } private Map<String, Object> loadMap() { Map<String, Object> outputMap = new HashMap<>(); SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences("MyVariables", Context.MODE_PRIVATE); try { if (pSharedPref != null) { String jsonString = pSharedPref.getString(mapKey, (new JSONObject()).toString()); JSONObject jsonObject = new JSONObject(jsonString); Iterator<String> keysItr = jsonObject.keys(); while (keysItr.hasNext()) { String key = keysItr.next(); outputMap.put(key, jsonObject.get(key)); } } } catch (Exception e) { e.printStackTrace(); } return outputMap; } } Step 4 − Add the following code to androidManifest.xml <?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="app.com.sample"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest> Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen – Click here to download the project code.
[ { "code": null, "e": 1153, "s": 1062, "text": "This example demonstrates about How can I save a HashMap to Shared Preferences in Android." }, { "code": null, "e": 1283, "s": 1153, "text": "Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project." }, { "code": null, "e": 1349, "s": 1283, "text": "Step 2 − Add the following code to res/layout/activity_main.xml." }, { "code": null, "e": 2431, "s": 1349, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:id=\"@+id/rlMain\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"match_parent\"\n android:layout_margin=\"16dp\"\n android:orientation=\"vertical\">\n <EditText\n android:id=\"@+id/etName\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Name\"\n android:inputType=\"text\" />\n <EditText\n android:id=\"@+id/etAge\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Age\"\n android:inputType=\"number\" />\n <EditText\n android:id=\"@+id/etGame\"\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:hint=\"Favourite game\"\n android:inputType=\"text\" />\n <Button\n android:layout_width=\"match_parent\"\n android:layout_height=\"wrap_content\"\n android:layout_marginTop=\"16dp\"\n android:onClick=\"saveLocal\"\n android:text=\"save local\" />\n</LinearLayout>" }, { "code": null, "e": 2489, "s": 2431, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 5804, "s": 2489, "text": "package app.com.sample;\nimport android.content.Context;\nimport android.content.SharedPreferences;\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.EditText;\nimport android.widget.Toast;\nimport androidx.appcompat.app.AppCompatActivity;\nimport org.json.JSONObject;\nimport java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.Objects;\npublic class MainActivity extends AppCompatActivity {\n final String mapKey = \"map\";\n EditText etName, etAge, etGame;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n etName = findViewById(R.id.etName);\n etAge = findViewById(R.id.etAge);\n etGame = findViewById(R.id.etGame);\n Map<String, Object> outputMap = loadMap();\n if (outputMap.containsKey(\"name\"))\n etName.setText(Objects.requireNonNull(outputMap.get(\"name\")).toString());\n if (outputMap.containsKey(\"age\"))\n etAge.setText(Objects.requireNonNull(outputMap.get(\"age\")).toString());\n if (outputMap.containsKey(\"game\"))\n etGame.setText(Objects.requireNonNull(outputMap.get(\"game\")).toString());\n }\n public void saveLocal(View view) {\n String name = etName.getText().toString().trim();\n String age = etAge.getText().toString().trim();\n String game = etGame.getText().toString().trim();\n if (name.isEmpty()) {\n etName.setError(\"*required\");\n etName.requestFocus();\n } else if (age.isEmpty()) {\n etAge.setError(\"*required\");\n etAge.requestFocus();\n } else if (game.isEmpty()) {\n etGame.setError(\"*required\");\n etGame.requestFocus();\n } else {\n Map<String, Object> inputMap = new HashMap<>();\n inputMap.put(\"name\", name);\n inputMap.put(\"age\", age);\n inputMap.put(\"game\", game);\n saveMap(inputMap);\n Toast.makeText(getApplicationContext(), \"Saved Locally!\", Toast.LENGTH_SHORT).show();\n }\n }\n private void saveMap(Map<String, Object> inputMap) {\n SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences(\"MyVariables\",\n Context.MODE_PRIVATE);\n if (pSharedPref != null) {\n JSONObject jsonObject = new JSONObject(inputMap);\n String jsonString = jsonObject.toString();\n SharedPreferences.Editor editor = pSharedPref.edit();\n editor.remove(mapKey).apply();\n editor.putString(mapKey, jsonString);\n editor.commit();\n }\n }\n private Map<String, Object> loadMap() {\n Map<String, Object> outputMap = new HashMap<>();\n SharedPreferences pSharedPref = getApplicationContext().getSharedPreferences(\"MyVariables\",\n Context.MODE_PRIVATE);\n try {\n if (pSharedPref != null) {\n String jsonString = pSharedPref.getString(mapKey, (new JSONObject()).toString());\n JSONObject jsonObject = new JSONObject(jsonString);\n Iterator<String> keysItr = jsonObject.keys();\n while (keysItr.hasNext()) {\n String key = keysItr.next();\n outputMap.put(key, jsonObject.get(key));\n }\n }\n } catch (Exception e) {\n e.printStackTrace();\n }\n return outputMap;\n }\n}" }, { "code": null, "e": 5860, "s": 5804, "text": "Step 4 − Add the following code to androidManifest.xml" }, { "code": null, "e": 6533, "s": 5860, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n package=\"app.com.sample\">\n <application\n android:allowBackup=\"true\"\n android:icon=\"@mipmap/ic_launcher\"\n android:label=\"@string/app_name\"\n android:roundIcon=\"@mipmap/ic_launcher_round\"\n android:supportsRtl=\"true\"\n android:theme=\"@style/AppTheme\">\n <activity android:name=\".MainActivity\">\n <intent-filter>\n <action android:name=\"android.intent.action.MAIN\" />\n <category android:name=\"android.intent.category.LAUNCHER\" />\n </intent-filter>\n </activity>\n </application>\n</manifest>" }, { "code": null, "e": 6880, "s": 6533, "text": "Let's try to run your application. I assume you have connected your actual Android Mobile device with your computer. To run the app from android studio, open one of your project's activity files and Click Run Icon from the toolbar. Select your mobile device as an option and then check your mobile device which will display your default screen –" }, { "code": null, "e": 6921, "s": 6880, "text": "Click here to download the project code." } ]
Python | Maximum distance between elements - GeeksforGeeks
01 Mar, 2020 Sometimes, while working with lists, we can have a problem in which we need to find maximum distance between reoccurring elements. This kind of problem can have application in competitive programming and web development domain. Let’s discuss certain way in which this task can be performed. Method : Using loop + max() + defaultdict() + enumerate()The combination of above functions can be used to perform this particular task. In this, we first initialize the temp dict with list using defaultdict(). The iteration is using enumerate() and max() performs the maximum distance between all similar numbers in list. # Python3 code to demonstrate # Maximum distance between elements# using max() + enumerate() + loop + defaultdict()from collections import defaultdict # Initializing listtest_list = [4, 5, 6, 4, 6, 3] # printing original listprint("The original list is : " + str(test_list)) # Maximum distance between elements# using max() + enumerate() + loop + defaultdict()temp = defaultdict(list)for idx, ele in enumerate(test_list): temp[ele].append(idx)res = max(temp[ele][-1]-temp[ele][0] for ele in temp) # printing result print ("Maximum distance between same element is : " + str(res)) The original list is : [4, 5, 6, 4, 6, 3] Maximum distance between same element is : 3 Python list-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Read a file line by line in Python How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Split string into list of characters Python | Convert a list to dictionary
[ { "code": null, "e": 25763, "s": 25735, "text": "\n01 Mar, 2020" }, { "code": null, "e": 26054, "s": 25763, "text": "Sometimes, while working with lists, we can have a problem in which we need to find maximum distance between reoccurring elements. This kind of problem can have application in competitive programming and web development domain. Let’s discuss certain way in which this task can be performed." }, { "code": null, "e": 26377, "s": 26054, "text": "Method : Using loop + max() + defaultdict() + enumerate()The combination of above functions can be used to perform this particular task. In this, we first initialize the temp dict with list using defaultdict(). The iteration is using enumerate() and max() performs the maximum distance between all similar numbers in list." }, { "code": "# Python3 code to demonstrate # Maximum distance between elements# using max() + enumerate() + loop + defaultdict()from collections import defaultdict # Initializing listtest_list = [4, 5, 6, 4, 6, 3] # printing original listprint(\"The original list is : \" + str(test_list)) # Maximum distance between elements# using max() + enumerate() + loop + defaultdict()temp = defaultdict(list)for idx, ele in enumerate(test_list): temp[ele].append(idx)res = max(temp[ele][-1]-temp[ele][0] for ele in temp) # printing result print (\"Maximum distance between same element is : \" + str(res))", "e": 26964, "s": 26377, "text": null }, { "code": null, "e": 27052, "s": 26964, "text": "The original list is : [4, 5, 6, 4, 6, 3]\nMaximum distance between same element is : 3\n" }, { "code": null, "e": 27075, "s": 27054, "text": "Python list-programs" }, { "code": null, "e": 27082, "s": 27075, "text": "Python" }, { "code": null, "e": 27098, "s": 27082, "text": "Python Programs" }, { "code": null, "e": 27196, "s": 27098, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27214, "s": 27196, "text": "Python Dictionary" }, { "code": null, "e": 27249, "s": 27214, "text": "Read a file line by line in Python" }, { "code": null, "e": 27281, "s": 27249, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27303, "s": 27281, "text": "Enumerate() in Python" }, { "code": null, "e": 27345, "s": 27303, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 27388, "s": 27345, "text": "Python program to convert a list to string" }, { "code": null, "e": 27410, "s": 27388, "text": "Defaultdict in Python" }, { "code": null, "e": 27449, "s": 27410, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27495, "s": 27449, "text": "Python | Split string into list of characters" } ]
Check if two nodes are cousins in a Binary Tree | Set-2 - GeeksforGeeks
23 Jun, 2021 Given a binary tree and the two nodes say ‘a’ and ‘b’, determine whether two given nodes are cousins of each other or not.Two nodes are cousins of each other if they are at same level and have different parents.Example: 6 / \ 3 5 / \ / \ 7 8 1 3 Say two node be 7 and 1, result is TRUE. Say two nodes are 3 and 5, result is FALSE. Say two nodes are 7 and 5, result is FALSE. A solution in Set-1 that finds whether given nodes are cousins or not by performing three traversals of binary tree has been discussed. The problem can be solved by performing level order traversal. The idea is to use a queue to perform level order traversal, in which each queue element is a pair of node and parent of that node. For each node visited in level order traversal, check if that node is either first given node or second given node. If any node is found store parent of that node. While performing level order traversal, one level is traversed at a time. If both nodes are found in given level, then their parent values are compared to check if they are siblings or not. If one node is found in given level and another is not found, then given nodes are not cousins.Below is the implementation of above approach: C++ Java Python3 C# Javascript // CPP program to check if two Nodes in// a binary tree are cousins// using level-order traversals#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // A utility function to create a new// Binary Tree Nodestruct Node* newNode(int item){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Returns true if a and b are cousins,// otherwise false.bool isCousin(Node* root, Node* a, Node* b){ if (root == NULL) return false; // To store parent of node a. Node* parA = NULL; // To store parent of node b. Node* parB = NULL; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. queue<pair<Node*, Node*> > q; // Dummy node to act like parent // of root node. Node* tmp = newNode(-1); // To store front element of queue. pair<Node*, Node*> ele; // Push root to queue. q.push(make_pair(root, tmp)); int levSize; while (!q.empty()) { // find number of elements in // current level. levSize = q.size(); while (levSize) { ele = q.front(); q.pop(); // check if current node is node a // or node b or not. if (ele.first->data == a->data) { parA = ele.second; } if (ele.first->data == b->data) { parB = ele.second; } // push children of current node // to queue. if (ele.first->left) { q.push(make_pair(ele.first->left, ele.first)); } if (ele.first->right) { q.push(make_pair(ele.first->right, ele.first)); } levSize--; // If both nodes are found in // current level then no need // to traverse current level further. if (parA && parB) break; } // Check if both nodes are siblings // or not. if (parA && parB) { return parA != parB; } // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA && !parB) || (parB && !parA)) { return false; } } return false;}// Driver Codeint main(){ /* 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 15 8 */ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); struct Node *Node1, *Node2; Node1 = root->left->left; Node2 = root->right->right; isCousin(root, Node1, Node2) ? puts("Yes") : puts("No"); return 0;} // Java program to check if two Nodes in// a binary tree are cousins// using level-order traversalsimport java.util.*;import javafx.util.Pair; // User defined node classclass Node{ int data; Node left, right; // Constructor to create a new tree node Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // Returns true if a and b are cousins, // otherwise false. boolean isCousin(Node node, Node a, Node b) { if(node == null) return false; // To store parent of node a. Node parA = null; // To store parent of node b. Node parB = null; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. Queue<Pair <Node,Node>> q = new LinkedList<> (); // Dummy node to act like parent // of root node. Node tmp = new Node(-1); // To store front element of queue. Pair<Node, Node> ele; // Push root to queue. q.add(new Pair <Node,Node> (node, tmp)); int levelSize; while(!q.isEmpty()) { // find number of elements in // current level. levelSize = q.size(); while(levelSize != 0) { ele = q.peek(); q.remove(); // check if current node is node a // or node b or not. if(ele.getKey().data == a.data) parA = ele.getValue(); if(ele.getKey().data == b.data) parB = ele.getValue(); // push children of current node // to queue. if(ele.getKey().left != null) q.add(new Pair<Node, Node>(ele.getKey().left, ele.getKey())); if(ele.getKey().right != null) q.add(new Pair<Node, Node>(ele.getKey().right, ele.getKey())); levelSize--; // If both nodes are found in // current level then no need // to traverse current level further. if(parA != null && parB != null) break; } // Check if both nodes are siblings // or not. if(parA != null && parB != null) return parA != parB; // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA!=null && parB==null) || (parB!=null && parA==null)) return false; } return false; } // Driver code public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.right.right = new Node(15); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Node Node1, Node2; Node1 = tree.root.left.right.right; Node2 = tree.root.right.left.right; if (tree.isCousin(tree.root, Node1, Node2)) System.out.println("Yes"); else System.out.println("No"); }} // This code is contributed by shubham96301 # Python3 program to check if two# Nodes in a binary tree are cousins# using level-order traversals # A Binary Tree Nodeclass Node: def __init__(self, item): self.data = item self.left = None self.right = None # Returns True if a and b# are cousins, otherwise False.def isCousin(root, a, b): if root == None: return False # To store parent of node a. parA = None # To store parent of node b. parB = None # queue to perform level order # traversal. Each element of queue # is a pair of node and its parent. q = [] # Dummy node to act like # parent of root node. tmp = Node(-1) # Push root to queue. q.append((root, tmp)) while len(q) > 0: # find number of elements in # current level. levSize = len(q) while levSize: ele = q.pop(0) # check if current node is # node a or node b or not. if ele[0].data == a.data: parA = ele[1] if ele[0].data == b.data: parB = ele[1] # push children of # current node to queue. if ele[0].left: q.append((ele[0].left, ele[0])) if ele[0].right: q.append((ele[0].right, ele[0])) levSize -= 1 # If both nodes are found in # current level then no need # to traverse current level further. if parA and parB: break # Check if both nodes # are siblings or not. if parA and parB: return parA != parB # If one node is found in current level # and another is not found, then # both nodes are not cousins. if (parA and not parB) or (parB and not parA): return False return False # Driver Codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.right = Node(15) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) Node1 = root.left.left Node2 = root.right.right if isCousin(root, Node1, Node2): print('Yes') else: print('No') # This code is contributed by Rituraj Jain // C# program to check if two Nodes in// a binary tree are cousins// using level-order traversalsusing System;using System.Collections.Generic; // User defined node classpublic class Node{ public int data; public Node left, right; // Constructor to create a new tree node public Node(int item) { data = item; left = right = null; }}// User defined pair classpublic class Pair{ public Node first, second; // Constructor to create a new tree node public Pair(Node first, Node second) { this.first = first; this.second = second; }} class BinaryTree{ Node root; // Returns true if a and b are cousins, // otherwise false. Boolean isCousin(Node node, Node a, Node b) { if(node == null) return false; // To store parent of node a. Node parA = null; // To store parent of node b. Node parB = null; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. Queue<Pair > q = new Queue<Pair > (); // Dummy node to act like parent // of root node. Node tmp = new Node(-1); // To store front element of queue. Pair ele; // Push root to queue. q.Enqueue(new Pair (node, tmp)); int levelSize; while(q.Count>0) { // find number of elements in // current level. levelSize = q.Count; while(levelSize != 0) { ele = q.Peek(); q.Dequeue(); // check if current node is node a // or node b or not. if(ele.first.data == a.data) parA = ele.second; if(ele.first.data == b.data) parB = ele.second; // push children of current node // to queue. if(ele.first.left != null) q.Enqueue(new Pair(ele.first.left, ele.first)); if(ele.first.right != null) q.Enqueue(new Pair(ele.first.right, ele.first)); levelSize--; // If both nodes are found in // current level then no need // to traverse current level further. if(parA != null && parB != null) break; } // Check if both nodes are siblings // or not. if(parA != null && parB != null) return parA != parB; // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA != null && parB == null) || (parB != null && parA == null)) return false; } return false; } // Driver code public static void Main(String []args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.right.right = new Node(15); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Node Node1, Node2; Node1 = tree.root.left.right.right; Node2 = tree.root.right.left.right; if (tree.isCousin(tree.root, Node1, Node2)) Console.WriteLine("Yes"); else Console.WriteLine("No"); }} // This code is contributed by Arnab Kundu <script> // JavaScript program to check if two Nodes in// a binary tree are cousins// using level-order traversals // User defined node classclass Node{ // Constructor to create a new tree node constructor(item) { this.data = item; this.left = null; this.right = null; } }// User defined pair classclass Pair{ // Constructor to create a new tree node constructor(first, second) { this.first = first; this.second = second; } } var root = null;// Returns true if a and b are cousins,// otherwise false.function isCousin(node, a, b){ if(node == null) return false; // To store parent of node a. var parA = null; // To store parent of node b. var parB = null; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. var q = []; // Dummy node to act like parent // of root node. var tmp = new Node(-1); // To store front element of queue. var ele; // Push root to queue. q.push(new Pair (node, tmp)); var levelSize; while(q.length>0) { // find number of elements in // current level. levelSize = q.length; while(levelSize != 0) { ele = q[0]; q.shift(); // check if current node is node a // or node b or not. if(ele.first.data == a.data) parA = ele.second; if(ele.first.data == b.data) parB = ele.second; // push children of current node // to queue. if(ele.first.left != null) q.push(new Pair(ele.first.left, ele.first)); if(ele.first.right != null) q.push(new Pair(ele.first.right, ele.first)); levelSize--; // If both nodes are found in // current level then no need // to traverse current level further. if(parA != null && parB != null) break; } // Check if both nodes are siblings // or not. if(parA != null && parB != null) return parA != parB; // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA != null && parB == null) || (parB != null && parA == null)) return false; } return false;}// Driver coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.left.right.right = new Node(15);root.right.left = new Node(6);root.right.right = new Node(7);root.right.left.right = new Node(8);var Node1, Node2;Node1 = root.left.right.right;Node2 = root.right.left.right;if (isCousin(root, Node1, Node2)) document.write("Yes");else document.write("No"); </script> Yes Time Complexity: O(n) Auxiliary Space: O(n) nobody_cares rituraj_jain andrew1234 rutvik_56 Binary Tree cpp-queue Data Structures-Tree Traversals tree-level-order Tree Tree Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Decision Tree Construct Tree from given Inorder and Preorder traversals Introduction to Tree Data Structure Complexity of different operations in Binary tree, Binary Search Tree and AVL tree Expression Tree Lowest Common Ancestor in a Binary Tree | Set 1 Deletion in a Binary Tree AVL Tree | Set 2 (Deletion) BFS vs DFS for Binary Tree Binary Tree (Array implementation)
[ { "code": null, "e": 26681, "s": 26653, "text": "\n23 Jun, 2021" }, { "code": null, "e": 26901, "s": 26681, "text": "Given a binary tree and the two nodes say ‘a’ and ‘b’, determine whether two given nodes are cousins of each other or not.Two nodes are cousins of each other if they are at same level and have different parents.Example:" }, { "code": null, "e": 27079, "s": 26901, "text": " 6\n / \\\n 3 5\n / \\ / \\\n7 8 1 3\nSay two node be 7 and 1, result is TRUE.\nSay two nodes are 3 and 5, result is FALSE.\nSay two nodes are 7 and 5, result is FALSE." }, { "code": null, "e": 27910, "s": 27081, "text": "A solution in Set-1 that finds whether given nodes are cousins or not by performing three traversals of binary tree has been discussed. The problem can be solved by performing level order traversal. The idea is to use a queue to perform level order traversal, in which each queue element is a pair of node and parent of that node. For each node visited in level order traversal, check if that node is either first given node or second given node. If any node is found store parent of that node. While performing level order traversal, one level is traversed at a time. If both nodes are found in given level, then their parent values are compared to check if they are siblings or not. If one node is found in given level and another is not found, then given nodes are not cousins.Below is the implementation of above approach: " }, { "code": null, "e": 27914, "s": 27910, "text": "C++" }, { "code": null, "e": 27919, "s": 27914, "text": "Java" }, { "code": null, "e": 27927, "s": 27919, "text": "Python3" }, { "code": null, "e": 27930, "s": 27927, "text": "C#" }, { "code": null, "e": 27941, "s": 27930, "text": "Javascript" }, { "code": "// CPP program to check if two Nodes in// a binary tree are cousins// using level-order traversals#include <bits/stdc++.h>using namespace std; // A Binary Tree Nodestruct Node { int data; struct Node *left, *right;}; // A utility function to create a new// Binary Tree Nodestruct Node* newNode(int item){ struct Node* temp = (struct Node*)malloc(sizeof(struct Node)); temp->data = item; temp->left = temp->right = NULL; return temp;} // Returns true if a and b are cousins,// otherwise false.bool isCousin(Node* root, Node* a, Node* b){ if (root == NULL) return false; // To store parent of node a. Node* parA = NULL; // To store parent of node b. Node* parB = NULL; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. queue<pair<Node*, Node*> > q; // Dummy node to act like parent // of root node. Node* tmp = newNode(-1); // To store front element of queue. pair<Node*, Node*> ele; // Push root to queue. q.push(make_pair(root, tmp)); int levSize; while (!q.empty()) { // find number of elements in // current level. levSize = q.size(); while (levSize) { ele = q.front(); q.pop(); // check if current node is node a // or node b or not. if (ele.first->data == a->data) { parA = ele.second; } if (ele.first->data == b->data) { parB = ele.second; } // push children of current node // to queue. if (ele.first->left) { q.push(make_pair(ele.first->left, ele.first)); } if (ele.first->right) { q.push(make_pair(ele.first->right, ele.first)); } levSize--; // If both nodes are found in // current level then no need // to traverse current level further. if (parA && parB) break; } // Check if both nodes are siblings // or not. if (parA && parB) { return parA != parB; } // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA && !parB) || (parB && !parA)) { return false; } } return false;}// Driver Codeint main(){ /* 1 / \\ 2 3 / \\ / \\ 4 5 6 7 \\ \\ 15 8 */ struct Node* root = newNode(1); root->left = newNode(2); root->right = newNode(3); root->left->left = newNode(4); root->left->right = newNode(5); root->left->right->right = newNode(15); root->right->left = newNode(6); root->right->right = newNode(7); root->right->left->right = newNode(8); struct Node *Node1, *Node2; Node1 = root->left->left; Node2 = root->right->right; isCousin(root, Node1, Node2) ? puts(\"Yes\") : puts(\"No\"); return 0;}", "e": 30990, "s": 27941, "text": null }, { "code": "// Java program to check if two Nodes in// a binary tree are cousins// using level-order traversalsimport java.util.*;import javafx.util.Pair; // User defined node classclass Node{ int data; Node left, right; // Constructor to create a new tree node Node(int item) { data = item; left = right = null; }} class BinaryTree{ Node root; // Returns true if a and b are cousins, // otherwise false. boolean isCousin(Node node, Node a, Node b) { if(node == null) return false; // To store parent of node a. Node parA = null; // To store parent of node b. Node parB = null; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. Queue<Pair <Node,Node>> q = new LinkedList<> (); // Dummy node to act like parent // of root node. Node tmp = new Node(-1); // To store front element of queue. Pair<Node, Node> ele; // Push root to queue. q.add(new Pair <Node,Node> (node, tmp)); int levelSize; while(!q.isEmpty()) { // find number of elements in // current level. levelSize = q.size(); while(levelSize != 0) { ele = q.peek(); q.remove(); // check if current node is node a // or node b or not. if(ele.getKey().data == a.data) parA = ele.getValue(); if(ele.getKey().data == b.data) parB = ele.getValue(); // push children of current node // to queue. if(ele.getKey().left != null) q.add(new Pair<Node, Node>(ele.getKey().left, ele.getKey())); if(ele.getKey().right != null) q.add(new Pair<Node, Node>(ele.getKey().right, ele.getKey())); levelSize--; // If both nodes are found in // current level then no need // to traverse current level further. if(parA != null && parB != null) break; } // Check if both nodes are siblings // or not. if(parA != null && parB != null) return parA != parB; // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA!=null && parB==null) || (parB!=null && parA==null)) return false; } return false; } // Driver code public static void main(String args[]) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.right.right = new Node(15); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Node Node1, Node2; Node1 = tree.root.left.right.right; Node2 = tree.root.right.left.right; if (tree.isCousin(tree.root, Node1, Node2)) System.out.println(\"Yes\"); else System.out.println(\"No\"); }} // This code is contributed by shubham96301", "e": 34445, "s": 30990, "text": null }, { "code": "# Python3 program to check if two# Nodes in a binary tree are cousins# using level-order traversals # A Binary Tree Nodeclass Node: def __init__(self, item): self.data = item self.left = None self.right = None # Returns True if a and b# are cousins, otherwise False.def isCousin(root, a, b): if root == None: return False # To store parent of node a. parA = None # To store parent of node b. parB = None # queue to perform level order # traversal. Each element of queue # is a pair of node and its parent. q = [] # Dummy node to act like # parent of root node. tmp = Node(-1) # Push root to queue. q.append((root, tmp)) while len(q) > 0: # find number of elements in # current level. levSize = len(q) while levSize: ele = q.pop(0) # check if current node is # node a or node b or not. if ele[0].data == a.data: parA = ele[1] if ele[0].data == b.data: parB = ele[1] # push children of # current node to queue. if ele[0].left: q.append((ele[0].left, ele[0])) if ele[0].right: q.append((ele[0].right, ele[0])) levSize -= 1 # If both nodes are found in # current level then no need # to traverse current level further. if parA and parB: break # Check if both nodes # are siblings or not. if parA and parB: return parA != parB # If one node is found in current level # and another is not found, then # both nodes are not cousins. if (parA and not parB) or (parB and not parA): return False return False # Driver Codeif __name__ == '__main__': root = Node(1) root.left = Node(2) root.right = Node(3) root.left.left = Node(4) root.left.right = Node(5) root.left.right.right = Node(15) root.right.left = Node(6) root.right.right = Node(7) root.right.left.right = Node(8) Node1 = root.left.left Node2 = root.right.right if isCousin(root, Node1, Node2): print('Yes') else: print('No') # This code is contributed by Rituraj Jain", "e": 36805, "s": 34445, "text": null }, { "code": "// C# program to check if two Nodes in// a binary tree are cousins// using level-order traversalsusing System;using System.Collections.Generic; // User defined node classpublic class Node{ public int data; public Node left, right; // Constructor to create a new tree node public Node(int item) { data = item; left = right = null; }}// User defined pair classpublic class Pair{ public Node first, second; // Constructor to create a new tree node public Pair(Node first, Node second) { this.first = first; this.second = second; }} class BinaryTree{ Node root; // Returns true if a and b are cousins, // otherwise false. Boolean isCousin(Node node, Node a, Node b) { if(node == null) return false; // To store parent of node a. Node parA = null; // To store parent of node b. Node parB = null; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. Queue<Pair > q = new Queue<Pair > (); // Dummy node to act like parent // of root node. Node tmp = new Node(-1); // To store front element of queue. Pair ele; // Push root to queue. q.Enqueue(new Pair (node, tmp)); int levelSize; while(q.Count>0) { // find number of elements in // current level. levelSize = q.Count; while(levelSize != 0) { ele = q.Peek(); q.Dequeue(); // check if current node is node a // or node b or not. if(ele.first.data == a.data) parA = ele.second; if(ele.first.data == b.data) parB = ele.second; // push children of current node // to queue. if(ele.first.left != null) q.Enqueue(new Pair(ele.first.left, ele.first)); if(ele.first.right != null) q.Enqueue(new Pair(ele.first.right, ele.first)); levelSize--; // If both nodes are found in // current level then no need // to traverse current level further. if(parA != null && parB != null) break; } // Check if both nodes are siblings // or not. if(parA != null && parB != null) return parA != parB; // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA != null && parB == null) || (parB != null && parA == null)) return false; } return false; } // Driver code public static void Main(String []args) { BinaryTree tree = new BinaryTree(); tree.root = new Node(1); tree.root.left = new Node(2); tree.root.right = new Node(3); tree.root.left.left = new Node(4); tree.root.left.right = new Node(5); tree.root.left.right.right = new Node(15); tree.root.right.left = new Node(6); tree.root.right.right = new Node(7); tree.root.right.left.right = new Node(8); Node Node1, Node2; Node1 = tree.root.left.right.right; Node2 = tree.root.right.left.right; if (tree.isCousin(tree.root, Node1, Node2)) Console.WriteLine(\"Yes\"); else Console.WriteLine(\"No\"); }} // This code is contributed by Arnab Kundu", "e": 40439, "s": 36805, "text": null }, { "code": "<script> // JavaScript program to check if two Nodes in// a binary tree are cousins// using level-order traversals // User defined node classclass Node{ // Constructor to create a new tree node constructor(item) { this.data = item; this.left = null; this.right = null; } }// User defined pair classclass Pair{ // Constructor to create a new tree node constructor(first, second) { this.first = first; this.second = second; } } var root = null;// Returns true if a and b are cousins,// otherwise false.function isCousin(node, a, b){ if(node == null) return false; // To store parent of node a. var parA = null; // To store parent of node b. var parB = null; // queue to perform level order // traversal. Each element of // queue is a pair of node and // its parent. var q = []; // Dummy node to act like parent // of root node. var tmp = new Node(-1); // To store front element of queue. var ele; // Push root to queue. q.push(new Pair (node, tmp)); var levelSize; while(q.length>0) { // find number of elements in // current level. levelSize = q.length; while(levelSize != 0) { ele = q[0]; q.shift(); // check if current node is node a // or node b or not. if(ele.first.data == a.data) parA = ele.second; if(ele.first.data == b.data) parB = ele.second; // push children of current node // to queue. if(ele.first.left != null) q.push(new Pair(ele.first.left, ele.first)); if(ele.first.right != null) q.push(new Pair(ele.first.right, ele.first)); levelSize--; // If both nodes are found in // current level then no need // to traverse current level further. if(parA != null && parB != null) break; } // Check if both nodes are siblings // or not. if(parA != null && parB != null) return parA != parB; // If one node is found in current level // and another is not found, then // both nodes are not cousins. if ((parA != null && parB == null) || (parB != null && parA == null)) return false; } return false;}// Driver coderoot = new Node(1);root.left = new Node(2);root.right = new Node(3);root.left.left = new Node(4);root.left.right = new Node(5);root.left.right.right = new Node(15);root.right.left = new Node(6);root.right.right = new Node(7);root.right.left.right = new Node(8);var Node1, Node2;Node1 = root.left.right.right;Node2 = root.right.left.right;if (isCousin(root, Node1, Node2)) document.write(\"Yes\");else document.write(\"No\"); </script>", "e": 43294, "s": 40439, "text": null }, { "code": null, "e": 43298, "s": 43294, "text": "Yes" }, { "code": null, "e": 43345, "s": 43300, "text": "Time Complexity: O(n) Auxiliary Space: O(n) " }, { "code": null, "e": 43358, "s": 43345, "text": "nobody_cares" }, { "code": null, "e": 43371, "s": 43358, "text": "rituraj_jain" }, { "code": null, "e": 43382, "s": 43371, "text": "andrew1234" }, { "code": null, "e": 43392, "s": 43382, "text": "rutvik_56" }, { "code": null, "e": 43404, "s": 43392, "text": "Binary Tree" }, { "code": null, "e": 43414, "s": 43404, "text": "cpp-queue" }, { "code": null, "e": 43446, "s": 43414, "text": "Data Structures-Tree Traversals" }, { "code": null, "e": 43463, "s": 43446, "text": "tree-level-order" }, { "code": null, "e": 43468, "s": 43463, "text": "Tree" }, { "code": null, "e": 43473, "s": 43468, "text": "Tree" }, { "code": null, "e": 43571, "s": 43473, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 43585, "s": 43571, "text": "Decision Tree" }, { "code": null, "e": 43643, "s": 43585, "text": "Construct Tree from given Inorder and Preorder traversals" }, { "code": null, "e": 43679, "s": 43643, "text": "Introduction to Tree Data Structure" }, { "code": null, "e": 43762, "s": 43679, "text": "Complexity of different operations in Binary tree, Binary Search Tree and AVL tree" }, { "code": null, "e": 43778, "s": 43762, "text": "Expression Tree" }, { "code": null, "e": 43826, "s": 43778, "text": "Lowest Common Ancestor in a Binary Tree | Set 1" }, { "code": null, "e": 43852, "s": 43826, "text": "Deletion in a Binary Tree" }, { "code": null, "e": 43880, "s": 43852, "text": "AVL Tree | Set 2 (Deletion)" }, { "code": null, "e": 43907, "s": 43880, "text": "BFS vs DFS for Binary Tree" } ]
C program to find frequency of each digit in a string
Suppose we have a string s. The s contains letters and digits both. We shall have to find frequencies of each digit and display them. To do this we can make an array of size 10 for each digits (0 through 9), initially all elements are 0 inside the array, then when we encounter a digit simply increase the value of that index and finally print them all. So, if the input is like s = "we85abc586wow236h69", then the output will be (Number 2, Freq 1) (Number 3, Freq 1) (Number 5, Freq 2) (Number 6, Freq 3) (Number 8, Freq 2) (Number 9, Freq 1) To solve this, we will follow these steps − Define an array freq of size: 10 and initialize all elements with 0 Define an array freq of size: 10 and initialize all elements with 0 for initialize i := 0, when i < size of s, update (increase i by 1), do:if s[i] is numeric, then:increase freq[s[i] - ASCII of '0'] by 1 for initialize i := 0, when i < size of s, update (increase i by 1), do: if s[i] is numeric, then:increase freq[s[i] - ASCII of '0'] by 1 if s[i] is numeric, then: increase freq[s[i] - ASCII of '0'] by 1 increase freq[s[i] - ASCII of '0'] by 1 for initialize i := 0, when i < 10, update (increase i by 1), do:if freq[i] > 0, then:display (Number i , Freq freq[i]) for initialize i := 0, when i < 10, update (increase i by 1), do: if freq[i] > 0, then:display (Number i , Freq freq[i]) if freq[i] > 0, then: display (Number i , Freq freq[i]) display (Number i , Freq freq[i]) Let us see the following implementation to get better understanding − #include <stdio.h> #include <string.h> void solve(char *s){ int freq[10] = {0}; for(int i = 0; i < strlen(s); i++){ if(s[i] >= '0' && s[i] <= '9'){ freq[s[i] - '0']++ ; } } for(int i = 0; i<10; i++){ if(freq[i] > 0) printf("(Number %d, Freq %d)\n", i, freq[i]); } } int main(){ char *s = "we85abc586wow236h69"; solve(s); } "we85abc586wow236h69" (Number 2, Freq 1) (Number 3, Freq 1) (Number 5, Freq 2) (Number 6, Freq 3) (Number 8, Freq 2) (Number 9, Freq 1)
[ { "code": null, "e": 1416, "s": 1062, "text": "Suppose we have a string s. The s contains letters and digits both. We shall have to find frequencies of each digit and display them. To do this we can make an array of size 10 for each digits (0 through 9), initially all elements are 0 inside the array, then when we encounter a digit simply increase the value of that index and finally print them all." }, { "code": null, "e": 1606, "s": 1416, "text": "So, if the input is like s = \"we85abc586wow236h69\", then the output will be (Number 2, Freq 1) (Number 3, Freq 1) (Number 5, Freq 2) (Number 6, Freq 3) (Number 8, Freq 2) (Number 9, Freq 1)" }, { "code": null, "e": 1650, "s": 1606, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1718, "s": 1650, "text": "Define an array freq of size: 10 and initialize all elements with 0" }, { "code": null, "e": 1786, "s": 1718, "text": "Define an array freq of size: 10 and initialize all elements with 0" }, { "code": null, "e": 1923, "s": 1786, "text": "for initialize i := 0, when i < size of s, update (increase i by 1), do:if s[i] is numeric, then:increase freq[s[i] - ASCII of '0'] by 1" }, { "code": null, "e": 1996, "s": 1923, "text": "for initialize i := 0, when i < size of s, update (increase i by 1), do:" }, { "code": null, "e": 2061, "s": 1996, "text": "if s[i] is numeric, then:increase freq[s[i] - ASCII of '0'] by 1" }, { "code": null, "e": 2087, "s": 2061, "text": "if s[i] is numeric, then:" }, { "code": null, "e": 2127, "s": 2087, "text": "increase freq[s[i] - ASCII of '0'] by 1" }, { "code": null, "e": 2167, "s": 2127, "text": "increase freq[s[i] - ASCII of '0'] by 1" }, { "code": null, "e": 2287, "s": 2167, "text": "for initialize i := 0, when i < 10, update (increase i by 1), do:if freq[i] > 0, then:display (Number i , Freq freq[i])" }, { "code": null, "e": 2353, "s": 2287, "text": "for initialize i := 0, when i < 10, update (increase i by 1), do:" }, { "code": null, "e": 2408, "s": 2353, "text": "if freq[i] > 0, then:display (Number i , Freq freq[i])" }, { "code": null, "e": 2430, "s": 2408, "text": "if freq[i] > 0, then:" }, { "code": null, "e": 2464, "s": 2430, "text": "display (Number i , Freq freq[i])" }, { "code": null, "e": 2498, "s": 2464, "text": "display (Number i , Freq freq[i])" }, { "code": null, "e": 2568, "s": 2498, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2972, "s": 2568, "text": "#include <stdio.h>\n#include <string.h>\nvoid solve(char *s){\n int freq[10] = {0};\n for(int i = 0; i < strlen(s); i++){\n if(s[i] >= '0' && s[i] <= '9'){\n freq[s[i] - '0']++ ; \n }\n }\n for(int i = 0; i<10; i++){\n if(freq[i] > 0)\n printf(\"(Number %d, Freq %d)\\n\", i, freq[i]);\n }\n}\nint main(){\n char *s = \"we85abc586wow236h69\";\n solve(s);\n}\n" }, { "code": null, "e": 2994, "s": 2972, "text": "\"we85abc586wow236h69\"" }, { "code": null, "e": 3108, "s": 2994, "text": "(Number 2, Freq 1)\n(Number 3, Freq 1)\n(Number 5, Freq 2)\n(Number 6, Freq 3)\n(Number 8, Freq 2)\n(Number 9, Freq 1)" } ]
C - Type Conversions - onlinetutorialspoint
PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC EXCEPTIONS COLLECTIONS SWING JDBC JAVA 8 SPRING SPRING BOOT HIBERNATE PYTHON PHP JQUERY PROGRAMMINGJava ExamplesC Examples Java Examples C Examples C Tutorials aws In this tutorial, we are going to learn about type conversions in the C language. When an operator has operands of different types, it is referred to as mixed mode. C supports the use of mixed-mode operations in expressions. For an operation to take place, both the operands must be of the same type. Type conversion is performed to convert one or both the operands to an appropriate data type before evaluation. Type conversion means converting one data type value into another data type value. There are two types of type conversions: implicit conversion (also called type coercion) explicit conversion (also called type casting) In the case of implicit type conversions, the compiler automatically converts one data type value into another data type value. It is also known as Automatic type conversion. Implicit type conversions can occur during an assignment or while using any other operators. During the assignment, the R-value is converted to the type of L-value. For example, in the statement int a = 17.35; 17.35 which is the value on the right-hand side, is automatically converted into an int type as 17. When values of different data types are used in arithmetic, relational and logical operators, the value of the lower size data type is converted automatically into the data type of the higher size before the evaluation. The conversion order is: bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double A programmer can instruct the compiler to explicitly convert a value of one type to another using a typecast operator. When a typecast operator is used explicitly, the type conversion process is called explicit type conversion or typecasting. This is user-defined. The syntax for using a typecast operator is: ( data_type ) expression where the expression is converted to the target data_type enclosed within the parentheses. Here, the expression may contain constants or variables and the data_type must be a primitive data type or void. For example, the expression (float) 1 / 3 is evaluated as 1.0 / 3 yielding 0.333333, whereas 1 / 3 yields 0 In the expression ((int)num)%2, if num is a float variable with value 5.5, then the expression evaluates to 1. For example, let us understand the following code: #include <stdio.h> void main () { float a, b; a = 35 / 17; b = (float) 35 / 17; printf("a = %f, b = %f\n", a, b); } output: a = 2.000000, b = 2.058824 Wiki – Type Conversion Happy Learning 🙂 Python TypeCasting for Different Types Difference between b++ and b=b+1 Python String to int Conversion Example Type Inference in Java 7 Example C – Arithmetic Operators C – Floating Point Data Types C – Derived and User Defined Data Types C – Bitwise Operators C – Logical Operators C – Expressions and Statements C – Integer Data Types – int, short int, long int and char Lambda Expressions in Java AngularJs Directive Example Tutorials Python – How to merge two dict in Python ? C Number System – Decimal, Binary, Octal and Hex Python TypeCasting for Different Types Difference between b++ and b=b+1 Python String to int Conversion Example Type Inference in Java 7 Example C – Arithmetic Operators C – Floating Point Data Types C – Derived and User Defined Data Types C – Bitwise Operators C – Logical Operators C – Expressions and Statements C – Integer Data Types – int, short int, long int and char Lambda Expressions in Java AngularJs Directive Example Tutorials Python – How to merge two dict in Python ? C Number System – Decimal, Binary, Octal and Hex Δ C – Introduction C – Features C – Variables & Keywords C – Program Structure C – Comment Lines & Tokens C – Number System C – Local and Global Variables C – Scope & Lifetime of Variables C – Data Types C – Integer Data Types C – Floating Data Types C – Derived, Defined Data Types C – Type Conversions C – Arithmetic Operators C – Bitwise Operators C – Logical Operators C – Comma and sizeof Operators C – Operator Precedence and Associativity C – Relational Operators C Flow Control – if, if-else, nested if-else, if-else-if C – Switch Case C Iterative – for, while, dowhile loops C Unconditional – break, continue, goto statements C – Expressions and Statements C – Header Files & Preprocessor Directives C – One Dimensional Arrays C – Multi Dimensional Arrays C – Pointers Basics C – Pointers with Arrays C – Functions C – How to Pass Arrays to Functions C – Categories of Functions C – User defined Functions C – Formal and Actual Arguments C – Recursion functions C – Structures Part -1 C – Structures Part -2 C – Unions C – File Handling C – File Operations C – Dynamic Memory Allocation C Program – Fibonacci Series C Program – Prime or Not C Program – Factorial of Number C Program – Even or Odd C Program – Sum of digits till Single Digit C Program – Sum of digits C Program – Reverse of a number C Program – Armstrong Numbers C Program – Print prime Numbers C Program – GCD of two Numbers C Program – Number Palindrome or Not C Program – Find Largest and Smallest number in an Array C Program – Add elements of an Array C Program – Addition of Matrices C Program – Multiplication of Matrices C Program – Reverse of an Array C Program – Bubble Sort C Program – Add and Sub without using + –
[ { "code": null, "e": 158, "s": 123, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 172, "s": 158, "text": "Java Examples" }, { "code": null, "e": 183, "s": 172, "text": "C Examples" }, { "code": null, "e": 195, "s": 183, "text": "C Tutorials" }, { "code": null, "e": 199, "s": 195, "text": "aws" }, { "code": null, "e": 234, "s": 199, "text": "JAVAEXCEPTIONSCOLLECTIONSSWINGJDBC" }, { "code": null, "e": 245, "s": 234, "text": "EXCEPTIONS" }, { "code": null, "e": 257, "s": 245, "text": "COLLECTIONS" }, { "code": null, "e": 263, "s": 257, "text": "SWING" }, { "code": null, "e": 268, "s": 263, "text": "JDBC" }, { "code": null, "e": 275, "s": 268, "text": "JAVA 8" }, { "code": null, "e": 282, "s": 275, "text": "SPRING" }, { "code": null, "e": 294, "s": 282, "text": "SPRING BOOT" }, { "code": null, "e": 304, "s": 294, "text": "HIBERNATE" }, { "code": null, "e": 311, "s": 304, "text": "PYTHON" }, { "code": null, "e": 315, "s": 311, "text": "PHP" }, { "code": null, "e": 322, "s": 315, "text": "JQUERY" }, { "code": null, "e": 357, "s": 322, "text": "PROGRAMMINGJava ExamplesC Examples" }, { "code": null, "e": 371, "s": 357, "text": "Java Examples" }, { "code": null, "e": 382, "s": 371, "text": "C Examples" }, { "code": null, "e": 394, "s": 382, "text": "C Tutorials" }, { "code": null, "e": 398, "s": 394, "text": "aws" }, { "code": null, "e": 480, "s": 398, "text": "In this tutorial, we are going to learn about type conversions in the C language." }, { "code": null, "e": 700, "s": 480, "text": "When an operator has operands of different types, it is referred to as mixed mode. C supports the use of mixed-mode operations in expressions. For an operation to take place, both the operands must be of the same type." }, { "code": null, "e": 812, "s": 700, "text": "Type conversion is performed to convert one or both the operands to an appropriate data type before evaluation." }, { "code": null, "e": 936, "s": 812, "text": "Type conversion means converting one data type value into another data type value. There are two types of type conversions:" }, { "code": null, "e": 984, "s": 936, "text": "implicit conversion (also called type coercion)" }, { "code": null, "e": 1031, "s": 984, "text": "explicit conversion (also called type casting)" }, { "code": null, "e": 1206, "s": 1031, "text": "In the case of implicit type conversions, the compiler automatically converts one data type value into another data type value. It is also known as Automatic type conversion." }, { "code": null, "e": 1371, "s": 1206, "text": "Implicit type conversions can occur during an assignment or while using any other operators. During the assignment, the R-value is converted to the type of L-value." }, { "code": null, "e": 1401, "s": 1371, "text": "For example, in the statement" }, { "code": null, "e": 1416, "s": 1401, "text": "int a = 17.35;" }, { "code": null, "e": 1516, "s": 1416, "text": "17.35 which is the value on the right-hand side, is automatically converted into an int type as 17." }, { "code": null, "e": 1736, "s": 1516, "text": "When values of different data types are used in arithmetic, relational and logical operators, the value of the lower size data type is converted automatically into the data type of the higher size before the evaluation." }, { "code": null, "e": 1761, "s": 1736, "text": "The conversion order is:" }, { "code": null, "e": 1877, "s": 1761, "text": "bool -> char -> short int -> int -> unsigned int -> long -> unsigned -> long long -> float -> double -> long double" }, { "code": null, "e": 1996, "s": 1877, "text": "A programmer can instruct the compiler to explicitly convert a value of one type to another using a typecast operator." }, { "code": null, "e": 2142, "s": 1996, "text": "When a typecast operator is used explicitly, the type conversion process is called explicit type conversion or typecasting. This is user-defined." }, { "code": null, "e": 2187, "s": 2142, "text": "The syntax for using a typecast operator is:" }, { "code": null, "e": 2212, "s": 2187, "text": "( data_type ) expression" }, { "code": null, "e": 2303, "s": 2212, "text": "where the expression is converted to the target data_type enclosed within the parentheses." }, { "code": null, "e": 2416, "s": 2303, "text": "Here, the expression may contain constants or variables and the data_type must be a primitive data type or void." }, { "code": null, "e": 2444, "s": 2416, "text": "For example, the expression" }, { "code": null, "e": 2482, "s": 2444, "text": "(float) 1 / 3 is evaluated as 1.0 / 3" }, { "code": null, "e": 2524, "s": 2482, "text": "yielding 0.333333, whereas 1 / 3 yields 0" }, { "code": null, "e": 2635, "s": 2524, "text": "In the expression ((int)num)%2, if num is a float variable with value 5.5, then the expression evaluates to 1." }, { "code": null, "e": 2686, "s": 2635, "text": "For example, let us understand the following code:" }, { "code": null, "e": 2822, "s": 2686, "text": "#include <stdio.h>\nvoid main () {\n float a, b;\n a = 35 / 17;\n b = (float) 35 / 17;\n printf(\"a = %f, b = %f\\n\", a, b);\n}" }, { "code": null, "e": 2830, "s": 2822, "text": "output:" }, { "code": null, "e": 2857, "s": 2830, "text": "a = 2.000000, b = 2.058824" }, { "code": null, "e": 2880, "s": 2857, "text": "Wiki – Type Conversion" }, { "code": null, "e": 2897, "s": 2880, "text": "Happy Learning 🙂" }, { "code": null, "e": 3430, "s": 2897, "text": "\nPython TypeCasting for Different Types\nDifference between b++ and b=b+1\nPython String to int Conversion Example\nType Inference in Java 7 Example\nC – Arithmetic Operators\nC – Floating Point Data Types\nC – Derived and User Defined Data Types\nC – Bitwise Operators\nC – Logical Operators\nC – Expressions and Statements\nC – Integer Data Types – int, short int, long int and char\nLambda Expressions in Java\nAngularJs Directive Example Tutorials\nPython – How to merge two dict in Python ?\nC Number System – Decimal, Binary, Octal and Hex\n" }, { "code": null, "e": 3469, "s": 3430, "text": "Python TypeCasting for Different Types" }, { "code": null, "e": 3502, "s": 3469, "text": "Difference between b++ and b=b+1" }, { "code": null, "e": 3542, "s": 3502, "text": "Python String to int Conversion Example" }, { "code": null, "e": 3575, "s": 3542, "text": "Type Inference in Java 7 Example" }, { "code": null, "e": 3600, "s": 3575, "text": "C – Arithmetic Operators" }, { "code": null, "e": 3630, "s": 3600, "text": "C – Floating Point Data Types" }, { "code": null, "e": 3670, "s": 3630, "text": "C – Derived and User Defined Data Types" }, { "code": null, "e": 3692, "s": 3670, "text": "C – Bitwise Operators" }, { "code": null, "e": 3714, "s": 3692, "text": "C – Logical Operators" }, { "code": null, "e": 3745, "s": 3714, "text": "C – Expressions and Statements" }, { "code": null, "e": 3804, "s": 3745, "text": "C – Integer Data Types – int, short int, long int and char" }, { "code": null, "e": 3831, "s": 3804, "text": "Lambda Expressions in Java" }, { "code": null, "e": 3869, "s": 3831, "text": "AngularJs Directive Example Tutorials" }, { "code": null, "e": 3912, "s": 3869, "text": "Python – How to merge two dict in Python ?" }, { "code": null, "e": 3961, "s": 3912, "text": "C Number System – Decimal, Binary, Octal and Hex" }, { "code": null, "e": 3967, "s": 3965, "text": "Δ" }, { "code": null, "e": 3985, "s": 3967, "text": " C – Introduction" }, { "code": null, "e": 3999, "s": 3985, "text": " C – Features" }, { "code": null, "e": 4025, "s": 3999, "text": " C – Variables & Keywords" }, { "code": null, "e": 4048, "s": 4025, "text": " C – Program Structure" }, { "code": null, "e": 4077, "s": 4048, "text": " C – Comment Lines & Tokens" }, { "code": null, "e": 4096, "s": 4077, "text": " C – Number System" }, { "code": null, "e": 4128, "s": 4096, "text": " C – Local and Global Variables" }, { "code": null, "e": 4163, "s": 4128, "text": " C – Scope & Lifetime of Variables" }, { "code": null, "e": 4179, "s": 4163, "text": " C – Data Types" }, { "code": null, "e": 4203, "s": 4179, "text": " C – Integer Data Types" }, { "code": null, "e": 4228, "s": 4203, "text": " C – Floating Data Types" }, { "code": null, "e": 4261, "s": 4228, "text": " C – Derived, Defined Data Types" }, { "code": null, "e": 4283, "s": 4261, "text": " C – Type Conversions" }, { "code": null, "e": 4309, "s": 4283, "text": " C – Arithmetic Operators" }, { "code": null, "e": 4332, "s": 4309, "text": " C – Bitwise Operators" }, { "code": null, "e": 4355, "s": 4332, "text": " C – Logical Operators" }, { "code": null, "e": 4388, "s": 4355, "text": " C – Comma and sizeof Operators" }, { "code": null, "e": 4431, "s": 4388, "text": " C – Operator Precedence and Associativity" }, { "code": null, "e": 4457, "s": 4431, "text": " C – Relational Operators" }, { "code": null, "e": 4515, "s": 4457, "text": " C Flow Control – if, if-else, nested if-else, if-else-if" }, { "code": null, "e": 4532, "s": 4515, "text": " C – Switch Case" }, { "code": null, "e": 4573, "s": 4532, "text": " C Iterative – for, while, dowhile loops" }, { "code": null, "e": 4625, "s": 4573, "text": " C Unconditional – break, continue, goto statements" }, { "code": null, "e": 4657, "s": 4625, "text": " C – Expressions and Statements" }, { "code": null, "e": 4701, "s": 4657, "text": " C – Header Files & Preprocessor Directives" }, { "code": null, "e": 4729, "s": 4701, "text": " C – One Dimensional Arrays" }, { "code": null, "e": 4759, "s": 4729, "text": " C – Multi Dimensional Arrays" }, { "code": null, "e": 4780, "s": 4759, "text": " C – Pointers Basics" }, { "code": null, "e": 4806, "s": 4780, "text": " C – Pointers with Arrays" }, { "code": null, "e": 4821, "s": 4806, "text": " C – Functions" }, { "code": null, "e": 4858, "s": 4821, "text": " C – How to Pass Arrays to Functions" }, { "code": null, "e": 4887, "s": 4858, "text": " C – Categories of Functions" }, { "code": null, "e": 4915, "s": 4887, "text": " C – User defined Functions" }, { "code": null, "e": 4948, "s": 4915, "text": " C – Formal and Actual Arguments" }, { "code": null, "e": 4973, "s": 4948, "text": " C – Recursion functions" }, { "code": null, "e": 4997, "s": 4973, "text": " C – Structures Part -1" }, { "code": null, "e": 5021, "s": 4997, "text": " C – Structures Part -2" }, { "code": null, "e": 5033, "s": 5021, "text": " C – Unions" }, { "code": null, "e": 5052, "s": 5033, "text": " C – File Handling" }, { "code": null, "e": 5073, "s": 5052, "text": " C – File Operations" }, { "code": null, "e": 5104, "s": 5073, "text": " C – Dynamic Memory Allocation" }, { "code": null, "e": 5134, "s": 5104, "text": " C Program – Fibonacci Series" }, { "code": null, "e": 5160, "s": 5134, "text": " C Program – Prime or Not" }, { "code": null, "e": 5193, "s": 5160, "text": " C Program – Factorial of Number" }, { "code": null, "e": 5218, "s": 5193, "text": " C Program – Even or Odd" }, { "code": null, "e": 5263, "s": 5218, "text": " C Program – Sum of digits till Single Digit" }, { "code": null, "e": 5290, "s": 5263, "text": " C Program – Sum of digits" }, { "code": null, "e": 5323, "s": 5290, "text": " C Program – Reverse of a number" }, { "code": null, "e": 5354, "s": 5323, "text": " C Program – Armstrong Numbers" }, { "code": null, "e": 5387, "s": 5354, "text": " C Program – Print prime Numbers" }, { "code": null, "e": 5419, "s": 5387, "text": " C Program – GCD of two Numbers" }, { "code": null, "e": 5457, "s": 5419, "text": " C Program – Number Palindrome or Not" }, { "code": null, "e": 5515, "s": 5457, "text": " C Program – Find Largest and Smallest number in an Array" }, { "code": null, "e": 5553, "s": 5515, "text": " C Program – Add elements of an Array" }, { "code": null, "e": 5587, "s": 5553, "text": " C Program – Addition of Matrices" }, { "code": null, "e": 5627, "s": 5587, "text": " C Program – Multiplication of Matrices" }, { "code": null, "e": 5660, "s": 5627, "text": " C Program – Reverse of an Array" }, { "code": null, "e": 5685, "s": 5660, "text": " C Program – Bubble Sort" } ]
Powershell - Delete File
Remove-Item cmdlet is used to delete a file by passing the path of the file to be deleted. In this example, we'll delete a file D:\Temp\Test Folder\Test.txt Type the following command in PowerShell ISE Console Remove-Item 'D:\temp\Test Folder\test.txt' You can see the Test Folder1 in Windows Explorer is deleted now. In this example, we'll remove the folder D:\Temp\Test Folder recursively deleting its all files. In first example, PowerShell confirms if directory is not empty. In this case, it will simply delete the item. Type the following command in PowerShell ISE Console Remove-Item 'D:\temp\Test Folder' -Recurse You can see the content of temp folder in Windows Explorer where its folder is now removed. 15 Lectures 3.5 hours Fabrice Chrzanowski 35 Lectures 2.5 hours Vijay Saini 145 Lectures 12.5 hours Fettah Ben Print Add Notes Bookmark this page
[ { "code": null, "e": 2125, "s": 2034, "text": "Remove-Item cmdlet is used to delete a file by passing the path of the file to be deleted." }, { "code": null, "e": 2191, "s": 2125, "text": "In this example, we'll delete a file D:\\Temp\\Test Folder\\Test.txt" }, { "code": null, "e": 2244, "s": 2191, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2287, "s": 2244, "text": "Remove-Item 'D:\\temp\\Test Folder\\test.txt'" }, { "code": null, "e": 2352, "s": 2287, "text": "You can see the Test Folder1 in Windows Explorer is deleted now." }, { "code": null, "e": 2560, "s": 2352, "text": "In this example, we'll remove the folder D:\\Temp\\Test Folder recursively deleting its all files. In first example, PowerShell confirms if directory is not empty. In this case, it will simply delete the item." }, { "code": null, "e": 2613, "s": 2560, "text": "Type the following command in PowerShell ISE Console" }, { "code": null, "e": 2656, "s": 2613, "text": "Remove-Item 'D:\\temp\\Test Folder' -Recurse" }, { "code": null, "e": 2748, "s": 2656, "text": "You can see the content of temp folder in Windows Explorer where its folder is now removed." }, { "code": null, "e": 2783, "s": 2748, "text": "\n 15 Lectures \n 3.5 hours \n" }, { "code": null, "e": 2804, "s": 2783, "text": " Fabrice Chrzanowski" }, { "code": null, "e": 2839, "s": 2804, "text": "\n 35 Lectures \n 2.5 hours \n" }, { "code": null, "e": 2852, "s": 2839, "text": " Vijay Saini" }, { "code": null, "e": 2889, "s": 2852, "text": "\n 145 Lectures \n 12.5 hours \n" }, { "code": null, "e": 2901, "s": 2889, "text": " Fettah Ben" }, { "code": null, "e": 2908, "s": 2901, "text": " Print" }, { "code": null, "e": 2919, "s": 2908, "text": " Add Notes" } ]
Check if any alert exists using selenium with python.
We can check if any alert exists with Selenium webdriver. An alert is designed on a webpage to notify users or to perform some actions on the alert. It is designed with the help of Javascript. An alert can be of three types – prompt, confirmation dialogue box or alert. Selenium has multiple APIs to handle alerts with an Alert interface. To check the presence of an alert we shall use the concept of explicit wait in synchronization. As we know, explicit wait is developed based on Expected condition for a specific element. For the alerts, we shall verify if alert_is_present exists after a specific wait time. If present, we shall accept it. Entire verification shall be inside a try except block. Let us see if the above alert is present in the page. WebDriverWait class along with ExpectedCondition is used for an explicit wait condition. Code Implementation. from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.common.exceptions import TimeoutException driver = webdriver.Chrome (executable_path="C:\\chromedriver.exe") # maximize with maximize_window() driver.maximize_window() driver.get("https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm") # identify element and click() l=driver.find_element_by_name("submit") l.click() // alert_is_present() expected condition wait for 5 seconds try: WebDriverWait(driver, 5).until (EC.alert_is_present()) // switch_to.alert for switching to alert and accept alert = driver.switch_to.alert alert.accept() print("alert Exists in page") except TimeoutException: print("alert does not Exist in page") driver.close()
[ { "code": null, "e": 1255, "s": 1062, "text": "We can check if any alert exists with Selenium webdriver. An alert is designed on a webpage to notify users or to perform some actions on the alert. It is designed with the help of Javascript." }, { "code": null, "e": 1497, "s": 1255, "text": "An alert can be of three types – prompt, confirmation dialogue box or alert. Selenium has multiple APIs to handle alerts with an Alert interface. To check the presence of an alert we shall use the concept of explicit wait in synchronization." }, { "code": null, "e": 1763, "s": 1497, "text": "As we know, explicit wait is developed based on Expected condition for a specific element. For the alerts, we shall verify if alert_is_present exists after a specific wait time. If present, we shall accept it. Entire verification shall be inside a try except block." }, { "code": null, "e": 1906, "s": 1763, "text": "Let us see if the above alert is present in the page. WebDriverWait class along with ExpectedCondition is used for an explicit wait condition." }, { "code": null, "e": 1927, "s": 1906, "text": "Code Implementation." }, { "code": null, "e": 2774, "s": 1927, "text": "from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\ndriver = webdriver.Chrome (executable_path=\"C:\\\\chromedriver.exe\")\n# maximize with maximize_window()\ndriver.maximize_window()\ndriver.get(\"https://www.tutorialspoint.com/selenium/selenium_automation_practice.htm\")\n# identify element and click()\nl=driver.find_element_by_name(\"submit\")\nl.click()\n// alert_is_present() expected condition wait for 5 seconds\ntry:\n WebDriverWait(driver, 5).until (EC.alert_is_present())\n // switch_to.alert for switching to alert and accept\n alert = driver.switch_to.alert\n alert.accept()\n print(\"alert Exists in page\")\nexcept TimeoutException:\n print(\"alert does not Exist in page\")\ndriver.close()" } ]
Python Coding Style Guide
In this tutorial, we are going to learn about the standard style guide that should follow in a Python project. Following a standard style guide of any programming language will keep all team members at the same pace. Moreover, it looks professional. For Python, most of the users follow PEP 8 style guide. The code looks pretty and more readable. You can find the full list of style guide here. We are presenting the curated list of a style guide in this article. Using a tab for indentation in the code make code more readable instead of using random spaces for multiple functions and methods. You can set the number of spaces for a tab in any code editors' settings. You can see some examples below. # example def sample(random): # statement 1 # statement 2 # ... return random Using Pythons' default UTF-8 or ASCII encoding is the best practice for international environments. Using a trailing comma in the tuples is one of the best practices. But, it's not mandatory. # example tup = (1, 2, 3,) Use docstring in the functions and classes. We can use the triple quotes for the docstrings. See some examples below. def sample(): """This is a function""" """ This is a function """ class Smaple: """This is a class""" """ This is a class """ Writing more than 79 characters in a line is not recommended in PEP 8 style guide. Avoid this by breaking the line into multiple lines using the escape character (). See the example below. # example def evaluate(a, b, c, d): return (2 ** (a + b) / (c // d) ** d + a - d * b) \ - (3 ** (a + b) / (c // d) ** d + a - d * b) It's one of the best practices to use a space before and after an operator. Use a space after the comma as well for more readability. # example import random result = random.randint(1, 3) + random.randint(1, 2) Follow the same case for variables, constants, classes and functions across the program. Most of the Python users will use snake_case for functions and variables naming and PascalCase for classes naming. For constants, use all uppercase letter separated with underscores (ex:- PI_TWO). snake_case => this_is_function PascalCase => ThisIsClass CONSTANT => THIS_IS_CONSTANT Don't try to import multiple modules in a single even though it is syntactically correct. See the example below. # don't import math, random # do import math import random Always keep your comments up to date. Don't forget to update the comments while updating code. It's one of the most important things in coding. And most of the user will forget it. Keep this in mind. We have some characters that shouldn't be used as variable names lonely. And they are I (uppercase i), and l (lowercase L) as they look similar to the roman letters. Using ASCII characters in identifiers is not at all a good practice. Avoid using them.
[ { "code": null, "e": 1312, "s": 1062, "text": "In this tutorial, we are going to learn about the standard style guide that should follow in a Python project. Following a standard style guide of any programming language will keep all team\nmembers at the same pace. Moreover, it looks professional." }, { "code": null, "e": 1526, "s": 1312, "text": "For Python, most of the users follow PEP 8 style guide. The code looks pretty and more\nreadable. You can find the full list of style guide here. We are presenting the curated list of a style guide in this article." }, { "code": null, "e": 1731, "s": 1526, "text": "Using a tab for indentation in the code make code more readable instead of using random spaces for multiple functions and methods. You can set the number of spaces for a tab in any code editors' settings." }, { "code": null, "e": 1764, "s": 1731, "text": "You can see some examples below." }, { "code": null, "e": 1854, "s": 1764, "text": "# example\ndef sample(random):\n # statement 1\n # statement 2\n # ...\n return random" }, { "code": null, "e": 1954, "s": 1854, "text": "Using Pythons' default UTF-8 or ASCII encoding is the best practice for international environments." }, { "code": null, "e": 2046, "s": 1954, "text": "Using a trailing comma in the tuples is one of the best practices. But, it's not mandatory." }, { "code": null, "e": 2073, "s": 2046, "text": "# example\ntup = (1, 2, 3,)" }, { "code": null, "e": 2191, "s": 2073, "text": "Use docstring in the functions and classes. We can use the triple quotes for the docstrings. See some examples below." }, { "code": null, "e": 2353, "s": 2191, "text": "def sample():\n \"\"\"This is a function\"\"\"\n \"\"\"\n This\n is\n a function\n \"\"\"\nclass Smaple:\n \"\"\"This is a class\"\"\"\n \"\"\"\n This\n is\n a class\n \"\"\"" }, { "code": null, "e": 2542, "s": 2353, "text": "Writing more than 79 characters in a line is not recommended in PEP 8 style guide. Avoid this by breaking the line into multiple lines using the escape character (). See the example below." }, { "code": null, "e": 2678, "s": 2542, "text": "# example\ndef evaluate(a, b, c, d):\n return (2 ** (a + b) / (c // d) ** d + a - d * b) \\ - (3 ** (a + b) / (c // d) ** d + a - d * b)" }, { "code": null, "e": 2812, "s": 2678, "text": "It's one of the best practices to use a space before and after an operator. Use a space after the comma as well for more readability." }, { "code": null, "e": 2889, "s": 2812, "text": "# example\nimport random\nresult = random.randint(1, 3) + random.randint(1, 2)" }, { "code": null, "e": 3175, "s": 2889, "text": "Follow the same case for variables, constants, classes and functions across the program. Most of the Python users will use snake_case for functions and variables naming and PascalCase for classes naming. For constants, use all uppercase letter separated with underscores (ex:- PI_TWO)." }, { "code": null, "e": 3206, "s": 3175, "text": "snake_case => this_is_function" }, { "code": null, "e": 3232, "s": 3206, "text": "PascalCase => ThisIsClass" }, { "code": null, "e": 3261, "s": 3232, "text": "CONSTANT => THIS_IS_CONSTANT" }, { "code": null, "e": 3374, "s": 3261, "text": "Don't try to import multiple modules in a single even though it is syntactically correct. See the example below." }, { "code": null, "e": 3433, "s": 3374, "text": "# don't\nimport math, random\n# do\nimport math\nimport random" }, { "code": null, "e": 3633, "s": 3433, "text": "Always keep your comments up to date. Don't forget to update the comments while updating\ncode. It's one of the most important things in coding. And most of the user will forget it. Keep this in mind." }, { "code": null, "e": 3799, "s": 3633, "text": "We have some characters that shouldn't be used as variable names lonely. And they are I\n(uppercase i), and l (lowercase L) as they look similar to the roman letters." }, { "code": null, "e": 3886, "s": 3799, "text": "Using ASCII characters in identifiers is not at all a good practice. Avoid using them." } ]
DateTime.ToShortDateString() Method in C#
The DateTime.ToShortDateString() method in C# is used to convert the value of the current DateTime object to its equivalent short date string representation. Following is the syntax − public string ToShortDateString (); Let us now see an example to implement the DateTime.ToShortDateString() method − using System; public class Demo { public static void Main() { DateTime d = new DateTime(2019, 08, 11, 9, 10, 45); Console.WriteLine("Date = {0}", d); string str = d.ToShortDateString(); Console.WriteLine("Short date string representation = {0}", str); } } This will produce the following output − Date = 8/11/2019 9:10:45 AM Short date string representation = 8/11/2019 Let us now see another example to implement the DateTime.ToShortDateString() method − using System; using System.Globalization; public class Demo { public static void Main() { DateTime d = DateTime.Now; Console.WriteLine("Date = {0}", d); Console.WriteLine("Current culture = "+CultureInfo.CurrentCulture.Name); var pattern = CultureInfo.CurrentCulture.DateTimeFormat; string str = d.ToShortDateString(); Console.WriteLine("Short date string = {0}", pattern.ShortDatePattern); Console.WriteLine("Short date string representation = {0}", str); } } This will produce the following output − Date = 10/16/2019 8:56:40 AM Current culture = en-US Short date string = M/d/yyyy Short date string representation = 10/16/2019
[ { "code": null, "e": 1220, "s": 1062, "text": "The DateTime.ToShortDateString() method in C# is used to convert the value of the current DateTime object to its equivalent short date string representation." }, { "code": null, "e": 1246, "s": 1220, "text": "Following is the syntax −" }, { "code": null, "e": 1282, "s": 1246, "text": "public string ToShortDateString ();" }, { "code": null, "e": 1363, "s": 1282, "text": "Let us now see an example to implement the DateTime.ToShortDateString() method −" }, { "code": null, "e": 1649, "s": 1363, "text": "using System;\npublic class Demo {\n public static void Main() {\n DateTime d = new DateTime(2019, 08, 11, 9, 10, 45);\n Console.WriteLine(\"Date = {0}\", d);\n string str = d.ToShortDateString();\n Console.WriteLine(\"Short date string representation = {0}\", str);\n }\n}" }, { "code": null, "e": 1690, "s": 1649, "text": "This will produce the following output −" }, { "code": null, "e": 1763, "s": 1690, "text": "Date = 8/11/2019 9:10:45 AM\nShort date string representation = 8/11/2019" }, { "code": null, "e": 1849, "s": 1763, "text": "Let us now see another example to implement the DateTime.ToShortDateString() method −" }, { "code": null, "e": 2358, "s": 1849, "text": "using System;\nusing System.Globalization;\npublic class Demo {\n public static void Main() {\n DateTime d = DateTime.Now;\n Console.WriteLine(\"Date = {0}\", d);\n Console.WriteLine(\"Current culture = \"+CultureInfo.CurrentCulture.Name);\n var pattern = CultureInfo.CurrentCulture.DateTimeFormat;\n string str = d.ToShortDateString();\n Console.WriteLine(\"Short date string = {0}\", pattern.ShortDatePattern);\n Console.WriteLine(\"Short date string representation = {0}\", str);\n }\n}" }, { "code": null, "e": 2399, "s": 2358, "text": "This will produce the following output −" }, { "code": null, "e": 2527, "s": 2399, "text": "Date = 10/16/2019 8:56:40 AM\nCurrent culture = en-US\nShort date string = M/d/yyyy\nShort date string representation = 10/16/2019" } ]
How can I create a directory if it does not exist using Python?
To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using: import os if not os.path.exists('my_folder'): os.makedirs('my_folder') You can also use the python idiom EAFP: Easier to ask for forgiveness than permission. For example, import os try: os.makedirs('my_folder') except OSError as e: if e.errno != errno.EEXIST: raise
[ { "code": null, "e": 1181, "s": 1062, "text": "To create a directory, first check if it already exists using os.path.exists(directory). Then you can create it using:" }, { "code": null, "e": 1256, "s": 1181, "text": "import os\nif not os.path.exists('my_folder'):\n os.makedirs('my_folder')" }, { "code": null, "e": 1356, "s": 1256, "text": "You can also use the python idiom EAFP: Easier to ask for forgiveness than permission. For example," }, { "code": null, "e": 1467, "s": 1356, "text": "import os\ntry:\n os.makedirs('my_folder')\nexcept OSError as e:\n if e.errno != errno.EEXIST:\n raise" } ]
Neural Search with Haystack — Semantic Search At Its Finest | by Yash Prakash | Towards Data Science
Semantic searches are pretty common in our everyday lives, especially with the number of times we use Google as the medium for answers to our most, if not all, questions. Up until a few years back, building a moderately good search engine without huge computational resources was a pain. Simply put, it was way too hard and required a significant amount of expertise over advanced NLP concepts. The advent of the BERT transformer model and its successors changed that. Although we still do need a good GPU to fine tune these models, some awesome libraries like Haystack have now made it extremely easy to build a production ready application around a dataset of our choice. In this article, I’ll be showing how you can quickly spin up your own custom search engine from a publicly available dataset from, for instance, Kaggle. Let’s get started! 👇 Simply put, it is an awesome library to build production ready, scalable search systems and question answering systems. It utilises the latest transformer models thus proving to be one of the best possible NLP toolkits to both researchers and developers. It provides different components used in building such systems and those are quite intuitive to learn and experiment with. I’ll be going over some of them in this article in the hopes of giving you a good starting point! We will be using a subset of this dataset from Kaggle. It contains about 1.7 million arxiv research papers from STEM with various features for each such as their abstract, authors, publication dates, title, etc. It’s available in json format which I’ve gone ahead and compiled a smaller version of. The smaller version is available here, at my GitHub repo. Go ahead and download the arxiv_short.csv onto your machine. I’ve made sure to only keep 50,000 documents and only three columns, for simplicity: authors — the authors of the papers abstract — the paper abstract title — the paper title Read it with pandas: import pandas as pddf = pd.read_csv('arxiv_short.csv')df.head() Let’s take a look at the data: We are now ready for setting up our haystack engine. This step requires only two lines of code. Make sure you’re in a virtual environment first. pip install git+https://github.com/deepset-ai/haystack.gitpip install sentence-transformers We’ll use haystack for building the actual search engine and sentence-transformers for creating sentence embeddings from our abstract text column on which our search engine will be based upon. Now, let’s go ahead and build different components for our haystack search engine! A Document Store stores our searchable text and its metadata. For example, here our text will be the abstract column from our dataset and the remaining two columns — title and authors — will consist of our metadata. It’s fairly simple to initialise and build: document_store_faiss = FAISSDocumentStore(faiss_index_factory_str="Flat", return_embedding=True) FAISS is a library used for efficient similarity search and clustering of dense vectors, and because it takes no additional setup, I’m prefering to use it here over Elasticsearch. Now comes the Retriever. A Retriever is filter that can quickly go through your full document store and make out a set of candidate documents from it, based upon a similarity search to a given query. At its heart, we are building a semantic search system, so getting relevant documents from a query is the core of our project. Initialising a Retriever is also as easy: retriever_faiss = EmbeddingRetriever(document_store_faiss, embedding_model='distilroberta-base-msmarco-v2',model_format='sentence_transformers') Here, distilroberta is simply a transformer model — a variation of BERT model — that we use here to make embeddings for our text. Its made available as part of the sentence-transformers package. Now, we want to write documents into our document store. We simply pass the columns of our dataframe to the document store. document_store_faiss.delete_all_documents() # a precautiondocument_store_faiss.write_documents(df[['authors', 'title', 'abstract']].rename(columns={ 'title':'name','author' : 'author','abstract':'text'}).to_dict(orient='records')) A little bit of renaming is needed here because haystack expects our documents to be written in this format: { 'text': DOCUMENT_TEXT, 'meta': {'name': DOCUMENT_NAME, ...} }, ... and so on. Finally, after this is built, we provide our document store into our retriever. document_store_faiss.update_embeddings(retriever=retriever_faiss) These two steps take longer the higher your dataset size is. We’re almost done! The only thing left is to make a function to retrieve documents matching with a query! We define a simple function to fetch 10 relevant documents (research paper abstracts) from our data. def get_results(query, retriever, n_res = 10): return [(item.text, item.to_dict()['meta']) for item in retriever.retrieve(q, top_k = n_res)] Finally, we test it! query = 'Poisson Dirichlet distribution with two-parameters'print('Results: ')res = get_results(query, retriever_faiss)for r in res: print(r) You can see the results like this: And there you have it — a custom semantic search engine built on a dataset of your choice! Go ahead and play with it! Tweak some parameters — for example, try changing the transformer model in the retriever object. The entire code is also available as a notebook in here: github.com Thanks for reading! :) Learning Data Science alone can be hard, follow me and let’s make it fun together. Promise. 😎 Also, here is the codebase of all my Data Science stories. Happy learning! ⭐️ Here is another article of mine that you might want to give a read:
[ { "code": null, "e": 567, "s": 172, "text": "Semantic searches are pretty common in our everyday lives, especially with the number of times we use Google as the medium for answers to our most, if not all, questions. Up until a few years back, building a moderately good search engine without huge computational resources was a pain. Simply put, it was way too hard and required a significant amount of expertise over advanced NLP concepts." }, { "code": null, "e": 846, "s": 567, "text": "The advent of the BERT transformer model and its successors changed that. Although we still do need a good GPU to fine tune these models, some awesome libraries like Haystack have now made it extremely easy to build a production ready application around a dataset of our choice." }, { "code": null, "e": 999, "s": 846, "text": "In this article, I’ll be showing how you can quickly spin up your own custom search engine from a publicly available dataset from, for instance, Kaggle." }, { "code": null, "e": 1020, "s": 999, "text": "Let’s get started! 👇" }, { "code": null, "e": 1140, "s": 1020, "text": "Simply put, it is an awesome library to build production ready, scalable search systems and question answering systems." }, { "code": null, "e": 1275, "s": 1140, "text": "It utilises the latest transformer models thus proving to be one of the best possible NLP toolkits to both researchers and developers." }, { "code": null, "e": 1496, "s": 1275, "text": "It provides different components used in building such systems and those are quite intuitive to learn and experiment with. I’ll be going over some of them in this article in the hopes of giving you a good starting point!" }, { "code": null, "e": 1795, "s": 1496, "text": "We will be using a subset of this dataset from Kaggle. It contains about 1.7 million arxiv research papers from STEM with various features for each such as their abstract, authors, publication dates, title, etc. It’s available in json format which I’ve gone ahead and compiled a smaller version of." }, { "code": null, "e": 1914, "s": 1795, "text": "The smaller version is available here, at my GitHub repo. Go ahead and download the arxiv_short.csv onto your machine." }, { "code": null, "e": 1999, "s": 1914, "text": "I’ve made sure to only keep 50,000 documents and only three columns, for simplicity:" }, { "code": null, "e": 2035, "s": 1999, "text": "authors — the authors of the papers" }, { "code": null, "e": 2065, "s": 2035, "text": "abstract — the paper abstract" }, { "code": null, "e": 2089, "s": 2065, "text": "title — the paper title" }, { "code": null, "e": 2110, "s": 2089, "text": "Read it with pandas:" }, { "code": null, "e": 2174, "s": 2110, "text": "import pandas as pddf = pd.read_csv('arxiv_short.csv')df.head()" }, { "code": null, "e": 2205, "s": 2174, "text": "Let’s take a look at the data:" }, { "code": null, "e": 2258, "s": 2205, "text": "We are now ready for setting up our haystack engine." }, { "code": null, "e": 2350, "s": 2258, "text": "This step requires only two lines of code. Make sure you’re in a virtual environment first." }, { "code": null, "e": 2442, "s": 2350, "text": "pip install git+https://github.com/deepset-ai/haystack.gitpip install sentence-transformers" }, { "code": null, "e": 2635, "s": 2442, "text": "We’ll use haystack for building the actual search engine and sentence-transformers for creating sentence embeddings from our abstract text column on which our search engine will be based upon." }, { "code": null, "e": 2718, "s": 2635, "text": "Now, let’s go ahead and build different components for our haystack search engine!" }, { "code": null, "e": 2780, "s": 2718, "text": "A Document Store stores our searchable text and its metadata." }, { "code": null, "e": 2934, "s": 2780, "text": "For example, here our text will be the abstract column from our dataset and the remaining two columns — title and authors — will consist of our metadata." }, { "code": null, "e": 2978, "s": 2934, "text": "It’s fairly simple to initialise and build:" }, { "code": null, "e": 3075, "s": 2978, "text": "document_store_faiss = FAISSDocumentStore(faiss_index_factory_str=\"Flat\", return_embedding=True)" }, { "code": null, "e": 3255, "s": 3075, "text": "FAISS is a library used for efficient similarity search and clustering of dense vectors, and because it takes no additional setup, I’m prefering to use it here over Elasticsearch." }, { "code": null, "e": 3280, "s": 3255, "text": "Now comes the Retriever." }, { "code": null, "e": 3455, "s": 3280, "text": "A Retriever is filter that can quickly go through your full document store and make out a set of candidate documents from it, based upon a similarity search to a given query." }, { "code": null, "e": 3582, "s": 3455, "text": "At its heart, we are building a semantic search system, so getting relevant documents from a query is the core of our project." }, { "code": null, "e": 3624, "s": 3582, "text": "Initialising a Retriever is also as easy:" }, { "code": null, "e": 3769, "s": 3624, "text": "retriever_faiss = EmbeddingRetriever(document_store_faiss, embedding_model='distilroberta-base-msmarco-v2',model_format='sentence_transformers')" }, { "code": null, "e": 3964, "s": 3769, "text": "Here, distilroberta is simply a transformer model — a variation of BERT model — that we use here to make embeddings for our text. Its made available as part of the sentence-transformers package." }, { "code": null, "e": 4021, "s": 3964, "text": "Now, we want to write documents into our document store." }, { "code": null, "e": 4088, "s": 4021, "text": "We simply pass the columns of our dataframe to the document store." }, { "code": null, "e": 4319, "s": 4088, "text": "document_store_faiss.delete_all_documents() # a precautiondocument_store_faiss.write_documents(df[['authors', 'title', 'abstract']].rename(columns={ 'title':'name','author' : 'author','abstract':'text'}).to_dict(orient='records'))" }, { "code": null, "e": 4428, "s": 4319, "text": "A little bit of renaming is needed here because haystack expects our documents to be written in this format:" }, { "code": null, "e": 4512, "s": 4428, "text": "{ 'text': DOCUMENT_TEXT, 'meta': {'name': DOCUMENT_NAME, ...} }, ... and so on." }, { "code": null, "e": 4592, "s": 4512, "text": "Finally, after this is built, we provide our document store into our retriever." }, { "code": null, "e": 4658, "s": 4592, "text": "document_store_faiss.update_embeddings(retriever=retriever_faiss)" }, { "code": null, "e": 4719, "s": 4658, "text": "These two steps take longer the higher your dataset size is." }, { "code": null, "e": 4825, "s": 4719, "text": "We’re almost done! The only thing left is to make a function to retrieve documents matching with a query!" }, { "code": null, "e": 4926, "s": 4825, "text": "We define a simple function to fetch 10 relevant documents (research paper abstracts) from our data." }, { "code": null, "e": 5073, "s": 4926, "text": "def get_results(query, retriever, n_res = 10): return [(item.text, item.to_dict()['meta']) for item in retriever.retrieve(q, top_k = n_res)]" }, { "code": null, "e": 5094, "s": 5073, "text": "Finally, we test it!" }, { "code": null, "e": 5239, "s": 5094, "text": "query = 'Poisson Dirichlet distribution with two-parameters'print('Results: ')res = get_results(query, retriever_faiss)for r in res: print(r)" }, { "code": null, "e": 5274, "s": 5239, "text": "You can see the results like this:" }, { "code": null, "e": 5365, "s": 5274, "text": "And there you have it — a custom semantic search engine built on a dataset of your choice!" }, { "code": null, "e": 5489, "s": 5365, "text": "Go ahead and play with it! Tweak some parameters — for example, try changing the transformer model in the retriever object." }, { "code": null, "e": 5546, "s": 5489, "text": "The entire code is also available as a notebook in here:" }, { "code": null, "e": 5557, "s": 5546, "text": "github.com" }, { "code": null, "e": 5580, "s": 5557, "text": "Thanks for reading! :)" }, { "code": null, "e": 5674, "s": 5580, "text": "Learning Data Science alone can be hard, follow me and let’s make it fun together. Promise. 😎" }, { "code": null, "e": 5752, "s": 5674, "text": "Also, here is the codebase of all my Data Science stories. Happy learning! ⭐️" } ]
K Subarray Sum | Practice | GeeksforGeeks
Given an integer array arr of size N and two integers K and M, the task is to find M largest sums of K sized subarrays. Input: 1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows. 2. The first line of each test case contains three integers N, K, and M. 3. The next line contains N space-separated integers. Output: For each test case, print M space-separated integers (Print the sums from the maximum to minimum) Constraints: 1. 1 <= T <= 100 2. 1 <= K <= N <= 104 3. 1 <= M <= N - K + 1 4. 1 <= arr[i] <= 105 Example: Input: 2 5 2 3 10 11 10 11 12 5 5 1 1 2 3 4 5 Output: 23 21 21 15 Explanation: Test Case 1: 2 sized subarray sum are {21, 21, 21, 21, 23}, We need to print 3 largest sums from maximum to minimum 0 lindan1233 months ago #include <bits/stdc++.h> using namespace std; int main() { int t; cin>>t; while(t--) { int n,k,m; cin>>n>>k>>m; vector<int> arr(n); for(int i=0;i<n;i++) { cin>>arr[i]; } if(n==1) { cout<<arr[0]; } else{ int i=0; int j=0; int c=0; int sum=0; vector<int> temp; while(j<n) { sum+=arr[j]; c++; if(c==k) { temp.push_back(sum); sum = sum-arr[i]; i++; c--; } j++; } sort(temp.rbegin(),temp.rend()); for(j=0;j<temp.size();j++) { if(m>=j+1) { cout<<temp[j]<<" "; } } } cout<<endl; } return 0; } Time Taken : 0.1sec Cpp +1 avinav26113 months ago Easy C++ Solution !!Working!! (minimum time and space complexity) -1 naitikrajyaguru3 months ago it's pizza time #include <bits/stdc++.h>using namespace std; int main() {//codeint t;cin>>t;while(t--){ int n,k,m; cin>>n>>k>>m; int a[n],i; for(i=0; i<=n-1; i++){ cin>>a[i]; } int sum[n]={0}; for(i=0; i<=n-k; i++){ for(int j=i; j<=i+k-1; j++){ sum[i]+=a[j]; } } sort(sum,sum+i); for(int j=i-1; j>=i-m; j--){ cout<<sum[j]<<" "; } cout<<endl;}return 0;} -1 vishallodha20093 months ago Easy c++ solution #include <bits/stdc++.h> using namespace std; vector<int> kSubArrSum(int arr[],int n,int k,int m){ vector<int> ans; for(int i=0;i<=n-k;i++){ int sum = 0; for(int j=i;j<i+k;j++){ sum+=arr[j]; } ans.push_back(sum); } sort(ans.begin(),ans.end(),::greater<int>()); vector<int> result; for(int i=0;i<m;i++){ result.push_back(ans[i]); } return result; } int main() { //code int T; cin >> T; for(int i=0;i<T;i++){ int n,k,m; cin >> n >> k >> m; int arr[n]; for(int i=0;i<n;i++){ cin >> arr[i]; } vector<int> ans = kSubArrSum(arr,n,k,m); for(int i=0;i<m;i++){ cout<<ans[i]<<" "; } cout<<endl; } return 0; } 0 lokendrabaghel0987653 months ago //JAVA SOLUTION CAN ANYONE HELP ME TO FIND THE TC & SC OF THIS PROBLEM? import java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main (String[] args){ Scanner scan = new Scanner(System.in); int T = scan.nextInt(); while(T-- > 0){ int N = scan.nextInt(); int K = scan.nextInt(); int M = scan.nextInt(); int arr[] = new int[N]; for(int i=0; i< N; i++) { arr[i] = scan.nextInt(); } PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); for(int i = 0; i <= N-K; i++) { int sum = 0; int temp = i; for(int j = i; j < arr.length && j < temp+K; j++) { sum += arr[j]; } pq.add(sum); } int z = 0; while(z < M) { System.out.print(pq.peek()+" "); pq.poll(); z++; } System.out.println(); } }} -1 deytulsi183 months ago [C++] [Time Complexity: O(nlogn)] [Space Complexity: O(n)] /* * author: deytulsi18 * problem: https://practice.geeksforgeeks.org/problems/k-subarray-sum/0/ * time complexity: O(nlogn) * space complexity: O(n) * language: cpp */ #define deb(x) cout << #x << " = " << x << endl; #include<bits/stdc++.h> using namespace std; void solution() { int n, k, m; int sum = 0; cin >> n >> k >> m; vector<int> arr(n); priority_queue<int> res; for (int i = 0; i < n; i++) cin >> arr[i]; for (int i = 0; i < k; i++) sum += arr[i]; res.push(sum); for (int i = k; i < n; i++) { sum = sum - arr[i - k] + arr[i]; res.push(sum); } for (int i = 1; i <= m; i++) { cout << res.top() << " "; res.pop(); } cout << endl; } int main() { int testCases = 0; cin >> testCases; while (testCases-->0) solution(); return 0; } +3 doramohitkumar4 months ago I had written the code in python But it said time limit exceeded 😅😅 +1 badgujarsachin835 months ago #include<iostream> #include<queue> #include<stack> using namespace std; int main() { //code int t; cin>>t; while(t--){ int n,k,m; cin>>n>>k>>m; int arr[n]; int sum=0; for(int i=0;i<n;i++){ cin>>arr[i]; } priority_queue<int,vector<int> ,greater<int>> q; for(int i=0;i<k;i++){ sum+=arr[i]; } int i=0,j=k-1; while(j<n){ q.push(sum); if(q.size()>m){ q.pop(); } sum-=arr[i++]; if(j+1<n){ sum+=arr[j+1]; } j++; } stack<int> st; while(!q.empty()){ st.push(q.top()); q.pop(); } while(!st.empty()){ cout<<st.top()<<" "; st.pop(); } cout<<endl; } return 0; } -1 imranwahid6 months ago Easy C++ solution #include<bits/stdc++.h> using namespace std; void helper(vector<int>&v,int k,int m) { priority_queue<int,vector<int>,greater<int>>q; int sum=0,i=0,j=k-1; for(int i=0;i<k;i++) { sum+=v[i]; } while(j<v.size()) { q.push(sum); if(q.size()>m) { q.pop(); } sum-=v[i]; if(j+1<v.size()) { sum+=v[j+1]; } i++; j++; } stack<int>stk; while(!q.empty()) { stk.push(q.top()); q.pop(); } while(!stk.empty()) { cout<<stk.top()<<" "; stk.pop(); } } int main() { int t; cin>>t; while(t--) { int n,k,m; cin>>n>>k>>m; vector<int>v(n); for(int i=0;i<n;i++) { cin>>v[i]; } helper(v,k,m); cout<<"\n"; } return 0; } 0 swayam60kumar7 months ago Use the sliding window method to find the sum of each interval and priorty queue to arrange the sum in the particular order We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab.
[ { "code": null, "e": 348, "s": 226, "text": "Given an integer array arr of size N and two integers K and M, the task is to find M largest sums of K sized subarrays. " }, { "code": null, "e": 620, "s": 348, "text": "Input: \n1. The first line of the input contains a single integer T denoting the number of test cases. The description of T test cases follows.\n2. The first line of each test case contains three integers N, K, and M.\n3. The next line contains N space-separated integers. " }, { "code": null, "e": 884, "s": 620, "text": "\nOutput: For each test case, print M space-separated integers (Print the sums from the maximum to minimum)\n\nConstraints:\n1. 1 <= T <= 100\n2. 1 <= K <= N <= 104\n3. 1 <= M <= N - K + 1\n4. 1 <= arr[i] <= 105\n\nExample:\nInput:\n2\n5 2 3\n10 11 10 11 12\n5 5 1\n1 2 3 4 5 \n " }, { "code": null, "e": 1034, "s": 884, "text": "Output:\n23 21 21\n15\n\nExplanation:\nTest Case 1: 2 sized subarray sum are {21, 21, 21, 21, 23}, We need to print 3 largest sums from maximum to minimum" }, { "code": null, "e": 1036, "s": 1034, "text": "0" }, { "code": null, "e": 1058, "s": 1036, "text": "lindan1233 months ago" }, { "code": null, "e": 1863, "s": 1058, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\nint main() {\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t int n,k,m;\n\t cin>>n>>k>>m;\n\t vector<int> arr(n);\n\t for(int i=0;i<n;i++)\n\t {\n\t cin>>arr[i];\n\t }\n\t \n\t if(n==1)\n\t {\n\t cout<<arr[0];\n\t }\n\t else{\n\t int i=0;\n\t int j=0;\n\t int c=0;\n\t int sum=0;\n\t vector<int> temp;\n\t while(j<n)\n\t {\n\t sum+=arr[j];\n\t c++;\n\t if(c==k)\n\t {\n\t temp.push_back(sum);\n\t sum = sum-arr[i];\n\t i++;\n\t c--;\n\t }\n\t j++;\n\t \n\t }\n\t \n\t \n\t sort(temp.rbegin(),temp.rend());\n\t for(j=0;j<temp.size();j++)\n\t {\n\t if(m>=j+1)\n\t {\n\t cout<<temp[j]<<\" \";\n\t }\n\t }\n\t }\n\t cout<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 1883, "s": 1863, "text": "Time Taken : 0.1sec" }, { "code": null, "e": 1887, "s": 1883, "text": "Cpp" }, { "code": null, "e": 1890, "s": 1887, "text": "+1" }, { "code": null, "e": 1913, "s": 1890, "text": "avinav26113 months ago" }, { "code": null, "e": 1943, "s": 1913, "text": "Easy C++ Solution !!Working!!" }, { "code": null, "e": 1979, "s": 1943, "text": "(minimum time and space complexity)" }, { "code": null, "e": 1984, "s": 1981, "text": "-1" }, { "code": null, "e": 2012, "s": 1984, "text": "naitikrajyaguru3 months ago" }, { "code": null, "e": 2028, "s": 2012, "text": "it's pizza time" }, { "code": null, "e": 2075, "s": 2030, "text": "#include <bits/stdc++.h>using namespace std;" }, { "code": null, "e": 2442, "s": 2075, "text": "int main() {//codeint t;cin>>t;while(t--){ int n,k,m; cin>>n>>k>>m; int a[n],i; for(i=0; i<=n-1; i++){ cin>>a[i]; } int sum[n]={0}; for(i=0; i<=n-k; i++){ for(int j=i; j<=i+k-1; j++){ sum[i]+=a[j]; } } sort(sum,sum+i); for(int j=i-1; j>=i-m; j--){ cout<<sum[j]<<\" \"; } cout<<endl;}return 0;}" }, { "code": null, "e": 2445, "s": 2442, "text": "-1" }, { "code": null, "e": 2473, "s": 2445, "text": "vishallodha20093 months ago" }, { "code": null, "e": 2491, "s": 2473, "text": "Easy c++ solution" }, { "code": null, "e": 3252, "s": 2493, "text": "#include <bits/stdc++.h>\nusing namespace std;\n\nvector<int> kSubArrSum(int arr[],int n,int k,int m){\n vector<int> ans;\n for(int i=0;i<=n-k;i++){\n int sum = 0;\n for(int j=i;j<i+k;j++){\n sum+=arr[j];\n }\n ans.push_back(sum);\n }\n \n sort(ans.begin(),ans.end(),::greater<int>());\n vector<int> result;\n for(int i=0;i<m;i++){\n result.push_back(ans[i]);\n }\n return result;\n}\n\nint main() {\n\t//code\n\tint T;\n\tcin >> T;\n\tfor(int i=0;i<T;i++){\n\t int n,k,m;\n\t cin >> n >> k >> m;\n\t int arr[n];\n\t for(int i=0;i<n;i++){\n\t cin >> arr[i];\n\t }\n\t vector<int> ans = kSubArrSum(arr,n,k,m);\n\t for(int i=0;i<m;i++){\n\t cout<<ans[i]<<\" \";\n\t }\n\t cout<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 3254, "s": 3252, "text": "0" }, { "code": null, "e": 3287, "s": 3254, "text": "lokendrabaghel0987653 months ago" }, { "code": null, "e": 3303, "s": 3287, "text": "//JAVA SOLUTION" }, { "code": null, "e": 3359, "s": 3303, "text": "CAN ANYONE HELP ME TO FIND THE TC & SC OF THIS PROBLEM?" }, { "code": null, "e": 4300, "s": 3359, "text": "import java.util.*;import java.lang.*;import java.io.*;class GFG{public static void main (String[] args){ Scanner scan = new Scanner(System.in); int T = scan.nextInt(); while(T-- > 0){ int N = scan.nextInt(); int K = scan.nextInt(); int M = scan.nextInt(); int arr[] = new int[N]; for(int i=0; i< N; i++) { arr[i] = scan.nextInt(); } PriorityQueue pq = new PriorityQueue<>(Comparator.reverseOrder()); for(int i = 0; i <= N-K; i++) { int sum = 0; int temp = i; for(int j = i; j < arr.length && j < temp+K; j++) { sum += arr[j]; } pq.add(sum); } int z = 0; while(z < M) { System.out.print(pq.peek()+\" \"); pq.poll(); z++; } System.out.println(); } }}" }, { "code": null, "e": 4303, "s": 4300, "text": "-1" }, { "code": null, "e": 4326, "s": 4303, "text": "deytulsi183 months ago" }, { "code": null, "e": 4385, "s": 4326, "text": "[C++] [Time Complexity: O(nlogn)] [Space Complexity: O(n)]" }, { "code": null, "e": 5276, "s": 4387, "text": "/*\n * author: deytulsi18\n * problem: https://practice.geeksforgeeks.org/problems/k-subarray-sum/0/\n * time complexity: O(nlogn)\n * space complexity: O(n)\n * language: cpp\n */\n#define deb(x) cout << #x << \" = \" << x << endl;\n\n#include<bits/stdc++.h>\nusing namespace std;\n\nvoid solution()\n{\n int n, k, m;\n int sum = 0;\n \n cin >> n >> k >> m;\n \n vector<int> arr(n);\n priority_queue<int> res;\n \n for (int i = 0; i < n; i++) cin >> arr[i];\n for (int i = 0; i < k; i++) sum += arr[i];\n \n res.push(sum);\n \n for (int i = k; i < n; i++)\n {\n sum = sum - arr[i - k] + arr[i];\n res.push(sum);\n }\n \n for (int i = 1; i <= m; i++)\n {\n cout << res.top() << \" \";\n res.pop();\n }\n \n cout << endl;\n}\n\nint main()\n {\n\tint testCases = 0;\n\tcin >> testCases;\n\t\n\twhile (testCases-->0)\n\t solution();\n\treturn 0;\n}" }, { "code": null, "e": 5279, "s": 5276, "text": "+3" }, { "code": null, "e": 5306, "s": 5279, "text": "doramohitkumar4 months ago" }, { "code": null, "e": 5339, "s": 5306, "text": "I had written the code in python" }, { "code": null, "e": 5374, "s": 5339, "text": "But it said time limit exceeded 😅😅" }, { "code": null, "e": 5377, "s": 5374, "text": "+1" }, { "code": null, "e": 5406, "s": 5377, "text": "badgujarsachin835 months ago" }, { "code": null, "e": 6195, "s": 5406, "text": "#include<iostream>\n#include<queue>\n#include<stack>\nusing namespace std;\nint main()\n {\n\t//code\n\tint t;\n\tcin>>t;\n\twhile(t--){\n\t int n,k,m;\n\t cin>>n>>k>>m;\n\t int arr[n];\n\t int sum=0;\n\t for(int i=0;i<n;i++){\n\t cin>>arr[i];\n\t }\n\t priority_queue<int,vector<int> ,greater<int>> q;\n\t for(int i=0;i<k;i++){\n\t sum+=arr[i];\n\t }\n\t int i=0,j=k-1;\n\t while(j<n){\n\t q.push(sum);\n\t if(q.size()>m){\n\t q.pop();\n\t }\n\t sum-=arr[i++];\n\t if(j+1<n){\n\t sum+=arr[j+1];\n\t }\n\t j++;\n\t }\n\t stack<int> st;\n\t while(!q.empty()){\n\t st.push(q.top());\n\t q.pop();\n\t }\n\t while(!st.empty()){\n\t cout<<st.top()<<\" \";\n\t st.pop();\n\t }\n\t cout<<endl;\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 6198, "s": 6195, "text": "-1" }, { "code": null, "e": 6221, "s": 6198, "text": "imranwahid6 months ago" }, { "code": null, "e": 6239, "s": 6221, "text": "Easy C++ solution" }, { "code": null, "e": 7090, "s": 6239, "text": "#include<bits/stdc++.h>\nusing namespace std;\nvoid helper(vector<int>&v,int k,int m)\n{\n priority_queue<int,vector<int>,greater<int>>q;\n int sum=0,i=0,j=k-1;\n for(int i=0;i<k;i++)\n {\n sum+=v[i];\n }\n while(j<v.size())\n {\n q.push(sum);\n if(q.size()>m)\n {\n q.pop();\n }\n sum-=v[i];\n if(j+1<v.size())\n {\n sum+=v[j+1];\n }\n i++;\n j++;\n }\n stack<int>stk;\n while(!q.empty())\n {\n stk.push(q.top());\n q.pop();\n }\n while(!stk.empty())\n {\n cout<<stk.top()<<\" \";\n stk.pop();\n }\n}\nint main()\n{\n\tint t;\n\tcin>>t;\n\twhile(t--)\n\t{\n\t int n,k,m;\n\t cin>>n>>k>>m;\n\t vector<int>v(n);\n\t for(int i=0;i<n;i++)\n\t {\n\t cin>>v[i];\n\t }\n\t helper(v,k,m);\n\t cout<<\"\\n\";\n\t}\n\treturn 0;\n}" }, { "code": null, "e": 7092, "s": 7090, "text": "0" }, { "code": null, "e": 7118, "s": 7092, "text": "swayam60kumar7 months ago" }, { "code": null, "e": 7242, "s": 7118, "text": "Use the sliding window method to find the sum of each interval and priorty queue to arrange the sum in the particular order" }, { "code": null, "e": 7388, "s": 7242, "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": 7424, "s": 7388, "text": " Login to access your submissions. " }, { "code": null, "e": 7434, "s": 7424, "text": "\nProblem\n" }, { "code": null, "e": 7444, "s": 7434, "text": "\nContest\n" }, { "code": null, "e": 7507, "s": 7444, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7655, "s": 7507, "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": 7863, "s": 7655, "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": 7969, "s": 7863, "text": "You can access the hints to get an idea about what is expected of you as well as the final solution code." } ]
How to deploy ONNX models on NVIDIA Jetson Nano using DeepStream | by Bharath Raj | Towards Data Science
Deploying complex deep learning models onto small embedded devices is challenging. Even with hardware optimized for deep learning such as the Jetson Nano and inference optimization tools such as TensorRT, bottlenecks can still present itself in the I/O pipeline. These bottlenecks can potentially compound if the model has to deal with complex I/O pipelines with multiple input and output streams. Wouldn’t it be great to have a tool that can take care of all bottlenecks in an end-to-end fashion? Turns out there is a SDK that attempts to mitigate this problem. DeepStream is an SDK that is optimized for NVIDIA Jetson and T4 platforms to provide a seamless end-to-end service to convert raw streaming data into actionable insights. It is built on top of the GStreamer framework. Here, “raw streaming data” is typically continuous (and multiple) video streams and “actionable insights” are the final outputs of your deep learning or other analytics algorithms. DeepStream SDK uses its custom GStreamer Plugins to provide various functionalities. Notably, it has plugins for TensorRT based inference and object tracking. The below image lists out the capabilities of their plugins. For an exhaustive technical guide about their plugins, you can refer to their Plugin Manual. One feature I particularly liked about DeepStream is that it optimally takes care of the entire I/O processing in a pipelined fashion. We can also stack multiple deep learning algorithms to process information asynchronously. This allows you to increase throughput without the hassle of manually creating and managing a multiprocessing system design. The best part is, for some supported applications such as object detection, tracking, classification or semantic segmentation, DeepStream is easy to use! For such an application, as long you have a deep learning model in a compatible format, you can easily launch DeepStream by just setting a few parameters in some text files. In this blog, we will design and run an experiment on DeepStream to test out its features and to see if it is easy to use on the Jetson Nano. To test the features of DeepStream, let's deploy a pre-trained object detection algorithm on the Jetson Nano. This is an ideal experiment for a couple of reasons: DeepStream is optimized for inference on NVIDIA T4 and Jetson platforms. DeepStream has a plugin for inference using TensorRT that supports object detection. Moreover, it automatically converts models in the ONNX format to an optimized TensorRT engine. It has plugins that support multiple streaming inputs. It also has plugins to save the output in multiple formats. The ONNX model zoo has a bunch of pre-trained object detection models. I chose the Tiny YOLO v2 model from the zoo as it was readily compatible with DeepStream and was also light enough to run fast on the Jetson Nano. Note: I did try using the SSD and YOLO v3 models from the zoo. But there were some compatibility issues. These issues are discussed in my GitHub repository, along with tips to verify and handle such cases. I ended up using Tiny YOLO v2 as it was readily compatible without any additional effort. Now, the features we want to investigate are as follows: Multiple input streams: Run DeepStream to perform inference on multiple video streams simultaneously. Specifically, we will try using up-to 4 video streams.Multiple output sinks: Display the result on screen and stream it using RTSP. The stream will be accessed by another device connected to the network. Multiple input streams: Run DeepStream to perform inference on multiple video streams simultaneously. Specifically, we will try using up-to 4 video streams. Multiple output sinks: Display the result on screen and stream it using RTSP. The stream will be accessed by another device connected to the network. The performance (Frames per Second, FPS) and ease-of-use will be evaluated for the experiment. The next few sections will guide you through how to set up DeepStream on Jetson Nano to run this experiment. All code used for this experiment is available on my GitHub repository. If you are just curious about how it turned out, feel free to skip to the results section. In this section, we will walk through some instructions to set things up for our experiment. Follow the instructions on the Getting Started With Jetson Nano Developer Kit to set up and boot your Jetson Nano. In case you face some issues with the setup, I would highly recommend following these resources. I would like to highlight some pointers that might save you some trouble: It is recommended to use at least a 32GB MicroSD card (I used 64GB). You need a wired ethernet connection. If you need to connect your Jetson Nano to WiFi, you need to use a dongle such as the Edimax EW-7811Un. You need a monitor that directly accepts HDMI input. I could not use my VGA monitor using a VGA-HDMI adapter. Now that you have your Jetson Nano up and running, we can install DeepStream. Nvidia has put together the DeepStream quick start guide where you can follow the instructions under the section Jetson Setup. Before you go ahead and install DeepStream using the above link, I would like to highlight a few points from my setup experience: The setup would suggest you install Jetpack using the Nvidia SDK Manager. I skipped that step as I realized using the OS image in Part-1 (above) had most of the required dependencies by default. In the sub-section “To install the DeepStream SDK” of the quick start guide, I used Method-2. After installing DeepStream and boosting the clocks (as mentioned in the guide), we can run one of their samples to verify that the installation is properly done. Move (cd) into your DeepStream installation folder and run the following command: deepstream-app -c ./samples/configs/deepstream-app/source8_1080p_dec_infer-resnet_tracker_tiled_display_fp16_nano.txt On execution, you should see something like this: If you see something similar, congrats! You can play around with more samples if you would like. The guide has a section named “Reference Application Source Details” which provides a description of the samples. Now that you have installed and tested DeepSteam, we can go ahead with our experiment. I have bundled up all the files required for the experiment in my GitHub repository. You can follow the step by step instruction in the repository’s readme file about the setup instructions. Before moving on with the experiment, if you have not used GStreamer before, it would be worth your time to go through their foundations page. This helps with better understanding of some of the jargons used in DeepStream’s documentation. In this section, we will explore how to interface the output of our ONNX model with DeepStream. More specifically, we will walk-through the process of creating a custom processing function in C++ to extract bounding box information from the output of the ONNX model and provide it to DeepStream. The ONNX model outputs a tensor of shape (125, 13, 13) in the channels-first format. However, when used with DeepStream, we obtain the flattened version of the tensor which has shape (21125). Our goal is to manually extract the bounding box information from this flattened tensor. Let us first try to visually understand the output tensor output by the ONNX model. Consider the output tensor to be a cuboid of dimensions (B, H, W), which in our case B=125,H=13,W=13. We can consider the axes X, Y and B along the width (W), height (H) and depth (B) respectively. Now, each location in the XY plane represents a single grid cell. Let us visualize a single grid cell (X=0, Y=0). There 125 values along the depth axis (B) for this given (X,Y) location. Let us rearrange the 125 values in groups of 25 as shown below: As we see here, each of the contiguous 25 values belong to a separate bounding box. Among each set of 25 values, the first 5 values are of the bounding box parameters and the last 20 values are class probabilities. Using this, we can extract the coordinates and confidence score for each of the 5 bounding boxes as shown here: Note that we have only performed this operation at one grid cell (X=0, Y=0). We must iterate over all combinations of X and Y to find the 5 bounding box predictions at each grid cell. Now that we have a visual idea of how the information is stored, let us try to extract it using indexing. After flattening the output tensor, we get a single array in which information is stored as shown in the image below: The flattened array has 125 * 13 * 13 = 21125 elements. As shown above, each location in the array corresponds to the indices (b, y, x). We can observe that for a given (y,x) value, the corresponding b values are separated by 13 * 13 = 169 . The following code snippet in Python shows how we can obtain the locations of b values corresponding to each of the 5 bounding boxes in a given (y, x) location. Do note that, as shown in Figure A, there are 25 b values for each bounding box for a given (y, x) location. ## Let arr be the flattened array.## The array values contains the value of arr at the 25 b_values per ## bbox,x,y combination.num_anchors = 5num_classes = 20xy_offset = y * 13 + xb_offset = 13 * 13bbox_offset = 5 + num_classesfor bbox in range(num_anchors): values = [] for b in range(bbox_offset): value = arr[xy_offset + b_offset * (b + bbox * bbox_offset)] values.append(value) All that is left to do is to write the C++ equivalent of the same. Now that we understand how the output is stored and can be extracted, we need to write a function in C++ to do the same. DeepStream expects a function with arguments as shown below: extern "C" bool NvDsInferParseCustomYoloV2Tiny( std::vector<NvDsInferLayerInfo> const& outputLayersInfo, NvDsInferNetworkInfo const& networkInfo, NvDsInferParseDetectionParams const& detectionParams, std::vector<NvDsInferParseObjectInfo>& objectList); In the above function prototype, outputLayersInfo is a std::vector containing information and data about each output layer of our ONNX model. In our case, since we have just one output layer, we can access the data using outputLayersInfo[0].buffer. The variable networkInfo has information about the height and width expected by the model and detectionParams has information about some configurations such as numClassesConfigured. The variable objectList should be updated with a std::vector of bounding box information stored as objects of type NvDsInferParseObjectInfo at every call of the function. Since the variable was passed by reference, we don’t need to return it as the changes will be reflected at the source. However, the function must return true at the end of its execution. For our use case, we create NvDsInferParseCustomYoloV2Tiny such that it will first decode the output of the ONNX model as described in Part-1 of this section. For each bounding box, we create an object of type NvDsInferParseObjectInfo to store its information. We then apply non-maximum suppression to remove duplicate bounding box detections of the same object. We then add the resulting bounding boxes to the objectList vector. My GitHub repository has nvdsparsebbox_tiny_yolo.cpp inside the directory custom_bbox_parser with the function already written for you. The below flowchart explains the flow of logic within the file. The code may seem large but that is only because it is heavily documented and commented for your understanding! All that’s left now is to compile the function into a .so file so that DeepStream can load and use it. Before you compile it, you may need to set some variables inside the Makefile. You can refer to step 4 of the ReadMe in my GitHub repository for instructions. Once that is done, cd into the GitHub repository and run the following command: make -C custom_bbox_parser The good news is that most of the heavy lifting work is done. All that is left is to set up some configuration files which will tell DeepStream how to run the experiments. A configurations file has a set of “groups”, each of which has a set of “properties” that are written in the key-file format. For our experiment, we need to set up two configuration files. In this section we will explore some important properties within these configuration files. Our ONNX model is used by the Gst-Nvinfer plugin of DeepStream. We need to set-up some properties to tell the plugin information such as the location of our ONNX model, location of our compiled bounding box parser and so on. In the GitHub repository, the configuration file named config_infer_custom_yolo.txt is already setup for our experiment. Comments are given in the file with reasoning for each property setting. For a detailed list of all the supported properties, check out this link. Some interesting properties that we have not used are the “net-scale-factor” and the “offset” properties. They essentially scale the input (x) using the formula: net_scale_factor * (x — mean). We did not use those properties as our network directly takes the unscaled image as the input. We also need to set a configuration file for DeepStream to enable and configure the various plugins that will be used by it. As mentioned before, the GitHub repository contains the configuration file deepstream_app_custom_yolo.txt which is already setup for our experiment. Unlike the previous part, this configuration has a lot of groups such as “osd” (On Screen Display), “primary-gie” (Primary GPU Inference Engine) and so on. This link has information about all possible groups that can be configured and the properties supported for each group. For our experiment, we define a single source group (source0) and three sink groups (sink0, sink1 and sink2). The single source group is responsible for reading four input video streams parallely. The three sink groups are used for displaying output on screen, streaming output using RTSP and for saving output to disk respectively. We provide the path of the configuration file of Tiny YOLOv2 in the primary-gie group. Moreover, we also set the titled-display and osd groups to control how the output appears on screen. This is the easiest part. All you have to do is to run the following command: deepstream-app -c ./config/deepstream_app_custom_yolo.txt Launching DeepStream for the first time would take a while as the ONNX model would need to be converted to a TensorRT Engine. It is recommended to close memory hungry apps such as Chromium during this process. Once the engine file is created, subsequent launches will be fast provided the path of the engine file is defined in the Tiny YOLOv2 configuration file. On running DeepStream, once the engine file is created we are presented with a 2x2 tiled display as shown in the video below. Each unit in the tiled display corresponds to a different streaming input. As expected, all four different inputs are processed simultaneously. Since we also enabled RTSP, we can access the stream at rtsp://localhost:8554/ds-test. I used VLC and the RTSP address (after replacing localhost with the IP address of my Jetson Nano) to access the stream on my laptop which was connected to the same network. Note that, another sink is also used to save the output stream to disk. It is impressive to note that the console periodically logs an FPS of nearly 6.7 per video stream! If we had a single input stream, then our FPS should ideally be four times greater than this four video case. I test this out by changing the values in the configuration files and launching DeepStream once again. As expected, we get a whopping near 27 FPS for the single video stream! The performance is impressive considering it still is sending output to three different sinks. We do however note that the detection accuracy of Tiny YOLOv2 is not as phenomenal as the FPS. This is particularly because the model was optimized for speed at the cost of some accuracy. Moreover, the people in the video had blurred faces and the model might not have encountered this blurriness while training. Hence, the model might have faced additional difficulty for that class. DeepStream is blazingly fast. Even though Tiny YOLOv2 is optimized for speed rather than accuracy, a stable high FPS performance while providing amazing features such as seamless multi-stream processing and an RTSP stream is something to be appreciated. However, using DeepStream may not be straightforward, especially if your model is not completely compatible with TensorRT. In such cases, manually writing your own TensorRT layers might be a more viable (albeit tedious) option. Moreover, it may so happen that the readily available ONNX models may have an opset version greater than what is currently accepted by DeepStream. Nevertheless, I do feel that the functionality offered by DeepStream is worth the effort. I would recommend you to give it a shot by replicating my experiment!
[ { "code": null, "e": 669, "s": 171, "text": "Deploying complex deep learning models onto small embedded devices is challenging. Even with hardware optimized for deep learning such as the Jetson Nano and inference optimization tools such as TensorRT, bottlenecks can still present itself in the I/O pipeline. These bottlenecks can potentially compound if the model has to deal with complex I/O pipelines with multiple input and output streams. Wouldn’t it be great to have a tool that can take care of all bottlenecks in an end-to-end fashion?" }, { "code": null, "e": 1133, "s": 669, "text": "Turns out there is a SDK that attempts to mitigate this problem. DeepStream is an SDK that is optimized for NVIDIA Jetson and T4 platforms to provide a seamless end-to-end service to convert raw streaming data into actionable insights. It is built on top of the GStreamer framework. Here, “raw streaming data” is typically continuous (and multiple) video streams and “actionable insights” are the final outputs of your deep learning or other analytics algorithms." }, { "code": null, "e": 1446, "s": 1133, "text": "DeepStream SDK uses its custom GStreamer Plugins to provide various functionalities. Notably, it has plugins for TensorRT based inference and object tracking. The below image lists out the capabilities of their plugins. For an exhaustive technical guide about their plugins, you can refer to their Plugin Manual." }, { "code": null, "e": 1797, "s": 1446, "text": "One feature I particularly liked about DeepStream is that it optimally takes care of the entire I/O processing in a pipelined fashion. We can also stack multiple deep learning algorithms to process information asynchronously. This allows you to increase throughput without the hassle of manually creating and managing a multiprocessing system design." }, { "code": null, "e": 2125, "s": 1797, "text": "The best part is, for some supported applications such as object detection, tracking, classification or semantic segmentation, DeepStream is easy to use! For such an application, as long you have a deep learning model in a compatible format, you can easily launch DeepStream by just setting a few parameters in some text files." }, { "code": null, "e": 2267, "s": 2125, "text": "In this blog, we will design and run an experiment on DeepStream to test out its features and to see if it is easy to use on the Jetson Nano." }, { "code": null, "e": 2430, "s": 2267, "text": "To test the features of DeepStream, let's deploy a pre-trained object detection algorithm on the Jetson Nano. This is an ideal experiment for a couple of reasons:" }, { "code": null, "e": 2503, "s": 2430, "text": "DeepStream is optimized for inference on NVIDIA T4 and Jetson platforms." }, { "code": null, "e": 2683, "s": 2503, "text": "DeepStream has a plugin for inference using TensorRT that supports object detection. Moreover, it automatically converts models in the ONNX format to an optimized TensorRT engine." }, { "code": null, "e": 2798, "s": 2683, "text": "It has plugins that support multiple streaming inputs. It also has plugins to save the output in multiple formats." }, { "code": null, "e": 3016, "s": 2798, "text": "The ONNX model zoo has a bunch of pre-trained object detection models. I chose the Tiny YOLO v2 model from the zoo as it was readily compatible with DeepStream and was also light enough to run fast on the Jetson Nano." }, { "code": null, "e": 3312, "s": 3016, "text": "Note: I did try using the SSD and YOLO v3 models from the zoo. But there were some compatibility issues. These issues are discussed in my GitHub repository, along with tips to verify and handle such cases. I ended up using Tiny YOLO v2 as it was readily compatible without any additional effort." }, { "code": null, "e": 3369, "s": 3312, "text": "Now, the features we want to investigate are as follows:" }, { "code": null, "e": 3675, "s": 3369, "text": "Multiple input streams: Run DeepStream to perform inference on multiple video streams simultaneously. Specifically, we will try using up-to 4 video streams.Multiple output sinks: Display the result on screen and stream it using RTSP. The stream will be accessed by another device connected to the network." }, { "code": null, "e": 3832, "s": 3675, "text": "Multiple input streams: Run DeepStream to perform inference on multiple video streams simultaneously. Specifically, we will try using up-to 4 video streams." }, { "code": null, "e": 3982, "s": 3832, "text": "Multiple output sinks: Display the result on screen and stream it using RTSP. The stream will be accessed by another device connected to the network." }, { "code": null, "e": 4349, "s": 3982, "text": "The performance (Frames per Second, FPS) and ease-of-use will be evaluated for the experiment. The next few sections will guide you through how to set up DeepStream on Jetson Nano to run this experiment. All code used for this experiment is available on my GitHub repository. If you are just curious about how it turned out, feel free to skip to the results section." }, { "code": null, "e": 4442, "s": 4349, "text": "In this section, we will walk through some instructions to set things up for our experiment." }, { "code": null, "e": 4654, "s": 4442, "text": "Follow the instructions on the Getting Started With Jetson Nano Developer Kit to set up and boot your Jetson Nano. In case you face some issues with the setup, I would highly recommend following these resources." }, { "code": null, "e": 4728, "s": 4654, "text": "I would like to highlight some pointers that might save you some trouble:" }, { "code": null, "e": 4797, "s": 4728, "text": "It is recommended to use at least a 32GB MicroSD card (I used 64GB)." }, { "code": null, "e": 4939, "s": 4797, "text": "You need a wired ethernet connection. If you need to connect your Jetson Nano to WiFi, you need to use a dongle such as the Edimax EW-7811Un." }, { "code": null, "e": 5049, "s": 4939, "text": "You need a monitor that directly accepts HDMI input. I could not use my VGA monitor using a VGA-HDMI adapter." }, { "code": null, "e": 5254, "s": 5049, "text": "Now that you have your Jetson Nano up and running, we can install DeepStream. Nvidia has put together the DeepStream quick start guide where you can follow the instructions under the section Jetson Setup." }, { "code": null, "e": 5384, "s": 5254, "text": "Before you go ahead and install DeepStream using the above link, I would like to highlight a few points from my setup experience:" }, { "code": null, "e": 5579, "s": 5384, "text": "The setup would suggest you install Jetpack using the Nvidia SDK Manager. I skipped that step as I realized using the OS image in Part-1 (above) had most of the required dependencies by default." }, { "code": null, "e": 5673, "s": 5579, "text": "In the sub-section “To install the DeepStream SDK” of the quick start guide, I used Method-2." }, { "code": null, "e": 5918, "s": 5673, "text": "After installing DeepStream and boosting the clocks (as mentioned in the guide), we can run one of their samples to verify that the installation is properly done. Move (cd) into your DeepStream installation folder and run the following command:" }, { "code": null, "e": 6036, "s": 5918, "text": "deepstream-app -c ./samples/configs/deepstream-app/source8_1080p_dec_infer-resnet_tracker_tiled_display_fp16_nano.txt" }, { "code": null, "e": 6086, "s": 6036, "text": "On execution, you should see something like this:" }, { "code": null, "e": 6297, "s": 6086, "text": "If you see something similar, congrats! You can play around with more samples if you would like. The guide has a section named “Reference Application Source Details” which provides a description of the samples." }, { "code": null, "e": 6575, "s": 6297, "text": "Now that you have installed and tested DeepSteam, we can go ahead with our experiment. I have bundled up all the files required for the experiment in my GitHub repository. You can follow the step by step instruction in the repository’s readme file about the setup instructions." }, { "code": null, "e": 6814, "s": 6575, "text": "Before moving on with the experiment, if you have not used GStreamer before, it would be worth your time to go through their foundations page. This helps with better understanding of some of the jargons used in DeepStream’s documentation." }, { "code": null, "e": 7110, "s": 6814, "text": "In this section, we will explore how to interface the output of our ONNX model with DeepStream. More specifically, we will walk-through the process of creating a custom processing function in C++ to extract bounding box information from the output of the ONNX model and provide it to DeepStream." }, { "code": null, "e": 7391, "s": 7110, "text": "The ONNX model outputs a tensor of shape (125, 13, 13) in the channels-first format. However, when used with DeepStream, we obtain the flattened version of the tensor which has shape (21125). Our goal is to manually extract the bounding box information from this flattened tensor." }, { "code": null, "e": 7739, "s": 7391, "text": "Let us first try to visually understand the output tensor output by the ONNX model. Consider the output tensor to be a cuboid of dimensions (B, H, W), which in our case B=125,H=13,W=13. We can consider the axes X, Y and B along the width (W), height (H) and depth (B) respectively. Now, each location in the XY plane represents a single grid cell." }, { "code": null, "e": 7924, "s": 7739, "text": "Let us visualize a single grid cell (X=0, Y=0). There 125 values along the depth axis (B) for this given (X,Y) location. Let us rearrange the 125 values in groups of 25 as shown below:" }, { "code": null, "e": 8251, "s": 7924, "text": "As we see here, each of the contiguous 25 values belong to a separate bounding box. Among each set of 25 values, the first 5 values are of the bounding box parameters and the last 20 values are class probabilities. Using this, we can extract the coordinates and confidence score for each of the 5 bounding boxes as shown here:" }, { "code": null, "e": 8435, "s": 8251, "text": "Note that we have only performed this operation at one grid cell (X=0, Y=0). We must iterate over all combinations of X and Y to find the 5 bounding box predictions at each grid cell." }, { "code": null, "e": 8659, "s": 8435, "text": "Now that we have a visual idea of how the information is stored, let us try to extract it using indexing. After flattening the output tensor, we get a single array in which information is stored as shown in the image below:" }, { "code": null, "e": 8901, "s": 8659, "text": "The flattened array has 125 * 13 * 13 = 21125 elements. As shown above, each location in the array corresponds to the indices (b, y, x). We can observe that for a given (y,x) value, the corresponding b values are separated by 13 * 13 = 169 ." }, { "code": null, "e": 9171, "s": 8901, "text": "The following code snippet in Python shows how we can obtain the locations of b values corresponding to each of the 5 bounding boxes in a given (y, x) location. Do note that, as shown in Figure A, there are 25 b values for each bounding box for a given (y, x) location." }, { "code": null, "e": 9563, "s": 9171, "text": "## Let arr be the flattened array.## The array values contains the value of arr at the 25 b_values per ## bbox,x,y combination.num_anchors = 5num_classes = 20xy_offset = y * 13 + xb_offset = 13 * 13bbox_offset = 5 + num_classesfor bbox in range(num_anchors): values = [] for b in range(bbox_offset): value = arr[xy_offset + b_offset * (b + bbox * bbox_offset)] values.append(value)" }, { "code": null, "e": 9630, "s": 9563, "text": "All that is left to do is to write the C++ equivalent of the same." }, { "code": null, "e": 9812, "s": 9630, "text": "Now that we understand how the output is stored and can be extracted, we need to write a function in C++ to do the same. DeepStream expects a function with arguments as shown below:" }, { "code": null, "e": 10076, "s": 9812, "text": "extern \"C\" bool NvDsInferParseCustomYoloV2Tiny( std::vector<NvDsInferLayerInfo> const& outputLayersInfo, NvDsInferNetworkInfo const& networkInfo, NvDsInferParseDetectionParams const& detectionParams, std::vector<NvDsInferParseObjectInfo>& objectList);" }, { "code": null, "e": 10507, "s": 10076, "text": "In the above function prototype, outputLayersInfo is a std::vector containing information and data about each output layer of our ONNX model. In our case, since we have just one output layer, we can access the data using outputLayersInfo[0].buffer. The variable networkInfo has information about the height and width expected by the model and detectionParams has information about some configurations such as numClassesConfigured." }, { "code": null, "e": 10865, "s": 10507, "text": "The variable objectList should be updated with a std::vector of bounding box information stored as objects of type NvDsInferParseObjectInfo at every call of the function. Since the variable was passed by reference, we don’t need to return it as the changes will be reflected at the source. However, the function must return true at the end of its execution." }, { "code": null, "e": 11295, "s": 10865, "text": "For our use case, we create NvDsInferParseCustomYoloV2Tiny such that it will first decode the output of the ONNX model as described in Part-1 of this section. For each bounding box, we create an object of type NvDsInferParseObjectInfo to store its information. We then apply non-maximum suppression to remove duplicate bounding box detections of the same object. We then add the resulting bounding boxes to the objectList vector." }, { "code": null, "e": 11607, "s": 11295, "text": "My GitHub repository has nvdsparsebbox_tiny_yolo.cpp inside the directory custom_bbox_parser with the function already written for you. The below flowchart explains the flow of logic within the file. The code may seem large but that is only because it is heavily documented and commented for your understanding!" }, { "code": null, "e": 11949, "s": 11607, "text": "All that’s left now is to compile the function into a .so file so that DeepStream can load and use it. Before you compile it, you may need to set some variables inside the Makefile. You can refer to step 4 of the ReadMe in my GitHub repository for instructions. Once that is done, cd into the GitHub repository and run the following command:" }, { "code": null, "e": 11976, "s": 11949, "text": "make -C custom_bbox_parser" }, { "code": null, "e": 12274, "s": 11976, "text": "The good news is that most of the heavy lifting work is done. All that is left is to set up some configuration files which will tell DeepStream how to run the experiments. A configurations file has a set of “groups”, each of which has a set of “properties” that are written in the key-file format." }, { "code": null, "e": 12429, "s": 12274, "text": "For our experiment, we need to set up two configuration files. In this section we will explore some important properties within these configuration files." }, { "code": null, "e": 12654, "s": 12429, "text": "Our ONNX model is used by the Gst-Nvinfer plugin of DeepStream. We need to set-up some properties to tell the plugin information such as the location of our ONNX model, location of our compiled bounding box parser and so on." }, { "code": null, "e": 12922, "s": 12654, "text": "In the GitHub repository, the configuration file named config_infer_custom_yolo.txt is already setup for our experiment. Comments are given in the file with reasoning for each property setting. For a detailed list of all the supported properties, check out this link." }, { "code": null, "e": 13210, "s": 12922, "text": "Some interesting properties that we have not used are the “net-scale-factor” and the “offset” properties. They essentially scale the input (x) using the formula: net_scale_factor * (x — mean). We did not use those properties as our network directly takes the unscaled image as the input." }, { "code": null, "e": 13484, "s": 13210, "text": "We also need to set a configuration file for DeepStream to enable and configure the various plugins that will be used by it. As mentioned before, the GitHub repository contains the configuration file deepstream_app_custom_yolo.txt which is already setup for our experiment." }, { "code": null, "e": 13760, "s": 13484, "text": "Unlike the previous part, this configuration has a lot of groups such as “osd” (On Screen Display), “primary-gie” (Primary GPU Inference Engine) and so on. This link has information about all possible groups that can be configured and the properties supported for each group." }, { "code": null, "e": 14281, "s": 13760, "text": "For our experiment, we define a single source group (source0) and three sink groups (sink0, sink1 and sink2). The single source group is responsible for reading four input video streams parallely. The three sink groups are used for displaying output on screen, streaming output using RTSP and for saving output to disk respectively. We provide the path of the configuration file of Tiny YOLOv2 in the primary-gie group. Moreover, we also set the titled-display and osd groups to control how the output appears on screen." }, { "code": null, "e": 14359, "s": 14281, "text": "This is the easiest part. All you have to do is to run the following command:" }, { "code": null, "e": 14417, "s": 14359, "text": "deepstream-app -c ./config/deepstream_app_custom_yolo.txt" }, { "code": null, "e": 14780, "s": 14417, "text": "Launching DeepStream for the first time would take a while as the ONNX model would need to be converted to a TensorRT Engine. It is recommended to close memory hungry apps such as Chromium during this process. Once the engine file is created, subsequent launches will be fast provided the path of the engine file is defined in the Tiny YOLOv2 configuration file." }, { "code": null, "e": 15050, "s": 14780, "text": "On running DeepStream, once the engine file is created we are presented with a 2x2 tiled display as shown in the video below. Each unit in the tiled display corresponds to a different streaming input. As expected, all four different inputs are processed simultaneously." }, { "code": null, "e": 15481, "s": 15050, "text": "Since we also enabled RTSP, we can access the stream at rtsp://localhost:8554/ds-test. I used VLC and the RTSP address (after replacing localhost with the IP address of my Jetson Nano) to access the stream on my laptop which was connected to the same network. Note that, another sink is also used to save the output stream to disk. It is impressive to note that the console periodically logs an FPS of nearly 6.7 per video stream!" }, { "code": null, "e": 15861, "s": 15481, "text": "If we had a single input stream, then our FPS should ideally be four times greater than this four video case. I test this out by changing the values in the configuration files and launching DeepStream once again. As expected, we get a whopping near 27 FPS for the single video stream! The performance is impressive considering it still is sending output to three different sinks." }, { "code": null, "e": 16246, "s": 15861, "text": "We do however note that the detection accuracy of Tiny YOLOv2 is not as phenomenal as the FPS. This is particularly because the model was optimized for speed at the cost of some accuracy. Moreover, the people in the video had blurred faces and the model might not have encountered this blurriness while training. Hence, the model might have faced additional difficulty for that class." }, { "code": null, "e": 16500, "s": 16246, "text": "DeepStream is blazingly fast. Even though Tiny YOLOv2 is optimized for speed rather than accuracy, a stable high FPS performance while providing amazing features such as seamless multi-stream processing and an RTSP stream is something to be appreciated." }, { "code": null, "e": 16875, "s": 16500, "text": "However, using DeepStream may not be straightforward, especially if your model is not completely compatible with TensorRT. In such cases, manually writing your own TensorRT layers might be a more viable (albeit tedious) option. Moreover, it may so happen that the readily available ONNX models may have an opset version greater than what is currently accepted by DeepStream." } ]
MySQL query to update all the values in a column with numeric incremental values like John1, John2, John3, etc.
To update all the values in a column to John1, John2, etc.; you need to set incremental values 1, 2, 3, etc. and concatenate them to the records. Let us first create a table − mysql> create table DemoTable ( StudentId varchar(80) ); Query OK, 0 rows affected (0.50 sec) Insert some records in the table using insert command. Here, for our example, we have set similar names − mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.14 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.08 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable values('John'); Query OK, 1 row affected (0.08 sec) Display all records from the table using select statement − mysql> select *from DemoTable; This will produce the following output − +-----------+ | StudentId | +-----------+ | John | | John | | John | | John | | John | +-----------+ 5 rows in set (0.00 sec) Following is the query to update/concatenate all names with numeric incremental values − mysql> update DemoTable,(select @row := 0) r set StudentId =concat('John',@row := @row+ 1); Query OK, 5 rows affected (0.11 sec) Rows matched: 5 Changed: 5 Warnings: 0 Let us check the table records once again − mysql> select *from DemoTable; This will produce the following output − +-----------+ | StudentId | +-----------+ | John1 | | John2 | | John3 | | John4 | | John5 | +-----------+ 5 rows in set (0.00 sec)
[ { "code": null, "e": 1238, "s": 1062, "text": "To update all the values in a column to John1, John2, etc.; you need to set incremental values 1, 2, 3, etc. and concatenate them to the records. Let us first create a table −" }, { "code": null, "e": 1335, "s": 1238, "text": "mysql> create table DemoTable\n(\n StudentId varchar(80)\n);\nQuery OK, 0 rows affected (0.50 sec)" }, { "code": null, "e": 1441, "s": 1335, "text": "Insert some records in the table using insert command. Here, for our example, we have set similar names −" }, { "code": null, "e": 1846, "s": 1441, "text": "mysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.14 sec)\nmysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.08 sec)\nmysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.07 sec)\nmysql> insert into DemoTable values('John');\nQuery OK, 1 row affected (0.08 sec)" }, { "code": null, "e": 1906, "s": 1846, "text": "Display all records from the table using select statement −" }, { "code": null, "e": 1937, "s": 1906, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 1978, "s": 1937, "text": "This will produce the following output −" }, { "code": null, "e": 2129, "s": 1978, "text": "+-----------+\n| StudentId |\n+-----------+\n| John |\n| John |\n| John |\n| John |\n| John |\n+-----------+\n5 rows in set (0.00 sec)" }, { "code": null, "e": 2218, "s": 2129, "text": "Following is the query to update/concatenate all names with numeric incremental values −" }, { "code": null, "e": 2386, "s": 2218, "text": "mysql> update DemoTable,(select @row := 0) r set StudentId =concat('John',@row := @row+ 1);\nQuery OK, 5 rows affected (0.11 sec)\nRows matched: 5 Changed: 5 Warnings: 0" }, { "code": null, "e": 2430, "s": 2386, "text": "Let us check the table records once again −" }, { "code": null, "e": 2461, "s": 2430, "text": "mysql> select *from DemoTable;" }, { "code": null, "e": 2502, "s": 2461, "text": "This will produce the following output −" }, { "code": null, "e": 2653, "s": 2502, "text": "+-----------+\n| StudentId |\n+-----------+\n| John1 |\n| John2 |\n| John3 |\n| John4 |\n| John5 |\n+-----------+\n5 rows in set (0.00 sec)" } ]
Return query based on date in MongoDB?
To return query based on the date in MongoDB, let us take an example. To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows − > db.returnQueryFromDate.insertOne({"PassengerName":"John","PassengerAge":23,"PassengerArrivalTime":new ISODate("2018-03-10 14:45:56")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a57be9064dcd4a68b70e4") } > db.returnQueryFromDate.insertOne({"PassengerName":"Larry","PassengerAge":21,"PassengerArrivalTime":new ISODate("2018-05-19 11:10:23")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e5") } > db.returnQueryFromDate.insertOne({"PassengerName":"Mike","PassengerAge":24,"PassengerArrivalTime":new ISODate("2018-08-25 16:40:12")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e6") } >db.returnQueryFromDate.insertOne({"PassengerName":"Carol","PassengerAge":26,"PassengerArrivalTime":new ISODate("2019-01-29 09:45:10")}); { "acknowledged" : true, "insertedId" : ObjectId("5c8a57bf9064dcd4a68b70e7") } Display all documents from a collection with the help of find() method. The query is as follows − > db.returnQueryFromDate.find().pretty(); The following is the output − { "_id" : ObjectId("5c8a57be9064dcd4a68b70e4"), "PassengerName" : "John", "PassengerAge" : 23, "PassengerArrivalTime" : ISODate("2018-03-10T14:45:56Z") } { "_id" : ObjectId("5c8a57bf9064dcd4a68b70e5"), "PassengerName" : "Larry", "PassengerAge" : 21, "PassengerArrivalTime" : ISODate("2018-05-19T11:10:23Z") } { "_id" : ObjectId("5c8a57bf9064dcd4a68b70e6"), "PassengerName" : "Mike", "PassengerAge" : 24, "PassengerArrivalTime" : ISODate("2018-08-25T16:40:12Z") } { "_id" : ObjectId("5c8a57bf9064dcd4a68b70e7"), "PassengerName" : "Carol", "PassengerAge" : 26, "PassengerArrivalTime" : ISODate("2019-01-29T09:45:10Z") } Here is return query based on date. The records with a date greater than 2018-05-19T11:10:23Z will be displayed − > db.returnQueryFromDate.find({"PassengerArrivalTime" : { $gte : new ISODate("2018-05-19T11:10:23Z") }}).pretty(); The following is the output − { "_id" : ObjectId("5c8a57bf9064dcd4a68b70e5"), "PassengerName" : "Larry", "PassengerAge" : 21, "PassengerArrivalTime" : ISODate("2018-05-19T11:10:23Z") } { "_id" : ObjectId("5c8a57bf9064dcd4a68b70e6"), "PassengerName" : "Mike", "PassengerAge" : 24, "PassengerArrivalTime" : ISODate("2018-08-25T16:40:12Z") } { "_id" : ObjectId("5c8a57bf9064dcd4a68b70e7"), "PassengerName" : "Carol", "PassengerAge" : 26, "PassengerArrivalTime" : ISODate("2019-01-29T09:45:10Z") }
[ { "code": null, "e": 1132, "s": 1062, "text": "To return query based on the date in MongoDB, let us take an example." }, { "code": null, "e": 1270, "s": 1132, "text": "To understand the concept, let us create a collection with the document. The query to create a collection with a document is as follows −" }, { "code": null, "e": 2151, "s": 1270, "text": "> db.returnQueryFromDate.insertOne({\"PassengerName\":\"John\",\"PassengerAge\":23,\"PassengerArrivalTime\":new ISODate(\"2018-03-10 14:45:56\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a57be9064dcd4a68b70e4\")\n}\n> db.returnQueryFromDate.insertOne({\"PassengerName\":\"Larry\",\"PassengerAge\":21,\"PassengerArrivalTime\":new ISODate(\"2018-05-19 11:10:23\")});\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5c8a57bf9064dcd4a68b70e5\")\n}\n> db.returnQueryFromDate.insertOne({\"PassengerName\":\"Mike\",\"PassengerAge\":24,\"PassengerArrivalTime\":new ISODate(\"2018-08-25 16:40:12\")});\n{\n\"acknowledged\" : true,\n\"insertedId\" : ObjectId(\"5c8a57bf9064dcd4a68b70e6\")\n}\n>db.returnQueryFromDate.insertOne({\"PassengerName\":\"Carol\",\"PassengerAge\":26,\"PassengerArrivalTime\":new ISODate(\"2019-01-29 09:45:10\")});\n{\n\"acknowledged\" : true,\n\"insertedId\" : ObjectId(\"5c8a57bf9064dcd4a68b70e7\")\n}" }, { "code": null, "e": 2249, "s": 2151, "text": "Display all documents from a collection with the help of find() method. The query is as follows −" }, { "code": null, "e": 2291, "s": 2249, "text": "> db.returnQueryFromDate.find().pretty();" }, { "code": null, "e": 2321, "s": 2291, "text": "The following is the output −" }, { "code": null, "e": 2987, "s": 2321, "text": "{\n \"_id\" : ObjectId(\"5c8a57be9064dcd4a68b70e4\"),\n \"PassengerName\" : \"John\",\n \"PassengerAge\" : 23,\n \"PassengerArrivalTime\" : ISODate(\"2018-03-10T14:45:56Z\")\n}\n{\n \"_id\" : ObjectId(\"5c8a57bf9064dcd4a68b70e5\"),\n \"PassengerName\" : \"Larry\",\n \"PassengerAge\" : 21,\n \"PassengerArrivalTime\" : ISODate(\"2018-05-19T11:10:23Z\")\n}\n{\n \"_id\" : ObjectId(\"5c8a57bf9064dcd4a68b70e6\"),\n \"PassengerName\" : \"Mike\",\n \"PassengerAge\" : 24,\n \"PassengerArrivalTime\" : ISODate(\"2018-08-25T16:40:12Z\")\n}\n{\n \"_id\" : ObjectId(\"5c8a57bf9064dcd4a68b70e7\"),\n \"PassengerName\" : \"Carol\",\n \"PassengerAge\" : 26,\n \"PassengerArrivalTime\" : ISODate(\"2019-01-29T09:45:10Z\")\n}" }, { "code": null, "e": 3101, "s": 2987, "text": "Here is return query based on date. The records with a date greater than 2018-05-19T11:10:23Z will be displayed −" }, { "code": null, "e": 3216, "s": 3101, "text": "> db.returnQueryFromDate.find({\"PassengerArrivalTime\" : { $gte : new ISODate(\"2018-05-19T11:10:23Z\") }}).pretty();" }, { "code": null, "e": 3246, "s": 3216, "text": "The following is the output −" }, { "code": null, "e": 3746, "s": 3246, "text": "{\n \"_id\" : ObjectId(\"5c8a57bf9064dcd4a68b70e5\"),\n \"PassengerName\" : \"Larry\",\n \"PassengerAge\" : 21,\n \"PassengerArrivalTime\" : ISODate(\"2018-05-19T11:10:23Z\")\n}\n{\n \"_id\" : ObjectId(\"5c8a57bf9064dcd4a68b70e6\"),\n \"PassengerName\" : \"Mike\",\n \"PassengerAge\" : 24,\n \"PassengerArrivalTime\" : ISODate(\"2018-08-25T16:40:12Z\")\n}\n{\n \"_id\" : ObjectId(\"5c8a57bf9064dcd4a68b70e7\"),\n \"PassengerName\" : \"Carol\",\n \"PassengerAge\" : 26,\n \"PassengerArrivalTime\" : ISODate(\"2019-01-29T09:45:10Z\")\n}" } ]
Find k-th smallest element in BST (Order Statistics in BST) in C++
Suppose we have a binary search tree and a value K as input, we have to find K-th smallest element in the tree. So, if the input is like k = 3, then the output will be 15. To solve this, we will follow these steps − Define a function find_kth_smallest(), this will take root, count, k, Define a function find_kth_smallest(), this will take root, count, k, if root is NULL, then −return NULL if root is NULL, then − return NULL return NULL left = find_kth_smallest(left of root, count, k) left = find_kth_smallest(left of root, count, k) if left is not NULL, then −return left if left is not NULL, then − return left return left (increase count by 1) (increase count by 1) if count is same as k, then −return root if count is same as k, then − return root return root return find_kth_smallest(right of root, count, k) return find_kth_smallest(right of root, count, k) From the main method, do the following − From the main method, do the following − count := 0 count := 0 res = find_kth_smallest(root, count, k) res = find_kth_smallest(root, count, k) if res is NULL, then −display not found if res is NULL, then − display not found display not found Otherwisedisplay val of res Otherwise display val of res display val of res Let us see the following implementation to get better understanding − Live Demo #include <iostream> using namespace std; struct TreeNode { int val; TreeNode *left, *right; TreeNode(int x) { val = x; left = right = NULL; } }; TreeNode* find_kth_smallest(TreeNode* root, int &count, int k) { if (root == NULL) return NULL; TreeNode* left = find_kth_smallest(root->left, count, k); if (left != NULL) return left; count++; if (count == k) return root; return find_kth_smallest(root->right, count, k); } void kth_smallest(TreeNode* root, int k) { int count = 0; TreeNode* res = find_kth_smallest(root, count, k); if (res == NULL) cout << "Not found"; else cout << res->val; } int main() { TreeNode* root = new TreeNode(25); root->left = new TreeNode(13); root->right = new TreeNode(27); root->left->left = new TreeNode(9); root->left->right = new TreeNode(17); root->left->right->left = new TreeNode(15); root->left->right->right = new TreeNode(19); int k = 3; kth_smallest(root, k); } TreeNode* root = new TreeNode(25); root->left = new TreeNode(13); root->right = new TreeNode(27); root->left->left = new TreeNode(9); root->left->right = new TreeNode(17); root- >left->right->left = new TreeNode(15); root->left->right->right = new TreeNode(19); k = 3 15
[ { "code": null, "e": 1174, "s": 1062, "text": "Suppose we have a binary search tree and a value K as input, we have to find K-th smallest element in the tree." }, { "code": null, "e": 1199, "s": 1174, "text": "So, if the input is like" }, { "code": null, "e": 1234, "s": 1199, "text": "k = 3, then the output will be 15." }, { "code": null, "e": 1278, "s": 1234, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1348, "s": 1278, "text": "Define a function find_kth_smallest(), this will take root, count, k," }, { "code": null, "e": 1418, "s": 1348, "text": "Define a function find_kth_smallest(), this will take root, count, k," }, { "code": null, "e": 1453, "s": 1418, "text": "if root is NULL, then −return NULL" }, { "code": null, "e": 1477, "s": 1453, "text": "if root is NULL, then −" }, { "code": null, "e": 1489, "s": 1477, "text": "return NULL" }, { "code": null, "e": 1501, "s": 1489, "text": "return NULL" }, { "code": null, "e": 1550, "s": 1501, "text": "left = find_kth_smallest(left of root, count, k)" }, { "code": null, "e": 1599, "s": 1550, "text": "left = find_kth_smallest(left of root, count, k)" }, { "code": null, "e": 1638, "s": 1599, "text": "if left is not NULL, then −return left" }, { "code": null, "e": 1666, "s": 1638, "text": "if left is not NULL, then −" }, { "code": null, "e": 1678, "s": 1666, "text": "return left" }, { "code": null, "e": 1690, "s": 1678, "text": "return left" }, { "code": null, "e": 1712, "s": 1690, "text": "(increase count by 1)" }, { "code": null, "e": 1734, "s": 1712, "text": "(increase count by 1)" }, { "code": null, "e": 1775, "s": 1734, "text": "if count is same as k, then −return root" }, { "code": null, "e": 1805, "s": 1775, "text": "if count is same as k, then −" }, { "code": null, "e": 1817, "s": 1805, "text": "return root" }, { "code": null, "e": 1829, "s": 1817, "text": "return root" }, { "code": null, "e": 1879, "s": 1829, "text": "return find_kth_smallest(right of root, count, k)" }, { "code": null, "e": 1929, "s": 1879, "text": "return find_kth_smallest(right of root, count, k)" }, { "code": null, "e": 1970, "s": 1929, "text": "From the main method, do the following −" }, { "code": null, "e": 2011, "s": 1970, "text": "From the main method, do the following −" }, { "code": null, "e": 2022, "s": 2011, "text": "count := 0" }, { "code": null, "e": 2033, "s": 2022, "text": "count := 0" }, { "code": null, "e": 2073, "s": 2033, "text": "res = find_kth_smallest(root, count, k)" }, { "code": null, "e": 2113, "s": 2073, "text": "res = find_kth_smallest(root, count, k)" }, { "code": null, "e": 2153, "s": 2113, "text": "if res is NULL, then −display not found" }, { "code": null, "e": 2176, "s": 2153, "text": "if res is NULL, then −" }, { "code": null, "e": 2194, "s": 2176, "text": "display not found" }, { "code": null, "e": 2212, "s": 2194, "text": "display not found" }, { "code": null, "e": 2240, "s": 2212, "text": "Otherwisedisplay val of res" }, { "code": null, "e": 2250, "s": 2240, "text": "Otherwise" }, { "code": null, "e": 2269, "s": 2250, "text": "display val of res" }, { "code": null, "e": 2288, "s": 2269, "text": "display val of res" }, { "code": null, "e": 2358, "s": 2288, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 2369, "s": 2358, "text": " Live Demo" }, { "code": null, "e": 3381, "s": 2369, "text": "#include <iostream>\nusing namespace std;\nstruct TreeNode {\n int val;\n TreeNode *left, *right;\n TreeNode(int x) {\n val = x;\n left = right = NULL;\n }\n};\nTreeNode* find_kth_smallest(TreeNode* root, int &count, int k) {\n if (root == NULL)\n return NULL;\n TreeNode* left = find_kth_smallest(root->left, count, k);\n if (left != NULL)\n return left;\n count++;\n if (count == k)\n return root;\n return find_kth_smallest(root->right, count, k);\n}\nvoid kth_smallest(TreeNode* root, int k) {\n int count = 0;\n TreeNode* res = find_kth_smallest(root, count, k);\n if (res == NULL)\n cout << \"Not found\";\n else\n cout << res->val;\n}\nint main() {\n TreeNode* root = new TreeNode(25);\n root->left = new TreeNode(13);\n root->right = new TreeNode(27);\n root->left->left = new TreeNode(9);\n root->left->right = new TreeNode(17);\n root->left->right->left = new TreeNode(15);\n root->left->right->right = new TreeNode(19);\n int k = 3;\n kth_smallest(root, k);\n}" }, { "code": null, "e": 3649, "s": 3381, "text": "TreeNode* root = new TreeNode(25); root->left = new TreeNode(13);\nroot->right = new TreeNode(27); root->left->left = new\nTreeNode(9); root->left->right = new TreeNode(17); root- >left->right->left = new TreeNode(15); root->left->right->right = new TreeNode(19); k = 3" }, { "code": null, "e": 3652, "s": 3649, "text": "15" } ]
Keras - Model Compilation
Previously, we studied the basics of how to create model using Sequential and Functional API. This chapter explains about how to compile the model. The compilation is the final step in creating a model. Once the compilation is done, we can move on to training phase. Let us learn few concepts required to better understand the compilation process. In machine learning, Loss function is used to find error or deviation in the learning process. Keras requires loss function during model compilation process. Keras provides quite a few loss function in the losses module and they are as follows − mean_squared_error mean_absolute_error mean_absolute_percentage_error mean_squared_logarithmic_error squared_hinge hinge categorical_hinge logcosh huber_loss categorical_crossentropy sparse_categorical_crossentropy binary_crossentropy kullback_leibler_divergence poisson cosine_proximity is_categorical_crossentropy All above loss function accepts two arguments − y_true − true labels as tensors y_true − true labels as tensors y_pred − prediction with same shape as y_true y_pred − prediction with same shape as y_true Import the losses module before using loss function as specified below − from keras import losses In machine learning, Optimization is an important process which optimize the input weights by comparing the prediction and the loss function. Keras provides quite a few optimizer as a module, optimizers and they are as follows: SGD − Stochastic gradient descent optimizer. keras.optimizers.SGD(learning_rate = 0.01, momentum = 0.0, nesterov = False) RMSprop − RMSProp optimizer. keras.optimizers.RMSprop(learning_rate = 0.001, rho = 0.9) Adagrad − Adagrad optimizer. keras.optimizers.Adagrad(learning_rate = 0.01) Adadelta − Adadelta optimizer. keras.optimizers.Adadelta(learning_rate = 1.0, rho = 0.95) Adam − Adam optimizer. keras.optimizers.Adam( learning_rate = 0.001, beta_1 = 0.9, beta_2 = 0.999, amsgrad = False ) Adamax − Adamax optimizer from Adam. keras.optimizers.Adamax(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999) Nadam − Nesterov Adam optimizer. keras.optimizers.Nadam(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999) Import the optimizers module before using optimizers as specified below − from keras import optimizers In machine learning, Metrics is used to evaluate the performance of your model. It is similar to loss function, but not used in training process. Keras provides quite a few metrics as a module, metrics and they are as follows accuracy binary_accuracy categorical_accuracy sparse_categorical_accuracy top_k_categorical_accuracy sparse_top_k_categorical_accuracy cosine_proximity clone_metric Similar to loss function, metrics also accepts below two arguments − y_true − true labels as tensors y_true − true labels as tensors y_pred − prediction with same shape as y_true y_pred − prediction with same shape as y_true Import the metrics module before using metrics as specified below − from keras import metrics Keras model provides a method, compile() to compile the model. The argument and default value of the compile() method is as follows compile( optimizer, loss = None, metrics = None, loss_weights = None, sample_weight_mode = None, weighted_metrics = None, target_tensors = None ) The important arguments are as follows − loss function Optimizer metrics A sample code to compile the mode is as follows − from keras import losses from keras import optimizers from keras import metrics model.compile(loss = 'mean_squared_error', optimizer = 'sgd', metrics = [metrics.categorical_accuracy]) where, loss function is set as mean_squared_error loss function is set as mean_squared_error optimizer is set as sgd optimizer is set as sgd metrics is set as metrics.categorical_accuracy metrics is set as metrics.categorical_accuracy Models are trained by NumPy arrays using fit(). The main purpose of this fit function is used to evaluate your model on training. This can be also used for graphing model performance. It has the following syntax − model.fit(X, y, epochs = , batch_size = ) Here, X, y − It is a tuple to evaluate your data. X, y − It is a tuple to evaluate your data. epochs − no of times the model is needed to be evaluated during training. epochs − no of times the model is needed to be evaluated during training. batch_size − training instances. batch_size − training instances. Let us take a simple example of numpy random data to use this concept. Let us create a random data using numpy for x and y with the help of below mentioned command − import numpy as np x_train = np.random.random((100,4,8)) y_train = np.random.random((100,10)) Now, create random validation data, x_val = np.random.random((100,4,8)) y_val = np.random.random((100,10)) Let us create simple sequential model − from keras.models import Sequential model = Sequential() Create layers to add model − from keras.layers import LSTM, Dense # add a sequence of vectors of dimension 16 model.add(LSTM(16, return_sequences = True)) model.add(Dense(10, activation = 'softmax')) Now model is defined. You can compile using the below command − model.compile( loss = 'categorical_crossentropy', optimizer = 'sgd', metrics = ['accuracy'] ) Now we apply fit() function to train our data − model.fit(x_train, y_train, batch_size = 32, epochs = 5, validation_data = (x_val, y_val)) We have learned to create, compile and train the Keras models. Let us apply our learning and create a simple MPL based ANN. Before creating a model, we need to choose a problem, need to collect the required data and convert the data to NumPy array. Once data is collected, we can prepare the model and train it by using the collected data. Data collection is one of the most difficult phase of machine learning. Keras provides a special module, datasets to download the online machine learning data for training purposes. It fetches the data from online server, process the data and return the data as training and test set. Let us check the data provided by Keras dataset module. The data available in the module are as follows, CIFAR10 small image classification CIFAR100 small image classification IMDB Movie reviews sentiment classification Reuters newswire topics classification MNIST database of handwritten digits Fashion-MNIST database of fashion articles Boston housing price regression dataset Let us use the MNIST database of handwritten digits (or minst) as our input. minst is a collection of 60,000, 28x28 grayscale images. It contains 10 digits. It also contains 10,000 test images. Below code can be used to load the dataset − from keras.datasets import mnist (x_train, y_train), (x_test, y_test) = mnist.load_data() where Line 1 imports minst from the keras dataset module. Line 1 imports minst from the keras dataset module. Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape. Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape. Other dataset can also be fetched using similar API and every API returns similar data as well except the shape of the data. The shape of the data depends on the type of data. Let us choose a simple multi-layer perceptron (MLP) as represented below and try to create the model using Keras. The core features of the model are as follows − Input layer consists of 784 values (28 x 28 = 784). Input layer consists of 784 values (28 x 28 = 784). First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function. First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function. Second hidden layer, Dropout has 0.2 as its value. Second hidden layer, Dropout has 0.2 as its value. Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function. Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function. Fourth hidden layer, Dropout has 0.2 as its value. Fourth hidden layer, Dropout has 0.2 as its value. Fifth and final layer consists of 10 neurons and ‘softmax’ activation function. Fifth and final layer consists of 10 neurons and ‘softmax’ activation function. Use categorical_crossentropy as loss function. Use categorical_crossentropy as loss function. Use RMSprop() as Optimizer. Use RMSprop() as Optimizer. Use accuracy as metrics. Use accuracy as metrics. Use 128 as batch size. Use 128 as batch size. Use 20 as epochs. Use 20 as epochs. Step 1 − Import the modules Let us import the necessary modules. import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop import numpy as np Step 2 − Load data Let us import the mnist dataset. (x_train, y_train), (x_test, y_test) = mnist.load_data() Step 3 − Process the data Let us change the dataset according to our model, so that it can be feed into our model. x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) Where reshape is used to reshape the input from (28, 28) tuple to (784, ) reshape is used to reshape the input from (28, 28) tuple to (784, ) to_categorical is used to convert vector to binary matrix to_categorical is used to convert vector to binary matrix Step 4 − Create the model Let us create the actual model. model = Sequential() model.add(Dense(512, activation = 'relu', input_shape = (784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation = 'softmax')) Step 5 − Compile the model Let us compile the model using selected loss function, optimizer and metrics. model.compile(loss = 'categorical_crossentropy', optimizer = RMSprop(), metrics = ['accuracy']) Step 6 − Train the model Let us train the model using fit() method. history = model.fit( x_train, y_train, batch_size = 128, epochs = 20, verbose = 1, validation_data = (x_test, y_test) ) We have created the model, loaded the data and also trained the data to the model. We still need to evaluate the model and predict output for unknown input, which we learn in upcoming chapter. import keras from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout from keras.optimizers import RMSprop import numpy as np (x_train, y_train), (x_test, y_test) = mnist.load_data() x_train = x_train.reshape(60000, 784) x_test = x_test.reshape(10000, 784) x_train = x_train.astype('float32') x_test = x_test.astype('float32') x_train /= 255 x_test /= 255 y_train = keras.utils.to_categorical(y_train, 10) y_test = keras.utils.to_categorical(y_test, 10) model = Sequential() model.add(Dense(512, activation='relu', input_shape = (784,))) model.add(Dropout(0.2)) model.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) model.add(Dense(10, activation = 'softmax')) model.compile(loss = 'categorical_crossentropy', optimizer = RMSprop(), metrics = ['accuracy']) history = model.fit(x_train, y_train, batch_size = 128, epochs = 20, verbose = 1, validation_data = (x_test, y_test)) Executing the application will give the below content as output − Train on 60000 samples, validate on 10000 samples Epoch 1/20 60000/60000 [==============================] - 7s 118us/step - loss: 0.2453 - acc: 0.9236 - val_loss: 0.1004 - val_acc: 0.9675 Epoch 2/20 60000/60000 [==============================] - 7s 110us/step - loss: 0.1023 - acc: 0.9693 - val_loss: 0.0797 - val_acc: 0.9761 Epoch 3/20 60000/60000 [==============================] - 7s 110us/step - loss: 0.0744 - acc: 0.9770 - val_loss: 0.0727 - val_acc: 0.9791 Epoch 4/20 60000/60000 [==============================] - 7s 110us/step - loss: 0.0599 - acc: 0.9823 - val_loss: 0.0704 - val_acc: 0.9801 Epoch 5/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0504 - acc: 0.9853 - val_loss: 0.0714 - val_acc: 0.9817 Epoch 6/20 60000/60000 [==============================] - 7s 111us/step - loss: 0.0438 - acc: 0.9868 - val_loss: 0.0845 - val_acc: 0.9809 Epoch 7/20 60000/60000 [==============================] - 7s 114us/step - loss: 0.0391 - acc: 0.9887 - val_loss: 0.0823 - val_acc: 0.9802 Epoch 8/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0364 - acc: 0.9892 - val_loss: 0.0818 - val_acc: 0.9830 Epoch 9/20 60000/60000 [==============================] - 7s 113us/step - loss: 0.0308 - acc: 0.9905 - val_loss: 0.0833 - val_acc: 0.9829 Epoch 10/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0289 - acc: 0.9917 - val_loss: 0.0947 - val_acc: 0.9815 Epoch 11/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0279 - acc: 0.9921 - val_loss: 0.0818 - val_acc: 0.9831 Epoch 12/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0260 - acc: 0.9927 - val_loss: 0.0945 - val_acc: 0.9819 Epoch 13/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0257 - acc: 0.9931 - val_loss: 0.0952 - val_acc: 0.9836 Epoch 14/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0229 - acc: 0.9937 - val_loss: 0.0924 - val_acc: 0.9832 Epoch 15/20 60000/60000 [==============================] - 7s 115us/step - loss: 0.0235 - acc: 0.9937 - val_loss: 0.1004 - val_acc: 0.9823 Epoch 16/20 60000/60000 [==============================] - 7s 113us/step - loss: 0.0214 - acc: 0.9941 - val_loss: 0.0991 - val_acc: 0.9847 Epoch 17/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0219 - acc: 0.9943 - val_loss: 0.1044 - val_acc: 0.9837 Epoch 18/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0190 - acc: 0.9952 - val_loss: 0.1129 - val_acc: 0.9836 Epoch 19/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0197 - acc: 0.9953 - val_loss: 0.0981 - val_acc: 0.9841 Epoch 20/20 60000/60000 [==============================] - 7s 112us/step - loss: 0.0198 - acc: 0.9950 - val_loss: 0.1215 - val_acc: 0.9828 87 Lectures 11 hours Abhilash Nelson 61 Lectures 9 hours Abhishek And Pukhraj 57 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 7 hours Abhishek And Pukhraj 52 Lectures 6 hours Abhishek And Pukhraj 68 Lectures 2 hours Mike West Print Add Notes Bookmark this page
[ { "code": null, "e": 2318, "s": 2051, "text": "Previously, we studied the basics of how to create model using Sequential and Functional API. This chapter explains about how to compile the model. The compilation is the final step in creating a model. Once the compilation is done, we can move on to training phase." }, { "code": null, "e": 2399, "s": 2318, "text": "Let us learn few concepts required to better understand the compilation process." }, { "code": null, "e": 2557, "s": 2399, "text": "In machine learning, Loss function is used to find error or deviation in the learning process. Keras requires loss function during model compilation process." }, { "code": null, "e": 2645, "s": 2557, "text": "Keras provides quite a few loss function in the losses module and they are as follows −" }, { "code": null, "e": 2664, "s": 2645, "text": "mean_squared_error" }, { "code": null, "e": 2684, "s": 2664, "text": "mean_absolute_error" }, { "code": null, "e": 2715, "s": 2684, "text": "mean_absolute_percentage_error" }, { "code": null, "e": 2746, "s": 2715, "text": "mean_squared_logarithmic_error" }, { "code": null, "e": 2760, "s": 2746, "text": "squared_hinge" }, { "code": null, "e": 2766, "s": 2760, "text": "hinge" }, { "code": null, "e": 2784, "s": 2766, "text": "categorical_hinge" }, { "code": null, "e": 2792, "s": 2784, "text": "logcosh" }, { "code": null, "e": 2803, "s": 2792, "text": "huber_loss" }, { "code": null, "e": 2828, "s": 2803, "text": "categorical_crossentropy" }, { "code": null, "e": 2860, "s": 2828, "text": "sparse_categorical_crossentropy" }, { "code": null, "e": 2880, "s": 2860, "text": "binary_crossentropy" }, { "code": null, "e": 2908, "s": 2880, "text": "kullback_leibler_divergence" }, { "code": null, "e": 2916, "s": 2908, "text": "poisson" }, { "code": null, "e": 2933, "s": 2916, "text": "cosine_proximity" }, { "code": null, "e": 2961, "s": 2933, "text": "is_categorical_crossentropy" }, { "code": null, "e": 3009, "s": 2961, "text": "All above loss function accepts two arguments −" }, { "code": null, "e": 3041, "s": 3009, "text": "y_true − true labels as tensors" }, { "code": null, "e": 3073, "s": 3041, "text": "y_true − true labels as tensors" }, { "code": null, "e": 3119, "s": 3073, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 3165, "s": 3119, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 3238, "s": 3165, "text": "Import the losses module before using loss function as specified below −" }, { "code": null, "e": 3264, "s": 3238, "text": "from keras import losses\n" }, { "code": null, "e": 3492, "s": 3264, "text": "In machine learning, Optimization is an important process which optimize the input weights by comparing the prediction and the loss function. Keras provides quite a few optimizer as a module, optimizers and they are as follows:" }, { "code": null, "e": 3537, "s": 3492, "text": "SGD − Stochastic gradient descent optimizer." }, { "code": null, "e": 3615, "s": 3537, "text": "keras.optimizers.SGD(learning_rate = 0.01, momentum = 0.0, nesterov = False)\n" }, { "code": null, "e": 3644, "s": 3615, "text": "RMSprop − RMSProp optimizer." }, { "code": null, "e": 3704, "s": 3644, "text": "keras.optimizers.RMSprop(learning_rate = 0.001, rho = 0.9)\n" }, { "code": null, "e": 3733, "s": 3704, "text": "Adagrad − Adagrad optimizer." }, { "code": null, "e": 3781, "s": 3733, "text": "keras.optimizers.Adagrad(learning_rate = 0.01)\n" }, { "code": null, "e": 3812, "s": 3781, "text": "Adadelta − Adadelta optimizer." }, { "code": null, "e": 3872, "s": 3812, "text": "keras.optimizers.Adadelta(learning_rate = 1.0, rho = 0.95)\n" }, { "code": null, "e": 3895, "s": 3872, "text": "Adam − Adam optimizer." }, { "code": null, "e": 3992, "s": 3895, "text": "keras.optimizers.Adam(\n learning_rate = 0.001, beta_1 = 0.9, beta_2 = 0.999, amsgrad = False\n)" }, { "code": null, "e": 4029, "s": 3992, "text": "Adamax − Adamax optimizer from Adam." }, { "code": null, "e": 4107, "s": 4029, "text": "keras.optimizers.Adamax(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999)\n" }, { "code": null, "e": 4140, "s": 4107, "text": "Nadam − Nesterov Adam optimizer." }, { "code": null, "e": 4217, "s": 4140, "text": "keras.optimizers.Nadam(learning_rate = 0.002, beta_1 = 0.9, beta_2 = 0.999)\n" }, { "code": null, "e": 4291, "s": 4217, "text": "Import the optimizers module before using optimizers as specified below −" }, { "code": null, "e": 4321, "s": 4291, "text": "from keras import optimizers\n" }, { "code": null, "e": 4547, "s": 4321, "text": "In machine learning, Metrics is used to evaluate the performance of your model. It is similar to loss function, but not used in training process. Keras provides quite a few metrics as a module, metrics and they are as follows" }, { "code": null, "e": 4556, "s": 4547, "text": "accuracy" }, { "code": null, "e": 4572, "s": 4556, "text": "binary_accuracy" }, { "code": null, "e": 4593, "s": 4572, "text": "categorical_accuracy" }, { "code": null, "e": 4621, "s": 4593, "text": "sparse_categorical_accuracy" }, { "code": null, "e": 4648, "s": 4621, "text": "top_k_categorical_accuracy" }, { "code": null, "e": 4682, "s": 4648, "text": "sparse_top_k_categorical_accuracy" }, { "code": null, "e": 4699, "s": 4682, "text": "cosine_proximity" }, { "code": null, "e": 4712, "s": 4699, "text": "clone_metric" }, { "code": null, "e": 4781, "s": 4712, "text": "Similar to loss function, metrics also accepts below two arguments −" }, { "code": null, "e": 4813, "s": 4781, "text": "y_true − true labels as tensors" }, { "code": null, "e": 4845, "s": 4813, "text": "y_true − true labels as tensors" }, { "code": null, "e": 4891, "s": 4845, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 4937, "s": 4891, "text": "y_pred − prediction with same shape as y_true" }, { "code": null, "e": 5005, "s": 4937, "text": "Import the metrics module before using metrics as specified below −" }, { "code": null, "e": 5032, "s": 5005, "text": "from keras import metrics\n" }, { "code": null, "e": 5164, "s": 5032, "text": "Keras model provides a method, compile() to compile the model. The argument and default value of the compile() method is as follows" }, { "code": null, "e": 5338, "s": 5164, "text": "compile(\n optimizer, \n loss = None, \n metrics = None, \n loss_weights = None, \n sample_weight_mode = None, \n weighted_metrics = None, \n target_tensors = None\n)\n" }, { "code": null, "e": 5379, "s": 5338, "text": "The important arguments are as follows −" }, { "code": null, "e": 5393, "s": 5379, "text": "loss function" }, { "code": null, "e": 5403, "s": 5393, "text": "Optimizer" }, { "code": null, "e": 5411, "s": 5403, "text": "metrics" }, { "code": null, "e": 5461, "s": 5411, "text": "A sample code to compile the mode is as follows −" }, { "code": null, "e": 5654, "s": 5461, "text": "from keras import losses \nfrom keras import optimizers \nfrom keras import metrics \n\nmodel.compile(loss = 'mean_squared_error', \n optimizer = 'sgd', metrics = [metrics.categorical_accuracy])" }, { "code": null, "e": 5661, "s": 5654, "text": "where," }, { "code": null, "e": 5704, "s": 5661, "text": "loss function is set as mean_squared_error" }, { "code": null, "e": 5747, "s": 5704, "text": "loss function is set as mean_squared_error" }, { "code": null, "e": 5771, "s": 5747, "text": "optimizer is set as sgd" }, { "code": null, "e": 5795, "s": 5771, "text": "optimizer is set as sgd" }, { "code": null, "e": 5842, "s": 5795, "text": "metrics is set as metrics.categorical_accuracy" }, { "code": null, "e": 5889, "s": 5842, "text": "metrics is set as metrics.categorical_accuracy" }, { "code": null, "e": 6103, "s": 5889, "text": "Models are trained by NumPy arrays using fit(). The main purpose of this fit function is used to evaluate your model on training. This can be also used for graphing model performance. It has the following syntax −" }, { "code": null, "e": 6146, "s": 6103, "text": "model.fit(X, y, epochs = , batch_size = )\n" }, { "code": null, "e": 6152, "s": 6146, "text": "Here," }, { "code": null, "e": 6196, "s": 6152, "text": "X, y − It is a tuple to evaluate your data." }, { "code": null, "e": 6240, "s": 6196, "text": "X, y − It is a tuple to evaluate your data." }, { "code": null, "e": 6314, "s": 6240, "text": "epochs − no of times the model is needed to be evaluated during training." }, { "code": null, "e": 6388, "s": 6314, "text": "epochs − no of times the model is needed to be evaluated during training." }, { "code": null, "e": 6421, "s": 6388, "text": "batch_size − training instances." }, { "code": null, "e": 6454, "s": 6421, "text": "batch_size − training instances." }, { "code": null, "e": 6525, "s": 6454, "text": "Let us take a simple example of numpy random data to use this concept." }, { "code": null, "e": 6620, "s": 6525, "text": "Let us create a random data using numpy for x and y with the help of below mentioned command −" }, { "code": null, "e": 6717, "s": 6620, "text": "import numpy as np \n\nx_train = np.random.random((100,4,8)) \ny_train = np.random.random((100,10))" }, { "code": null, "e": 6753, "s": 6717, "text": "Now, create random validation data," }, { "code": null, "e": 6826, "s": 6753, "text": "x_val = np.random.random((100,4,8)) \ny_val = np.random.random((100,10))\n" }, { "code": null, "e": 6866, "s": 6826, "text": "Let us create simple sequential model −" }, { "code": null, "e": 6924, "s": 6866, "text": "from keras.models import Sequential model = Sequential()\n" }, { "code": null, "e": 6953, "s": 6924, "text": "Create layers to add model −" }, { "code": null, "e": 7129, "s": 6953, "text": "from keras.layers import LSTM, Dense \n\n# add a sequence of vectors of dimension 16 \nmodel.add(LSTM(16, return_sequences = True)) \nmodel.add(Dense(10, activation = 'softmax'))\n" }, { "code": null, "e": 7193, "s": 7129, "text": "Now model is defined. You can compile using the below command −" }, { "code": null, "e": 7291, "s": 7193, "text": "model.compile(\n loss = 'categorical_crossentropy', optimizer = 'sgd', metrics = ['accuracy']\n)\n" }, { "code": null, "e": 7339, "s": 7291, "text": "Now we apply fit() function to train our data −" }, { "code": null, "e": 7431, "s": 7339, "text": "model.fit(x_train, y_train, batch_size = 32, epochs = 5, validation_data = (x_val, y_val))\n" }, { "code": null, "e": 7494, "s": 7431, "text": "We have learned to create, compile and train the Keras models." }, { "code": null, "e": 7555, "s": 7494, "text": "Let us apply our learning and create a simple MPL based ANN." }, { "code": null, "e": 8161, "s": 7555, "text": "Before creating a model, we need to choose a problem, need to collect the required data and convert the data to NumPy array. Once data is collected, we can prepare the model and train it by using the collected data. Data collection is one of the most difficult phase of machine learning. Keras provides a special module, datasets to download the online machine learning data for training purposes. It fetches the data from online server, process the data and return the data as training and test set. Let us check the data provided by Keras dataset module. The data available in the module are as follows," }, { "code": null, "e": 8196, "s": 8161, "text": "CIFAR10 small image classification" }, { "code": null, "e": 8232, "s": 8196, "text": "CIFAR100 small image classification" }, { "code": null, "e": 8276, "s": 8232, "text": "IMDB Movie reviews sentiment classification" }, { "code": null, "e": 8315, "s": 8276, "text": "Reuters newswire topics classification" }, { "code": null, "e": 8352, "s": 8315, "text": "MNIST database of handwritten digits" }, { "code": null, "e": 8395, "s": 8352, "text": "Fashion-MNIST database of fashion articles" }, { "code": null, "e": 8435, "s": 8395, "text": "Boston housing price regression dataset" }, { "code": null, "e": 8629, "s": 8435, "text": "Let us use the MNIST database of handwritten digits (or minst) as our input. minst is a collection of 60,000, 28x28 grayscale images. It contains 10 digits. It also contains 10,000 test images." }, { "code": null, "e": 8674, "s": 8629, "text": "Below code can be used to load the dataset −" }, { "code": null, "e": 8766, "s": 8674, "text": "from keras.datasets import mnist \n\n(x_train, y_train), (x_test, y_test) = mnist.load_data()" }, { "code": null, "e": 8772, "s": 8766, "text": "where" }, { "code": null, "e": 8824, "s": 8772, "text": "Line 1 imports minst from the keras dataset module." }, { "code": null, "e": 8876, "s": 8824, "text": "Line 1 imports minst from the keras dataset module." }, { "code": null, "e": 9207, "s": 8876, "text": "Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape." }, { "code": null, "e": 9538, "s": 9207, "text": "Line 3 calls the load_data function, which will fetch the data from online server and return the data as 2 tuples, First tuple, (x_train, y_train) represent the training data with shape, (number_sample, 28, 28) and its digit label with shape, (number_samples, ). Second tuple, (x_test, y_test) represent test data with same shape." }, { "code": null, "e": 9714, "s": 9538, "text": "Other dataset can also be fetched using similar API and every API returns similar data as well except the shape of the data. The shape of the data depends on the type of data." }, { "code": null, "e": 9828, "s": 9714, "text": "Let us choose a simple multi-layer perceptron (MLP) as represented below and try to create the model using Keras." }, { "code": null, "e": 9876, "s": 9828, "text": "The core features of the model are as follows −" }, { "code": null, "e": 9928, "s": 9876, "text": "Input layer consists of 784 values (28 x 28 = 784)." }, { "code": null, "e": 9980, "s": 9928, "text": "Input layer consists of 784 values (28 x 28 = 784)." }, { "code": null, "e": 10062, "s": 9980, "text": "First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 10144, "s": 10062, "text": "First hidden layer, Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 10195, "s": 10144, "text": "Second hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 10246, "s": 10195, "text": "Second hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 10334, "s": 10246, "text": "Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 10422, "s": 10334, "text": "Third hidden layer, again Dense consists of 512 neurons and ‘relu’ activation function." }, { "code": null, "e": 10473, "s": 10422, "text": "Fourth hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 10524, "s": 10473, "text": "Fourth hidden layer, Dropout has 0.2 as its value." }, { "code": null, "e": 10604, "s": 10524, "text": "Fifth and final layer consists of 10 neurons and ‘softmax’ activation function." }, { "code": null, "e": 10684, "s": 10604, "text": "Fifth and final layer consists of 10 neurons and ‘softmax’ activation function." }, { "code": null, "e": 10731, "s": 10684, "text": "Use categorical_crossentropy as loss function." }, { "code": null, "e": 10778, "s": 10731, "text": "Use categorical_crossentropy as loss function." }, { "code": null, "e": 10806, "s": 10778, "text": "Use RMSprop() as Optimizer." }, { "code": null, "e": 10834, "s": 10806, "text": "Use RMSprop() as Optimizer." }, { "code": null, "e": 10859, "s": 10834, "text": "Use accuracy as metrics." }, { "code": null, "e": 10884, "s": 10859, "text": "Use accuracy as metrics." }, { "code": null, "e": 10907, "s": 10884, "text": "Use 128 as batch size." }, { "code": null, "e": 10930, "s": 10907, "text": "Use 128 as batch size." }, { "code": null, "e": 10948, "s": 10930, "text": "Use 20 as epochs." }, { "code": null, "e": 10966, "s": 10948, "text": "Use 20 as epochs." }, { "code": null, "e": 10994, "s": 10966, "text": "Step 1 − Import the modules" }, { "code": null, "e": 11031, "s": 10994, "text": "Let us import the necessary modules." }, { "code": null, "e": 11214, "s": 11031, "text": "import keras \nfrom keras.datasets import mnist \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Dropout \nfrom keras.optimizers import RMSprop \nimport numpy as np" }, { "code": null, "e": 11233, "s": 11214, "text": "Step 2 − Load data" }, { "code": null, "e": 11266, "s": 11233, "text": "Let us import the mnist dataset." }, { "code": null, "e": 11324, "s": 11266, "text": "(x_train, y_train), (x_test, y_test) = mnist.load_data()\n" }, { "code": null, "e": 11350, "s": 11324, "text": "Step 3 − Process the data" }, { "code": null, "e": 11439, "s": 11350, "text": "Let us change the dataset according to our model, so that it can be feed into our model." }, { "code": null, "e": 11718, "s": 11439, "text": "x_train = x_train.reshape(60000, 784) \nx_test = x_test.reshape(10000, 784) \nx_train = x_train.astype('float32') \nx_test = x_test.astype('float32') \nx_train /= 255 \nx_test /= 255 \n\ny_train = keras.utils.to_categorical(y_train, 10) \ny_test = keras.utils.to_categorical(y_test, 10)" }, { "code": null, "e": 11724, "s": 11718, "text": "Where" }, { "code": null, "e": 11792, "s": 11724, "text": "reshape is used to reshape the input from (28, 28) tuple to (784, )" }, { "code": null, "e": 11860, "s": 11792, "text": "reshape is used to reshape the input from (28, 28) tuple to (784, )" }, { "code": null, "e": 11918, "s": 11860, "text": "to_categorical is used to convert vector to binary matrix" }, { "code": null, "e": 11976, "s": 11918, "text": "to_categorical is used to convert vector to binary matrix" }, { "code": null, "e": 12002, "s": 11976, "text": "Step 4 − Create the model" }, { "code": null, "e": 12034, "s": 12002, "text": "Let us create the actual model." }, { "code": null, "e": 12260, "s": 12034, "text": "model = Sequential() \nmodel.add(Dense(512, activation = 'relu', input_shape = (784,))) \nmodel.add(Dropout(0.2)) \nmodel.add(Dense(512, activation = 'relu'))\nmodel.add(Dropout(0.2)) \nmodel.add(Dense(10, activation = 'softmax'))" }, { "code": null, "e": 12287, "s": 12260, "text": "Step 5 − Compile the model" }, { "code": null, "e": 12365, "s": 12287, "text": "Let us compile the model using selected loss function, optimizer and metrics." }, { "code": null, "e": 12473, "s": 12365, "text": "model.compile(loss = 'categorical_crossentropy', \n optimizer = RMSprop(), \n metrics = ['accuracy'])" }, { "code": null, "e": 12498, "s": 12473, "text": "Step 6 − Train the model" }, { "code": null, "e": 12541, "s": 12498, "text": "Let us train the model using fit() method." }, { "code": null, "e": 12680, "s": 12541, "text": "history = model.fit(\n x_train, y_train, \n batch_size = 128, \n epochs = 20, \n verbose = 1, \n validation_data = (x_test, y_test)\n)" }, { "code": null, "e": 12873, "s": 12680, "text": "We have created the model, loaded the data and also trained the data to the model. We still need to evaluate the model and predict output for unknown input, which we learn in upcoming chapter." }, { "code": null, "e": 13850, "s": 12873, "text": "import keras \nfrom keras.datasets import mnist \nfrom keras.models import Sequential \nfrom keras.layers import Dense, Dropout \nfrom keras.optimizers import RMSprop \nimport numpy as np \n\n(x_train, y_train), (x_test, y_test) = mnist.load_data() \n\nx_train = x_train.reshape(60000, 784) \nx_test = x_test.reshape(10000, 784) \nx_train = x_train.astype('float32') \nx_test = x_test.astype('float32') \nx_train /= 255 \nx_test /= 255 \n\ny_train = keras.utils.to_categorical(y_train, 10) \ny_test = keras.utils.to_categorical(y_test, 10) \n\nmodel = Sequential() \nmodel.add(Dense(512, activation='relu', input_shape = (784,))) \nmodel.add(Dropout(0.2)) \nmodel.add(Dense(512, activation = 'relu')) model.add(Dropout(0.2)) \nmodel.add(Dense(10, activation = 'softmax'))\nmodel.compile(loss = 'categorical_crossentropy', \n optimizer = RMSprop(), \n metrics = ['accuracy']) \n\nhistory = model.fit(x_train, y_train, \n batch_size = 128, epochs = 20, verbose = 1, validation_data = (x_test, y_test))" }, { "code": null, "e": 13916, "s": 13850, "text": "Executing the application will give the below content as output −" }, { "code": null, "e": 16776, "s": 13916, "text": "Train on 60000 samples, validate on 10000 samples Epoch 1/20 \n60000/60000 [==============================] - 7s 118us/step - loss: 0.2453 \n- acc: 0.9236 - val_loss: 0.1004 - val_acc: 0.9675 Epoch 2/20 \n60000/60000 [==============================] - 7s 110us/step - loss: 0.1023 \n- acc: 0.9693 - val_loss: 0.0797 - val_acc: 0.9761 Epoch 3/20 \n60000/60000 [==============================] - 7s 110us/step - loss: 0.0744 \n- acc: 0.9770 - val_loss: 0.0727 - val_acc: 0.9791 Epoch 4/20 \n60000/60000 [==============================] - 7s 110us/step - loss: 0.0599 \n- acc: 0.9823 - val_loss: 0.0704 - val_acc: 0.9801 Epoch 5/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0504 \n- acc: 0.9853 - val_loss: 0.0714 - val_acc: 0.9817 Epoch 6/20 \n60000/60000 [==============================] - 7s 111us/step - loss: 0.0438 \n- acc: 0.9868 - val_loss: 0.0845 - val_acc: 0.9809 Epoch 7/20 \n60000/60000 [==============================] - 7s 114us/step - loss: 0.0391 \n- acc: 0.9887 - val_loss: 0.0823 - val_acc: 0.9802 Epoch 8/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0364 \n- acc: 0.9892 - val_loss: 0.0818 - val_acc: 0.9830 Epoch 9/20 \n60000/60000 [==============================] - 7s 113us/step - loss: 0.0308 \n- acc: 0.9905 - val_loss: 0.0833 - val_acc: 0.9829 Epoch 10/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0289 \n- acc: 0.9917 - val_loss: 0.0947 - val_acc: 0.9815 Epoch 11/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0279 \n- acc: 0.9921 - val_loss: 0.0818 - val_acc: 0.9831 Epoch 12/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0260 \n- acc: 0.9927 - val_loss: 0.0945 - val_acc: 0.9819 Epoch 13/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0257 \n- acc: 0.9931 - val_loss: 0.0952 - val_acc: 0.9836 Epoch 14/20\n60000/60000 [==============================] - 7s 112us/step - loss: 0.0229 \n- acc: 0.9937 - val_loss: 0.0924 - val_acc: 0.9832 Epoch 15/20 \n60000/60000 [==============================] - 7s 115us/step - loss: 0.0235 \n- acc: 0.9937 - val_loss: 0.1004 - val_acc: 0.9823 Epoch 16/20 \n60000/60000 [==============================] - 7s 113us/step - loss: 0.0214 \n- acc: 0.9941 - val_loss: 0.0991 - val_acc: 0.9847 Epoch 17/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0219 \n- acc: 0.9943 - val_loss: 0.1044 - val_acc: 0.9837 Epoch 18/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0190 \n- acc: 0.9952 - val_loss: 0.1129 - val_acc: 0.9836 Epoch 19/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0197 \n- acc: 0.9953 - val_loss: 0.0981 - val_acc: 0.9841 Epoch 20/20 \n60000/60000 [==============================] - 7s 112us/step - loss: 0.0198 \n- acc: 0.9950 - val_loss: 0.1215 - val_acc: 0.9828" }, { "code": null, "e": 16810, "s": 16776, "text": "\n 87 Lectures \n 11 hours \n" }, { "code": null, "e": 16827, "s": 16810, "text": " Abhilash Nelson" }, { "code": null, "e": 16860, "s": 16827, "text": "\n 61 Lectures \n 9 hours \n" }, { "code": null, "e": 16882, "s": 16860, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 16915, "s": 16882, "text": "\n 57 Lectures \n 7 hours \n" }, { "code": null, "e": 16937, "s": 16915, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 16970, "s": 16937, "text": "\n 52 Lectures \n 7 hours \n" }, { "code": null, "e": 16992, "s": 16970, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 17025, "s": 16992, "text": "\n 52 Lectures \n 6 hours \n" }, { "code": null, "e": 17047, "s": 17025, "text": " Abhishek And Pukhraj" }, { "code": null, "e": 17080, "s": 17047, "text": "\n 68 Lectures \n 2 hours \n" }, { "code": null, "e": 17091, "s": 17080, "text": " Mike West" }, { "code": null, "e": 17098, "s": 17091, "text": " Print" }, { "code": null, "e": 17109, "s": 17098, "text": " Add Notes" } ]
Clustering Techniques. Clustering falls under the unsupervised... | by M Bharathwaj | Towards Data Science
Clustering falls under the unsupervised learning technique. In this technique, the data is not labelled and there is no defined dependant variable. This type of learning is usually done to identify patterns in the data and/or to group similar data. In this post, a detailed explanation on the type of clustering techniques and a code walk-through is provided. Clustering is a method of grouping of similar objects. The objective of clustering is to create homogeneous groups out of heterogeneous observations. The assumption is that the data comes from multiple population, for example, there could be people from different walks of life requesting loan from a bank for different purposes. If the person is a student, he/she could ask for an education loan, someone who is looking to buy a house can ask for home loan and so on. Clustering helps to identify similar group and cater the needs better. Clustering is a distance-based algorithm. The purpose of clustering is to minimize the intra-cluster distance and maximize the inter-cluster distance. Clustering as a tool can be used to gain insight into the data. Huge amount of information can be obtained by visualizing the data. The output of the clustering can also be used as a pre-processing step for other algorithms. There are several use cases of this technique that is used widely — some of the important ones are market segmentation, customer segmentation, image processing. Before proceeding further, let us understand the core of clustering. Clustering is all about distance between two points and distance between two clusters. Distance cannot be negative. There are a few common measures of distance that the algorithm uses for the clustering problem. EUCLIDEAN DISTANCE It is a default distance used by the algorithm. It is best explained as the distance between two points. If the distance between two points p and q are to be measured, then the Euclidean distance is MANHATTAN DISTANCE It is the distance between two points calculated on a perpendicular angle along the axes. It is also called taxicab distance as this represents how vehicles in the city of Manhattan drive where the streets intersect at right angles. MINKOWSKI DISTANCE In an n-dimensional space, the distance between two points is called Minkowski distance. It is a generalization of the Euclidean and Manhattan distance that if the value of p is 2, it becomes Euclidean distance and if the value of p is 1, it becomes Manhattan distance. There are two major types of clustering techniques Hierarchical or Agglomerativek-means Hierarchical or Agglomerative k-means Let us look at each type along with code walk-through It is a bottom-up approach. Records in the data set are grouped sequentially to form clusters based on distance between the records and also the distance between the clusters. Here is a step-wise approach to this method - Start with n clusters where each row is considered as a clusterUsing distance based approach, two records that are closest to each other are merged into a cluster. In Fig 3, for the given five records, assuming A and C are closest in distance, they form a cluster and likewise B and E form another cluster and so on Start with n clusters where each row is considered as a cluster Using distance based approach, two records that are closest to each other are merged into a cluster. In Fig 3, for the given five records, assuming A and C are closest in distance, they form a cluster and likewise B and E form another cluster and so on 3. At every step, two closest clusters will be merged. Either a single record(singleton) is added to the existing cluster or two clusters are combined. After at least one multiple-element cluster is formed, a scenario where the distance needs to be computed for a singleton and a set of observations and that is where the concept of linkages comes into picture. There are five major types of linkages. By using one of the below concepts, the clustering happens- Single linkage: It is the shortest distance between any two points in both the clusters Complete linkage: It is the opposite of single linkage. It is the longest distance between any two points in both the clusters Average linkage: It is the average distance between each point in one cluster to every point in the other cluster Centroid linkage: The distance between the center point in one cluster to the center point in the other cluster Ward’s linkage: A combination of average and centroid methods. The within cluster variance is calculated by determining the center point of the cluster and the distance of the observations from the center. While trying to merge two clusters, the variance is found between the clusters and the clusters are merged whose variance is less compared to the other combination. A point to note is that each linkage method produces an unique result. When each of these methods are applied on the same data set, it may be clustered differently. 4. Repeat the steps until there is a single cluster with all the records To visualize the clustering, there is a concept called dendrogram. The dendrogram is a tree diagram summarizing the clustering process. The records are on the x-axis. Similar records are joined by lines whose vertical length reflects the distance between the records. The greater the difference in height, more the dissimilarity. A sample dendrogram is shown - The code for hierarchical clustering is written in Python 3x using jupyter notebook. Let’s begin by importing the necessary libraries. #Import the necessary librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinefrom scipy.cluster.hierarchy import linkage, dendrogram, fcluster Next, load the data set. Here, a data set on the food menu of Starbucks is used. #Read the datasetdf = pd.read_csv('starbucks_menu.csv')#Look at the top 5 rows df.head() Do the necessary Exploratory Data Analysis like looking at the descriptive statistics, checking for null values, duplicate values. Perform uni-variate and bi-variate analysis, do outlier treatment(if any). Since this is a distance based algorithm, it is necessary to perform normalization wherever applicable so that all the variables are free of any units of measurement. This enables the model to perform at its best. from scipy.stats import zscoredf.iloc[:,1:6] = df.iloc[:,1:6].apply(zscore)#Check the head after scalingdf.head() Once the data is ready, let us work towards building the model. A label list needs to be assigned which is a list of unique value of categorical variable. Here, label list is created from the Food variable. #Before clustering, setup label list from the food variablelabelList = list(df.Food.unique())labelList Next step is to form a linkage to cluster a singleton and another cluster. In this case, ward’s method is preferred. #Create linkage method using Ward's methodlink_method = linkage(df.iloc[:,1:6], method = 'ward') Visualize the clustering with the help of a dendrogram. In this case, a truncated dendrogram by specifying the p value which displays the ante-penultimate and penultimate clusters. #Generate the dendrogramdend = dendrogram(link_method, labels = labelList, truncate_mode='lastp', p=10) Once the dendrogram is created, it is necessary to cut the tree to determine the optimum number of clusters. It can be done in one of two ways (explained in the diagram). In this case, 3 clusters are chosen. The clusters can be attached to the data frame as a new column for gaining insights. #Method 1: criterion = 'maxclust' where a cut is defined based on the number of clustersclusters = fcluster(link_method, 3, criterion='maxclust') clusters#Method 2: criterion='distance' where a cut is defined based on distance in the y-axis#clusters = fcluster(link_method, 800, criterion='distance')#Apply the clusters back to the datasetdf['HCluster'] = clustersdf.head() The last step is to do cluster profiling to extract information and insights from the algorithm to help with effective decision making. The cluster profiling is done by grouping the mean of the cluster and sorting based on the frequency. aggdata=df.iloc[:,1:8].groupby('HCluster').mean()aggdata['Frequency']=df.HCluster.value_counts().sort_index()aggdata A quick insight is that the first cluster has the food items that are usually low in calories and hence the macro nutrients are on the lower side. The second cluster has the food items with the most amount of calories and hence more in macro nutrients and there is a mid range in between cluster 1 and 2 which is the third cluster that has good amount of calories and macro nutrients. Overall, on a brief, this model has clustered well. Let’s move on to the next method K-Means is a non-hierarchical approach. The idea is to specify the number of clusters before hand. Based on the number of clusters, each record is assigned to the cluster based on the distance from each cluster. This approach is preferred when the data set is large. The word means in k-means refers to averaging of the data which is also referred to as finding the centroid. Here is a step-wise approach- Specify the k value before handAssign each record to the cluster whose distance is smallest to the centroid. The K-Means by default uses Euclidean distanceRe-calculate the centroid for the newly formed clusters. There is a chance that some of the data points may move around based on the distance.Re-assignment may happen on an iterative basis and new centroid is formed. This process will stop until there is no jumping of observations from cluster to cluster.If there is any re-assignment, go back to step 3 and continue the steps. If not, the clusters are finalized. Specify the k value before hand Assign each record to the cluster whose distance is smallest to the centroid. The K-Means by default uses Euclidean distance Re-calculate the centroid for the newly formed clusters. There is a chance that some of the data points may move around based on the distance. Re-assignment may happen on an iterative basis and new centroid is formed. This process will stop until there is no jumping of observations from cluster to cluster. If there is any re-assignment, go back to step 3 and continue the steps. If not, the clusters are finalized. Although we have determined the number of clusters before hand, it may not be always right and it is necessary to determine the optimum number of clusters. There is no solid solution to determine the number of clusters, however, there is a common method in place. For each value of k, a Within Sum of Squares(WSS) value can be identified. A single cluster cannot be chosen so it is important to find that k value after which there is no significant difference in the WSS value. To make this more efficient, an elbow plot can be drawn with WSS scores in the y-axis and number of clusters in the x-axis to visualize the optimum number of clusters. There is a way to understand how well the model has performed. It is done by checking two metrics, namely Silhouette Width and Silhouette Score. This helps us to analyse whether each and every observation mapped to the clusters is correct or not based on distance criteria. Silhoutte Width is calculated as where b is the distance between the observation and the neighboring cluster’s centroid and a is the distance between the observation and the very own cluster’s centroid. The Silhouette Width can have a value in the range of -1 to 1. If the value of Silhoutte Width is positive, then the mapping of the observation to the current cluster is correct. When a > b, Silhouette Width will return a negative value. The average of all the Silhouette Width is called the Silhouette Score. If the final score is a positive value and it is close to +1, the clusters are well separated on an average. If it is close to 0, it is not separated well enough. If it is negative value, the model has done a blunder in clustering. Let’s begin by importing the necessary libraries #Import the necessary librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.cluster import KMeansfrom sklearn.metrics import silhouette_score Next, load the data set. The same data set used for Hierarchical clustering is used here. Do the necessary Exploratory Data Analysis like looking at the descriptive statistics, checking for null values, duplicate values. Perform uni-variate and bi-variate analysis, do outlier treatment(if any). K-means clustering demands scaling. It is done so that all the variables are free of any units of measurement. This enables the model to perform at its best. In this case, StandardScaler method is put to use. #Importing the standard scaler module and applying it on continuous variablesfrom sklearn.preprocessing import StandardScaler X = StandardScaler()scaled_df = X.fit_transform(df.iloc[:,1:6])scaled_df Next is to invoke the KMeans method with defining the number of clusters before hand. Then fit the scaled data set to the model. # Create K Means cluster and store the result in the object k_meansk_means = KMeans(n_clusters=2)# Fit K means on the scaled_dfk_means.fit(scaled_df)# Get the labelsk_means.labels_ Now is the time to find the optimum number of clusters by analyzing the values of Within Sum of Squares(WSS) for a given range of k. #To determine the optimum number of clusters, check the wss score for a given range of kwss =[] for i in range(1,11): KM = KMeans(n_clusters=i) KM.fit(scaled_df) wss.append(KM.inertia_) wss It is seen that there is a dip in WSS score after k=2 hence let’s keep an eye on k=3. The same can be visualized using an elbow plot #Draw the elbow plotplt.plot(range(1,11), wss, marker = '*') Another helping hand in deciding the number of clusters could be the value of Silhouette score. As discussed before, better the score, better the clustering. Let’s check the score. #Checking for n-clusters=3k_means_three = KMeans(n_clusters = 3)k_means_three.fit(scaled_df)print('WSS for K=3:', k_means_three.inertia_)labels_three = k_means_three.labels_print(labels_three)#Calculating silhouette_score for k=3print(silhouette_score(scaled_df, labels_three)) The WSS for k=3 is 261.67 and the Silhouette score for those labels is 0.3054. Since the score is positive, it is a sign that good clustering has happened. The final step is to do cluster profiling to understand how the cluster has happened and gain more insights. clust_profile=df.iloc[:,1:8].groupby('KMCluster').mean()clust_profile['KMFrequency']=df.KMCluster.value_counts().sort_index()clust_profile Just like Hierarchical clustering, these three clusters indicate three levels of foods with different calorie and macro nutrients range. Data set source: https://www.kaggle.com/starbucks/starbucks-menu?select=starbucks-menu-nutrition-food.csv To view the jupyter notebook files, click here
[ { "code": null, "e": 421, "s": 172, "text": "Clustering falls under the unsupervised learning technique. In this technique, the data is not labelled and there is no defined dependant variable. This type of learning is usually done to identify patterns in the data and/or to group similar data." }, { "code": null, "e": 532, "s": 421, "text": "In this post, a detailed explanation on the type of clustering techniques and a code walk-through is provided." }, { "code": null, "e": 1072, "s": 532, "text": "Clustering is a method of grouping of similar objects. The objective of clustering is to create homogeneous groups out of heterogeneous observations. The assumption is that the data comes from multiple population, for example, there could be people from different walks of life requesting loan from a bank for different purposes. If the person is a student, he/she could ask for an education loan, someone who is looking to buy a house can ask for home loan and so on. Clustering helps to identify similar group and cater the needs better." }, { "code": null, "e": 1223, "s": 1072, "text": "Clustering is a distance-based algorithm. The purpose of clustering is to minimize the intra-cluster distance and maximize the inter-cluster distance." }, { "code": null, "e": 1609, "s": 1223, "text": "Clustering as a tool can be used to gain insight into the data. Huge amount of information can be obtained by visualizing the data. The output of the clustering can also be used as a pre-processing step for other algorithms. There are several use cases of this technique that is used widely — some of the important ones are market segmentation, customer segmentation, image processing." }, { "code": null, "e": 1678, "s": 1609, "text": "Before proceeding further, let us understand the core of clustering." }, { "code": null, "e": 1890, "s": 1678, "text": "Clustering is all about distance between two points and distance between two clusters. Distance cannot be negative. There are a few common measures of distance that the algorithm uses for the clustering problem." }, { "code": null, "e": 1909, "s": 1890, "text": "EUCLIDEAN DISTANCE" }, { "code": null, "e": 2108, "s": 1909, "text": "It is a default distance used by the algorithm. It is best explained as the distance between two points. If the distance between two points p and q are to be measured, then the Euclidean distance is" }, { "code": null, "e": 2127, "s": 2108, "text": "MANHATTAN DISTANCE" }, { "code": null, "e": 2360, "s": 2127, "text": "It is the distance between two points calculated on a perpendicular angle along the axes. It is also called taxicab distance as this represents how vehicles in the city of Manhattan drive where the streets intersect at right angles." }, { "code": null, "e": 2379, "s": 2360, "text": "MINKOWSKI DISTANCE" }, { "code": null, "e": 2468, "s": 2379, "text": "In an n-dimensional space, the distance between two points is called Minkowski distance." }, { "code": null, "e": 2649, "s": 2468, "text": "It is a generalization of the Euclidean and Manhattan distance that if the value of p is 2, it becomes Euclidean distance and if the value of p is 1, it becomes Manhattan distance." }, { "code": null, "e": 2700, "s": 2649, "text": "There are two major types of clustering techniques" }, { "code": null, "e": 2737, "s": 2700, "text": "Hierarchical or Agglomerativek-means" }, { "code": null, "e": 2767, "s": 2737, "text": "Hierarchical or Agglomerative" }, { "code": null, "e": 2775, "s": 2767, "text": "k-means" }, { "code": null, "e": 2829, "s": 2775, "text": "Let us look at each type along with code walk-through" }, { "code": null, "e": 3051, "s": 2829, "text": "It is a bottom-up approach. Records in the data set are grouped sequentially to form clusters based on distance between the records and also the distance between the clusters. Here is a step-wise approach to this method -" }, { "code": null, "e": 3367, "s": 3051, "text": "Start with n clusters where each row is considered as a clusterUsing distance based approach, two records that are closest to each other are merged into a cluster. In Fig 3, for the given five records, assuming A and C are closest in distance, they form a cluster and likewise B and E form another cluster and so on" }, { "code": null, "e": 3431, "s": 3367, "text": "Start with n clusters where each row is considered as a cluster" }, { "code": null, "e": 3684, "s": 3431, "text": "Using distance based approach, two records that are closest to each other are merged into a cluster. In Fig 3, for the given five records, assuming A and C are closest in distance, they form a cluster and likewise B and E form another cluster and so on" }, { "code": null, "e": 4146, "s": 3684, "text": "3. At every step, two closest clusters will be merged. Either a single record(singleton) is added to the existing cluster or two clusters are combined. After at least one multiple-element cluster is formed, a scenario where the distance needs to be computed for a singleton and a set of observations and that is where the concept of linkages comes into picture. There are five major types of linkages. By using one of the below concepts, the clustering happens-" }, { "code": null, "e": 4234, "s": 4146, "text": "Single linkage: It is the shortest distance between any two points in both the clusters" }, { "code": null, "e": 4361, "s": 4234, "text": "Complete linkage: It is the opposite of single linkage. It is the longest distance between any two points in both the clusters" }, { "code": null, "e": 4475, "s": 4361, "text": "Average linkage: It is the average distance between each point in one cluster to every point in the other cluster" }, { "code": null, "e": 4587, "s": 4475, "text": "Centroid linkage: The distance between the center point in one cluster to the center point in the other cluster" }, { "code": null, "e": 4958, "s": 4587, "text": "Ward’s linkage: A combination of average and centroid methods. The within cluster variance is calculated by determining the center point of the cluster and the distance of the observations from the center. While trying to merge two clusters, the variance is found between the clusters and the clusters are merged whose variance is less compared to the other combination." }, { "code": null, "e": 5123, "s": 4958, "text": "A point to note is that each linkage method produces an unique result. When each of these methods are applied on the same data set, it may be clustered differently." }, { "code": null, "e": 5196, "s": 5123, "text": "4. Repeat the steps until there is a single cluster with all the records" }, { "code": null, "e": 5557, "s": 5196, "text": "To visualize the clustering, there is a concept called dendrogram. The dendrogram is a tree diagram summarizing the clustering process. The records are on the x-axis. Similar records are joined by lines whose vertical length reflects the distance between the records. The greater the difference in height, more the dissimilarity. A sample dendrogram is shown -" }, { "code": null, "e": 5692, "s": 5557, "text": "The code for hierarchical clustering is written in Python 3x using jupyter notebook. Let’s begin by importing the necessary libraries." }, { "code": null, "e": 5896, "s": 5692, "text": "#Import the necessary librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinefrom scipy.cluster.hierarchy import linkage, dendrogram, fcluster" }, { "code": null, "e": 5977, "s": 5896, "text": "Next, load the data set. Here, a data set on the food menu of Starbucks is used." }, { "code": null, "e": 6066, "s": 5977, "text": "#Read the datasetdf = pd.read_csv('starbucks_menu.csv')#Look at the top 5 rows df.head()" }, { "code": null, "e": 6486, "s": 6066, "text": "Do the necessary Exploratory Data Analysis like looking at the descriptive statistics, checking for null values, duplicate values. Perform uni-variate and bi-variate analysis, do outlier treatment(if any). Since this is a distance based algorithm, it is necessary to perform normalization wherever applicable so that all the variables are free of any units of measurement. This enables the model to perform at its best." }, { "code": null, "e": 6600, "s": 6486, "text": "from scipy.stats import zscoredf.iloc[:,1:6] = df.iloc[:,1:6].apply(zscore)#Check the head after scalingdf.head()" }, { "code": null, "e": 6807, "s": 6600, "text": "Once the data is ready, let us work towards building the model. A label list needs to be assigned which is a list of unique value of categorical variable. Here, label list is created from the Food variable." }, { "code": null, "e": 6910, "s": 6807, "text": "#Before clustering, setup label list from the food variablelabelList = list(df.Food.unique())labelList" }, { "code": null, "e": 7027, "s": 6910, "text": "Next step is to form a linkage to cluster a singleton and another cluster. In this case, ward’s method is preferred." }, { "code": null, "e": 7124, "s": 7027, "text": "#Create linkage method using Ward's methodlink_method = linkage(df.iloc[:,1:6], method = 'ward')" }, { "code": null, "e": 7305, "s": 7124, "text": "Visualize the clustering with the help of a dendrogram. In this case, a truncated dendrogram by specifying the p value which displays the ante-penultimate and penultimate clusters." }, { "code": null, "e": 7461, "s": 7305, "text": "#Generate the dendrogramdend = dendrogram(link_method, labels = labelList, truncate_mode='lastp', p=10)" }, { "code": null, "e": 7754, "s": 7461, "text": "Once the dendrogram is created, it is necessary to cut the tree to determine the optimum number of clusters. It can be done in one of two ways (explained in the diagram). In this case, 3 clusters are chosen. The clusters can be attached to the data frame as a new column for gaining insights." }, { "code": null, "e": 8128, "s": 7754, "text": "#Method 1: criterion = 'maxclust' where a cut is defined based on the number of clustersclusters = fcluster(link_method, 3, criterion='maxclust') clusters#Method 2: criterion='distance' where a cut is defined based on distance in the y-axis#clusters = fcluster(link_method, 800, criterion='distance')#Apply the clusters back to the datasetdf['HCluster'] = clustersdf.head()" }, { "code": null, "e": 8366, "s": 8128, "text": "The last step is to do cluster profiling to extract information and insights from the algorithm to help with effective decision making. The cluster profiling is done by grouping the mean of the cluster and sorting based on the frequency." }, { "code": null, "e": 8483, "s": 8366, "text": "aggdata=df.iloc[:,1:8].groupby('HCluster').mean()aggdata['Frequency']=df.HCluster.value_counts().sort_index()aggdata" }, { "code": null, "e": 8920, "s": 8483, "text": "A quick insight is that the first cluster has the food items that are usually low in calories and hence the macro nutrients are on the lower side. The second cluster has the food items with the most amount of calories and hence more in macro nutrients and there is a mid range in between cluster 1 and 2 which is the third cluster that has good amount of calories and macro nutrients. Overall, on a brief, this model has clustered well." }, { "code": null, "e": 8953, "s": 8920, "text": "Let’s move on to the next method" }, { "code": null, "e": 9359, "s": 8953, "text": "K-Means is a non-hierarchical approach. The idea is to specify the number of clusters before hand. Based on the number of clusters, each record is assigned to the cluster based on the distance from each cluster. This approach is preferred when the data set is large. The word means in k-means refers to averaging of the data which is also referred to as finding the centroid. Here is a step-wise approach-" }, { "code": null, "e": 9929, "s": 9359, "text": "Specify the k value before handAssign each record to the cluster whose distance is smallest to the centroid. The K-Means by default uses Euclidean distanceRe-calculate the centroid for the newly formed clusters. There is a chance that some of the data points may move around based on the distance.Re-assignment may happen on an iterative basis and new centroid is formed. This process will stop until there is no jumping of observations from cluster to cluster.If there is any re-assignment, go back to step 3 and continue the steps. If not, the clusters are finalized." }, { "code": null, "e": 9961, "s": 9929, "text": "Specify the k value before hand" }, { "code": null, "e": 10086, "s": 9961, "text": "Assign each record to the cluster whose distance is smallest to the centroid. The K-Means by default uses Euclidean distance" }, { "code": null, "e": 10229, "s": 10086, "text": "Re-calculate the centroid for the newly formed clusters. There is a chance that some of the data points may move around based on the distance." }, { "code": null, "e": 10394, "s": 10229, "text": "Re-assignment may happen on an iterative basis and new centroid is formed. This process will stop until there is no jumping of observations from cluster to cluster." }, { "code": null, "e": 10503, "s": 10394, "text": "If there is any re-assignment, go back to step 3 and continue the steps. If not, the clusters are finalized." }, { "code": null, "e": 11149, "s": 10503, "text": "Although we have determined the number of clusters before hand, it may not be always right and it is necessary to determine the optimum number of clusters. There is no solid solution to determine the number of clusters, however, there is a common method in place. For each value of k, a Within Sum of Squares(WSS) value can be identified. A single cluster cannot be chosen so it is important to find that k value after which there is no significant difference in the WSS value. To make this more efficient, an elbow plot can be drawn with WSS scores in the y-axis and number of clusters in the x-axis to visualize the optimum number of clusters." }, { "code": null, "e": 11456, "s": 11149, "text": "There is a way to understand how well the model has performed. It is done by checking two metrics, namely Silhouette Width and Silhouette Score. This helps us to analyse whether each and every observation mapped to the clusters is correct or not based on distance criteria. Silhoutte Width is calculated as" }, { "code": null, "e": 11626, "s": 11456, "text": "where b is the distance between the observation and the neighboring cluster’s centroid and a is the distance between the observation and the very own cluster’s centroid." }, { "code": null, "e": 12168, "s": 11626, "text": "The Silhouette Width can have a value in the range of -1 to 1. If the value of Silhoutte Width is positive, then the mapping of the observation to the current cluster is correct. When a > b, Silhouette Width will return a negative value. The average of all the Silhouette Width is called the Silhouette Score. If the final score is a positive value and it is close to +1, the clusters are well separated on an average. If it is close to 0, it is not separated well enough. If it is negative value, the model has done a blunder in clustering." }, { "code": null, "e": 12217, "s": 12168, "text": "Let’s begin by importing the necessary libraries" }, { "code": null, "e": 12434, "s": 12217, "text": "#Import the necessary librariesimport numpy as npimport pandas as pdimport seaborn as snsimport matplotlib.pyplot as plt%matplotlib inlinefrom sklearn.cluster import KMeansfrom sklearn.metrics import silhouette_score" }, { "code": null, "e": 12524, "s": 12434, "text": "Next, load the data set. The same data set used for Hierarchical clustering is used here." }, { "code": null, "e": 12939, "s": 12524, "text": "Do the necessary Exploratory Data Analysis like looking at the descriptive statistics, checking for null values, duplicate values. Perform uni-variate and bi-variate analysis, do outlier treatment(if any). K-means clustering demands scaling. It is done so that all the variables are free of any units of measurement. This enables the model to perform at its best. In this case, StandardScaler method is put to use." }, { "code": null, "e": 13138, "s": 12939, "text": "#Importing the standard scaler module and applying it on continuous variablesfrom sklearn.preprocessing import StandardScaler X = StandardScaler()scaled_df = X.fit_transform(df.iloc[:,1:6])scaled_df" }, { "code": null, "e": 13267, "s": 13138, "text": "Next is to invoke the KMeans method with defining the number of clusters before hand. Then fit the scaled data set to the model." }, { "code": null, "e": 13448, "s": 13267, "text": "# Create K Means cluster and store the result in the object k_meansk_means = KMeans(n_clusters=2)# Fit K means on the scaled_dfk_means.fit(scaled_df)# Get the labelsk_means.labels_" }, { "code": null, "e": 13581, "s": 13448, "text": "Now is the time to find the optimum number of clusters by analyzing the values of Within Sum of Squares(WSS) for a given range of k." }, { "code": null, "e": 13783, "s": 13581, "text": "#To determine the optimum number of clusters, check the wss score for a given range of kwss =[] for i in range(1,11): KM = KMeans(n_clusters=i) KM.fit(scaled_df) wss.append(KM.inertia_) wss" }, { "code": null, "e": 13916, "s": 13783, "text": "It is seen that there is a dip in WSS score after k=2 hence let’s keep an eye on k=3. The same can be visualized using an elbow plot" }, { "code": null, "e": 13977, "s": 13916, "text": "#Draw the elbow plotplt.plot(range(1,11), wss, marker = '*')" }, { "code": null, "e": 14158, "s": 13977, "text": "Another helping hand in deciding the number of clusters could be the value of Silhouette score. As discussed before, better the score, better the clustering. Let’s check the score." }, { "code": null, "e": 14436, "s": 14158, "text": "#Checking for n-clusters=3k_means_three = KMeans(n_clusters = 3)k_means_three.fit(scaled_df)print('WSS for K=3:', k_means_three.inertia_)labels_three = k_means_three.labels_print(labels_three)#Calculating silhouette_score for k=3print(silhouette_score(scaled_df, labels_three))" }, { "code": null, "e": 14592, "s": 14436, "text": "The WSS for k=3 is 261.67 and the Silhouette score for those labels is 0.3054. Since the score is positive, it is a sign that good clustering has happened." }, { "code": null, "e": 14701, "s": 14592, "text": "The final step is to do cluster profiling to understand how the cluster has happened and gain more insights." }, { "code": null, "e": 14840, "s": 14701, "text": "clust_profile=df.iloc[:,1:8].groupby('KMCluster').mean()clust_profile['KMFrequency']=df.KMCluster.value_counts().sort_index()clust_profile" }, { "code": null, "e": 14977, "s": 14840, "text": "Just like Hierarchical clustering, these three clusters indicate three levels of foods with different calorie and macro nutrients range." }, { "code": null, "e": 15083, "s": 14977, "text": "Data set source: https://www.kaggle.com/starbucks/starbucks-menu?select=starbucks-menu-nutrition-food.csv" } ]
JSP - Debugging
In this chapter, we will discuss Debugging a JSP. It is always difficult testing/debugging a JSP and servlets. JSP and Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce. The following are a few hints and suggestions that may aid you in your debugging. System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Consider the following additional points − Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications. Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications. Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when the iming is crucial. Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when the iming is crucial. Following is the syntax to use System.out.println() − System.out.println("Debugging message"); Following example shows how to use System.out.print() − <%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <html> <head><title>System.out.println</title></head> <body> <c:forEach var = "counter" begin = "1" end = "10" step = "1" > <c:out value = "${counter-5}"/></br> <% System.out.println( "counter = " + pageContext.findAttribute("counter") ); %> </c:forEach> </body> </html> Access the above JSP, the browser will show the following result − -4 -3 -2 -1 0 1 2 3 4 5 If you are using Tomcat, you will also find these lines appended to the end of stdout.log in the logs directory. counter = 1 counter = 2 counter = 3 counter = 4 counter = 5 counter = 6 counter = 7 counter = 8 counter = 9 counter = 10 This way you can bring variables and other information into the system log which can be analyzed to find out the root cause of the problem or for various other reasons. The J2SE logging framework is designed to provide logging services for any class running in the JVM. We can make use of this framework to log any information. Let us re-write the above example using JDK logger API − <%@taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %> <%@page import = "java.util.logging.Logger" %> <html> <head><title>Logger.info</title></head> <body> <% Logger logger = Logger.getLogger(this.getClass().getName());%> <c:forEach var = "counter" begin = "1" end = "10" step = "1" > <c:set var = "myCount" value = "${counter-5}" /> <c:out value = "${myCount}"/></br> <% String message = "counter = " + pageContext.findAttribute("counter") + "myCount = " + pageContext.findAttribute("myCount"); logger.info( message ); %> </c:forEach> </body> </html> The above code will generate similar result on the browser and in stdout.log, but you will have additional information in stdout.log. We will use the info method of the logger because and log the message just for informational purpose. Following is a snapshot of the stdout.log file − 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 1 myCount = -4 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 2 myCount = -3 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 3 myCount = -2 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 4 myCount = -1 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 5 myCount = 0 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 6 myCount = 1 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 7 myCount = 2 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 8 myCount = 3 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 9 myCount = 4 24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService INFO: counter = 10 myCount = 5 Messages can be sent at various levels by using the convenience functions severe(), warning(), info(), config(), fine(), finer(), and finest(). Here finest() method can be used to log finest information and the severe() method can be used to log severe information. You can use Log4J Framework to log messages in different files based on their severity levels and importance. NetBeans is a free and open-source Java Integrated Development Environment that supports the development of standalone Java applications and Web applications supporting the JSP and servlet specifications and includes a JSP debugger as well. NetBeans supports the following basic debugging functionalities − Breakpoints Stepping through code Watchpoints You can refere to NetBeans documentation to understand above debugging functionalities. You can debug JSP and servlets with the same jdb commands you use to debug an applet or an application. To debug a JSP or servlet, you can debug sun.servlet.http.HttpServer, then observe as HttpServer executes the JSP/servlets in response to HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer. Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for JSP, you have to help your debugger by considering the following − Set your debugger's classpath. This helps you find sun.servlet.http.Http-Server and the associated classes. Set your debugger's classpath. This helps you find sun.servlet.http.Http-Server and the associated classes. Set your debugger's classpath. This helps you find your JSP and support classes, typically ROOT\WEB-INF\classes. Set your debugger's classpath. This helps you find your JSP and support classes, typically ROOT\WEB-INF\classes. Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever JSP you're interested in debugging, then use a web browser to make a request to the HttpServer for the given JSP (http://localhost:8080/JSPToDebug). The execution here stops at breakpoints. Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process. The JSP uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem. Sometimes when a JSP doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you're familiar with the structure of HTTP, you can read the request and response and see what exactly is going with those headers. Here is a list of some more debugging tips on JSP debugging − Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu. Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu. Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh. Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh. 108 Lectures 11 hours Chaand Sheikh 517 Lectures 57 hours Chaand Sheikh 41 Lectures 4.5 hours Karthikeya T 42 Lectures 5.5 hours TELCOMA Global 15 Lectures 3 hours TELCOMA Global 44 Lectures 15 hours Uplatz Print Add Notes Bookmark this page
[ { "code": null, "e": 2472, "s": 2239, "text": "In this chapter, we will discuss Debugging a JSP. It is always difficult testing/debugging a JSP and servlets. JSP and Servlets tend to involve a large amount of client/server interaction, making errors likely but hard to reproduce." }, { "code": null, "e": 2554, "s": 2472, "text": "The following are a few hints and suggestions that may aid you in your debugging." }, { "code": null, "e": 2753, "s": 2554, "text": "System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We can print out variable values as well. Consider the following additional points −" }, { "code": null, "e": 2982, "s": 2753, "text": "Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications." }, { "code": null, "e": 3211, "s": 2982, "text": "Since the System object is part of the core Java objects, it can be used everywhere without the need to install any extra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications." }, { "code": null, "e": 3400, "s": 3211, "text": "Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when the iming is crucial." }, { "code": null, "e": 3589, "s": 3400, "text": "Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal execution flow of the application, which makes it very valuable when the iming is crucial." }, { "code": null, "e": 3643, "s": 3589, "text": "Following is the syntax to use System.out.println() −" }, { "code": null, "e": 3685, "s": 3643, "text": "System.out.println(\"Debugging message\");\n" }, { "code": null, "e": 3741, "s": 3685, "text": "Following example shows how to use System.out.print() −" }, { "code": null, "e": 4134, "s": 3741, "text": "<%@taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n\n<html>\n <head><title>System.out.println</title></head>\n <body>\n <c:forEach var = \"counter\" begin = \"1\" end = \"10\" step = \"1\" >\n \n <c:out value = \"${counter-5}\"/></br>\n <% System.out.println( \"counter = \" + pageContext.findAttribute(\"counter\") ); %>\n </c:forEach>\n \n </body>\n</html>" }, { "code": null, "e": 4201, "s": 4134, "text": "Access the above JSP, the browser will show the following result −" }, { "code": null, "e": 4226, "s": 4201, "text": "-4\n-3\n-2\n-1\n0\n1\n2\n3\n4\n5\n" }, { "code": null, "e": 4339, "s": 4226, "text": "If you are using Tomcat, you will also find these lines appended to the end of stdout.log in the logs directory." }, { "code": null, "e": 4461, "s": 4339, "text": "counter = 1\ncounter = 2\ncounter = 3\ncounter = 4\ncounter = 5\ncounter = 6\ncounter = 7\ncounter = 8\ncounter = 9\ncounter = 10\n" }, { "code": null, "e": 4630, "s": 4461, "text": "This way you can bring variables and other information into the system log which can be analyzed to find out the root cause of the problem or for various other reasons." }, { "code": null, "e": 4789, "s": 4630, "text": "The J2SE logging framework is designed to provide logging services for any class running in the JVM. We can make use of this framework to log any information." }, { "code": null, "e": 4846, "s": 4789, "text": "Let us re-write the above example using JDK logger API −" }, { "code": null, "e": 5517, "s": 4846, "text": "<%@taglib prefix = \"c\" uri = \"http://java.sun.com/jsp/jstl/core\" %>\n<%@page import = \"java.util.logging.Logger\" %>\n\n<html>\n <head><title>Logger.info</title></head>\n \n <body>\n <% Logger logger = Logger.getLogger(this.getClass().getName());%>\n\n <c:forEach var = \"counter\" begin = \"1\" end = \"10\" step = \"1\" >\n <c:set var = \"myCount\" value = \"${counter-5}\" />\n <c:out value = \"${myCount}\"/></br>\n <% String message = \"counter = \"\n + pageContext.findAttribute(\"counter\") + \"myCount = \"\n + pageContext.findAttribute(\"myCount\");\n logger.info( message );\n %>\n </c:forEach>\n \n </body>\n</html>" }, { "code": null, "e": 5802, "s": 5517, "text": "The above code will generate similar result on the browser and in stdout.log, but you will have additional information in stdout.log. We will use the info method of the logger because and log the message just for informational purpose. Following is a snapshot of the stdout.log file −" }, { "code": null, "e": 6678, "s": 5802, "text": "24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 1 myCount = -4\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 2 myCount = -3\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 3 myCount = -2\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 4 myCount = -1\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 5 myCount = 0\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 6 myCount = 1\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 7 myCount = 2\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 8 myCount = 3\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 9 myCount = 4\n24-Sep-2010 23:31:31 org.apache.jsp.main_jsp _jspService\nINFO: counter = 10 myCount = 5\n" }, { "code": null, "e": 6944, "s": 6678, "text": "Messages can be sent at various levels by using the convenience functions severe(), warning(), info(), config(), fine(), finer(), and finest(). Here finest() method can be used to log finest information and the severe() method can be used to log severe information." }, { "code": null, "e": 7054, "s": 6944, "text": "You can use Log4J Framework to log messages in different files based on their severity levels and importance." }, { "code": null, "e": 7295, "s": 7054, "text": "NetBeans is a free and open-source Java Integrated Development Environment that supports the development of standalone Java applications and Web applications supporting the JSP and servlet specifications and includes a JSP debugger as well." }, { "code": null, "e": 7361, "s": 7295, "text": "NetBeans supports the following basic debugging functionalities −" }, { "code": null, "e": 7373, "s": 7361, "text": "Breakpoints" }, { "code": null, "e": 7395, "s": 7373, "text": "Stepping through code" }, { "code": null, "e": 7407, "s": 7395, "text": "Watchpoints" }, { "code": null, "e": 7495, "s": 7407, "text": "You can refere to NetBeans documentation to understand above debugging functionalities." }, { "code": null, "e": 7599, "s": 7495, "text": "You can debug JSP and servlets with the same jdb commands you use to debug an applet or an application." }, { "code": null, "e": 7924, "s": 7599, "text": "To debug a JSP or servlet, you can debug sun.servlet.http.HttpServer, then observe as HttpServer executes the JSP/servlets in response to HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that with applets, the actual program being debugged is sun.applet.AppletViewer." }, { "code": null, "e": 8097, "s": 7924, "text": "Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for JSP, you have to help your debugger by considering the following −" }, { "code": null, "e": 8205, "s": 8097, "text": "Set your debugger's classpath. This helps you find sun.servlet.http.Http-Server and the associated classes." }, { "code": null, "e": 8313, "s": 8205, "text": "Set your debugger's classpath. This helps you find sun.servlet.http.Http-Server and the associated classes." }, { "code": null, "e": 8426, "s": 8313, "text": "Set your debugger's classpath. This helps you find your JSP and support classes, typically ROOT\\WEB-INF\\classes." }, { "code": null, "e": 8539, "s": 8426, "text": "Set your debugger's classpath. This helps you find your JSP and support classes, typically ROOT\\WEB-INF\\classes." }, { "code": null, "e": 8850, "s": 8539, "text": "Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever JSP you're interested in debugging, then use a web browser to make a request to the HttpServer for the given JSP (http://localhost:8080/JSPToDebug). The execution here stops at breakpoints." }, { "code": null, "e": 8989, "s": 8850, "text": "Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in the debugging process." }, { "code": null, "e": 9238, "s": 8989, "text": "The JSP uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarily remove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the problem." }, { "code": null, "e": 9480, "s": 9238, "text": "Sometimes when a JSP doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you're familiar with the structure of HTTP, you can read the request and response and see what exactly is going with those headers." }, { "code": null, "e": 9542, "s": 9480, "text": "Here is a list of some more debugging tips on JSP debugging −" }, { "code": null, "e": 9698, "s": 9542, "text": "Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu." }, { "code": null, "e": 9854, "s": 9698, "text": "Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It's usually an option under the View menu." }, { "code": null, "e": 10041, "s": 9854, "text": "Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh." }, { "code": null, "e": 10228, "s": 10041, "text": "Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. With Netscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh." }, { "code": null, "e": 10263, "s": 10228, "text": "\n 108 Lectures \n 11 hours \n" }, { "code": null, "e": 10278, "s": 10263, "text": " Chaand Sheikh" }, { "code": null, "e": 10313, "s": 10278, "text": "\n 517 Lectures \n 57 hours \n" }, { "code": null, "e": 10328, "s": 10313, "text": " Chaand Sheikh" }, { "code": null, "e": 10363, "s": 10328, "text": "\n 41 Lectures \n 4.5 hours \n" }, { "code": null, "e": 10377, "s": 10363, "text": " Karthikeya T" }, { "code": null, "e": 10412, "s": 10377, "text": "\n 42 Lectures \n 5.5 hours \n" }, { "code": null, "e": 10428, "s": 10412, "text": " TELCOMA Global" }, { "code": null, "e": 10461, "s": 10428, "text": "\n 15 Lectures \n 3 hours \n" }, { "code": null, "e": 10477, "s": 10461, "text": " TELCOMA Global" }, { "code": null, "e": 10511, "s": 10477, "text": "\n 44 Lectures \n 15 hours \n" }, { "code": null, "e": 10519, "s": 10511, "text": " Uplatz" }, { "code": null, "e": 10526, "s": 10519, "text": " Print" }, { "code": null, "e": 10537, "s": 10526, "text": " Add Notes" } ]
Maximum given sized rectangles that can be cut out of a sheet of paper - GeeksforGeeks
30 May, 2021 Given the length L and breadth B of a sheet of paper, the task is to find the maximum number of rectangles with given length l and breadth b that can be cut from this sheet of paper.Examples: Input: L = 5, B = 2, l = 14, b = 3 Output: 0 The sheet is smaller than the required rectangle. So, no rectangle of the given dimension can be cut from the sheet.Input: L = 10, B = 7, l = 4, b = 3 Output: 4 Approach: Try to cut the rectangles horizontally i.e. length of the rectangle is aligned with the length of the sheet and breadth of the rectangle is aligned with the breadth of the sheet and store the count of rectangles possible in horizontal. Repeat the same with vertical alignment i.e. when length of the rectangle is aligned with the breadth of the sheet and breadth of the rectangle is aligned with the length of the sheet and store the result in vertical. Print max(horizontal, vertical) as the result. Below is the implementation of the above approach: C++ Java Python3 C# PHP Javascript // CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the maximum rectangles possibleint maxRectangles(int L, int B, int l, int b){ int horizontal = 0, vertical = 0; // Cut rectangles horizontally if possible if (l <= L && b <= B) { // One rectangle is a single cell int columns = B / b; int rows = L / l; // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { int columns = L / b; int rows = B / l; vertical = rows * columns; } // Return the maximum possible rectangles return max(horizontal, vertical);} // Driver codeint main(){ int L = 10, B = 7, l = 4, b = 3; cout << (maxRectangles(L, B, l, b)) << endl;} // This code is contributed by// Sanjit_Prasad // Java implementation of the approachclass GFG { // Function to return the maximum rectangles possible static int maxRectangles(int L, int B, int l, int b) { int horizontal = 0, vertical = 0; // Cut rectangles horizontally if possible if (l <= L && b <= B) { // One rectangle is a single cell int columns = B / b; int rows = L / l; // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { int columns = L / b; int rows = B / l; vertical = rows * columns; } // Return the maximum possible rectangles return Math.max(horizontal, vertical); } // Driver code public static void main(String[] args) { int L = 10, B = 7, l = 4, b = 3; System.out.print(maxRectangles(L, B, l, b)); }} # Python3 implementation of the approach # Function to return the maximum# rectangles possibledef maxRectangles(L, B, l, b): horizontal, vertical = 0, 0 # Cut rectangles horizontally if possible if l <= L and b <= B: # One rectangle is a single cell columns = B // b rows = L // l # Total rectangles = total cells horizontal = rows * columns # Cut rectangles vertically if possible if l <= B and b <= L: columns = L // b rows = B // l vertical = rows * columns # Return the maximum possible rectangles return max(horizontal, vertical) # Driver codeif __name__ == "__main__": L, B, l, b = 10, 7, 4, 3 print(maxRectangles(L, B, l, b)) # This code is contributed by Rituraj Jain // C# implementation of the above approachusing System; class GFG{ // Function to return the // maximum rectangles possible static int maxRectangles(int L, int B, int l, int b) { int horizontal = 0, vertical = 0; // Cut rectangles horizontally if possible if (l <= L && b <= B) { // One rectangle is a single cell int columns = B / b; int rows = L / l; // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { int columns = L / b; int rows = B / l; vertical = rows * columns; } // Return the maximum possible rectangles return Math.Max(horizontal, vertical); } // Driver code public static void Main() { int L = 10, B = 7, l = 4, b = 3; Console.WriteLine(maxRectangles(L, B, l, b)); }} // This code is contributed by Ryuga <?php// PHP implementation of the approach // Function to return the maximum// rectangles possiblefunction maxRectangles($L, $B, $l, $b){ $horizontal = 0; $vertical = 0; // Cut rectangles horizontally if possible if ($l <= $L && $b <= $B) { // One rectangle is a single cell $columns = (int)($B / $b); $rows = (int)($L / $l); // Total rectangles = total cells $horizontal = $rows * $columns; } // Cut rectangles vertically if possible if ($l <= $B && $b <= $L) { $columns = (int)($L / $b); $rows = (int)($B / $l); $vertical = $rows * $columns; } // Return the maximum possible rectangles return max($horizontal, $vertical);} // Driver code$L = 10;$B = 7;$l = 4;$b = 3;print(maxRectangles($L, $B, $l, $b)); // This code is contributed by mits?> <script> // Javascript implementation of the approach // Function to return the maximum// rectangles possiblefunction maxRectangles(L, B, l, b){ var horizontal = 0, vertical = 0; // Cut rectangles horizontally // if possible if (l <= L && b <= B) { // One rectangle is a single cell var columns = parseInt(B / b); var rows = parseInt(L / l); // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { var columns = parseInt(L / b); var rows = parseInt(B / l); vertical = rows * columns; } // Return the maximum possible rectangles return Math.max(horizontal, vertical);} // Driver Codevar L = 10, B = 7, l = 4, b = 3; document.write(maxRectangles(L, B, l, b)); // This code is contributed by kirti </script> 4 Time Complexity: O(1)Auxiliary Space: O(1) ankthon Sanjit_Prasad Mithun Kumar rituraj_jain Kirti_Mangal ujjwalgoel1103 maths-cube square-rectangle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Convex Hull using Divide and Conquer Algorithm Maximum number of region in which N non-parallel lines can divide a plane Equation of circle when three points on the circle are given Program to find line passing through 2 Points Orientation of 3 ordered points Program for Fibonacci numbers C++ Data Types Write a program to print all permutations of a given string Set in C++ Standard Template Library (STL) Coin Change | DP-7
[ { "code": null, "e": 24963, "s": 24935, "text": "\n30 May, 2021" }, { "code": null, "e": 25157, "s": 24963, "text": "Given the length L and breadth B of a sheet of paper, the task is to find the maximum number of rectangles with given length l and breadth b that can be cut from this sheet of paper.Examples: " }, { "code": null, "e": 25365, "s": 25157, "text": "Input: L = 5, B = 2, l = 14, b = 3 Output: 0 The sheet is smaller than the required rectangle. So, no rectangle of the given dimension can be cut from the sheet.Input: L = 10, B = 7, l = 4, b = 3 Output: 4 " }, { "code": null, "e": 25379, "s": 25367, "text": "Approach: " }, { "code": null, "e": 25615, "s": 25379, "text": "Try to cut the rectangles horizontally i.e. length of the rectangle is aligned with the length of the sheet and breadth of the rectangle is aligned with the breadth of the sheet and store the count of rectangles possible in horizontal." }, { "code": null, "e": 25880, "s": 25615, "text": "Repeat the same with vertical alignment i.e. when length of the rectangle is aligned with the breadth of the sheet and breadth of the rectangle is aligned with the length of the sheet and store the result in vertical. Print max(horizontal, vertical) as the result." }, { "code": null, "e": 25933, "s": 25880, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 25937, "s": 25933, "text": "C++" }, { "code": null, "e": 25942, "s": 25937, "text": "Java" }, { "code": null, "e": 25950, "s": 25942, "text": "Python3" }, { "code": null, "e": 25953, "s": 25950, "text": "C#" }, { "code": null, "e": 25957, "s": 25953, "text": "PHP" }, { "code": null, "e": 25968, "s": 25957, "text": "Javascript" }, { "code": "// CPP implementation of the approach#include<bits/stdc++.h>using namespace std; // Function to return the maximum rectangles possibleint maxRectangles(int L, int B, int l, int b){ int horizontal = 0, vertical = 0; // Cut rectangles horizontally if possible if (l <= L && b <= B) { // One rectangle is a single cell int columns = B / b; int rows = L / l; // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { int columns = L / b; int rows = B / l; vertical = rows * columns; } // Return the maximum possible rectangles return max(horizontal, vertical);} // Driver codeint main(){ int L = 10, B = 7, l = 4, b = 3; cout << (maxRectangles(L, B, l, b)) << endl;} // This code is contributed by// Sanjit_Prasad", "e": 26851, "s": 25968, "text": null }, { "code": "// Java implementation of the approachclass GFG { // Function to return the maximum rectangles possible static int maxRectangles(int L, int B, int l, int b) { int horizontal = 0, vertical = 0; // Cut rectangles horizontally if possible if (l <= L && b <= B) { // One rectangle is a single cell int columns = B / b; int rows = L / l; // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { int columns = L / b; int rows = B / l; vertical = rows * columns; } // Return the maximum possible rectangles return Math.max(horizontal, vertical); } // Driver code public static void main(String[] args) { int L = 10, B = 7, l = 4, b = 3; System.out.print(maxRectangles(L, B, l, b)); }}", "e": 27799, "s": 26851, "text": null }, { "code": "# Python3 implementation of the approach # Function to return the maximum# rectangles possibledef maxRectangles(L, B, l, b): horizontal, vertical = 0, 0 # Cut rectangles horizontally if possible if l <= L and b <= B: # One rectangle is a single cell columns = B // b rows = L // l # Total rectangles = total cells horizontal = rows * columns # Cut rectangles vertically if possible if l <= B and b <= L: columns = L // b rows = B // l vertical = rows * columns # Return the maximum possible rectangles return max(horizontal, vertical) # Driver codeif __name__ == \"__main__\": L, B, l, b = 10, 7, 4, 3 print(maxRectangles(L, B, l, b)) # This code is contributed by Rituraj Jain", "e": 28571, "s": 27799, "text": null }, { "code": "// C# implementation of the above approachusing System; class GFG{ // Function to return the // maximum rectangles possible static int maxRectangles(int L, int B, int l, int b) { int horizontal = 0, vertical = 0; // Cut rectangles horizontally if possible if (l <= L && b <= B) { // One rectangle is a single cell int columns = B / b; int rows = L / l; // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { int columns = L / b; int rows = B / l; vertical = rows * columns; } // Return the maximum possible rectangles return Math.Max(horizontal, vertical); } // Driver code public static void Main() { int L = 10, B = 7, l = 4, b = 3; Console.WriteLine(maxRectangles(L, B, l, b)); }} // This code is contributed by Ryuga", "e": 29611, "s": 28571, "text": null }, { "code": "<?php// PHP implementation of the approach // Function to return the maximum// rectangles possiblefunction maxRectangles($L, $B, $l, $b){ $horizontal = 0; $vertical = 0; // Cut rectangles horizontally if possible if ($l <= $L && $b <= $B) { // One rectangle is a single cell $columns = (int)($B / $b); $rows = (int)($L / $l); // Total rectangles = total cells $horizontal = $rows * $columns; } // Cut rectangles vertically if possible if ($l <= $B && $b <= $L) { $columns = (int)($L / $b); $rows = (int)($B / $l); $vertical = $rows * $columns; } // Return the maximum possible rectangles return max($horizontal, $vertical);} // Driver code$L = 10;$B = 7;$l = 4;$b = 3;print(maxRectangles($L, $B, $l, $b)); // This code is contributed by mits?>", "e": 30453, "s": 29611, "text": null }, { "code": "<script> // Javascript implementation of the approach // Function to return the maximum// rectangles possiblefunction maxRectangles(L, B, l, b){ var horizontal = 0, vertical = 0; // Cut rectangles horizontally // if possible if (l <= L && b <= B) { // One rectangle is a single cell var columns = parseInt(B / b); var rows = parseInt(L / l); // Total rectangles = total cells horizontal = rows * columns; } // Cut rectangles vertically if possible if (l <= B && b <= L) { var columns = parseInt(L / b); var rows = parseInt(B / l); vertical = rows * columns; } // Return the maximum possible rectangles return Math.max(horizontal, vertical);} // Driver Codevar L = 10, B = 7, l = 4, b = 3; document.write(maxRectangles(L, B, l, b)); // This code is contributed by kirti </script>", "e": 31338, "s": 30453, "text": null }, { "code": null, "e": 31340, "s": 31338, "text": "4" }, { "code": null, "e": 31385, "s": 31342, "text": "Time Complexity: O(1)Auxiliary Space: O(1)" }, { "code": null, "e": 31393, "s": 31385, "text": "ankthon" }, { "code": null, "e": 31407, "s": 31393, "text": "Sanjit_Prasad" }, { "code": null, "e": 31420, "s": 31407, "text": "Mithun Kumar" }, { "code": null, "e": 31433, "s": 31420, "text": "rituraj_jain" }, { "code": null, "e": 31446, "s": 31433, "text": "Kirti_Mangal" }, { "code": null, "e": 31461, "s": 31446, "text": "ujjwalgoel1103" }, { "code": null, "e": 31472, "s": 31461, "text": "maths-cube" }, { "code": null, "e": 31489, "s": 31472, "text": "square-rectangle" }, { "code": null, "e": 31499, "s": 31489, "text": "Geometric" }, { "code": null, "e": 31512, "s": 31499, "text": "Mathematical" }, { "code": null, "e": 31525, "s": 31512, "text": "Mathematical" }, { "code": null, "e": 31535, "s": 31525, "text": "Geometric" }, { "code": null, "e": 31633, "s": 31535, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31642, "s": 31633, "text": "Comments" }, { "code": null, "e": 31655, "s": 31642, "text": "Old Comments" }, { "code": null, "e": 31702, "s": 31655, "text": "Convex Hull using Divide and Conquer Algorithm" }, { "code": null, "e": 31776, "s": 31702, "text": "Maximum number of region in which N non-parallel lines can divide a plane" }, { "code": null, "e": 31837, "s": 31776, "text": "Equation of circle when three points on the circle are given" }, { "code": null, "e": 31883, "s": 31837, "text": "Program to find line passing through 2 Points" }, { "code": null, "e": 31915, "s": 31883, "text": "Orientation of 3 ordered points" }, { "code": null, "e": 31945, "s": 31915, "text": "Program for Fibonacci numbers" }, { "code": null, "e": 31960, "s": 31945, "text": "C++ Data Types" }, { "code": null, "e": 32020, "s": 31960, "text": "Write a program to print all permutations of a given string" }, { "code": null, "e": 32063, "s": 32020, "text": "Set in C++ Standard Template Library (STL)" } ]
C# | List.TrimExcess Method - GeeksforGeeks
01 Feb, 2019 List<T>.TrimExcess Method is used to set the capacity to the actual number of elements in the List<T>, if that number is less than a threshold value. Syntax: public void TrimExcess (); Note: This method can be used to minimize a collection’s memory overhead if no new elements will be added to the collection. To reset a List<T> to its initial state, call the Clear method before calling TrimExcess method. Trimming an empty List<T> sets the capacity of the List<T> to the default capacity. The cost of reallocating and copying a large List<T> can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity. This avoids incurring a large reallocation cost for a relatively small gain. This method is an O(n) operation, where n is Count. Below programs illustrate the use of List<T>.TrimExcess Method: Example 1: // C# code to set the capacity to the// actual number of elements in the Listusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of strings List<string> mylist = new List<string>(); // Inserting elements into List mylist.Add("1"); mylist.Add("2"); mylist.Add("3"); mylist.Add("4"); mylist.Add("5"); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using TrimExcess method mylist.TrimExcess(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); }} Output: 8 5 5 5 Example 2: // C# code to set the capacity to the// actual number of elements in the Listusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of integers List<int> mylist = new List<int>(); // Inserting elements into List mylist.Add(45); mylist.Add(78); mylist.Add(32); mylist.Add(231); mylist.Add(123); mylist.Add(76); mylist.Add(726); mylist.Add(716); mylist.Add(876); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using TrimExcess method mylist.TrimExcess(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using clear method mylist.Clear(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); }} Output: 16 9 9 9 9 0 Reference: https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.trimexcess?view=netframework-4.7.2 CSharp-Generic-List CSharp-Generic-Namespace CSharp-method C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Extension Method in C# HashSet in C# with Examples C# | Inheritance Partial Classes in C# C# | Generics - Introduction Top 50 C# Interview Questions & Answers Switch Statement in C# C# | How to insert an element in an Array? Convert String to Character Array in C# Lambda Expressions in C#
[ { "code": null, "e": 25547, "s": 25519, "text": "\n01 Feb, 2019" }, { "code": null, "e": 25697, "s": 25547, "text": "List<T>.TrimExcess Method is used to set the capacity to the actual number of elements in the List<T>, if that number is less than a threshold value." }, { "code": null, "e": 25705, "s": 25697, "text": "Syntax:" }, { "code": null, "e": 25732, "s": 25705, "text": "public void TrimExcess ();" }, { "code": null, "e": 25738, "s": 25732, "text": "Note:" }, { "code": null, "e": 25857, "s": 25738, "text": "This method can be used to minimize a collection’s memory overhead if no new elements will be added to the collection." }, { "code": null, "e": 25954, "s": 25857, "text": "To reset a List<T> to its initial state, call the Clear method before calling TrimExcess method." }, { "code": null, "e": 26038, "s": 25954, "text": "Trimming an empty List<T> sets the capacity of the List<T> to the default capacity." }, { "code": null, "e": 26288, "s": 26038, "text": "The cost of reallocating and copying a large List<T> can be considerable, however, so the TrimExcess method does nothing if the list is at more than 90 percent of capacity. This avoids incurring a large reallocation cost for a relatively small gain." }, { "code": null, "e": 26340, "s": 26288, "text": "This method is an O(n) operation, where n is Count." }, { "code": null, "e": 26404, "s": 26340, "text": "Below programs illustrate the use of List<T>.TrimExcess Method:" }, { "code": null, "e": 26415, "s": 26404, "text": "Example 1:" }, { "code": "// C# code to set the capacity to the// actual number of elements in the Listusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of strings List<string> mylist = new List<string>(); // Inserting elements into List mylist.Add(\"1\"); mylist.Add(\"2\"); mylist.Add(\"3\"); mylist.Add(\"4\"); mylist.Add(\"5\"); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using TrimExcess method mylist.TrimExcess(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); }}", "e": 27281, "s": 26415, "text": null }, { "code": null, "e": 27289, "s": 27281, "text": "Output:" }, { "code": null, "e": 27298, "s": 27289, "text": "8\n5\n5\n5\n" }, { "code": null, "e": 27309, "s": 27298, "text": "Example 2:" }, { "code": "// C# code to set the capacity to the// actual number of elements in the Listusing System;using System.Collections.Generic; class GFG { // Driver code public static void Main() { // Creating a List of integers List<int> mylist = new List<int>(); // Inserting elements into List mylist.Add(45); mylist.Add(78); mylist.Add(32); mylist.Add(231); mylist.Add(123); mylist.Add(76); mylist.Add(726); mylist.Add(716); mylist.Add(876); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using TrimExcess method mylist.TrimExcess(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); // using clear method mylist.Clear(); // To display the capacity of list Console.WriteLine(mylist.Capacity); // To display number of elements in List Console.WriteLine(mylist.Count); }}", "e": 28494, "s": 27309, "text": null }, { "code": null, "e": 28502, "s": 28494, "text": "Output:" }, { "code": null, "e": 28516, "s": 28502, "text": "16\n9\n9\n9\n9\n0\n" }, { "code": null, "e": 28527, "s": 28516, "text": "Reference:" }, { "code": null, "e": 28640, "s": 28527, "text": "https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.trimexcess?view=netframework-4.7.2" }, { "code": null, "e": 28660, "s": 28640, "text": "CSharp-Generic-List" }, { "code": null, "e": 28685, "s": 28660, "text": "CSharp-Generic-Namespace" }, { "code": null, "e": 28699, "s": 28685, "text": "CSharp-method" }, { "code": null, "e": 28702, "s": 28699, "text": "C#" }, { "code": null, "e": 28800, "s": 28702, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 28823, "s": 28800, "text": "Extension Method in C#" }, { "code": null, "e": 28851, "s": 28823, "text": "HashSet in C# with Examples" }, { "code": null, "e": 28868, "s": 28851, "text": "C# | Inheritance" }, { "code": null, "e": 28890, "s": 28868, "text": "Partial Classes in C#" }, { "code": null, "e": 28919, "s": 28890, "text": "C# | Generics - Introduction" }, { "code": null, "e": 28959, "s": 28919, "text": "Top 50 C# Interview Questions & Answers" }, { "code": null, "e": 28982, "s": 28959, "text": "Switch Statement in C#" }, { "code": null, "e": 29025, "s": 28982, "text": "C# | How to insert an element in an Array?" }, { "code": null, "e": 29065, "s": 29025, "text": "Convert String to Character Array in C#" } ]
JavaScript | Top 10 Tips and Tricks - GeeksforGeeks
08 Sep, 2021 For web development or cross-platform development, JavaScript is gaining wide popularity. Once it was considered only as a front-end scripting language but it’s now getting popularity as the back-end too. Even Facebook’s React Native is based on JavaScript. Hence it would surely be beneficial to know some tricks in JavaScript which will not only prevent us from writing extra lines of code but will also make our code crisp and efficient.1. Faster array indexing: Consider an array [10, 9, 8, 7, 6], if we want to assign a value of this array to any variable, our go-to method would be const a = array[0]. If we would like to assign multiple variables, it would be tedious to keep on doing so. Code 1: Old school way. html <script> var array1 = [10, 9, 8, 7, 6]; var x = array1[0]; var y = array1[1]; var z = array1[2]; document.write("x = " + x + "<br>"); document.write("y = " + y + "<br>"); document.write("z = " + z + "<br>");</script> Output: x = 10 y = 9 z = 8 Code 2: A smarter way. html <script> var array2 = [10, 9, 8, 7, 6]; var [x, y, z, ...rest] = array2; document.write("x = " + x + "<br>"); document.write("y = " + y + "<br>"); document.write("z = " + z + "<br>"); document.write("rest = " + rest + "<br>");</script> Output: x = 10 y = 9 z = 8 rest = 7, 6 2. Defining functions: The idea is to put some commonly or repeatedly task together and make a function so that instead of writing the same code again and again for different inputs, we can call that function. Everyone must have used functions like this in JavaScript. Code 1: Defining function in normal form. html <!DOCTYPE html><html> <body> <p>Usual function in JavaScript</p> <p id="demo"></p> <script> function myFunction(p1, p2) { return p1 * p2; } document.getElementById("demo").innerHTML = myFunction(4, 3); </script></body> </html> Output: Usual function in JavaScript 12 Code 2: There is another way in which functions are treated as variables instead not a very useful trick but still something new. Holding function in a variable, it makes use of arrow functions like this. javascript <!DOCTYPE html><html> <body> <p> Function treated as variable in JavaScript: </p> <p id="demo"></p> <script> var myFunction = (p1, p2) => { return p1 * p2; } document.getElementById("demo") .innerHTML = myFunction(4, 3); </script></body> </html> Output: Function treated as variable in JavaScript 12 3. Defining functions in a single line: Now this trick is really cool. If you know Python, you probably know the lambda function which behaves as an arbitrary function and is written in a single line. Well, we don’t use lambda function in JavaScript, but we can still write one-liner functions. Say we would like to calculate the product of two numbers a and b, we can do it in a one-line script. We need not to specifically write the return statement as this way of defining already means that it will return the output on its own. Code: javascript <!DOCTYPE html><html> <body> <p> Function treated as variable in JavaScript </p> <p id="demo"></p> <script> const productNum = (a, b) => a * b document.getElementById("demo") .innerHTML = myFunction(4, 3); </script></body> </html> Output: Function treated as variable in JavaScript 12 4. Boolean: While every programming language, there are only two Boolean value True and False. JavaScript takes it a bit further by introducing a feature enabling the user to create bools. Unlike True and False, these are commonly referred as “Truthy” and “Falsy” respectively. To avoid confusion, all the values except 0, False, NaN, null, “” are defaulted as Truthy. This extended use of bools help us in checking a condition efficiently. Code: javascript <script> const a = !1; const b = !!!0; console.log(a); console.log(b);</script> Output: False True 5. Filtering Boolean: Sometimes we may want to filter out all the bools, say the “Falsy” bools( 0, False, NaN, null, “”) from an array, this can be done by using map and filter functions in conjunction. Here, it uses the Boolean keyword to filter out Falsy values. Code: JavaScript <script>arrayToFilter .map(item => { // Item values }) .filter(Boolean);</script> Input: [1, 2, 3, 0, "Hi", False, True] Output: [1, 2, 3, "Hi", True] 6. Creating completely empty objects: If asked to create an empty object in JavaScript, our first go-to method will use in curly braces and assign it to a variable. But this is not a blank object as it still has object properties of JavaScript such as __proto__ and other methods. There is a way around this to create an object without any existent object properties. For this, we use a dictionary and assign it to a null value with its __proto__ being undefined. Code: javascript <script> /* Using .create() method to create a completely empty object */ let dict = Object.create(null); // dict.__proto__ === "undefined"</script> 7. Truncating an array: Although .splice() method is widely used to cut or remove specific portions of an array, but it has a worst-case time complexity of O(n). There exists a better alternative for removing elements from the end of an array. It uses the .length property of the array to do so. Code: javascript <script>let arrayToTruncate = [10, 5, 7, 8, 3, 4, 6, 1, 0]; /* Specifying the length till where the array should be truncated */arrayToTruncate.length = 6; console.log(arrayToTruncate)</script> Output: As seen, we must know the length of the array to be truncated in this way otherwise it will result in an error. The run time here is of O(k) where k is the number of elements that will be left in the array. [10, 5, 7, 8, 3, 4] 8. Merging objects: The introduction of spread operator(...) allows user to easily merge to or more objects which was previously achieved by creating a separate function for doing the same. Code 1: javascript <script>function mergeObjects(obj1, obj2) { for (var key in obj2) { if (obj2.hasOwnProperty(key)) obj1[key] = obj2[key]; } return obj1;}</script> Code 2: By using spread operator, the above task can be achieved easily and the code is also quite lucid. javascript <script> const obj1 = {}; // Items inside the object const obj2 = {}; // Items inside the object const obj3 = {...obj1, ...obj2};</script> Input: obj1 = { site:'GeeksforGeeks', purpose:'Education'} obj2 = { location:'Noida'} Output: obj3 = {site:'GeeksforGeeks', purpose:'Education', location:'Noida'} 9. Faster conditional checking: Checking and looping through conditions is an essential part of every programming language. In JavaScript, we do it as: Code 1: javascript <script>if (condition) { doSomething();}</script> Code 2: However, the use of bit-wise operators make it easier to check conditions and also makes the code one line: javascript <script> condition && doSomething();</script> 10. Using regex to replace all characters: Very often, one comes to a situation where every occurrence of a character or a sub-string but unfortunately, .replace() method replaces only one instance of occurrence. We can get around this by using regex with .replace() method. Code: javascript <script> var string = "GeeksforGeeks"; // Some string console.log(string.replace(/eek/, "ool"));</script> Output: "GoolsforGools" sagartomar9927 JavaScript-Misc JavaScript Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Difference between var, let and const keywords in JavaScript Difference Between PUT and PATCH Request How to get character array from string in JavaScript? Remove elements from a JavaScript Array How to filter object array based on attributes? Roadmap to Become a Web Developer in 2022 Installation of Node.js on Linux How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 25300, "s": 25272, "text": "\n08 Sep, 2021" }, { "code": null, "e": 25997, "s": 25300, "text": "For web development or cross-platform development, JavaScript is gaining wide popularity. Once it was considered only as a front-end scripting language but it’s now getting popularity as the back-end too. Even Facebook’s React Native is based on JavaScript. Hence it would surely be beneficial to know some tricks in JavaScript which will not only prevent us from writing extra lines of code but will also make our code crisp and efficient.1. Faster array indexing: Consider an array [10, 9, 8, 7, 6], if we want to assign a value of this array to any variable, our go-to method would be const a = array[0]. If we would like to assign multiple variables, it would be tedious to keep on doing so. " }, { "code": null, "e": 26023, "s": 25997, "text": "Code 1: Old school way. " }, { "code": null, "e": 26028, "s": 26023, "text": "html" }, { "code": "<script> var array1 = [10, 9, 8, 7, 6]; var x = array1[0]; var y = array1[1]; var z = array1[2]; document.write(\"x = \" + x + \"<br>\"); document.write(\"y = \" + y + \"<br>\"); document.write(\"z = \" + z + \"<br>\");</script>", "e": 26266, "s": 26028, "text": null }, { "code": null, "e": 26276, "s": 26266, "text": "Output: " }, { "code": null, "e": 26295, "s": 26276, "text": "x = 10\ny = 9\nz = 8" }, { "code": null, "e": 26320, "s": 26295, "text": "Code 2: A smarter way. " }, { "code": null, "e": 26325, "s": 26320, "text": "html" }, { "code": "<script> var array2 = [10, 9, 8, 7, 6]; var [x, y, z, ...rest] = array2; document.write(\"x = \" + x + \"<br>\"); document.write(\"y = \" + y + \"<br>\"); document.write(\"z = \" + z + \"<br>\"); document.write(\"rest = \" + rest + \"<br>\");</script>", "e": 26579, "s": 26325, "text": null }, { "code": null, "e": 26589, "s": 26579, "text": "Output: " }, { "code": null, "e": 26620, "s": 26589, "text": "x = 10\ny = 9\nz = 8\nrest = 7, 6" }, { "code": null, "e": 26890, "s": 26620, "text": "2. Defining functions: The idea is to put some commonly or repeatedly task together and make a function so that instead of writing the same code again and again for different inputs, we can call that function. Everyone must have used functions like this in JavaScript. " }, { "code": null, "e": 26934, "s": 26890, "text": "Code 1: Defining function in normal form. " }, { "code": null, "e": 26939, "s": 26934, "text": "html" }, { "code": "<!DOCTYPE html><html> <body> <p>Usual function in JavaScript</p> <p id=\"demo\"></p> <script> function myFunction(p1, p2) { return p1 * p2; } document.getElementById(\"demo\").innerHTML = myFunction(4, 3); </script></body> </html>", "e": 27229, "s": 26939, "text": null }, { "code": null, "e": 27239, "s": 27229, "text": "Output: " }, { "code": null, "e": 27271, "s": 27239, "text": "Usual function in JavaScript\n12" }, { "code": null, "e": 27477, "s": 27271, "text": "Code 2: There is another way in which functions are treated as variables instead not a very useful trick but still something new. Holding function in a variable, it makes use of arrow functions like this. " }, { "code": null, "e": 27488, "s": 27477, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p> Function treated as variable in JavaScript: </p> <p id=\"demo\"></p> <script> var myFunction = (p1, p2) => { return p1 * p2; } document.getElementById(\"demo\") .innerHTML = myFunction(4, 3); </script></body> </html>", "e": 27811, "s": 27488, "text": null }, { "code": null, "e": 27821, "s": 27811, "text": "Output: " }, { "code": null, "e": 27867, "s": 27821, "text": "Function treated as variable in JavaScript\n12" }, { "code": null, "e": 28401, "s": 27867, "text": "3. Defining functions in a single line: Now this trick is really cool. If you know Python, you probably know the lambda function which behaves as an arbitrary function and is written in a single line. Well, we don’t use lambda function in JavaScript, but we can still write one-liner functions. Say we would like to calculate the product of two numbers a and b, we can do it in a one-line script. We need not to specifically write the return statement as this way of defining already means that it will return the output on its own. " }, { "code": null, "e": 28409, "s": 28401, "text": "Code: " }, { "code": null, "e": 28420, "s": 28409, "text": "javascript" }, { "code": "<!DOCTYPE html><html> <body> <p> Function treated as variable in JavaScript </p> <p id=\"demo\"></p> <script> const productNum = (a, b) => a * b document.getElementById(\"demo\") .innerHTML = myFunction(4, 3); </script></body> </html>", "e": 28715, "s": 28420, "text": null }, { "code": null, "e": 28725, "s": 28715, "text": "Output: " }, { "code": null, "e": 28771, "s": 28725, "text": "Function treated as variable in JavaScript\n12" }, { "code": null, "e": 29214, "s": 28771, "text": "4. Boolean: While every programming language, there are only two Boolean value True and False. JavaScript takes it a bit further by introducing a feature enabling the user to create bools. Unlike True and False, these are commonly referred as “Truthy” and “Falsy” respectively. To avoid confusion, all the values except 0, False, NaN, null, “” are defaulted as Truthy. This extended use of bools help us in checking a condition efficiently. " }, { "code": null, "e": 29222, "s": 29214, "text": "Code: " }, { "code": null, "e": 29233, "s": 29222, "text": "javascript" }, { "code": "<script> const a = !1; const b = !!!0; console.log(a); console.log(b);</script>", "e": 29326, "s": 29233, "text": null }, { "code": null, "e": 29336, "s": 29326, "text": "Output: " }, { "code": null, "e": 29347, "s": 29336, "text": "False\nTrue" }, { "code": null, "e": 29613, "s": 29347, "text": "5. Filtering Boolean: Sometimes we may want to filter out all the bools, say the “Falsy” bools( 0, False, NaN, null, “”) from an array, this can be done by using map and filter functions in conjunction. Here, it uses the Boolean keyword to filter out Falsy values. " }, { "code": null, "e": 29621, "s": 29613, "text": "Code: " }, { "code": null, "e": 29632, "s": 29621, "text": "JavaScript" }, { "code": "<script>arrayToFilter .map(item => { // Item values }) .filter(Boolean);</script>", "e": 29735, "s": 29632, "text": null }, { "code": null, "e": 29805, "s": 29735, "text": "Input: [1, 2, 3, 0, \"Hi\", False, True]\n\nOutput: [1, 2, 3, \"Hi\", True]" }, { "code": null, "e": 30270, "s": 29805, "text": "6. Creating completely empty objects: If asked to create an empty object in JavaScript, our first go-to method will use in curly braces and assign it to a variable. But this is not a blank object as it still has object properties of JavaScript such as __proto__ and other methods. There is a way around this to create an object without any existent object properties. For this, we use a dictionary and assign it to a null value with its __proto__ being undefined. " }, { "code": null, "e": 30278, "s": 30270, "text": "Code: " }, { "code": null, "e": 30289, "s": 30278, "text": "javascript" }, { "code": "<script> /* Using .create() method to create a completely empty object */ let dict = Object.create(null); // dict.__proto__ === \"undefined\"</script>", "e": 30456, "s": 30289, "text": null }, { "code": null, "e": 30754, "s": 30456, "text": "7. Truncating an array: Although .splice() method is widely used to cut or remove specific portions of an array, but it has a worst-case time complexity of O(n). There exists a better alternative for removing elements from the end of an array. It uses the .length property of the array to do so. " }, { "code": null, "e": 30762, "s": 30754, "text": "Code: " }, { "code": null, "e": 30773, "s": 30762, "text": "javascript" }, { "code": "<script>let arrayToTruncate = [10, 5, 7, 8, 3, 4, 6, 1, 0]; /* Specifying the length till where the array should be truncated */arrayToTruncate.length = 6; console.log(arrayToTruncate)</script>", "e": 30969, "s": 30773, "text": null }, { "code": null, "e": 31186, "s": 30969, "text": "Output: As seen, we must know the length of the array to be truncated in this way otherwise it will result in an error. The run time here is of O(k) where k is the number of elements that will be left in the array. " }, { "code": null, "e": 31206, "s": 31186, "text": "[10, 5, 7, 8, 3, 4]" }, { "code": null, "e": 31397, "s": 31206, "text": "8. Merging objects: The introduction of spread operator(...) allows user to easily merge to or more objects which was previously achieved by creating a separate function for doing the same. " }, { "code": null, "e": 31407, "s": 31397, "text": "Code 1: " }, { "code": null, "e": 31418, "s": 31407, "text": "javascript" }, { "code": "<script>function mergeObjects(obj1, obj2) { for (var key in obj2) { if (obj2.hasOwnProperty(key)) obj1[key] = obj2[key]; } return obj1;}</script>", "e": 31580, "s": 31418, "text": null }, { "code": null, "e": 31688, "s": 31580, "text": "Code 2: By using spread operator, the above task can be achieved easily and the code is also quite lucid. " }, { "code": null, "e": 31699, "s": 31688, "text": "javascript" }, { "code": "<script> const obj1 = {}; // Items inside the object const obj2 = {}; // Items inside the object const obj3 = {...obj1, ...obj2};</script>", "e": 31848, "s": 31699, "text": null }, { "code": null, "e": 32013, "s": 31848, "text": "Input: \nobj1 = { site:'GeeksforGeeks', purpose:'Education'}\nobj2 = { location:'Noida'}\n\nOutput:\nobj3 = {site:'GeeksforGeeks', purpose:'Education', location:'Noida'}" }, { "code": null, "e": 32167, "s": 32013, "text": "9. Faster conditional checking: Checking and looping through conditions is an essential part of every programming language. In JavaScript, we do it as: " }, { "code": null, "e": 32177, "s": 32167, "text": "Code 1: " }, { "code": null, "e": 32188, "s": 32177, "text": "javascript" }, { "code": "<script>if (condition) { doSomething();}</script>", "e": 32241, "s": 32188, "text": null }, { "code": null, "e": 32359, "s": 32241, "text": "Code 2: However, the use of bit-wise operators make it easier to check conditions and also makes the code one line: " }, { "code": null, "e": 32370, "s": 32359, "text": "javascript" }, { "code": "<script> condition && doSomething();</script>", "e": 32419, "s": 32370, "text": null }, { "code": null, "e": 32696, "s": 32419, "text": "10. Using regex to replace all characters: Very often, one comes to a situation where every occurrence of a character or a sub-string but unfortunately, .replace() method replaces only one instance of occurrence. We can get around this by using regex with .replace() method. " }, { "code": null, "e": 32704, "s": 32696, "text": "Code: " }, { "code": null, "e": 32715, "s": 32704, "text": "javascript" }, { "code": "<script> var string = \"GeeksforGeeks\"; // Some string console.log(string.replace(/eek/, \"ool\"));</script>", "e": 32828, "s": 32715, "text": null }, { "code": null, "e": 32838, "s": 32828, "text": "Output: " }, { "code": null, "e": 32854, "s": 32838, "text": "\"GoolsforGools\"" }, { "code": null, "e": 32871, "s": 32856, "text": "sagartomar9927" }, { "code": null, "e": 32887, "s": 32871, "text": "JavaScript-Misc" }, { "code": null, "e": 32898, "s": 32887, "text": "JavaScript" }, { "code": null, "e": 32915, "s": 32898, "text": "Web Technologies" }, { "code": null, "e": 32942, "s": 32915, "text": "Web technologies Questions" }, { "code": null, "e": 33040, "s": 32942, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 33049, "s": 33040, "text": "Comments" }, { "code": null, "e": 33062, "s": 33049, "text": "Old Comments" }, { "code": null, "e": 33123, "s": 33062, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 33164, "s": 33123, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 33218, "s": 33164, "text": "How to get character array from string in JavaScript?" }, { "code": null, "e": 33258, "s": 33218, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 33306, "s": 33258, "text": "How to filter object array based on attributes?" }, { "code": null, "e": 33348, "s": 33306, "text": "Roadmap to Become a Web Developer in 2022" }, { "code": null, "e": 33381, "s": 33348, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 33431, "s": 33381, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 33493, "s": 33431, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" } ]
To check divisibility of any large number by 999 - GeeksforGeeks
16 Apr, 2021 You are given an n-digit large number, you have to check whether it is divisible by 999 without dividing or finding modulo of number by 999.Examples: Input : 235764 Output : Yes Input : 23576 Output : No Since input number may be very large, we cannot use n % 999 to check if a number is divisible by 999 or not, especially in languages like C/C++. The idea is based on following fact. The solutions is based on below fact. A number is divisible by 999 if sum of its 3-digit-groups (if required groups are formed by appending a 0s at the beginning) is divisible by 999. Illustration: Input : 235764 Output : Yes Explanation : Step I - read input : 235, 764 Step II - 235 + 764 = 999 As result is 999 then we can conclude that it is divisible by 999. Input : 1244633121 Output : Yes Explanation : Step I - read input : 1, 244, 633, 121 Step II - 001 + 244 + 633 + 121 = 999 As result is 999 then we can conclude that it is divisible by 999. Input : 999999999 Output : Yes Explanation : Step I - read input : 999, 999, 999 Step II - 999 + 999 + 999 = 2997 Step III - 997 + 002 = 999 As result is 999 then we can conclude that it is divisible by 999. How does this work? Let us consider 235764, we can write it as 235764 = 2*105 + 3*104 + 5*103 + 7*102 + 6*10 + 4 The idea is based on below observation: Remainder of 103 divided by 999 is 1 For i > 3, 10i % 999 = 10i-3 % 999 Let us see how we use above fact. Remainder of 2*105 + 3*104 + 5*103 + 7*102 + 6*10 + 4 Remainder with 999 can be written as : 2*100 + 3*10 + 5*1 + 7*100 + 6*10 + 4 The above expression is basically sum of groups of size 3. Since the sum is divisible by 999, answer is yes. A simple and efficient method is to take input in form of string (make its length in form of 3*m by adding 0 to left of number if required) and then you have to add the digits in blocks of three from right to left until it become a 3 digit number and if that result is 999 we can say that number is divisible by 999.As in the case of “divisibility by 9” we check that sum of all digit is divisible by 9 or not, the same thing follows within the case of divisibility by 999. We sum up all 3-digits group from right to left and check whether the final result is 999 or not. C++ Java Python 3 C# PHP Javascript // CPP for divisibility of number by 999#include<bits/stdc++.h>using namespace std; // function to check divisibilitybool isDivisible999(string num){ int n = num.length(); if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i<n; i++) { // group saves 3-digit group int group = 0; group += (num[i++] - '0') * 100; group += (num[i++] - '0') * 10; group += num[i] - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = to_string(gSum); n = num.length(); gSum = isDivisible999(num); } return (gSum == 999);} // driver programint main(){ string num = "1998"; int n = num.length(); if (isDivisible999(num)) cout << "Divisible"; else cout << "Not divisible"; return 0;} //Java for divisibility of number by 999 class Test{ // Method to check divisibility static boolean isDivisible999(String num) { int n = num.length(); if (n == 0 && num.charAt(0) == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i<n; i++) { // group saves 3-digit group int group = 0; group += (num.charAt(i++) - '0') * 100; group += (num.charAt(i++) - '0') * 10; group += num.charAt(i) - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = Integer.toString(gSum); n = num.length(); gSum = isDivisible999(num) ? 1 : 0; } return (gSum == 999); } // Driver method public static void main(String args[]) { String num = "1998"; System.out.println(isDivisible999(num) ? "Divisible" : "Not divisible"); }} # Python3 program for divisibility# of number by 999 # function to check divisibilitydef isDivisible999(num): n = len(num); if(n == 0 or num[0] == '0'): return true # Append required 0s at the beginning. if((n % 3) == 1): num = "00" + num if((n % 3) == 2): num = "0" + num # add digits in group of three in gSum gSum = 0 for i in range(0, n, 3): # group saves 3-digit group group = 0 group += (ord(num[i]) - 48) * 100 group += (ord(num[i + 1]) - 48) * 10 group += (ord(num[i + 2]) - 48) gSum += group # calculate result till 3 digit sum if(gSum > 1000): num = str(gSum) n = len(num) gSum = isDivisible999(num) return (gSum == 999) # Driver codeif __name__=="__main__": num = "1998" n = len(num) if(isDivisible999(num)): print("Divisible") else: print("Not divisible") # This code is contributed# by Sairahul Jella // C# code for divisibility of number by 999 using System;class Test{ // Method to check divisibility static bool isDivisible999(String num) { int n = num.Length; if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i<n; i++) { // group saves 3-digit group int group = 0; group += (num[i++] - '0') * 100; group += (num[i++] - '0') * 10; group += num[i] - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = Convert.ToString(gSum); n = num.Length ; gSum = isDivisible999(num) ? 1 : 0; } return (gSum == 999); } // Driver method public static void Main() { String num = "1998"; Console.WriteLine(isDivisible999(num) ? "Divisible" : "Not divisible"); } // This code is contributed by Ryuga} <?php// PHP for divisibility of number by 999 // function to check divisibilityfunction isDivisible999($num){ $n = strlen($num); if ($n == 0 && $num[0] == '0') return true; // Append required 0s at the beginning. if ($n % 3 == 1) $num = "00" . $num; if ($n % 3 == 2) $num = "0" . $num; // add digits in group of three in gSum $gSum = 0; for ($i = 0; $i < $n; $i += 3) { // group saves 3-digit group $group = 0; $group += (ord($num[$i]) - 48) * 100; $group += (ord($num[$i + 1]) - 48) * 10; $group += (ord($num[$i + 2]) - 48); $gSum += $group; } // calculate result till 3 digit sum if ($gSum > 1000) { $num = strval($gSum); $n = strlen($num); $gSum = isDivisible999($num); } return ($gSum == 999);} // Driver Code$num = "1998";if (isDivisible999($num)) echo "Divisible";else echo "Not divisible"; // This code is contributed by mits?> <script>// Javascript for divisibility of number by 999 // function to check divisibilityfunction isDivisible999(num){ let n = num.length; if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = "00" + num; if (n % 3 == 2) num = "0" + num; // add digits in group of three in gSum let gSum = 0; for (let i = 0; i < n; i += 3) { // group saves 3-digit group group = 0; group += (num.charCodeAt(i) - 48) * 100; group += (num.charCodeAt(i + 1) - 48) * 10; group += (num.charCodeAt(i + 2) - 48); gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = String(gSum); n = strlen(num); gSum = isDivisible999(num); } return (gSum == 999);} // Driver Codelet num = "1998";if (isDivisible999(num)) document.write("Divisible");else document.write("Not divisible"); // This code is contributed by _saurabh_jaiswal.</script> Output: Divisible More Divisibility Algorithms.This article is contributed by Shivam Pradhan (anuj_charm). 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. ankthon Sairahul Jella Mithun Kumar ManasChhabra2 _saurabh_jaiswal divisibility large-numbers Mathematical Strings Strings Mathematical Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Merge two sorted arrays Modulo Operator (%) in C/C++ with Examples Prime Numbers Program to find GCD or HCF of two numbers Print all possible combinations of r elements in a given array of size n Write a program to reverse an array or string Reverse a string in Java Longest Common Subsequence | DP-4 Check for Balanced Brackets in an expression (well-formedness) using Stack Python program to check if a string is palindrome or not
[ { "code": null, "e": 26737, "s": 26709, "text": "\n16 Apr, 2021" }, { "code": null, "e": 26889, "s": 26737, "text": "You are given an n-digit large number, you have to check whether it is divisible by 999 without dividing or finding modulo of number by 999.Examples: " }, { "code": null, "e": 26946, "s": 26889, "text": "Input : 235764 \nOutput : Yes\n\nInput : 23576 \nOutput : No" }, { "code": null, "e": 27129, "s": 26946, "text": "Since input number may be very large, we cannot use n % 999 to check if a number is divisible by 999 or not, especially in languages like C/C++. The idea is based on following fact. " }, { "code": null, "e": 27168, "s": 27129, "text": "The solutions is based on below fact. " }, { "code": null, "e": 27314, "s": 27168, "text": "A number is divisible by 999 if sum of its 3-digit-groups (if required groups are formed by appending a 0s at the beginning) is divisible by 999." }, { "code": null, "e": 27330, "s": 27314, "text": "Illustration: " }, { "code": null, "e": 28041, "s": 27330, "text": "Input : 235764 \nOutput : Yes\nExplanation : Step I - read input : 235, 764\n Step II - 235 + 764 = 999\n As result is 999 then we can \n conclude that it is divisible by 999.\n\nInput : 1244633121\nOutput : Yes\nExplanation : Step I - read input : 1, 244, 633, 121\n Step II - 001 + 244 + 633 + 121 = 999\n As result is 999 then we can conclude \n that it is divisible by 999.\n\nInput : 999999999\nOutput : Yes\nExplanation : Step I - read input : 999, 999, 999\n Step II - 999 + 999 + 999 = 2997\n Step III - 997 + 002 = 999\n As result is 999 then we can conclude \n that it is divisible by 999." }, { "code": null, "e": 28063, "s": 28041, "text": "How does this work? " }, { "code": null, "e": 28559, "s": 28063, "text": "Let us consider 235764, we can write it as\n235764 = 2*105 + 3*104 + 5*103 + \n 7*102 + 6*10 + 4\n\nThe idea is based on below observation:\nRemainder of 103 divided by 999 is 1\nFor i > 3, 10i % 999 = 10i-3 % 999 \n\nLet us see how we use above fact.\nRemainder of 2*105 + 3*104 + 5*103 + \n7*102 + 6*10 + 4\nRemainder with 999 can be written as : \n2*100 + 3*10 + 5*1 + 7*100 + 6*10 + 4 \nThe above expression is basically sum of\ngroups of size 3.\n\nSince the sum is divisible by 999, answer is yes." }, { "code": null, "e": 29132, "s": 28559, "text": "A simple and efficient method is to take input in form of string (make its length in form of 3*m by adding 0 to left of number if required) and then you have to add the digits in blocks of three from right to left until it become a 3 digit number and if that result is 999 we can say that number is divisible by 999.As in the case of “divisibility by 9” we check that sum of all digit is divisible by 9 or not, the same thing follows within the case of divisibility by 999. We sum up all 3-digits group from right to left and check whether the final result is 999 or not. " }, { "code": null, "e": 29136, "s": 29132, "text": "C++" }, { "code": null, "e": 29141, "s": 29136, "text": "Java" }, { "code": null, "e": 29150, "s": 29141, "text": "Python 3" }, { "code": null, "e": 29153, "s": 29150, "text": "C#" }, { "code": null, "e": 29157, "s": 29153, "text": "PHP" }, { "code": null, "e": 29168, "s": 29157, "text": "Javascript" }, { "code": "// CPP for divisibility of number by 999#include<bits/stdc++.h>using namespace std; // function to check divisibilitybool isDivisible999(string num){ int n = num.length(); if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = \"00\" + num; if (n % 3 == 2) num = \"0\" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i<n; i++) { // group saves 3-digit group int group = 0; group += (num[i++] - '0') * 100; group += (num[i++] - '0') * 10; group += num[i] - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = to_string(gSum); n = num.length(); gSum = isDivisible999(num); } return (gSum == 999);} // driver programint main(){ string num = \"1998\"; int n = num.length(); if (isDivisible999(num)) cout << \"Divisible\"; else cout << \"Not divisible\"; return 0;}", "e": 30187, "s": 29168, "text": null }, { "code": "//Java for divisibility of number by 999 class Test{ // Method to check divisibility static boolean isDivisible999(String num) { int n = num.length(); if (n == 0 && num.charAt(0) == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = \"00\" + num; if (n % 3 == 2) num = \"0\" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i<n; i++) { // group saves 3-digit group int group = 0; group += (num.charAt(i++) - '0') * 100; group += (num.charAt(i++) - '0') * 10; group += num.charAt(i) - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = Integer.toString(gSum); n = num.length(); gSum = isDivisible999(num) ? 1 : 0; } return (gSum == 999); } // Driver method public static void main(String args[]) { String num = \"1998\"; System.out.println(isDivisible999(num) ? \"Divisible\" : \"Not divisible\"); }}", "e": 31371, "s": 30187, "text": null }, { "code": "# Python3 program for divisibility# of number by 999 # function to check divisibilitydef isDivisible999(num): n = len(num); if(n == 0 or num[0] == '0'): return true # Append required 0s at the beginning. if((n % 3) == 1): num = \"00\" + num if((n % 3) == 2): num = \"0\" + num # add digits in group of three in gSum gSum = 0 for i in range(0, n, 3): # group saves 3-digit group group = 0 group += (ord(num[i]) - 48) * 100 group += (ord(num[i + 1]) - 48) * 10 group += (ord(num[i + 2]) - 48) gSum += group # calculate result till 3 digit sum if(gSum > 1000): num = str(gSum) n = len(num) gSum = isDivisible999(num) return (gSum == 999) # Driver codeif __name__==\"__main__\": num = \"1998\" n = len(num) if(isDivisible999(num)): print(\"Divisible\") else: print(\"Not divisible\") # This code is contributed# by Sairahul Jella", "e": 32356, "s": 31371, "text": null }, { "code": "// C# code for divisibility of number by 999 using System;class Test{ // Method to check divisibility static bool isDivisible999(String num) { int n = num.Length; if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = \"00\" + num; if (n % 3 == 2) num = \"0\" + num; // add digits in group of three in gSum int gSum = 0; for (int i = 0; i<n; i++) { // group saves 3-digit group int group = 0; group += (num[i++] - '0') * 100; group += (num[i++] - '0') * 10; group += num[i] - '0'; gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = Convert.ToString(gSum); n = num.Length ; gSum = isDivisible999(num) ? 1 : 0; } return (gSum == 999); } // Driver method public static void Main() { String num = \"1998\"; Console.WriteLine(isDivisible999(num) ? \"Divisible\" : \"Not divisible\"); } // This code is contributed by Ryuga}", "e": 33533, "s": 32356, "text": null }, { "code": "<?php// PHP for divisibility of number by 999 // function to check divisibilityfunction isDivisible999($num){ $n = strlen($num); if ($n == 0 && $num[0] == '0') return true; // Append required 0s at the beginning. if ($n % 3 == 1) $num = \"00\" . $num; if ($n % 3 == 2) $num = \"0\" . $num; // add digits in group of three in gSum $gSum = 0; for ($i = 0; $i < $n; $i += 3) { // group saves 3-digit group $group = 0; $group += (ord($num[$i]) - 48) * 100; $group += (ord($num[$i + 1]) - 48) * 10; $group += (ord($num[$i + 2]) - 48); $gSum += $group; } // calculate result till 3 digit sum if ($gSum > 1000) { $num = strval($gSum); $n = strlen($num); $gSum = isDivisible999($num); } return ($gSum == 999);} // Driver Code$num = \"1998\";if (isDivisible999($num)) echo \"Divisible\";else echo \"Not divisible\"; // This code is contributed by mits?>", "e": 34506, "s": 33533, "text": null }, { "code": "<script>// Javascript for divisibility of number by 999 // function to check divisibilityfunction isDivisible999(num){ let n = num.length; if (n == 0 && num[0] == '0') return true; // Append required 0s at the beginning. if (n % 3 == 1) num = \"00\" + num; if (n % 3 == 2) num = \"0\" + num; // add digits in group of three in gSum let gSum = 0; for (let i = 0; i < n; i += 3) { // group saves 3-digit group group = 0; group += (num.charCodeAt(i) - 48) * 100; group += (num.charCodeAt(i + 1) - 48) * 10; group += (num.charCodeAt(i + 2) - 48); gSum += group; } // calculate result till 3 digit sum if (gSum > 1000) { num = String(gSum); n = strlen(num); gSum = isDivisible999(num); } return (gSum == 999);} // Driver Codelet num = \"1998\";if (isDivisible999(num)) document.write(\"Divisible\");else document.write(\"Not divisible\"); // This code is contributed by _saurabh_jaiswal.</script>", "e": 35526, "s": 34506, "text": null }, { "code": null, "e": 35536, "s": 35526, "text": "Output: " }, { "code": null, "e": 35546, "s": 35536, "text": "Divisible" }, { "code": null, "e": 36011, "s": 35546, "text": "More Divisibility Algorithms.This article is contributed by Shivam Pradhan (anuj_charm). 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": 36019, "s": 36011, "text": "ankthon" }, { "code": null, "e": 36034, "s": 36019, "text": "Sairahul Jella" }, { "code": null, "e": 36047, "s": 36034, "text": "Mithun Kumar" }, { "code": null, "e": 36061, "s": 36047, "text": "ManasChhabra2" }, { "code": null, "e": 36078, "s": 36061, "text": "_saurabh_jaiswal" }, { "code": null, "e": 36091, "s": 36078, "text": "divisibility" }, { "code": null, "e": 36105, "s": 36091, "text": "large-numbers" }, { "code": null, "e": 36118, "s": 36105, "text": "Mathematical" }, { "code": null, "e": 36126, "s": 36118, "text": "Strings" }, { "code": null, "e": 36134, "s": 36126, "text": "Strings" }, { "code": null, "e": 36147, "s": 36134, "text": "Mathematical" }, { "code": null, "e": 36245, "s": 36147, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 36269, "s": 36245, "text": "Merge two sorted arrays" }, { "code": null, "e": 36312, "s": 36269, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 36326, "s": 36312, "text": "Prime Numbers" }, { "code": null, "e": 36368, "s": 36326, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 36441, "s": 36368, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 36487, "s": 36441, "text": "Write a program to reverse an array or string" }, { "code": null, "e": 36512, "s": 36487, "text": "Reverse a string in Java" }, { "code": null, "e": 36546, "s": 36512, "text": "Longest Common Subsequence | DP-4" }, { "code": null, "e": 36621, "s": 36546, "text": "Check for Balanced Brackets in an expression (well-formedness) using Stack" } ]
Jupyter Notebooks in the IDE. I work with Jupyter Notebooks every... | by Marc Wouts | Towards Data Science
I work with Jupyter Notebooks every day. And every day I use and edit Python libraries. Both are key elements in my work. Notebooks are a great way to document and explain your findings. And libraries are a safe investment in the long-term as they make your code reusable. Now, did you ever wonder... outside of using Jupyter for the notebooks and IDEs for the libraries, could we do otherwise? If you know me as the author of Jupytext, you already know that I think there’s a lot of added value of being able to edit your Jupyter notebooks in your favorite IDE. If you’ve not heard of Jupytext, then let me just mention that Jupytext is a plugin for Jupyter that lets you pair your traditional .ipynb notebooks with one or more text files. The paired text file, e.g. a Python script, can be edited (using any text editor or IDE), and then you get the changes back in Jupyter when you reload the notebook. Jupytext offers one way of accessing your notebook from the IDE. But it is not the only way. Spyder has a long history of offering an interactive mode on scripts with double percent cell markers. Hydrogen is a plugin for the Atom editor that lets you run these scripts interactively. And the two editors that I most use, PyCharm and Visual Studio Code, now let you open your .ipynb notebooks directly in the IDE! I was curious to see how well that works. Is the experience of using notebooks in those IDEs better than in Jupyter? Will I make the switch? In this article, I describe my current workflow with notebooks, then I compare it to what PyCharm and Visual Studio Code make possible now. I will take the example of a typical day at work. Today, I have to answer a new question about our data and algorithms. It turns out that I already answered a similar question in the past. So, to begin, I search which of my existing notebooks is the closest to yield the answer to today’s question. Since I use Jupytext, all my .ipynb notebooks have a paired .py representation. So I open PyCharm, and use the Find in Path search window to identify, among my collection of .py notebooks, which can get me started on today's question: Let me add that the search experience is much improved when you restrict the search to *.py files, and add .ipynb_checkpoints to Ignore Files and Folders in PyCharm Settings/Editor/File Types and that, if you want to pair all the notebook in the current directory to percent scripts, you can simply run jupytext --set-formats ipynb,py:percent *.ipynb. Now I open the existing notebook, which will serve as a template. I copy an extract of its content — the part that I want to start with — to a new .py file. I take care of including the YAML header, because it's where the Jupytext pairing information and the notebook kernel are defined. Then I adjust the new .py notebook to today's question. In a Markdown cell (delimited with # %% [markdown]), I write a few words about what I want to do today. Then I adjust the code to better address the current question. Doing this in an IDE is more comfortable than in the notebook. It is also safer and faster, as I benefit from the IDE syntax checks and highlighting. When my draft is good enough, I open the .py file in Jupyter as a notebook (single click in Jupyter Notebook; in JupyterLab, right-click on the file, and choose Edit with/Notebook). At this stage, it has no outputs, so I run it. Of course, the new notebook will probably not work well on the first run, so I continue editing the notebook in Jupyter, until it runs properly. When I save the notebook in Jupyter, the .py file gets updated to match the latest contents. Also, an .ipynb file is created, with outputs included, because the Jupytext header has ipynb at this line: formats:ipynb,py:percent. And if I forgot to copy the header, I can use the Jupytext menu in Jupyter and select: Pair notebook with .ipynb document to activate the pairing with a .ipynb notebook. Now I am done. Usually, I will share the .ipynb file (using, for instance, Jupyter nbviewer), and version the .py file. What do I most like about this workflow? Searching among notebooks is super easy — they are just text files. Drafting a new notebook is so comfortable. Never before was I able to copy-paste multiple cells from different notebooks so easily. When I edit the .py notebook in PyCharm, I benefit from the advanced capabilities of the IDE: syntax checks, completion, reformat, documentation tips... And I am also free to edit the notebook in Jupyter. Jupytext solves the issue of version control. Usually, I don’t want to keep the notebook outputs in git, so I only version the .py file, which has a clean diff history. Note that here I use PyCharm Professional, but it’s only because it is my favorite IDE. You can use any other editor, the workflow will work the same. What I am less fan of: Each notebook has a dual representation (.ipynb/.py). This may surprise more than one user. Working on the same document simultaneously in two editors (here, PyCharm and Jupyter) requires extra care. I must pay attention to saving the document in the current editor before switching to the other one (and maybe deactivate the autosave). And I need to refresh the notebook in the editor I am switching to. PyCharm could execute and debug my script, however, the outputs appear as text in the terminal, so in practice, I prefer to execute the notebook in Jupyter. PyCharm is my favorite code editor. Please don’t ask me why, as I am not sure there is a single reason for that... What I am sure however is that it is so great to edit scripts and libraries there! Also, I love PyCharm’s test and debugging tool suite (have a look at the Appendix to find out how to configure PyCharm). And version control is well integrated... PyCharm is available in two editions: Community and Professional. You can do a lot already with the Community Edition. Jupyter notebooks, however, are only available in the Professional Edition. I have prepared a test notebook made of a Markdown cell a code cell, which outputs a Pandas DataFrame a Matplotlib plot a Jupyter widget and a Plotly plot. Now I open the notebook in PyCharm Professional 2019.3.1, and I get this: This is super impressive, isn’t it? What do I like most? All the outputs in the notebook work! Even the widget, or the Plotly graph. Well done, PyCharm! I can edit the notebook as a Python script. Just like with Jupytext, copy-pasting multiple cells is super easy! A new code cell is created with just #%%. Use #%% md to create a Markdown cell. The shortcuts for executing a cell are the same as in Jupyter (Ctrl+Enter, Shift+Enter to execute and move the cursor to the next cell). And the preview window is well synchronized with the input window. When you click on one input cell, the view pane automatically scrolls to the corresponding output, and vice-versa. You can leverage PyCharm when you type or inspect code (e.g., ctrl+click brings you to the definition of functions or objects). Code completion, documentation tips etc are available in the notebook. You can set breakpoints, both on the notebook or on the underlying libraries. And the notebook variables appear in the variable explorer: If there is something that I am not fond of, maybe that is how the notebook is displayed. It is significantly different from Jupyter, as the outputs appear in the preview pane. I am not used to that. It also reduces the room available for my plots or tables. I think I’d prefer to have the outputs just below the inputs, as in Code, Hydrogen or even RStudio. Also, at work, I may write very long notebooks, and for that kind of notebooks the Table of Contents extension is super helpful as it lets me navigate easily between the different parts of the notebook — I’ll probably miss that feature in PyCharm’s notebook editor. If you are one of PyCharm’s developer team, let me tell you that, as a notebook user, I am so glad to see you working on this! You’ve done an impressive job! Now I have a few additional observations for you: Would you consider displaying the inputs right after the code cell? Could you do that and still let us select/copy/paste multiple cells easily? The Markdown cell markers are not standard. Following Spyder’s conventions, # %% md is a cell with title md. Could you instead use # %% [md] or # %% [markdown], like Code, Hydrogen or Jupytext? The search window (Find in Path) does not work well with notebooks — it displays extracts of their JSON content. Displaying their .py representation could have been more user-friendly. Reformatting the code (Ctrl+Alt+L) is not effective in the context of a notebook. Executing the notebook adds some cell metadata ({"pycharm": {"is_executing": false}}). Lastly, maybe the .py format is not appropriate for all notebooks. Some of my tutorials contain a lot of text, and for those, I prefer to use Jupytext's Markdown format. PyCharm works well with Markdown files, but it won't let me run the code there... what would you think of rendering these documents as notebooks in the IDE? Well done, PyCharm! Now let’s see what VS Code has to offer. Visual Studio Code is a free and open-source editor developed and maintained by Microsoft. It is not specific to Python, and has plugins for many languages. Here we will be testing Code in version 1.41.1, with the latest Python extension by Microsoft released on Jan 13, 2020. I use Code whenever I want to edit a Markdown file, or a script in any other language than Python, like Javascript or Typescript. But until recently I was not using Code much for Python. Looking back, I think the reason was that I did not know how to set up code to work with my conda environment. This is now solved and documented in the appendix, and I’d like to thank Luciana from the Python Visual Studio Code team for helping me with that. Now let me open in Code the same notebook that we just opened in PyCharm. The result is like this: What did I like? It works! All the outputs are nicely displayed (widgets are not yet supported, but I was told that they will be in the next release). Here as well, the shortcuts for executing one cell are the same as in Jupyter (Ctrl+Enter, Shift+Enter to execute and move the cursor to the next cell, Esc-A to create a cell above, etc). I like to have the outputs right under the code as in Jupyter. Typing code is comfortable thanks to the automatic completion. And we can examine the notebook variables in the variable explorer. But maybe I want a bit more. I would like to select/copy/paste multiple cells at once. I would like to navigate to a function’s definition, as we do in a script with ctrl-click. Why don’t we have the same context menu than in .py scripts? I'd like to set breakpoints in my notebook... And, but I already said that, I would appreciate a table of contents for finding my way in long notebooks. Is my story over... No! There’s one last thing I want to try. In Code’s documentation: Working with Jupyter Notebooks in Visual Studio Code, it is said that you can set up breakpoints once you convert the notebook to a Python script! Let’s try that. Now we click on convert the notebook to a Python script. We get a script that looks like PyCharm’s notebooks: What do I like here? I can leverage Code’s advanced functions to edit the file. Ctrl+click works and lets me navigate to definitions. I can easily select/copy/paste multiple cells at once. Tables, plots and interactive plots work in the interactive preview. I can type and execute Python code in the terminal without having to create a new cell. This is great! How many times did I create a new cell just because I needed to inspect a variable, and then I forgot to remove that cell from the notebook... The script uses the same cell markers as Jupytext. That means that I could rely on Jupytext for doing the conversion and sync between the notebook and script. In Jupyter, I would go to Jupytext/Pair with percent script, and save/reload the notebook to update both files. In the terminal, I would use jupytext notebook.ipynb --set-formats ipynb,py:percent and then jupytext notebook.ipynb --sync to keep the two files in sync. What I like even more are the breakpoints. Put a breakpoint on the script, and you can debug the cell and watch variables! I like very much that interactive mode! At this point, it is one of my favorite ways of editing a notebook in an editor. Now I have a few questions for the developers of the Python extension for Visual Studio Code: I know that I can connect VS Code to a local or remote Jupyter kernel. Now, could I share the same session between both Jupyter and Code, using for instance the %connect_info magic command? That would let me execute most of my notebook in Jupyter, and debug only a specific cell in Code, without having to re-run the notebook in full in Code. Jupytext allows me to edit my notebooks as either scripts or Markdown files. I find that the Markdown format is more appropriate for notebooks that contain more text than code, like tutorials or documentation. Would you like to offer a Markdown-mode for notebooks, or conversely, make Markdown files interactively executable in Code in the form of notebooks? Visual Studio Code and PyCharm are two great code editors. They make it so easy to design, edit or refactor Python code. So I really appreciate the idea of being able to open notebooks in those IDEs. How should notebooks be represented in the IDE? I liked the script-like notebook mode of PyCharm, and the interactive script mode of Code, as they allow to work on the notebook in the exact same way as one works with scripts (copy/paste, navigate in code, set breakpoints...). Will I make the switch to the IDE for my notebooks? I think I will continue to alternate between the IDE, when I want to search among my notebooks, draft a new notebook, refactor an existing one, or set a breakpoint, and Jupyter, when I want to navigate in the notebook using its Table of Content, analyse the plots, comment on my findings, or present the notebook. I want to thank the Python Tools for VS, Python Visual Studio Code, and JetBrains PyCharm developers for their work. I know by experience that addressing the notebook in the IDE has great potential, but is not an easy challenge. So I love to see more people working on this. Let me also thank the early readers who helped me to improve this article: François Wouts, and at CFM, Eric O. Lebigot, Florent Zara and Vincent Nguyen. In this part, I share my notes on how to properly install Python and configure PyCharm and Code. My notes are for Windows 10, but I expect them to work for any platform. Please clone the environment and example files from my GitHub repository: git clone https://github.com/mwouts/notebooks_in_vscode_and_pycharm_jan_2020.git Please install one of Miniconda or Anaconda. If you don’t know the difference, take Miniconda, it is lighter. Then go to the start menu, type Miniconda and then click on Anaconda Powershell Prompt (Miniconda3). In the terminal, change the directory to this project, and then create the example Python environment with e.g. cd Documents\Github\notebooks_in_vscode_and_pycharm_jan_2020 conda env create --file environment.yml Now we activate the environment with conda activate notebooks_in_vscode_and_pycharm_jan_2020 The environment that we have just created includes Jupyter and Jupytext. Launch Jupyter with cd Documents\Github\notebooks_in_vscode_and_pycharm_jan_2020conda env create --file environment.yml and you will be able to explore our example scripts and notebooks, and also see how Jupytext works. Let me assume that you have installed either PyCharm Community or PyCharm Professional and that you have opened our notebooks_in_vscode_and_pycharm_jan_2020 project in PyCharm. The next step is to tell PyCharm which Python we want to use. For this, after having activated the environment, with conda activate notebooks_in_vscode_and_pycharm_jan_2020, we do execute where.exe python on Windows, or which python on Linux or Mac OSX: Now we go to File\Settings, search for Project Interpreter, click on the gear/Add, select Existing Environment, and paste the full path to the Python interpreter — in my case: C:\Users\Marc\Miniconda3\envs\notebooks_in_vscode_and_pycharm_jan_2020\python.exe. Visual Studio Code’s documentation explains in detail how to configure Visual Studio Code with virtual Python environments. If you want to use conda instead, you will have to launch Code from within Conda. So we go to the Anaconda PowerShell Prompt, and start VS Code by typing code: Now you can close the shell. As Code inherited from the conda environment, you will be able to use Python and Jupyter from that environment. Let me stress out that if you don’t start Visual Studio Code within conda, you will get various types of errors, including: conda is not recognized as internal or external command.CommandNotFoundError: Your shell has not been properly configured to use 'conda activate' (I know, you added conda to your PATH... but that's not enough)or even, "Import Error: Unable to import required dependencies: numpy:". conda is not recognized as internal or external command. CommandNotFoundError: Your shell has not been properly configured to use 'conda activate' (I know, you added conda to your PATH... but that's not enough) or even, "Import Error: Unable to import required dependencies: numpy:".
[ { "code": null, "e": 567, "s": 172, "text": "I work with Jupyter Notebooks every day. And every day I use and edit Python libraries. Both are key elements in my work. Notebooks are a great way to document and explain your findings. And libraries are a safe investment in the long-term as they make your code reusable. Now, did you ever wonder... outside of using Jupyter for the notebooks and IDEs for the libraries, could we do otherwise?" }, { "code": null, "e": 735, "s": 567, "text": "If you know me as the author of Jupytext, you already know that I think there’s a lot of added value of being able to edit your Jupyter notebooks in your favorite IDE." }, { "code": null, "e": 1078, "s": 735, "text": "If you’ve not heard of Jupytext, then let me just mention that Jupytext is a plugin for Jupyter that lets you pair your traditional .ipynb notebooks with one or more text files. The paired text file, e.g. a Python script, can be edited (using any text editor or IDE), and then you get the changes back in Jupyter when you reload the notebook." }, { "code": null, "e": 1491, "s": 1078, "text": "Jupytext offers one way of accessing your notebook from the IDE. But it is not the only way. Spyder has a long history of offering an interactive mode on scripts with double percent cell markers. Hydrogen is a plugin for the Atom editor that lets you run these scripts interactively. And the two editors that I most use, PyCharm and Visual Studio Code, now let you open your .ipynb notebooks directly in the IDE!" }, { "code": null, "e": 1772, "s": 1491, "text": "I was curious to see how well that works. Is the experience of using notebooks in those IDEs better than in Jupyter? Will I make the switch? In this article, I describe my current workflow with notebooks, then I compare it to what PyCharm and Visual Studio Code make possible now." }, { "code": null, "e": 2071, "s": 1772, "text": "I will take the example of a typical day at work. Today, I have to answer a new question about our data and algorithms. It turns out that I already answered a similar question in the past. So, to begin, I search which of my existing notebooks is the closest to yield the answer to today’s question." }, { "code": null, "e": 2306, "s": 2071, "text": "Since I use Jupytext, all my .ipynb notebooks have a paired .py representation. So I open PyCharm, and use the Find in Path search window to identify, among my collection of .py notebooks, which can get me started on today's question:" }, { "code": null, "e": 2322, "s": 2306, "text": "Let me add that" }, { "code": null, "e": 2498, "s": 2322, "text": "the search experience is much improved when you restrict the search to *.py files, and add .ipynb_checkpoints to Ignore Files and Folders in PyCharm Settings/Editor/File Types" }, { "code": null, "e": 2658, "s": 2498, "text": "and that, if you want to pair all the notebook in the current directory to percent scripts, you can simply run jupytext --set-formats ipynb,py:percent *.ipynb." }, { "code": null, "e": 3319, "s": 2658, "text": "Now I open the existing notebook, which will serve as a template. I copy an extract of its content — the part that I want to start with — to a new .py file. I take care of including the YAML header, because it's where the Jupytext pairing information and the notebook kernel are defined. Then I adjust the new .py notebook to today's question. In a Markdown cell (delimited with # %% [markdown]), I write a few words about what I want to do today. Then I adjust the code to better address the current question. Doing this in an IDE is more comfortable than in the notebook. It is also safer and faster, as I benefit from the IDE syntax checks and highlighting." }, { "code": null, "e": 3693, "s": 3319, "text": "When my draft is good enough, I open the .py file in Jupyter as a notebook (single click in Jupyter Notebook; in JupyterLab, right-click on the file, and choose Edit with/Notebook). At this stage, it has no outputs, so I run it. Of course, the new notebook will probably not work well on the first run, so I continue editing the notebook in Jupyter, until it runs properly." }, { "code": null, "e": 4090, "s": 3693, "text": "When I save the notebook in Jupyter, the .py file gets updated to match the latest contents. Also, an .ipynb file is created, with outputs included, because the Jupytext header has ipynb at this line: formats:ipynb,py:percent. And if I forgot to copy the header, I can use the Jupytext menu in Jupyter and select: Pair notebook with .ipynb document to activate the pairing with a .ipynb notebook." }, { "code": null, "e": 4210, "s": 4090, "text": "Now I am done. Usually, I will share the .ipynb file (using, for instance, Jupyter nbviewer), and version the .py file." }, { "code": null, "e": 4251, "s": 4210, "text": "What do I most like about this workflow?" }, { "code": null, "e": 4319, "s": 4251, "text": "Searching among notebooks is super easy — they are just text files." }, { "code": null, "e": 4451, "s": 4319, "text": "Drafting a new notebook is so comfortable. Never before was I able to copy-paste multiple cells from different notebooks so easily." }, { "code": null, "e": 4604, "s": 4451, "text": "When I edit the .py notebook in PyCharm, I benefit from the advanced capabilities of the IDE: syntax checks, completion, reformat, documentation tips..." }, { "code": null, "e": 4656, "s": 4604, "text": "And I am also free to edit the notebook in Jupyter." }, { "code": null, "e": 4825, "s": 4656, "text": "Jupytext solves the issue of version control. Usually, I don’t want to keep the notebook outputs in git, so I only version the .py file, which has a clean diff history." }, { "code": null, "e": 4976, "s": 4825, "text": "Note that here I use PyCharm Professional, but it’s only because it is my favorite IDE. You can use any other editor, the workflow will work the same." }, { "code": null, "e": 4999, "s": 4976, "text": "What I am less fan of:" }, { "code": null, "e": 5091, "s": 4999, "text": "Each notebook has a dual representation (.ipynb/.py). This may surprise more than one user." }, { "code": null, "e": 5404, "s": 5091, "text": "Working on the same document simultaneously in two editors (here, PyCharm and Jupyter) requires extra care. I must pay attention to saving the document in the current editor before switching to the other one (and maybe deactivate the autosave). And I need to refresh the notebook in the editor I am switching to." }, { "code": null, "e": 5561, "s": 5404, "text": "PyCharm could execute and debug my script, however, the outputs appear as text in the terminal, so in practice, I prefer to execute the notebook in Jupyter." }, { "code": null, "e": 5922, "s": 5561, "text": "PyCharm is my favorite code editor. Please don’t ask me why, as I am not sure there is a single reason for that... What I am sure however is that it is so great to edit scripts and libraries there! Also, I love PyCharm’s test and debugging tool suite (have a look at the Appendix to find out how to configure PyCharm). And version control is well integrated..." }, { "code": null, "e": 6117, "s": 5922, "text": "PyCharm is available in two editions: Community and Professional. You can do a lot already with the Community Edition. Jupyter notebooks, however, are only available in the Professional Edition." }, { "code": null, "e": 6157, "s": 6117, "text": "I have prepared a test notebook made of" }, { "code": null, "e": 6173, "s": 6157, "text": "a Markdown cell" }, { "code": null, "e": 6219, "s": 6173, "text": "a code cell, which outputs a Pandas DataFrame" }, { "code": null, "e": 6237, "s": 6219, "text": "a Matplotlib plot" }, { "code": null, "e": 6254, "s": 6237, "text": "a Jupyter widget" }, { "code": null, "e": 6273, "s": 6254, "text": "and a Plotly plot." }, { "code": null, "e": 6347, "s": 6273, "text": "Now I open the notebook in PyCharm Professional 2019.3.1, and I get this:" }, { "code": null, "e": 6383, "s": 6347, "text": "This is super impressive, isn’t it?" }, { "code": null, "e": 6404, "s": 6383, "text": "What do I like most?" }, { "code": null, "e": 6500, "s": 6404, "text": "All the outputs in the notebook work! Even the widget, or the Plotly graph. Well done, PyCharm!" }, { "code": null, "e": 6692, "s": 6500, "text": "I can edit the notebook as a Python script. Just like with Jupytext, copy-pasting multiple cells is super easy! A new code cell is created with just #%%. Use #%% md to create a Markdown cell." }, { "code": null, "e": 7011, "s": 6692, "text": "The shortcuts for executing a cell are the same as in Jupyter (Ctrl+Enter, Shift+Enter to execute and move the cursor to the next cell). And the preview window is well synchronized with the input window. When you click on one input cell, the view pane automatically scrolls to the corresponding output, and vice-versa." }, { "code": null, "e": 7210, "s": 7011, "text": "You can leverage PyCharm when you type or inspect code (e.g., ctrl+click brings you to the definition of functions or objects). Code completion, documentation tips etc are available in the notebook." }, { "code": null, "e": 7288, "s": 7210, "text": "You can set breakpoints, both on the notebook or on the underlying libraries." }, { "code": null, "e": 7348, "s": 7288, "text": "And the notebook variables appear in the variable explorer:" }, { "code": null, "e": 7973, "s": 7348, "text": "If there is something that I am not fond of, maybe that is how the notebook is displayed. It is significantly different from Jupyter, as the outputs appear in the preview pane. I am not used to that. It also reduces the room available for my plots or tables. I think I’d prefer to have the outputs just below the inputs, as in Code, Hydrogen or even RStudio. Also, at work, I may write very long notebooks, and for that kind of notebooks the Table of Contents extension is super helpful as it lets me navigate easily between the different parts of the notebook — I’ll probably miss that feature in PyCharm’s notebook editor." }, { "code": null, "e": 8181, "s": 7973, "text": "If you are one of PyCharm’s developer team, let me tell you that, as a notebook user, I am so glad to see you working on this! You’ve done an impressive job! Now I have a few additional observations for you:" }, { "code": null, "e": 8325, "s": 8181, "text": "Would you consider displaying the inputs right after the code cell? Could you do that and still let us select/copy/paste multiple cells easily?" }, { "code": null, "e": 8519, "s": 8325, "text": "The Markdown cell markers are not standard. Following Spyder’s conventions, # %% md is a cell with title md. Could you instead use # %% [md] or # %% [markdown], like Code, Hydrogen or Jupytext?" }, { "code": null, "e": 8704, "s": 8519, "text": "The search window (Find in Path) does not work well with notebooks — it displays extracts of their JSON content. Displaying their .py representation could have been more user-friendly." }, { "code": null, "e": 8786, "s": 8704, "text": "Reformatting the code (Ctrl+Alt+L) is not effective in the context of a notebook." }, { "code": null, "e": 8873, "s": 8786, "text": "Executing the notebook adds some cell metadata ({\"pycharm\": {\"is_executing\": false}})." }, { "code": null, "e": 9200, "s": 8873, "text": "Lastly, maybe the .py format is not appropriate for all notebooks. Some of my tutorials contain a lot of text, and for those, I prefer to use Jupytext's Markdown format. PyCharm works well with Markdown files, but it won't let me run the code there... what would you think of rendering these documents as notebooks in the IDE?" }, { "code": null, "e": 9261, "s": 9200, "text": "Well done, PyCharm! Now let’s see what VS Code has to offer." }, { "code": null, "e": 9538, "s": 9261, "text": "Visual Studio Code is a free and open-source editor developed and maintained by Microsoft. It is not specific to Python, and has plugins for many languages. Here we will be testing Code in version 1.41.1, with the latest Python extension by Microsoft released on Jan 13, 2020." }, { "code": null, "e": 9983, "s": 9538, "text": "I use Code whenever I want to edit a Markdown file, or a script in any other language than Python, like Javascript or Typescript. But until recently I was not using Code much for Python. Looking back, I think the reason was that I did not know how to set up code to work with my conda environment. This is now solved and documented in the appendix, and I’d like to thank Luciana from the Python Visual Studio Code team for helping me with that." }, { "code": null, "e": 10082, "s": 9983, "text": "Now let me open in Code the same notebook that we just opened in PyCharm. The result is like this:" }, { "code": null, "e": 10099, "s": 10082, "text": "What did I like?" }, { "code": null, "e": 10233, "s": 10099, "text": "It works! All the outputs are nicely displayed (widgets are not yet supported, but I was told that they will be in the next release)." }, { "code": null, "e": 10421, "s": 10233, "text": "Here as well, the shortcuts for executing one cell are the same as in Jupyter (Ctrl+Enter, Shift+Enter to execute and move the cursor to the next cell, Esc-A to create a cell above, etc)." }, { "code": null, "e": 10484, "s": 10421, "text": "I like to have the outputs right under the code as in Jupyter." }, { "code": null, "e": 10547, "s": 10484, "text": "Typing code is comfortable thanks to the automatic completion." }, { "code": null, "e": 10615, "s": 10547, "text": "And we can examine the notebook variables in the variable explorer." }, { "code": null, "e": 11007, "s": 10615, "text": "But maybe I want a bit more. I would like to select/copy/paste multiple cells at once. I would like to navigate to a function’s definition, as we do in a script with ctrl-click. Why don’t we have the same context menu than in .py scripts? I'd like to set breakpoints in my notebook... And, but I already said that, I would appreciate a table of contents for finding my way in long notebooks." }, { "code": null, "e": 11257, "s": 11007, "text": "Is my story over... No! There’s one last thing I want to try. In Code’s documentation: Working with Jupyter Notebooks in Visual Studio Code, it is said that you can set up breakpoints once you convert the notebook to a Python script! Let’s try that." }, { "code": null, "e": 11367, "s": 11257, "text": "Now we click on convert the notebook to a Python script. We get a script that looks like PyCharm’s notebooks:" }, { "code": null, "e": 11388, "s": 11367, "text": "What do I like here?" }, { "code": null, "e": 11556, "s": 11388, "text": "I can leverage Code’s advanced functions to edit the file. Ctrl+click works and lets me navigate to definitions. I can easily select/copy/paste multiple cells at once." }, { "code": null, "e": 11625, "s": 11556, "text": "Tables, plots and interactive plots work in the interactive preview." }, { "code": null, "e": 11871, "s": 11625, "text": "I can type and execute Python code in the terminal without having to create a new cell. This is great! How many times did I create a new cell just because I needed to inspect a variable, and then I forgot to remove that cell from the notebook..." }, { "code": null, "e": 12297, "s": 11871, "text": "The script uses the same cell markers as Jupytext. That means that I could rely on Jupytext for doing the conversion and sync between the notebook and script. In Jupyter, I would go to Jupytext/Pair with percent script, and save/reload the notebook to update both files. In the terminal, I would use jupytext notebook.ipynb --set-formats ipynb,py:percent and then jupytext notebook.ipynb --sync to keep the two files in sync." }, { "code": null, "e": 12420, "s": 12297, "text": "What I like even more are the breakpoints. Put a breakpoint on the script, and you can debug the cell and watch variables!" }, { "code": null, "e": 12541, "s": 12420, "text": "I like very much that interactive mode! At this point, it is one of my favorite ways of editing a notebook in an editor." }, { "code": null, "e": 12635, "s": 12541, "text": "Now I have a few questions for the developers of the Python extension for Visual Studio Code:" }, { "code": null, "e": 12978, "s": 12635, "text": "I know that I can connect VS Code to a local or remote Jupyter kernel. Now, could I share the same session between both Jupyter and Code, using for instance the %connect_info magic command? That would let me execute most of my notebook in Jupyter, and debug only a specific cell in Code, without having to re-run the notebook in full in Code." }, { "code": null, "e": 13337, "s": 12978, "text": "Jupytext allows me to edit my notebooks as either scripts or Markdown files. I find that the Markdown format is more appropriate for notebooks that contain more text than code, like tutorials or documentation. Would you like to offer a Markdown-mode for notebooks, or conversely, make Markdown files interactively executable in Code in the form of notebooks?" }, { "code": null, "e": 13537, "s": 13337, "text": "Visual Studio Code and PyCharm are two great code editors. They make it so easy to design, edit or refactor Python code. So I really appreciate the idea of being able to open notebooks in those IDEs." }, { "code": null, "e": 13814, "s": 13537, "text": "How should notebooks be represented in the IDE? I liked the script-like notebook mode of PyCharm, and the interactive script mode of Code, as they allow to work on the notebook in the exact same way as one works with scripts (copy/paste, navigate in code, set breakpoints...)." }, { "code": null, "e": 14180, "s": 13814, "text": "Will I make the switch to the IDE for my notebooks? I think I will continue to alternate between the IDE, when I want to search among my notebooks, draft a new notebook, refactor an existing one, or set a breakpoint, and Jupyter, when I want to navigate in the notebook using its Table of Content, analyse the plots, comment on my findings, or present the notebook." }, { "code": null, "e": 14455, "s": 14180, "text": "I want to thank the Python Tools for VS, Python Visual Studio Code, and JetBrains PyCharm developers for their work. I know by experience that addressing the notebook in the IDE has great potential, but is not an easy challenge. So I love to see more people working on this." }, { "code": null, "e": 14609, "s": 14455, "text": "Let me also thank the early readers who helped me to improve this article: François Wouts, and at CFM, Eric O. Lebigot, Florent Zara and Vincent Nguyen." }, { "code": null, "e": 14779, "s": 14609, "text": "In this part, I share my notes on how to properly install Python and configure PyCharm and Code. My notes are for Windows 10, but I expect them to work for any platform." }, { "code": null, "e": 14853, "s": 14779, "text": "Please clone the environment and example files from my GitHub repository:" }, { "code": null, "e": 14934, "s": 14853, "text": "git clone https://github.com/mwouts/notebooks_in_vscode_and_pycharm_jan_2020.git" }, { "code": null, "e": 15044, "s": 14934, "text": "Please install one of Miniconda or Anaconda. If you don’t know the difference, take Miniconda, it is lighter." }, { "code": null, "e": 15257, "s": 15044, "text": "Then go to the start menu, type Miniconda and then click on Anaconda Powershell Prompt (Miniconda3). In the terminal, change the directory to this project, and then create the example Python environment with e.g." }, { "code": null, "e": 15358, "s": 15257, "text": "cd Documents\\Github\\notebooks_in_vscode_and_pycharm_jan_2020 conda env create --file environment.yml" }, { "code": null, "e": 15395, "s": 15358, "text": "Now we activate the environment with" }, { "code": null, "e": 15451, "s": 15395, "text": "conda activate notebooks_in_vscode_and_pycharm_jan_2020" }, { "code": null, "e": 15544, "s": 15451, "text": "The environment that we have just created includes Jupyter and Jupytext. Launch Jupyter with" }, { "code": null, "e": 15644, "s": 15544, "text": "cd Documents\\Github\\notebooks_in_vscode_and_pycharm_jan_2020conda env create --file environment.yml" }, { "code": null, "e": 15744, "s": 15644, "text": "and you will be able to explore our example scripts and notebooks, and also see how Jupytext works." }, { "code": null, "e": 15921, "s": 15744, "text": "Let me assume that you have installed either PyCharm Community or PyCharm Professional and that you have opened our notebooks_in_vscode_and_pycharm_jan_2020 project in PyCharm." }, { "code": null, "e": 16175, "s": 15921, "text": "The next step is to tell PyCharm which Python we want to use. For this, after having activated the environment, with conda activate notebooks_in_vscode_and_pycharm_jan_2020, we do execute where.exe python on Windows, or which python on Linux or Mac OSX:" }, { "code": null, "e": 16434, "s": 16175, "text": "Now we go to File\\Settings, search for Project Interpreter, click on the gear/Add, select Existing Environment, and paste the full path to the Python interpreter — in my case: C:\\Users\\Marc\\Miniconda3\\envs\\notebooks_in_vscode_and_pycharm_jan_2020\\python.exe." }, { "code": null, "e": 16558, "s": 16434, "text": "Visual Studio Code’s documentation explains in detail how to configure Visual Studio Code with virtual Python environments." }, { "code": null, "e": 16718, "s": 16558, "text": "If you want to use conda instead, you will have to launch Code from within Conda. So we go to the Anaconda PowerShell Prompt, and start VS Code by typing code:" }, { "code": null, "e": 16859, "s": 16718, "text": "Now you can close the shell. As Code inherited from the conda environment, you will be able to use Python and Jupyter from that environment." }, { "code": null, "e": 16983, "s": 16859, "text": "Let me stress out that if you don’t start Visual Studio Code within conda, you will get various types of errors, including:" }, { "code": null, "e": 17265, "s": 16983, "text": "conda is not recognized as internal or external command.CommandNotFoundError: Your shell has not been properly configured to use 'conda activate' (I know, you added conda to your PATH... but that's not enough)or even, \"Import Error: Unable to import required dependencies: numpy:\"." }, { "code": null, "e": 17322, "s": 17265, "text": "conda is not recognized as internal or external command." }, { "code": null, "e": 17476, "s": 17322, "text": "CommandNotFoundError: Your shell has not been properly configured to use 'conda activate' (I know, you added conda to your PATH... but that's not enough)" } ]
Explicit waits in Selenium Python - GeeksforGeeks
19 May, 2020 Selenium Python is one of the great tools for testing automation. These days most of the web apps are using AJAX techniques. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes locating elements difficult: if an element is not yet present in the DOM, a locate function will raise an ElementNotVisibleException exception. Using waits, we can solve this issue. Waiting provides some slack between actions performed – mostly locating an element or any other operation with the element. Selenium Webdriver provides two types of waits – implicit & explicit. This article revolves around Explicit wait in Selenium Python. Explicit WaitsAn explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. Explicit waits are achieved by using webdriverWait class in combination with expected_conditions. Let’s consider an example – # import necessary classesfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC # create driver object driver = webdriver.Firefox() # A URL that delays loadingdriver.get("http://somedomain / url_that_delays_loading") try: # wait 10 seconds before looking for element element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, "myDynamicElement")) )finally: # else quit driver.quit() This waits up to 10 seconds before throwing a TimeoutException unless it finds the element to return within 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.Expected Conditions –There are some common conditions that are frequently of use when automating web browsers. For example, presence_of_element_located, title_is, ad so on. one can check entire methods from here – Convenience Methods. Some of them are – title_is title_contains presence_of_element_located visibility_of_element_located visibility_of presence_of_all_elements_located element_located_to_be_selected element_selection_state_to_be element_located_selection_state_to_be alert_is_present Explicit wait as defined would be the combination of WebDriverWait and Expected conditions. Let’s implement this on https://www.geeksforgeeks.org/ and wait 10 seconds before locating an element. # import webdriver from selenium import webdriver from selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC # create webdriver object driver = webdriver.Firefox() # get geeksforgeeks.org driver.get("https://www.geeksforgeeks.org/") # get element after explicitly waiting for 10 secondselement = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.link_text, "Courses")) )# click the element element.click() Output –First it opens https://www.geeksforgeeks.org/ and then finds Courses link It clicks on courses links and is redirected to https://practice.geeksforgeeks.org/ Python-selenium selenium Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary How to Install PIP on Windows ? Enumerate() in Python Different ways to create Pandas Dataframe Python String | replace() Reading and Writing to text files in Python *args and **kwargs in Python Create a Pandas DataFrame from Lists Check if element exists in list in Python How To Convert Python Dictionary To JSON?
[ { "code": null, "e": 25929, "s": 25901, "text": "\n19 May, 2020" }, { "code": null, "e": 26610, "s": 25929, "text": "Selenium Python is one of the great tools for testing automation. These days most of the web apps are using AJAX techniques. When a page is loaded by the browser, the elements within that page may load at different time intervals. This makes locating elements difficult: if an element is not yet present in the DOM, a locate function will raise an ElementNotVisibleException exception. Using waits, we can solve this issue. Waiting provides some slack between actions performed – mostly locating an element or any other operation with the element. Selenium Webdriver provides two types of waits – implicit & explicit. This article revolves around Explicit wait in Selenium Python." }, { "code": null, "e": 27078, "s": 26610, "text": "Explicit WaitsAn explicit wait is a code you define to wait for a certain condition to occur before proceeding further in the code. The extreme case of this is time.sleep(), which sets the condition to an exact time period to wait. There are some convenience methods provided that help you write code that will wait only as long as required. Explicit waits are achieved by using webdriverWait class in combination with expected_conditions. Let’s consider an example –" }, { "code": "# import necessary classesfrom selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC # create driver object driver = webdriver.Firefox() # A URL that delays loadingdriver.get(\"http://somedomain / url_that_delays_loading\") try: # wait 10 seconds before looking for element element = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.ID, \"myDynamicElement\")) )finally: # else quit driver.quit()", "e": 27618, "s": 27078, "text": null }, { "code": null, "e": 28098, "s": 27618, "text": "This waits up to 10 seconds before throwing a TimeoutException unless it finds the element to return within 10 seconds. WebDriverWait by default calls the ExpectedCondition every 500 milliseconds until it returns successfully.Expected Conditions –There are some common conditions that are frequently of use when automating web browsers. For example, presence_of_element_located, title_is, ad so on. one can check entire methods from here – Convenience Methods. Some of them are –" }, { "code": null, "e": 28107, "s": 28098, "text": "title_is" }, { "code": null, "e": 28122, "s": 28107, "text": "title_contains" }, { "code": null, "e": 28150, "s": 28122, "text": "presence_of_element_located" }, { "code": null, "e": 28180, "s": 28150, "text": "visibility_of_element_located" }, { "code": null, "e": 28194, "s": 28180, "text": "visibility_of" }, { "code": null, "e": 28227, "s": 28194, "text": "presence_of_all_elements_located" }, { "code": null, "e": 28258, "s": 28227, "text": "element_located_to_be_selected" }, { "code": null, "e": 28288, "s": 28258, "text": "element_selection_state_to_be" }, { "code": null, "e": 28326, "s": 28288, "text": "element_located_selection_state_to_be" }, { "code": null, "e": 28343, "s": 28326, "text": "alert_is_present" }, { "code": null, "e": 28538, "s": 28343, "text": "Explicit wait as defined would be the combination of WebDriverWait and Expected conditions. Let’s implement this on https://www.geeksforgeeks.org/ and wait 10 seconds before locating an element." }, { "code": "# import webdriver from selenium import webdriver from selenium.webdriver.common.by import Byfrom selenium.webdriver.support.ui import WebDriverWaitfrom selenium.webdriver.support import expected_conditions as EC # create webdriver object driver = webdriver.Firefox() # get geeksforgeeks.org driver.get(\"https://www.geeksforgeeks.org/\") # get element after explicitly waiting for 10 secondselement = WebDriverWait(driver, 10).until( EC.presence_of_element_located((By.link_text, \"Courses\")) )# click the element element.click() ", "e": 29087, "s": 28538, "text": null }, { "code": null, "e": 29169, "s": 29087, "text": "Output –First it opens https://www.geeksforgeeks.org/ and then finds Courses link" }, { "code": null, "e": 29253, "s": 29169, "text": "It clicks on courses links and is redirected to https://practice.geeksforgeeks.org/" }, { "code": null, "e": 29269, "s": 29253, "text": "Python-selenium" }, { "code": null, "e": 29278, "s": 29269, "text": "selenium" }, { "code": null, "e": 29285, "s": 29278, "text": "Python" }, { "code": null, "e": 29383, "s": 29285, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29401, "s": 29383, "text": "Python Dictionary" }, { "code": null, "e": 29433, "s": 29401, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29455, "s": 29433, "text": "Enumerate() in Python" }, { "code": null, "e": 29497, "s": 29455, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29523, "s": 29497, "text": "Python String | replace()" }, { "code": null, "e": 29567, "s": 29523, "text": "Reading and Writing to text files in Python" }, { "code": null, "e": 29596, "s": 29567, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29633, "s": 29596, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29675, "s": 29633, "text": "Check if element exists in list in Python" } ]
What are public and private variables in Python class?
Python doesn’t restrict us from accessing any variable or calling any member method in a python program. All python variables and methods are public by default in Python. So when we want to make any variable or method public, we just do nothing. Let us see the example below − class Mug: def __init__(self): self.color = None self.content = None def fill(self, beverage): self.content = beverage def empty(self): self.content = None brownMug = Mug() brownMug.color = "brown" print brownMug.empty() print brownMug.fill('tea') print brownMug.color print brownMug.content All the variables and the methods in the code are public by default. When we declare our data member private we mean, that nobody should be able to access it from outside the class. Here Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName> . So to make our member private, let’s have a look at the example below − class Cup: def __init__(self, color): self.__content = None # private variable def fill(self, beverage): self.__content = beverage def empty(self): self.__content = None Our cup now can be only filled and poured out by using fill() and empty() methods. Note, that if you try accessing __content from outside, you’ll get an error. But you can still stumble upon something like this − redCup = Cup("red") redCup._Cup__content = "tea"
[ { "code": null, "e": 1167, "s": 1062, "text": "Python doesn’t restrict us from accessing any variable or calling any member method in a python program." }, { "code": null, "e": 1339, "s": 1167, "text": "All python variables and methods are public by default in Python. So when we want to make any variable or method public, we just do nothing. Let us see the example below −" }, { "code": null, "e": 1678, "s": 1339, "text": "class Mug:\n def __init__(self):\n self.color = None\n self.content = None\n\n def fill(self, beverage):\n self.content = beverage\n\n def empty(self):\n self.content = None\n\nbrownMug = Mug()\nbrownMug.color = \"brown\"\nprint brownMug.empty()\nprint brownMug.fill('tea')\nprint brownMug.color\nprint brownMug.content" }, { "code": null, "e": 1747, "s": 1678, "text": "All the variables and the methods in the code are public by default." }, { "code": null, "e": 2136, "s": 1747, "text": "When we declare our data member private we mean, that nobody should be able to access it from outside the class. Here Python supports a technique called name mangling. This feature turns every member name prefixed with at least two underscores and suffixed with at most one underscore into _<className><memberName> . So to make our member private, let’s have a look at the example below −" }, { "code": null, "e": 2344, "s": 2136, "text": "class Cup:\n def __init__(self, color):\n self.__content = None # private variable\n def fill(self, beverage):\n self.__content = beverage\n def empty(self):\n self.__content = None" }, { "code": null, "e": 2557, "s": 2344, "text": "Our cup now can be only filled and poured out by using fill() and empty() methods. Note, that if you try accessing __content from outside, you’ll get an error. But you can still stumble upon something like this −" }, { "code": null, "e": 2606, "s": 2557, "text": "redCup = Cup(\"red\")\nredCup._Cup__content = \"tea\"" } ]
How to use Dynamic SQL in BigQuery | by Lak Lakshmanan | Towards Data Science
Let’s say that we want to find the number of confirmed COVID cases over the past 3 days in various Canadian provinces. There is a BigQuery public dataset with information published by Johns Hopkins, and we can query it as follows: SELECT * FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_casesWHERE country_region LIKE 'Canada' We get: Yikes! There is a column for every date. How do we find the last three days for which there is data? We can use INFORMATION_SCHEMA to get the list of columns and find the last three days using: SELECT column_name, parse_date('_%m_%d_%y', column_name) AS dateFROM `bigquery-public-data`.covid19_jhu_csse.INFORMATION_SCHEMA.COLUMNSWHERE table_name = 'confirmed_cases' AND STARTS_WITH(column_name, '_')ORDER BY date DESC LIMIT 3 This returns: You can run a dynamic SQL statement using EXECUTE IMMEDIATE. For example, suppose we have a variable with the column name _5_18_20, this is how to use it to execute a SELECT statement: DECLARE col_0 STRING;SET col_0 = '_5_18_20';EXECUTE IMMEDIATE format(""" SELECT country_region, province_state, %s AS cases_day0 FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE 'Canada' ORDER BY cases_day0 DESC""", col_0); Look carefully at the query above. First of all, because I’m declaring a variable, etc., this is a BigQuery script where each statement ends with a semicolon. I am then using BigQuery’s string format function to create the statement I want to run. Because I am passing in a string, I specify %s in the format string and pass in col_0. The result consists of two stages: with the result of the second stage being: We can combine the above three ideas — INFORMATION_SCHEMA, scripting, and EXECUTE IMMEDIATE to get the data for the past 3 days. DECLARE columns ARRAY<STRUCT<column_name STRING, date DATE>>;SET columns = ( WITH all_date_columns AS ( SELECT column_name, parse_date('_%m_%d_%y', column_name) AS date FROM `bigquery-public-data`.covid19_jhu_csse.INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'confirmed_cases' AND STARTS_WITH(column_name, '_') ) SELECT ARRAY_AGG(STRUCT(column_name, date) ORDER BY date DESC LIMIT 3) AS columns FROM all_date_columns);EXECUTE IMMEDIATE format(""" SELECT country_region, province_state, %s AS cases_day0, '%t' AS date_day0, %s AS cases_day1, '%t' AS date_day1, %s AS cases_day2, '%t' AS date_day2 FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE 'Canada' ORDER BY cases_day0 DESC""", columns[OFFSET(0)].column_name, columns[OFFSET(0)].date,columns[OFFSET(1)].column_name, columns[OFFSET(1)].date,columns[OFFSET(2)].column_name, columns[OFFSET(2)].date); The steps: Declare columns as an array variable that will store the column name and date for the 3 most recent days Set columns to be the result of the query to get 3 days. Notice that I’m doing an ARRAY_AGG so that I get the complete resultset stored in one variable. Format the query. Note that I am using `%t` to represent a timestamp (see the String format documentation for details), and passing in six parameters. The result is: Instead of using String format, you can do named variables as follows: EXECUTE IMMEDIATE """ SELECT country_region, province_state, _5_18_20 AS cases FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE @country ORDER BY cases DESC LIMIT 3"""USING 'Canada' AS country; You can also do positional variables using question marks: EXECUTE IMMEDIATE """ SELECT country_region, province_state, _5_18_20 AS cases FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE ? ORDER BY cases DESC LIMIT ?"""USING 'Canada', 3; The USING clause is tricky in some situations. For example, the following doesn’t work: EXECUTE IMMEDIATE """ SELECT country_region, province_state, ? AS cases -- PROBLEM!!! FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE ? ORDER BY cases DESC LIMIT ?"""USING '_5_18_20', 'Canada', 3; -- DOESNT WORK!!!! That’s because the first parameter gets interpreted as: '_5_18_20' AS cases So, you can’t pass in a column name through USING. Hence, I recommend using String FORMAT() to create the query to execute immediately because it doesn’t have these problems. The Dynamic SQL feature was released on BigQuery’s 10th birthday. Here’s a video featuring some BigQuery friends wishing it a happy birthday: The very first user thread from 10 years ago raves about processing 60B records in a few seconds and muses about near-real-time queries (the more things change ...). In that same thread is the first feature request ... for pivots: Dynamic SQL finally makes this possible and Felipe Hoffa has promised he’ll write a function to finally be able to PIVOT() inside BigQuery - stay tuned. Enjoy! Thanks to my colleague Jagan R. Athreya for useful discussions on USING and the suggestion to use FORMAT and to Felipe Hoffa for the walk down nostalgia lane.
[ { "code": null, "e": 403, "s": 172, "text": "Let’s say that we want to find the number of confirmed COVID cases over the past 3 days in various Canadian provinces. There is a BigQuery public dataset with information published by Johns Hopkins, and we can query it as follows:" }, { "code": null, "e": 510, "s": 403, "text": "SELECT * FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_casesWHERE country_region LIKE 'Canada'" }, { "code": null, "e": 518, "s": 510, "text": "We get:" }, { "code": null, "e": 619, "s": 518, "text": "Yikes! There is a column for every date. How do we find the last three days for which there is data?" }, { "code": null, "e": 712, "s": 619, "text": "We can use INFORMATION_SCHEMA to get the list of columns and find the last three days using:" }, { "code": null, "e": 961, "s": 712, "text": "SELECT column_name, parse_date('_%m_%d_%y', column_name) AS dateFROM `bigquery-public-data`.covid19_jhu_csse.INFORMATION_SCHEMA.COLUMNSWHERE table_name = 'confirmed_cases' AND STARTS_WITH(column_name, '_')ORDER BY date DESC LIMIT 3" }, { "code": null, "e": 975, "s": 961, "text": "This returns:" }, { "code": null, "e": 1160, "s": 975, "text": "You can run a dynamic SQL statement using EXECUTE IMMEDIATE. For example, suppose we have a variable with the column name _5_18_20, this is how to use it to execute a SELECT statement:" }, { "code": null, "e": 1436, "s": 1160, "text": "DECLARE col_0 STRING;SET col_0 = '_5_18_20';EXECUTE IMMEDIATE format(\"\"\" SELECT country_region, province_state, %s AS cases_day0 FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE 'Canada' ORDER BY cases_day0 DESC\"\"\", col_0);" }, { "code": null, "e": 1595, "s": 1436, "text": "Look carefully at the query above. First of all, because I’m declaring a variable, etc., this is a BigQuery script where each statement ends with a semicolon." }, { "code": null, "e": 1771, "s": 1595, "text": "I am then using BigQuery’s string format function to create the statement I want to run. Because I am passing in a string, I specify %s in the format string and pass in col_0." }, { "code": null, "e": 1806, "s": 1771, "text": "The result consists of two stages:" }, { "code": null, "e": 1849, "s": 1806, "text": "with the result of the second stage being:" }, { "code": null, "e": 1978, "s": 1849, "text": "We can combine the above three ideas — INFORMATION_SCHEMA, scripting, and EXECUTE IMMEDIATE to get the data for the past 3 days." }, { "code": null, "e": 2905, "s": 1978, "text": "DECLARE columns ARRAY<STRUCT<column_name STRING, date DATE>>;SET columns = ( WITH all_date_columns AS ( SELECT column_name, parse_date('_%m_%d_%y', column_name) AS date FROM `bigquery-public-data`.covid19_jhu_csse.INFORMATION_SCHEMA.COLUMNS WHERE table_name = 'confirmed_cases' AND STARTS_WITH(column_name, '_') ) SELECT ARRAY_AGG(STRUCT(column_name, date) ORDER BY date DESC LIMIT 3) AS columns FROM all_date_columns);EXECUTE IMMEDIATE format(\"\"\" SELECT country_region, province_state, %s AS cases_day0, '%t' AS date_day0, %s AS cases_day1, '%t' AS date_day1, %s AS cases_day2, '%t' AS date_day2 FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE 'Canada' ORDER BY cases_day0 DESC\"\"\", columns[OFFSET(0)].column_name, columns[OFFSET(0)].date,columns[OFFSET(1)].column_name, columns[OFFSET(1)].date,columns[OFFSET(2)].column_name, columns[OFFSET(2)].date);" }, { "code": null, "e": 2916, "s": 2905, "text": "The steps:" }, { "code": null, "e": 3021, "s": 2916, "text": "Declare columns as an array variable that will store the column name and date for the 3 most recent days" }, { "code": null, "e": 3174, "s": 3021, "text": "Set columns to be the result of the query to get 3 days. Notice that I’m doing an ARRAY_AGG so that I get the complete resultset stored in one variable." }, { "code": null, "e": 3325, "s": 3174, "text": "Format the query. Note that I am using `%t` to represent a timestamp (see the String format documentation for details), and passing in six parameters." }, { "code": null, "e": 3340, "s": 3325, "text": "The result is:" }, { "code": null, "e": 3411, "s": 3340, "text": "Instead of using String format, you can do named variables as follows:" }, { "code": null, "e": 3649, "s": 3411, "text": "EXECUTE IMMEDIATE \"\"\" SELECT country_region, province_state, _5_18_20 AS cases FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE @country ORDER BY cases DESC LIMIT 3\"\"\"USING 'Canada' AS country;" }, { "code": null, "e": 3708, "s": 3649, "text": "You can also do positional variables using question marks:" }, { "code": null, "e": 3931, "s": 3708, "text": "EXECUTE IMMEDIATE \"\"\" SELECT country_region, province_state, _5_18_20 AS cases FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE ? ORDER BY cases DESC LIMIT ?\"\"\"USING 'Canada', 3;" }, { "code": null, "e": 4019, "s": 3931, "text": "The USING clause is tricky in some situations. For example, the following doesn’t work:" }, { "code": null, "e": 4279, "s": 4019, "text": "EXECUTE IMMEDIATE \"\"\" SELECT country_region, province_state, ? AS cases -- PROBLEM!!! FROM `bigquery-public-data`.covid19_jhu_csse.confirmed_cases WHERE country_region LIKE ? ORDER BY cases DESC LIMIT ?\"\"\"USING '_5_18_20', 'Canada', 3; -- DOESNT WORK!!!!" }, { "code": null, "e": 4335, "s": 4279, "text": "That’s because the first parameter gets interpreted as:" }, { "code": null, "e": 4355, "s": 4335, "text": "'_5_18_20' AS cases" }, { "code": null, "e": 4530, "s": 4355, "text": "So, you can’t pass in a column name through USING. Hence, I recommend using String FORMAT() to create the query to execute immediately because it doesn’t have these problems." }, { "code": null, "e": 4672, "s": 4530, "text": "The Dynamic SQL feature was released on BigQuery’s 10th birthday. Here’s a video featuring some BigQuery friends wishing it a happy birthday:" }, { "code": null, "e": 4903, "s": 4672, "text": "The very first user thread from 10 years ago raves about processing 60B records in a few seconds and muses about near-real-time queries (the more things change ...). In that same thread is the first feature request ... for pivots:" }, { "code": null, "e": 5056, "s": 4903, "text": "Dynamic SQL finally makes this possible and Felipe Hoffa has promised he’ll write a function to finally be able to PIVOT() inside BigQuery - stay tuned." }, { "code": null, "e": 5063, "s": 5056, "text": "Enjoy!" } ]
How do I update NULL values in a field in MySQL?
Let us first create a table − mysql> create table OrderDemo -> ( -> OrderId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> OrderPrice int, -> OrderDatetime datetime -> ); Query OK, 0 rows affected (0.66 sec) Now you can insert some records in the table using insert command. The query is as follows − mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(200,'2016-09-12'); Query OK, 1 row affected (0.24 sec) mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(NULL,'2002-11-18'); Query OK, 1 row affected (0.26 sec) mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(1000,'2017-12-28'); Query OK, 1 row affected (0.15 sec) Display all records from the table using a select statement. The query is as follows − mysql> select *from OrderDemo; +---------+------------+---------------------+ | OrderId | OrderPrice | OrderDatetime | +---------+------------+---------------------+ | 1 | 200 | 2016-09-12 00:00:00 | | 2 | NULL | 2002-11-18 00:00:00 | | 3 | 1000 | 2017-12-28 00:00:00 | +---------+------------+---------------------+ 3 rows in set (0.00 sec) Here is the query to add a row in OrderPrice column where OrderPrice is NULL i.e. updating the NULL − mysql> update OrderDemo set OrderPrice = 6500 where OrderPrice IS NULL; Query OK, 1 row affected (0.17 sec) Rows matched: 1 Changed: 1 Warnings: 0 Now check the table record once again. The query is as follows − mysql> select *from OrderDemo; +---------+------------+---------------------+ | OrderId | OrderPrice | OrderDatetime | +---------+------------+---------------------+ | 1 | 200 | 2016-09-12 00:00:00 | | 2 | 6500 | 2002-11-18 00:00:00 | | 3 | 1000 | 2017-12-28 00:00:00 | +---------+------------+---------------------+ 3 rows in set (0.00 sec) The NULL value has been replaced with 6500.
[ { "code": null, "e": 1092, "s": 1062, "text": "Let us first create a table −" }, { "code": null, "e": 1282, "s": 1092, "text": "mysql> create table OrderDemo\n -> (\n -> OrderId int NOT NULL AUTO_INCREMENT PRIMARY KEY,\n -> OrderPrice int,\n -> OrderDatetime datetime\n -> );\nQuery OK, 0 rows affected (0.66 sec)" }, { "code": null, "e": 1375, "s": 1282, "text": "Now you can insert some records in the table using insert command. The query is as follows −" }, { "code": null, "e": 1728, "s": 1375, "text": "mysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(200,'2016-09-12');\nQuery OK, 1 row affected (0.24 sec)\nmysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(NULL,'2002-11-18');\nQuery OK, 1 row affected (0.26 sec)\nmysql> insert into OrderDemo(OrderPrice,OrderDatetime) values(1000,'2017-12-28');\nQuery OK, 1 row affected (0.15 sec)" }, { "code": null, "e": 1815, "s": 1728, "text": "Display all records from the table using a select statement. The query is as follows −" }, { "code": null, "e": 1846, "s": 1815, "text": "mysql> select *from OrderDemo;" }, { "code": null, "e": 2200, "s": 1846, "text": "+---------+------------+---------------------+\n| OrderId | OrderPrice | OrderDatetime |\n+---------+------------+---------------------+\n| 1 | 200 | 2016-09-12 00:00:00 |\n| 2 | NULL | 2002-11-18 00:00:00 |\n| 3 | 1000 | 2017-12-28 00:00:00 |\n+---------+------------+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2302, "s": 2200, "text": "Here is the query to add a row in OrderPrice column where OrderPrice is NULL i.e. updating the NULL −" }, { "code": null, "e": 2449, "s": 2302, "text": "mysql> update OrderDemo set OrderPrice = 6500 where OrderPrice IS NULL;\nQuery OK, 1 row affected (0.17 sec)\nRows matched: 1 Changed: 1 Warnings: 0" }, { "code": null, "e": 2514, "s": 2449, "text": "Now check the table record once again. The query is as follows −" }, { "code": null, "e": 2545, "s": 2514, "text": "mysql> select *from OrderDemo;" }, { "code": null, "e": 2899, "s": 2545, "text": "+---------+------------+---------------------+\n| OrderId | OrderPrice | OrderDatetime |\n+---------+------------+---------------------+\n| 1 | 200 | 2016-09-12 00:00:00 |\n| 2 | 6500 | 2002-11-18 00:00:00 |\n| 3 | 1000 | 2017-12-28 00:00:00 |\n+---------+------------+---------------------+\n3 rows in set (0.00 sec)" }, { "code": null, "e": 2943, "s": 2899, "text": "The NULL value has been replaced with 6500." } ]
jMeter - Regular Expressions
Regular expressions are used to search and manipulate text, based on patterns. JMeter interprets forms of regular expressions or patterns being used throughout a JMeter test plan, by including the pattern matching software Apache Jakarta ORO. With the use of regular expressions, we can certainly save a lot of time and achieve greater flexibility as we create or enhance a Test Plan. Regular expressions provide a simple method to get information from pages when it is impossible or very hard to predict an outcome. To use regular expressions in your test plan, you need to use the Regular Expression Extractor of JMeter. You can place regular expressions in any component in a Test Plan. It is worth stressing the difference between contains and matches, as used on the Response Assertion test element − contains means that the regular expression matched at least some part of the target, so 'alphabet' "contains" 'ph.b.' because the regular expression matches the substring 'phabe'. contains means that the regular expression matched at least some part of the target, so 'alphabet' "contains" 'ph.b.' because the regular expression matches the substring 'phabe'. matches means that the regular expression matched the whole target. Hence the 'alphabet' is "matched" by 'al.*t'. matches means that the regular expression matched the whole target. Hence the 'alphabet' is "matched" by 'al.*t'. Suppose you want to match the following portion of a web-page − name = "file" value = "readme.txt" And you want to extract readme.txt. A suitable regular expression would be − name = "file" value = "(.+?)"> The special characters above are − ( and ) − these enclose the portion of the match string to be returned ( and ) − these enclose the portion of the match string to be returned . − match any character . − match any character + − one or more times + − one or more times ? − stop when first match succeeds ? − stop when first match succeeds Let us understand the use of Regular expressions in the Regular Expression Extractor—a Post-Processor Element by writing a test plan. This element extracts text from the current page using a Regular Expression to identify the text pattern that a desired element conforms with. First we write an HTML page which a list of people and their email IDs. We deploy it to our tomcat server. The contents of html (index.html) are as follows − <html> <head> </head> <body> <table style = "border: 1px solid #000000;"> <th style = "border: 1px solid #000000;">ID</th> <th style = "border: 1px solid #000000;">name</th> <th style = "border: 1px solid #000000;">Email</th> <tr> <td id = "ID" style = "border: 1px solid #000000;">3</td> <td id = "Name" style = "border: 1px solid #000000;">Manisha</td> <td id = "Email" style = "border: 1px solid #000000;">[email protected]</td> </tr> <tr> <td id = "ID" style = "border: 1px solid #000000;">4</td> <td id = "Name" style = "border: 1px solid #000000;">joe</td> <td id = "Email" style = "border: 1px solid #000000;">[email protected]</td> </tr> </table> </body> </html> On deploying it on the tomcat server, this page would look like as shown in the following screenshot − In our test plan, we will select the person in the first row of the person table seen in the person list page above. To capture the ID of this person, let us first determine the pattern where we will find the person in the second row. As can be seen in the following snapshot, the ID of the second person is surrounded by <td id = "ID"> and </td >, and it is the second row of data having this pattern. We can use this to match the exact pattern that we want to extract information from. As we want to extract two pieces of information from this page, the person ID and the person name, the fields are defined as follows − Start JMeter, add a Thread group Test Plan → Add→ Threads(Users)→ Thread Group. Next add a sampler HTTP Request, select the test plan, right click Add → Sampler → HTTP Request and enter the details as shown below − Name − Manage Name − Manage Server Name or IP − localhost Server Name or IP − localhost Port Number − 8080 Port Number − 8080 Protocol − We will keep this blank, which means we want HTTP as the protocol. Protocol − We will keep this blank, which means we want HTTP as the protocol. Path − jmeter/index.html Path − jmeter/index.html Next, add a Regular Expression Extractor. Select the HTTP Request Sampler (Manage), right click Add → Post Processor → Regular Expression Extractor. The following table provides a description of the fields used in the above screenshot − Reference Name The name of the variable in which the extracted test will be stored (refname). Regular Expression The pattern against which the text to be extracted will be matched. The text groups that will extracted are enclosed by the characters '(' and ')'. We use '.+?' to indicate a single instance of the text enclosed by the <td..>..</td> tags. In our example the expression is − <td id = "ID">(+?)</td>\s*<td id = "Name">(+?)</td>\s* Template Each group of extracted text placed as a member of the variable Person, following the order of each group of pattern enclosed by '(' and ')'. Each group is stored as refname_g#, where refname is the string you entered as the reference name, and # is the group number. $1$ to refers to group 1, $2$ to refers to group 2, etc. $0$ refers to whatever the entire expression matches. In this example, the ID we extract is maintained in Person_g1, while the Name value is stored in Person_g2. Match No. Since we plan to extract only the second occurrence of this pattern, matching the second volunteer, we use value 2. Value 0 would make a random matching, while a negative value needs to be used with the ForEach Controller. Default If the item is not found, this will be the default value. This is an optional field. You may leave it blank. Add a listener to capture the result of this Test Plan. Right-click the Thread Group and select Add → Listener → View Results Tree option to add the listener. Save the test plan as reg_express_test.jmx and run the test. The output would be a success as shown in the following screenshot − 59 Lectures 9.5 hours Rahul Shetty 54 Lectures 13.5 hours Wallace Tauriac 23 Lectures 1.5 hours Anuja Jain 12 Lectures 1 hours Spotle Learn Print Add Notes Bookmark this page
[ { "code": null, "e": 2148, "s": 1905, "text": "Regular expressions are used to search and manipulate text, based on patterns. JMeter interprets forms of regular expressions or patterns being used throughout a JMeter test plan, by including the pattern matching software Apache Jakarta ORO." }, { "code": null, "e": 2422, "s": 2148, "text": "With the use of regular expressions, we can certainly save a lot of time and achieve greater flexibility as we create or enhance a Test Plan. Regular expressions provide a simple method to get information from pages when it is impossible or very hard to predict an outcome." }, { "code": null, "e": 2595, "s": 2422, "text": "To use regular expressions in your test plan, you need to use the Regular Expression Extractor of JMeter. You can place regular expressions in any component in a Test Plan." }, { "code": null, "e": 2711, "s": 2595, "text": "It is worth stressing the difference between contains and matches, as used on the Response Assertion test element −" }, { "code": null, "e": 2891, "s": 2711, "text": "contains means that the regular expression matched at least some part of the target, so 'alphabet' \"contains\" 'ph.b.' because the regular expression matches the substring 'phabe'." }, { "code": null, "e": 3071, "s": 2891, "text": "contains means that the regular expression matched at least some part of the target, so 'alphabet' \"contains\" 'ph.b.' because the regular expression matches the substring 'phabe'." }, { "code": null, "e": 3185, "s": 3071, "text": "matches means that the regular expression matched the whole target. Hence the 'alphabet' is \"matched\" by 'al.*t'." }, { "code": null, "e": 3299, "s": 3185, "text": "matches means that the regular expression matched the whole target. Hence the 'alphabet' is \"matched\" by 'al.*t'." }, { "code": null, "e": 3363, "s": 3299, "text": "Suppose you want to match the following portion of a web-page −" }, { "code": null, "e": 3400, "s": 3363, "text": "name = \"file\" value = \"readme.txt\" \n" }, { "code": null, "e": 3477, "s": 3400, "text": "And you want to extract readme.txt. A suitable regular expression would be −" }, { "code": null, "e": 3509, "s": 3477, "text": "name = \"file\" value = \"(.+?)\">\n" }, { "code": null, "e": 3544, "s": 3509, "text": "The special characters above are −" }, { "code": null, "e": 3615, "s": 3544, "text": "( and ) − these enclose the portion of the match string to be returned" }, { "code": null, "e": 3686, "s": 3615, "text": "( and ) − these enclose the portion of the match string to be returned" }, { "code": null, "e": 3710, "s": 3686, "text": ". − match any character" }, { "code": null, "e": 3734, "s": 3710, "text": ". − match any character" }, { "code": null, "e": 3756, "s": 3734, "text": "+ − one or more times" }, { "code": null, "e": 3778, "s": 3756, "text": "+ − one or more times" }, { "code": null, "e": 3813, "s": 3778, "text": "? − stop when first match succeeds" }, { "code": null, "e": 3848, "s": 3813, "text": "? − stop when first match succeeds" }, { "code": null, "e": 4125, "s": 3848, "text": "Let us understand the use of Regular expressions in the Regular Expression Extractor—a Post-Processor Element by writing a test plan. This element extracts text from the current page using a Regular Expression to identify the text pattern that a desired element conforms with." }, { "code": null, "e": 4283, "s": 4125, "text": "First we write an HTML page which a list of people and their email IDs. We deploy it to our tomcat server. The contents of html (index.html) are as follows −" }, { "code": null, "e": 5128, "s": 4283, "text": "<html>\n <head>\n </head>\n\t\n <body>\n <table style = \"border: 1px solid #000000;\">\n\t\t\n <th style = \"border: 1px solid #000000;\">ID</th>\n <th style = \"border: 1px solid #000000;\">name</th>\n <th style = \"border: 1px solid #000000;\">Email</th>\n\t\t\t\n <tr>\n <td id = \"ID\" style = \"border: 1px solid #000000;\">3</td>\n <td id = \"Name\" style = \"border: 1px solid #000000;\">Manisha</td>\n <td id = \"Email\" style = \"border: 1px solid #000000;\">[email protected]</td>\n </tr>\n\t\t\t\n <tr>\n <td id = \"ID\" style = \"border: 1px solid #000000;\">4</td>\n <td id = \"Name\" style = \"border: 1px solid #000000;\">joe</td>\n <td id = \"Email\" style = \"border: 1px solid #000000;\">[email protected]</td>\n </tr>\n\t\t\t\n </table>\n </body>\n</html>" }, { "code": null, "e": 5231, "s": 5128, "text": "On deploying it on the tomcat server, this page would look like as shown in the following screenshot −" }, { "code": null, "e": 5467, "s": 5231, "text": "In our test plan, we will select the person in the first row of the person table seen in the person list page above. To capture the ID of this person, let us first determine the pattern where we will find the person in the second row. " }, { "code": null, "e": 5855, "s": 5467, "text": "As can be seen in the following snapshot, the ID of the second person is surrounded by <td id = \"ID\"> and </td >, and it is the second row of data having this pattern. We can use this to match the exact pattern that we want to extract information from. As we want to extract two pieces of information from this page, the person ID and the person name, the fields are defined as follows −" }, { "code": null, "e": 5935, "s": 5855, "text": "Start JMeter, add a Thread group Test Plan → Add→ Threads(Users)→ Thread Group." }, { "code": null, "e": 6070, "s": 5935, "text": "Next add a sampler HTTP Request, select the test plan, right click Add → Sampler → HTTP Request and enter the details as shown below −" }, { "code": null, "e": 6084, "s": 6070, "text": "Name − Manage" }, { "code": null, "e": 6098, "s": 6084, "text": "Name − Manage" }, { "code": null, "e": 6128, "s": 6098, "text": "Server Name or IP − localhost" }, { "code": null, "e": 6158, "s": 6128, "text": "Server Name or IP − localhost" }, { "code": null, "e": 6177, "s": 6158, "text": "Port Number − 8080" }, { "code": null, "e": 6196, "s": 6177, "text": "Port Number − 8080" }, { "code": null, "e": 6274, "s": 6196, "text": "Protocol − We will keep this blank, which means we want HTTP as the protocol." }, { "code": null, "e": 6352, "s": 6274, "text": "Protocol − We will keep this blank, which means we want HTTP as the protocol." }, { "code": null, "e": 6377, "s": 6352, "text": "Path − jmeter/index.html" }, { "code": null, "e": 6402, "s": 6377, "text": "Path − jmeter/index.html" }, { "code": null, "e": 6551, "s": 6402, "text": "Next, add a Regular Expression Extractor. Select the HTTP Request Sampler (Manage), right click Add → Post Processor → Regular Expression Extractor." }, { "code": null, "e": 6639, "s": 6551, "text": "The following table provides a description of the fields used in the above screenshot −" }, { "code": null, "e": 6654, "s": 6639, "text": "Reference Name" }, { "code": null, "e": 6733, "s": 6654, "text": "The name of the variable in which the extracted test will be stored (refname)." }, { "code": null, "e": 6752, "s": 6733, "text": "Regular Expression" }, { "code": null, "e": 7081, "s": 6752, "text": "The pattern against which the text to be extracted will be matched. The text groups that will extracted are enclosed by the characters '(' and ')'. We use '.+?' to indicate a single instance of the text enclosed by the <td..>..</td> tags. In our example the expression is − <td id = \"ID\">(+?)</td>\\s*<td id = \"Name\">(+?)</td>\\s*" }, { "code": null, "e": 7090, "s": 7081, "text": "Template" }, { "code": null, "e": 7577, "s": 7090, "text": "Each group of extracted text placed as a member of the variable Person, following the order of each group of pattern enclosed by '(' and ')'. Each group is stored as refname_g#, where refname is the string you entered as the reference name, and # is the group number. $1$ to refers to group 1, $2$ to refers to group 2, etc. $0$ refers to whatever the entire expression matches. In this example, the ID we extract is maintained in Person_g1, while the Name value is stored in Person_g2." }, { "code": null, "e": 7587, "s": 7577, "text": "Match No." }, { "code": null, "e": 7810, "s": 7587, "text": "Since we plan to extract only the second occurrence of this pattern, matching the second volunteer, we use value 2. Value 0 would make a random matching, while a negative value needs to be used with the ForEach Controller." }, { "code": null, "e": 7818, "s": 7810, "text": "Default" }, { "code": null, "e": 7927, "s": 7818, "text": "If the item is not found, this will be the default value. This is an optional field. You may leave it blank." }, { "code": null, "e": 8086, "s": 7927, "text": "Add a listener to capture the result of this Test Plan. Right-click the Thread Group and select Add → Listener → View Results Tree option to add the listener." }, { "code": null, "e": 8216, "s": 8086, "text": "Save the test plan as reg_express_test.jmx and run the test. The output would be a success as shown in the following screenshot −" }, { "code": null, "e": 8251, "s": 8216, "text": "\n 59 Lectures \n 9.5 hours \n" }, { "code": null, "e": 8265, "s": 8251, "text": " Rahul Shetty" }, { "code": null, "e": 8301, "s": 8265, "text": "\n 54 Lectures \n 13.5 hours \n" }, { "code": null, "e": 8318, "s": 8301, "text": " Wallace Tauriac" }, { "code": null, "e": 8353, "s": 8318, "text": "\n 23 Lectures \n 1.5 hours \n" }, { "code": null, "e": 8365, "s": 8353, "text": " Anuja Jain" }, { "code": null, "e": 8398, "s": 8365, "text": "\n 12 Lectures \n 1 hours \n" }, { "code": null, "e": 8412, "s": 8398, "text": " Spotle Learn" }, { "code": null, "e": 8419, "s": 8412, "text": " Print" }, { "code": null, "e": 8430, "s": 8419, "text": " Add Notes" } ]
A Comprehensive Hands-on Guide to Transfer Learning with Real-World Applications in Deep Learning | by Dipanjan (DJ) Sarkar | Towards Data Science
Humans have an inherent ability to transfer knowledge across tasks. What we acquire as knowledge while learning about one task, we utilize in the same way to solve related tasks. The more related the tasks, the easier it is for us to transfer, or cross-utilize our knowledge. Some simple examples would be, Know how to ride a motorbike ⮫ Learn how to ride a car Know how to play classic piano ⮫ Learn how to play jazz piano Know math and statistics ⮫ Learn machine learning In each of the above scenarios, we don’t learn everything from scratch when we attempt to learn new aspects or topics. We transfer and leverage our knowledge from what we have learnt in the past! Conventional machine learning and deep learning algorithms, so far, have been traditionally designed to work in isolation. These algorithms are trained to solve specific tasks. The models have to be rebuilt from scratch once the feature-space distribution changes. Transfer learning is the idea of overcoming the isolated learning paradigm and utilizing knowledge acquired for one task to solve related ones. In this article, we will do a comprehensive coverage of the concepts, scope and real-world applications of transfer learning and even showcase some hands-on examples. To be more specific, we will be covering the following. Motivation for Transfer Learning Understanding Transfer Learning Transfer Learning Strategies Transfer Learning for Deep Learning Deep Transfer Learning Strategies Types of Deep Transfer Learning Applications of Transfer Learning Case Study 1: Image Classification with a Data Availability Constraint Case Study 2: Multi-Class Fine-grained Image Classification with Large Number of Classes and Less Data Availability Transfer Learning Advantages Transfer Learning Challenges Conclusion & Future Scope We will look at transfer learning as a general high-level concept which started right from the days of machine learning and statistical modeling, however, we will be more focused around deep learning in this article. Note: All the case studies will cover step by step details with code and outputs. The case studies depicted here and their results are purely based on actual experiments which we conducted when we implemented and tested these models while working on our book: Hands on Transfer Learning with Python (details at the end of this article). This article aims to be an attempt to cover theoretical concepts as well as demonstrate practical hands-on examples of deep learning applications in one place, given the information overload which is out there on the web. All examples will be covered in Python using keras with a tensorflow backend, a perfect match for people who are veterans or just getting started with deep learning! Interested in PyTorch? Feel free to convert these examples and contact me and I’ll feature your work here and on GitHub! We have already briefly discussed that humans don’t learn everything from the ground up and leverage and transfer their knowledge from previously learnt domains to newer domains and tasks. Given the craze for True Artificial General Intelligence, transfer learning is something which data scientists and researchers believe can further our progress towards AGI. In fact, Andrew Ng, renowned professor and data scientist, who has been associated with Google Brain, Baidu, Stanford and Coursera, recently gave an amazing tutorial in NIPS 2016 called ‘Nuts and bolts of building AI applications using Deep Learning’ where he mentioned, After supervised learning — Transfer Learning will be the next driver of ML commercial success I recommend interested folks to check out his interesting tutorial from NIPS 2016. In fact, transfer learning is not a concept which just cropped up in the 2010s. The Neural Information Processing Systems (NIPS) 1995 workshop Learning to Learn: Knowledge Consolidation and Transfer in Inductive Systems is believed to have provided the initial motivation for research in this field. Since then, terms such as Learning to Learn, Knowledge Consolidation, and Inductive Transfer have been used interchangeably with transfer learning. Invariably, different researchers and academic texts provide definitions from different contexts. In their famous book, Deep Learning, Goodfellow et al refer to transfer learning in the context of generalization. Their definition is as follows: Situation where what has been learned in one setting is exploited to improve generalization in another setting. Thus, the key motivation, especially considering the context of deep learning is the fact that most models which solve complex problems need a whole lot of data, and getting vast amounts of labeled data for supervised models can be really difficult, considering the time and effort it takes to label data points. A simple example would be the ImageNet dataset, which has millions of images pertaining to different categories, thanks to years of hard work starting at Stanford! However, getting such a dataset for every domain is tough. Besides, most deep learning models are very specialized to a particular domain or even a specific task. While these might be state-of-the-art models, with really high accuracy and beating all benchmarks, it would be only on very specific datasets and end up suffering a significant loss in performance when used in a new task which might still be similar to the one it was trained on. This forms the motivation for transfer learning, which goes beyond specific tasks and domains, and tries to see how to leverage knowledge from pre-trained models and use it to solve new problems! The first thing to remember here is that, transfer learning, is not a new concept which is very specific to deep learning. There is a stark difference between the traditional approach of building and training machine learning models, and using a methodology following transfer learning principles. Traditional learning is isolated and occurs purely based on specific tasks, datasets and training separate isolated models on them. No knowledge is retained which can be transferred from one model to another. In transfer learning, you can leverage knowledge (features, weights etc) from previously trained models for training newer models and even tackle problems like having less data for the newer task! Let’s understand the preceding explanation with the help of an example. Let’s assume our task is to identify objects in images within a restricted domain of a restaurant. Let’s mark this task in its defined scope as T1. Given the dataset for this task, we train a model and tune it to perform well (generalize) on unseen data points from the same domain (restaurant). Traditional supervised ML algorithms break down when we do not have sufficient training examples for the required tasks in given domains. Suppose, we now must detect objects from images in a park or a café (say, task T2). Ideally, we should be able to apply the model trained for T1, but in reality, we face performance degradation and models that do not generalize well. This happens for a variety of reasons, which we can liberally and collectively term as the model’s bias towards training data and domain. Transfer learning should enable us to utilize knowledge from previously learned tasks and apply them to newer, related ones. If we have significantly more data for task T1, we may utilize its learning, and generalize this knowledge (features, weights) for task T2 (which has significantly less data). In the case of problems in the computer vision domain, certain low-level features, such as edges, shapes, corners and intensity, can be shared across tasks, and thus enable knowledge transfer among tasks! Also, as we have depicted in the earlier figure, knowledge from an existing task acts as an additional input when learning a new target task. Let’s now take a look at a formal definition for transfer learning and then utilize it to understand different strategies. In their paper, A Survey on Transfer Learning, Pan and Yang use domain, task, and marginal probabilities to present a framework for understanding transfer learning. The framework is defined as follows: A domain, D, is defined as a two-element tuple consisting of feature space, ꭕ, and marginal probability, P(Χ), where Χ is a sample data point. Thus, we can represent the domain mathematically as D = {ꭕ, P(Χ)} Here xi represents a specific vector as represented in the above depiction. A task, T, on the other hand, can be defined as a two-element tuple of the label space, γ, and objective function, η. The objective function can also be denoted as P(γ| Χ) from a probabilistic view point. Thus, armed with these definitions and representations, we can define transfer learning as follows, thanks to an excellent article from Sebastian Ruder. Let’s now take a look at the typical scenarios involving transfer learning based on our previous definition. To give some more clarity on the difference between the terms domain and task, the following figure tries to explain them with some examples. Transfer learning, as we have seen so far, is having the ability to utilize existing knowledge from the source learner in the target task. During the process of transfer learning, the following three important questions must be answered: What to transfer: This is the first and the most important step in the whole process. We try to seek answers about which part of the knowledge can be transferred from the source to the target in order to improve the performance of the target task. When trying to answer this question, we try to identify which portion of knowledge is source-specific and what is common between the source and the target. When to transfer: There can be scenarios where transferring knowledge for the sake of it may make matters worse than improving anything (also known as negative transfer). We should aim at utilizing transfer learning to improve target task performance/results and not degrade them. We need to be careful about when to transfer and when not to. How to transfer: Once the what and when have been answered, we can proceed towards identifying ways of actually transferring the knowledge across domains/tasks. This involves changes to existing algorithms and different techniques, which we will cover in later sections of this article. Also, specific case studies are lined up in the end for a better understanding of how to transfer. This should help us define the various scenarios where transfer learning can be applied and possible techniques, which we will discuss in the next section. There are different transfer learning strategies and techniques, which can be applied based on the domain, task at hand, and the availability of data. I really like the following figure from the paper on transfer learning we mentioned earlier, A Survey on Transfer Learning. Thus, based on the previous figure, transfer learning methods can be categorized based on the type of traditional ML algorithms involved, such as: Inductive Transfer learning: In this scenario, the source and target domains are the same, yet the source and target tasks are different from each other. The algorithms try to utilize the inductive biases of the source domain to help improve the target task. Depending upon whether the source domain contains labeled data or not, this can be further divided into two subcategories, similar to multitask learning and self-taught learning, respectively. Unsupervised Transfer Learning: This setting is similar to inductive transfer itself, with a focus on unsupervised tasks in the target domain. The source and target domains are similar, but the tasks are different. In this scenario, labeled data is unavailable in either of the domains. Transductive Transfer Learning: In this scenario, there are similarities between the source and target tasks, but the corresponding domains are different. In this setting, the source domain has a lot of labeled data, while the target domain has none. This can be further classified into subcategories, referring to settings where either the feature spaces are different or the marginal probabilities. We can summarize the different settings and scenarios for each of the above techniques in the following table. The three transfer categories discussed in the previous section outline different settings where transfer learning can be applied, and studied in detail. To answer the question of what to transfer across these categories, some of the following approaches can be applied: Instance transfer: Reusing knowledge from the source domain to the target task is usually an ideal scenario. In most cases, the source domain data cannot be reused directly. Rather, there are certain instances from the source domain that can be reused along with target data to improve results. In case of inductive transfer, modifications such as AdaBoost by Dai and their co-authors help utilize training instances from the source domain for improvements in the target task. Feature-representation transfer: This approach aims to minimize domain divergence and reduce error rates by identifying good feature representations that can be utilized from the source to target domains. Depending upon the availability of labeled data, supervised or unsupervised methods may be applied for feature-representation-based transfers. Parameter transfer: This approach works on the assumption that the models for related tasks share some parameters or prior distribution of hyperparameters. Unlike multitask learning, where both the source and target tasks are learned simultaneously, for transfer learning, we may apply additional weightage to the loss of the target domain to improve overall performance. Relational-knowledge transfer: Unlike the preceding three approaches, the relational-knowledge transfer attempts to handle non-IID data, such as data that is not independent and identically distributed. In other words, data, where each data point has a relationship with other data points; for instance, social network data utilizes relational-knowledge-transfer techniques. The following table clearly summarizes the relationship between different transfer learning strategies and what to transfer. Let’s now utilize this understanding and learn how transfer learning is applied in the context of deep learning. The strategies we discussed in the previous section are general approaches which can be applied towards machine learning techniques, which brings us to the question, can transfer learning really be applied in the context of deep learning? Deep learning models are representative of what is also known as inductive learning. The objective for inductive-learning algorithms is to infer a mapping from a set of training examples. For instance, in cases of classification, the model learns mapping between input features and class labels. In order for such a learner to generalize well on unseen data, its algorithm works with a set of assumptions related to the distribution of the training data. These sets of assumptions are known as inductive bias. The inductive bias or assumptions can be characterized by multiple factors, such as the hypothesis space it restricts to and the search process through the hypothesis space. Thus, these biases impact how and what is learned by the model on the given task and domain. Inductive transfer techniques utilize the inductive biases of the source task to assist the target task. This can be done in different ways, such as by adjusting the inductive bias of the target task by limiting the model space, narrowing down the hypothesis space, or making adjustments to the search process itself with the help of knowledge from the source task. This process is depicted visually in the following figure. Apart from inductive transfer, inductive-learning algorithms also utilize Bayesian and Hierarchical transfer techniques to assist with improvements in the learning and performance of the target task. Deep learning has made considerable progress in recent years. This has enabled us to tackle complex problems and yield amazing results. However, the training time and the amount of data required for such deep learning systems are much more than that of traditional ML systems. There are various deep learning networks with state-of-the-art performance (sometimes as good or even better than human performance) that have been developed and tested across domains such as computer vision and natural language processing (NLP). In most cases, teams/people share the details of these networks for others to use. These pre-trained networks/models form the basis of transfer learning in the context of deep learning, or what I like to call ‘deep transfer learning’. Let’s look at the two most popular strategies for deep transfer learning. Deep learning systems and models are layered architectures that learn different features at different layers (hierarchical representations of layered features). These layers are then finally connected to a last layer (usually a fully connected layer, in the case of supervised learning) to get the final output. This layered architecture allows us to utilize a pre-trained network (such as Inception V3 or VGG) without its final layer as a fixed feature extractor for other tasks. The key idea here is to just leverage the pre-trained model’s weighted layers to extract features but not to update the weights of the model’s layers during training with new data for the new task. For instance, if we utilize AlexNet without its final classification layer, it will help us transform images from a new domain task into a 4096-dimensional vector based on its hidden states, thus enabling us to extract features from a new domain task, utilizing the knowledge from a source-domain task. This is one of the most widely utilized methods of performing transfer learning using deep neural networks. Now a question might arise, how well do these pre-trained off-the-shelf features really work in practice with different tasks? It definitely seems to work really well in real-world tasks, and if the chart in the above table is not very clear, the following figure should make things more clear with regard to their performance in different computer vision based tasks! Based on the red and pink bars in the above figure, you can clearly see that the features from the pre-trained models consistently out-perform very specialized task-focused deep learning models. This is a more involved technique, where we do not just replace the final layer (for classification/regression), but we also selectively retrain some of the previous layers. Deep neural networks are highly configurable architectures with various hyperparameters. As discussed earlier, the initial layers have been seen to capture generic features, while the later ones focus more on the specific task at hand. An example is depicted in the following figure on a face-recognition problem, where initial lower layers of the network learn very generic features and the higher layers learn very task-specific features. Using this insight, we may freeze (fix weights) certain layers while retraining, or fine-tune the rest of them to suit our needs. In this case, we utilize the knowledge in terms of the overall architecture of the network and use its states as the starting point for our retraining step. This, in turn, helps us achieve better performance with less training time. This brings us to the question, should we freeze layers in the network to use them as feature extractors or should we also fine-tune layers in the process? This should give us a good perspective on what each of these strategies are and when should they be used! One of the fundamental requirements for transfer learning is the presence of models that perform well on source tasks. Luckily, the deep learning world believes in sharing. Many of the state-of-the art deep learning architectures have been openly shared by their respective teams. These span across different domains, such as computer vision and NLP, the two most popular domains for deep learning applications. Pre-trained models are usually shared in the form of the millions of parameters/weights the model achieved while being trained to a stable state. Pre-trained models are available for everyone to use through different means. The famous deep learning Python library, keras, provides an interface to download some popular models. You can also access pre-trained models from the web since most of them have been open-sourced. For computer vision, you can leverage some popular models including, VGG-16 VGG-19 Inception V3 XCeption ResNet-50 For natural language processing tasks, things become more difficult due to the varied nature of NLP tasks. You can leverage word embedding models including, Word2Vec GloVe FastText But wait, that’s not all! Recently, there have been some excellent advancements towards transfer learning for NLP. Most notably, Universal Sentence Encoder by Google Bidirectional Encoder Representations from Transformers (BERT) by Google They definitely hold a lot of promise and I’m sure they will be widely adopted pretty soon for real-world applications. The literature on transfer learning has gone through a lot of iterations, and as mentioned at the start of this chapter, the terms associated with it have been used loosely and often interchangeably. Hence, it is sometimes confusing to differentiate between transfer learning, domain adaptation, and multi-task learning. Rest assured, these are all related and try to solve similar problems. In general, you should always think of transfer learning as a general concept or principle, where we will try to solve a target task using source task-domain knowledge. Domain adaption is usually referred to in scenarios where the marginal probabilities between the source and target domains are different, such as P(Xs) ≠ P(Xt). There is an inherent shift or drift in the data distribution of the source and target domains that requires tweaks to transfer the learning. For instance, a corpus of movie reviews labeled as positive or negative would be different from a corpus of product-review sentiments. A classifier trained on movie-review sentiment would see a different distribution if utilized to classify product reviews. Thus, domain adaptation techniques are utilized in transfer learning in these scenarios. We learned different transfer learning strategies and even discussed the three questions of what, when, and how to transfer knowledge from the source to the target. In particular, we discussed how feature-representation transfer can be useful. It is worth re-iterating that different layers in a deep learning network capture different sets of features. We can utilize this fact to learn domain-invariant features and improve their transferability across domains. Instead of allowing the model to learn any representation, we nudge the representations of both domains to be as similar as possible. This can be achieved by applying certain pre-processing steps directly to the representations themselves. Some of these have been discussed by Baochen Sun, Jiashi Feng, and Kate Saenko in their paper ‘Return of Frustratingly Easy Domain Adaptation’. This nudge toward the similarity of representation has also been presented by Ganin et. al. in their paper, ‘Domain-Adversarial Training of Neural Networks’. The basic idea behind this technique is to add another objective to the source model to encourage similarity by confusing the domain itself, hence domain confusion. Multitask learning is a slightly different flavor of the transfer learning world. In the case of multitask learning, several tasks are learned simultaneously without distinction between the source and targets. In this case, the learner receives information about multiple tasks at once, as compared to transfer learning, where the learner initially has no idea about the target task. This is depicted in the following figure. Deep learning systems are data-hungry by nature, such that they need many training examples to learn the weights. This is one of the limiting aspects of deep neural networks, though such is not the case with human learning. For instance, once a child is shown what an apple looks like, they can easily identify a different variety of apple (with one or a few training examples); this is not the case with ML and deep learning algorithms. One-shot learning is a variant of transfer learning, where we try to infer the required output based on just one or a few training examples. This is essentially helpful in real-world scenarios where it is not possible to have labeled data for every possible class (if it is a classification task), and in scenarios where new classes can be added often. The landmark paper by Fei-Fei and their co-authors, ‘One Shot Learning of Object Categories’, is supposedly what coined the term one-shot learning and the research in this sub-field. This paper presented a variation on a Bayesian framework for representation learning for object categorization. This approach has since been improved upon, and applied using deep learning systems. Zero-shot learning is another extreme variant of transfer learning, which relies on no labeled examples to learn a task. This might sound unbelievable, especially when learning using examples is what most supervised learning algorithms are about. Zero-data learning or zero-short learning methods, make clever adjustments during the training stage itself to exploit additional information to understand unseen data. In their book on Deep Learning, Goodfellow and their co-authors present zero-shot learning as a scenario where three variables are learned, such as the traditional input variable, x, the traditional output variable, y, and the additional random variable that describes the task, T. The model is thus trained to learn the conditional probability distribution of P(y | x, T). Zero-shot learning comes in handy in scenarios such as machine translation, where we may not even have labels in the target language. Deep learning is definitely one of the specific categories of algorithms that has been utilized to reap the benefits of transfer learning very successfully. The following are a few examples: Transfer learning for NLP: Textual data presents all sorts of challenges when it comes to ML and deep learning. These are usually transformed or vectorized using different techniques. Embeddings, such as Word2vec and FastText, have been prepared using different training datasets. These are utilized in different tasks, such as sentiment analysis and document classification, by transferring the knowledge from the source tasks. Besides this, newer models like the Universal Sentence Encoder and BERT definitely present a myriad of possibilities for the future. Transfer learning for Audio/Speech: Similar to domains like NLP and Computer Vision, deep learning has been successfully used for tasks based on audio data. For instance, Automatic Speech Recognition (ASR) models developed for English have been successfully used to improve speech recognition performance for other languages, such as German. Also, automated-speaker identification is another example where transfer learning has greatly helped. Transfer learning for Computer Vision: Deep learning has been quite successfully utilized for various computer vision tasks, such as object recognition and identification, using different CNN architectures. In their paper, How transferable are features in deep neural networks, Yosinski and their co-authors (https://arxiv.org/abs/1411.1792) present their findings on how the lower layers act as conventional computer-vision feature extractors, such as edge detectors, while the final layers work toward task-specific features. Thus, these findings have helped in utilizing existing state-of-the-art models, such as VGG, AlexNet, and Inceptions, for target tasks, such as style transfer and face detection, that were different from what these models were trained for initially. Let’s explore some real-world case studies now and build some deep transfer learning models! In this simple case study, will be working on an image categorization problem with the constraint of having a very small number of training samples per category. The dataset for our problem is available on Kaggle and is one of the most popular computer vision based datasets out there. The dataset that we will be using, comes from the very popular Dogs vs. Cats Challenge, where our primary objective is to build a deep learning model that can successfully recognize and categorize images into either a cat or a dog. In terms of ML, this is a binary classification problem based on images. Before getting started, I would like to thank Francois Chollet for not only creating the amazing deep learning framework, keras, but also for talking about the real-world problem where transfer learning is effective in his book, ‘Deep Learning with Python’. I’ve have taken that as an inspiration to portray the true power of transfer learning in this chapter, and all results are based on building and running each model in my own GPU-based cloud setup (AWS p2.x) To start, download the train.zip file from the dataset page and store it in your local system. Once downloaded, unzip it into a folder. This folder will contain 25,000 images of dogs and cats; that is, 12,500 images per category. While we can use all 25,000 images and build some nice models on them, if you remember, our problem objective includes the added constraint of having a small number of images per category. Let’s build our own dataset for this purpose. import globimport numpy as npimport osimport shutilnp.random.seed(42) Let’s now load up all the images in our original training data folder as follows: (12500, 12500) We can verify with the preceding output that we have 12,500 images for each category. Let’s now build our smaller dataset, so that we have 3,000 images for training, 1,000 images for validation, and 1,000 images for our test dataset (with equal representation for the two animal categories). Cat datasets: (1500,) (500,) (500,)Dog datasets: (1500,) (500,) (500,) Now that our datasets have been created, let’s write them out to our disk in separate folders, so that we can come back to them anytime in the future without worrying if they are present in our main memory. Since this is an image categorization problem, we will be leveraging CNN models or ConvNets to try and tackle this problem. We will start by building simple CNN models from scratch, then try to improve using techniques such as regularization and image augmentation. Then, we will try and leverage pre-trained models to unleash the true power of transfer learning! Before we jump into modeling, let’s load and prepare our datasets. To start with, we load up some basic dependencies. import globimport numpy as npimport matplotlib.pyplot as pltfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img%matplotlib inline Let’s now load our datasets, using the following code snippet. Train dataset shape: (3000, 150, 150, 3) Validation dataset shape: (1000, 150, 150, 3) We can clearly see that we have 3000 training images and 1000 validation images. Each image is of size 150 x 150 and has three channels for red, green, and blue (RGB), hence giving each image the (150, 150, 3) dimensions. We will now scale each image with pixel values between (0, 255) to values between (0, 1) because deep learning models work really well with small input values. The preceding output shows one of the sample images from our training dataset. Let’s now set up some basic configuration parameters and also encode our text class labels into numeric values (otherwise, Keras will throw an error). ['cat', 'cat', 'cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'dog', 'dog'] [0 0 0 0 0 1 1 1 1 1] We can see that our encoding scheme assigns the number 0 to the cat labels and 1 to the dog labels. We are now ready to build our first CNN-based deep learning model. We will start by building a basic CNN model with three convolutional layers, coupled with max pooling for auto-extraction of features from our images and also downsampling the output convolution feature maps. We assume you have enough knowledge about CNNs and hence, won’t cover theoretical details. Feel free to refer to my book or any other resources on the web which explain convolutional neural networks! Let’s leverage Keras and build our CNN model architecture now. The preceding output shows us our basic CNN model summary. Just like we mentioned before, we are using three convolutional layers for feature extraction. The flatten layer is used to flatten out 128 of the 17 x 17 feature maps that we get as output from the third convolution layer. This is fed to our dense layers to get the final prediction of whether the image should be a dog (1) or a cat (0). All of this is part of the model training process, so let’s train our model using the following snippet which leverages the fit(...) function. The following terminology is very important with regard to training our model: The batch_size indicates the total number of images passed to the model per iteration. The weights of the units in layers are updated after each iteration. The total number of iterations is always equal to the total number of training samples divided by the batch_size An epoch is when the complete dataset has passed through the network once, that is, all the iterations are completed based on data batches. We use a batch_size of 30 and our training data has a total of 3,000 samples, which indicates that there will be a total of 100 iterations per epoch. We train the model for a total of 30 epochs and validate it consequently on our validation set of 1,000 images. Train on 3000 samples, validate on 1000 samplesEpoch 1/303000/3000 - 10s - loss: 0.7583 - acc: 0.5627 - val_loss: 0.7182 - val_acc: 0.5520Epoch 2/303000/3000 - 8s - loss: 0.6343 - acc: 0.6533 - val_loss: 0.5891 - val_acc: 0.7190......Epoch 29/303000/3000 - 8s - loss: 0.0314 - acc: 0.9950 - val_loss: 2.7014 - val_acc: 0.7140Epoch 30/303000/3000 - 8s - loss: 0.0147 - acc: 0.9967 - val_loss: 2.4963 - val_acc: 0.7220 Looks like our model is kind of overfitting, based on the training and validation accuracy values. We can plot our model accuracy and errors using the following snippet to get a better perspective. You can clearly see that after 2–3 epochs the model starts overfitting on the training data. The average accuracy we get in our validation set is around 72%, which is not a bad start! Can we improve upon this model? Let’s improve upon our base CNN model by adding in one more convolution layer, another dense hidden layer. Besides this, we will add dropout of 0.3 after each hidden dense layer to enable regularization. Basically, dropout is a powerful method of regularizing in deep neural nets. It can be applied separately to both input layers and the hidden layers. Dropout randomly masks the outputs of a fraction of units from a layer by setting their output to zero (in our case, it is 30% of the units in our dense layers). Train on 3000 samples, validate on 1000 samplesEpoch 1/303000/3000 - 7s - loss: 0.6945 - acc: 0.5487 - val_loss: 0.7341 - val_acc: 0.5210Epoch 2/303000/3000 - 7s - loss: 0.6601 - acc: 0.6047 - val_loss: 0.6308 - val_acc: 0.6480......Epoch 29/303000/3000 - 7s - loss: 0.0927 - acc: 0.9797 - val_loss: 1.1696 - val_acc: 0.7380Epoch 30/303000/3000 - 7s - loss: 0.0975 - acc: 0.9803 - val_loss: 1.6790 - val_acc: 0.7840 You can clearly see from the preceding outputs that we still end up overfitting the model, though it takes slightly longer and we also get a slightly better validation accuracy of around 78%, which is decent but not amazing. The reason for model overfitting is because we have much less training data and the model keeps seeing the same instances over time across each epoch. A way to combat this would be to leverage an image augmentation strategy to augment our existing training data with images that are slight variations of the existing images. We will cover this in detail in the following section. Let’s save this model for the time being so we can use it later to evaluate its performance on the test data. model.save(‘cats_dogs_basic_cnn.h5’) Let’s improve upon our regularized CNN model by adding in more data using a proper image augmentation strategy. Since our previous model was trained on the same small sample of data points each time, it wasn’t able to generalize well and ended up overfitting after a few epochs. The idea behind image augmentation is that we follow a set process of taking in existing images from our training dataset and applying some image transformation operations to them, such as rotation, shearing, translation, zooming, and so on, to produce new, altered versions of existing images. Due to these random transformations, we don’t get the same images each time, and we will leverage Python generators to feed in these new images to our model during training. The Keras framework has an excellent utility called ImageDataGenerator that can help us in doing all the preceding operations. Let’s initialize two of the data generators for our training and validation datasets. There are a lot of options available in ImageDataGenerator and we have just utilized a few of them. Feel free to check out the documentation to get a more detailed perspective. In our training data generator, we take in the raw images and then perform several transformations on them to generate new images. These include the following. Zooming the image randomly by a factor of 0.3 using the zoom_range parameter. Rotating the image randomly by 50 degrees using the rotation_range parameter. Translating the image randomly horizontally or vertically by a 0.2 factor of the image’s width or height using the width_shift_range and the height_shift_range parameters. Applying shear-based transformations randomly using the shear_range parameter. Randomly flipping half of the images horizontally using the horizontal_flip parameter. Leveraging the fill_mode parameter to fill in new pixels for images after we apply any of the preceding operations (especially rotation or translation). In this case, we just fill in the new pixels with their nearest surrounding pixel values. Let’s see how some of these generated images might look so that you can understand them better. We will take two sample images from our training dataset to illustrate the same. The first image is an image of a cat. You can clearly see in the previous output that we generate a new version of our training image each time (with translations, rotations, and zoom) and also we assign a label of cat to it so that the model can extract relevant features from these images and also remember that these are cats. Let’s look at how image augmentation works on a sample dog image now. This shows us how image augmentation helps in creating new images, and how training a model on them should help in combating overfitting. Remember for our validation generator, we just need to send the validation images (original ones) to the model for evaluation; hence, we just scale the image pixels (between 0–1) and do not apply any transformations. We just apply image augmentation transformations only on our training images. Let’s now train a CNN model with regularization using the image augmentation data generators we created. We will use the same model architecture from before. We reduce the default learning rate by a factor of 10 here for our optimizer to prevent the model from getting stuck in a local minima or overfit, as we will be sending a lot of images with random transformations. To train the model, we need to slightly modify our approach now, since we are using data generators. We will leverage the fit_generator(...) function from Keras to train this model. The train_generator generates 30 images each time, so we will use the steps_per_epoch parameter and set it to 100 to train the model on 3,000 randomly generated images from the training data for each epoch. Our val_generator generates 20 images each time so we will set the validation_steps parameter to 50 to validate our model accuracy on all the 1,000 validation images (remember we are not augmenting our validation dataset). Epoch 1/100100/100 - 12s - loss: 0.6924 - acc: 0.5113 - val_loss: 0.6943 - val_acc: 0.5000Epoch 2/100100/100 - 11s - loss: 0.6855 - acc: 0.5490 - val_loss: 0.6711 - val_acc: 0.5780Epoch 3/100100/100 - 11s - loss: 0.6691 - acc: 0.5920 - val_loss: 0.6642 - val_acc: 0.5950......Epoch 99/100100/100 - 11s - loss: 0.3735 - acc: 0.8367 - val_loss: 0.4425 - val_acc: 0.8340Epoch 100/100100/100 - 11s - loss: 0.3733 - acc: 0.8257 - val_loss: 0.4046 - val_acc: 0.8200 We get a validation accuracy jump to around 82%, which is almost 4–5% better than our previous model. Also, our training accuracy is very similar to our validation accuracy, indicating our model isn’t overfitting anymore. The following depict the model accuracy and loss per epoch. While there are some spikes in the validation accuracy and loss, overall, we see that it is much closer to the training accuracy, with the loss indicating that we obtained a model that generalizes much better as compared to our previous models. Let’s save this model now so we can evaluate it later on our test dataset. model.save(‘cats_dogs_cnn_img_aug.h5’) We will now try and leverage the power of transfer learning to see if we can build a better model! Pre-trained models are used in the following two popular ways when building new models or reusing them: Using a pre-trained model as a feature extractor Fine-tuning the pre-trained model We will cover both of them in detail in this section. The pre-trained model that we will be using in this chapter is the popular VGG-16 model, created by the Visual Geometry Group at the University of Oxford, which specializes in building very deep convolutional networks for large-scale visual recognition. A pre-trained model like the VGG-16 is an already pre-trained model on a huge dataset (ImageNet) with a lot of diverse image categories. Considering this fact, the model should have learned a robust hierarchy of features, which are spatial, rotation, and translation invariant with regard to features learned by CNN models. Hence, the model, having learned a good representation of features for over a million images belonging to 1,000 different categories, can act as a good feature extractor for new images suitable for computer vision problems. These new images might never exist in the ImageNet dataset or might be of totally different categories, but the model should still be able to extract relevant features from these images. This gives us an advantage of using pre-trained models as effective feature extractors for new images, to solve diverse and complex computer vision tasks, such as solving our cat versus dog classifier with fewer images, or even building a dog breed classifier, a facial expression classifier, and much more! Let’s briefly discuss the VGG-16 model architecture before unleashing the power of transfer learning on our problem. The VGG-16 model is a 16-layer (convolution and fully connected) network built on the ImageNet database, which is built for the purpose of image recognition and classification. This model was built by Karen Simonyan and Andrew Zisserman and is mentioned in their paper titled ‘Very Deep Convolutional Networks for Large-Scale Image Recognition’. I recommend all interested readers to go and read up on the excellent literature in this paper. The architecture of the VGG-16 model is depicted in the following figure. You can clearly see that we have a total of 13 convolution layers using 3 x 3 convolution filters along with max pooling layers for downsampling and a total of two fully connected hidden layers of 4096 units in each layer followed by a dense layer of 1000 units, where each unit represents one of the image categories in the ImageNet database. We do not need the last three layers since we will be using our own fully connected dense layers to predict whether images will be a dog or a cat. We are more concerned with the first five blocks, so that we can leverage the VGG model as an effective feature extractor. For one of the models, we will use it as a simple feature extractor by freezing all the five convolution blocks to make sure their weights don’t get updated after each epoch. For the last model, we will apply fine-tuning to the VGG model, where we will unfreeze the last two blocks (Block 4 and Block 5) so that their weights get updated in each epoch (per batch of data) as we train our own model. We represent the preceding architecture, along with the two variants (basic feature extractor and fine-tuning) that we will be using, in the following block diagram, so you can get a better visual perspective. Thus, we are mostly concerned with leveraging the convolution blocks of the VGG-16 model and then flattening the final output (from the feature maps) so that we can feed it into our own dense layers for our classifier. Let’s leverage Keras, load up the VGG-16 model, and freeze the convolution blocks so that we can use it as just an image feature extractor. It is quite clear from the preceding output that all the layers of the VGG-16 model are frozen, which is good, because we don’t want their weights to change during model training. The last activation feature map in the VGG-16 model (output from block5_pool) gives us the bottleneck features, which can then be flattened and fed to a fully connected deep neural network classifier. The following snippet shows what the bottleneck features look like for a sample image from our training data. bottleneck_feature_example = vgg.predict(train_imgs_scaled[0:1])print(bottleneck_feature_example.shape)plt.imshow(bottleneck_feature_example[0][:,:,0]) We flatten the bottleneck features in the vgg_model object to make them ready to be fed to our fully connected classifier. A way to save time in model training is to use this model and extract out all the features from our training and validation datasets and then feed them as inputs to our classifier. Let’s extract out the bottleneck features from our training and validation sets now. Train Bottleneck Features: (3000, 8192) Validation Bottleneck Features: (1000, 8192) The preceding output tells us that we have successfully extracted the flattened bottleneck features of dimension 1 x 8192 for our 3,000 training images and our 1,000 validation images. Let’s build the architecture of our deep neural network classifier now, which will take these features as input. Just like we mentioned previously, bottleneck feature vectors of size 8192 serve as input to our classification model. We use the same architecture as our previous models here with regard to the dense layers. Let’s train this model now. Train on 3000 samples, validate on 1000 samplesEpoch 1/303000/3000 - 1s 373us/step - loss: 0.4325 - acc: 0.7897 - val_loss: 0.2958 - val_acc: 0.8730Epoch 2/303000/3000 - 1s 286us/step - loss: 0.2857 - acc: 0.8783 - val_loss: 0.3294 - val_acc: 0.8530Epoch 3/303000/3000 - 1s 289us/step - loss: 0.2353 - acc: 0.9043 - val_loss: 0.2708 - val_acc: 0.8700......Epoch 29/303000/3000 - 1s 287us/step - loss: 0.0121 - acc: 0.9943 - val_loss: 0.7760 - val_acc: 0.8930Epoch 30/303000/3000 - 1s 287us/step - loss: 0.0102 - acc: 0.9987 - val_loss: 0.8344 - val_acc: 0.8720 We get a model with a validation accuracy of close to 88%, almost a 5–6% improvement from our basic CNN model with image augmentation, which is excellent. The model does seem to be overfitting though. There is a decent gap between the model train and validation accuracy after the fifth epoch, which kind of makes it clear that the model is overfitting on the training data after that. But overall, this seems to be the best model so far. Let’s try using our image augmentation strategy on this model. Before that, we save this model to disk using the following code. model.save('cats_dogs_tlearn_basic_cnn.h5') We will leverage the same data generators for our train and validation datasets that we used before. The code for building them is depicted as follows for ease of understanding. Let’s now build our deep learning model and train it. We won’t extract the bottleneck features like last time since we will be training on data generators; hence, we will be passing the vgg_model object as an input to our own model. We bring the learning rate slightly down since we will be training for 100 epochs and don’t want to make any sudden abrupt weight adjustments to our model layers. Do remember that the VGG-16 model’s layers are still frozen here, and we are still using it as a basic feature extractor only. Epoch 1/100100/100 - 45s 449ms/step - loss: 0.6511 - acc: 0.6153 - val_loss: 0.5147 - val_acc: 0.7840Epoch 2/100100/100 - 41s 414ms/step - loss: 0.5651 - acc: 0.7110 - val_loss: 0.4249 - val_acc: 0.8180Epoch 3/100100/100 - 41s 415ms/step - loss: 0.5069 - acc: 0.7527 - val_loss: 0.3790 - val_acc: 0.8260......Epoch 99/100100/100 - 42s 417ms/step - loss: 0.2656 - acc: 0.8907 - val_loss: 0.2757 - val_acc: 0.9050Epoch 100/100100/100 - 42s 418ms/step - loss: 0.2876 - acc: 0.8833 - val_loss: 0.2665 - val_acc: 0.9000 We can see that our model has an overall validation accuracy of 90%, which is a slight improvement from our previous model, and also the train and validation accuracy are quite close to each other, indicating that the model is not overfitting. Let’s save this model on the disk now for future evaluation on the test data. model.save(‘cats_dogs_tlearn_img_aug_cnn.h5’) We will now fine-tune the VGG-16 model to build our last classifier, where we will unfreeze blocks 4 and 5, as we depicted in our block diagram earlier. We will now leverage our VGG-16 model object stored in the vgg_model variable and unfreeze convolution blocks 4 and 5 while keeping the first three blocks frozen. The following code helps us achieve this. You can clearly see from the preceding output that the convolution and pooling layers pertaining to blocks 4 and 5 are now trainable. This means the weights for these layers will also get updated with backpropagation in each epoch as we pass each batch of data. We will use the same data generators and model architecture as our previous model and train our model. We reduce the learning rate slightly, since we don’t want to get stuck at any local minimal, and we also do not want to suddenly update the weights of the trainable VGG-16 model layers by a big factor that might adversely affect the model. Epoch 1/100100/100 - 64s 642ms/step - loss: 0.6070 - acc: 0.6547 - val_loss: 0.4029 - val_acc: 0.8250Epoch 2/100100/100 - 63s 630ms/step - loss: 0.3976 - acc: 0.8103 - val_loss: 0.2273 - val_acc: 0.9030Epoch 3/100100/100 - 63s 631ms/step - loss: 0.3440 - acc: 0.8530 - val_loss: 0.2221 - val_acc: 0.9150......Epoch 99/100100/100 - 63s 629ms/step - loss: 0.0243 - acc: 0.9913 - val_loss: 0.2861 - val_acc: 0.9620Epoch 100/100100/100 - 63s 629ms/step - loss: 0.0226 - acc: 0.9930 - val_loss: 0.3002 - val_acc: 0.9610 We can see from the preceding output that our model has obtained a validation accuracy of around 96%, which is a 6% improvement from our previous model. Overall, this model has gained a 24% improvement in validation accuracy from our first basic CNN model. This really shows how useful transfer learning can be. We can see that accuracy values are really excellent here, and although the model looks like it might be slightly overfitting on the training data, we still get great validation accuracy. Let’s save this model to disk now using the following code. model.save('cats_dogs_tlearn_finetune_img_aug_cnn.h5') Let’s now put all our models to the test by actually evaluating their performance on our test dataset. We will now evaluate the five different models that we built so far, by first testing them on our test dataset, because just validation is not enough! We have also built a nifty utility module called model_evaluation_utils, which we will be using to evaluate the performance of our deep learning models. Let's load up the necessary dependencies and our saved models before getting started. It’s time now for the final test, where we literally test the performance of our models by making predictions on our test dataset. Let’s load up and prepare our test dataset first before we try making predictions. Test dataset shape: (1000, 150, 150, 3)['dog', 'dog', 'dog', 'dog', 'dog'] [1, 1, 1, 1, 1] Now that we have our scaled dataset ready, let’s evaluate each model by making predictions for all the test images, and then evaluate the model performance by checking how accurate are the predictions. We can see that we definitely have some interesting results. Each subsequent model performs better than the previous model, which is expected, since we tried more advanced techniques with each new model. Our worst model is our basic CNN model, with a model accuracy and F1-score of around 78%, and our best model is our fine-tuned model with transfer learning and image augmentation, which gives us a model accuracy and F1-score of 96%, which is really amazing considering we trained our model from our 3,000 image training dataset. Let’s plot the ROC curves of our worst and best models now. This should give you a good idea of how much of a difference pre-trained models and transfer learning can make, especially in tackling complex problems when we have constraints like less data. We encourage you to try out similar strategies with your own data! Now in this case study, let us level up the game and make the task of image classification even more exciting. We built a simple binary classification model in the previous case study (albeit we used some complex techniques for solving the small data constraint problem!). In this case-study, we will be concentrating toward the task of fine-grained image classification. Unlike usual image classification tasks, fine-grained image classification refers to the task of recognizing different sub-classes within a higher-level class. To help understand this task better, we will be focusing our discussion around the Stanford Dogs dataset. This dataset, as the name suggests, contains images of different dog breeds. In this case, the task is to identify each of those dog breeds. Hence, the high-level concept is the dog itself, while the task is to categorize different subconcepts or subclasses — in this case, breeds — correctly. We will be leveraging the dataset available through Kaggle available here. We will only be using the train dataset since it has labeled data. This dataset contains around 10,000 labeled images of 120 different dog breeds. Thus our task is to build a fine-grained 120-class classification model to categorize 120 different dog breeds. Definitely challenging! Let’s take a look at how our dataset looks like by loading the data and viewing a sample batch of images. From the preceding grid, we can see that there is a lot of variation, in terms of resolution, lighting, zoom levels, and so on, available along with the fact that images do not just contain just a single dog but other dogs and surrounding items as well. This is going to be a challenge! Let’s start by looking at how the dataset labels look like to get an idea of what we are dealing with. data_labels = pd.read_csv('labels/labels.csv')target_labels = data_labels['breed']print(len(set(target_labels)))data_labels.head()------------------120 What we do next is to add in the exact image path for each image present in the disk using the following code. This will help us in easily locating and loading up the images during model training. It’s now time to prepare our train, test and validation datasets. We will leverage the following code to help us build these datasets! Initial Dataset Size: (10222, 299, 299, 3)Initial Train and Test Datasets Size: (7155, 299, 299, 3) (3067, 299, 299, 3)Train and Validation Datasets Size: (6081, 299, 299, 3) (1074, 299, 299, 3)Train, Test and Validation Datasets Size: (6081, 299, 299, 3) (3067, 299, 299, 3) (1074, 299, 299, 3) We also need to convert the text class labels to one-hot encoded labels, else our model will not run. ((6081, 120), (3067, 120), (1074, 120)) Everything looks to be in order. Now, if you remember from the previous case study, image augmentation is a great way to deal with having less data per class. In this case, we have a total of 10222 samples and 120 classes. This means, an average of only 85 images per class! We do this using the ImageDataGenerator utility from keras. Now that we have our data ready, the next step is to actually build our deep learning model! Now that our datasets are ready, let’s get started with the modeling process. We already know how to build a deep convolutional network from scratch. We also understand the amount of fine-tuning required to achieve good performance. For this task, we will be utilizing concepts of transfer learning. A pre-trained model is the basic ingredient required to begin with the task of transfer learning. In this case study, we will concentrate on utilizing a pre-trained model as a feature extractor. We know, a deep learning model is basically a stacking of interconnected layers of neurons, with the final one acting as a classifier. This architecture enables deep neural networks to capture different features at different levels in the network. Thus, we can utilize this property to use them as feature extractors. This is made possible by removing the final layer or using the output from the penultimate layer. This output from the penultimate layer is then fed into an additional set of layers, followed by a classification layer. We will be using the Inception V3 Model from Google as our pre-trained model. Based on the previous output, you can clearly see that the Inception V3 model is huge with a lot of layers and parameters. Let’s start training our model now. We train the model using the fit_generator(...) method to leverage the data augmentation prepared in the previous step. We set the batch size to 32, and train the model for 15 epochs. Epoch 1/15190/190 - 155s 816ms/step - loss: 4.1095 - acc: 0.2216 - val_loss: 2.6067 - val_acc: 0.5748Epoch 2/15190/190 - 159s 836ms/step - loss: 2.1797 - acc: 0.5719 - val_loss: 1.0696 - val_acc: 0.7377Epoch 3/15190/190 - 155s 815ms/step - loss: 1.3583 - acc: 0.6814 - val_loss: 0.7742 - val_acc: 0.7888......Epoch 14/15190/190 - 156s 823ms/step - loss: 0.6686 - acc: 0.8030 - val_loss: 0.6745 - val_acc: 0.7955Epoch 15/15190/190 - 161s 850ms/step - loss: 0.6276 - acc: 0.8194 - val_loss: 0.6579 - val_acc: 0.8144 The model achieves a commendable performance of more than 80% accuracy on both train and validation sets within just 15 epochs. The plot on the right-hand side shows how quickly the loss drops and converges to around 0.5. This is a clear example of how powerful, yet simple, transfer learning can be. Training and validation performance is pretty good, but how about performance on unseen data? Since we already divided our original dataset into three separate portions. The important thing to remember here is that the test dataset has to undergo similar pre-processing as the training dataset. To account for this, we scale the test dataset as well, before feeding it into the function. Accuracy: 0.864Precision: 0.8783Recall: 0.864F1 Score: 0.8591 The model achieves an amazing 86% accuracy as well as F1-score on the test dataset. Given that we just trained for 15 epochs with minimal inputs from our side, transfer learning helped us achieve a pretty decent classifier. We can also check the per-class classification metrics using the following code. We can also visualize model predictions in a visually appealing way using the following code. The preceding image presents a visual proof of the model’s performance. As we can see, in most of the cases, the model is not only predicting the correct dog breed, it also does so with very high confidence. We have already covered several advantages of transfer learning in some way or the other in the previous sections. Typically transfer learning enables us to build more robust models which can perform a wide variety of tasks. Helps solve complex real-world problems with several constraints Tackle problems like having little or almost no labeled data availability Ease of transfering knowledge from one model to another based on domains and tasks Provides a path towards achieving Artificial General Intelligence some day in the future! Transfer learning has immense potential and is a commonly required enhancement for existing learning algorithms. Yet, there are certain pertinent issues related to transfer learning that need more research and exploration. Apart from the difficulty of answering the questions of what, when, and how to transfer, negative transfer and transfer bounds present major challenges. Negative Transfer: The cases we have discussed so far talk about improvements in target tasks based on knowledge transfer from the source task. There are cases when transfer learning can lead to a drop in performance. Negative transfer refers to scenarios where the transfer of knowledge from the source to the target does not lead to any improvement, but rather causes a drop in the overall performance of the target task. There can be various reasons for negative transfer, such as cases when the source task is not sufficiently related to the target task, or if the transfer method could not leverage the relationship between the source and target tasks very well. Avoiding negative transfer is very important and requires careful investigation. In their work, Rosenstien and their co-authors present empirically how brute-force transfer degrades performance in target tasks when the source and target are too dissimilar. Bayesian approaches by Bakker and their co-authors, along with other techniques exploring clustering-based solutions to identify relatedness, are being researched to avoid negative transfers. Transfer Bounds: Quantifying the transfer in transfer learning is also very important, that affects the quality of the transfer and its viability. To gauge the amount for the transfer, Hassan Mahmud and their co-authors used Kolmogorov complexity to prove certain theoretical bounds to analyze transfer learning and measure relatedness between tasks. Eaton and their co-authors presented a novel graph-based approach to measure knowledge transfer. Detailed discussions of these techniques are outside the scope of this article. Readers are encouraged to explore more on these topics using the publications outlined in this section! This concludes perhaps one of my longest articles with a comprehensive coverage about transfer learning concepts, strategies, focus on deep transfer learning, challenges and advantages. We also covered two hands-on real-world case studies to give you a good idea of how to implement these techniques. If you are reading this section, kudos on reading through this pretty long article! Transfer learning is definitely going to be one of the key drivers for machine learning and deep learning success in mainstream adoption in the industry. I definitely hope to see more pre-trained models and innovative case studies which leverage this concept and methodology. For some of my future articles, you can definitely expect some of the following. Transfer Learning for NLP Transfer Learning on Audio Data Transfer Learning for Generative Deep Learning More complex Computer Vision problems like Image Captioning Let’s hope for more success stories around transfer learning and deep learning which enable us to build more intelligent systems to make the world a better place and drive our own personal goals! All of the content above has been adopted in some form from my recent book, ‘Hands on Transfer Learning with Python’ which is available on the Packt website as well as on Amazon. www.amazon.com Don’t have the time to read through the book or can’t spend right now? Don’t worry, you can still access all the wonderful examples and case studies we implemented on our GitHub repository! github.com A big shoutout goes to my co-authors Raghav & Tamoghna for working with me on the book which paved the way for this content! Thanks to Francois Chollet and his amazing book ‘Deep Learning with Python’ for a lot of the motivation and inspiration behind some of the examples used in this article. www.manning.com Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn. www.linkedin.com Thanks to Durba for editing this article.
[ { "code": null, "e": 479, "s": 172, "text": "Humans have an inherent ability to transfer knowledge across tasks. What we acquire as knowledge while learning about one task, we utilize in the same way to solve related tasks. The more related the tasks, the easier it is for us to transfer, or cross-utilize our knowledge. Some simple examples would be," }, { "code": null, "e": 534, "s": 479, "text": "Know how to ride a motorbike ⮫ Learn how to ride a car" }, { "code": null, "e": 596, "s": 534, "text": "Know how to play classic piano ⮫ Learn how to play jazz piano" }, { "code": null, "e": 646, "s": 596, "text": "Know math and statistics ⮫ Learn machine learning" }, { "code": null, "e": 842, "s": 646, "text": "In each of the above scenarios, we don’t learn everything from scratch when we attempt to learn new aspects or topics. We transfer and leverage our knowledge from what we have learnt in the past!" }, { "code": null, "e": 1474, "s": 842, "text": "Conventional machine learning and deep learning algorithms, so far, have been traditionally designed to work in isolation. These algorithms are trained to solve specific tasks. The models have to be rebuilt from scratch once the feature-space distribution changes. Transfer learning is the idea of overcoming the isolated learning paradigm and utilizing knowledge acquired for one task to solve related ones. In this article, we will do a comprehensive coverage of the concepts, scope and real-world applications of transfer learning and even showcase some hands-on examples. To be more specific, we will be covering the following." }, { "code": null, "e": 1507, "s": 1474, "text": "Motivation for Transfer Learning" }, { "code": null, "e": 1539, "s": 1507, "text": "Understanding Transfer Learning" }, { "code": null, "e": 1568, "s": 1539, "text": "Transfer Learning Strategies" }, { "code": null, "e": 1604, "s": 1568, "text": "Transfer Learning for Deep Learning" }, { "code": null, "e": 1638, "s": 1604, "text": "Deep Transfer Learning Strategies" }, { "code": null, "e": 1670, "s": 1638, "text": "Types of Deep Transfer Learning" }, { "code": null, "e": 1704, "s": 1670, "text": "Applications of Transfer Learning" }, { "code": null, "e": 1775, "s": 1704, "text": "Case Study 1: Image Classification with a Data Availability Constraint" }, { "code": null, "e": 1891, "s": 1775, "text": "Case Study 2: Multi-Class Fine-grained Image Classification with Large Number of Classes and Less Data Availability" }, { "code": null, "e": 1920, "s": 1891, "text": "Transfer Learning Advantages" }, { "code": null, "e": 1949, "s": 1920, "text": "Transfer Learning Challenges" }, { "code": null, "e": 1975, "s": 1949, "text": "Conclusion & Future Scope" }, { "code": null, "e": 2192, "s": 1975, "text": "We will look at transfer learning as a general high-level concept which started right from the days of machine learning and statistical modeling, however, we will be more focused around deep learning in this article." }, { "code": null, "e": 2529, "s": 2192, "text": "Note: All the case studies will cover step by step details with code and outputs. The case studies depicted here and their results are purely based on actual experiments which we conducted when we implemented and tested these models while working on our book: Hands on Transfer Learning with Python (details at the end of this article)." }, { "code": null, "e": 3038, "s": 2529, "text": "This article aims to be an attempt to cover theoretical concepts as well as demonstrate practical hands-on examples of deep learning applications in one place, given the information overload which is out there on the web. All examples will be covered in Python using keras with a tensorflow backend, a perfect match for people who are veterans or just getting started with deep learning! Interested in PyTorch? Feel free to convert these examples and contact me and I’ll feature your work here and on GitHub!" }, { "code": null, "e": 3671, "s": 3038, "text": "We have already briefly discussed that humans don’t learn everything from the ground up and leverage and transfer their knowledge from previously learnt domains to newer domains and tasks. Given the craze for True Artificial General Intelligence, transfer learning is something which data scientists and researchers believe can further our progress towards AGI. In fact, Andrew Ng, renowned professor and data scientist, who has been associated with Google Brain, Baidu, Stanford and Coursera, recently gave an amazing tutorial in NIPS 2016 called ‘Nuts and bolts of building AI applications using Deep Learning’ where he mentioned," }, { "code": null, "e": 3766, "s": 3671, "text": "After supervised learning — Transfer Learning will be the next driver of ML commercial success" }, { "code": null, "e": 3849, "s": 3766, "text": "I recommend interested folks to check out his interesting tutorial from NIPS 2016." }, { "code": null, "e": 4542, "s": 3849, "text": "In fact, transfer learning is not a concept which just cropped up in the 2010s. The Neural Information Processing Systems (NIPS) 1995 workshop Learning to Learn: Knowledge Consolidation and Transfer in Inductive Systems is believed to have provided the initial motivation for research in this field. Since then, terms such as Learning to Learn, Knowledge Consolidation, and Inductive Transfer have been used interchangeably with transfer learning. Invariably, different researchers and academic texts provide definitions from different contexts. In their famous book, Deep Learning, Goodfellow et al refer to transfer learning in the context of generalization. Their definition is as follows:" }, { "code": null, "e": 4654, "s": 4542, "text": "Situation where what has been learned in one setting is exploited to improve generalization in another setting." }, { "code": null, "e": 5131, "s": 4654, "text": "Thus, the key motivation, especially considering the context of deep learning is the fact that most models which solve complex problems need a whole lot of data, and getting vast amounts of labeled data for supervised models can be really difficult, considering the time and effort it takes to label data points. A simple example would be the ImageNet dataset, which has millions of images pertaining to different categories, thanks to years of hard work starting at Stanford!" }, { "code": null, "e": 5771, "s": 5131, "text": "However, getting such a dataset for every domain is tough. Besides, most deep learning models are very specialized to a particular domain or even a specific task. While these might be state-of-the-art models, with really high accuracy and beating all benchmarks, it would be only on very specific datasets and end up suffering a significant loss in performance when used in a new task which might still be similar to the one it was trained on. This forms the motivation for transfer learning, which goes beyond specific tasks and domains, and tries to see how to leverage knowledge from pre-trained models and use it to solve new problems!" }, { "code": null, "e": 6069, "s": 5771, "text": "The first thing to remember here is that, transfer learning, is not a new concept which is very specific to deep learning. There is a stark difference between the traditional approach of building and training machine learning models, and using a methodology following transfer learning principles." }, { "code": null, "e": 6475, "s": 6069, "text": "Traditional learning is isolated and occurs purely based on specific tasks, datasets and training separate isolated models on them. No knowledge is retained which can be transferred from one model to another. In transfer learning, you can leverage knowledge (features, weights etc) from previously trained models for training newer models and even tackle problems like having less data for the newer task!" }, { "code": null, "e": 7354, "s": 6475, "text": "Let’s understand the preceding explanation with the help of an example. Let’s assume our task is to identify objects in images within a restricted domain of a restaurant. Let’s mark this task in its defined scope as T1. Given the dataset for this task, we train a model and tune it to perform well (generalize) on unseen data points from the same domain (restaurant). Traditional supervised ML algorithms break down when we do not have sufficient training examples for the required tasks in given domains. Suppose, we now must detect objects from images in a park or a café (say, task T2). Ideally, we should be able to apply the model trained for T1, but in reality, we face performance degradation and models that do not generalize well. This happens for a variety of reasons, which we can liberally and collectively term as the model’s bias towards training data and domain." }, { "code": null, "e": 8002, "s": 7354, "text": "Transfer learning should enable us to utilize knowledge from previously learned tasks and apply them to newer, related ones. If we have significantly more data for task T1, we may utilize its learning, and generalize this knowledge (features, weights) for task T2 (which has significantly less data). In the case of problems in the computer vision domain, certain low-level features, such as edges, shapes, corners and intensity, can be shared across tasks, and thus enable knowledge transfer among tasks! Also, as we have depicted in the earlier figure, knowledge from an existing task acts as an additional input when learning a new target task." }, { "code": null, "e": 8327, "s": 8002, "text": "Let’s now take a look at a formal definition for transfer learning and then utilize it to understand different strategies. In their paper, A Survey on Transfer Learning, Pan and Yang use domain, task, and marginal probabilities to present a framework for understanding transfer learning. The framework is defined as follows:" }, { "code": null, "e": 8536, "s": 8327, "text": "A domain, D, is defined as a two-element tuple consisting of feature space, ꭕ, and marginal probability, P(Χ), where Χ is a sample data point. Thus, we can represent the domain mathematically as D = {ꭕ, P(Χ)}" }, { "code": null, "e": 8817, "s": 8536, "text": "Here xi represents a specific vector as represented in the above depiction. A task, T, on the other hand, can be defined as a two-element tuple of the label space, γ, and objective function, η. The objective function can also be denoted as P(γ| Χ) from a probabilistic view point." }, { "code": null, "e": 8970, "s": 8817, "text": "Thus, armed with these definitions and representations, we can define transfer learning as follows, thanks to an excellent article from Sebastian Ruder." }, { "code": null, "e": 9079, "s": 8970, "text": "Let’s now take a look at the typical scenarios involving transfer learning based on our previous definition." }, { "code": null, "e": 9221, "s": 9079, "text": "To give some more clarity on the difference between the terms domain and task, the following figure tries to explain them with some examples." }, { "code": null, "e": 9459, "s": 9221, "text": "Transfer learning, as we have seen so far, is having the ability to utilize existing knowledge from the source learner in the target task. During the process of transfer learning, the following three important questions must be answered:" }, { "code": null, "e": 9863, "s": 9459, "text": "What to transfer: This is the first and the most important step in the whole process. We try to seek answers about which part of the knowledge can be transferred from the source to the target in order to improve the performance of the target task. When trying to answer this question, we try to identify which portion of knowledge is source-specific and what is common between the source and the target." }, { "code": null, "e": 10206, "s": 9863, "text": "When to transfer: There can be scenarios where transferring knowledge for the sake of it may make matters worse than improving anything (also known as negative transfer). We should aim at utilizing transfer learning to improve target task performance/results and not degrade them. We need to be careful about when to transfer and when not to." }, { "code": null, "e": 10592, "s": 10206, "text": "How to transfer: Once the what and when have been answered, we can proceed towards identifying ways of actually transferring the knowledge across domains/tasks. This involves changes to existing algorithms and different techniques, which we will cover in later sections of this article. Also, specific case studies are lined up in the end for a better understanding of how to transfer." }, { "code": null, "e": 10748, "s": 10592, "text": "This should help us define the various scenarios where transfer learning can be applied and possible techniques, which we will discuss in the next section." }, { "code": null, "e": 11023, "s": 10748, "text": "There are different transfer learning strategies and techniques, which can be applied based on the domain, task at hand, and the availability of data. I really like the following figure from the paper on transfer learning we mentioned earlier, A Survey on Transfer Learning." }, { "code": null, "e": 11170, "s": 11023, "text": "Thus, based on the previous figure, transfer learning methods can be categorized based on the type of traditional ML algorithms involved, such as:" }, { "code": null, "e": 11622, "s": 11170, "text": "Inductive Transfer learning: In this scenario, the source and target domains are the same, yet the source and target tasks are different from each other. The algorithms try to utilize the inductive biases of the source domain to help improve the target task. Depending upon whether the source domain contains labeled data or not, this can be further divided into two subcategories, similar to multitask learning and self-taught learning, respectively." }, { "code": null, "e": 11909, "s": 11622, "text": "Unsupervised Transfer Learning: This setting is similar to inductive transfer itself, with a focus on unsupervised tasks in the target domain. The source and target domains are similar, but the tasks are different. In this scenario, labeled data is unavailable in either of the domains." }, { "code": null, "e": 12310, "s": 11909, "text": "Transductive Transfer Learning: In this scenario, there are similarities between the source and target tasks, but the corresponding domains are different. In this setting, the source domain has a lot of labeled data, while the target domain has none. This can be further classified into subcategories, referring to settings where either the feature spaces are different or the marginal probabilities." }, { "code": null, "e": 12421, "s": 12310, "text": "We can summarize the different settings and scenarios for each of the above techniques in the following table." }, { "code": null, "e": 12692, "s": 12421, "text": "The three transfer categories discussed in the previous section outline different settings where transfer learning can be applied, and studied in detail. To answer the question of what to transfer across these categories, some of the following approaches can be applied:" }, { "code": null, "e": 13169, "s": 12692, "text": "Instance transfer: Reusing knowledge from the source domain to the target task is usually an ideal scenario. In most cases, the source domain data cannot be reused directly. Rather, there are certain instances from the source domain that can be reused along with target data to improve results. In case of inductive transfer, modifications such as AdaBoost by Dai and their co-authors help utilize training instances from the source domain for improvements in the target task." }, { "code": null, "e": 13517, "s": 13169, "text": "Feature-representation transfer: This approach aims to minimize domain divergence and reduce error rates by identifying good feature representations that can be utilized from the source to target domains. Depending upon the availability of labeled data, supervised or unsupervised methods may be applied for feature-representation-based transfers." }, { "code": null, "e": 13889, "s": 13517, "text": "Parameter transfer: This approach works on the assumption that the models for related tasks share some parameters or prior distribution of hyperparameters. Unlike multitask learning, where both the source and target tasks are learned simultaneously, for transfer learning, we may apply additional weightage to the loss of the target domain to improve overall performance." }, { "code": null, "e": 14264, "s": 13889, "text": "Relational-knowledge transfer: Unlike the preceding three approaches, the relational-knowledge transfer attempts to handle non-IID data, such as data that is not independent and identically distributed. In other words, data, where each data point has a relationship with other data points; for instance, social network data utilizes relational-knowledge-transfer techniques." }, { "code": null, "e": 14389, "s": 14264, "text": "The following table clearly summarizes the relationship between different transfer learning strategies and what to transfer." }, { "code": null, "e": 14502, "s": 14389, "text": "Let’s now utilize this understanding and learn how transfer learning is applied in the context of deep learning." }, { "code": null, "e": 14741, "s": 14502, "text": "The strategies we discussed in the previous section are general approaches which can be applied towards machine learning techniques, which brings us to the question, can transfer learning really be applied in the context of deep learning?" }, { "code": null, "e": 15518, "s": 14741, "text": "Deep learning models are representative of what is also known as inductive learning. The objective for inductive-learning algorithms is to infer a mapping from a set of training examples. For instance, in cases of classification, the model learns mapping between input features and class labels. In order for such a learner to generalize well on unseen data, its algorithm works with a set of assumptions related to the distribution of the training data. These sets of assumptions are known as inductive bias. The inductive bias or assumptions can be characterized by multiple factors, such as the hypothesis space it restricts to and the search process through the hypothesis space. Thus, these biases impact how and what is learned by the model on the given task and domain." }, { "code": null, "e": 15943, "s": 15518, "text": "Inductive transfer techniques utilize the inductive biases of the source task to assist the target task. This can be done in different ways, such as by adjusting the inductive bias of the target task by limiting the model space, narrowing down the hypothesis space, or making adjustments to the search process itself with the help of knowledge from the source task. This process is depicted visually in the following figure." }, { "code": null, "e": 16143, "s": 15943, "text": "Apart from inductive transfer, inductive-learning algorithms also utilize Bayesian and Hierarchical transfer techniques to assist with improvements in the learning and performance of the target task." }, { "code": null, "e": 16976, "s": 16143, "text": "Deep learning has made considerable progress in recent years. This has enabled us to tackle complex problems and yield amazing results. However, the training time and the amount of data required for such deep learning systems are much more than that of traditional ML systems. There are various deep learning networks with state-of-the-art performance (sometimes as good or even better than human performance) that have been developed and tested across domains such as computer vision and natural language processing (NLP). In most cases, teams/people share the details of these networks for others to use. These pre-trained networks/models form the basis of transfer learning in the context of deep learning, or what I like to call ‘deep transfer learning’. Let’s look at the two most popular strategies for deep transfer learning." }, { "code": null, "e": 17457, "s": 16976, "text": "Deep learning systems and models are layered architectures that learn different features at different layers (hierarchical representations of layered features). These layers are then finally connected to a last layer (usually a fully connected layer, in the case of supervised learning) to get the final output. This layered architecture allows us to utilize a pre-trained network (such as Inception V3 or VGG) without its final layer as a fixed feature extractor for other tasks." }, { "code": null, "e": 17655, "s": 17457, "text": "The key idea here is to just leverage the pre-trained model’s weighted layers to extract features but not to update the weights of the model’s layers during training with new data for the new task." }, { "code": null, "e": 18066, "s": 17655, "text": "For instance, if we utilize AlexNet without its final classification layer, it will help us transform images from a new domain task into a 4096-dimensional vector based on its hidden states, thus enabling us to extract features from a new domain task, utilizing the knowledge from a source-domain task. This is one of the most widely utilized methods of performing transfer learning using deep neural networks." }, { "code": null, "e": 18193, "s": 18066, "text": "Now a question might arise, how well do these pre-trained off-the-shelf features really work in practice with different tasks?" }, { "code": null, "e": 18435, "s": 18193, "text": "It definitely seems to work really well in real-world tasks, and if the chart in the above table is not very clear, the following figure should make things more clear with regard to their performance in different computer vision based tasks!" }, { "code": null, "e": 18630, "s": 18435, "text": "Based on the red and pink bars in the above figure, you can clearly see that the features from the pre-trained models consistently out-perform very specialized task-focused deep learning models." }, { "code": null, "e": 19245, "s": 18630, "text": "This is a more involved technique, where we do not just replace the final layer (for classification/regression), but we also selectively retrain some of the previous layers. Deep neural networks are highly configurable architectures with various hyperparameters. As discussed earlier, the initial layers have been seen to capture generic features, while the later ones focus more on the specific task at hand. An example is depicted in the following figure on a face-recognition problem, where initial lower layers of the network learn very generic features and the higher layers learn very task-specific features." }, { "code": null, "e": 19608, "s": 19245, "text": "Using this insight, we may freeze (fix weights) certain layers while retraining, or fine-tune the rest of them to suit our needs. In this case, we utilize the knowledge in terms of the overall architecture of the network and use its states as the starting point for our retraining step. This, in turn, helps us achieve better performance with less training time." }, { "code": null, "e": 19764, "s": 19608, "text": "This brings us to the question, should we freeze layers in the network to use them as feature extractors or should we also fine-tune layers in the process?" }, { "code": null, "e": 19870, "s": 19764, "text": "This should give us a good perspective on what each of these strategies are and when should they be used!" }, { "code": null, "e": 20704, "s": 19870, "text": "One of the fundamental requirements for transfer learning is the presence of models that perform well on source tasks. Luckily, the deep learning world believes in sharing. Many of the state-of-the art deep learning architectures have been openly shared by their respective teams. These span across different domains, such as computer vision and NLP, the two most popular domains for deep learning applications. Pre-trained models are usually shared in the form of the millions of parameters/weights the model achieved while being trained to a stable state. Pre-trained models are available for everyone to use through different means. The famous deep learning Python library, keras, provides an interface to download some popular models. You can also access pre-trained models from the web since most of them have been open-sourced." }, { "code": null, "e": 20773, "s": 20704, "text": "For computer vision, you can leverage some popular models including," }, { "code": null, "e": 20780, "s": 20773, "text": "VGG-16" }, { "code": null, "e": 20787, "s": 20780, "text": "VGG-19" }, { "code": null, "e": 20800, "s": 20787, "text": "Inception V3" }, { "code": null, "e": 20809, "s": 20800, "text": "XCeption" }, { "code": null, "e": 20819, "s": 20809, "text": "ResNet-50" }, { "code": null, "e": 20976, "s": 20819, "text": "For natural language processing tasks, things become more difficult due to the varied nature of NLP tasks. You can leverage word embedding models including," }, { "code": null, "e": 20985, "s": 20976, "text": "Word2Vec" }, { "code": null, "e": 20991, "s": 20985, "text": "GloVe" }, { "code": null, "e": 21000, "s": 20991, "text": "FastText" }, { "code": null, "e": 21129, "s": 21000, "text": "But wait, that’s not all! Recently, there have been some excellent advancements towards transfer learning for NLP. Most notably," }, { "code": null, "e": 21166, "s": 21129, "text": "Universal Sentence Encoder by Google" }, { "code": null, "e": 21239, "s": 21166, "text": "Bidirectional Encoder Representations from Transformers (BERT) by Google" }, { "code": null, "e": 21359, "s": 21239, "text": "They definitely hold a lot of promise and I’m sure they will be widely adopted pretty soon for real-world applications." }, { "code": null, "e": 21920, "s": 21359, "text": "The literature on transfer learning has gone through a lot of iterations, and as mentioned at the start of this chapter, the terms associated with it have been used loosely and often interchangeably. Hence, it is sometimes confusing to differentiate between transfer learning, domain adaptation, and multi-task learning. Rest assured, these are all related and try to solve similar problems. In general, you should always think of transfer learning as a general concept or principle, where we will try to solve a target task using source task-domain knowledge." }, { "code": null, "e": 22570, "s": 21920, "text": "Domain adaption is usually referred to in scenarios where the marginal probabilities between the source and target domains are different, such as P(Xs) ≠ P(Xt). There is an inherent shift or drift in the data distribution of the source and target domains that requires tweaks to transfer the learning. For instance, a corpus of movie reviews labeled as positive or negative would be different from a corpus of product-review sentiments. A classifier trained on movie-review sentiment would see a different distribution if utilized to classify product reviews. Thus, domain adaptation techniques are utilized in transfer learning in these scenarios." }, { "code": null, "e": 23741, "s": 22570, "text": "We learned different transfer learning strategies and even discussed the three questions of what, when, and how to transfer knowledge from the source to the target. In particular, we discussed how feature-representation transfer can be useful. It is worth re-iterating that different layers in a deep learning network capture different sets of features. We can utilize this fact to learn domain-invariant features and improve their transferability across domains. Instead of allowing the model to learn any representation, we nudge the representations of both domains to be as similar as possible. This can be achieved by applying certain pre-processing steps directly to the representations themselves. Some of these have been discussed by Baochen Sun, Jiashi Feng, and Kate Saenko in their paper ‘Return of Frustratingly Easy Domain Adaptation’. This nudge toward the similarity of representation has also been presented by Ganin et. al. in their paper, ‘Domain-Adversarial Training of Neural Networks’. The basic idea behind this technique is to add another objective to the source model to encourage similarity by confusing the domain itself, hence domain confusion." }, { "code": null, "e": 24167, "s": 23741, "text": "Multitask learning is a slightly different flavor of the transfer learning world. In the case of multitask learning, several tasks are learned simultaneously without distinction between the source and targets. In this case, the learner receives information about multiple tasks at once, as compared to transfer learning, where the learner initially has no idea about the target task. This is depicted in the following figure." }, { "code": null, "e": 25338, "s": 24167, "text": "Deep learning systems are data-hungry by nature, such that they need many training examples to learn the weights. This is one of the limiting aspects of deep neural networks, though such is not the case with human learning. For instance, once a child is shown what an apple looks like, they can easily identify a different variety of apple (with one or a few training examples); this is not the case with ML and deep learning algorithms. One-shot learning is a variant of transfer learning, where we try to infer the required output based on just one or a few training examples. This is essentially helpful in real-world scenarios where it is not possible to have labeled data for every possible class (if it is a classification task), and in scenarios where new classes can be added often. The landmark paper by Fei-Fei and their co-authors, ‘One Shot Learning of Object Categories’, is supposedly what coined the term one-shot learning and the research in this sub-field. This paper presented a variation on a Bayesian framework for representation learning for object categorization. This approach has since been improved upon, and applied using deep learning systems." }, { "code": null, "e": 26262, "s": 25338, "text": "Zero-shot learning is another extreme variant of transfer learning, which relies on no labeled examples to learn a task. This might sound unbelievable, especially when learning using examples is what most supervised learning algorithms are about. Zero-data learning or zero-short learning methods, make clever adjustments during the training stage itself to exploit additional information to understand unseen data. In their book on Deep Learning, Goodfellow and their co-authors present zero-shot learning as a scenario where three variables are learned, such as the traditional input variable, x, the traditional output variable, y, and the additional random variable that describes the task, T. The model is thus trained to learn the conditional probability distribution of P(y | x, T). Zero-shot learning comes in handy in scenarios such as machine translation, where we may not even have labels in the target language." }, { "code": null, "e": 26453, "s": 26262, "text": "Deep learning is definitely one of the specific categories of algorithms that has been utilized to reap the benefits of transfer learning very successfully. The following are a few examples:" }, { "code": null, "e": 27015, "s": 26453, "text": "Transfer learning for NLP: Textual data presents all sorts of challenges when it comes to ML and deep learning. These are usually transformed or vectorized using different techniques. Embeddings, such as Word2vec and FastText, have been prepared using different training datasets. These are utilized in different tasks, such as sentiment analysis and document classification, by transferring the knowledge from the source tasks. Besides this, newer models like the Universal Sentence Encoder and BERT definitely present a myriad of possibilities for the future." }, { "code": null, "e": 27459, "s": 27015, "text": "Transfer learning for Audio/Speech: Similar to domains like NLP and Computer Vision, deep learning has been successfully used for tasks based on audio data. For instance, Automatic Speech Recognition (ASR) models developed for English have been successfully used to improve speech recognition performance for other languages, such as German. Also, automated-speaker identification is another example where transfer learning has greatly helped." }, { "code": null, "e": 27987, "s": 27459, "text": "Transfer learning for Computer Vision: Deep learning has been quite successfully utilized for various computer vision tasks, such as object recognition and identification, using different CNN architectures. In their paper, How transferable are features in deep neural networks, Yosinski and their co-authors (https://arxiv.org/abs/1411.1792) present their findings on how the lower layers act as conventional computer-vision feature extractors, such as edge detectors, while the final layers work toward task-specific features." }, { "code": null, "e": 28330, "s": 27987, "text": "Thus, these findings have helped in utilizing existing state-of-the-art models, such as VGG, AlexNet, and Inceptions, for target tasks, such as style transfer and face detection, that were different from what these models were trained for initially. Let’s explore some real-world case studies now and build some deep transfer learning models!" }, { "code": null, "e": 28616, "s": 28330, "text": "In this simple case study, will be working on an image categorization problem with the constraint of having a very small number of training samples per category. The dataset for our problem is available on Kaggle and is one of the most popular computer vision based datasets out there." }, { "code": null, "e": 28848, "s": 28616, "text": "The dataset that we will be using, comes from the very popular Dogs vs. Cats Challenge, where our primary objective is to build a deep learning model that can successfully recognize and categorize images into either a cat or a dog." }, { "code": null, "e": 29386, "s": 28848, "text": "In terms of ML, this is a binary classification problem based on images. Before getting started, I would like to thank Francois Chollet for not only creating the amazing deep learning framework, keras, but also for talking about the real-world problem where transfer learning is effective in his book, ‘Deep Learning with Python’. I’ve have taken that as an inspiration to portray the true power of transfer learning in this chapter, and all results are based on building and running each model in my own GPU-based cloud setup (AWS p2.x)" }, { "code": null, "e": 29851, "s": 29386, "text": "To start, download the train.zip file from the dataset page and store it in your local system. Once downloaded, unzip it into a folder. This folder will contain 25,000 images of dogs and cats; that is, 12,500 images per category. While we can use all 25,000 images and build some nice models on them, if you remember, our problem objective includes the added constraint of having a small number of images per category. Let’s build our own dataset for this purpose." }, { "code": null, "e": 29921, "s": 29851, "text": "import globimport numpy as npimport osimport shutilnp.random.seed(42)" }, { "code": null, "e": 30003, "s": 29921, "text": "Let’s now load up all the images in our original training data folder as follows:" }, { "code": null, "e": 30018, "s": 30003, "text": "(12500, 12500)" }, { "code": null, "e": 30310, "s": 30018, "text": "We can verify with the preceding output that we have 12,500 images for each category. Let’s now build our smaller dataset, so that we have 3,000 images for training, 1,000 images for validation, and 1,000 images for our test dataset (with equal representation for the two animal categories)." }, { "code": null, "e": 30381, "s": 30310, "text": "Cat datasets: (1500,) (500,) (500,)Dog datasets: (1500,) (500,) (500,)" }, { "code": null, "e": 30588, "s": 30381, "text": "Now that our datasets have been created, let’s write them out to our disk in separate folders, so that we can come back to them anytime in the future without worrying if they are present in our main memory." }, { "code": null, "e": 30952, "s": 30588, "text": "Since this is an image categorization problem, we will be leveraging CNN models or ConvNets to try and tackle this problem. We will start by building simple CNN models from scratch, then try to improve using techniques such as regularization and image augmentation. Then, we will try and leverage pre-trained models to unleash the true power of transfer learning!" }, { "code": null, "e": 31070, "s": 30952, "text": "Before we jump into modeling, let’s load and prepare our datasets. To start with, we load up some basic dependencies." }, { "code": null, "e": 31243, "s": 31070, "text": "import globimport numpy as npimport matplotlib.pyplot as pltfrom keras.preprocessing.image import ImageDataGenerator, load_img, img_to_array, array_to_img%matplotlib inline" }, { "code": null, "e": 31306, "s": 31243, "text": "Let’s now load our datasets, using the following code snippet." }, { "code": null, "e": 31394, "s": 31306, "text": "Train dataset shape: (3000, 150, 150, 3) \tValidation dataset shape: (1000, 150, 150, 3)" }, { "code": null, "e": 31776, "s": 31394, "text": "We can clearly see that we have 3000 training images and 1000 validation images. Each image is of size 150 x 150 and has three channels for red, green, and blue (RGB), hence giving each image the (150, 150, 3) dimensions. We will now scale each image with pixel values between (0, 255) to values between (0, 1) because deep learning models work really well with small input values." }, { "code": null, "e": 32006, "s": 31776, "text": "The preceding output shows one of the sample images from our training dataset. Let’s now set up some basic configuration parameters and also encode our text class labels into numeric values (otherwise, Keras will throw an error)." }, { "code": null, "e": 32099, "s": 32006, "text": "['cat', 'cat', 'cat', 'cat', 'cat', 'dog', 'dog', 'dog', 'dog', 'dog'] [0 0 0 0 0 1 1 1 1 1]" }, { "code": null, "e": 32266, "s": 32099, "text": "We can see that our encoding scheme assigns the number 0 to the cat labels and 1 to the dog labels. We are now ready to build our first CNN-based deep learning model." }, { "code": null, "e": 32475, "s": 32266, "text": "We will start by building a basic CNN model with three convolutional layers, coupled with max pooling for auto-extraction of features from our images and also downsampling the output convolution feature maps." }, { "code": null, "e": 32738, "s": 32475, "text": "We assume you have enough knowledge about CNNs and hence, won’t cover theoretical details. Feel free to refer to my book or any other resources on the web which explain convolutional neural networks! Let’s leverage Keras and build our CNN model architecture now." }, { "code": null, "e": 33279, "s": 32738, "text": "The preceding output shows us our basic CNN model summary. Just like we mentioned before, we are using three convolutional layers for feature extraction. The flatten layer is used to flatten out 128 of the 17 x 17 feature maps that we get as output from the third convolution layer. This is fed to our dense layers to get the final prediction of whether the image should be a dog (1) or a cat (0). All of this is part of the model training process, so let’s train our model using the following snippet which leverages the fit(...) function." }, { "code": null, "e": 33358, "s": 33279, "text": "The following terminology is very important with regard to training our model:" }, { "code": null, "e": 33445, "s": 33358, "text": "The batch_size indicates the total number of images passed to the model per iteration." }, { "code": null, "e": 33514, "s": 33445, "text": "The weights of the units in layers are updated after each iteration." }, { "code": null, "e": 33627, "s": 33514, "text": "The total number of iterations is always equal to the total number of training samples divided by the batch_size" }, { "code": null, "e": 33767, "s": 33627, "text": "An epoch is when the complete dataset has passed through the network once, that is, all the iterations are completed based on data batches." }, { "code": null, "e": 34029, "s": 33767, "text": "We use a batch_size of 30 and our training data has a total of 3,000 samples, which indicates that there will be a total of 100 iterations per epoch. We train the model for a total of 30 epochs and validate it consequently on our validation set of 1,000 images." }, { "code": null, "e": 34446, "s": 34029, "text": "Train on 3000 samples, validate on 1000 samplesEpoch 1/303000/3000 - 10s - loss: 0.7583 - acc: 0.5627 - val_loss: 0.7182 - val_acc: 0.5520Epoch 2/303000/3000 - 8s - loss: 0.6343 - acc: 0.6533 - val_loss: 0.5891 - val_acc: 0.7190......Epoch 29/303000/3000 - 8s - loss: 0.0314 - acc: 0.9950 - val_loss: 2.7014 - val_acc: 0.7140Epoch 30/303000/3000 - 8s - loss: 0.0147 - acc: 0.9967 - val_loss: 2.4963 - val_acc: 0.7220" }, { "code": null, "e": 34644, "s": 34446, "text": "Looks like our model is kind of overfitting, based on the training and validation accuracy values. We can plot our model accuracy and errors using the following snippet to get a better perspective." }, { "code": null, "e": 34860, "s": 34644, "text": "You can clearly see that after 2–3 epochs the model starts overfitting on the training data. The average accuracy we get in our validation set is around 72%, which is not a bad start! Can we improve upon this model?" }, { "code": null, "e": 35376, "s": 34860, "text": "Let’s improve upon our base CNN model by adding in one more convolution layer, another dense hidden layer. Besides this, we will add dropout of 0.3 after each hidden dense layer to enable regularization. Basically, dropout is a powerful method of regularizing in deep neural nets. It can be applied separately to both input layers and the hidden layers. Dropout randomly masks the outputs of a fraction of units from a layer by setting their output to zero (in our case, it is 30% of the units in our dense layers)." }, { "code": null, "e": 35792, "s": 35376, "text": "Train on 3000 samples, validate on 1000 samplesEpoch 1/303000/3000 - 7s - loss: 0.6945 - acc: 0.5487 - val_loss: 0.7341 - val_acc: 0.5210Epoch 2/303000/3000 - 7s - loss: 0.6601 - acc: 0.6047 - val_loss: 0.6308 - val_acc: 0.6480......Epoch 29/303000/3000 - 7s - loss: 0.0927 - acc: 0.9797 - val_loss: 1.1696 - val_acc: 0.7380Epoch 30/303000/3000 - 7s - loss: 0.0975 - acc: 0.9803 - val_loss: 1.6790 - val_acc: 0.7840" }, { "code": null, "e": 36507, "s": 35792, "text": "You can clearly see from the preceding outputs that we still end up overfitting the model, though it takes slightly longer and we also get a slightly better validation accuracy of around 78%, which is decent but not amazing. The reason for model overfitting is because we have much less training data and the model keeps seeing the same instances over time across each epoch. A way to combat this would be to leverage an image augmentation strategy to augment our existing training data with images that are slight variations of the existing images. We will cover this in detail in the following section. Let’s save this model for the time being so we can use it later to evaluate its performance on the test data." }, { "code": null, "e": 36544, "s": 36507, "text": "model.save(‘cats_dogs_basic_cnn.h5’)" }, { "code": null, "e": 37292, "s": 36544, "text": "Let’s improve upon our regularized CNN model by adding in more data using a proper image augmentation strategy. Since our previous model was trained on the same small sample of data points each time, it wasn’t able to generalize well and ended up overfitting after a few epochs. The idea behind image augmentation is that we follow a set process of taking in existing images from our training dataset and applying some image transformation operations to them, such as rotation, shearing, translation, zooming, and so on, to produce new, altered versions of existing images. Due to these random transformations, we don’t get the same images each time, and we will leverage Python generators to feed in these new images to our model during training." }, { "code": null, "e": 37505, "s": 37292, "text": "The Keras framework has an excellent utility called ImageDataGenerator that can help us in doing all the preceding operations. Let’s initialize two of the data generators for our training and validation datasets." }, { "code": null, "e": 37842, "s": 37505, "text": "There are a lot of options available in ImageDataGenerator and we have just utilized a few of them. Feel free to check out the documentation to get a more detailed perspective. In our training data generator, we take in the raw images and then perform several transformations on them to generate new images. These include the following." }, { "code": null, "e": 37920, "s": 37842, "text": "Zooming the image randomly by a factor of 0.3 using the zoom_range parameter." }, { "code": null, "e": 37998, "s": 37920, "text": "Rotating the image randomly by 50 degrees using the rotation_range parameter." }, { "code": null, "e": 38170, "s": 37998, "text": "Translating the image randomly horizontally or vertically by a 0.2 factor of the image’s width or height using the width_shift_range and the height_shift_range parameters." }, { "code": null, "e": 38249, "s": 38170, "text": "Applying shear-based transformations randomly using the shear_range parameter." }, { "code": null, "e": 38336, "s": 38249, "text": "Randomly flipping half of the images horizontally using the horizontal_flip parameter." }, { "code": null, "e": 38579, "s": 38336, "text": "Leveraging the fill_mode parameter to fill in new pixels for images after we apply any of the preceding operations (especially rotation or translation). In this case, we just fill in the new pixels with their nearest surrounding pixel values." }, { "code": null, "e": 38794, "s": 38579, "text": "Let’s see how some of these generated images might look so that you can understand them better. We will take two sample images from our training dataset to illustrate the same. The first image is an image of a cat." }, { "code": null, "e": 39156, "s": 38794, "text": "You can clearly see in the previous output that we generate a new version of our training image each time (with translations, rotations, and zoom) and also we assign a label of cat to it so that the model can extract relevant features from these images and also remember that these are cats. Let’s look at how image augmentation works on a sample dog image now." }, { "code": null, "e": 39747, "s": 39156, "text": "This shows us how image augmentation helps in creating new images, and how training a model on them should help in combating overfitting. Remember for our validation generator, we just need to send the validation images (original ones) to the model for evaluation; hence, we just scale the image pixels (between 0–1) and do not apply any transformations. We just apply image augmentation transformations only on our training images. Let’s now train a CNN model with regularization using the image augmentation data generators we created. We will use the same model architecture from before." }, { "code": null, "e": 40573, "s": 39747, "text": "We reduce the default learning rate by a factor of 10 here for our optimizer to prevent the model from getting stuck in a local minima or overfit, as we will be sending a lot of images with random transformations. To train the model, we need to slightly modify our approach now, since we are using data generators. We will leverage the fit_generator(...) function from Keras to train this model. The train_generator generates 30 images each time, so we will use the steps_per_epoch parameter and set it to 100 to train the model on 3,000 randomly generated images from the training data for each epoch. Our val_generator generates 20 images each time so we will set the validation_steps parameter to 50 to validate our model accuracy on all the 1,000 validation images (remember we are not augmenting our validation dataset)." }, { "code": null, "e": 41033, "s": 40573, "text": "Epoch 1/100100/100 - 12s - loss: 0.6924 - acc: 0.5113 - val_loss: 0.6943 - val_acc: 0.5000Epoch 2/100100/100 - 11s - loss: 0.6855 - acc: 0.5490 - val_loss: 0.6711 - val_acc: 0.5780Epoch 3/100100/100 - 11s - loss: 0.6691 - acc: 0.5920 - val_loss: 0.6642 - val_acc: 0.5950......Epoch 99/100100/100 - 11s - loss: 0.3735 - acc: 0.8367 - val_loss: 0.4425 - val_acc: 0.8340Epoch 100/100100/100 - 11s - loss: 0.3733 - acc: 0.8257 - val_loss: 0.4046 - val_acc: 0.8200" }, { "code": null, "e": 41315, "s": 41033, "text": "We get a validation accuracy jump to around 82%, which is almost 4–5% better than our previous model. Also, our training accuracy is very similar to our validation accuracy, indicating our model isn’t overfitting anymore. The following depict the model accuracy and loss per epoch." }, { "code": null, "e": 41635, "s": 41315, "text": "While there are some spikes in the validation accuracy and loss, overall, we see that it is much closer to the training accuracy, with the loss indicating that we obtained a model that generalizes much better as compared to our previous models. Let’s save this model now so we can evaluate it later on our test dataset." }, { "code": null, "e": 41674, "s": 41635, "text": "model.save(‘cats_dogs_cnn_img_aug.h5’)" }, { "code": null, "e": 41773, "s": 41674, "text": "We will now try and leverage the power of transfer learning to see if we can build a better model!" }, { "code": null, "e": 41877, "s": 41773, "text": "Pre-trained models are used in the following two popular ways when building new models or reusing them:" }, { "code": null, "e": 41926, "s": 41877, "text": "Using a pre-trained model as a feature extractor" }, { "code": null, "e": 41960, "s": 41926, "text": "Fine-tuning the pre-trained model" }, { "code": null, "e": 42268, "s": 41960, "text": "We will cover both of them in detail in this section. The pre-trained model that we will be using in this chapter is the popular VGG-16 model, created by the Visual Geometry Group at the University of Oxford, which specializes in building very deep convolutional networks for large-scale visual recognition." }, { "code": null, "e": 43003, "s": 42268, "text": "A pre-trained model like the VGG-16 is an already pre-trained model on a huge dataset (ImageNet) with a lot of diverse image categories. Considering this fact, the model should have learned a robust hierarchy of features, which are spatial, rotation, and translation invariant with regard to features learned by CNN models. Hence, the model, having learned a good representation of features for over a million images belonging to 1,000 different categories, can act as a good feature extractor for new images suitable for computer vision problems. These new images might never exist in the ImageNet dataset or might be of totally different categories, but the model should still be able to extract relevant features from these images." }, { "code": null, "e": 43428, "s": 43003, "text": "This gives us an advantage of using pre-trained models as effective feature extractors for new images, to solve diverse and complex computer vision tasks, such as solving our cat versus dog classifier with fewer images, or even building a dog breed classifier, a facial expression classifier, and much more! Let’s briefly discuss the VGG-16 model architecture before unleashing the power of transfer learning on our problem." }, { "code": null, "e": 43944, "s": 43428, "text": "The VGG-16 model is a 16-layer (convolution and fully connected) network built on the ImageNet database, which is built for the purpose of image recognition and classification. This model was built by Karen Simonyan and Andrew Zisserman and is mentioned in their paper titled ‘Very Deep Convolutional Networks for Large-Scale Image Recognition’. I recommend all interested readers to go and read up on the excellent literature in this paper. The architecture of the VGG-16 model is depicted in the following figure." }, { "code": null, "e": 44558, "s": 43944, "text": "You can clearly see that we have a total of 13 convolution layers using 3 x 3 convolution filters along with max pooling layers for downsampling and a total of two fully connected hidden layers of 4096 units in each layer followed by a dense layer of 1000 units, where each unit represents one of the image categories in the ImageNet database. We do not need the last three layers since we will be using our own fully connected dense layers to predict whether images will be a dog or a cat. We are more concerned with the first five blocks, so that we can leverage the VGG model as an effective feature extractor." }, { "code": null, "e": 45167, "s": 44558, "text": "For one of the models, we will use it as a simple feature extractor by freezing all the five convolution blocks to make sure their weights don’t get updated after each epoch. For the last model, we will apply fine-tuning to the VGG model, where we will unfreeze the last two blocks (Block 4 and Block 5) so that their weights get updated in each epoch (per batch of data) as we train our own model. We represent the preceding architecture, along with the two variants (basic feature extractor and fine-tuning) that we will be using, in the following block diagram, so you can get a better visual perspective." }, { "code": null, "e": 45386, "s": 45167, "text": "Thus, we are mostly concerned with leveraging the convolution blocks of the VGG-16 model and then flattening the final output (from the feature maps) so that we can feed it into our own dense layers for our classifier." }, { "code": null, "e": 45526, "s": 45386, "text": "Let’s leverage Keras, load up the VGG-16 model, and freeze the convolution blocks so that we can use it as just an image feature extractor." }, { "code": null, "e": 46017, "s": 45526, "text": "It is quite clear from the preceding output that all the layers of the VGG-16 model are frozen, which is good, because we don’t want their weights to change during model training. The last activation feature map in the VGG-16 model (output from block5_pool) gives us the bottleneck features, which can then be flattened and fed to a fully connected deep neural network classifier. The following snippet shows what the bottleneck features look like for a sample image from our training data." }, { "code": null, "e": 46169, "s": 46017, "text": "bottleneck_feature_example = vgg.predict(train_imgs_scaled[0:1])print(bottleneck_feature_example.shape)plt.imshow(bottleneck_feature_example[0][:,:,0])" }, { "code": null, "e": 46558, "s": 46169, "text": "We flatten the bottleneck features in the vgg_model object to make them ready to be fed to our fully connected classifier. A way to save time in model training is to use this model and extract out all the features from our training and validation datasets and then feed them as inputs to our classifier. Let’s extract out the bottleneck features from our training and validation sets now." }, { "code": null, "e": 46644, "s": 46558, "text": "Train Bottleneck Features: (3000, 8192) \tValidation Bottleneck Features: (1000, 8192)" }, { "code": null, "e": 46942, "s": 46644, "text": "The preceding output tells us that we have successfully extracted the flattened bottleneck features of dimension 1 x 8192 for our 3,000 training images and our 1,000 validation images. Let’s build the architecture of our deep neural network classifier now, which will take these features as input." }, { "code": null, "e": 47179, "s": 46942, "text": "Just like we mentioned previously, bottleneck feature vectors of size 8192 serve as input to our classification model. We use the same architecture as our previous models here with regard to the dense layers. Let’s train this model now." }, { "code": null, "e": 47740, "s": 47179, "text": "Train on 3000 samples, validate on 1000 samplesEpoch 1/303000/3000 - 1s 373us/step - loss: 0.4325 - acc: 0.7897 - val_loss: 0.2958 - val_acc: 0.8730Epoch 2/303000/3000 - 1s 286us/step - loss: 0.2857 - acc: 0.8783 - val_loss: 0.3294 - val_acc: 0.8530Epoch 3/303000/3000 - 1s 289us/step - loss: 0.2353 - acc: 0.9043 - val_loss: 0.2708 - val_acc: 0.8700......Epoch 29/303000/3000 - 1s 287us/step - loss: 0.0121 - acc: 0.9943 - val_loss: 0.7760 - val_acc: 0.8930Epoch 30/303000/3000 - 1s 287us/step - loss: 0.0102 - acc: 0.9987 - val_loss: 0.8344 - val_acc: 0.8720" }, { "code": null, "e": 48308, "s": 47740, "text": "We get a model with a validation accuracy of close to 88%, almost a 5–6% improvement from our basic CNN model with image augmentation, which is excellent. The model does seem to be overfitting though. There is a decent gap between the model train and validation accuracy after the fifth epoch, which kind of makes it clear that the model is overfitting on the training data after that. But overall, this seems to be the best model so far. Let’s try using our image augmentation strategy on this model. Before that, we save this model to disk using the following code." }, { "code": null, "e": 48352, "s": 48308, "text": "model.save('cats_dogs_tlearn_basic_cnn.h5')" }, { "code": null, "e": 48530, "s": 48352, "text": "We will leverage the same data generators for our train and validation datasets that we used before. The code for building them is depicted as follows for ease of understanding." }, { "code": null, "e": 49053, "s": 48530, "text": "Let’s now build our deep learning model and train it. We won’t extract the bottleneck features like last time since we will be training on data generators; hence, we will be passing the vgg_model object as an input to our own model. We bring the learning rate slightly down since we will be training for 100 epochs and don’t want to make any sudden abrupt weight adjustments to our model layers. Do remember that the VGG-16 model’s layers are still frozen here, and we are still using it as a basic feature extractor only." }, { "code": null, "e": 49568, "s": 49053, "text": "Epoch 1/100100/100 - 45s 449ms/step - loss: 0.6511 - acc: 0.6153 - val_loss: 0.5147 - val_acc: 0.7840Epoch 2/100100/100 - 41s 414ms/step - loss: 0.5651 - acc: 0.7110 - val_loss: 0.4249 - val_acc: 0.8180Epoch 3/100100/100 - 41s 415ms/step - loss: 0.5069 - acc: 0.7527 - val_loss: 0.3790 - val_acc: 0.8260......Epoch 99/100100/100 - 42s 417ms/step - loss: 0.2656 - acc: 0.8907 - val_loss: 0.2757 - val_acc: 0.9050Epoch 100/100100/100 - 42s 418ms/step - loss: 0.2876 - acc: 0.8833 - val_loss: 0.2665 - val_acc: 0.9000" }, { "code": null, "e": 49890, "s": 49568, "text": "We can see that our model has an overall validation accuracy of 90%, which is a slight improvement from our previous model, and also the train and validation accuracy are quite close to each other, indicating that the model is not overfitting. Let’s save this model on the disk now for future evaluation on the test data." }, { "code": null, "e": 49936, "s": 49890, "text": "model.save(‘cats_dogs_tlearn_img_aug_cnn.h5’)" }, { "code": null, "e": 50089, "s": 49936, "text": "We will now fine-tune the VGG-16 model to build our last classifier, where we will unfreeze blocks 4 and 5, as we depicted in our block diagram earlier." }, { "code": null, "e": 50294, "s": 50089, "text": "We will now leverage our VGG-16 model object stored in the vgg_model variable and unfreeze convolution blocks 4 and 5 while keeping the first three blocks frozen. The following code helps us achieve this." }, { "code": null, "e": 50899, "s": 50294, "text": "You can clearly see from the preceding output that the convolution and pooling layers pertaining to blocks 4 and 5 are now trainable. This means the weights for these layers will also get updated with backpropagation in each epoch as we pass each batch of data. We will use the same data generators and model architecture as our previous model and train our model. We reduce the learning rate slightly, since we don’t want to get stuck at any local minimal, and we also do not want to suddenly update the weights of the trainable VGG-16 model layers by a big factor that might adversely affect the model." }, { "code": null, "e": 51414, "s": 50899, "text": "Epoch 1/100100/100 - 64s 642ms/step - loss: 0.6070 - acc: 0.6547 - val_loss: 0.4029 - val_acc: 0.8250Epoch 2/100100/100 - 63s 630ms/step - loss: 0.3976 - acc: 0.8103 - val_loss: 0.2273 - val_acc: 0.9030Epoch 3/100100/100 - 63s 631ms/step - loss: 0.3440 - acc: 0.8530 - val_loss: 0.2221 - val_acc: 0.9150......Epoch 99/100100/100 - 63s 629ms/step - loss: 0.0243 - acc: 0.9913 - val_loss: 0.2861 - val_acc: 0.9620Epoch 100/100100/100 - 63s 629ms/step - loss: 0.0226 - acc: 0.9930 - val_loss: 0.3002 - val_acc: 0.9610" }, { "code": null, "e": 51974, "s": 51414, "text": "We can see from the preceding output that our model has obtained a validation accuracy of around 96%, which is a 6% improvement from our previous model. Overall, this model has gained a 24% improvement in validation accuracy from our first basic CNN model. This really shows how useful transfer learning can be. We can see that accuracy values are really excellent here, and although the model looks like it might be slightly overfitting on the training data, we still get great validation accuracy. Let’s save this model to disk now using the following code." }, { "code": null, "e": 52029, "s": 51974, "text": "model.save('cats_dogs_tlearn_finetune_img_aug_cnn.h5')" }, { "code": null, "e": 52132, "s": 52029, "text": "Let’s now put all our models to the test by actually evaluating their performance on our test dataset." }, { "code": null, "e": 52522, "s": 52132, "text": "We will now evaluate the five different models that we built so far, by first testing them on our test dataset, because just validation is not enough! We have also built a nifty utility module called model_evaluation_utils, which we will be using to evaluate the performance of our deep learning models. Let's load up the necessary dependencies and our saved models before getting started." }, { "code": null, "e": 52736, "s": 52522, "text": "It’s time now for the final test, where we literally test the performance of our models by making predictions on our test dataset. Let’s load up and prepare our test dataset first before we try making predictions." }, { "code": null, "e": 52827, "s": 52736, "text": "Test dataset shape: (1000, 150, 150, 3)['dog', 'dog', 'dog', 'dog', 'dog'] [1, 1, 1, 1, 1]" }, { "code": null, "e": 53029, "s": 52827, "text": "Now that we have our scaled dataset ready, let’s evaluate each model by making predictions for all the test images, and then evaluate the model performance by checking how accurate are the predictions." }, { "code": null, "e": 53233, "s": 53029, "text": "We can see that we definitely have some interesting results. Each subsequent model performs better than the previous model, which is expected, since we tried more advanced techniques with each new model." }, { "code": null, "e": 53622, "s": 53233, "text": "Our worst model is our basic CNN model, with a model accuracy and F1-score of around 78%, and our best model is our fine-tuned model with transfer learning and image augmentation, which gives us a model accuracy and F1-score of 96%, which is really amazing considering we trained our model from our 3,000 image training dataset. Let’s plot the ROC curves of our worst and best models now." }, { "code": null, "e": 53882, "s": 53622, "text": "This should give you a good idea of how much of a difference pre-trained models and transfer learning can make, especially in tackling complex problems when we have constraints like less data. We encourage you to try out similar strategies with your own data!" }, { "code": null, "e": 54414, "s": 53882, "text": "Now in this case study, let us level up the game and make the task of image classification even more exciting. We built a simple binary classification model in the previous case study (albeit we used some complex techniques for solving the small data constraint problem!). In this case-study, we will be concentrating toward the task of fine-grained image classification. Unlike usual image classification tasks, fine-grained image classification refers to the task of recognizing different sub-classes within a higher-level class." }, { "code": null, "e": 54814, "s": 54414, "text": "To help understand this task better, we will be focusing our discussion around the Stanford Dogs dataset. This dataset, as the name suggests, contains images of different dog breeds. In this case, the task is to identify each of those dog breeds. Hence, the high-level concept is the dog itself, while the task is to categorize different subconcepts or subclasses — in this case, breeds — correctly." }, { "code": null, "e": 55172, "s": 54814, "text": "We will be leveraging the dataset available through Kaggle available here. We will only be using the train dataset since it has labeled data. This dataset contains around 10,000 labeled images of 120 different dog breeds. Thus our task is to build a fine-grained 120-class classification model to categorize 120 different dog breeds. Definitely challenging!" }, { "code": null, "e": 55278, "s": 55172, "text": "Let’s take a look at how our dataset looks like by loading the data and viewing a sample batch of images." }, { "code": null, "e": 55565, "s": 55278, "text": "From the preceding grid, we can see that there is a lot of variation, in terms of resolution, lighting, zoom levels, and so on, available along with the fact that images do not just contain just a single dog but other dogs and surrounding items as well. This is going to be a challenge!" }, { "code": null, "e": 55668, "s": 55565, "text": "Let’s start by looking at how the dataset labels look like to get an idea of what we are dealing with." }, { "code": null, "e": 55820, "s": 55668, "text": "data_labels = pd.read_csv('labels/labels.csv')target_labels = data_labels['breed']print(len(set(target_labels)))data_labels.head()------------------120" }, { "code": null, "e": 56017, "s": 55820, "text": "What we do next is to add in the exact image path for each image present in the disk using the following code. This will help us in easily locating and loading up the images during model training." }, { "code": null, "e": 56152, "s": 56017, "text": "It’s now time to prepare our train, test and validation datasets. We will leverage the following code to help us build these datasets!" }, { "code": null, "e": 56448, "s": 56152, "text": "Initial Dataset Size: (10222, 299, 299, 3)Initial Train and Test Datasets Size: (7155, 299, 299, 3) (3067, 299, 299, 3)Train and Validation Datasets Size: (6081, 299, 299, 3) (1074, 299, 299, 3)Train, Test and Validation Datasets Size: (6081, 299, 299, 3) (3067, 299, 299, 3) (1074, 299, 299, 3)" }, { "code": null, "e": 56550, "s": 56448, "text": "We also need to convert the text class labels to one-hot encoded labels, else our model will not run." }, { "code": null, "e": 56590, "s": 56550, "text": "((6081, 120), (3067, 120), (1074, 120))" }, { "code": null, "e": 56925, "s": 56590, "text": "Everything looks to be in order. Now, if you remember from the previous case study, image augmentation is a great way to deal with having less data per class. In this case, we have a total of 10222 samples and 120 classes. This means, an average of only 85 images per class! We do this using the ImageDataGenerator utility from keras." }, { "code": null, "e": 57018, "s": 56925, "text": "Now that we have our data ready, the next step is to actually build our deep learning model!" }, { "code": null, "e": 57416, "s": 57018, "text": "Now that our datasets are ready, let’s get started with the modeling process. We already know how to build a deep convolutional network from scratch. We also understand the amount of fine-tuning required to achieve good performance. For this task, we will be utilizing concepts of transfer learning. A pre-trained model is the basic ingredient required to begin with the task of transfer learning." }, { "code": null, "e": 58128, "s": 57416, "text": "In this case study, we will concentrate on utilizing a pre-trained model as a feature extractor. We know, a deep learning model is basically a stacking of interconnected layers of neurons, with the final one acting as a classifier. This architecture enables deep neural networks to capture different features at different levels in the network. Thus, we can utilize this property to use them as feature extractors. This is made possible by removing the final layer or using the output from the penultimate layer. This output from the penultimate layer is then fed into an additional set of layers, followed by a classification layer. We will be using the Inception V3 Model from Google as our pre-trained model." }, { "code": null, "e": 58471, "s": 58128, "text": "Based on the previous output, you can clearly see that the Inception V3 model is huge with a lot of layers and parameters. Let’s start training our model now. We train the model using the fit_generator(...) method to leverage the data augmentation prepared in the previous step. We set the batch size to 32, and train the model for 15 epochs." }, { "code": null, "e": 58985, "s": 58471, "text": "Epoch 1/15190/190 - 155s 816ms/step - loss: 4.1095 - acc: 0.2216 - val_loss: 2.6067 - val_acc: 0.5748Epoch 2/15190/190 - 159s 836ms/step - loss: 2.1797 - acc: 0.5719 - val_loss: 1.0696 - val_acc: 0.7377Epoch 3/15190/190 - 155s 815ms/step - loss: 1.3583 - acc: 0.6814 - val_loss: 0.7742 - val_acc: 0.7888......Epoch 14/15190/190 - 156s 823ms/step - loss: 0.6686 - acc: 0.8030 - val_loss: 0.6745 - val_acc: 0.7955Epoch 15/15190/190 - 161s 850ms/step - loss: 0.6276 - acc: 0.8194 - val_loss: 0.6579 - val_acc: 0.8144" }, { "code": null, "e": 59286, "s": 58985, "text": "The model achieves a commendable performance of more than 80% accuracy on both train and validation sets within just 15 epochs. The plot on the right-hand side shows how quickly the loss drops and converges to around 0.5. This is a clear example of how powerful, yet simple, transfer learning can be." }, { "code": null, "e": 59674, "s": 59286, "text": "Training and validation performance is pretty good, but how about performance on unseen data? Since we already divided our original dataset into three separate portions. The important thing to remember here is that the test dataset has to undergo similar pre-processing as the training dataset. To account for this, we scale the test dataset as well, before feeding it into the function." }, { "code": null, "e": 59736, "s": 59674, "text": "Accuracy: 0.864Precision: 0.8783Recall: 0.864F1 Score: 0.8591" }, { "code": null, "e": 60041, "s": 59736, "text": "The model achieves an amazing 86% accuracy as well as F1-score on the test dataset. Given that we just trained for 15 epochs with minimal inputs from our side, transfer learning helped us achieve a pretty decent classifier. We can also check the per-class classification metrics using the following code." }, { "code": null, "e": 60135, "s": 60041, "text": "We can also visualize model predictions in a visually appealing way using the following code." }, { "code": null, "e": 60343, "s": 60135, "text": "The preceding image presents a visual proof of the model’s performance. As we can see, in most of the cases, the model is not only predicting the correct dog breed, it also does so with very high confidence." }, { "code": null, "e": 60568, "s": 60343, "text": "We have already covered several advantages of transfer learning in some way or the other in the previous sections. Typically transfer learning enables us to build more robust models which can perform a wide variety of tasks." }, { "code": null, "e": 60633, "s": 60568, "text": "Helps solve complex real-world problems with several constraints" }, { "code": null, "e": 60707, "s": 60633, "text": "Tackle problems like having little or almost no labeled data availability" }, { "code": null, "e": 60790, "s": 60707, "text": "Ease of transfering knowledge from one model to another based on domains and tasks" }, { "code": null, "e": 60880, "s": 60790, "text": "Provides a path towards achieving Artificial General Intelligence some day in the future!" }, { "code": null, "e": 61256, "s": 60880, "text": "Transfer learning has immense potential and is a commonly required enhancement for existing learning algorithms. Yet, there are certain pertinent issues related to transfer learning that need more research and exploration. Apart from the difficulty of answering the questions of what, when, and how to transfer, negative transfer and transfer bounds present major challenges." }, { "code": null, "e": 62373, "s": 61256, "text": "Negative Transfer: The cases we have discussed so far talk about improvements in target tasks based on knowledge transfer from the source task. There are cases when transfer learning can lead to a drop in performance. Negative transfer refers to scenarios where the transfer of knowledge from the source to the target does not lead to any improvement, but rather causes a drop in the overall performance of the target task. There can be various reasons for negative transfer, such as cases when the source task is not sufficiently related to the target task, or if the transfer method could not leverage the relationship between the source and target tasks very well. Avoiding negative transfer is very important and requires careful investigation. In their work, Rosenstien and their co-authors present empirically how brute-force transfer degrades performance in target tasks when the source and target are too dissimilar. Bayesian approaches by Bakker and their co-authors, along with other techniques exploring clustering-based solutions to identify relatedness, are being researched to avoid negative transfers." }, { "code": null, "e": 63005, "s": 62373, "text": "Transfer Bounds: Quantifying the transfer in transfer learning is also very important, that affects the quality of the transfer and its viability. To gauge the amount for the transfer, Hassan Mahmud and their co-authors used Kolmogorov complexity to prove certain theoretical bounds to analyze transfer learning and measure relatedness between tasks. Eaton and their co-authors presented a novel graph-based approach to measure knowledge transfer. Detailed discussions of these techniques are outside the scope of this article. Readers are encouraged to explore more on these topics using the publications outlined in this section!" }, { "code": null, "e": 63390, "s": 63005, "text": "This concludes perhaps one of my longest articles with a comprehensive coverage about transfer learning concepts, strategies, focus on deep transfer learning, challenges and advantages. We also covered two hands-on real-world case studies to give you a good idea of how to implement these techniques. If you are reading this section, kudos on reading through this pretty long article!" }, { "code": null, "e": 63747, "s": 63390, "text": "Transfer learning is definitely going to be one of the key drivers for machine learning and deep learning success in mainstream adoption in the industry. I definitely hope to see more pre-trained models and innovative case studies which leverage this concept and methodology. For some of my future articles, you can definitely expect some of the following." }, { "code": null, "e": 63773, "s": 63747, "text": "Transfer Learning for NLP" }, { "code": null, "e": 63805, "s": 63773, "text": "Transfer Learning on Audio Data" }, { "code": null, "e": 63852, "s": 63805, "text": "Transfer Learning for Generative Deep Learning" }, { "code": null, "e": 63912, "s": 63852, "text": "More complex Computer Vision problems like Image Captioning" }, { "code": null, "e": 64108, "s": 63912, "text": "Let’s hope for more success stories around transfer learning and deep learning which enable us to build more intelligent systems to make the world a better place and drive our own personal goals!" }, { "code": null, "e": 64287, "s": 64108, "text": "All of the content above has been adopted in some form from my recent book, ‘Hands on Transfer Learning with Python’ which is available on the Packt website as well as on Amazon." }, { "code": null, "e": 64302, "s": 64287, "text": "www.amazon.com" }, { "code": null, "e": 64492, "s": 64302, "text": "Don’t have the time to read through the book or can’t spend right now? Don’t worry, you can still access all the wonderful examples and case studies we implemented on our GitHub repository!" }, { "code": null, "e": 64503, "s": 64492, "text": "github.com" }, { "code": null, "e": 64628, "s": 64503, "text": "A big shoutout goes to my co-authors Raghav & Tamoghna for working with me on the book which paved the way for this content!" }, { "code": null, "e": 64798, "s": 64628, "text": "Thanks to Francois Chollet and his amazing book ‘Deep Learning with Python’ for a lot of the motivation and inspiration behind some of the examples used in this article." }, { "code": null, "e": 64814, "s": 64798, "text": "www.manning.com" }, { "code": null, "e": 64995, "s": 64814, "text": "Have feedback for me? Or interested in working with me on research, data science, artificial intelligence or even publishing an article on TDS? You can reach out to me on LinkedIn." }, { "code": null, "e": 65012, "s": 64995, "text": "www.linkedin.com" } ]
What are the in-built functional interfaces in Java?
The java.util.function package defines several in-built functional interfaces that can be used when creating lambda expressions or method references. The Function interface has only one single method apply(). It can accept an object of any data type and returns a result of any datatype. import java.util.*; import java.util.function.*; public class FunctionTest { public static void main(String args[]) { String[] countries = {"India", "Australia", "England", "South Africa", "Srilanka", "Newzealand", "West Indies", "Scotland"}; Function<String[], String> converter = (all) -> { // lambda expression String names = ""; for(String n : all) { String result = n.substring(0, n.indexOf("")); result = n.substring(n.indexOf("")) + " " + result; names += result + "\n"; } return names; }; System.out.println(converter.apply(countries)); } } India Australia England South Africa Srilanka Newzealand West Indies Scotland A Supplier interface has only one single method called get(). It does not accept any arguments and returns an object of any data type. import java.util.*; import java.util.function.*; public class SupplierTest { private static void printNames(Supplier<String> arg) { System.out.println(arg.get()); } private static void listBeginWith(List<String> list, Predicate<String> valid) { printNames(() -> "\nList of countries:"); list.forEach(country -> { // lambda expression if(valid.test(country)) { printNames(() -> country); } }); } public static void main(String[] args) { String[] countries = {"India", "Australia", "England", "South Africa", "Srilanka", "Newzealand", "West Indies"}; List<String> countryList = Arrays.asList(countries); listBeginWith(countryList, (s) -> s.startsWith("I")); listBeginWith(countryList, (s) -> s.contains("I")); listBeginWith(countryList, (s) -> s.endsWith("ia")); } } List of countries: India List of countries: India West Indies List of countries: India Australia The Consumer interface has only one single method called accept(). It accepts a single argument of any data type and does not return any result. import java.util.*; import java.util.function.*; public class ConsumerTest { public static void main(String[] args) { String[] countries = {"India", "Australia", "England", "South Africa", "Srilanka", "Newzealand", "West Indies"}; System.out.print("The list of countries:\n"); Arrays.asList(countries).forEach((country) -> System.out.println(country)); // lambda expression } } The list of countries: India Australia England South Africa Srilanka Newzealand West Indies The Predicate interface has only one single method test(). It may be true or false depending on the values of its variables. import java.util.*; import java.util.function.*; public class PredicateTest { private static List getBeginWith(List<String> list, Predicate<String> valid) { List<String> selected = new ArrayList<>(); list.forEach(country -> { // lambda expression if(valid.test(country)) { selected.add(country); } }); return selected; } public static void main(String[] args) { String[] countries = {"India", "Australia", "England", "South Africa", "Srilanka", "Newzealand", "West Indies"}; List<String> countryList = Arrays.asList(countries); System.out.println(getBeginWith(countryList, (s) -> s.startsWith("A"))); System.out.println(getBeginWith(countryList, (s) -> s.contains("W"))); System.out.println(getBeginWith(countryList, (s) -> s.endsWith("nd"))); } } [Australia] [West Indies] [England, Newzealand]
[ { "code": null, "e": 1212, "s": 1062, "text": "The java.util.function package defines several in-built functional interfaces that can be used when creating lambda expressions or method references." }, { "code": null, "e": 1350, "s": 1212, "text": "The Function interface has only one single method apply(). It can accept an object of any data type and returns a result of any datatype." }, { "code": null, "e": 2003, "s": 1350, "text": "import java.util.*;\nimport java.util.function.*;\n\npublic class FunctionTest {\n public static void main(String args[]) {\n String[] countries = {\"India\", \"Australia\", \"England\", \"South Africa\", \"Srilanka\", \"Newzealand\", \"West Indies\", \"Scotland\"};\n Function<String[], String> converter = (all) -> { // lambda expression\n String names = \"\";\n for(String n : all) {\n String result = n.substring(0, n.indexOf(\"\"));\n result = n.substring(n.indexOf(\"\")) + \" \" + result;\n names += result + \"\\n\";\n }\n return names;\n };\n System.out.println(converter.apply(countries));\n }\n}" }, { "code": null, "e": 2081, "s": 2003, "text": "India\nAustralia\nEngland\nSouth Africa\nSrilanka\nNewzealand\nWest Indies\nScotland" }, { "code": null, "e": 2216, "s": 2081, "text": "A Supplier interface has only one single method called get(). It does not accept any arguments and returns an object of any data type." }, { "code": null, "e": 3088, "s": 2216, "text": "import java.util.*;\nimport java.util.function.*;\n\npublic class SupplierTest {\n private static void printNames(Supplier<String> arg) {\n System.out.println(arg.get());\n }\n private static void listBeginWith(List<String> list, Predicate<String> valid) {\n printNames(() -> \"\\nList of countries:\");\n list.forEach(country -> { // lambda expression\n if(valid.test(country)) {\n printNames(() -> country);\n }\n });\n }\n public static void main(String[] args) {\n String[] countries = {\"India\", \"Australia\", \"England\", \"South Africa\", \"Srilanka\", \"Newzealand\", \"West Indies\"};\n List<String> countryList = Arrays.asList(countries);\n listBeginWith(countryList, (s) -> s.startsWith(\"I\"));\n listBeginWith(countryList, (s) -> s.contains(\"I\"));\n listBeginWith(countryList, (s) -> s.endsWith(\"ia\"));\n }\n}" }, { "code": null, "e": 3187, "s": 3088, "text": "List of countries:\nIndia\n\nList of countries:\nIndia\nWest Indies\n\nList of countries:\nIndia\nAustralia" }, { "code": null, "e": 3332, "s": 3187, "text": "The Consumer interface has only one single method called accept(). It accepts a single argument of any data type and does not return any result." }, { "code": null, "e": 3735, "s": 3332, "text": "import java.util.*;\nimport java.util.function.*;\n\npublic class ConsumerTest {\n public static void main(String[] args) {\n String[] countries = {\"India\", \"Australia\", \"England\", \"South Africa\", \"Srilanka\", \"Newzealand\", \"West Indies\"};\n System.out.print(\"The list of countries:\\n\");\n Arrays.asList(countries).forEach((country) -> System.out.println(country)); // lambda expression\n }\n}" }, { "code": null, "e": 3827, "s": 3735, "text": "The list of countries:\nIndia\nAustralia\nEngland\nSouth Africa\nSrilanka\nNewzealand\nWest Indies" }, { "code": null, "e": 3952, "s": 3827, "text": "The Predicate interface has only one single method test(). It may be true or false depending on the values of its variables." }, { "code": null, "e": 4810, "s": 3952, "text": "import java.util.*;\nimport java.util.function.*;\n\npublic class PredicateTest {\n private static List getBeginWith(List<String> list, Predicate<String> valid) {\n List<String> selected = new ArrayList<>();\n list.forEach(country -> { // lambda expression\n if(valid.test(country)) {\n selected.add(country);\n }\n });\n return selected;\n }\n public static void main(String[] args) {\n String[] countries = {\"India\", \"Australia\", \"England\", \"South Africa\", \"Srilanka\", \"Newzealand\", \"West Indies\"};\n List<String> countryList = Arrays.asList(countries);\n System.out.println(getBeginWith(countryList, (s) -> s.startsWith(\"A\")));\n System.out.println(getBeginWith(countryList, (s) -> s.contains(\"W\")));\n System.out.println(getBeginWith(countryList, (s) -> s.endsWith(\"nd\")));\n }\n}" }, { "code": null, "e": 4858, "s": 4810, "text": "[Australia]\n[West Indies]\n[England, Newzealand]" } ]
DateTime.Add() Method in C#
The DateTime.Add() method in C# is used to return a new DateTime that adds the value of the specified TimeSpan to the value of this instance. Following is the syntax − public DateTime Add (TimeSpan val); Above, Val is the positive or negative time interval. Let us now see an example to implement the DateTime.Add() method − using System; public class Demo { public static void Main(){ DateTime d1 = new DateTime(2019, 3, 7, 8, 0, 15); TimeSpan span = new TimeSpan(115, 0, 0, 0); DateTime d2 = d1.Add(span); System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1); System.Console.WriteLine("\nNew DateTime = {0:y} {0:dd}", d2); } } This will produce the following output − Initial DateTime = March 2019 07 New DateTime = June 2019 30 Let us now see another example to implement the DateTime.Add() method − using System; public class Demo { public static void Main(){ DateTime d1 = new DateTime(2019, 9, 7, 8, 0, 15); // subtracting days TimeSpan span = new TimeSpan(-75, 0, 0, 0); DateTime d2 = d1.Add(span); System.Console.WriteLine("Initial DateTime = {0:y} {0:dd}", d1); System.Console.WriteLine("\nNew DateTime = {0:y} {0:dd}", d2); } } This will produce the following output − Initial DateTime = September 2019 07 New DateTime = June 2019 24
[ { "code": null, "e": 1204, "s": 1062, "text": "The DateTime.Add() method in C# is used to return a new DateTime that adds the value of the specified TimeSpan to the value of this instance." }, { "code": null, "e": 1230, "s": 1204, "text": "Following is the syntax −" }, { "code": null, "e": 1266, "s": 1230, "text": "public DateTime Add (TimeSpan val);" }, { "code": null, "e": 1320, "s": 1266, "text": "Above, Val is the positive or negative time interval." }, { "code": null, "e": 1387, "s": 1320, "text": "Let us now see an example to implement the DateTime.Add() method −" }, { "code": null, "e": 1738, "s": 1387, "text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime d1 = new DateTime(2019, 3, 7, 8, 0, 15);\n TimeSpan span = new TimeSpan(115, 0, 0, 0);\n DateTime d2 = d1.Add(span);\n System.Console.WriteLine(\"Initial DateTime = {0:y} {0:dd}\", d1);\n System.Console.WriteLine(\"\\nNew DateTime = {0:y} {0:dd}\", d2);\n }\n}" }, { "code": null, "e": 1779, "s": 1738, "text": "This will produce the following output −" }, { "code": null, "e": 1840, "s": 1779, "text": "Initial DateTime = March 2019 07\nNew DateTime = June 2019 30" }, { "code": null, "e": 1912, "s": 1840, "text": "Let us now see another example to implement the DateTime.Add() method −" }, { "code": null, "e": 2289, "s": 1912, "text": "using System;\npublic class Demo {\n public static void Main(){\n DateTime d1 = new DateTime(2019, 9, 7, 8, 0, 15);\n // subtracting days\n TimeSpan span = new TimeSpan(-75, 0, 0, 0);\n DateTime d2 = d1.Add(span);\n System.Console.WriteLine(\"Initial DateTime = {0:y} {0:dd}\", d1);\n System.Console.WriteLine(\"\\nNew DateTime = {0:y} {0:dd}\", d2);\n }\n}" }, { "code": null, "e": 2330, "s": 2289, "text": "This will produce the following output −" }, { "code": null, "e": 2395, "s": 2330, "text": "Initial DateTime = September 2019 07\nNew DateTime = June 2019 24" } ]
Get index of first true value of array in Julia | Array findfirst() Method - GeeksforGeeks
23 Mar, 2020 The findfirst() is an inbuilt function in julia which is used to return the index or key of the first true value in the specified array. Here values of index or key start from 1 i.e, for index of 1st element is 1, index of 2nd element is 2 and so on. Syntax:findfirst(A)orfindfirst(predicate::Function, A) Parameters: A: Specified array Predicate Function: Determines whether something is true or false based on the specified arguments Returns: It returns the index or key of the first true value in the specified array. Example 1: # Julia program to illustrate # the use of Array findfirst() method # Finding index of first true value from # the 1D array AA = [false, true, true, false]println(findfirst(A)) # Finding index of first true value from # the 2D array B of size 2 * 2B = [false false; true false]println(findfirst(B)) # Finding index of first true value from # the 3D array C of size 2 * 2*2C = cat([false false; true false], [false true; true false], [true false; true true], dims = 3)println(findfirst(C)) Output: Example 2: # Julia program to illustrate # the use of Array findfirst() method # Finding index of first even value from # the 1D array AA = [1, 2, 5, 6]println(findfirst(iseven, A)) # Finding index of first even value from # the 2D array B of size 2 * 2B = [3 5; 6 7]println(findfirst(iseven, B)) # Finding index of first even value from # the 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3)println(findfirst(iseven, C)) Output: Julia Array-functions Julia Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments while loop in Julia Getting rounded value of a number in Julia - round() Method Working with Date and Time in Julia Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder) Storing Output on a File in Julia Functions in Julia Working with DataFrames in Julia Reshaping array dimensions in Julia | Array reshape() Method Get array dimensions and size of a dimension in Julia - size() Method Vectors in Julia
[ { "code": null, "e": 23993, "s": 23965, "text": "\n23 Mar, 2020" }, { "code": null, "e": 24244, "s": 23993, "text": "The findfirst() is an inbuilt function in julia which is used to return the index or key of the first true value in the specified array. Here values of index or key start from 1 i.e, for index of 1st element is 1, index of 2nd element is 2 and so on." }, { "code": null, "e": 24299, "s": 24244, "text": "Syntax:findfirst(A)orfindfirst(predicate::Function, A)" }, { "code": null, "e": 24311, "s": 24299, "text": "Parameters:" }, { "code": null, "e": 24330, "s": 24311, "text": "A: Specified array" }, { "code": null, "e": 24429, "s": 24330, "text": "Predicate Function: Determines whether something is true or false based on the specified arguments" }, { "code": null, "e": 24514, "s": 24429, "text": "Returns: It returns the index or key of the first true value in the specified array." }, { "code": null, "e": 24525, "s": 24514, "text": "Example 1:" }, { "code": "# Julia program to illustrate # the use of Array findfirst() method # Finding index of first true value from # the 1D array AA = [false, true, true, false]println(findfirst(A)) # Finding index of first true value from # the 2D array B of size 2 * 2B = [false false; true false]println(findfirst(B)) # Finding index of first true value from # the 3D array C of size 2 * 2*2C = cat([false false; true false], [false true; true false], [true false; true true], dims = 3)println(findfirst(C))", "e": 25035, "s": 24525, "text": null }, { "code": null, "e": 25043, "s": 25035, "text": "Output:" }, { "code": null, "e": 25054, "s": 25043, "text": "Example 2:" }, { "code": "# Julia program to illustrate # the use of Array findfirst() method # Finding index of first even value from # the 1D array AA = [1, 2, 5, 6]println(findfirst(iseven, A)) # Finding index of first even value from # the 2D array B of size 2 * 2B = [3 5; 6 7]println(findfirst(iseven, B)) # Finding index of first even value from # the 3D array C of size 2 * 2*2C = cat([1 2; 3 4], [5 6; 7 8], [9 10; 11 12], dims = 3)println(findfirst(iseven, C))", "e": 25513, "s": 25054, "text": null }, { "code": null, "e": 25521, "s": 25513, "text": "Output:" }, { "code": null, "e": 25543, "s": 25521, "text": "Julia Array-functions" }, { "code": null, "e": 25549, "s": 25543, "text": "Julia" }, { "code": null, "e": 25647, "s": 25549, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25656, "s": 25647, "text": "Comments" }, { "code": null, "e": 25669, "s": 25656, "text": "Old Comments" }, { "code": null, "e": 25689, "s": 25669, "text": "while loop in Julia" }, { "code": null, "e": 25749, "s": 25689, "text": "Getting rounded value of a number in Julia - round() Method" }, { "code": null, "e": 25785, "s": 25749, "text": "Working with Date and Time in Julia" }, { "code": null, "e": 25858, "s": 25785, "text": "Decision Making in Julia (if, if-else, Nested-if, if-elseif-else ladder)" }, { "code": null, "e": 25892, "s": 25858, "text": "Storing Output on a File in Julia" }, { "code": null, "e": 25911, "s": 25892, "text": "Functions in Julia" }, { "code": null, "e": 25944, "s": 25911, "text": "Working with DataFrames in Julia" }, { "code": null, "e": 26005, "s": 25944, "text": "Reshaping array dimensions in Julia | Array reshape() Method" }, { "code": null, "e": 26075, "s": 26005, "text": "Get array dimensions and size of a dimension in Julia - size() Method" } ]
Ignore null values in MongoDB documents
To ignore null values in MongoDB, use "$ne" : null in aggregate(). Let us create a collection with documents − > db.demo722.insertOne( ... { ... id:101, ... details: [ ... { Name:""}, ... { Name: "David"}, ... {Name:null}, ... {Name:"Carol"} ... ] ... } ... ); { "acknowledged" : true, "insertedId" : ObjectId("5eab07d543417811278f5889") } Display all documents from a collection with the help of find() method − > db.demo722.find(); This will produce the following output − { "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : [ { "Name" : "" }, { "Name" : "David" }, { "Name" : null }, { "Name" : "Carol" } ] } Following is the query to ignore null values in MongoDB using $ne − > db.demo722.aggregate([ ... {"$unwind": "$details"}, ... ... {"$match": { "details.Name" :{ "$ne" : null } } } ... ]) This will produce the following output − { "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "" } } { "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "David" } } { "_id" : ObjectId("5eab07d543417811278f5889"), "id" : 101, "details" : { "Name" : "Carol" } }
[ { "code": null, "e": 1173, "s": 1062, "text": "To ignore null values in MongoDB, use \"$ne\" : null in aggregate(). Let us create a collection with documents −" }, { "code": null, "e": 1468, "s": 1173, "text": "> db.demo722.insertOne(\n... {\n... id:101,\n... details: [\n... { Name:\"\"},\n... { Name: \"David\"},\n... {Name:null},\n... {Name:\"Carol\"}\n... ]\n... }\n... );\n{\n \"acknowledged\" : true,\n \"insertedId\" : ObjectId(\"5eab07d543417811278f5889\")\n}" }, { "code": null, "e": 1541, "s": 1468, "text": "Display all documents from a collection with the help of find() method −" }, { "code": null, "e": 1562, "s": 1541, "text": "> db.demo722.find();" }, { "code": null, "e": 1603, "s": 1562, "text": "This will produce the following output −" }, { "code": null, "e": 1760, "s": 1603, "text": "{ \"_id\" : ObjectId(\"5eab07d543417811278f5889\"), \"id\" : 101, \"details\" : [ { \"Name\" : \"\" }, { \"Name\" : \"David\" }, { \"Name\" : null }, { \"Name\" : \"Carol\" } ] }" }, { "code": null, "e": 1828, "s": 1760, "text": "Following is the query to ignore null values in MongoDB using $ne −" }, { "code": null, "e": 1953, "s": 1828, "text": "> db.demo722.aggregate([\n... {\"$unwind\": \"$details\"},\n...\n... {\"$match\": { \"details.Name\" :{ \"$ne\" : null } } }\n... ])" }, { "code": null, "e": 1994, "s": 1953, "text": "This will produce the following output −" }, { "code": null, "e": 2274, "s": 1994, "text": "{ \"_id\" : ObjectId(\"5eab07d543417811278f5889\"), \"id\" : 101, \"details\" : { \"Name\" : \"\" } }\n{ \"_id\" : ObjectId(\"5eab07d543417811278f5889\"), \"id\" : 101, \"details\" : { \"Name\" : \"David\" } }\n{ \"_id\" : ObjectId(\"5eab07d543417811278f5889\"), \"id\" : 101, \"details\" : { \"Name\" : \"Carol\" } }" } ]
Calculate Inverse tangent of a value in R Programming - atan() Function - GeeksforGeeks
01 Jun, 2020 atan() function in R Language is used to calculate the inverse tangent value of the numeric value passed to it as argument. Syntax: atan(x) Parameter:x: Numeric value Example 1: # R code to calculate inverse tangent of a value # Assigning values to variablesx1 <- -1x2 <- 0.5 # Using atan() Functionatan(x1)atan(x2) Output: [1] -0.7853982 [1] 0.4636476 Example 2: # R code to calculate inverse tangent of a value # Assigning values to variables x1 <- 0.224587x2 <- 0.456732 # Using atan() Functionatan(x1)atan(x2) Output: [1] 0.2209213 [1] 0.4284381 R Math-Function R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Replace specific values in column in R DataFrame ? Filter data by multiple conditions in R using Dplyr Loops in R (for, while, repeat) Change Color of Bars in Barchart using ggplot2 in R How to change Row Names of DataFrame in R ? Printing Output of an R Program Remove rows with NA in one column of R DataFrame How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame?
[ { "code": null, "e": 24806, "s": 24778, "text": "\n01 Jun, 2020" }, { "code": null, "e": 24930, "s": 24806, "text": "atan() function in R Language is used to calculate the inverse tangent value of the numeric value passed to it as argument." }, { "code": null, "e": 24946, "s": 24930, "text": "Syntax: atan(x)" }, { "code": null, "e": 24973, "s": 24946, "text": "Parameter:x: Numeric value" }, { "code": null, "e": 24984, "s": 24973, "text": "Example 1:" }, { "code": "# R code to calculate inverse tangent of a value # Assigning values to variablesx1 <- -1x2 <- 0.5 # Using atan() Functionatan(x1)atan(x2)", "e": 25124, "s": 24984, "text": null }, { "code": null, "e": 25132, "s": 25124, "text": "Output:" }, { "code": null, "e": 25161, "s": 25132, "text": "[1] -0.7853982\n[1] 0.4636476" }, { "code": null, "e": 25172, "s": 25161, "text": "Example 2:" }, { "code": "# R code to calculate inverse tangent of a value # Assigning values to variables x1 <- 0.224587x2 <- 0.456732 # Using atan() Functionatan(x1)atan(x2)", "e": 25324, "s": 25172, "text": null }, { "code": null, "e": 25332, "s": 25324, "text": "Output:" }, { "code": null, "e": 25360, "s": 25332, "text": "[1] 0.2209213\n[1] 0.4284381" }, { "code": null, "e": 25376, "s": 25360, "text": "R Math-Function" }, { "code": null, "e": 25387, "s": 25376, "text": "R Language" }, { "code": null, "e": 25485, "s": 25387, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25494, "s": 25485, "text": "Comments" }, { "code": null, "e": 25507, "s": 25494, "text": "Old Comments" }, { "code": null, "e": 25565, "s": 25507, "text": "How to Replace specific values in column in R DataFrame ?" }, { "code": null, "e": 25617, "s": 25565, "text": "Filter data by multiple conditions in R using Dplyr" }, { "code": null, "e": 25649, "s": 25617, "text": "Loops in R (for, while, repeat)" }, { "code": null, "e": 25701, "s": 25649, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 25745, "s": 25701, "text": "How to change Row Names of DataFrame in R ?" }, { "code": null, "e": 25777, "s": 25745, "text": "Printing Output of an R Program" }, { "code": null, "e": 25826, "s": 25777, "text": "Remove rows with NA in one column of R DataFrame" }, { "code": null, "e": 25864, "s": 25826, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 25899, "s": 25864, "text": "Group by function in R using Dplyr" } ]
Python - Convert List of Lists to Tuple of Tuples - GeeksforGeeks
26 May, 2020 Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let’s discuss certain ways in which this task can be performed. Input : test_list = [[‘Best’], [‘Gfg’], [‘Gfg’]]Output : ((‘Best’, ), (‘Gfg’, ), (‘Gfg’, )) Input : test_list = [[‘Gfg’, ‘is’, ‘Best’]]Output : ((‘Gfg’, ‘is’, ‘Best’), ) Method #1 : Using tuple() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the conversion using tuple() and list comprehension is used to extend logic to all the containers. # Python3 code to demonstrate working of # Convert List of Lists to Tuple of Tuples# Using tuple + list comprehension # initializing listtest_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']] # printing original listprint("The original list is : " + str(test_list)) # Convert List of Lists to Tuple of Tuples# Using tuple + list comprehensionres = tuple(tuple(sub) for sub in test_list) # printing result print("The converted data : " + str(res)) The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’)) Method #2 : Using map() + tuple()The combination of above functions can be used to solve this problem. In this, we perform the task performed using list comprehension using map(), to extend the conversion logic to each sublist. # Python3 code to demonstrate working of # Convert List of Lists to Tuple of Tuples# Using map() + tuple() # initializing listtest_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']] # printing original listprint("The original list is : " + str(test_list)) # Convert List of Lists to Tuple of Tuples# Using map() + tuple()res = tuple(map(tuple, test_list)) # printing result print("The converted data : " + str(res)) The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’)) Python list-programs Python tuple-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Python Dictionary Read a file line by line in Python Enumerate() in Python How to Install PIP on Windows ? Iterate over a list in Python Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python program to check whether a number is Prime or not How to print without newline in Python?
[ { "code": null, "e": 24544, "s": 24516, "text": "\n26 May, 2020" }, { "code": null, "e": 24851, "s": 24544, "text": "Sometimes, while working with Python data, we can have a problem in which we need to perform interconversion of data types. This kind of problem can occur in domains in which we need to get data in particular formats such as Machine Learning. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24943, "s": 24851, "text": "Input : test_list = [[‘Best’], [‘Gfg’], [‘Gfg’]]Output : ((‘Best’, ), (‘Gfg’, ), (‘Gfg’, ))" }, { "code": null, "e": 25021, "s": 24943, "text": "Input : test_list = [[‘Gfg’, ‘is’, ‘Best’]]Output : ((‘Gfg’, ‘is’, ‘Best’), )" }, { "code": null, "e": 25256, "s": 25021, "text": "Method #1 : Using tuple() + list comprehensionThe combination of above functions can be used to solve this problem. In this, we perform the conversion using tuple() and list comprehension is used to extend logic to all the containers." }, { "code": "# Python3 code to demonstrate working of # Convert List of Lists to Tuple of Tuples# Using tuple + list comprehension # initializing listtest_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert List of Lists to Tuple of Tuples# Using tuple + list comprehensionres = tuple(tuple(sub) for sub in test_list) # printing result print(\"The converted data : \" + str(res)) ", "e": 25770, "s": 25256, "text": null }, { "code": null, "e": 25969, "s": 25770, "text": "The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’))" }, { "code": null, "e": 26199, "s": 25971, "text": "Method #2 : Using map() + tuple()The combination of above functions can be used to solve this problem. In this, we perform the task performed using list comprehension using map(), to extend the conversion logic to each sublist." }, { "code": "# Python3 code to demonstrate working of # Convert List of Lists to Tuple of Tuples# Using map() + tuple() # initializing listtest_list = [['Gfg', 'is', 'Best'], ['Gfg', 'is', 'love'], ['Gfg', 'is', 'for', 'Geeks']] # printing original listprint(\"The original list is : \" + str(test_list)) # Convert List of Lists to Tuple of Tuples# Using map() + tuple()res = tuple(map(tuple, test_list)) # printing result print(\"The converted data : \" + str(res)) ", "e": 26682, "s": 26199, "text": null }, { "code": null, "e": 26881, "s": 26682, "text": "The original list is : [[‘Gfg’, ‘is’, ‘Best’], [‘Gfg’, ‘is’, ‘love’], [‘Gfg’, ‘is’, ‘for’, ‘Geeks’]]The converted data : ((‘Gfg’, ‘is’, ‘Best’), (‘Gfg’, ‘is’, ‘love’), (‘Gfg’, ‘is’, ‘for’, ‘Geeks’))" }, { "code": null, "e": 26902, "s": 26881, "text": "Python list-programs" }, { "code": null, "e": 26924, "s": 26902, "text": "Python tuple-programs" }, { "code": null, "e": 26931, "s": 26924, "text": "Python" }, { "code": null, "e": 26947, "s": 26931, "text": "Python Programs" }, { "code": null, "e": 27045, "s": 26947, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27054, "s": 27045, "text": "Comments" }, { "code": null, "e": 27067, "s": 27054, "text": "Old Comments" }, { "code": null, "e": 27085, "s": 27067, "text": "Python Dictionary" }, { "code": null, "e": 27120, "s": 27085, "text": "Read a file line by line in Python" }, { "code": null, "e": 27142, "s": 27120, "text": "Enumerate() in Python" }, { "code": null, "e": 27174, "s": 27142, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 27204, "s": 27174, "text": "Iterate over a list in Python" }, { "code": null, "e": 27226, "s": 27204, "text": "Defaultdict in Python" }, { "code": null, "e": 27265, "s": 27226, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 27303, "s": 27265, "text": "Python | Convert a list to dictionary" }, { "code": null, "e": 27360, "s": 27303, "text": "Python program to check whether a number is Prime or not" } ]