title
stringlengths 3
221
| text
stringlengths 17
477k
| parsed
listlengths 0
3.17k
|
---|---|---|
How to run SQL script in MySQL? | To run SQL script in MySQL, use the MySQL workbench. First, you need to open MySQL workbench.
The snapshot is as follows −
Now, File -> Open SQL Script to open the SQL script.
Alternatively, use the following shortcut key −
Ctrl+Shift+O
After that an option would be visible for you to choose your .sql file from the disk. In my system, the file is located on the Desktop. I will select the same “tblstudent” SQL file as shown in the following screenshot −
After browsing .sql files, you need to select the option “Reconnect to database” as shown in the following screenshot −
Now, it will ask for password to connect with MySQL. Add the password and click “OK” as in the following screenshot −
Note − Press OK button twice to connect with MySQL.
After completing the above process, the following screen will be visible with our SQL file “tblstudent”, which we uploaded before −
After that you need to execute the script. To execute the script, click the symbol marked in the following screenshot −
After that you will get the following output − | [
{
"code": null,
"e": 1156,
"s": 1062,
"text": "To run SQL script in MySQL, use the MySQL workbench. First, you need to open MySQL workbench."
},
{
"code": null,
"e": 1185,
"s": 1156,
"text": "The snapshot is as follows −"
},
{
"code": null,
"e": 1238,
"s": 1185,
"text": "Now, File -> Open SQL Script to open the SQL script."
},
{
"code": null,
"e": 1286,
"s": 1238,
"text": "Alternatively, use the following shortcut key −"
},
{
"code": null,
"e": 1299,
"s": 1286,
"text": "Ctrl+Shift+O"
},
{
"code": null,
"e": 1519,
"s": 1299,
"text": "After that an option would be visible for you to choose your .sql file from the disk. In my system, the file is located on the Desktop. I will select the same “tblstudent” SQL file as shown in the following screenshot −"
},
{
"code": null,
"e": 1639,
"s": 1519,
"text": "After browsing .sql files, you need to select the option “Reconnect to database” as shown in the following screenshot −"
},
{
"code": null,
"e": 1757,
"s": 1639,
"text": "Now, it will ask for password to connect with MySQL. Add the password and click “OK” as in the following screenshot −"
},
{
"code": null,
"e": 1809,
"s": 1757,
"text": "Note − Press OK button twice to connect with MySQL."
},
{
"code": null,
"e": 1941,
"s": 1809,
"text": "After completing the above process, the following screen will be visible with our SQL file “tblstudent”, which we uploaded before −"
},
{
"code": null,
"e": 2061,
"s": 1941,
"text": "After that you need to execute the script. To execute the script, click the symbol marked in the following screenshot −"
},
{
"code": null,
"e": 2108,
"s": 2061,
"text": "After that you will get the following output −"
}
] |
5 Best Python Project Ideas With Full Code Snippets And Useful Links! | by Bharath K | Towards Data Science | Python is an exceptional programming language for users ranging from beginners to advanced. It is emerging out as an extremely popular language, and also the most talked-about coding language today thanks to its flexibility.
The coding language python is not only easy to learn and implement but also provides a wide diversity while maintaining simplicity. Python being an overall easy language to get started with and implement top-notch projects provides room for us to execute a wide array of options.
Today, we will go over 5 project ideas that we will be implementing with the help of python. I have mentioned 2 basic level project ideas for beginners, another 2 intermediate level project ideas, and finally, 1 complex project idea for the last project.
I will be thoroughly discussing each project idea with necessary codes, examples, essential guides, and useful links to help you to start building the mentioned python projects.
With the brief introduction out of the way, let us dive into the interesting part of this article and discuss each of these projects in detail so you can start working on them right away!
This basic project to be implemented can be done in any way you choose. Let us analyze how the execution of this simple calculator project is done for each class of difficulty. I will begin with beginner’s implementation of simple calculators, but even if you have basic programming knowledge, stick on till the next part of this section as I have suggestions for taking this project to the next level as shown in the above image.
If you are a beginner and you are just getting started with python, then please refer to the starter code provided below, which is one of the best ways you can understand the use of functions in python.
With just a simple code as displayed above, you have successfully created four functions to compute the four basic operations of a calculator. To take the two inputs from the user for the calculation purpose, you can use the following code block assignment.
After executing the following code block, I will assign my two numbers like 5 and 2, for the interpretation of the calculations. You can feel free to declare any number you desire as per your requirement. The answers you should get for the following assignments should be as follows:
Enter the first number: 5Enter the second number: 2The Sum is: 7The Difference is: 3The product is: 10The answer is: 2.5
This part completes the simple calculator program. However, this is not even close to the end. There are a ton of improvements to be made with the use of various techniques. Let us discuss how we can accomplish this task. For the intermediate-level programmer, I would highly suggest that you go beyond the two input integers to a higher n-element approach by making use of the *args option available for functions. Then, try to use classes for understanding that concept more precisely and develop a more complicated calculator.
For more advanced or expert level construction of the same project, look into graphical user interface libraries like Tkinter. Using this module, users can develop an awesome GUI structure for your calculator. There are also other graphics modules you can use, but I would personally recommend Tkinter as a good starting point. Refer to the amazing code snippet provided by Programming Knowledge user in the GitHub link in the image above for a concise guide on the calculator development.
An important aspect of python and machine learning is understanding the math behind these concepts and knowing how some of the code in machine learning libraries. To have a better grasp of these concepts, it is essential to practice the ideas implemented in scientific modules like numpy and scikit-learn by ourselves. One such programming application is performing the matrix multiplication operation without using any ML libraries.
To perform this task, the main requirement is knowledge of how matrices works. The complete explanation and guide can be obtained from my article below. However, if you are just interested in the basic gist of this coding problem and want to try to solve this on your own, then use the next reference paragraphs to help you get started.
towardsdatascience.com
My approach to this problem is going to be to take all the inputs from the user. These are the number of rows and columns of both the first and second matrix. Also, based on the number of rows and columns of each matrix, we will respectively fill the alternative positions accordingly.
The first step, before doing any matrix multiplication is to check if this operation between the two matrices is actually possible. This can be done by checking if the columns of the first matrix matches the shape of the rows in the second matrix. This can be formulated as:
This should be a great starting point for you to get started.
The outdated GIF you guys can see above is one of my first projects I ever did with the help of pygame about three years ago. If you want a more concise guide on how you can build this from scratch with python then do let me know. But the main idea here is to build a game with python from scratch on your own. Start off with something simple like a snake game, or tic-tac-toe, and proceed towards a more advanced one like flappy birds with reinforcement learning.
The idea behind accomplishing this task is more of personal opinion and preference. I believe that one of the best ways to get a good hold of any programming language is to start with a project that is fun and enjoyable. I am also a bit of a gaming nerd. To get started with gaming projects related to python, I would highly recommend the use of the Pygame library module for the execution of such programs.
With the pygame module, you can build some simple, fun games with python. However, don’t expect anything too fancy as it has its limitations. Regardless, it is a fantastic way to get started, and below is the starter code to dive in. Just install pygame with a simple pip command and then use the following import pygame command. The following message will greet you upon the successful importing of the module.
pygame 1.9.6Hello from the pygame community. https://www.pygame.org/contribute.html
The versions might differ depending on the time on installation, so don’t worry too much. Just use the updated versions always in any scenario. I will go over some basic commands you should know and how they work. Below is the complete code block for all the important aspects you need to know to get started with pygame.
#imports the pygame library moduleimport pygame# initilize the pygame modulepygame.init()# Setting your screen size with a tuple of the screen width and screen heightdisplay_screen = pygame.display.set_mode((800,600)) # Setting a random caption title for your pygame graphical window.pygame.display.set_caption("pygame test")# Update your screen when requiredpygame.display.update()# quit the pygame initialization and modulepygame.quit()# End the programquit()
I would highly recommend you check out some YouTube videos for better understanding and learning to build some games. The documentation for the pygame module, albeit a little lengthy, is probably one the best resources to learn more about this module.
The next intermediate level we will be focusing on is one of the coolest aspects of having python programming knowledge. Complicated tasks such as text-to-speech conversion and optical character recognition of python can be completed just with the help of understanding the python library modules created for this purpose.
The text-to-speech (TTS) is the process of converting words into a vocal audio form. The program, tool, or software takes an input text from the user, and using methods of natural language processing, understands the linguistics of the language being used, and performs logical inference on the text. This processed text is passed into the next block, where digital signal processing is performed on the processed text. With the use of the many algorithms and transformations, this processed text is finally converted into a speech format. This entire process involves the synthesizing of speech.
Optical Character Recognition is the conversion of 2-Dimensional text data into a form of machine-encoded text by the use of an electronic or mechanical device. The 2-Dimensional text data can be obtained from various sources such as scanned documents like PDF files, images with text data in formats such as .png or .jpeg, signposts like traffic posts, or any other images with any form of textual data. There is a wide range of interesting applications for optical character recognition.
Below is the list of two articles that will be extremely useful to get you acquainted with the Google Text-To-Speech module for speech translation and the pytesseract module for optical character recognition. Refer to these below articles for a comprehensive guide for getting started with them and perform a project using them together.
towardsdatascience.com
towardsdatascience.com
You can make the best use of these modules for more advanced projects like using them with sequence to sequence with attention for the construction of deep learning models for machine translation and so much more. Have fun experimenting and exploring these libraries.
The virtual assistant project is one where your computer will listen to every single command of yours and perform all of your desired tasks. This project will be useful to control all your activities with a simple voice command.
You can carry out actions like the automation of emails after typing it out with just your voice, and the virtual assistant takes care of an autocorrect required. You can also command your virtual assistant for browsing the internet or for opening any websites or shopping or any other thing you desire. I will be going over one of my virtual assistant projects, but you can feel free to be innovative and try out any of your self-made ideas as well. All the reference links are also available in the respective parts of this section.
Firstly, I wanted my virtual assistant to grant access to only me or the selected members of my choice. I built a smart face lock system that would only permit me access. I constructed the face recognition model by using deep learning technologies and python. The entire concise feedback to this project is available from the following link below.
towardsdatascience.com
The next thing I wanted my virtual assistant to do was automatically predict the next words in my mind and perform the prediction task of the next words and complete my messages at a faster pace without needing much effort. The Next Word Prediction model with natural language processing and deep learning using python accomplished this exact task.
Below is the complete, concise guide for the implementation of the next word prediction model, which covers all these concepts in-depth.
towardsdatascience.com
The final part of my virtual assistant project was the implementation of the chatbot. I wanted a partner to talk to me and understand what I was saying and reply with appropriate responses. I designed my chatbot using a sarcastic dataset, and this made the chatbot to reply with funny messages filled with sarcasm. Below is the complete and concise guide for building your chatbot from scratch with Python and deep learning.
towardsdatascience.com
You can feel free to do the same thing as I have implemented with my above ideas or try something unique and innovative with your style guide of implementation of the virtual assistant project.
These five projects mentioned in this article will be useful for all levels of programmers, and it does not matter if your just getting started or have an intermediate to an advanced-level knowledge of Python. If you have any clarification regarding any of these five projects mentioned in this article, then feel free to hit me up.
Artificial Intelligence is on the rise, and we are close to conquering even the entire universe. With these python projects and understanding of concepts such as sparsity, we can all learn and develop into a more evolutionary modern era.
If you are interested in similar articles that cover amazing project ideas, then check out one of my previous articles related to 5 awesome computer vision projects that can be implemented with python, machine learning, and deep learning.
towardsdatascience.com
Check out my other concise guides to learn more about python and understand everything you need to know about python to get accustomed to programming with it for machine learning projects.
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
towardsdatascience.com
Thank you all for sticking on till the end. I hope you enjoyed reading the article. Wish you all a wonderful day. | [
{
"code": null,
"e": 397,
"s": 172,
"text": "Python is an exceptional programming language for users ranging from beginners to advanced. It is emerging out as an extremely popular language, and also the most talked-about coding language today thanks to its flexibility."
},
{
"code": null,
"e": 677,
"s": 397,
"text": "The coding language python is not only easy to learn and implement but also provides a wide diversity while maintaining simplicity. Python being an overall easy language to get started with and implement top-notch projects provides room for us to execute a wide array of options."
},
{
"code": null,
"e": 932,
"s": 677,
"text": "Today, we will go over 5 project ideas that we will be implementing with the help of python. I have mentioned 2 basic level project ideas for beginners, another 2 intermediate level project ideas, and finally, 1 complex project idea for the last project."
},
{
"code": null,
"e": 1110,
"s": 932,
"text": "I will be thoroughly discussing each project idea with necessary codes, examples, essential guides, and useful links to help you to start building the mentioned python projects."
},
{
"code": null,
"e": 1298,
"s": 1110,
"text": "With the brief introduction out of the way, let us dive into the interesting part of this article and discuss each of these projects in detail so you can start working on them right away!"
},
{
"code": null,
"e": 1729,
"s": 1298,
"text": "This basic project to be implemented can be done in any way you choose. Let us analyze how the execution of this simple calculator project is done for each class of difficulty. I will begin with beginner’s implementation of simple calculators, but even if you have basic programming knowledge, stick on till the next part of this section as I have suggestions for taking this project to the next level as shown in the above image."
},
{
"code": null,
"e": 1932,
"s": 1729,
"text": "If you are a beginner and you are just getting started with python, then please refer to the starter code provided below, which is one of the best ways you can understand the use of functions in python."
},
{
"code": null,
"e": 2190,
"s": 1932,
"text": "With just a simple code as displayed above, you have successfully created four functions to compute the four basic operations of a calculator. To take the two inputs from the user for the calculation purpose, you can use the following code block assignment."
},
{
"code": null,
"e": 2474,
"s": 2190,
"text": "After executing the following code block, I will assign my two numbers like 5 and 2, for the interpretation of the calculations. You can feel free to declare any number you desire as per your requirement. The answers you should get for the following assignments should be as follows:"
},
{
"code": null,
"e": 2599,
"s": 2474,
"text": "Enter the first number: 5Enter the second number: 2The Sum is: 7The Difference is: 3The product is: 10The answer is: 2.5"
},
{
"code": null,
"e": 3129,
"s": 2599,
"text": "This part completes the simple calculator program. However, this is not even close to the end. There are a ton of improvements to be made with the use of various techniques. Let us discuss how we can accomplish this task. For the intermediate-level programmer, I would highly suggest that you go beyond the two input integers to a higher n-element approach by making use of the *args option available for functions. Then, try to use classes for understanding that concept more precisely and develop a more complicated calculator."
},
{
"code": null,
"e": 3619,
"s": 3129,
"text": "For more advanced or expert level construction of the same project, look into graphical user interface libraries like Tkinter. Using this module, users can develop an awesome GUI structure for your calculator. There are also other graphics modules you can use, but I would personally recommend Tkinter as a good starting point. Refer to the amazing code snippet provided by Programming Knowledge user in the GitHub link in the image above for a concise guide on the calculator development."
},
{
"code": null,
"e": 4053,
"s": 3619,
"text": "An important aspect of python and machine learning is understanding the math behind these concepts and knowing how some of the code in machine learning libraries. To have a better grasp of these concepts, it is essential to practice the ideas implemented in scientific modules like numpy and scikit-learn by ourselves. One such programming application is performing the matrix multiplication operation without using any ML libraries."
},
{
"code": null,
"e": 4390,
"s": 4053,
"text": "To perform this task, the main requirement is knowledge of how matrices works. The complete explanation and guide can be obtained from my article below. However, if you are just interested in the basic gist of this coding problem and want to try to solve this on your own, then use the next reference paragraphs to help you get started."
},
{
"code": null,
"e": 4413,
"s": 4390,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 4699,
"s": 4413,
"text": "My approach to this problem is going to be to take all the inputs from the user. These are the number of rows and columns of both the first and second matrix. Also, based on the number of rows and columns of each matrix, we will respectively fill the alternative positions accordingly."
},
{
"code": null,
"e": 4974,
"s": 4699,
"text": "The first step, before doing any matrix multiplication is to check if this operation between the two matrices is actually possible. This can be done by checking if the columns of the first matrix matches the shape of the rows in the second matrix. This can be formulated as:"
},
{
"code": null,
"e": 5036,
"s": 4974,
"text": "This should be a great starting point for you to get started."
},
{
"code": null,
"e": 5501,
"s": 5036,
"text": "The outdated GIF you guys can see above is one of my first projects I ever did with the help of pygame about three years ago. If you want a more concise guide on how you can build this from scratch with python then do let me know. But the main idea here is to build a game with python from scratch on your own. Start off with something simple like a snake game, or tic-tac-toe, and proceed towards a more advanced one like flappy birds with reinforcement learning."
},
{
"code": null,
"e": 5909,
"s": 5501,
"text": "The idea behind accomplishing this task is more of personal opinion and preference. I believe that one of the best ways to get a good hold of any programming language is to start with a project that is fun and enjoyable. I am also a bit of a gaming nerd. To get started with gaming projects related to python, I would highly recommend the use of the Pygame library module for the execution of such programs."
},
{
"code": null,
"e": 6321,
"s": 5909,
"text": "With the pygame module, you can build some simple, fun games with python. However, don’t expect anything too fancy as it has its limitations. Regardless, it is a fantastic way to get started, and below is the starter code to dive in. Just install pygame with a simple pip command and then use the following import pygame command. The following message will greet you upon the successful importing of the module."
},
{
"code": null,
"e": 6405,
"s": 6321,
"text": "pygame 1.9.6Hello from the pygame community. https://www.pygame.org/contribute.html"
},
{
"code": null,
"e": 6727,
"s": 6405,
"text": "The versions might differ depending on the time on installation, so don’t worry too much. Just use the updated versions always in any scenario. I will go over some basic commands you should know and how they work. Below is the complete code block for all the important aspects you need to know to get started with pygame."
},
{
"code": null,
"e": 7190,
"s": 6727,
"text": "#imports the pygame library moduleimport pygame# initilize the pygame modulepygame.init()# Setting your screen size with a tuple of the screen width and screen heightdisplay_screen = pygame.display.set_mode((800,600)) # Setting a random caption title for your pygame graphical window.pygame.display.set_caption(\"pygame test\")# Update your screen when requiredpygame.display.update()# quit the pygame initialization and modulepygame.quit()# End the programquit()"
},
{
"code": null,
"e": 7442,
"s": 7190,
"text": "I would highly recommend you check out some YouTube videos for better understanding and learning to build some games. The documentation for the pygame module, albeit a little lengthy, is probably one the best resources to learn more about this module."
},
{
"code": null,
"e": 7765,
"s": 7442,
"text": "The next intermediate level we will be focusing on is one of the coolest aspects of having python programming knowledge. Complicated tasks such as text-to-speech conversion and optical character recognition of python can be completed just with the help of understanding the python library modules created for this purpose."
},
{
"code": null,
"e": 8362,
"s": 7765,
"text": "The text-to-speech (TTS) is the process of converting words into a vocal audio form. The program, tool, or software takes an input text from the user, and using methods of natural language processing, understands the linguistics of the language being used, and performs logical inference on the text. This processed text is passed into the next block, where digital signal processing is performed on the processed text. With the use of the many algorithms and transformations, this processed text is finally converted into a speech format. This entire process involves the synthesizing of speech."
},
{
"code": null,
"e": 8852,
"s": 8362,
"text": "Optical Character Recognition is the conversion of 2-Dimensional text data into a form of machine-encoded text by the use of an electronic or mechanical device. The 2-Dimensional text data can be obtained from various sources such as scanned documents like PDF files, images with text data in formats such as .png or .jpeg, signposts like traffic posts, or any other images with any form of textual data. There is a wide range of interesting applications for optical character recognition."
},
{
"code": null,
"e": 9190,
"s": 8852,
"text": "Below is the list of two articles that will be extremely useful to get you acquainted with the Google Text-To-Speech module for speech translation and the pytesseract module for optical character recognition. Refer to these below articles for a comprehensive guide for getting started with them and perform a project using them together."
},
{
"code": null,
"e": 9213,
"s": 9190,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9236,
"s": 9213,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 9504,
"s": 9236,
"text": "You can make the best use of these modules for more advanced projects like using them with sequence to sequence with attention for the construction of deep learning models for machine translation and so much more. Have fun experimenting and exploring these libraries."
},
{
"code": null,
"e": 9733,
"s": 9504,
"text": "The virtual assistant project is one where your computer will listen to every single command of yours and perform all of your desired tasks. This project will be useful to control all your activities with a simple voice command."
},
{
"code": null,
"e": 10268,
"s": 9733,
"text": "You can carry out actions like the automation of emails after typing it out with just your voice, and the virtual assistant takes care of an autocorrect required. You can also command your virtual assistant for browsing the internet or for opening any websites or shopping or any other thing you desire. I will be going over one of my virtual assistant projects, but you can feel free to be innovative and try out any of your self-made ideas as well. All the reference links are also available in the respective parts of this section."
},
{
"code": null,
"e": 10616,
"s": 10268,
"text": "Firstly, I wanted my virtual assistant to grant access to only me or the selected members of my choice. I built a smart face lock system that would only permit me access. I constructed the face recognition model by using deep learning technologies and python. The entire concise feedback to this project is available from the following link below."
},
{
"code": null,
"e": 10639,
"s": 10616,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 10988,
"s": 10639,
"text": "The next thing I wanted my virtual assistant to do was automatically predict the next words in my mind and perform the prediction task of the next words and complete my messages at a faster pace without needing much effort. The Next Word Prediction model with natural language processing and deep learning using python accomplished this exact task."
},
{
"code": null,
"e": 11125,
"s": 10988,
"text": "Below is the complete, concise guide for the implementation of the next word prediction model, which covers all these concepts in-depth."
},
{
"code": null,
"e": 11148,
"s": 11125,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11573,
"s": 11148,
"text": "The final part of my virtual assistant project was the implementation of the chatbot. I wanted a partner to talk to me and understand what I was saying and reply with appropriate responses. I designed my chatbot using a sarcastic dataset, and this made the chatbot to reply with funny messages filled with sarcasm. Below is the complete and concise guide for building your chatbot from scratch with Python and deep learning."
},
{
"code": null,
"e": 11596,
"s": 11573,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 11790,
"s": 11596,
"text": "You can feel free to do the same thing as I have implemented with my above ideas or try something unique and innovative with your style guide of implementation of the virtual assistant project."
},
{
"code": null,
"e": 12123,
"s": 11790,
"text": "These five projects mentioned in this article will be useful for all levels of programmers, and it does not matter if your just getting started or have an intermediate to an advanced-level knowledge of Python. If you have any clarification regarding any of these five projects mentioned in this article, then feel free to hit me up."
},
{
"code": null,
"e": 12361,
"s": 12123,
"text": "Artificial Intelligence is on the rise, and we are close to conquering even the entire universe. With these python projects and understanding of concepts such as sparsity, we can all learn and develop into a more evolutionary modern era."
},
{
"code": null,
"e": 12600,
"s": 12361,
"text": "If you are interested in similar articles that cover amazing project ideas, then check out one of my previous articles related to 5 awesome computer vision projects that can be implemented with python, machine learning, and deep learning."
},
{
"code": null,
"e": 12623,
"s": 12600,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12812,
"s": 12623,
"text": "Check out my other concise guides to learn more about python and understand everything you need to know about python to get accustomed to programming with it for machine learning projects."
},
{
"code": null,
"e": 12835,
"s": 12812,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12858,
"s": 12835,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12881,
"s": 12858,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 12904,
"s": 12881,
"text": "towardsdatascience.com"
}
] |
How to return a value from a JavaScript function? | To return a value from a JavaScript function, use the return statement in JavaScript. You need to run the following code to learn how to return a value −
<html>
<head>
<script>
function concatenate(name, age) {
var val;
val = name + age;
return val;
}
function DisplayFunction() {
var result;
result = concatenate('John ', 20) ;
document.write (result );
}
</script>
</head>
<body>
<p>Click the following button to call the function</p>
<form>
<input type = "button" onclick = "DisplayFunction()" value = "Result">
</form>
</body>
</html> | [
{
"code": null,
"e": 1216,
"s": 1062,
"text": "To return a value from a JavaScript function, use the return statement in JavaScript. You need to run the following code to learn how to return a value −"
},
{
"code": null,
"e": 1761,
"s": 1216,
"text": "<html>\n <head>\n <script>\n function concatenate(name, age) {\n var val;\n val = name + age;\n return val;\n }\n function DisplayFunction() {\n var result;\n result = concatenate('John ', 20) ;\n document.write (result );\n }\n </script>\n </head>\n <body>\n <p>Click the following button to call the function</p>\n\n <form>\n <input type = \"button\" onclick = \"DisplayFunction()\" value = \"Result\">\n </form>\n </body>\n</html>"
}
] |
DAX Filter - ALLEXCEPT function | Removes all context filters in the table except filters that have been applied to the specified columns.
ALLEXCEPT (<table>, <column>, [<column>] ...)
table
The table over which all context filters are removed, except filters on those columns that are specified in subsequent arguments.
column
One or more columns that are specified for which context filters must be preserved.
For the ALLEXCEPT function, the first argument must be a reference to a base table. All the subsequent arguments must be references to base columns in that table.
You cannot use table expressions or column expressions with the ALLEXCEPT function.
A table with all filters removed except for the filters on the specified columns.
ALLEXCEPT function is not used by itself, but serves as an intermediate function that can be used to change the set of results over which some other calculation is performed.
You can use ALLEXCEPT function if you want to remove the filters on many, but not all, columns in a table.
= CALCULATE (COUNTA (Results[Medal]), ALLEXCEPT (Hosts, Hosts[City]))
The values in Medal column in the Results table are counted with all the filters removed, except for the filters on the Column City in the Hosts table.
53 Lectures
5.5 hours
Abhay Gadiya
24 Lectures
2 hours
Randy Minder
26 Lectures
4.5 hours
Randy Minder
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2106,
"s": 2001,
"text": "Removes all context filters in the table except filters that have been applied to the specified columns."
},
{
"code": null,
"e": 2154,
"s": 2106,
"text": "ALLEXCEPT (<table>, <column>, [<column>] ...) \n"
},
{
"code": null,
"e": 2160,
"s": 2154,
"text": "table"
},
{
"code": null,
"e": 2290,
"s": 2160,
"text": "The table over which all context filters are removed, except filters on those columns that are specified in subsequent arguments."
},
{
"code": null,
"e": 2297,
"s": 2290,
"text": "column"
},
{
"code": null,
"e": 2381,
"s": 2297,
"text": "One or more columns that are specified for which context filters must be preserved."
},
{
"code": null,
"e": 2544,
"s": 2381,
"text": "For the ALLEXCEPT function, the first argument must be a reference to a base table. All the subsequent arguments must be references to base columns in that table."
},
{
"code": null,
"e": 2628,
"s": 2544,
"text": "You cannot use table expressions or column expressions with the ALLEXCEPT function."
},
{
"code": null,
"e": 2710,
"s": 2628,
"text": "A table with all filters removed except for the filters on the specified columns."
},
{
"code": null,
"e": 2885,
"s": 2710,
"text": "ALLEXCEPT function is not used by itself, but serves as an intermediate function that can be used to change the set of results over which some other calculation is performed."
},
{
"code": null,
"e": 2992,
"s": 2885,
"text": "You can use ALLEXCEPT function if you want to remove the filters on many, but not all, columns in a table."
},
{
"code": null,
"e": 3063,
"s": 2992,
"text": "= CALCULATE (COUNTA (Results[Medal]), ALLEXCEPT (Hosts, Hosts[City])) "
},
{
"code": null,
"e": 3215,
"s": 3063,
"text": "The values in Medal column in the Results table are counted with all the filters removed, except for the filters on the Column City in the Hosts table."
},
{
"code": null,
"e": 3250,
"s": 3215,
"text": "\n 53 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 3264,
"s": 3250,
"text": " Abhay Gadiya"
},
{
"code": null,
"e": 3297,
"s": 3264,
"text": "\n 24 Lectures \n 2 hours \n"
},
{
"code": null,
"e": 3311,
"s": 3297,
"text": " Randy Minder"
},
{
"code": null,
"e": 3346,
"s": 3311,
"text": "\n 26 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3360,
"s": 3346,
"text": " Randy Minder"
},
{
"code": null,
"e": 3367,
"s": 3360,
"text": " Print"
},
{
"code": null,
"e": 3378,
"s": 3367,
"text": " Add Notes"
}
] |
Why and how are Python functions hashable? | 31 Aug, 2020
So start with the question i.e. Why and how are Python functions hashable? First, one should know what actually hashable means in Python. So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set.
An object is hashable if it has a hash value that does not change during its entire lifetime. Python has a built-in hash method ( __hash__() ) that can be compared to other objects. For comparing it needs __eq__() or __cmp__() method and if the hashable objects are equal then they have the same hash value. All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable.
Objects which are instances of the user-defined class are hashable by default, they all compare unequal, and their hash value is their id().
Example: Consider two tuples t1, t2 with the same values, and see the differences:
Python3
t1 = (1, 5, 6) t2 = (1, 5, 6) # show the id of objectprint(id(t1)) print(id(t2))
Output:
140040984150664
140040984150880
In the above example, two objects are different as for immutable types the hash value depends on the data stored not on their id.
Example: Let’s see lambda functions are hashable or not.
Python3
# create a one-line functionl = lambda x : 1 # show the hash valueprint(hash(l)) # show the id valueprint(id(l)) # show the hash valueprint (l.__hash__())
Output:
-9223363246992694337
140637793303544
-9223363246992694337
Hence, lambda functions are hashable.
Example: Let’s see user defined def based function are hashable or not.
Python3
# create an empty functiondef fun(): pass # print types of functionprint(type(fun)) # print hash valueprint(fun.__hash__()) # print hash valueprint(hash(fun))
Output:
<class 'function'>
-9223363242199589441
-9223363242199589441
Therefore, any user defined function is hashable as its hash value remains same during its lifetime.
urvashisaxena1997
Python-Functions
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n31 Aug, 2020"
},
{
"code": null,
"e": 388,
"s": 52,
"text": "So start with the question i.e. Why and how are Python functions hashable? First, one should know what actually hashable means in Python. So, hashable is a feature of Python objects that tells if the object has a hash value or not. If the object has a hash value then it can be used as a key for a dictionary or as an element in a set."
},
{
"code": null,
"e": 838,
"s": 388,
"text": "An object is hashable if it has a hash value that does not change during its entire lifetime. Python has a built-in hash method ( __hash__() ) that can be compared to other objects. For comparing it needs __eq__() or __cmp__() method and if the hashable objects are equal then they have the same hash value. All immutable built-in objects in Python are hashable like tuples while the mutable containers like lists and dictionaries are not hashable. "
},
{
"code": null,
"e": 979,
"s": 838,
"text": "Objects which are instances of the user-defined class are hashable by default, they all compare unequal, and their hash value is their id()."
},
{
"code": null,
"e": 1062,
"s": 979,
"text": "Example: Consider two tuples t1, t2 with the same values, and see the differences:"
},
{
"code": null,
"e": 1070,
"s": 1062,
"text": "Python3"
},
{
"code": "t1 = (1, 5, 6) t2 = (1, 5, 6) # show the id of objectprint(id(t1)) print(id(t2))",
"e": 1151,
"s": 1070,
"text": null
},
{
"code": null,
"e": 1162,
"s": 1154,
"text": "Output:"
},
{
"code": null,
"e": 1198,
"s": 1164,
"text": "140040984150664\n140040984150880\n\n"
},
{
"code": null,
"e": 1330,
"s": 1200,
"text": "In the above example, two objects are different as for immutable types the hash value depends on the data stored not on their id."
},
{
"code": null,
"e": 1389,
"s": 1332,
"text": "Example: Let’s see lambda functions are hashable or not."
},
{
"code": null,
"e": 1399,
"s": 1391,
"text": "Python3"
},
{
"code": "# create a one-line functionl = lambda x : 1 # show the hash valueprint(hash(l)) # show the id valueprint(id(l)) # show the hash valueprint (l.__hash__())",
"e": 1554,
"s": 1399,
"text": null
},
{
"code": null,
"e": 1565,
"s": 1557,
"text": "Output:"
},
{
"code": null,
"e": 1627,
"s": 1567,
"text": "-9223363246992694337\n140637793303544\n-9223363246992694337\n\n"
},
{
"code": null,
"e": 1667,
"s": 1629,
"text": "Hence, lambda functions are hashable."
},
{
"code": null,
"e": 1741,
"s": 1669,
"text": "Example: Let’s see user defined def based function are hashable or not."
},
{
"code": null,
"e": 1751,
"s": 1743,
"text": "Python3"
},
{
"code": "# create an empty functiondef fun(): pass # print types of functionprint(type(fun)) # print hash valueprint(fun.__hash__()) # print hash valueprint(hash(fun))",
"e": 1911,
"s": 1751,
"text": null
},
{
"code": null,
"e": 1922,
"s": 1914,
"text": "Output:"
},
{
"code": null,
"e": 1988,
"s": 1924,
"text": "<class 'function'>\n-9223363242199589441\n-9223363242199589441 \n\n"
},
{
"code": null,
"e": 2091,
"s": 1990,
"text": "Therefore, any user defined function is hashable as its hash value remains same during its lifetime."
},
{
"code": null,
"e": 2111,
"s": 2093,
"text": "urvashisaxena1997"
},
{
"code": null,
"e": 2128,
"s": 2111,
"text": "Python-Functions"
},
{
"code": null,
"e": 2135,
"s": 2128,
"text": "Python"
}
] |
Sorting Big Integers | 21 Apr, 2022
Given a array of n positive integers where each integer can have digits upto 106, print the array elements in ascending order.
Input: arr[] = {54, 724523015759812365462, 870112101220845, 8723}
Output: 54 8723 870112101220845 724523015759812365462
Explanation:
All elements of array are sorted in non-descending(i.e., ascending)
order of their integer value
Input: arr[] = {3643641264874311, 451234654453211101231,
4510122010112121012121}
Output: 3641264874311 451234654453211101231 4510122010112121012121
A naive approach is to use arbitrary precision data type such as int in python or Biginteger class in Java. But that approach will not be fruitful because internal conversion of string to int and then perform sorting will leads to slow down the calculations of addition and multiplications in binary number system.Efficient Solution : As size of integer is very large even it can’t be fit in long long data type of C/C++, so we just need to input all numbers as strings and sort them using a comparison function. Following are the key points compare function:-
If lengths of two strings are different, then we need to compare lengths to decide sorting order.If Lengths are same then we just need to compare both the strings in lexicographically order.
If lengths of two strings are different, then we need to compare lengths to decide sorting order.
If Lengths are same then we just need to compare both the strings in lexicographically order.
Assumption : There are no leading zeros.
C++
Python
Javascript
// Below is C++ code to sort the Big integers in// ascending order#include<bits/stdc++.h>using namespace std; // comp function to perform sortingbool comp(const string &left, const string &right){ // if length of both string are equals then sort // them in lexicographically order if (left.size() == right.size()) return left < right; // Otherwise sort them according to the length // of string in ascending order else return left.size() < right.size();} // Function to sort arr[] elements according// to integer valuevoid SortingBigIntegers(string arr[], int n){ // Copy the arr[] elements to sortArr[] vector<string> sortArr(arr, arr + n); // Inbuilt sort function using function as comp sort(sortArr.begin(), sortArr.end(), comp); // Print the final sorted array for (auto &ele : sortArr) cout << ele << " ";} // Driver code of above implementationint main(){ string arr[] = {"54", "724523015759812365462", "870112101220845", "8723"}; int n = sizeof(arr) / sizeof(arr[0]); SortingBigIntegers(arr, n); return 0;}
# Below is Python code to sort the Big integers# in ascending orderdef SortingBigIntegers(arr, n): # Direct sorting using lambda operator # and length comparison arr.sort(key = lambda x: (len(x), x)) # Driver code of above implementationarr = ["54", "724523015759812365462", "870112101220845", "8723"]n = len(arr) SortingBigIntegers(arr, n) # Print the final sorted list using# join methodprint " ".join(arr)
<script>// Below is Javascript code to sort the Big integers in// ascending order // comp function to perform sortingfunction comp(left, right){ // if length of both string are equals then sort // them in lexicographically order if (left.length == right.length) return left < right; // Otherwise sort them according to the length // of string in ascending order else return left.length - right.length;} // Function to sort arr[] elements according// to integer valuefunction SortingBigIntegers(arr, n){ // Copy the arr[] elements to sortArr[] let sortArr = [...arr] // Inbuilt sort function using function as comp sortArr.sort(comp); // Print the final sorted array for (ele of sortArr) document.write(ele + " ");} // Driver code of above implementationlet arr = ["54", "724523015759812365462", "870112101220845", "8723"]let n = arr.length SortingBigIntegers(arr, n); // This code is contributed by gfgking.</script>
Output: 54 8723 870112101220845 724523015759812365462
Time complexity: O(sum * log(n)) where sum is the total sum of all string length and n is size of array Auxiliary space: O(n)Similar Post : Sort an array of large numbersThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gfgking
surinderdawra388
large-numbers
Sorting
Sorting
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Count Inversions in an array | Set 1 (Using Merge Sort)
Merge two sorted arrays
Chocolate Distribution Problem
Sort an array of 0s, 1s and 2s | Dutch National Flag problem
Longest Consecutive Subsequence
k largest(or smallest) elements in an array
Find a triplet that sum to a given value
sort() in Python
Merge Sort for Linked Lists
Sort string of characters | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n21 Apr, 2022"
},
{
"code": null,
"e": 183,
"s": 54,
"text": "Given a array of n positive integers where each integer can have digits upto 106, print the array elements in ascending order. "
},
{
"code": null,
"e": 579,
"s": 183,
"text": "Input: arr[] = {54, 724523015759812365462, 870112101220845, 8723} \nOutput: 54 8723 870112101220845 724523015759812365462\nExplanation:\nAll elements of array are sorted in non-descending(i.e., ascending)\norder of their integer value\n\nInput: arr[] = {3643641264874311, 451234654453211101231,\n 4510122010112121012121}\nOutput: 3641264874311 451234654453211101231 4510122010112121012121"
},
{
"code": null,
"e": 1144,
"s": 581,
"text": "A naive approach is to use arbitrary precision data type such as int in python or Biginteger class in Java. But that approach will not be fruitful because internal conversion of string to int and then perform sorting will leads to slow down the calculations of addition and multiplications in binary number system.Efficient Solution : As size of integer is very large even it can’t be fit in long long data type of C/C++, so we just need to input all numbers as strings and sort them using a comparison function. Following are the key points compare function:- "
},
{
"code": null,
"e": 1335,
"s": 1144,
"text": "If lengths of two strings are different, then we need to compare lengths to decide sorting order.If Lengths are same then we just need to compare both the strings in lexicographically order."
},
{
"code": null,
"e": 1433,
"s": 1335,
"text": "If lengths of two strings are different, then we need to compare lengths to decide sorting order."
},
{
"code": null,
"e": 1527,
"s": 1433,
"text": "If Lengths are same then we just need to compare both the strings in lexicographically order."
},
{
"code": null,
"e": 1569,
"s": 1527,
"text": "Assumption : There are no leading zeros. "
},
{
"code": null,
"e": 1573,
"s": 1569,
"text": "C++"
},
{
"code": null,
"e": 1580,
"s": 1573,
"text": "Python"
},
{
"code": null,
"e": 1591,
"s": 1580,
"text": "Javascript"
},
{
"code": "// Below is C++ code to sort the Big integers in// ascending order#include<bits/stdc++.h>using namespace std; // comp function to perform sortingbool comp(const string &left, const string &right){ // if length of both string are equals then sort // them in lexicographically order if (left.size() == right.size()) return left < right; // Otherwise sort them according to the length // of string in ascending order else return left.size() < right.size();} // Function to sort arr[] elements according// to integer valuevoid SortingBigIntegers(string arr[], int n){ // Copy the arr[] elements to sortArr[] vector<string> sortArr(arr, arr + n); // Inbuilt sort function using function as comp sort(sortArr.begin(), sortArr.end(), comp); // Print the final sorted array for (auto &ele : sortArr) cout << ele << \" \";} // Driver code of above implementationint main(){ string arr[] = {\"54\", \"724523015759812365462\", \"870112101220845\", \"8723\"}; int n = sizeof(arr) / sizeof(arr[0]); SortingBigIntegers(arr, n); return 0;}",
"e": 2699,
"s": 1591,
"text": null
},
{
"code": "# Below is Python code to sort the Big integers# in ascending orderdef SortingBigIntegers(arr, n): # Direct sorting using lambda operator # and length comparison arr.sort(key = lambda x: (len(x), x)) # Driver code of above implementationarr = [\"54\", \"724523015759812365462\", \"870112101220845\", \"8723\"]n = len(arr) SortingBigIntegers(arr, n) # Print the final sorted list using# join methodprint \" \".join(arr)",
"e": 3121,
"s": 2699,
"text": null
},
{
"code": "<script>// Below is Javascript code to sort the Big integers in// ascending order // comp function to perform sortingfunction comp(left, right){ // if length of both string are equals then sort // them in lexicographically order if (left.length == right.length) return left < right; // Otherwise sort them according to the length // of string in ascending order else return left.length - right.length;} // Function to sort arr[] elements according// to integer valuefunction SortingBigIntegers(arr, n){ // Copy the arr[] elements to sortArr[] let sortArr = [...arr] // Inbuilt sort function using function as comp sortArr.sort(comp); // Print the final sorted array for (ele of sortArr) document.write(ele + \" \");} // Driver code of above implementationlet arr = [\"54\", \"724523015759812365462\", \"870112101220845\", \"8723\"]let n = arr.length SortingBigIntegers(arr, n); // This code is contributed by gfgking.</script>",
"e": 4104,
"s": 3121,
"text": null
},
{
"code": null,
"e": 4158,
"s": 4104,
"text": "Output: 54 8723 870112101220845 724523015759812365462"
},
{
"code": null,
"e": 4751,
"s": 4158,
"text": "Time complexity: O(sum * log(n)) where sum is the total sum of all string length and n is size of array Auxiliary space: O(n)Similar Post : Sort an array of large numbersThis article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 4759,
"s": 4751,
"text": "gfgking"
},
{
"code": null,
"e": 4776,
"s": 4759,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4790,
"s": 4776,
"text": "large-numbers"
},
{
"code": null,
"e": 4798,
"s": 4790,
"text": "Sorting"
},
{
"code": null,
"e": 4806,
"s": 4798,
"text": "Sorting"
},
{
"code": null,
"e": 4904,
"s": 4806,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4960,
"s": 4904,
"text": "Count Inversions in an array | Set 1 (Using Merge Sort)"
},
{
"code": null,
"e": 4984,
"s": 4960,
"text": "Merge two sorted arrays"
},
{
"code": null,
"e": 5015,
"s": 4984,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 5076,
"s": 5015,
"text": "Sort an array of 0s, 1s and 2s | Dutch National Flag problem"
},
{
"code": null,
"e": 5108,
"s": 5076,
"text": "Longest Consecutive Subsequence"
},
{
"code": null,
"e": 5152,
"s": 5108,
"text": "k largest(or smallest) elements in an array"
},
{
"code": null,
"e": 5193,
"s": 5152,
"text": "Find a triplet that sum to a given value"
},
{
"code": null,
"e": 5210,
"s": 5193,
"text": "sort() in Python"
},
{
"code": null,
"e": 5238,
"s": 5210,
"text": "Merge Sort for Linked Lists"
}
] |
R – Data Types | 23 Feb, 2022
Each variable in R has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. R Programming language has the following basic data types and the following table shows the data type and the values that each data type can take.
Decimal values are called numerics in R. It is the default data type for numbers in R. If you assign a decimal value to a variable x as follows, x will be of numeric type.
R
# A simple R program# to illustrate Numeric data type # Assign a decimal value to xx = 5.6 # print the class name of variableprint(class(x)) # print the type of variableprint(typeof(x))
Output:
[1] "numeric"
[1] "double"
Even if an integer is assigned to a variable y, it is still being saved as a numeric value.
R
# A simple R program# to illustrate Numeric data type # Assign an integer value to yy = 5 # print the class name of variableprint(class(y)) # print the type of variableprint(typeof(y))
Output:
[1] "numeric"
[1] "double"
When R stores a number in a variable, it converts the number into a “double” value or a decimal type with at least two decimal places. This means that a value such as “5” here, is stored as 5.00 with a type of double and a class of numeric. And also y is not an integer here can be confirmed with the is.integer() function.
R
# A simple R program# to illustrate Numeric data type # Assign a integer value to yy = 5 # is y an integer?print(is.integer(y))
Output:
[1] FALSE
R supports integer data types which are the set of all integers. You can create as well as convert a value into an integer type using the as.integer() function. You can also use the capital ‘L’ notation as a suffix to denote that a particular value is of the integer data type.
R
# A simple R program# to illustrate integer data type # Create an integer valuex = as.integer(5) # print the class name of xprint(class(x)) # print the type of xprint(typeof(x)) # Declare an integer by appending an L suffix.y = 5L # print the class name of yprint(class(y)) # print the type of yprint(typeof(y))
Output:
[1] "integer"
[1] "integer"
[1] "integer"
[1] "integer"
R has logical data types that take either a value of true or false. A logical value is often created via a comparison between variables.
R
# A simple R program# to illustrate logical data type # Sample valuesx = 4y = 3 # Comparing two valuesz = x > y # print the logical valueprint(z) # print the class name of zprint(class(z)) # print the type of zprint(typeof())
Output:
[1] TRUE
[1] "logical"
[1] "logical"
R supports complex data types that are set of all the complex numbers. The complex data type is to store numbers with an imaginary component.
R
# A simple R program# to illustrate complex data type # Assign a complex value to xx = 4 + 3i # print the class name of xprint(class(x)) # print the type of xprint(typeof(x))
Output:
[1] "complex"
[1] "complex"
R supports character data types where you have all the alphabets and special characters. It stores character values or strings. Strings in R can contain alphabets, numbers, and symbols. The easiest way to denote that a value is of character type in R is to wrap the value inside single or double inverted commas.
R
# A simple R program# to illustrate character data type # Assign a character value to charchar = "Geeksforgeeks" # print the class name of charprint(class(char)) # print the type of charprint(typeof(char))
Output:
[1] "character"
[1] "character"
There are several tasks that can be done using data types. Let’s understand each task with its action and the syntax for doing the task along with an R code to illustrate the task.
To find the data type of an object you have to use class() function. The syntax for doing that is you need to pass the object as an argument to the function class() to find the data type of an object.
Syntax:
class(object)
Example:
R
# A simple R program# to find data type of an object # Logicalprint(class(TRUE)) # Integerprint(class(3L)) # Numericprint(class(10.5)) # Complexprint(class(1+2i)) # Characterprint(class("12-04-2020"))
Output:
[1] "logical"
[1] "integer"
[1] "numeric"
[1] "complex"
[1] "character"
To do that, you need to use the prefix “is.” before the data type as a command. The syntax for that is, is.data_type() of the object you have to verify.
Syntax:
is.data_type(object)
Example:
R
# A simple R program# Verify if an object is of a certain datatype # Logicalprint(is.logical(TRUE)) # Integerprint(is.integer(3L)) # Numericprint(is.numeric(10.5)) # Complexprint(is.complex(1+2i)) # Characterprint(is.character("12-04-2020")) print(is.integer("a")) print(is.numeric(2+3i))
Output:
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] TRUE
[1] FALSE
[1] FALSE
This task is interesting where you can change or convert the data type of one object to another. To perform this action you have to use the prefix “as.” before the data type as the command. The syntax for doing that is as.data_type() of the object which you want to coerce.
Syntax:
as.data_type(object)
Note: All the coercions are not possible and if attempted will be returning an “NA” value.
Example:
R
# A simple R program# convert data type of an object to another # Logicalprint(as.numeric(TRUE)) # Integerprint(as.complex(3L)) # Numericprint(as.logical(10.5)) # Complexprint(as.character(1+2i)) # Can't possibleprint(as.numeric("12-04-2020"))
Output:
[1] 1
[1] 3+0i
[1] TRUE
[1] "1+2i"
[1] NA
Warning message:
In print(as.numeric("12-04-2020")) : NAs introduced by coercion
kumar_satyam
ishmartishtiaq709
Picked
R Data-types
Programming Language
R Language
Write From Home
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n23 Feb, 2022"
},
{
"code": null,
"e": 340,
"s": 28,
"text": "Each variable in R has an associated data type. Each data type requires different amounts of memory and has some specific operations which can be performed over it. R Programming language has the following basic data types and the following table shows the data type and the values that each data type can take."
},
{
"code": null,
"e": 512,
"s": 340,
"text": "Decimal values are called numerics in R. It is the default data type for numbers in R. If you assign a decimal value to a variable x as follows, x will be of numeric type."
},
{
"code": null,
"e": 514,
"s": 512,
"text": "R"
},
{
"code": "# A simple R program# to illustrate Numeric data type # Assign a decimal value to xx = 5.6 # print the class name of variableprint(class(x)) # print the type of variableprint(typeof(x))",
"e": 700,
"s": 514,
"text": null
},
{
"code": null,
"e": 709,
"s": 700,
"text": "Output: "
},
{
"code": null,
"e": 736,
"s": 709,
"text": "[1] \"numeric\"\n[1] \"double\""
},
{
"code": null,
"e": 828,
"s": 736,
"text": "Even if an integer is assigned to a variable y, it is still being saved as a numeric value."
},
{
"code": null,
"e": 830,
"s": 828,
"text": "R"
},
{
"code": "# A simple R program# to illustrate Numeric data type # Assign an integer value to yy = 5 # print the class name of variableprint(class(y)) # print the type of variableprint(typeof(y))",
"e": 1015,
"s": 830,
"text": null
},
{
"code": null,
"e": 1024,
"s": 1015,
"text": "Output: "
},
{
"code": null,
"e": 1051,
"s": 1024,
"text": "[1] \"numeric\"\n[1] \"double\""
},
{
"code": null,
"e": 1376,
"s": 1051,
"text": "When R stores a number in a variable, it converts the number into a “double” value or a decimal type with at least two decimal places. This means that a value such as “5” here, is stored as 5.00 with a type of double and a class of numeric. And also y is not an integer here can be confirmed with the is.integer() function. "
},
{
"code": null,
"e": 1378,
"s": 1376,
"text": "R"
},
{
"code": "# A simple R program# to illustrate Numeric data type # Assign a integer value to yy = 5 # is y an integer?print(is.integer(y))",
"e": 1506,
"s": 1378,
"text": null
},
{
"code": null,
"e": 1515,
"s": 1506,
"text": "Output: "
},
{
"code": null,
"e": 1525,
"s": 1515,
"text": "[1] FALSE"
},
{
"code": null,
"e": 1803,
"s": 1525,
"text": "R supports integer data types which are the set of all integers. You can create as well as convert a value into an integer type using the as.integer() function. You can also use the capital ‘L’ notation as a suffix to denote that a particular value is of the integer data type."
},
{
"code": null,
"e": 1805,
"s": 1803,
"text": "R"
},
{
"code": "# A simple R program# to illustrate integer data type # Create an integer valuex = as.integer(5) # print the class name of xprint(class(x)) # print the type of xprint(typeof(x)) # Declare an integer by appending an L suffix.y = 5L # print the class name of yprint(class(y)) # print the type of yprint(typeof(y))",
"e": 2117,
"s": 1805,
"text": null
},
{
"code": null,
"e": 2126,
"s": 2117,
"text": "Output: "
},
{
"code": null,
"e": 2182,
"s": 2126,
"text": "[1] \"integer\"\n[1] \"integer\"\n[1] \"integer\"\n[1] \"integer\""
},
{
"code": null,
"e": 2320,
"s": 2182,
"text": "R has logical data types that take either a value of true or false. A logical value is often created via a comparison between variables. "
},
{
"code": null,
"e": 2322,
"s": 2320,
"text": "R"
},
{
"code": "# A simple R program# to illustrate logical data type # Sample valuesx = 4y = 3 # Comparing two valuesz = x > y # print the logical valueprint(z) # print the class name of zprint(class(z)) # print the type of zprint(typeof())",
"e": 2548,
"s": 2322,
"text": null
},
{
"code": null,
"e": 2557,
"s": 2548,
"text": "Output: "
},
{
"code": null,
"e": 2594,
"s": 2557,
"text": "[1] TRUE\n[1] \"logical\"\n[1] \"logical\""
},
{
"code": null,
"e": 2737,
"s": 2594,
"text": "R supports complex data types that are set of all the complex numbers. The complex data type is to store numbers with an imaginary component. "
},
{
"code": null,
"e": 2739,
"s": 2737,
"text": "R"
},
{
"code": "# A simple R program# to illustrate complex data type # Assign a complex value to xx = 4 + 3i # print the class name of xprint(class(x)) # print the type of xprint(typeof(x))",
"e": 2914,
"s": 2739,
"text": null
},
{
"code": null,
"e": 2923,
"s": 2914,
"text": "Output: "
},
{
"code": null,
"e": 2951,
"s": 2923,
"text": "[1] \"complex\"\n[1] \"complex\""
},
{
"code": null,
"e": 3265,
"s": 2951,
"text": "R supports character data types where you have all the alphabets and special characters. It stores character values or strings. Strings in R can contain alphabets, numbers, and symbols. The easiest way to denote that a value is of character type in R is to wrap the value inside single or double inverted commas. "
},
{
"code": null,
"e": 3267,
"s": 3265,
"text": "R"
},
{
"code": "# A simple R program# to illustrate character data type # Assign a character value to charchar = \"Geeksforgeeks\" # print the class name of charprint(class(char)) # print the type of charprint(typeof(char))",
"e": 3473,
"s": 3267,
"text": null
},
{
"code": null,
"e": 3482,
"s": 3473,
"text": "Output: "
},
{
"code": null,
"e": 3514,
"s": 3482,
"text": "[1] \"character\"\n[1] \"character\""
},
{
"code": null,
"e": 3697,
"s": 3514,
"text": "There are several tasks that can be done using data types. Let’s understand each task with its action and the syntax for doing the task along with an R code to illustrate the task. "
},
{
"code": null,
"e": 3898,
"s": 3697,
"text": "To find the data type of an object you have to use class() function. The syntax for doing that is you need to pass the object as an argument to the function class() to find the data type of an object."
},
{
"code": null,
"e": 3908,
"s": 3898,
"text": "Syntax: "
},
{
"code": null,
"e": 3922,
"s": 3908,
"text": "class(object)"
},
{
"code": null,
"e": 3932,
"s": 3922,
"text": "Example: "
},
{
"code": null,
"e": 3934,
"s": 3932,
"text": "R"
},
{
"code": "# A simple R program# to find data type of an object # Logicalprint(class(TRUE)) # Integerprint(class(3L)) # Numericprint(class(10.5)) # Complexprint(class(1+2i)) # Characterprint(class(\"12-04-2020\"))",
"e": 4135,
"s": 3934,
"text": null
},
{
"code": null,
"e": 4144,
"s": 4135,
"text": "Output: "
},
{
"code": null,
"e": 4216,
"s": 4144,
"text": "[1] \"logical\"\n[1] \"integer\"\n[1] \"numeric\"\n[1] \"complex\"\n[1] \"character\""
},
{
"code": null,
"e": 4369,
"s": 4216,
"text": "To do that, you need to use the prefix “is.” before the data type as a command. The syntax for that is, is.data_type() of the object you have to verify."
},
{
"code": null,
"e": 4378,
"s": 4369,
"text": "Syntax: "
},
{
"code": null,
"e": 4399,
"s": 4378,
"text": "is.data_type(object)"
},
{
"code": null,
"e": 4410,
"s": 4399,
"text": "Example: "
},
{
"code": null,
"e": 4412,
"s": 4410,
"text": "R"
},
{
"code": "# A simple R program# Verify if an object is of a certain datatype # Logicalprint(is.logical(TRUE)) # Integerprint(is.integer(3L)) # Numericprint(is.numeric(10.5)) # Complexprint(is.complex(1+2i)) # Characterprint(is.character(\"12-04-2020\")) print(is.integer(\"a\")) print(is.numeric(2+3i))",
"e": 4701,
"s": 4412,
"text": null
},
{
"code": null,
"e": 4710,
"s": 4701,
"text": "Output: "
},
{
"code": null,
"e": 4775,
"s": 4710,
"text": "[1] TRUE\n[1] TRUE\n[1] TRUE\n[1] TRUE\n[1] TRUE\n[1] FALSE\n[1] FALSE"
},
{
"code": null,
"e": 5049,
"s": 4775,
"text": "This task is interesting where you can change or convert the data type of one object to another. To perform this action you have to use the prefix “as.” before the data type as the command. The syntax for doing that is as.data_type() of the object which you want to coerce."
},
{
"code": null,
"e": 5059,
"s": 5049,
"text": "Syntax: "
},
{
"code": null,
"e": 5081,
"s": 5059,
"text": "as.data_type(object) "
},
{
"code": null,
"e": 5172,
"s": 5081,
"text": "Note: All the coercions are not possible and if attempted will be returning an “NA” value."
},
{
"code": null,
"e": 5183,
"s": 5172,
"text": "Example: "
},
{
"code": null,
"e": 5185,
"s": 5183,
"text": "R"
},
{
"code": "# A simple R program# convert data type of an object to another # Logicalprint(as.numeric(TRUE)) # Integerprint(as.complex(3L)) # Numericprint(as.logical(10.5)) # Complexprint(as.character(1+2i)) # Can't possibleprint(as.numeric(\"12-04-2020\"))",
"e": 5429,
"s": 5185,
"text": null
},
{
"code": null,
"e": 5438,
"s": 5429,
"text": "Output: "
},
{
"code": null,
"e": 5561,
"s": 5438,
"text": "[1] 1\n[1] 3+0i\n[1] TRUE\n[1] \"1+2i\"\n[1] NA\nWarning message:\nIn print(as.numeric(\"12-04-2020\")) : NAs introduced by coercion"
},
{
"code": null,
"e": 5574,
"s": 5561,
"text": "kumar_satyam"
},
{
"code": null,
"e": 5592,
"s": 5574,
"text": "ishmartishtiaq709"
},
{
"code": null,
"e": 5599,
"s": 5592,
"text": "Picked"
},
{
"code": null,
"e": 5612,
"s": 5599,
"text": "R Data-types"
},
{
"code": null,
"e": 5633,
"s": 5612,
"text": "Programming Language"
},
{
"code": null,
"e": 5644,
"s": 5633,
"text": "R Language"
},
{
"code": null,
"e": 5660,
"s": 5644,
"text": "Write From Home"
}
] |
Find the length of a JavaScript object | 26 Jul, 2021
Method 1: Using the Object.keys() method: The Object.keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object.
Syntax:
objectLength = Object.keys(exampleObject).length
Example:
<!DOCTYPE html><html> <head> <title>Length of a JavaScript object</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>Length of a JavaScript object</b> <p> exampleObject = { id: 1, name: 'Arun', age: 30 } </p> <p> Click on the button to get the length of the object. </p> <p> Length of the object is: <span class="output"></span> </p> <button onclick="getObjectLength()"> Get object length </button> <script> function getObjectLength() { // Declare an object exampleObject = { id: 1, name: 'Arun', age: 30 } // Using Object.keys() method to get length objectLenght = Object.keys(exampleObject).length; document.querySelector('.output').textContent = objectLenght; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
Method 2: Loop through all the fields of the object and check their property: The hasOwnProperty() method is used to return a boolean value indicating whether the object has the specified property as its own property. This method can be used to check if each key is present in the object itself. The contents of the object are looped through and if the key is present, the total count of keys is incremented. This gives the length of the object.
Syntax:
var key, count = 0;
// Check if every key has its own property
for (key in exampleObject) {
if (exampleObject.hasOwnProperty(key))
// If the key is found, add it to the total length
count++;
}
objectLenght = count;
Example:
<!DOCTYPE html><html> <head> <title>Length of a JavaScript object</title></head> <body> <h1 style="color: green">GeeksforGeeks</h1> <b>Length of a JavaScript object</b> <p> exampleObject = { id: 1, name: 'Arun', age: 30, department: 'sales' } </p> <p> Click on the button to get the length of the object. </p> <p> Length of the object is: <span class="output"></span> </p> <button onclick="getObjectLength()"> Get object length </button> <script> function getObjectLength() { // Declare an object exampleObject = { id: 1, name: 'Arun', age: 30, department: 'sales' } var key, count = 0; // Check if every key has its own property for (key in exampleObject) { if (exampleObject.hasOwnProperty(key)) // If key is found, add it // to total length count++; } objectLenght = count; document.querySelector('.output').textContent = objectLenght; } </script></body> </html>
Output:
Before clicking the button:
After clicking the button:
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.
shubham_singh
javascript-object
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n26 Jul, 2021"
},
{
"code": null,
"e": 263,
"s": 28,
"text": "Method 1: Using the Object.keys() method: The Object.keys() method is used to return the object property name as an array. The length property is used to get the number of keys present in the object. It gives the length of the object."
},
{
"code": null,
"e": 271,
"s": 263,
"text": "Syntax:"
},
{
"code": null,
"e": 320,
"s": 271,
"text": "objectLength = Object.keys(exampleObject).length"
},
{
"code": null,
"e": 329,
"s": 320,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Length of a JavaScript object</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>Length of a JavaScript object</b> <p> exampleObject = { id: 1, name: 'Arun', age: 30 } </p> <p> Click on the button to get the length of the object. </p> <p> Length of the object is: <span class=\"output\"></span> </p> <button onclick=\"getObjectLength()\"> Get object length </button> <script> function getObjectLength() { // Declare an object exampleObject = { id: 1, name: 'Arun', age: 30 } // Using Object.keys() method to get length objectLenght = Object.keys(exampleObject).length; document.querySelector('.output').textContent = objectLenght; } </script></body> </html> ",
"e": 1376,
"s": 329,
"text": null
},
{
"code": null,
"e": 1384,
"s": 1376,
"text": "Output:"
},
{
"code": null,
"e": 1412,
"s": 1384,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 1439,
"s": 1412,
"text": "After clicking the button:"
},
{
"code": null,
"e": 1885,
"s": 1439,
"text": "Method 2: Loop through all the fields of the object and check their property: The hasOwnProperty() method is used to return a boolean value indicating whether the object has the specified property as its own property. This method can be used to check if each key is present in the object itself. The contents of the object are looped through and if the key is present, the total count of keys is incremented. This gives the length of the object."
},
{
"code": null,
"e": 1893,
"s": 1885,
"text": "Syntax:"
},
{
"code": null,
"e": 2131,
"s": 1893,
"text": "var key, count = 0;\n\n// Check if every key has its own property\nfor (key in exampleObject) {\n if (exampleObject.hasOwnProperty(key))\n\n // If the key is found, add it to the total length\n count++;\n}\nobjectLenght = count;\n"
},
{
"code": null,
"e": 2140,
"s": 2131,
"text": "Example:"
},
{
"code": "<!DOCTYPE html><html> <head> <title>Length of a JavaScript object</title></head> <body> <h1 style=\"color: green\">GeeksforGeeks</h1> <b>Length of a JavaScript object</b> <p> exampleObject = { id: 1, name: 'Arun', age: 30, department: 'sales' } </p> <p> Click on the button to get the length of the object. </p> <p> Length of the object is: <span class=\"output\"></span> </p> <button onclick=\"getObjectLength()\"> Get object length </button> <script> function getObjectLength() { // Declare an object exampleObject = { id: 1, name: 'Arun', age: 30, department: 'sales' } var key, count = 0; // Check if every key has its own property for (key in exampleObject) { if (exampleObject.hasOwnProperty(key)) // If key is found, add it // to total length count++; } objectLenght = count; document.querySelector('.output').textContent = objectLenght; } </script></body> </html> ",
"e": 3467,
"s": 2140,
"text": null
},
{
"code": null,
"e": 3475,
"s": 3467,
"text": "Output:"
},
{
"code": null,
"e": 3503,
"s": 3475,
"text": "Before clicking the button:"
},
{
"code": null,
"e": 3530,
"s": 3503,
"text": "After clicking the button:"
},
{
"code": null,
"e": 3749,
"s": 3530,
"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": 3763,
"s": 3749,
"text": "shubham_singh"
},
{
"code": null,
"e": 3781,
"s": 3763,
"text": "javascript-object"
},
{
"code": null,
"e": 3788,
"s": 3781,
"text": "Picked"
},
{
"code": null,
"e": 3799,
"s": 3788,
"text": "JavaScript"
},
{
"code": null,
"e": 3816,
"s": 3799,
"text": "Web Technologies"
},
{
"code": null,
"e": 3843,
"s": 3816,
"text": "Web technologies Questions"
}
] |
Lodash _.union() Method | 01 Sep, 2020
The _.union() method is used to take n number of arrays and creates an array of unique values in order, from all given arrays using SameValueZero for equality comparisons.
Syntax:
_.union(*arrays)
Parameters: This method accepts a single parameter as mentioned above and described below:
arrays: This parameter holds arrays to inspect.
Return Value: This method is used to return the new array of combined values.
Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file.
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.union() method let gfg = _.union([20, 12], [8, 15, 6]); // Printing the output console.log(gfg)
Output:
[20, 12, 8, 15, 6]
Example 2:
Javascript
// Requiring the lodash library const _ = require("lodash"); // Use of _.union() method let gfg = _.union([1, 2, 3], [3, 4, 5], [6, 2, 7]); // Printing the output console.log(gfg)
Output:
[1, 2, 3, 4, 5, 6, 7]
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Sep, 2020"
},
{
"code": null,
"e": 200,
"s": 28,
"text": "The _.union() method is used to take n number of arrays and creates an array of unique values in order, from all given arrays using SameValueZero for equality comparisons."
},
{
"code": null,
"e": 209,
"s": 200,
"text": "Syntax: "
},
{
"code": null,
"e": 226,
"s": 209,
"text": "_.union(*arrays)"
},
{
"code": null,
"e": 317,
"s": 226,
"text": "Parameters: This method accepts a single parameter as mentioned above and described below:"
},
{
"code": null,
"e": 365,
"s": 317,
"text": "arrays: This parameter holds arrays to inspect."
},
{
"code": null,
"e": 443,
"s": 365,
"text": "Return Value: This method is used to return the new array of combined values."
},
{
"code": null,
"e": 538,
"s": 443,
"text": "Example 1: Here, const _ = require(‘lodash’) is used to import the lodash library in the file."
},
{
"code": null,
"e": 549,
"s": 538,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.union() method let gfg = _.union([20, 12], [8, 15, 6]); // Printing the output console.log(gfg)",
"e": 731,
"s": 549,
"text": null
},
{
"code": null,
"e": 739,
"s": 731,
"text": "Output:"
},
{
"code": null,
"e": 758,
"s": 739,
"text": "[20, 12, 8, 15, 6]"
},
{
"code": null,
"e": 770,
"s": 758,
"text": "Example 2: "
},
{
"code": null,
"e": 781,
"s": 770,
"text": "Javascript"
},
{
"code": "// Requiring the lodash library const _ = require(\"lodash\"); // Use of _.union() method let gfg = _.union([1, 2, 3], [3, 4, 5], [6, 2, 7]); // Printing the output console.log(gfg)",
"e": 1008,
"s": 781,
"text": null
},
{
"code": null,
"e": 1016,
"s": 1008,
"text": "Output:"
},
{
"code": null,
"e": 1038,
"s": 1016,
"text": "[1, 2, 3, 4, 5, 6, 7]"
},
{
"code": null,
"e": 1056,
"s": 1038,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 1067,
"s": 1056,
"text": "JavaScript"
},
{
"code": null,
"e": 1084,
"s": 1067,
"text": "Web Technologies"
}
] |
ReactJS Portals | 31 Mar, 2021
React portals come up with a way to render children into a DOM node that occurs outside the DOM hierarchy of the parent component. The portals were introduced in React 16.0 version.
So far we were having one DOM element in the HTML into which we were mounting our react application, i.e., the root element of our index.html in the public folder. Basically, we mount our App component onto our root element. It is almost a convention to have a div element with the id of root to be used as the root DOM element. If you take a look at the browser in the DOM tree every single React component in our application falls under the root element, i.e., inside this statement.
<div id="root"></div>
But React Portals provide us the ability to break out of this dom tree and render a component onto a dom node that is not under this root element. Doing so breaks the convention where a component needs to be rendered as a new element and follow a parent-child hierarchy. They are commonly used in modal dialog boxes, hovercards, loaders, and popup messages.
Syntax:
ReactDOM.createPortal(child, container)
Parameters: Here the first parameter is a child which can be a React element, string, or a fragment and the second parameter is a container which is the DOM node (or location) lying outside the DOM hierarchy of the parent component at which our portal is to be inserted.
Importing: To create and use portals you need to import ReactDOM as shown below.
import ReactDOM from 'react-dom';
Creating React Application:
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
Project Structure: It will look like the following.
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 ReactDOM from 'react-dom'function App() { // Creating a portal return ReactDOM.createPortal( <h1>Portal demo</h1>, document.getElementById('portal') )} export default App;
index.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <title>React App</title> </head> <body> <noscript> You need to enable JavaScript to run this app. </noscript> <div id="root"></div> <!-- new div added to access the child component --> <div id="portal"></div> </body></html>
Output:
Explanation: Here, we can see that our <h1> tag Portal Demo is under the newly created portal DOM node, not the traditional root DOM node. It clearly tells us how React Portal provides the ability to break out of the root DOM tree and renders a component/element outside the parent DOM element.
Event Bubbling inside a portal: Although we don’t render a portal inside the parent DOM element, its behavior is still similar to a regular React component inside the application. It can access the props and state as it resides inside the DOM tree hierarchy. For example, if we fire an event from inside a portal it will propagate to the Parent component in the containing React tree, i.e., event bubbling works the same way as it does in normal circumstances. Let us understand this with another example:
Example: Program to demonstrate how event bubbling works with portals. Here, we are going to update the previous value of the state by triggering an event listener from outside of the parent DOM node.
App.js
import React, { Component } from 'react'import ReactDOM from 'react-dom' class Portal extends Component { render() { // Creating portal return ReactDOM.createPortal( <button style={{marginLeft: '10px'}}> Click </button>, document.getElementById('portal') ); }} class App extends Component { constructor(props) { super(props); // Set initial state this.state = {click: 0}; // Binding this keyword this.handleClick = this.handleClick.bind(this); } handleClick() { // This will trigger when the button inside Portal // is clicked, It updates Parent's state, even though it // is not rendered inside the parent DOM element this.setState(prevState => ({ click: prevState.click + 1 })); } render() { return ( <div onClick={this.handleClick} style={{marginLeft: '10px'}}> <p> You have clicked me {this.state.click} times </p> <Portal /> </div> ); }} export default App;
index.html
<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8" /> <link rel="icon" href="%PUBLIC_URL%/favicon.ico" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app" /> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" href="%PUBLIC_URL%/manifest.json" /> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id="root"></div> <!-- new div added to access the child component --> <div id="portal"></div> </body></html>
Output:
Explanation: We create a state count with an initial value of 0 and a function handleClick which increments the previous value of state by 1. The latter gets triggered as an onClick event when we click on the button which has been rendered outside the root DOM node. Even then, it is able to propagate the event to the parent component and access the state value as if it is a regular React component.
Reference Link: https://reactjs.org/docs/portals.html
Picked
ReactJS-Basics
ReactJS
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Mar, 2021"
},
{
"code": null,
"e": 210,
"s": 28,
"text": "React portals come up with a way to render children into a DOM node that occurs outside the DOM hierarchy of the parent component. The portals were introduced in React 16.0 version."
},
{
"code": null,
"e": 696,
"s": 210,
"text": "So far we were having one DOM element in the HTML into which we were mounting our react application, i.e., the root element of our index.html in the public folder. Basically, we mount our App component onto our root element. It is almost a convention to have a div element with the id of root to be used as the root DOM element. If you take a look at the browser in the DOM tree every single React component in our application falls under the root element, i.e., inside this statement."
},
{
"code": null,
"e": 718,
"s": 696,
"text": "<div id=\"root\"></div>"
},
{
"code": null,
"e": 1076,
"s": 718,
"text": "But React Portals provide us the ability to break out of this dom tree and render a component onto a dom node that is not under this root element. Doing so breaks the convention where a component needs to be rendered as a new element and follow a parent-child hierarchy. They are commonly used in modal dialog boxes, hovercards, loaders, and popup messages."
},
{
"code": null,
"e": 1084,
"s": 1076,
"text": "Syntax:"
},
{
"code": null,
"e": 1124,
"s": 1084,
"text": "ReactDOM.createPortal(child, container)"
},
{
"code": null,
"e": 1395,
"s": 1124,
"text": "Parameters: Here the first parameter is a child which can be a React element, string, or a fragment and the second parameter is a container which is the DOM node (or location) lying outside the DOM hierarchy of the parent component at which our portal is to be inserted."
},
{
"code": null,
"e": 1476,
"s": 1395,
"text": "Importing: To create and use portals you need to import ReactDOM as shown below."
},
{
"code": null,
"e": 1510,
"s": 1476,
"text": "import ReactDOM from 'react-dom';"
},
{
"code": null,
"e": 1538,
"s": 1510,
"text": "Creating React Application:"
},
{
"code": null,
"e": 1633,
"s": 1538,
"text": "Step 1: Create a React application using the following command.npx create-react-app foldername"
},
{
"code": null,
"e": 1697,
"s": 1633,
"text": "Step 1: Create a React application using the following command."
},
{
"code": null,
"e": 1729,
"s": 1697,
"text": "npx create-react-app foldername"
},
{
"code": null,
"e": 1842,
"s": 1729,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command.cd foldername"
},
{
"code": null,
"e": 1942,
"s": 1842,
"text": "Step 2: After creating your project folder i.e. foldername, move to it using the following command."
},
{
"code": null,
"e": 1956,
"s": 1942,
"text": "cd foldername"
},
{
"code": null,
"e": 2008,
"s": 1956,
"text": "Project Structure: It will look like the following."
},
{
"code": null,
"e": 2138,
"s": 2008,
"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": 2145,
"s": 2138,
"text": "App.js"
},
{
"code": "import ReactDOM from 'react-dom'function App() { // Creating a portal return ReactDOM.createPortal( <h1>Portal demo</h1>, document.getElementById('portal') )} export default App;",
"e": 2335,
"s": 2145,
"text": null
},
{
"code": null,
"e": 2346,
"s": 2335,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <meta name=\"theme-color\" content=\"#000000\" /> <meta name=\"description\" content=\"Web site created using create-react-app\" /> <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" /> <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" /> <title>React App</title> </head> <body> <noscript> You need to enable JavaScript to run this app. </noscript> <div id=\"root\"></div> <!-- new div added to access the child component --> <div id=\"portal\"></div> </body></html>",
"e": 3070,
"s": 2346,
"text": null
},
{
"code": null,
"e": 3078,
"s": 3070,
"text": "Output:"
},
{
"code": null,
"e": 3373,
"s": 3078,
"text": "Explanation: Here, we can see that our <h1> tag Portal Demo is under the newly created portal DOM node, not the traditional root DOM node. It clearly tells us how React Portal provides the ability to break out of the root DOM tree and renders a component/element outside the parent DOM element."
},
{
"code": null,
"e": 3879,
"s": 3373,
"text": "Event Bubbling inside a portal: Although we don’t render a portal inside the parent DOM element, its behavior is still similar to a regular React component inside the application. It can access the props and state as it resides inside the DOM tree hierarchy. For example, if we fire an event from inside a portal it will propagate to the Parent component in the containing React tree, i.e., event bubbling works the same way as it does in normal circumstances. Let us understand this with another example:"
},
{
"code": null,
"e": 4080,
"s": 3879,
"text": "Example: Program to demonstrate how event bubbling works with portals. Here, we are going to update the previous value of the state by triggering an event listener from outside of the parent DOM node."
},
{
"code": null,
"e": 4087,
"s": 4080,
"text": "App.js"
},
{
"code": "import React, { Component } from 'react'import ReactDOM from 'react-dom' class Portal extends Component { render() { // Creating portal return ReactDOM.createPortal( <button style={{marginLeft: '10px'}}> Click </button>, document.getElementById('portal') ); }} class App extends Component { constructor(props) { super(props); // Set initial state this.state = {click: 0}; // Binding this keyword this.handleClick = this.handleClick.bind(this); } handleClick() { // This will trigger when the button inside Portal // is clicked, It updates Parent's state, even though it // is not rendered inside the parent DOM element this.setState(prevState => ({ click: prevState.click + 1 })); } render() { return ( <div onClick={this.handleClick} style={{marginLeft: '10px'}}> <p> You have clicked me {this.state.click} times </p> <Portal /> </div> ); }} export default App;",
"e": 5096,
"s": 4087,
"text": null
},
{
"code": null,
"e": 5107,
"s": 5096,
"text": "index.html"
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"utf-8\" /> <link rel=\"icon\" href=\"%PUBLIC_URL%/favicon.ico\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\" /> <meta name=\"theme-color\" content=\"#000000\" /> <meta name=\"description\" content=\"Web site created using create-react-app\" /> <link rel=\"apple-touch-icon\" href=\"%PUBLIC_URL%/logo192.png\" /> <link rel=\"manifest\" href=\"%PUBLIC_URL%/manifest.json\" /> <title>React App</title> </head> <body> <noscript>You need to enable JavaScript to run this app.</noscript> <div id=\"root\"></div> <!-- new div added to access the child component --> <div id=\"portal\"></div> </body></html>",
"e": 5821,
"s": 5107,
"text": null
},
{
"code": null,
"e": 5829,
"s": 5821,
"text": "Output:"
},
{
"code": null,
"e": 6231,
"s": 5829,
"text": "Explanation: We create a state count with an initial value of 0 and a function handleClick which increments the previous value of state by 1. The latter gets triggered as an onClick event when we click on the button which has been rendered outside the root DOM node. Even then, it is able to propagate the event to the parent component and access the state value as if it is a regular React component."
},
{
"code": null,
"e": 6285,
"s": 6231,
"text": "Reference Link: https://reactjs.org/docs/portals.html"
},
{
"code": null,
"e": 6292,
"s": 6285,
"text": "Picked"
},
{
"code": null,
"e": 6307,
"s": 6292,
"text": "ReactJS-Basics"
},
{
"code": null,
"e": 6315,
"s": 6307,
"text": "ReactJS"
},
{
"code": null,
"e": 6332,
"s": 6315,
"text": "Web Technologies"
}
] |
Set of Vectors in C++ STL with Examples | 17 Mar, 2020
Set in STL Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element.
Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators.
Set of Vectors in STL: Set of Vectors can be very efficient in designing complex data structures.
Syntax:
set<vector<datatype>> set_of_vector;
For example: Consider a simple problem where we have to print all the unique vectors.
// C++ program to demonstrate// use of set for vectors #include <bits/stdc++.h>using namespace std; set<vector<int> > set_of_vectors; // Print elements of Vectorvoid Print_Vector(vector<int> Vec){ for (int i = 0; i < Vec.size(); i++) { cout << Vec[i] << " "; } cout << endl; return;} // Driver codeint main(){ // Initializing some vectors vector<int> data_1{ 10, 20, 30, 40 }; vector<int> data_2{ 5, 10, 15 }; vector<int> data_3{ 1, 3, 5, 7, 9, 11, 13 }; vector<int> data_4{ 5, 10, 15 }; vector<int> data_5{ 10, 20, 30, 40 }; // Inserting vectors into set set_of_vectors.insert(data_1); set_of_vectors.insert(data_2); set_of_vectors.insert(data_3); set_of_vectors.insert(data_4); set_of_vectors.insert(data_5); // printing all the unique vectors in set cout << "Set of Vectors: \n"; for (auto it = set_of_vectors.begin(); it != set_of_vectors.end(); it++) { Print_Vector(*it); } return 0;}
Set of Vectors:
1 3 5 7 9 11 13
5 10 15
10 20 30 40
cpp-set
cpp-vector
C++ Programs
Data Structures
Data Structures
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Shallow Copy and Deep Copy in C++
C++ Program to check if a given String is Palindrome or not
delete keyword in C++
C Program to Swap two Numbers
C++ Program for QuickSort
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
Top 50 Array Coding Problems for Interviews
What is Hashing | A Complete Tutorial
Introduction to Data Structures | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n17 Mar, 2020"
},
{
"code": null,
"e": 344,
"s": 54,
"text": "Set in STL Sets are a type of associative containers in which each element has to be unique, because the value of the element identifies it. The value of the element cannot be modified once it is added to the set, though it is possible to remove and add the modified value of that element."
},
{
"code": null,
"e": 653,
"s": 344,
"text": "Vector in STL Vector is same as dynamic arrays with the ability to resize itself automatically when an element is inserted or deleted, with their storage being handled automatically by the container. Vector elements are placed in contiguous storage so that they can be accessed and traversed using iterators."
},
{
"code": null,
"e": 751,
"s": 653,
"text": "Set of Vectors in STL: Set of Vectors can be very efficient in designing complex data structures."
},
{
"code": null,
"e": 759,
"s": 751,
"text": "Syntax:"
},
{
"code": null,
"e": 797,
"s": 759,
"text": "set<vector<datatype>> set_of_vector;\n"
},
{
"code": null,
"e": 883,
"s": 797,
"text": "For example: Consider a simple problem where we have to print all the unique vectors."
},
{
"code": "// C++ program to demonstrate// use of set for vectors #include <bits/stdc++.h>using namespace std; set<vector<int> > set_of_vectors; // Print elements of Vectorvoid Print_Vector(vector<int> Vec){ for (int i = 0; i < Vec.size(); i++) { cout << Vec[i] << \" \"; } cout << endl; return;} // Driver codeint main(){ // Initializing some vectors vector<int> data_1{ 10, 20, 30, 40 }; vector<int> data_2{ 5, 10, 15 }; vector<int> data_3{ 1, 3, 5, 7, 9, 11, 13 }; vector<int> data_4{ 5, 10, 15 }; vector<int> data_5{ 10, 20, 30, 40 }; // Inserting vectors into set set_of_vectors.insert(data_1); set_of_vectors.insert(data_2); set_of_vectors.insert(data_3); set_of_vectors.insert(data_4); set_of_vectors.insert(data_5); // printing all the unique vectors in set cout << \"Set of Vectors: \\n\"; for (auto it = set_of_vectors.begin(); it != set_of_vectors.end(); it++) { Print_Vector(*it); } return 0;}",
"e": 1878,
"s": 883,
"text": null
},
{
"code": null,
"e": 1934,
"s": 1878,
"text": "Set of Vectors: \n1 3 5 7 9 11 13 \n5 10 15 \n10 20 30 40\n"
},
{
"code": null,
"e": 1942,
"s": 1934,
"text": "cpp-set"
},
{
"code": null,
"e": 1953,
"s": 1942,
"text": "cpp-vector"
},
{
"code": null,
"e": 1966,
"s": 1953,
"text": "C++ Programs"
},
{
"code": null,
"e": 1982,
"s": 1966,
"text": "Data Structures"
},
{
"code": null,
"e": 1998,
"s": 1982,
"text": "Data Structures"
},
{
"code": null,
"e": 2096,
"s": 1998,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2130,
"s": 2096,
"text": "Shallow Copy and Deep Copy in C++"
},
{
"code": null,
"e": 2190,
"s": 2130,
"text": "C++ Program to check if a given String is Palindrome or not"
},
{
"code": null,
"e": 2212,
"s": 2190,
"text": "delete keyword in C++"
},
{
"code": null,
"e": 2242,
"s": 2212,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 2268,
"s": 2242,
"text": "C++ Program for QuickSort"
},
{
"code": null,
"e": 2293,
"s": 2268,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 2342,
"s": 2293,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 2386,
"s": 2342,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 2424,
"s": 2386,
"text": "What is Hashing | A Complete Tutorial"
}
] |
\shoveleft - Tex Command | \shoveleft - Used for forces flush left typesetting in a \multline or \multline* environment.
{ \shoveleft }
\shoveleft command is used for forces flush left typesetting in a \multline or \multline* environment.
\begin{multline}
(a+b+c+d)^2 \\
+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2 \\
+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2 \\
+ (w+x+y+z)^2
\end{multline}
(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2
\begin{multline}
(a+b+c+d)^2 \\
\shoveleft{+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2} \\
\shoveright{+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2} \\
+ (w+x+y+z)^2
\end{multline}
(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2
\begin{multline}
(a+b+c+d)^2 \\
+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2 \\
+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2 \\
+ (w+x+y+z)^2
\end{multline}
(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2
\begin{multline}
(a+b+c+d)^2 \\
+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2 \\
+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2 \\
+ (w+x+y+z)^2
\end{multline}
\begin{multline}
(a+b+c+d)^2 \\
\shoveleft{+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2} \\
\shoveright{+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2} \\
+ (w+x+y+z)^2
\end{multline}
(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2
\begin{multline}
(a+b+c+d)^2 \\
\shoveleft{+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2} \\
\shoveright{+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2} \\ | [
{
"code": null,
"e": 8215,
"s": 8120,
"text": "\\shoveleft - Used for forces flush left typesetting in a \\multline or \\multline* environment."
},
{
"code": null,
"e": 8230,
"s": 8215,
"text": "{ \\shoveleft }"
},
{
"code": null,
"e": 8334,
"s": 8230,
"text": "\\shoveleft command is used for forces flush left typesetting in a \\multline or \\multline* environment."
},
{
"code": null,
"e": 8855,
"s": 8334,
"text": "\n\\begin{multline}\n(a+b+c+d)^2 \\\\\n+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2 \\\\\n+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2 \\\\\n+ (w+x+y+z)^2\n\\end{multline}\n\n\n(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2\n\n\n\\begin{multline}\n(a+b+c+d)^2 \\\\\n\\shoveleft{+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2} \\\\\n\\shoveright{+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2} \\\\\n+ (w+x+y+z)^2\n\\end{multline}\n\n\n(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2\n\n\n"
},
{
"code": null,
"e": 9102,
"s": 8855,
"text": "\\begin{multline}\n(a+b+c+d)^2 \\\\\n+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2 \\\\\n+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2 \\\\\n+ (w+x+y+z)^2\n\\end{multline}\n\n\n(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2\n\n"
},
{
"code": null,
"e": 9261,
"s": 9102,
"text": "\\begin{multline}\n(a+b+c+d)^2 \\\\\n+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2 \\\\\n+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2 \\\\\n+ (w+x+y+z)^2\n\\end{multline}\n"
},
{
"code": null,
"e": 9533,
"s": 9261,
"text": "\\begin{multline}\n(a+b+c+d)^2 \\\\\n\\shoveleft{+ (e+f)^2 + (g+h)^2 + (i+j)^2 + (k+l)^2} \\\\\n\\shoveright{+ (m+n)^2 + (o+p)^2 + (q+r)^2 + (s+t)^2 + (u+v)^2} \\\\\n+ (w+x+y+z)^2\n\\end{multline}\n\n\n(a+b+c+d)2+(e+f)2+(g+h)2+(i+j)2+(k+l)2+(m+n)2+(o+p)2+(q+r)2+(s+t)2+(u+v)2+(w+x+y+z)2\n\n"
}
] |
Java Program to Reverse a Number & Check if it is a Palindrome | 04 Nov, 2020
Given number can be said palindromic in nature if the reverse of the given number is the same as that of a given number. Length of number is log10(n), i.e. For BigIntegers using string operation like creation reverse and check palindrome will take log10(n) time.
A. Number under Java int limit
Example :
Input : n = 46355364
Output: Reverse of n = 46355364
Palindrome = Yes
Input : n = 87476572465
Output: Reverse of n = 56427567478
Palindrome = No
We can reverse a number in multiple ways, below is the iterative implementation for the same.
Iterative Algorithm :
Input: number
1. Initialize reversed_number = 0
2. Loop while num
ber > 0
a. Multiply reversed_number by 10 and add number % 10 to reversed_number
reversed_number = reversed_number*10 + number %10;
b. Divide number by 10
3. Return reversed_number
Example:
number = 1234
reversed_number= 0
reversed_number = reversed_number *10 + number%10 = 4
number = number/10 = 123
reversed_number = reversed_number*10 + number%10 = 20 + 6 = 43
number = number/10 = 12
reversed_number = reversed_number*10 + number%10 = 260 + 5 = 432
number = number/10 = 1
reversed_number = reversed_number*10 + number%10 = 265 + 4 = 4321
number = number/10 = 0
Below is the implementation of the above approach.
Java
// Java program to reverse a number// and find if it is a palindrome or notclass GFG { // Iterative function to // reverse the digits of number static int reversNumber(int n) { int reversed_n = 0; while (n > 0) { reversed_n = reversed_n * 10 + n % 10; n = n / 10; } return reversed_n; } // Main function public static void main(String[] args) { int n = 123464321; int reverseN = reversNumber(n); System.out.println("Reverse of n = " + reverseN); // Checking if n is same // as reverse of n if (n == reverseN) System.out.println("Palindrome = Yes"); else System.out.println("Palindrome = No"); }}
Reverse of n = 123464321
Palindrome = Yes
Time Complexity: O(log10(n)) where n is the input number.
B. Large integer: Use BigInteger Class
Example
Input : n = 12345678999999999987654321
Output: Reverse of n = 12345678999999999987654321
Palindrome = Yes
Approach
Take input in BigInteger variable.Reverse the given BigInteger using the reverse method.Compare both BigIntegers using compareTo() method.
Take input in BigInteger variable.
Reverse the given BigInteger using the reverse method.
Compare both BigIntegers using compareTo() method.
Below is the implementation of the above approach.
Java
// Java program to reverse a number// and find if it is a palindrome or notimport java.io.*;import java.math.BigInteger;class GFG { // Reverse Big Integer public static BigInteger reverse(BigInteger n) { String s = n.toString(); StringBuilder sb = new StringBuilder(s); return new BigInteger(sb.reverse().toString()); } // Main Function public static void main(String[] args) { BigInteger n = new BigInteger("12345678999999999987654321"); BigInteger reverseN = reverse(n); System.out.println("Reverse of n = " + reverseN); // Checking if n is same // as reverse of n if (n.compareTo(reverseN) == 0) System.out.println("Palindrome = Yes"); else System.out.println("Palindrome = No"); }}
Reverse of n = 12345678999999999987654321
Palindrome = Yes
Time Complexity: O(log10(n)) where n is the input number.
palindrome
Reverse
Java
Java Programs
Java
palindrome
Reverse
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
How to iterate any Map in Java
Interfaces in Java
HashMap in Java with Examples
ArrayList in Java
Initializing a List in Java
Java Programming Examples
Convert a String to Character Array in Java
Implementing a Linked List in Java using Class
Factory method design pattern in Java | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n04 Nov, 2020"
},
{
"code": null,
"e": 316,
"s": 52,
"text": "Given number can be said palindromic in nature if the reverse of the given number is the same as that of a given number. Length of number is log10(n), i.e. For BigIntegers using string operation like creation reverse and check palindrome will take log10(n) time. "
},
{
"code": null,
"e": 348,
"s": 316,
"text": "A. Number under Java int limit "
},
{
"code": null,
"e": 359,
"s": 348,
"text": "Example : "
},
{
"code": null,
"e": 514,
"s": 359,
"text": "Input : n = 46355364\nOutput: Reverse of n = 46355364\n Palindrome = Yes\n\nInput : n = 87476572465\nOutput: Reverse of n = 56427567478\n Palindrome = No\n"
},
{
"code": null,
"e": 608,
"s": 514,
"text": "We can reverse a number in multiple ways, below is the iterative implementation for the same."
},
{
"code": null,
"e": 630,
"s": 608,
"text": "Iterative Algorithm :"
},
{
"code": null,
"e": 906,
"s": 630,
"text": "Input: number\n1. Initialize reversed_number = 0\n2. Loop while num\nber > 0\n a. Multiply reversed_number by 10 and add number % 10 to reversed_number\n reversed_number = reversed_number*10 + number %10;\n b. Divide number by 10\n3. Return reversed_number\n"
},
{
"code": null,
"e": 915,
"s": 906,
"text": "Example:"
},
{
"code": null,
"e": 1296,
"s": 915,
"text": "number = 1234\nreversed_number= 0\n\nreversed_number = reversed_number *10 + number%10 = 4\nnumber = number/10 = 123\n\nreversed_number = reversed_number*10 + number%10 = 20 + 6 = 43\nnumber = number/10 = 12\n\nreversed_number = reversed_number*10 + number%10 = 260 + 5 = 432\nnumber = number/10 = 1\n\nreversed_number = reversed_number*10 + number%10 = 265 + 4 = 4321\nnumber = number/10 = 0\n"
},
{
"code": null,
"e": 1348,
"s": 1296,
"text": "Below is the implementation of the above approach. "
},
{
"code": null,
"e": 1353,
"s": 1348,
"text": "Java"
},
{
"code": "// Java program to reverse a number// and find if it is a palindrome or notclass GFG { // Iterative function to // reverse the digits of number static int reversNumber(int n) { int reversed_n = 0; while (n > 0) { reversed_n = reversed_n * 10 + n % 10; n = n / 10; } return reversed_n; } // Main function public static void main(String[] args) { int n = 123464321; int reverseN = reversNumber(n); System.out.println(\"Reverse of n = \" + reverseN); // Checking if n is same // as reverse of n if (n == reverseN) System.out.println(\"Palindrome = Yes\"); else System.out.println(\"Palindrome = No\"); }}",
"e": 2109,
"s": 1353,
"text": null
},
{
"code": null,
"e": 2153,
"s": 2109,
"text": "Reverse of n = 123464321\nPalindrome = Yes\n\n"
},
{
"code": null,
"e": 2211,
"s": 2153,
"text": "Time Complexity: O(log10(n)) where n is the input number."
},
{
"code": null,
"e": 2250,
"s": 2211,
"text": "B. Large integer: Use BigInteger Class"
},
{
"code": null,
"e": 2258,
"s": 2250,
"text": "Example"
},
{
"code": null,
"e": 2369,
"s": 2258,
"text": "Input : n = 12345678999999999987654321\nOutput: Reverse of n = 12345678999999999987654321\n Palindrome = Yes\n"
},
{
"code": null,
"e": 2378,
"s": 2369,
"text": "Approach"
},
{
"code": null,
"e": 2517,
"s": 2378,
"text": "Take input in BigInteger variable.Reverse the given BigInteger using the reverse method.Compare both BigIntegers using compareTo() method."
},
{
"code": null,
"e": 2552,
"s": 2517,
"text": "Take input in BigInteger variable."
},
{
"code": null,
"e": 2607,
"s": 2552,
"text": "Reverse the given BigInteger using the reverse method."
},
{
"code": null,
"e": 2658,
"s": 2607,
"text": "Compare both BigIntegers using compareTo() method."
},
{
"code": null,
"e": 2709,
"s": 2658,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 2714,
"s": 2709,
"text": "Java"
},
{
"code": "// Java program to reverse a number// and find if it is a palindrome or notimport java.io.*;import java.math.BigInteger;class GFG { // Reverse Big Integer public static BigInteger reverse(BigInteger n) { String s = n.toString(); StringBuilder sb = new StringBuilder(s); return new BigInteger(sb.reverse().toString()); } // Main Function public static void main(String[] args) { BigInteger n = new BigInteger(\"12345678999999999987654321\"); BigInteger reverseN = reverse(n); System.out.println(\"Reverse of n = \" + reverseN); // Checking if n is same // as reverse of n if (n.compareTo(reverseN) == 0) System.out.println(\"Palindrome = Yes\"); else System.out.println(\"Palindrome = No\"); }}",
"e": 3529,
"s": 2714,
"text": null
},
{
"code": null,
"e": 3590,
"s": 3529,
"text": "Reverse of n = 12345678999999999987654321\nPalindrome = Yes\n\n"
},
{
"code": null,
"e": 3648,
"s": 3590,
"text": "Time Complexity: O(log10(n)) where n is the input number."
},
{
"code": null,
"e": 3659,
"s": 3648,
"text": "palindrome"
},
{
"code": null,
"e": 3667,
"s": 3659,
"text": "Reverse"
},
{
"code": null,
"e": 3672,
"s": 3667,
"text": "Java"
},
{
"code": null,
"e": 3686,
"s": 3672,
"text": "Java Programs"
},
{
"code": null,
"e": 3691,
"s": 3686,
"text": "Java"
},
{
"code": null,
"e": 3702,
"s": 3691,
"text": "palindrome"
},
{
"code": null,
"e": 3710,
"s": 3702,
"text": "Reverse"
},
{
"code": null,
"e": 3808,
"s": 3710,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3859,
"s": 3808,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 3890,
"s": 3859,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 3909,
"s": 3890,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 3939,
"s": 3909,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 3957,
"s": 3939,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 3985,
"s": 3957,
"text": "Initializing a List in Java"
},
{
"code": null,
"e": 4011,
"s": 3985,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 4055,
"s": 4011,
"text": "Convert a String to Character Array in Java"
},
{
"code": null,
"e": 4102,
"s": 4055,
"text": "Implementing a Linked List in Java using Class"
}
] |
Flutter – ListTile Widget | 14 Jun, 2022
ListTile widget is used to populate a ListView in Flutter. It contains title as well as leading or trailing icons. Let’s understand this with the help of an example.
ListTile({Key key,
Widget leading,
Widget title,
Widget subtitle,
Widget trailing,
bool isThreeLine: false,
bool dense,
VisualDensity visualDensity,
ShapeBorder shape,
EdgeInsetsGeometry contentPadding,
bool enabled: true,
GestureTapCallback onTap,
GestureLongPressCallback onLongPress,
MouseCursor mouseCursor,
bool selected: false,
Color focusColor,
Color hoverColor,
FocusNode focusNode,
bool autofocus: false})
autofocus: This property takes in a boolean as the object to decide whether this widget will be selected on the initial focus or not.
contentPadding: By taking EdgeInsetsGeometry as the object this property controls the padding.
dense: This property decides whether the ListTile will be a part of a vertically dense list or not by taking in a boolean as the object.
enable: This property controls whether the ListTile will be interactive or not by taking in a boolean as the object.
focusColor: This property holds Color class as the object to control the color of the widget at the time of input focus.
focusNode: This property provides an additional node.
hoverColor: This property takes in Color class as the object to decide the color of the tile at the time of hover.
isThreeLine: whether this list item should display three lines of text or not.
leading: leading widget of the ListTile.
mouseCursor: The mouseCursor property holds MouseCursor class as the object to decide the cursor for the mouse pointer at the time of pointer event.
onLongPress: This holds GestureLongPressCallback typedef as the object
onTap: function to be called when the list tile is pressed.
selected: This property holds a boolean as the object. If set to true then the text and icon will be painted with the same color.
selectedTileColor: This property controls the background color of the ListTile when it is selected.
shape: the shape of the title’s InkWell.
subtitle: additional content displayed below the title.
titleColor: This property defines the background color of the ListTile when it is not selected, by taking in Color class as the object.
tile: title to be given to ListTile widget.
trailing: trailing widget of the ListTile.
visualDensity. This property takes in VisualDensity class as the object. It defines the compactness in the layout of the ListTile.
Example:
The main.dart file.
Dart
import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} // Classclass MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is//the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ListTile', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), debugShowCheckedModeBanner: false, ); }} // Classclass MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { String txt = ''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), backgroundColor: Colors.grey[100], body: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Container( color: Colors.blue[50], child: ListTile( leading: const Icon(Icons.add), title: const Text( 'GFG title', textScaleFactor: 1.5, ), trailing: const Icon(Icons.done), subtitle: const Text('This is subtitle'), selected: true, onTap: () { setState(() { txt = 'List Tile pressed'; }); }, ), ), ), Text( txt, textScaleFactor: 2, ) ], ), ); }}
Output:
If the properties are defined as below:
const ListTile(
leading: Icon(Icons.add),
title: Text(
'GFG title',
textScaleFactor: 1.5,
),
trailing: Icon(Icons.done),
),
The following design changes can be observed:
If the properties are defined as below:
const ListTile(
leading: Icon(Icons.add),
title: Text(
'GFG title',
textScaleFactor: 1.5,
),
trailing: Icon(Icons.done),
subtitle: Text('This is subtitle'),
selected: true,
),
The following design changes can be observed:
If the properties are defined as below:
ListTile(
leading: const Icon(Icons.add),
title: const Text(
'GFG title',
textScaleFactor: 1.5,
),
trailing: const Icon(Icons.done),
subtitle: const Text('This is subtitle'),
selected: true,
onTap: () {
setState(() {
txt = 'List Tile pressed';
});
},
),
// when user tap the list tile then below output will be shown.
The following design changes can be observed:
Output explanation:
Create a ListTile widget and wrap it with Container widget.
After that, give ListTile a title, leading, trailing, onTap, etc.
Add other widgets also like subtitle, selected, etc.
ankit_kumar_
android
Flutter
Flutter-widgets
Dart
Flutter
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n14 Jun, 2022"
},
{
"code": null,
"e": 218,
"s": 52,
"text": "ListTile widget is used to populate a ListView in Flutter. It contains title as well as leading or trailing icons. Let’s understand this with the help of an example."
},
{
"code": null,
"e": 694,
"s": 218,
"text": "ListTile({Key key, \n Widget leading, \n Widget title, \n Widget subtitle, \n Widget trailing, \n \nbool isThreeLine: false, \nbool dense, \nVisualDensity visualDensity, \nShapeBorder shape, \nEdgeInsetsGeometry contentPadding, \n\nbool enabled: true, \nGestureTapCallback onTap, \nGestureLongPressCallback onLongPress, \nMouseCursor mouseCursor, \n\nbool selected: false, \nColor focusColor, \nColor hoverColor, \nFocusNode focusNode, \nbool autofocus: false})"
},
{
"code": null,
"e": 828,
"s": 694,
"text": "autofocus: This property takes in a boolean as the object to decide whether this widget will be selected on the initial focus or not."
},
{
"code": null,
"e": 923,
"s": 828,
"text": "contentPadding: By taking EdgeInsetsGeometry as the object this property controls the padding."
},
{
"code": null,
"e": 1060,
"s": 923,
"text": "dense: This property decides whether the ListTile will be a part of a vertically dense list or not by taking in a boolean as the object."
},
{
"code": null,
"e": 1177,
"s": 1060,
"text": "enable: This property controls whether the ListTile will be interactive or not by taking in a boolean as the object."
},
{
"code": null,
"e": 1298,
"s": 1177,
"text": "focusColor: This property holds Color class as the object to control the color of the widget at the time of input focus."
},
{
"code": null,
"e": 1353,
"s": 1298,
"text": "focusNode: This property provides an additional node."
},
{
"code": null,
"e": 1468,
"s": 1353,
"text": "hoverColor: This property takes in Color class as the object to decide the color of the tile at the time of hover."
},
{
"code": null,
"e": 1547,
"s": 1468,
"text": "isThreeLine: whether this list item should display three lines of text or not."
},
{
"code": null,
"e": 1588,
"s": 1547,
"text": "leading: leading widget of the ListTile."
},
{
"code": null,
"e": 1737,
"s": 1588,
"text": "mouseCursor: The mouseCursor property holds MouseCursor class as the object to decide the cursor for the mouse pointer at the time of pointer event."
},
{
"code": null,
"e": 1808,
"s": 1737,
"text": "onLongPress: This holds GestureLongPressCallback typedef as the object"
},
{
"code": null,
"e": 1868,
"s": 1808,
"text": "onTap: function to be called when the list tile is pressed."
},
{
"code": null,
"e": 1998,
"s": 1868,
"text": "selected: This property holds a boolean as the object. If set to true then the text and icon will be painted with the same color."
},
{
"code": null,
"e": 2098,
"s": 1998,
"text": "selectedTileColor: This property controls the background color of the ListTile when it is selected."
},
{
"code": null,
"e": 2139,
"s": 2098,
"text": "shape: the shape of the title’s InkWell."
},
{
"code": null,
"e": 2195,
"s": 2139,
"text": "subtitle: additional content displayed below the title."
},
{
"code": null,
"e": 2331,
"s": 2195,
"text": "titleColor: This property defines the background color of the ListTile when it is not selected, by taking in Color class as the object."
},
{
"code": null,
"e": 2375,
"s": 2331,
"text": "tile: title to be given to ListTile widget."
},
{
"code": null,
"e": 2418,
"s": 2375,
"text": "trailing: trailing widget of the ListTile."
},
{
"code": null,
"e": 2549,
"s": 2418,
"text": "visualDensity. This property takes in VisualDensity class as the object. It defines the compactness in the layout of the ListTile."
},
{
"code": null,
"e": 2558,
"s": 2549,
"text": "Example:"
},
{
"code": null,
"e": 2578,
"s": 2558,
"text": "The main.dart file."
},
{
"code": null,
"e": 2583,
"s": 2578,
"text": "Dart"
},
{
"code": "import 'package:flutter/material.dart'; void main() { runApp(const MyApp());} // Classclass MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); // This widget is//the root of your application. @override Widget build(BuildContext context) { return MaterialApp( title: 'ListTile', theme: ThemeData( primarySwatch: Colors.blue, ), home: const MyHomePage(), debugShowCheckedModeBanner: false, ); }} // Classclass MyHomePage extends StatefulWidget { const MyHomePage({Key? key}) : super(key: key); @override // ignore: library_private_types_in_public_api _MyHomePageState createState() => _MyHomePageState();} class _MyHomePageState extends State<MyHomePage> { String txt = ''; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('GeeksforGeeks'), backgroundColor: Colors.green, ), backgroundColor: Colors.grey[100], body: Column( children: <Widget>[ Padding( padding: const EdgeInsets.all(8.0), child: Container( color: Colors.blue[50], child: ListTile( leading: const Icon(Icons.add), title: const Text( 'GFG title', textScaleFactor: 1.5, ), trailing: const Icon(Icons.done), subtitle: const Text('This is subtitle'), selected: true, onTap: () { setState(() { txt = 'List Tile pressed'; }); }, ), ), ), Text( txt, textScaleFactor: 2, ) ], ), ); }}",
"e": 4346,
"s": 2583,
"text": null
},
{
"code": null,
"e": 4354,
"s": 4346,
"text": "Output:"
},
{
"code": null,
"e": 4394,
"s": 4354,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 4632,
"s": 4394,
"text": "const ListTile(\n leading: Icon(Icons.add),\n title: Text(\n 'GFG title',\n textScaleFactor: 1.5,\n ),\n trailing: Icon(Icons.done),\n ),"
},
{
"code": null,
"e": 4678,
"s": 4632,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 4718,
"s": 4678,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 5040,
"s": 4718,
"text": "const ListTile(\n leading: Icon(Icons.add),\n title: Text(\n 'GFG title',\n textScaleFactor: 1.5,\n ),\n trailing: Icon(Icons.done),\n subtitle: Text('This is subtitle'),\n selected: true,\n ),"
},
{
"code": null,
"e": 5086,
"s": 5040,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 5126,
"s": 5086,
"text": "If the properties are defined as below:"
},
{
"code": null,
"e": 5692,
"s": 5126,
"text": "ListTile(\n leading: const Icon(Icons.add),\n title: const Text(\n 'GFG title',\n textScaleFactor: 1.5,\n ),\n trailing: const Icon(Icons.done),\n subtitle: const Text('This is subtitle'),\n selected: true,\n onTap: () {\n setState(() {\n txt = 'List Tile pressed';\n });\n },\n ),\n // when user tap the list tile then below output will be shown."
},
{
"code": null,
"e": 5738,
"s": 5692,
"text": "The following design changes can be observed:"
},
{
"code": null,
"e": 5758,
"s": 5738,
"text": "Output explanation:"
},
{
"code": null,
"e": 5818,
"s": 5758,
"text": "Create a ListTile widget and wrap it with Container widget."
},
{
"code": null,
"e": 5884,
"s": 5818,
"text": "After that, give ListTile a title, leading, trailing, onTap, etc."
},
{
"code": null,
"e": 5937,
"s": 5884,
"text": "Add other widgets also like subtitle, selected, etc."
},
{
"code": null,
"e": 5950,
"s": 5937,
"text": "ankit_kumar_"
},
{
"code": null,
"e": 5958,
"s": 5950,
"text": "android"
},
{
"code": null,
"e": 5966,
"s": 5958,
"text": "Flutter"
},
{
"code": null,
"e": 5982,
"s": 5966,
"text": "Flutter-widgets"
},
{
"code": null,
"e": 5987,
"s": 5982,
"text": "Dart"
},
{
"code": null,
"e": 5995,
"s": 5987,
"text": "Flutter"
}
] |
Python – Itertools Combinations() function | 22 Feb, 2020
Itertool is a module of Python which is used to creation of iterators which helps us in efficient looping in terms of space as well as time. This module helps us to solve complex problems easily with the help of different sub-functions of itertools. The different sub-functions are divided into 3 subgroups which are:-
Infinite Iterators
Iterators terminating on the shortest input sequence
Combinatoric Generators
Note: For more information, refer to Python Itertools
Itertools.combinations() falls under the third subcategory called “Combinatoric Generators”. Combinatoric Generators are those iterators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products
As understood by name combinations is refers to a sequence or set of numbers or letters used in the iterator. Similarly itertools.combinations() provides us with all the possible tuples a sequence or set of numbers or letters used in the iterator and the elements are assumed to be unique on the basis of there positions which are distinct for all elements. All these combinations are emitted in lexicographical order. This function takes ‘r’ as input here ‘r’ represents the size of different combinations that are possible. All the combinations emitted are of length ‘r’ and ‘r’ is a necessary argument here.
Syntax:
combinations(iterator, r)
Example 1:-
# Combinations Of string "GeEKS" OF SIZE 3. from itertools import combinations letters ="GeEKS" # size of combination is set to 3a = combinations(letters, 3) y = [' '.join(i) for i in a] print(y)
Output:-
['G e E', 'G e K', 'G e S', 'G E K', 'G E S', 'G K S', 'e E K', 'e E S', 'e K S', 'E K S']
Example 2:-
from itertools import combinations print ("All the combination of list in sorted order(without replacement) is:") print(list(combinations(['A', 2], 2))) print() print ("All the combination of string in sorted order(without replacement) is:") print(list(combinations('AB', 2))) print() print ("All the combination of list in sorted order(without replacement) is:") print(list(combinations(range(2), 1)))
Output :-
All the combination of list in sorted order(without replacement) is:
[('A', 2)]
All the combination of string in sorted order(without replacement) is:
[('A', 'B')]
All the combination of list in sorted order(without replacement) is:
[(0,), (1,)]
Python-itertools
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
Python String | replace()
How to Install PIP on Windows ?
*args and **kwargs in Python
Python Classes and Objects
Iterate over a list in Python
Python OOPs Concepts | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n22 Feb, 2020"
},
{
"code": null,
"e": 372,
"s": 53,
"text": "Itertool is a module of Python which is used to creation of iterators which helps us in efficient looping in terms of space as well as time. This module helps us to solve complex problems easily with the help of different sub-functions of itertools. The different sub-functions are divided into 3 subgroups which are:-"
},
{
"code": null,
"e": 391,
"s": 372,
"text": "Infinite Iterators"
},
{
"code": null,
"e": 444,
"s": 391,
"text": "Iterators terminating on the shortest input sequence"
},
{
"code": null,
"e": 468,
"s": 444,
"text": "Combinatoric Generators"
},
{
"code": null,
"e": 522,
"s": 468,
"text": "Note: For more information, refer to Python Itertools"
},
{
"code": null,
"e": 769,
"s": 522,
"text": "Itertools.combinations() falls under the third subcategory called “Combinatoric Generators”. Combinatoric Generators are those iterators that are used to simplify combinatorial constructs such as permutations, combinations, and Cartesian products"
},
{
"code": null,
"e": 1380,
"s": 769,
"text": "As understood by name combinations is refers to a sequence or set of numbers or letters used in the iterator. Similarly itertools.combinations() provides us with all the possible tuples a sequence or set of numbers or letters used in the iterator and the elements are assumed to be unique on the basis of there positions which are distinct for all elements. All these combinations are emitted in lexicographical order. This function takes ‘r’ as input here ‘r’ represents the size of different combinations that are possible. All the combinations emitted are of length ‘r’ and ‘r’ is a necessary argument here."
},
{
"code": null,
"e": 1388,
"s": 1380,
"text": "Syntax:"
},
{
"code": null,
"e": 1414,
"s": 1388,
"text": "combinations(iterator, r)"
},
{
"code": null,
"e": 1426,
"s": 1414,
"text": "Example 1:-"
},
{
"code": "# Combinations Of string \"GeEKS\" OF SIZE 3. from itertools import combinations letters =\"GeEKS\" # size of combination is set to 3a = combinations(letters, 3) y = [' '.join(i) for i in a] print(y)",
"e": 1628,
"s": 1426,
"text": null
},
{
"code": null,
"e": 1637,
"s": 1628,
"text": "Output:-"
},
{
"code": null,
"e": 1729,
"s": 1637,
"text": "['G e E', 'G e K', 'G e S', 'G E K', 'G E S', 'G K S', 'e E K', 'e E S', 'e K S', 'E K S']\n"
},
{
"code": null,
"e": 1741,
"s": 1729,
"text": "Example 2:-"
},
{
"code": "from itertools import combinations print (\"All the combination of list in sorted order(without replacement) is:\") print(list(combinations(['A', 2], 2))) print() print (\"All the combination of string in sorted order(without replacement) is:\") print(list(combinations('AB', 2))) print() print (\"All the combination of list in sorted order(without replacement) is:\") print(list(combinations(range(2), 1))) ",
"e": 2172,
"s": 1741,
"text": null
},
{
"code": null,
"e": 2182,
"s": 2172,
"text": "Output :-"
},
{
"code": null,
"e": 2431,
"s": 2182,
"text": "All the combination of list in sorted order(without replacement) is:\n[('A', 2)]\n\nAll the combination of string in sorted order(without replacement) is:\n[('A', 'B')]\n\nAll the combination of list in sorted order(without replacement) is:\n[(0,), (1,)]\n"
},
{
"code": null,
"e": 2448,
"s": 2431,
"text": "Python-itertools"
},
{
"code": null,
"e": 2455,
"s": 2448,
"text": "Python"
},
{
"code": null,
"e": 2553,
"s": 2455,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2571,
"s": 2553,
"text": "Python Dictionary"
},
{
"code": null,
"e": 2613,
"s": 2571,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 2635,
"s": 2613,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 2670,
"s": 2635,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 2696,
"s": 2670,
"text": "Python String | replace()"
},
{
"code": null,
"e": 2728,
"s": 2696,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 2757,
"s": 2728,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 2784,
"s": 2757,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 2814,
"s": 2784,
"text": "Iterate over a list in Python"
}
] |
Merge two Pandas DataFrames with complex conditions | 07 Apr, 2021
In this article, we let’s discuss how to merge two Pandas Dataframe with some complex conditions. Dataframes in Pandas can be merged using pandas.merge() method.
Syntax:
pandas.merge(parameters)
Returns : A DataFrame of the two merged objects.
While working on datasets there may be a need to merge two data frames with some complex conditions, below are some examples of merging two data frames with some complex conditions.
Example 1 :
Merging two data frames with merge() function with the parameters as the two data frames.
Python3
# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'ID': [1, 2, 3, 4], 'Name': ['John', 'Tom', 'Simon', 'Jose']}) df2 = pd.DataFrame({'ID': [1, 2, 3, 5], 'Class': ['Second', 'Third', 'Fifth', 'Fourth']}) # merging df1 and df2 with merge functiondf = pd.merge(df1, df2)print(df)
Output :
Example 2 :
Merging two data frames with merge() function on some specified column name of the data frames.
Python3
# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name': ['John', 'Tom', 'Simon', 'Jose'], 'Age': [5, 6, 4, 5]}) df2 = pd.DataFrame({'Name': ['John', 'Tom', 'Jose'], 'Class': ['Second', 'Third', 'Fifth']}) # merging df1 and df2 with merge function # with the common column as Namedf = pd.merge(df1, df2, on='Name')print(df)
Output :
Example 3 :
Merging two data frames with all the values in the first data frame and NaN for the not matched values from the second data frame. The same can be done to merge with all values of the second data frame what we have to do is just give the position of the data frame when merging as left or right.
Python3
# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name': ['John', 'Tom', 'Simon', 'Jose'], 'Age': [5, 6, 4, 5]}) df2 = pd.DataFrame({'Name': ['John', 'Tom', 'Jose'], 'Class': ['Second', 'Third', 'Fifth']}) # merging df1 and df2 with merge function # with the common column as Namedf = pd.merge(df1, df2, on='Name', how="left")print(df)
Output :
Example 4 :
Merging two data frames with all the values of both the data frames using merge function with an outer join. The same can be done do join two data frames with inner join as well.
Python3
# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Jose'], 'Age':[5, 6, 4, 5]}) df2 = pd.DataFrame({'Name':['John', 'Tom', 'Philip'], 'Class':['Second', 'Third', 'Fifth']}) # merging df1 and df2 with merge function # with the records of both the dataframesdf = pd.merge(df1, df2, how = "outer")print(df)
Output :
Example 5 :
Merging data frames with the indicator value to see which data frame has that particular record.
Python3
# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Jose'], 'Age':[5, 6, 4, 5]}) df2 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Tom'], 'Class':['Second', 'Third', 'Fifth', 'Fourth']}) # merging df1 and df2 with merge function # with the records of both the dataframesdf = pd.merge(df1, df2, how = 'left', indicator = True)print(df)
Output :
Example 6 :
Merging data frames with the one-to-many relation in the two data frames. The same can be done to merge with many-to-many, one-to-one, and one-to-many type of relationship.
Python3
# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Jose'], 'Age':[5, 6, 4, 5]}) df2 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Tom'], 'Class':['Second', 'Third', 'Fifth', 'Fourth']}) # merging df1 and df2 with merge function with # the one to many relations from both the dataframesdf = pd.merge(df1, df2, validate = 'one_to_many')print(df)
Output :
Picked
Python pandas-dataFrame
Python-pandas
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Apr, 2021"
},
{
"code": null,
"e": 190,
"s": 28,
"text": "In this article, we let’s discuss how to merge two Pandas Dataframe with some complex conditions. Dataframes in Pandas can be merged using pandas.merge() method."
},
{
"code": null,
"e": 198,
"s": 190,
"text": "Syntax:"
},
{
"code": null,
"e": 223,
"s": 198,
"text": "pandas.merge(parameters)"
},
{
"code": null,
"e": 272,
"s": 223,
"text": "Returns : A DataFrame of the two merged objects."
},
{
"code": null,
"e": 454,
"s": 272,
"text": "While working on datasets there may be a need to merge two data frames with some complex conditions, below are some examples of merging two data frames with some complex conditions."
},
{
"code": null,
"e": 466,
"s": 454,
"text": "Example 1 :"
},
{
"code": null,
"e": 557,
"s": 466,
"text": "Merging two data frames with merge() function with the parameters as the two data frames. "
},
{
"code": null,
"e": 565,
"s": 557,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'ID': [1, 2, 3, 4], 'Name': ['John', 'Tom', 'Simon', 'Jose']}) df2 = pd.DataFrame({'ID': [1, 2, 3, 5], 'Class': ['Second', 'Third', 'Fifth', 'Fourth']}) # merging df1 and df2 with merge functiondf = pd.merge(df1, df2)print(df)",
"e": 920,
"s": 565,
"text": null
},
{
"code": null,
"e": 930,
"s": 920,
"text": "Output : "
},
{
"code": null,
"e": 942,
"s": 930,
"text": "Example 2 :"
},
{
"code": null,
"e": 1038,
"s": 942,
"text": "Merging two data frames with merge() function on some specified column name of the data frames."
},
{
"code": null,
"e": 1046,
"s": 1038,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name': ['John', 'Tom', 'Simon', 'Jose'], 'Age': [5, 6, 4, 5]}) df2 = pd.DataFrame({'Name': ['John', 'Tom', 'Jose'], 'Class': ['Second', 'Third', 'Fifth']}) # merging df1 and df2 with merge function # with the common column as Namedf = pd.merge(df1, df2, on='Name')print(df)",
"e": 1447,
"s": 1046,
"text": null
},
{
"code": null,
"e": 1457,
"s": 1447,
"text": "Output : "
},
{
"code": null,
"e": 1469,
"s": 1457,
"text": "Example 3 :"
},
{
"code": null,
"e": 1765,
"s": 1469,
"text": "Merging two data frames with all the values in the first data frame and NaN for the not matched values from the second data frame. The same can be done to merge with all values of the second data frame what we have to do is just give the position of the data frame when merging as left or right."
},
{
"code": null,
"e": 1773,
"s": 1765,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name': ['John', 'Tom', 'Simon', 'Jose'], 'Age': [5, 6, 4, 5]}) df2 = pd.DataFrame({'Name': ['John', 'Tom', 'Jose'], 'Class': ['Second', 'Third', 'Fifth']}) # merging df1 and df2 with merge function # with the common column as Namedf = pd.merge(df1, df2, on='Name', how=\"left\")print(df)",
"e": 2187,
"s": 1773,
"text": null
},
{
"code": null,
"e": 2197,
"s": 2187,
"text": "Output : "
},
{
"code": null,
"e": 2209,
"s": 2197,
"text": "Example 4 :"
},
{
"code": null,
"e": 2388,
"s": 2209,
"text": "Merging two data frames with all the values of both the data frames using merge function with an outer join. The same can be done do join two data frames with inner join as well."
},
{
"code": null,
"e": 2396,
"s": 2388,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Jose'], 'Age':[5, 6, 4, 5]}) df2 = pd.DataFrame({'Name':['John', 'Tom', 'Philip'], 'Class':['Second', 'Third', 'Fifth']}) # merging df1 and df2 with merge function # with the records of both the dataframesdf = pd.merge(df1, df2, how = \"outer\")print(df)",
"e": 2808,
"s": 2396,
"text": null
},
{
"code": null,
"e": 2818,
"s": 2808,
"text": "Output : "
},
{
"code": null,
"e": 2831,
"s": 2818,
"text": "Example 5 : "
},
{
"code": null,
"e": 2928,
"s": 2831,
"text": "Merging data frames with the indicator value to see which data frame has that particular record."
},
{
"code": null,
"e": 2936,
"s": 2928,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Jose'], 'Age':[5, 6, 4, 5]}) df2 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Tom'], 'Class':['Second', 'Third', 'Fifth', 'Fourth']}) # merging df1 and df2 with merge function # with the records of both the dataframesdf = pd.merge(df1, df2, how = 'left', indicator = True)print(df)",
"e": 3381,
"s": 2936,
"text": null
},
{
"code": null,
"e": 3391,
"s": 3381,
"text": "Output : "
},
{
"code": null,
"e": 3403,
"s": 3391,
"text": "Example 6 :"
},
{
"code": null,
"e": 3576,
"s": 3403,
"text": "Merging data frames with the one-to-many relation in the two data frames. The same can be done to merge with many-to-many, one-to-one, and one-to-many type of relationship."
},
{
"code": null,
"e": 3584,
"s": 3576,
"text": "Python3"
},
{
"code": "# importing pandas as pdimport pandas as pd # creating dataframesdf1 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Jose'], 'Age':[5, 6, 4, 5]}) df2 = pd.DataFrame({'Name':['John', 'Tom', 'Simon', 'Tom'], 'Class':['Second', 'Third', 'Fifth', 'Fourth']}) # merging df1 and df2 with merge function with # the one to many relations from both the dataframesdf = pd.merge(df1, df2, validate = 'one_to_many')print(df)",
"e": 4039,
"s": 3584,
"text": null
},
{
"code": null,
"e": 4049,
"s": 4039,
"text": "Output : "
},
{
"code": null,
"e": 4056,
"s": 4049,
"text": "Picked"
},
{
"code": null,
"e": 4080,
"s": 4056,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 4094,
"s": 4080,
"text": "Python-pandas"
},
{
"code": null,
"e": 4101,
"s": 4094,
"text": "Python"
}
] |
Software Engineering | Iterative Waterfall Model | 29 Sep, 2021
In a practical software development project, the classical waterfall model is hard to use. So, the Iterative waterfall model can be thought of as incorporating the necessary changes to the classical waterfall model to make it usable in practical software development projects. It is almost the same as the classical waterfall model except some changes are made to increase the efficiency of the software development.
The iterative waterfall model provides feedback paths from every phase to its preceding phases, which is the main difference from the classical waterfall model.
Feedback paths introduced by the iterative waterfall model are shown in the figure below.
When errors are detected at some later phase, these feedback paths allow correcting errors committed by programmers during some phase. The feedback paths allow the phase to be reworked in which errors are committed and these changes are reflected in the later phases. But, there is no feedback path to the stage – feasibility study, because once a project has been taken, does not give up the project easily.
It is good to detect errors in the same phase in which they are committed. It reduces the effort and time required to correct the errors.
Phase Containment of Errors :The principle of detecting errors as close to their points of commitment as possible is known as Phase containment of errors.
Advantages of Iterative Waterfall Model :
Feedback Path –In the classical waterfall model, there are no feedback paths, so there is no mechanism for error correction. But in the iterative waterfall model feedback path from one phase to its preceding phase allows correcting the errors that are committed and these changes are reflected in the later phases.
Simple –Iterative waterfall model is very simple to understand and use. That’s why it is one of the most widely used software development models.
Cost-Effective –It is highly cost-effective to change the plan or requirements in the model. Moreover, it is best suited for agile organizations.
Well-organized –In this model, less time is consumed on documenting and the team can spend more time on development and designing.
Drawbacks of Iterative Waterfall Model :
Difficult to incorporate change requests –The major drawback of the iterative waterfall model is that all the requirements must be clearly stated before starting the development phase. Customers may change requirements after some time but the iterative waterfall model does not leave any scope to incorporate change requests that are made after the development phase starts.
Incremental delivery not supported –In the iterative waterfall model, the full software is completely developed and tested before delivery to the customer. There is no scope for any intermediate delivery. So, customers have to wait a long for getting the software.
Overlapping of phases not supported –Iterative waterfall model assumes that one phase can start after completion of the previous phase, But in real projects, phases may overlap to reduce the effort and time needed to complete the project.
Risk handling not supported –Projects may suffer from various types of risks. But, the Iterative waterfall model has no mechanism for risk handling.
Limited customer interactions –Customer interaction occurs at the start of the project at the time of requirement gathering and at project completion at the time of software delivery. These fewer interactions with the customers may lead to many problems as the finally developed software may differ from the customers’ actual requirements.
prakhyatsinghal08
Software Engineering
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Types of Software Testing
Differences between Black Box Testing vs White Box Testing
Functional vs Non Functional Requirements
Differences between Verification and Validation
Unit Testing | Software Testing
Software Testing | Basics
System Testing
Software Requirement Specification (SRS) Format
Difference between Spring and Spring Boot
Software Testing Life Cycle (STLC) | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n29 Sep, 2021"
},
{
"code": null,
"e": 470,
"s": 52,
"text": "In a practical software development project, the classical waterfall model is hard to use. So, the Iterative waterfall model can be thought of as incorporating the necessary changes to the classical waterfall model to make it usable in practical software development projects. It is almost the same as the classical waterfall model except some changes are made to increase the efficiency of the software development. "
},
{
"code": null,
"e": 632,
"s": 470,
"text": "The iterative waterfall model provides feedback paths from every phase to its preceding phases, which is the main difference from the classical waterfall model. "
},
{
"code": null,
"e": 724,
"s": 632,
"text": "Feedback paths introduced by the iterative waterfall model are shown in the figure below. "
},
{
"code": null,
"e": 1134,
"s": 724,
"text": "When errors are detected at some later phase, these feedback paths allow correcting errors committed by programmers during some phase. The feedback paths allow the phase to be reworked in which errors are committed and these changes are reflected in the later phases. But, there is no feedback path to the stage – feasibility study, because once a project has been taken, does not give up the project easily. "
},
{
"code": null,
"e": 1273,
"s": 1134,
"text": "It is good to detect errors in the same phase in which they are committed. It reduces the effort and time required to correct the errors. "
},
{
"code": null,
"e": 1429,
"s": 1273,
"text": "Phase Containment of Errors :The principle of detecting errors as close to their points of commitment as possible is known as Phase containment of errors. "
},
{
"code": null,
"e": 1472,
"s": 1429,
"text": " Advantages of Iterative Waterfall Model :"
},
{
"code": null,
"e": 1787,
"s": 1472,
"text": "Feedback Path –In the classical waterfall model, there are no feedback paths, so there is no mechanism for error correction. But in the iterative waterfall model feedback path from one phase to its preceding phase allows correcting the errors that are committed and these changes are reflected in the later phases."
},
{
"code": null,
"e": 1933,
"s": 1787,
"text": "Simple –Iterative waterfall model is very simple to understand and use. That’s why it is one of the most widely used software development models."
},
{
"code": null,
"e": 2079,
"s": 1933,
"text": "Cost-Effective –It is highly cost-effective to change the plan or requirements in the model. Moreover, it is best suited for agile organizations."
},
{
"code": null,
"e": 2211,
"s": 2079,
"text": "Well-organized –In this model, less time is consumed on documenting and the team can spend more time on development and designing. "
},
{
"code": null,
"e": 2252,
"s": 2211,
"text": "Drawbacks of Iterative Waterfall Model :"
},
{
"code": null,
"e": 2629,
"s": 2252,
"text": "Difficult to incorporate change requests –The major drawback of the iterative waterfall model is that all the requirements must be clearly stated before starting the development phase. Customers may change requirements after some time but the iterative waterfall model does not leave any scope to incorporate change requests that are made after the development phase starts. "
},
{
"code": null,
"e": 2896,
"s": 2629,
"text": "Incremental delivery not supported –In the iterative waterfall model, the full software is completely developed and tested before delivery to the customer. There is no scope for any intermediate delivery. So, customers have to wait a long for getting the software. "
},
{
"code": null,
"e": 3137,
"s": 2896,
"text": "Overlapping of phases not supported –Iterative waterfall model assumes that one phase can start after completion of the previous phase, But in real projects, phases may overlap to reduce the effort and time needed to complete the project. "
},
{
"code": null,
"e": 3288,
"s": 3137,
"text": "Risk handling not supported –Projects may suffer from various types of risks. But, the Iterative waterfall model has no mechanism for risk handling. "
},
{
"code": null,
"e": 3629,
"s": 3288,
"text": "Limited customer interactions –Customer interaction occurs at the start of the project at the time of requirement gathering and at project completion at the time of software delivery. These fewer interactions with the customers may lead to many problems as the finally developed software may differ from the customers’ actual requirements. "
},
{
"code": null,
"e": 3647,
"s": 3629,
"text": "prakhyatsinghal08"
},
{
"code": null,
"e": 3668,
"s": 3647,
"text": "Software Engineering"
},
{
"code": null,
"e": 3766,
"s": 3668,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3792,
"s": 3766,
"text": "Types of Software Testing"
},
{
"code": null,
"e": 3851,
"s": 3792,
"text": "Differences between Black Box Testing vs White Box Testing"
},
{
"code": null,
"e": 3893,
"s": 3851,
"text": "Functional vs Non Functional Requirements"
},
{
"code": null,
"e": 3941,
"s": 3893,
"text": "Differences between Verification and Validation"
},
{
"code": null,
"e": 3973,
"s": 3941,
"text": "Unit Testing | Software Testing"
},
{
"code": null,
"e": 3999,
"s": 3973,
"text": "Software Testing | Basics"
},
{
"code": null,
"e": 4014,
"s": 3999,
"text": "System Testing"
},
{
"code": null,
"e": 4062,
"s": 4014,
"text": "Software Requirement Specification (SRS) Format"
},
{
"code": null,
"e": 4104,
"s": 4062,
"text": "Difference between Spring and Spring Boot"
}
] |
MongoDB $concat Operator | 01 Aug, 2020
MongoDB provides different types of string expression operators that are used in the aggregation pipeline stages $concat operator is one of them. This operator is used to concatenate two or more strings and returns a single string.
Syntax:
{ $concat: [ <expression1>, <expression2>, ... ] }
Here, the arguments passed in this operator can be any valid expression until they resolve to strings.
If the entered argument resolves to null, then this operator will return null.
If the entered argument refers to a missing field, then this operator will return null.
Examples:
In the following examples, we are working with:
Database: GeeksforGeeks
Collection: employee
Document: three documents that contain the details of the employees in the form of field-value pairs.
Concatenating strings using $concat operator:
In this example, we are finding the department of the employees. Here, we concatenate “My department is:” string with the value of the department field.
db.employee.aggregate([
... {$project: {"name.first": 1, _id: 0, dept:
... {$concat: ["My department is: ", "$department"]}}}])
Concatenating strings in the embedded documents using $concat operator:
In this example, we are going to find the full name of the employees by concatenating the values of the name.first, name.middle, and name.last fields.
db.employee.aggregate([
... {$project: {fullname:
... {$concat: ["$name.first", "$name.middle", "$name.last"]}}}])
MongoDB-operators
MongoDB
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to connect MongoDB with ReactJS ?
MongoDB - limit() Method
Create user and add role in MongoDB
MongoDB - sort() Method
MongoDB - FindOne() Method
Export data from MongoDB
MongoDB updateOne() Method - db.Collection.updateOne()
MongoDB - Compound Indexes
MongoDB - Regex
MongoDB updateMany() Method - db.Collection.updateMany() | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n01 Aug, 2020"
},
{
"code": null,
"e": 260,
"s": 28,
"text": "MongoDB provides different types of string expression operators that are used in the aggregation pipeline stages $concat operator is one of them. This operator is used to concatenate two or more strings and returns a single string."
},
{
"code": null,
"e": 269,
"s": 260,
"text": "Syntax: "
},
{
"code": null,
"e": 322,
"s": 269,
"text": "{ $concat: [ <expression1>, <expression2>, ... ] }\n\n"
},
{
"code": null,
"e": 425,
"s": 322,
"text": "Here, the arguments passed in this operator can be any valid expression until they resolve to strings."
},
{
"code": null,
"e": 504,
"s": 425,
"text": "If the entered argument resolves to null, then this operator will return null."
},
{
"code": null,
"e": 592,
"s": 504,
"text": "If the entered argument refers to a missing field, then this operator will return null."
},
{
"code": null,
"e": 602,
"s": 592,
"text": "Examples:"
},
{
"code": null,
"e": 650,
"s": 602,
"text": "In the following examples, we are working with:"
},
{
"code": null,
"e": 674,
"s": 650,
"text": "Database: GeeksforGeeks"
},
{
"code": null,
"e": 695,
"s": 674,
"text": "Collection: employee"
},
{
"code": null,
"e": 797,
"s": 695,
"text": "Document: three documents that contain the details of the employees in the form of field-value pairs."
},
{
"code": null,
"e": 843,
"s": 797,
"text": "Concatenating strings using $concat operator:"
},
{
"code": null,
"e": 996,
"s": 843,
"text": "In this example, we are finding the department of the employees. Here, we concatenate “My department is:” string with the value of the department field."
},
{
"code": null,
"e": 1125,
"s": 996,
"text": "db.employee.aggregate([\n... {$project: {\"name.first\": 1, _id: 0, dept:\n... {$concat: [\"My department is: \", \"$department\"]}}}])\n"
},
{
"code": null,
"e": 1197,
"s": 1125,
"text": "Concatenating strings in the embedded documents using $concat operator:"
},
{
"code": null,
"e": 1349,
"s": 1197,
"text": "In this example, we are going to find the full name of the employees by concatenating the values of the name.first, name.middle, and name.last fields. "
},
{
"code": null,
"e": 1465,
"s": 1349,
"text": "db.employee.aggregate([\n... {$project: {fullname:\n... {$concat: [\"$name.first\", \"$name.middle\", \"$name.last\"]}}}])\n"
},
{
"code": null,
"e": 1483,
"s": 1465,
"text": "MongoDB-operators"
},
{
"code": null,
"e": 1491,
"s": 1483,
"text": "MongoDB"
},
{
"code": null,
"e": 1589,
"s": 1491,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1627,
"s": 1589,
"text": "How to connect MongoDB with ReactJS ?"
},
{
"code": null,
"e": 1652,
"s": 1627,
"text": "MongoDB - limit() Method"
},
{
"code": null,
"e": 1688,
"s": 1652,
"text": "Create user and add role in MongoDB"
},
{
"code": null,
"e": 1712,
"s": 1688,
"text": "MongoDB - sort() Method"
},
{
"code": null,
"e": 1739,
"s": 1712,
"text": "MongoDB - FindOne() Method"
},
{
"code": null,
"e": 1764,
"s": 1739,
"text": "Export data from MongoDB"
},
{
"code": null,
"e": 1819,
"s": 1764,
"text": "MongoDB updateOne() Method - db.Collection.updateOne()"
},
{
"code": null,
"e": 1846,
"s": 1819,
"text": "MongoDB - Compound Indexes"
},
{
"code": null,
"e": 1862,
"s": 1846,
"text": "MongoDB - Regex"
}
] |
How to encrypt and decrypt passwords using PHP ? | 31 Jul, 2021
The best way to encrypt and decrypt passwords is to use a standard library in PHP because the method of properly encrypting and decrypting passwords from scratch is complex and involves multiple possibilities of security vulnerabilities. Using the standard library ensures that the hashing implementation is verified and trusted.
Note: This uses the PHP Password API available in version 5.5.0 and above.
Encryption of the password: To generate a hash from the string, we use the password_hash() function.
Syntax:
string password_hash(string $password,
mixed $algo, [array $options])
The password_hash() function creates a new password hash of the string using one of the available hashing algorithm. It returns the hash that is currently 60 character long, however, as new and stronger algorithms will be added to PHP, the length of the hash may increase. It is therefore recommended to allocate 255 characters for the column that may be used to store the hash in database.
The following algorithms are currently supported when using this function:
PASSWORD_DEFAULT
PASSWORD_BCRYPT
PASSWORD_ARGON2I
PASSWORD_ARGON2ID
Additional options can be passed to this function can be used to set the cost of encryption, the salt to be used during hashing, etc in the $options array.
The below example shows the method of using the password_hash() method:
Example:
php
<?php // The plain text password to be hashed $plaintext_password = "Password@123"; // The hash of the password that // can be stored in the database $hash = password_hash($plaintext_password, PASSWORD_DEFAULT); // Print the generated hash echo "Generated hash: ".$hash;?>
Output:
Generated hash: $2y$10$7rLSvRVyTQORapkDOqmkhetjF6H9lJHngr4hJMSM2lHObJbW5EQh6
Decryption of the password: To decrypt a password hash and retrieve the original string, we use the password_verify() function.
Syntax:
bool password_verify(string $password, string $hash)
The password_verify() function verifies that the given hash matches the given password, generated by the password_hash() function. It returns true if the password and hash match, or false otherwise.
php
<?php // Plaintext password entered by the user $plaintext_password = "Password@123"; // The hashed password retrieved from database $hash = "$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm"; // Verify the hash against the password entered $verify = password_verify($plaintext_password, $hash); // Print the result depending if they match if ($verify) { echo 'Password Verified!'; } else { echo 'Incorrect Password!'; }?>
Output:
Password Verified!
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.
PHP-Misc
Picked
PHP
PHP Programs
Web Technologies
Web technologies Questions
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to convert array to string in PHP ?
PHP | Converting string to Date and DateTime
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
Removing Array Element and Re-Indexing in PHP
How to convert array to string in PHP ?
How to call PHP function on the click of a Button ?
How to get parameters from a URL string in PHP?
Split a comma delimited string into an array in PHP
How to pass JavaScript variables to PHP ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n31 Jul, 2021"
},
{
"code": null,
"e": 358,
"s": 28,
"text": "The best way to encrypt and decrypt passwords is to use a standard library in PHP because the method of properly encrypting and decrypting passwords from scratch is complex and involves multiple possibilities of security vulnerabilities. Using the standard library ensures that the hashing implementation is verified and trusted."
},
{
"code": null,
"e": 433,
"s": 358,
"text": "Note: This uses the PHP Password API available in version 5.5.0 and above."
},
{
"code": null,
"e": 534,
"s": 433,
"text": "Encryption of the password: To generate a hash from the string, we use the password_hash() function."
},
{
"code": null,
"e": 542,
"s": 534,
"text": "Syntax:"
},
{
"code": null,
"e": 623,
"s": 542,
"text": "string password_hash(string $password, \n mixed $algo, [array $options])"
},
{
"code": null,
"e": 1014,
"s": 623,
"text": "The password_hash() function creates a new password hash of the string using one of the available hashing algorithm. It returns the hash that is currently 60 character long, however, as new and stronger algorithms will be added to PHP, the length of the hash may increase. It is therefore recommended to allocate 255 characters for the column that may be used to store the hash in database."
},
{
"code": null,
"e": 1089,
"s": 1014,
"text": "The following algorithms are currently supported when using this function:"
},
{
"code": null,
"e": 1106,
"s": 1089,
"text": "PASSWORD_DEFAULT"
},
{
"code": null,
"e": 1122,
"s": 1106,
"text": "PASSWORD_BCRYPT"
},
{
"code": null,
"e": 1139,
"s": 1122,
"text": "PASSWORD_ARGON2I"
},
{
"code": null,
"e": 1157,
"s": 1139,
"text": "PASSWORD_ARGON2ID"
},
{
"code": null,
"e": 1313,
"s": 1157,
"text": "Additional options can be passed to this function can be used to set the cost of encryption, the salt to be used during hashing, etc in the $options array."
},
{
"code": null,
"e": 1385,
"s": 1313,
"text": "The below example shows the method of using the password_hash() method:"
},
{
"code": null,
"e": 1394,
"s": 1385,
"text": "Example:"
},
{
"code": null,
"e": 1398,
"s": 1394,
"text": "php"
},
{
"code": "<?php // The plain text password to be hashed $plaintext_password = \"Password@123\"; // The hash of the password that // can be stored in the database $hash = password_hash($plaintext_password, PASSWORD_DEFAULT); // Print the generated hash echo \"Generated hash: \".$hash;?>",
"e": 1694,
"s": 1398,
"text": null
},
{
"code": null,
"e": 1702,
"s": 1694,
"text": "Output:"
},
{
"code": null,
"e": 1779,
"s": 1702,
"text": "Generated hash: $2y$10$7rLSvRVyTQORapkDOqmkhetjF6H9lJHngr4hJMSM2lHObJbW5EQh6"
},
{
"code": null,
"e": 1907,
"s": 1779,
"text": "Decryption of the password: To decrypt a password hash and retrieve the original string, we use the password_verify() function."
},
{
"code": null,
"e": 1915,
"s": 1907,
"text": "Syntax:"
},
{
"code": null,
"e": 1968,
"s": 1915,
"text": "bool password_verify(string $password, string $hash)"
},
{
"code": null,
"e": 2167,
"s": 1968,
"text": "The password_verify() function verifies that the given hash matches the given password, generated by the password_hash() function. It returns true if the password and hash match, or false otherwise."
},
{
"code": null,
"e": 2171,
"s": 2167,
"text": "php"
},
{
"code": "<?php // Plaintext password entered by the user $plaintext_password = \"Password@123\"; // The hashed password retrieved from database $hash = \"$2y$10$8sA2N5Sx/1zMQv2yrTDAaOFlbGWECrrgB68axL.hBb78NhQdyAqWm\"; // Verify the hash against the password entered $verify = password_verify($plaintext_password, $hash); // Print the result depending if they match if ($verify) { echo 'Password Verified!'; } else { echo 'Incorrect Password!'; }?>",
"e": 2634,
"s": 2171,
"text": null
},
{
"code": null,
"e": 2642,
"s": 2634,
"text": "Output:"
},
{
"code": null,
"e": 2661,
"s": 2642,
"text": "Password Verified!"
},
{
"code": null,
"e": 2830,
"s": 2661,
"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": 2839,
"s": 2830,
"text": "PHP-Misc"
},
{
"code": null,
"e": 2846,
"s": 2839,
"text": "Picked"
},
{
"code": null,
"e": 2850,
"s": 2846,
"text": "PHP"
},
{
"code": null,
"e": 2863,
"s": 2850,
"text": "PHP Programs"
},
{
"code": null,
"e": 2880,
"s": 2863,
"text": "Web Technologies"
},
{
"code": null,
"e": 2907,
"s": 2880,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 2911,
"s": 2907,
"text": "PHP"
},
{
"code": null,
"e": 3009,
"s": 2911,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 3049,
"s": 3009,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3094,
"s": 3049,
"text": "PHP | Converting string to Date and DateTime"
},
{
"code": null,
"e": 3142,
"s": 3094,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3194,
"s": 3142,
"text": "Split a comma delimited string into an array in PHP"
},
{
"code": null,
"e": 3240,
"s": 3194,
"text": "Removing Array Element and Re-Indexing in PHP"
},
{
"code": null,
"e": 3280,
"s": 3240,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 3332,
"s": 3280,
"text": "How to call PHP function on the click of a Button ?"
},
{
"code": null,
"e": 3380,
"s": 3332,
"text": "How to get parameters from a URL string in PHP?"
},
{
"code": null,
"e": 3432,
"s": 3380,
"text": "Split a comma delimited string into an array in PHP"
}
] |
How to validate an IP address using ReGex | 07 Jun, 2022
Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address.
Examples:
Input: str = “203.120.223.13” Output: Valid IPv4
Input: str = “000.12.234.23.23” Output: Invalid IP
Input: str = “2F33:12a0:3Ea0:0302” Output: Invalid IP
Input: str = “I.Am.not.an.ip” Output: Invalid IP
Approach:
Regex (Regular Expression) In C++ will be used to check the IP address.
Range Specifications Specifying a range of characters or literals is one of the simplest criteria used in a regex.
i) [a-z]
ii) [A-Za-z0-9]
In the above expression ([]) square brackets are used to specify the range.
The first expression will match exactly one lowercase character.
The second expression specifies the range containing one single uppercase character, one lowercase character, and a digit from 0 to 9.
Now to include a ‘.’ as part of an expression, we need to escape ‘.’ and this can be done as :
[\\.0-9]
The above expression indicates an ‘.’ and a digit in the range 0 to 9 as a regex.
regex_match() function is used to match the given pattern. This function returns true if the given expression matches the string. Otherwise, the function returns false.
Here is the implementation of the above approach.
C++
Python3
// C++ program to validate// IP address using Regex #include <bits/stdc++.h>using namespace std; // Function for Validating IPstring Validate_It(string IP){ // Regex expression for validating IPv4 regex ipv4("(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])"); // Regex expression for validating IPv6 regex ipv6("((([0-9a-fA-F]){1,4})\\:){7}([0-9a-fA-F]){1,4}"); // Checking if it is a valid IPv4 addresses if (regex_match(IP, ipv4)) return "Valid IPv4"; // Checking if it is a valid IPv6 addresses else if (regex_match(IP, ipv6)) return "Valid IPv6"; // Return Invalid return "Invalid IP";} // Driver Codeint main(){ // IP addresses to validate string IP = "257.120.223.13"; cout << Validate_It(IP) << endl; IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001"; cout << Validate_It(IP) << endl; IP = "2F33:12a0:3Ea0:0302"; cout << Validate_It(IP) << endl; return 0;}
# Python3 program to validate# IP address using Regeximport re # Function for Validating IP def Validate_It(IP): # Regex expression for validating IPv4 regex = "^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$" # Regex expression for validating IPv6 regex1 = "((([0-9a-fA-F]){1,4})\\:){7}"\ "([0-9a-fA-F]){1,4}" p = re.compile(regex) p1 = re.compile(regex1) # Checking if it is a valid IPv4 addresses if (re.search(p, IP)): return "Valid IPv4" # Checking if it is a valid IPv6 addresses elif (re.search(p1, IP)): return "Valid IPv6" # Return Invalid return "Invalid IP" # Driver Code # IP addresses to validateIP = "257.120.223.13"print(Validate_It(IP)) IP = "fffe:3465:efab:23fe:2235:6565:aaab:0001"print(Validate_It(IP)) IP = "2F33:12a0:3Ea0:0302"print(Validate_It(IP)) # This code is contributed by avanitrachhadiya2155
Invalid IP
Valid IPv6
Invalid IP
Time Complexity: O (N) Auxiliary Space: O (1)
abhishek_padghan
avanitrachhadiya2155
harendrakumar123
CPP-regex
IP Addressing
java-regular-expression
python-regex
regular-expression
Computer Networks
Searching
Strings
Searching
Strings
Computer Networks
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": 246,
"s": 28,
"text": "Given an IP address, the task is to validate this IP address with the help of Regex (Regular Expression) in C++ as a valid IPv4 address or IPv6 address. If the IP address is not valid then print an invalid IP address."
},
{
"code": null,
"e": 257,
"s": 246,
"text": "Examples: "
},
{
"code": null,
"e": 306,
"s": 257,
"text": "Input: str = “203.120.223.13” Output: Valid IPv4"
},
{
"code": null,
"e": 357,
"s": 306,
"text": "Input: str = “000.12.234.23.23” Output: Invalid IP"
},
{
"code": null,
"e": 411,
"s": 357,
"text": "Input: str = “2F33:12a0:3Ea0:0302” Output: Invalid IP"
},
{
"code": null,
"e": 461,
"s": 411,
"text": "Input: str = “I.Am.not.an.ip” Output: Invalid IP "
},
{
"code": null,
"e": 471,
"s": 461,
"text": "Approach:"
},
{
"code": null,
"e": 543,
"s": 471,
"text": "Regex (Regular Expression) In C++ will be used to check the IP address."
},
{
"code": null,
"e": 658,
"s": 543,
"text": "Range Specifications Specifying a range of characters or literals is one of the simplest criteria used in a regex."
},
{
"code": null,
"e": 683,
"s": 658,
"text": "i) [a-z]\nii) [A-Za-z0-9]"
},
{
"code": null,
"e": 759,
"s": 683,
"text": "In the above expression ([]) square brackets are used to specify the range."
},
{
"code": null,
"e": 824,
"s": 759,
"text": "The first expression will match exactly one lowercase character."
},
{
"code": null,
"e": 959,
"s": 824,
"text": "The second expression specifies the range containing one single uppercase character, one lowercase character, and a digit from 0 to 9."
},
{
"code": null,
"e": 1054,
"s": 959,
"text": "Now to include a ‘.’ as part of an expression, we need to escape ‘.’ and this can be done as :"
},
{
"code": null,
"e": 1063,
"s": 1054,
"text": "[\\\\.0-9]"
},
{
"code": null,
"e": 1145,
"s": 1063,
"text": "The above expression indicates an ‘.’ and a digit in the range 0 to 9 as a regex."
},
{
"code": null,
"e": 1314,
"s": 1145,
"text": "regex_match() function is used to match the given pattern. This function returns true if the given expression matches the string. Otherwise, the function returns false."
},
{
"code": null,
"e": 1365,
"s": 1314,
"text": "Here is the implementation of the above approach. "
},
{
"code": null,
"e": 1369,
"s": 1365,
"text": "C++"
},
{
"code": null,
"e": 1377,
"s": 1369,
"text": "Python3"
},
{
"code": "// C++ program to validate// IP address using Regex #include <bits/stdc++.h>using namespace std; // Function for Validating IPstring Validate_It(string IP){ // Regex expression for validating IPv4 regex ipv4(\"(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\\\\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\"); // Regex expression for validating IPv6 regex ipv6(\"((([0-9a-fA-F]){1,4})\\\\:){7}([0-9a-fA-F]){1,4}\"); // Checking if it is a valid IPv4 addresses if (regex_match(IP, ipv4)) return \"Valid IPv4\"; // Checking if it is a valid IPv6 addresses else if (regex_match(IP, ipv6)) return \"Valid IPv6\"; // Return Invalid return \"Invalid IP\";} // Driver Codeint main(){ // IP addresses to validate string IP = \"257.120.223.13\"; cout << Validate_It(IP) << endl; IP = \"fffe:3465:efab:23fe:2235:6565:aaab:0001\"; cout << Validate_It(IP) << endl; IP = \"2F33:12a0:3Ea0:0302\"; cout << Validate_It(IP) << endl; return 0;}",
"e": 2375,
"s": 1377,
"text": null
},
{
"code": "# Python3 program to validate# IP address using Regeximport re # Function for Validating IP def Validate_It(IP): # Regex expression for validating IPv4 regex = \"^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])\\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9]?[0-9])$\" # Regex expression for validating IPv6 regex1 = \"((([0-9a-fA-F]){1,4})\\\\:){7}\"\\ \"([0-9a-fA-F]){1,4}\" p = re.compile(regex) p1 = re.compile(regex1) # Checking if it is a valid IPv4 addresses if (re.search(p, IP)): return \"Valid IPv4\" # Checking if it is a valid IPv6 addresses elif (re.search(p1, IP)): return \"Valid IPv6\" # Return Invalid return \"Invalid IP\" # Driver Code # IP addresses to validateIP = \"257.120.223.13\"print(Validate_It(IP)) IP = \"fffe:3465:efab:23fe:2235:6565:aaab:0001\"print(Validate_It(IP)) IP = \"2F33:12a0:3Ea0:0302\"print(Validate_It(IP)) # This code is contributed by avanitrachhadiya2155",
"e": 3319,
"s": 2375,
"text": null
},
{
"code": null,
"e": 3353,
"s": 3319,
"text": "Invalid IP\nValid IPv6\nInvalid IP\n"
},
{
"code": null,
"e": 3400,
"s": 3353,
"text": "Time Complexity: O (N) Auxiliary Space: O (1) "
},
{
"code": null,
"e": 3417,
"s": 3400,
"text": "abhishek_padghan"
},
{
"code": null,
"e": 3438,
"s": 3417,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 3455,
"s": 3438,
"text": "harendrakumar123"
},
{
"code": null,
"e": 3465,
"s": 3455,
"text": "CPP-regex"
},
{
"code": null,
"e": 3479,
"s": 3465,
"text": "IP Addressing"
},
{
"code": null,
"e": 3503,
"s": 3479,
"text": "java-regular-expression"
},
{
"code": null,
"e": 3516,
"s": 3503,
"text": "python-regex"
},
{
"code": null,
"e": 3535,
"s": 3516,
"text": "regular-expression"
},
{
"code": null,
"e": 3553,
"s": 3535,
"text": "Computer Networks"
},
{
"code": null,
"e": 3563,
"s": 3553,
"text": "Searching"
},
{
"code": null,
"e": 3571,
"s": 3563,
"text": "Strings"
},
{
"code": null,
"e": 3581,
"s": 3571,
"text": "Searching"
},
{
"code": null,
"e": 3589,
"s": 3581,
"text": "Strings"
},
{
"code": null,
"e": 3607,
"s": 3589,
"text": "Computer Networks"
}
] |
Difference Between GIT and SVN | 21 Jun, 2022
GIT: Git is an open-source distributed version control system developed by Linus Torvalds in 2005. Its emphasis on speed and data integrity in which there is no centralized connectivity is needed. It is powerful and cheap branching with easy merge in which each developer has his repository and have a local copy in which they can change history. It supports non-linear development branches and applications with a large number of codes files.
Here are some .git directory structures used in GIT:
HEAD/: A pointer structure used in git.
Config/: Contains all configuration preferences.
description/: Description of your project.
index/: It is used as a staging area between working directory.
object/: All the data are stored here.
logs/: Keeps record to change that are made.
SVN: Apache Subversion is an open-source software version and revision control system under the Apache license. It managed files and folders that are present in the repository. It can operate across the network, which allows it and used by people on different computer .we can say that a repository is like an ordinary file server which allows it to be used by people on a different computer.
Below is a table of differences between GIT and SVN:
Features of GIT:
Distributed System.
Branching.
Compatibility.
Non-linear Development.
Lightweight.
Open source.
Features of SVN:
Directories are versioned
Copying, deleting, and renaming.
Free-form versioned metadata .
Atomic commits.
Branching and tagging.
Merge tracking.
File locking.
9okfx6axjopy1zpnpkhuhgar0w0wg5p1enclhc5x
mitalibhola94
Difference Between
Git
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
Difference Between Method Overloading and Method Overriding in Java
Differences between JDK, JRE and JVM
Difference between Process and Thread
Difference between Clustered and Non-clustered index
Working on Git for GUI
How to Set Git Username and Password in GitBash?
How to integrate Git Bash with Visual Studio Code?
Git - Difference Between Git Fetch and Git Pull
How to Set Upstream Branch on Git? | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n21 Jun, 2022"
},
{
"code": null,
"e": 497,
"s": 52,
"text": "GIT: Git is an open-source distributed version control system developed by Linus Torvalds in 2005. Its emphasis on speed and data integrity in which there is no centralized connectivity is needed. It is powerful and cheap branching with easy merge in which each developer has his repository and have a local copy in which they can change history. It supports non-linear development branches and applications with a large number of codes files. "
},
{
"code": null,
"e": 550,
"s": 497,
"text": "Here are some .git directory structures used in GIT:"
},
{
"code": null,
"e": 590,
"s": 550,
"text": "HEAD/: A pointer structure used in git."
},
{
"code": null,
"e": 639,
"s": 590,
"text": "Config/: Contains all configuration preferences."
},
{
"code": null,
"e": 682,
"s": 639,
"text": "description/: Description of your project."
},
{
"code": null,
"e": 746,
"s": 682,
"text": "index/: It is used as a staging area between working directory."
},
{
"code": null,
"e": 785,
"s": 746,
"text": "object/: All the data are stored here."
},
{
"code": null,
"e": 830,
"s": 785,
"text": "logs/: Keeps record to change that are made."
},
{
"code": null,
"e": 1223,
"s": 830,
"text": "SVN: Apache Subversion is an open-source software version and revision control system under the Apache license. It managed files and folders that are present in the repository. It can operate across the network, which allows it and used by people on different computer .we can say that a repository is like an ordinary file server which allows it to be used by people on a different computer."
},
{
"code": null,
"e": 1279,
"s": 1226,
"text": "Below is a table of differences between GIT and SVN:"
},
{
"code": null,
"e": 1296,
"s": 1279,
"text": "Features of GIT:"
},
{
"code": null,
"e": 1316,
"s": 1296,
"text": "Distributed System."
},
{
"code": null,
"e": 1327,
"s": 1316,
"text": "Branching."
},
{
"code": null,
"e": 1342,
"s": 1327,
"text": "Compatibility."
},
{
"code": null,
"e": 1366,
"s": 1342,
"text": "Non-linear Development."
},
{
"code": null,
"e": 1379,
"s": 1366,
"text": "Lightweight."
},
{
"code": null,
"e": 1392,
"s": 1379,
"text": "Open source."
},
{
"code": null,
"e": 1409,
"s": 1392,
"text": "Features of SVN:"
},
{
"code": null,
"e": 1435,
"s": 1409,
"text": "Directories are versioned"
},
{
"code": null,
"e": 1468,
"s": 1435,
"text": "Copying, deleting, and renaming."
},
{
"code": null,
"e": 1499,
"s": 1468,
"text": "Free-form versioned metadata ."
},
{
"code": null,
"e": 1515,
"s": 1499,
"text": "Atomic commits."
},
{
"code": null,
"e": 1538,
"s": 1515,
"text": "Branching and tagging."
},
{
"code": null,
"e": 1554,
"s": 1538,
"text": "Merge tracking."
},
{
"code": null,
"e": 1568,
"s": 1554,
"text": "File locking."
},
{
"code": null,
"e": 1609,
"s": 1568,
"text": "9okfx6axjopy1zpnpkhuhgar0w0wg5p1enclhc5x"
},
{
"code": null,
"e": 1623,
"s": 1609,
"text": "mitalibhola94"
},
{
"code": null,
"e": 1642,
"s": 1623,
"text": "Difference Between"
},
{
"code": null,
"e": 1646,
"s": 1642,
"text": "Git"
},
{
"code": null,
"e": 1744,
"s": 1646,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1805,
"s": 1744,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 1873,
"s": 1805,
"text": "Difference Between Method Overloading and Method Overriding in Java"
},
{
"code": null,
"e": 1910,
"s": 1873,
"text": "Differences between JDK, JRE and JVM"
},
{
"code": null,
"e": 1948,
"s": 1910,
"text": "Difference between Process and Thread"
},
{
"code": null,
"e": 2001,
"s": 1948,
"text": "Difference between Clustered and Non-clustered index"
},
{
"code": null,
"e": 2024,
"s": 2001,
"text": "Working on Git for GUI"
},
{
"code": null,
"e": 2073,
"s": 2024,
"text": "How to Set Git Username and Password in GitBash?"
},
{
"code": null,
"e": 2124,
"s": 2073,
"text": "How to integrate Git Bash with Visual Studio Code?"
},
{
"code": null,
"e": 2172,
"s": 2124,
"text": "Git - Difference Between Git Fetch and Git Pull"
}
] |
ML | Training Image Classifier using Tensorflow Object Detection API | 28 Oct, 2019
This article aims to learn how to build an object detector using Tensorflow’s object detection API.
Requirement :
Python Programming
Basics of Machine Learning
Basics of neural networks (Not Mandatory)
An enthusiasm to build a Cool project(Mandatory) :p
Even though if you don’t have the first three essentials, you’re welcome to the adventure. Don’t worry about getting lost, I’ll guide you properly through the journey!
What is object detection?Object detection is the process of finding instances of real-world objects such as faces, buildings, and bicycle in images or videos. Object detection algorithms typically use extracted features and learning algorithms to recognize instances of an object category. It is commonly used in applications such as image retrieval, security, surveillance, and advanced driver assistance systems (Self-driving cars). I personally have used object detection to build a prototype of an Image-Based Search Engine.
What is Tensorflow’s Object Detection API?Tensorflow is an open-source deep learning framework created by Google Brain. Tensorflow’s Object Detection API is a powerful tool which enables everyone to create their own powerful Image Classifiers. No coding or programming knowledge is needed to use Tensorflow’s Object Detection API. But to understand it’s working, knowing python programming and basics of machine learning helps.
Before starting the Adventure let’s us make sure that, Python 3 is installed in your system
For installing python and pip refer this site
First things first! Make sure that the below-given packages are installed in your system. These are essential in your adventure.
pip install protobuf
pip install pillow
pip install lxml
pip install Cython
pip install jupyter
pip install matplotlib
pip install pandas
pip install opencv-python
pip install tensorflow
In order to start the adventure, we must get the vehicle and make the necessary configurations to it.Tensorflow’s Object Detection API
We can get Tensorflow’s Object Detection API from githubVisit the link provided: Download here
We can get Tensorflow’s Object Detection API from github
Visit the link provided: Download here
After downloading the models folder, extract it to the project’s directory. We can find the object_detection directory inside
models-master/research/
Creating a PYTHONPATH variable:A PYTHONPATH variable must be created that points to the \models, \models\research, and \models\research\slim directories. Issue the command in the following manner from any directory. In my case, set PYTHONPATH=F:\Programming\geeksforgeeks_project\models-master;F:\Programming\geeksforgeeks_project\models-master\research;F:\Programming\geeksforgeeks_project\models-master\research\slim
set PYTHONPATH=F:\Programming\geeksforgeeks_project\models-master;F:\Programming\geeksforgeeks_project\models-master\research;F:\Programming\geeksforgeeks_project\models-master\research\slim
Compiling protobuf files and running setup.py:The need to compile the Protobuf files, which are used by TensorFlow to configure the model and the training parameters.For Compiling protoc files first we need to get protobuf compiler. You can Download it here. Download protoc-3.8-win64.zip file for windows OS and for other operating systems download the related zip file. Extract the bin folder to research directory.Copy the below given code and save it as use_protobuf.py in your research directory.
import os
import sys
args = sys.argv
directory = args[1]
protoc_path = args[2]
for file in os.listdir(directory):
if file.endswith(".proto"):
os.system(protoc_path+" "+directory+"/"+file+" --python_out=.")
Go to research directory in command promt and use the command given below.
python use_protobuf.py .\object_detection\protos\ .\bin\protoc
This compiles all the protobuf files and creates a name_pb2.py file from every name.proto file in the \object_detection\protos folder.Finally, run the following commands from the models-master\research directory:
python setup.py build
python setup.py install
With this the installation is finished and a package named object-detection is installed.
Testing the API:For testing the Object Detection api, go to object_detection directory and enter the following command:jupyter notebook object_detection_tutorial.ipynbThis opens up the jupyter notebook in the browser.Note:If you have a line sys.path.append(“..”) in the first cell of the notebook, remove that line.Run all the cells of the notebook and check if you’re getting an output similar to the below image:
jupyter notebook object_detection_tutorial.ipynb
This opens up the jupyter notebook in the browser.Note:If you have a line sys.path.append(“..”) in the first cell of the notebook, remove that line.
Run all the cells of the notebook and check if you’re getting an output similar to the below image:
With this we have successfully configured our vehicle.
Let’s begin our journey!
To reach our destination we need to cross 6 Check points:
Preparing DatasetLabeling the DatasetGenerating Records for TrainingConfiguring TrainingTraining the ModelExporting Inference Graph
Preparing Dataset
Labeling the Dataset
Generating Records for Training
Configuring Training
Training the Model
Exporting Inference Graph
Plan what objects do you want to detect using the classifier.
Check Point 1: Preparing Dataset:In this adventure, I am going to build a classifier which detects shoes and water bottles. Remember, the dataset is the most important thing in building a classifier. This will be the basis of your classifier on which object detection is done. Collect as many different and variety of images consisting of the objects. Create a directory named images inside research directory. Store 80% of the images into train directory and 20% of the images into test directory inside the images directory. I have collected 50 images in train directory and 10 images in the test directory. The more the number of images the better is the precision of your classifier.Images in train directoryImages in test directory
In this adventure, I am going to build a classifier which detects shoes and water bottles. Remember, the dataset is the most important thing in building a classifier. This will be the basis of your classifier on which object detection is done. Collect as many different and variety of images consisting of the objects. Create a directory named images inside research directory. Store 80% of the images into train directory and 20% of the images into test directory inside the images directory. I have collected 50 images in train directory and 10 images in the test directory. The more the number of images the better is the precision of your classifier.
Images in train directory
Images in test directory
Check Point 2: Labeling the Dataset:To cross this checkpoint, we need to have a tool called as labelimg. You can get it from: labelimg downloadOpen the labelimg application and start drawing the rect boxes on the image where ever the object is present. And label them with an appropriate name as shown in the figure:Save each image after labeling which generates a xml file with the respective image’s name as shown in the below image.
Open the labelimg application and start drawing the rect boxes on the image where ever the object is present. And label them with an appropriate name as shown in the figure:
Save each image after labeling which generates a xml file with the respective image’s name as shown in the below image.
Check Point 3: Generating Records for Training:To cross this check point, we need to create TFRecords that can be served as input data for training of the object detector. In order to create the TFRecords we will use two scripts from Dat Tran’s Racoon Detector. Namely the xml_to_csv.py and generate_tfrecord.py files. Download them and save them in object_detection folder.replace the main() method of the xml_to_csv.py with the following code:def main():
for folder in ['train', 'test']:
image_path = os.path.join(os.getcwd(), ('images/' + folder))
xml_df = xml_to_csv(image_path)
xml_df.to_csv(('images/'+folder+'_labels.csv'), index=None)
print('Successfully converted xml to csv.')And also, add the below lines of code in xml_to_csv() method before the return statement as shown in the below figure.names=[]
for i in xml_df['filename']:
names.append(i+'.jpg')
xml_df['filename']=namesFirst let’s convert all the XML files to CSV files by running xml_to_csv.py file with the following command in the object_detection directory:python xml_to_csv.pyThis creates test.csv and train.csv files in the images folder.Next, open the generate_tfrecord.py file in a text editor and edit the method class_text_to_int() which can be found in the line 30 as shown in the below image.Then, generate the TFRecord files by issuing these commands from the \object_detection folder:python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record
python generate_tfrecord.py --csv_input=images\test_labels.csv --image_dir=images\test --output_path=test.recordThis creates test.record and train.record files in object_detection directory.
replace the main() method of the xml_to_csv.py with the following code:
def main():
for folder in ['train', 'test']:
image_path = os.path.join(os.getcwd(), ('images/' + folder))
xml_df = xml_to_csv(image_path)
xml_df.to_csv(('images/'+folder+'_labels.csv'), index=None)
print('Successfully converted xml to csv.')
And also, add the below lines of code in xml_to_csv() method before the return statement as shown in the below figure.
names=[]
for i in xml_df['filename']:
names.append(i+'.jpg')
xml_df['filename']=names
First let’s convert all the XML files to CSV files by running xml_to_csv.py file with the following command in the object_detection directory:
python xml_to_csv.py
This creates test.csv and train.csv files in the images folder.
Next, open the generate_tfrecord.py file in a text editor and edit the method class_text_to_int() which can be found in the line 30 as shown in the below image.
Then, generate the TFRecord files by issuing these commands from the \object_detection folder:
python generate_tfrecord.py --csv_input=images\train_labels.csv --image_dir=images\train --output_path=train.record
python generate_tfrecord.py --csv_input=images\test_labels.csv --image_dir=images\test --output_path=test.record
This creates test.record and train.record files in object_detection directory.
Check Point 4: Configuring Training:In order to cross this checkpoint, we first need to create a label map.Create a new directory named training inside object_detection directory.Use a text editor to create a new file and save it as labelmap.pbtxt in the training directory. The label map tells the trainer what each object is by defining a mapping of class names to class ID numbers.Now, add content in labelmap.pbtxt file in the following format to create a labelmap for your classifier.item {
id: 1
name: 'shoe'
}
item {
id: 2
name: 'bottle'
}The label map ID numbers should be the same as what is defined in the generate_tfrecord.py file.Now let’s start to configure training!We need a model i.e, algorithm to train our classifier. In this project we are going to use faster_rcnn_inception model. Tensorflow’s object detection API comes with a huge number of models. Navigate to object_detection\samples\configs.In this location you can find a lot of config files to all the models provided by the API. You can download the model using this link. Download the file faster_rcnn_inception_v2_coco. After the downloading is finished, extract the folder faster_rcnn_inception_v2_coco_2018_01_28 to object_detection directory. For understanding the working of the model refer this article.As we are using faster_rcnn_inception_v2_coco model in this project, copy the faster_rcnn_inception_v2_coco.config file from object_detection\samples\configs and paste it in the training directory created before.Use a text editor to open the config file and make the following changes to the faster_rcnn_inception_v2_pets.config file.Note: The paths must be entered with single forward slashes (NOT backslashes), or TensorFlow will give a file path error when trying to train the model! Also, the paths must be in double quotation marks ( ” ), not single quotation marks ( ‘ ).Line 10: Set the num_classes value to the number of objects your classifier is classifying. In my case, as I am classifying shoes and bottles it would be num_classes: 2.In Line 107: Give the absolute path of model.ckpt file to the file_tuning_checkpoint parameter. model.ckpt file is present in the location object_detection/faster_rcnn_inception_v2_coco_2018_01_28. In my case,fine_tune_checkpoint: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt”train_input_reader section: you can find this section in the line 120. In this section set the input_path parameter to your train.record file. In my case it isinput_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”.Set the label_map_path parameter to the labelmap.pbtxt file. In my case it is:label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”eval config section: You can find this section in the line 128. set num_examples parameter to the number of images present in the test directory. In my case,num_examples: 10eval_input_reader section: You can find this section in the line 134. Similar to train_input_reader section, set the paths to test.record and labelmap.pbtxt files. In my case,input_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”With this all the configurations are done and we’re going to reach our last checkpoint.
In order to cross this checkpoint, we first need to create a label map.
Create a new directory named training inside object_detection directory.
Use a text editor to create a new file and save it as labelmap.pbtxt in the training directory. The label map tells the trainer what each object is by defining a mapping of class names to class ID numbers.Now, add content in labelmap.pbtxt file in the following format to create a labelmap for your classifier.
item {
id: 1
name: 'shoe'
}
item {
id: 2
name: 'bottle'
}
The label map ID numbers should be the same as what is defined in the generate_tfrecord.py file.
Now let’s start to configure training!
We need a model i.e, algorithm to train our classifier. In this project we are going to use faster_rcnn_inception model. Tensorflow’s object detection API comes with a huge number of models. Navigate to object_detection\samples\configs.In this location you can find a lot of config files to all the models provided by the API. You can download the model using this link. Download the file faster_rcnn_inception_v2_coco. After the downloading is finished, extract the folder faster_rcnn_inception_v2_coco_2018_01_28 to object_detection directory. For understanding the working of the model refer this article.
As we are using faster_rcnn_inception_v2_coco model in this project, copy the faster_rcnn_inception_v2_coco.config file from object_detection\samples\configs and paste it in the training directory created before.Use a text editor to open the config file and make the following changes to the faster_rcnn_inception_v2_pets.config file.Note: The paths must be entered with single forward slashes (NOT backslashes), or TensorFlow will give a file path error when trying to train the model! Also, the paths must be in double quotation marks ( ” ), not single quotation marks ( ‘ ).
Line 10: Set the num_classes value to the number of objects your classifier is classifying. In my case, as I am classifying shoes and bottles it would be num_classes: 2.
In Line 107: Give the absolute path of model.ckpt file to the file_tuning_checkpoint parameter. model.ckpt file is present in the location object_detection/faster_rcnn_inception_v2_coco_2018_01_28. In my case,fine_tune_checkpoint: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt”
fine_tune_checkpoint: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt”
train_input_reader section: you can find this section in the line 120. In this section set the input_path parameter to your train.record file. In my case it isinput_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”.Set the label_map_path parameter to the labelmap.pbtxt file. In my case it is:label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”
Set the label_map_path parameter to the labelmap.pbtxt file. In my case it is:label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”
eval config section: You can find this section in the line 128. set num_examples parameter to the number of images present in the test directory. In my case,num_examples: 10
eval_input_reader section: You can find this section in the line 134. Similar to train_input_reader section, set the paths to test.record and labelmap.pbtxt files. In my case,input_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”
label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”
With this all the configurations are done and we’re going to reach our last checkpoint.
Check Point 5: Training the Model:Finally the time has come to train our model. You can find a file named train.py at the location object_detection/legacy/.Copy the train.py file and paste it in the object_detection directory.Navigate to object_detection directory and run the following command to start training your model!python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_coco.config
It takes around 1min to initialize the setup before the training begins. When the training begins, it looks like:Tensorflow creates a checkpoint for every 5 minutes and stores it. You can see that all the checkpoints are saved in the training directory.You can view the progress of the training job by using TensorBoard. To do this, open a new command prompt and navigate to the object_detection directory, and issue the following command:tensorboard --logdir=trainingTensorboard looks like:Continue the training process until the loss is less than or equal to 0.1.
Copy the train.py file and paste it in the object_detection directory.Navigate to object_detection directory and run the following command to start training your model!
python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_coco.config
It takes around 1min to initialize the setup before the training begins. When the training begins, it looks like:
Tensorflow creates a checkpoint for every 5 minutes and stores it. You can see that all the checkpoints are saved in the training directory.You can view the progress of the training job by using TensorBoard. To do this, open a new command prompt and navigate to the object_detection directory, and issue the following command:
tensorboard --logdir=training
Tensorboard looks like:
Continue the training process until the loss is less than or equal to 0.1.
Check Point 6: Exporting Inference Graph:This is the last checkpoint to be crossed to reach the destination.Now that we have a trained model we need to generate an inference graph, which can be used to run the model. For doing so we need to first of find out the highest saved step number. For this, we need to navigate to the training directory and look for the model.ckpt file with the biggest index.Then we can create the inference graph by typing the following command in the command line.python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_coco.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graphXXXX should be filled by the highest checkpoint number.This creates a frozen_inference_graph.pb file in the \object_detection\inference_graph folder. The .pb file contains the object detection classifier.
Then we can create the inference graph by typing the following command in the command line.
python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_coco.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph
XXXX should be filled by the highest checkpoint number.This creates a frozen_inference_graph.pb file in the \object_detection\inference_graph folder. The .pb file contains the object detection classifier.
With this, we have finished building our classifier. All that is left to finish our adventure is using our model to detect objects.
create a python file in the object_detection directory with the below code:
# Write Python3 code hereimport osimport cv2import numpy as npimport tensorflow as tfimport sys # This is needed since the notebook is stored in the object_detection folder.sys.path.append("..") # Import utilitesfrom utils import label_map_utilfrom utils import visualization_utils as vis_util # Name of the directory containing the object detection module we're usingMODEL_NAME = 'inference_graph' # The path to the directory where frozen_inference_graph is stored.IMAGE_NAME = '11man.jpg' # The path to the image in which the object has to be detected. # Grab path to current working directoryCWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which contains the model that is used# for object detection.PATH_TO_CKPT = os.path.join(CWD_PATH, MODEL_NAME, 'frozen_inference_graph.pb') # Path to label map filePATH_TO_LABELS = os.path.join(CWD_PATH, 'training', 'labelmap.pbtxt') # Path to imagePATH_TO_IMAGE = os.path.join(CWD_PATH, IMAGE_NAME) # Number of classes the object detector can identifyNUM_CLASSES = 2 # Load the label map.# Label maps map indices to category names, so that when our convolution# network predicts `5`, we know that this corresponds to `king`.# Here we use internal utility functions, but anything that returns a# dictionary mapping integers to appropriate string labels would be finelabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)categories = label_map_util.convert_label_map_to_categories( label_map, max_num_classes = NUM_CLASSES, use_display_name = True)category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory.detection_graph = tf.Graph()with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name ='') sess = tf.Session(graph = detection_graph) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the imageimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes# Each box represents a part of the image where a particular object was detecteddetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects.# The score is shown on the result image, together with the class label.detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detectednum_detections = detection_graph.get_tensor_by_name('num_detections:0') # Load image using OpenCV and# expand image dimensions to have shape: [1, None, None, 3]# i.e. a single-column array, where each item in the column has the pixel RGB valueimage = cv2.imread(PATH_TO_IMAGE)image_expanded = np.expand_dims(image, axis = 0) # Perform the actual detection by running the model with the image as input(boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict ={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visualize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates = True, line_thickness = 8, min_score_thresh = 0.60) # All the results have been drawn on the image. Now display the image.cv2.imshow('Object detector', image) # Press any key to close the imagecv2.waitKey(0) # Clean upcv2.destroyAllWindows()
Give the path to the image in which object to be detected in the line 17.
Below are some of the results of my model.
So finally our model is ready. This model has also been used to build an Image-based search engine, which searches using image inputs by detecting objects in the image.
nidhi_biet
Tensorflow
Advanced Computer Subject
Articles
Machine Learning
Project
Python
Machine Learning
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
System Design Tutorial
ML | Linear Regression
Docker - COPY Instruction
Reinforcement learning
Supervised and Unsupervised learning
Tree Traversals (Inorder, Preorder and Postorder)
SQL | Join (Inner, Left, Right and Full Joins)
find command in Linux with examples
Analysis of Algorithms | Set 1 (Asymptotic Analysis)
Time Complexity and Space Complexity | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n28 Oct, 2019"
},
{
"code": null,
"e": 154,
"s": 54,
"text": "This article aims to learn how to build an object detector using Tensorflow’s object detection API."
},
{
"code": null,
"e": 168,
"s": 154,
"text": "Requirement :"
},
{
"code": null,
"e": 187,
"s": 168,
"text": "Python Programming"
},
{
"code": null,
"e": 214,
"s": 187,
"text": "Basics of Machine Learning"
},
{
"code": null,
"e": 256,
"s": 214,
"text": "Basics of neural networks (Not Mandatory)"
},
{
"code": null,
"e": 308,
"s": 256,
"text": "An enthusiasm to build a Cool project(Mandatory) :p"
},
{
"code": null,
"e": 476,
"s": 308,
"text": "Even though if you don’t have the first three essentials, you’re welcome to the adventure. Don’t worry about getting lost, I’ll guide you properly through the journey!"
},
{
"code": null,
"e": 1005,
"s": 476,
"text": "What is object detection?Object detection is the process of finding instances of real-world objects such as faces, buildings, and bicycle in images or videos. Object detection algorithms typically use extracted features and learning algorithms to recognize instances of an object category. It is commonly used in applications such as image retrieval, security, surveillance, and advanced driver assistance systems (Self-driving cars). I personally have used object detection to build a prototype of an Image-Based Search Engine."
},
{
"code": null,
"e": 1433,
"s": 1005,
"text": "What is Tensorflow’s Object Detection API?Tensorflow is an open-source deep learning framework created by Google Brain. Tensorflow’s Object Detection API is a powerful tool which enables everyone to create their own powerful Image Classifiers. No coding or programming knowledge is needed to use Tensorflow’s Object Detection API. But to understand it’s working, knowing python programming and basics of machine learning helps."
},
{
"code": null,
"e": 1525,
"s": 1433,
"text": "Before starting the Adventure let’s us make sure that, Python 3 is installed in your system"
},
{
"code": null,
"e": 1571,
"s": 1525,
"text": "For installing python and pip refer this site"
},
{
"code": null,
"e": 1700,
"s": 1571,
"text": "First things first! Make sure that the below-given packages are installed in your system. These are essential in your adventure."
},
{
"code": null,
"e": 1952,
"s": 1700,
"text": " pip install protobuf\n pip install pillow\n pip install lxml\n pip install Cython\n pip install jupyter\n pip install matplotlib\n pip install pandas\n pip install opencv-python \n pip install tensorflow\n"
},
{
"code": null,
"e": 2087,
"s": 1952,
"text": "In order to start the adventure, we must get the vehicle and make the necessary configurations to it.Tensorflow’s Object Detection API"
},
{
"code": null,
"e": 2182,
"s": 2087,
"text": "We can get Tensorflow’s Object Detection API from githubVisit the link provided: Download here"
},
{
"code": null,
"e": 2239,
"s": 2182,
"text": "We can get Tensorflow’s Object Detection API from github"
},
{
"code": null,
"e": 2278,
"s": 2239,
"text": "Visit the link provided: Download here"
},
{
"code": null,
"e": 2404,
"s": 2278,
"text": "After downloading the models folder, extract it to the project’s directory. We can find the object_detection directory inside"
},
{
"code": null,
"e": 2430,
"s": 2404,
"text": " models-master/research/ "
},
{
"code": null,
"e": 2851,
"s": 2430,
"text": "Creating a PYTHONPATH variable:A PYTHONPATH variable must be created that points to the \\models, \\models\\research, and \\models\\research\\slim directories. Issue the command in the following manner from any directory. In my case, set PYTHONPATH=F:\\Programming\\geeksforgeeks_project\\models-master;F:\\Programming\\geeksforgeeks_project\\models-master\\research;F:\\Programming\\geeksforgeeks_project\\models-master\\research\\slim"
},
{
"code": null,
"e": 3045,
"s": 2851,
"text": " set PYTHONPATH=F:\\Programming\\geeksforgeeks_project\\models-master;F:\\Programming\\geeksforgeeks_project\\models-master\\research;F:\\Programming\\geeksforgeeks_project\\models-master\\research\\slim"
},
{
"code": null,
"e": 3547,
"s": 3045,
"text": "Compiling protobuf files and running setup.py:The need to compile the Protobuf files, which are used by TensorFlow to configure the model and the training parameters.For Compiling protoc files first we need to get protobuf compiler. You can Download it here. Download protoc-3.8-win64.zip file for windows OS and for other operating systems download the related zip file. Extract the bin folder to research directory.Copy the below given code and save it as use_protobuf.py in your research directory."
},
{
"code": null,
"e": 3784,
"s": 3547,
"text": " import os \n import sys \n args = sys.argv \n directory = args[1] \n protoc_path = args[2] \n for file in os.listdir(directory):\n if file.endswith(\".proto\"):\n os.system(protoc_path+\" \"+directory+\"/\"+file+\" --python_out=.\")"
},
{
"code": null,
"e": 3859,
"s": 3784,
"text": "Go to research directory in command promt and use the command given below."
},
{
"code": null,
"e": 3923,
"s": 3859,
"text": "python use_protobuf.py .\\object_detection\\protos\\ .\\bin\\protoc"
},
{
"code": null,
"e": 4136,
"s": 3923,
"text": "This compiles all the protobuf files and creates a name_pb2.py file from every name.proto file in the \\object_detection\\protos folder.Finally, run the following commands from the models-master\\research directory:"
},
{
"code": null,
"e": 4186,
"s": 4136,
"text": " python setup.py build\n python setup.py install"
},
{
"code": null,
"e": 4276,
"s": 4186,
"text": "With this the installation is finished and a package named object-detection is installed."
},
{
"code": null,
"e": 4691,
"s": 4276,
"text": "Testing the API:For testing the Object Detection api, go to object_detection directory and enter the following command:jupyter notebook object_detection_tutorial.ipynbThis opens up the jupyter notebook in the browser.Note:If you have a line sys.path.append(“..”) in the first cell of the notebook, remove that line.Run all the cells of the notebook and check if you’re getting an output similar to the below image:"
},
{
"code": null,
"e": 4740,
"s": 4691,
"text": "jupyter notebook object_detection_tutorial.ipynb"
},
{
"code": null,
"e": 4889,
"s": 4740,
"text": "This opens up the jupyter notebook in the browser.Note:If you have a line sys.path.append(“..”) in the first cell of the notebook, remove that line."
},
{
"code": null,
"e": 4989,
"s": 4889,
"text": "Run all the cells of the notebook and check if you’re getting an output similar to the below image:"
},
{
"code": null,
"e": 5044,
"s": 4989,
"text": "With this we have successfully configured our vehicle."
},
{
"code": null,
"e": 5069,
"s": 5044,
"text": "Let’s begin our journey!"
},
{
"code": null,
"e": 5127,
"s": 5069,
"text": "To reach our destination we need to cross 6 Check points:"
},
{
"code": null,
"e": 5259,
"s": 5127,
"text": "Preparing DatasetLabeling the DatasetGenerating Records for TrainingConfiguring TrainingTraining the ModelExporting Inference Graph"
},
{
"code": null,
"e": 5277,
"s": 5259,
"text": "Preparing Dataset"
},
{
"code": null,
"e": 5298,
"s": 5277,
"text": "Labeling the Dataset"
},
{
"code": null,
"e": 5330,
"s": 5298,
"text": "Generating Records for Training"
},
{
"code": null,
"e": 5351,
"s": 5330,
"text": "Configuring Training"
},
{
"code": null,
"e": 5370,
"s": 5351,
"text": "Training the Model"
},
{
"code": null,
"e": 5396,
"s": 5370,
"text": "Exporting Inference Graph"
},
{
"code": null,
"e": 5458,
"s": 5396,
"text": "Plan what objects do you want to detect using the classifier."
},
{
"code": null,
"e": 6195,
"s": 5458,
"text": "Check Point 1: Preparing Dataset:In this adventure, I am going to build a classifier which detects shoes and water bottles. Remember, the dataset is the most important thing in building a classifier. This will be the basis of your classifier on which object detection is done. Collect as many different and variety of images consisting of the objects. Create a directory named images inside research directory. Store 80% of the images into train directory and 20% of the images into test directory inside the images directory. I have collected 50 images in train directory and 10 images in the test directory. The more the number of images the better is the precision of your classifier.Images in train directoryImages in test directory"
},
{
"code": null,
"e": 6850,
"s": 6195,
"text": "In this adventure, I am going to build a classifier which detects shoes and water bottles. Remember, the dataset is the most important thing in building a classifier. This will be the basis of your classifier on which object detection is done. Collect as many different and variety of images consisting of the objects. Create a directory named images inside research directory. Store 80% of the images into train directory and 20% of the images into test directory inside the images directory. I have collected 50 images in train directory and 10 images in the test directory. The more the number of images the better is the precision of your classifier."
},
{
"code": null,
"e": 6876,
"s": 6850,
"text": "Images in train directory"
},
{
"code": null,
"e": 6901,
"s": 6876,
"text": "Images in test directory"
},
{
"code": null,
"e": 7337,
"s": 6901,
"text": "Check Point 2: Labeling the Dataset:To cross this checkpoint, we need to have a tool called as labelimg. You can get it from: labelimg downloadOpen the labelimg application and start drawing the rect boxes on the image where ever the object is present. And label them with an appropriate name as shown in the figure:Save each image after labeling which generates a xml file with the respective image’s name as shown in the below image."
},
{
"code": null,
"e": 7511,
"s": 7337,
"text": "Open the labelimg application and start drawing the rect boxes on the image where ever the object is present. And label them with an appropriate name as shown in the figure:"
},
{
"code": null,
"e": 7631,
"s": 7511,
"text": "Save each image after labeling which generates a xml file with the respective image’s name as shown in the below image."
},
{
"code": null,
"e": 9358,
"s": 7631,
"text": "Check Point 3: Generating Records for Training:To cross this check point, we need to create TFRecords that can be served as input data for training of the object detector. In order to create the TFRecords we will use two scripts from Dat Tran’s Racoon Detector. Namely the xml_to_csv.py and generate_tfrecord.py files. Download them and save them in object_detection folder.replace the main() method of the xml_to_csv.py with the following code:def main():\n for folder in ['train', 'test']:\n image_path = os.path.join(os.getcwd(), ('images/' + folder))\n xml_df = xml_to_csv(image_path)\n xml_df.to_csv(('images/'+folder+'_labels.csv'), index=None)\n print('Successfully converted xml to csv.')And also, add the below lines of code in xml_to_csv() method before the return statement as shown in the below figure.names=[]\n for i in xml_df['filename']:\n names.append(i+'.jpg')\n xml_df['filename']=namesFirst let’s convert all the XML files to CSV files by running xml_to_csv.py file with the following command in the object_detection directory:python xml_to_csv.pyThis creates test.csv and train.csv files in the images folder.Next, open the generate_tfrecord.py file in a text editor and edit the method class_text_to_int() which can be found in the line 30 as shown in the below image.Then, generate the TFRecord files by issuing these commands from the \\object_detection folder:python generate_tfrecord.py --csv_input=images\\train_labels.csv --image_dir=images\\train --output_path=train.record\npython generate_tfrecord.py --csv_input=images\\test_labels.csv --image_dir=images\\test --output_path=test.recordThis creates test.record and train.record files in object_detection directory."
},
{
"code": null,
"e": 9430,
"s": 9358,
"text": "replace the main() method of the xml_to_csv.py with the following code:"
},
{
"code": null,
"e": 9708,
"s": 9430,
"text": "def main():\n for folder in ['train', 'test']:\n image_path = os.path.join(os.getcwd(), ('images/' + folder))\n xml_df = xml_to_csv(image_path)\n xml_df.to_csv(('images/'+folder+'_labels.csv'), index=None)\n print('Successfully converted xml to csv.')"
},
{
"code": null,
"e": 9827,
"s": 9708,
"text": "And also, add the below lines of code in xml_to_csv() method before the return statement as shown in the below figure."
},
{
"code": null,
"e": 9929,
"s": 9827,
"text": "names=[]\n for i in xml_df['filename']:\n names.append(i+'.jpg')\n xml_df['filename']=names"
},
{
"code": null,
"e": 10072,
"s": 9929,
"text": "First let’s convert all the XML files to CSV files by running xml_to_csv.py file with the following command in the object_detection directory:"
},
{
"code": null,
"e": 10093,
"s": 10072,
"text": "python xml_to_csv.py"
},
{
"code": null,
"e": 10157,
"s": 10093,
"text": "This creates test.csv and train.csv files in the images folder."
},
{
"code": null,
"e": 10318,
"s": 10157,
"text": "Next, open the generate_tfrecord.py file in a text editor and edit the method class_text_to_int() which can be found in the line 30 as shown in the below image."
},
{
"code": null,
"e": 10413,
"s": 10318,
"text": "Then, generate the TFRecord files by issuing these commands from the \\object_detection folder:"
},
{
"code": null,
"e": 10642,
"s": 10413,
"text": "python generate_tfrecord.py --csv_input=images\\train_labels.csv --image_dir=images\\train --output_path=train.record\npython generate_tfrecord.py --csv_input=images\\test_labels.csv --image_dir=images\\test --output_path=test.record"
},
{
"code": null,
"e": 10721,
"s": 10642,
"text": "This creates test.record and train.record files in object_detection directory."
},
{
"code": null,
"e": 14241,
"s": 10721,
"text": "Check Point 4: Configuring Training:In order to cross this checkpoint, we first need to create a label map.Create a new directory named training inside object_detection directory.Use a text editor to create a new file and save it as labelmap.pbtxt in the training directory. The label map tells the trainer what each object is by defining a mapping of class names to class ID numbers.Now, add content in labelmap.pbtxt file in the following format to create a labelmap for your classifier.item {\n id: 1\n name: 'shoe'\n}\n\nitem {\n id: 2\n name: 'bottle'\n}The label map ID numbers should be the same as what is defined in the generate_tfrecord.py file.Now let’s start to configure training!We need a model i.e, algorithm to train our classifier. In this project we are going to use faster_rcnn_inception model. Tensorflow’s object detection API comes with a huge number of models. Navigate to object_detection\\samples\\configs.In this location you can find a lot of config files to all the models provided by the API. You can download the model using this link. Download the file faster_rcnn_inception_v2_coco. After the downloading is finished, extract the folder faster_rcnn_inception_v2_coco_2018_01_28 to object_detection directory. For understanding the working of the model refer this article.As we are using faster_rcnn_inception_v2_coco model in this project, copy the faster_rcnn_inception_v2_coco.config file from object_detection\\samples\\configs and paste it in the training directory created before.Use a text editor to open the config file and make the following changes to the faster_rcnn_inception_v2_pets.config file.Note: The paths must be entered with single forward slashes (NOT backslashes), or TensorFlow will give a file path error when trying to train the model! Also, the paths must be in double quotation marks ( ” ), not single quotation marks ( ‘ ).Line 10: Set the num_classes value to the number of objects your classifier is classifying. In my case, as I am classifying shoes and bottles it would be num_classes: 2.In Line 107: Give the absolute path of model.ckpt file to the file_tuning_checkpoint parameter. model.ckpt file is present in the location object_detection/faster_rcnn_inception_v2_coco_2018_01_28. In my case,fine_tune_checkpoint: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt”train_input_reader section: you can find this section in the line 120. In this section set the input_path parameter to your train.record file. In my case it isinput_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”.Set the label_map_path parameter to the labelmap.pbtxt file. In my case it is:label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”eval config section: You can find this section in the line 128. set num_examples parameter to the number of images present in the test directory. In my case,num_examples: 10eval_input_reader section: You can find this section in the line 134. Similar to train_input_reader section, set the paths to test.record and labelmap.pbtxt files. In my case,input_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”With this all the configurations are done and we’re going to reach our last checkpoint."
},
{
"code": null,
"e": 14313,
"s": 14241,
"text": "In order to cross this checkpoint, we first need to create a label map."
},
{
"code": null,
"e": 14386,
"s": 14313,
"text": "Create a new directory named training inside object_detection directory."
},
{
"code": null,
"e": 14697,
"s": 14386,
"text": "Use a text editor to create a new file and save it as labelmap.pbtxt in the training directory. The label map tells the trainer what each object is by defining a mapping of class names to class ID numbers.Now, add content in labelmap.pbtxt file in the following format to create a labelmap for your classifier."
},
{
"code": null,
"e": 14764,
"s": 14697,
"text": "item {\n id: 1\n name: 'shoe'\n}\n\nitem {\n id: 2\n name: 'bottle'\n}"
},
{
"code": null,
"e": 14861,
"s": 14764,
"text": "The label map ID numbers should be the same as what is defined in the generate_tfrecord.py file."
},
{
"code": null,
"e": 14900,
"s": 14861,
"text": "Now let’s start to configure training!"
},
{
"code": null,
"e": 15509,
"s": 14900,
"text": "We need a model i.e, algorithm to train our classifier. In this project we are going to use faster_rcnn_inception model. Tensorflow’s object detection API comes with a huge number of models. Navigate to object_detection\\samples\\configs.In this location you can find a lot of config files to all the models provided by the API. You can download the model using this link. Download the file faster_rcnn_inception_v2_coco. After the downloading is finished, extract the folder faster_rcnn_inception_v2_coco_2018_01_28 to object_detection directory. For understanding the working of the model refer this article."
},
{
"code": null,
"e": 16087,
"s": 15509,
"text": "As we are using faster_rcnn_inception_v2_coco model in this project, copy the faster_rcnn_inception_v2_coco.config file from object_detection\\samples\\configs and paste it in the training directory created before.Use a text editor to open the config file and make the following changes to the faster_rcnn_inception_v2_pets.config file.Note: The paths must be entered with single forward slashes (NOT backslashes), or TensorFlow will give a file path error when trying to train the model! Also, the paths must be in double quotation marks ( ” ), not single quotation marks ( ‘ )."
},
{
"code": null,
"e": 16257,
"s": 16087,
"text": "Line 10: Set the num_classes value to the number of objects your classifier is classifying. In my case, as I am classifying shoes and bottles it would be num_classes: 2."
},
{
"code": null,
"e": 16619,
"s": 16257,
"text": "In Line 107: Give the absolute path of model.ckpt file to the file_tuning_checkpoint parameter. model.ckpt file is present in the location object_detection/faster_rcnn_inception_v2_coco_2018_01_28. In my case,fine_tune_checkpoint: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt”"
},
{
"code": null,
"e": 16772,
"s": 16619,
"text": "fine_tune_checkpoint: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/faster_rcnn_inception_v2_coco_2018_01_28/model.ckpt”"
},
{
"code": null,
"e": 17232,
"s": 16772,
"text": "train_input_reader section: you can find this section in the line 120. In this section set the input_path parameter to your train.record file. In my case it isinput_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”.Set the label_map_path parameter to the labelmap.pbtxt file. In my case it is:label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”"
},
{
"code": null,
"e": 17429,
"s": 17232,
"text": "Set the label_map_path parameter to the labelmap.pbtxt file. In my case it is:label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”"
},
{
"code": null,
"e": 17603,
"s": 17429,
"text": "eval config section: You can find this section in the line 128. set num_examples parameter to the number of images present in the test directory. In my case,num_examples: 10"
},
{
"code": null,
"e": 18000,
"s": 17603,
"text": "eval_input_reader section: You can find this section in the line 134. Similar to train_input_reader section, set the paths to test.record and labelmap.pbtxt files. In my case,input_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/train.record”label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”"
},
{
"code": null,
"e": 18119,
"s": 18000,
"text": "label_map_path: “F:/Programming/geeksforgeeks_project/models-master/research/object_detection/training/labelmap.pbtxt”"
},
{
"code": null,
"e": 18207,
"s": 18119,
"text": "With this all the configurations are done and we’re going to reach our last checkpoint."
},
{
"code": null,
"e": 19218,
"s": 18207,
"text": "Check Point 5: Training the Model:Finally the time has come to train our model. You can find a file named train.py at the location object_detection/legacy/.Copy the train.py file and paste it in the object_detection directory.Navigate to object_detection directory and run the following command to start training your model!python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_coco.config\nIt takes around 1min to initialize the setup before the training begins. When the training begins, it looks like:Tensorflow creates a checkpoint for every 5 minutes and stores it. You can see that all the checkpoints are saved in the training directory.You can view the progress of the training job by using TensorBoard. To do this, open a new command prompt and navigate to the object_detection directory, and issue the following command:tensorboard --logdir=trainingTensorboard looks like:Continue the training process until the loss is less than or equal to 0.1."
},
{
"code": null,
"e": 19387,
"s": 19218,
"text": "Copy the train.py file and paste it in the object_detection directory.Navigate to object_detection directory and run the following command to start training your model!"
},
{
"code": null,
"e": 19509,
"s": 19387,
"text": "python train.py --logtostderr --train_dir=training/ --pipeline_config_path=training/faster_rcnn_inception_v2_coco.config\n"
},
{
"code": null,
"e": 19623,
"s": 19509,
"text": "It takes around 1min to initialize the setup before the training begins. When the training begins, it looks like:"
},
{
"code": null,
"e": 19950,
"s": 19623,
"text": "Tensorflow creates a checkpoint for every 5 minutes and stores it. You can see that all the checkpoints are saved in the training directory.You can view the progress of the training job by using TensorBoard. To do this, open a new command prompt and navigate to the object_detection directory, and issue the following command:"
},
{
"code": null,
"e": 19980,
"s": 19950,
"text": "tensorboard --logdir=training"
},
{
"code": null,
"e": 20004,
"s": 19980,
"text": "Tensorboard looks like:"
},
{
"code": null,
"e": 20079,
"s": 20004,
"text": "Continue the training process until the loss is less than or equal to 0.1."
},
{
"code": null,
"e": 20992,
"s": 20079,
"text": "Check Point 6: Exporting Inference Graph:This is the last checkpoint to be crossed to reach the destination.Now that we have a trained model we need to generate an inference graph, which can be used to run the model. For doing so we need to first of find out the highest saved step number. For this, we need to navigate to the training directory and look for the model.ckpt file with the biggest index.Then we can create the inference graph by typing the following command in the command line.python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_coco.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graphXXXX should be filled by the highest checkpoint number.This creates a frozen_inference_graph.pb file in the \\object_detection\\inference_graph folder. The .pb file contains the object detection classifier."
},
{
"code": null,
"e": 21084,
"s": 20992,
"text": "Then we can create the inference graph by typing the following command in the command line."
},
{
"code": null,
"e": 21300,
"s": 21084,
"text": "python export_inference_graph.py --input_type image_tensor --pipeline_config_path training/faster_rcnn_inception_v2_coco.config --trained_checkpoint_prefix training/model.ckpt-XXXX --output_directory inference_graph"
},
{
"code": null,
"e": 21505,
"s": 21300,
"text": "XXXX should be filled by the highest checkpoint number.This creates a frozen_inference_graph.pb file in the \\object_detection\\inference_graph folder. The .pb file contains the object detection classifier."
},
{
"code": null,
"e": 21637,
"s": 21505,
"text": "With this, we have finished building our classifier. All that is left to finish our adventure is using our model to detect objects."
},
{
"code": null,
"e": 21713,
"s": 21637,
"text": "create a python file in the object_detection directory with the below code:"
},
{
"code": "# Write Python3 code hereimport osimport cv2import numpy as npimport tensorflow as tfimport sys # This is needed since the notebook is stored in the object_detection folder.sys.path.append(\"..\") # Import utilitesfrom utils import label_map_utilfrom utils import visualization_utils as vis_util # Name of the directory containing the object detection module we're usingMODEL_NAME = 'inference_graph' # The path to the directory where frozen_inference_graph is stored.IMAGE_NAME = '11man.jpg' # The path to the image in which the object has to be detected. # Grab path to current working directoryCWD_PATH = os.getcwd() # Path to frozen detection graph .pb file, which contains the model that is used# for object detection.PATH_TO_CKPT = os.path.join(CWD_PATH, MODEL_NAME, 'frozen_inference_graph.pb') # Path to label map filePATH_TO_LABELS = os.path.join(CWD_PATH, 'training', 'labelmap.pbtxt') # Path to imagePATH_TO_IMAGE = os.path.join(CWD_PATH, IMAGE_NAME) # Number of classes the object detector can identifyNUM_CLASSES = 2 # Load the label map.# Label maps map indices to category names, so that when our convolution# network predicts `5`, we know that this corresponds to `king`.# Here we use internal utility functions, but anything that returns a# dictionary mapping integers to appropriate string labels would be finelabel_map = label_map_util.load_labelmap(PATH_TO_LABELS)categories = label_map_util.convert_label_map_to_categories( label_map, max_num_classes = NUM_CLASSES, use_display_name = True)category_index = label_map_util.create_category_index(categories) # Load the Tensorflow model into memory.detection_graph = tf.Graph()with detection_graph.as_default(): od_graph_def = tf.GraphDef() with tf.gfile.GFile(PATH_TO_CKPT, 'rb') as fid: serialized_graph = fid.read() od_graph_def.ParseFromString(serialized_graph) tf.import_graph_def(od_graph_def, name ='') sess = tf.Session(graph = detection_graph) # Define input and output tensors (i.e. data) for the object detection classifier # Input tensor is the imageimage_tensor = detection_graph.get_tensor_by_name('image_tensor:0') # Output tensors are the detection boxes, scores, and classes# Each box represents a part of the image where a particular object was detecteddetection_boxes = detection_graph.get_tensor_by_name('detection_boxes:0') # Each score represents level of confidence for each of the objects.# The score is shown on the result image, together with the class label.detection_scores = detection_graph.get_tensor_by_name('detection_scores:0')detection_classes = detection_graph.get_tensor_by_name('detection_classes:0') # Number of objects detectednum_detections = detection_graph.get_tensor_by_name('num_detections:0') # Load image using OpenCV and# expand image dimensions to have shape: [1, None, None, 3]# i.e. a single-column array, where each item in the column has the pixel RGB valueimage = cv2.imread(PATH_TO_IMAGE)image_expanded = np.expand_dims(image, axis = 0) # Perform the actual detection by running the model with the image as input(boxes, scores, classes, num) = sess.run( [detection_boxes, detection_scores, detection_classes, num_detections], feed_dict ={image_tensor: image_expanded}) # Draw the results of the detection (aka 'visualize the results') vis_util.visualize_boxes_and_labels_on_image_array( image, np.squeeze(boxes), np.squeeze(classes).astype(np.int32), np.squeeze(scores), category_index, use_normalized_coordinates = True, line_thickness = 8, min_score_thresh = 0.60) # All the results have been drawn on the image. Now display the image.cv2.imshow('Object detector', image) # Press any key to close the imagecv2.waitKey(0) # Clean upcv2.destroyAllWindows()",
"e": 25482,
"s": 21713,
"text": null
},
{
"code": null,
"e": 25556,
"s": 25482,
"text": "Give the path to the image in which object to be detected in the line 17."
},
{
"code": null,
"e": 25599,
"s": 25556,
"text": "Below are some of the results of my model."
},
{
"code": null,
"e": 25768,
"s": 25599,
"text": "So finally our model is ready. This model has also been used to build an Image-based search engine, which searches using image inputs by detecting objects in the image."
},
{
"code": null,
"e": 25779,
"s": 25768,
"text": "nidhi_biet"
},
{
"code": null,
"e": 25790,
"s": 25779,
"text": "Tensorflow"
},
{
"code": null,
"e": 25816,
"s": 25790,
"text": "Advanced Computer Subject"
},
{
"code": null,
"e": 25825,
"s": 25816,
"text": "Articles"
},
{
"code": null,
"e": 25842,
"s": 25825,
"text": "Machine Learning"
},
{
"code": null,
"e": 25850,
"s": 25842,
"text": "Project"
},
{
"code": null,
"e": 25857,
"s": 25850,
"text": "Python"
},
{
"code": null,
"e": 25874,
"s": 25857,
"text": "Machine Learning"
},
{
"code": null,
"e": 25972,
"s": 25874,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 25995,
"s": 25972,
"text": "System Design Tutorial"
},
{
"code": null,
"e": 26018,
"s": 25995,
"text": "ML | Linear Regression"
},
{
"code": null,
"e": 26044,
"s": 26018,
"text": "Docker - COPY Instruction"
},
{
"code": null,
"e": 26067,
"s": 26044,
"text": "Reinforcement learning"
},
{
"code": null,
"e": 26104,
"s": 26067,
"text": "Supervised and Unsupervised learning"
},
{
"code": null,
"e": 26154,
"s": 26104,
"text": "Tree Traversals (Inorder, Preorder and Postorder)"
},
{
"code": null,
"e": 26201,
"s": 26154,
"text": "SQL | Join (Inner, Left, Right and Full Joins)"
},
{
"code": null,
"e": 26237,
"s": 26201,
"text": "find command in Linux with examples"
},
{
"code": null,
"e": 26290,
"s": 26237,
"text": "Analysis of Algorithms | Set 1 (Asymptotic Analysis)"
}
] |
The New Era of App – Intelligent Apps | 17 Dec, 2021
From the early 2000s, a series of development and modification into the existing mobile phones carved the smartphone that we all use today. It is capable of doing many of our tasks hence making it an essential component in our lives. With smartphones, apps come into existence that programs to perform a specific task or to provide a specific service. Over time, many advances and modern applications have been made, which are not only able to do single tasks but are multitasking as well as able to do many complex operations. With the emergence of Artificial Intelligence and Machine Learning, the viewpoint of developers and companies in the app market has completely changed. Apps that can be smarter and can learn from users who are much in demand.
With the growth and development in the artificial intelligence and machine learning industry, many technologies have emerged side by side using the later, as the foundation. We have been engulfed with these modern technologies and instruments, and so do the apps.
In simple terms, intelligent apps are one which uses modern technologies such as artificial intelligence and machine learning & some part of reinforcement learning. These apps are not intended to perform the basic operation, rather used to perform complex tasks that can be automated with continued usage, as the app learns from the operational behavior of the users. These apps can provide personalized user experience combined with the adaptability and richness. Intelligent apps use to power of combined data organization, user predictability, prescriptive analytics, consumer data, and operational data, thus providing the users a very rich experience.
Also termed as smart apps, developers, as well as many mobile app companies, have switched their focus from native-single-operational apps to intelligent apps. The app market is versatile and the technology changes that take place here are very rapid.
1. Adaptive: Since the app will be used by thousands of users, the app is expected to be adaptive. Every user is different in their use, adaptability of the app plays a very crucial role. The use of machine learning helps the app to adapt to a common point where users share some of the similarities in their operations. In some apps, the use of reinforced learning is also being done, to produce a highly-satisfying user experience.
2. Suggestive & Decision-Oriented: While working with a large number of users, the intelligent apps does not wait for the user to decide, rather helps the users to decide what suits best for them, using the user interaction and artificial intelligence. It gives prompt to the users, to opt for a certain decision, but the final decision remains with the user. But yes, these apps can heavily impact on how users choose their decision and interact with the app.
3. Data Powered: Be it online data or offline data, intelligent apps are heavily dependent on data. Data is very essential for intelligence apps, as data serves as the warehouse of information. Most of these apps use online data and require an internet connection. These gather data from a variety of sources, such as online, user interaction, sensors, etc. & compile them, thus providing better user experience.
4. Responsive to Inputs: The inputs from the users are the rich source of information that the app can get. The inputs can be either in the form of text, photos, or voices. The app has to be responsive to the inputs, as these help in identifying the user and behavior.
5. Cross-Platform Operation: The app also should have the ability to understand the common responses and process the desired output. Also, some of the features require cross-platform operations, which can help the app to understand the user better when working with cross platforms. The role of artificial intelligence comes into the picture, which organizes and processes the output in a way that the users feel the same experience while working on cross platforms.
Intelligent apps are so powerful that every sector can use these apps, but the major sectors which can use the advantage of such apps are as below:
1. Healthcare Sector: One of the most important and evergreen sectors, which faces new challenges every single day, the healthcare sector can surely take advantage of smart apps. Many AI-based learning models are being used to train machines about the sector and also many low-level cures are being done using the solutions provided by artificial intelligence. With the onset of the new decade, healthcare and intelligent apps are a perfect match for each other.
2. Education Sector: Education in its form has already started to use the benefits of intelligent apps. Due to more focus on digital education, the market is set to reach high numbers in terms of income and growth. Intelligent apps can be used to asses students and understand their behavior and learning patterns, upon which a better and personalized learning model can be introduced in the education system. Intelligent apps can be used to provide learning assistance based on an individual’s learning ability.
3. Finance Sector: The finance sector is one of the largest sectors to target for any developer or company which makes intelligent apps. Finance, when combined with technology, is called, Fin-tech. With the help of smart apps, the financing sector can reap rewards of potentially high profit and stabilized market. The intelligent apps can accurately predict the changes in the market based on the ongoing as well as past events, analyzing the companies and their profit ratio.
4. Food Businesses: Smart apps are heavily used by users to order foods, book a restaurant, checking the nearest restaurants and not only that these apps also suggest users the meals based on their previous choices and their interaction with the app. The mode of marketing and user acquisition is completely changed, not only the app companies, but restaurants are also making profits and acquiring customers from delivering food online.
5. Hospitality Sector: Using intelligent apps in the right way can help the hospitality sector in taking the right steps to deliver a better experience to the customers. Smart apps can monitor the way guests behave, their needs, & they can predict the adequate personalized experience and can use better ways of marketing the products and services.
surindertarika1234
Artificial Intelligence
GBlog
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 783,
"s": 28,
"text": "From the early 2000s, a series of development and modification into the existing mobile phones carved the smartphone that we all use today. It is capable of doing many of our tasks hence making it an essential component in our lives. With smartphones, apps come into existence that programs to perform a specific task or to provide a specific service. Over time, many advances and modern applications have been made, which are not only able to do single tasks but are multitasking as well as able to do many complex operations. With the emergence of Artificial Intelligence and Machine Learning, the viewpoint of developers and companies in the app market has completely changed. Apps that can be smarter and can learn from users who are much in demand. "
},
{
"code": null,
"e": 1048,
"s": 783,
"text": "With the growth and development in the artificial intelligence and machine learning industry, many technologies have emerged side by side using the later, as the foundation. We have been engulfed with these modern technologies and instruments, and so do the apps. "
},
{
"code": null,
"e": 1706,
"s": 1048,
"text": "In simple terms, intelligent apps are one which uses modern technologies such as artificial intelligence and machine learning & some part of reinforcement learning. These apps are not intended to perform the basic operation, rather used to perform complex tasks that can be automated with continued usage, as the app learns from the operational behavior of the users. These apps can provide personalized user experience combined with the adaptability and richness. Intelligent apps use to power of combined data organization, user predictability, prescriptive analytics, consumer data, and operational data, thus providing the users a very rich experience. "
},
{
"code": null,
"e": 1959,
"s": 1706,
"text": "Also termed as smart apps, developers, as well as many mobile app companies, have switched their focus from native-single-operational apps to intelligent apps. The app market is versatile and the technology changes that take place here are very rapid. "
},
{
"code": null,
"e": 2394,
"s": 1959,
"text": "1. Adaptive: Since the app will be used by thousands of users, the app is expected to be adaptive. Every user is different in their use, adaptability of the app plays a very crucial role. The use of machine learning helps the app to adapt to a common point where users share some of the similarities in their operations. In some apps, the use of reinforced learning is also being done, to produce a highly-satisfying user experience. "
},
{
"code": null,
"e": 2856,
"s": 2394,
"text": "2. Suggestive & Decision-Oriented: While working with a large number of users, the intelligent apps does not wait for the user to decide, rather helps the users to decide what suits best for them, using the user interaction and artificial intelligence. It gives prompt to the users, to opt for a certain decision, but the final decision remains with the user. But yes, these apps can heavily impact on how users choose their decision and interact with the app. "
},
{
"code": null,
"e": 3270,
"s": 2856,
"text": "3. Data Powered: Be it online data or offline data, intelligent apps are heavily dependent on data. Data is very essential for intelligence apps, as data serves as the warehouse of information. Most of these apps use online data and require an internet connection. These gather data from a variety of sources, such as online, user interaction, sensors, etc. & compile them, thus providing better user experience. "
},
{
"code": null,
"e": 3540,
"s": 3270,
"text": "4. Responsive to Inputs: The inputs from the users are the rich source of information that the app can get. The inputs can be either in the form of text, photos, or voices. The app has to be responsive to the inputs, as these help in identifying the user and behavior. "
},
{
"code": null,
"e": 4008,
"s": 3540,
"text": "5. Cross-Platform Operation: The app also should have the ability to understand the common responses and process the desired output. Also, some of the features require cross-platform operations, which can help the app to understand the user better when working with cross platforms. The role of artificial intelligence comes into the picture, which organizes and processes the output in a way that the users feel the same experience while working on cross platforms. "
},
{
"code": null,
"e": 4157,
"s": 4008,
"text": "Intelligent apps are so powerful that every sector can use these apps, but the major sectors which can use the advantage of such apps are as below: "
},
{
"code": null,
"e": 4621,
"s": 4157,
"text": "1. Healthcare Sector: One of the most important and evergreen sectors, which faces new challenges every single day, the healthcare sector can surely take advantage of smart apps. Many AI-based learning models are being used to train machines about the sector and also many low-level cures are being done using the solutions provided by artificial intelligence. With the onset of the new decade, healthcare and intelligent apps are a perfect match for each other. "
},
{
"code": null,
"e": 5135,
"s": 4621,
"text": "2. Education Sector: Education in its form has already started to use the benefits of intelligent apps. Due to more focus on digital education, the market is set to reach high numbers in terms of income and growth. Intelligent apps can be used to asses students and understand their behavior and learning patterns, upon which a better and personalized learning model can be introduced in the education system. Intelligent apps can be used to provide learning assistance based on an individual’s learning ability. "
},
{
"code": null,
"e": 5614,
"s": 5135,
"text": "3. Finance Sector: The finance sector is one of the largest sectors to target for any developer or company which makes intelligent apps. Finance, when combined with technology, is called, Fin-tech. With the help of smart apps, the financing sector can reap rewards of potentially high profit and stabilized market. The intelligent apps can accurately predict the changes in the market based on the ongoing as well as past events, analyzing the companies and their profit ratio. "
},
{
"code": null,
"e": 6053,
"s": 5614,
"text": "4. Food Businesses: Smart apps are heavily used by users to order foods, book a restaurant, checking the nearest restaurants and not only that these apps also suggest users the meals based on their previous choices and their interaction with the app. The mode of marketing and user acquisition is completely changed, not only the app companies, but restaurants are also making profits and acquiring customers from delivering food online. "
},
{
"code": null,
"e": 6403,
"s": 6053,
"text": "5. Hospitality Sector: Using intelligent apps in the right way can help the hospitality sector in taking the right steps to deliver a better experience to the customers. Smart apps can monitor the way guests behave, their needs, & they can predict the adequate personalized experience and can use better ways of marketing the products and services. "
},
{
"code": null,
"e": 6422,
"s": 6403,
"text": "surindertarika1234"
},
{
"code": null,
"e": 6446,
"s": 6422,
"text": "Artificial Intelligence"
},
{
"code": null,
"e": 6452,
"s": 6446,
"text": "GBlog"
}
] |
Impala - Group By Clause | The Impala GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups.
Following is the syntax of the GROUP BY clause.
select data from table_name Group BY col_name;
Assume we have a table named customers in the database my_db and its contents are as follows −
[quickstart.cloudera:21000] > select * from customers;
Query: select * from customers
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Khilan | 25 | Delhi | 15000 |
| 3 | kaushik | 23 | Kota | 30000 |
| 4 | Chaitali | 25 | Mumbai | 35000 |
| 5 | Hardik | 27 | Bhopal | 40000 |
| 6 | Komal | 22 | MP | 32000 |
+----+----------+-----+-----------+--------+
Fetched 6 row(s) in 0.51s
You can get the total amount of salary of each customer using GROUP BY query as shown below.
[quickstart.cloudera:21000] > Select name, sum(salary) from customers Group BY name;
On executing, the above query gives the following output.
Query: select name, sum(salary) from customers Group BY name
+----------+-------------+
| name | sum(salary) |
+----------+-------------+
| Ramesh | 20000 |
| Komal | 32000 |
| Hardik | 40000 |
| Khilan | 15000 |
| Chaitali | 35000 |
| kaushik | 30000 |
+----------+-------------+
Fetched 6 row(s) in 1.75s
Assume that this table has multiple records as shown below.
+----+----------+-----+-----------+--------+
| id | name | age | address | salary |
+----+----------+-----+-----------+--------+
| 1 | Ramesh | 32 | Ahmedabad | 20000 |
| 2 | Ramesh | 32 | Ahmedabad | 1000| |
| 3 | Khilan | 25 | Delhi | 15000 |
| 4 | kaushik | 23 | Kota | 30000 |
| 5 | Chaitali | 25 | Mumbai | 35000 |
| 6 | Chaitali | 25 | Mumbai | 2000 |
| 7 | Hardik | 27 | Bhopal | 40000 |
| 8 | Komal | 22 | MP | 32000 |
+----+----------+-----+-----------+--------+
Now again, you can get the total amount of salaries of the employees, considering the repeated entries of records, using the Group By clause as shown below.
Select name, sum(salary) from customers Group BY name;
On executing, the above query gives the following output.
Query: select name, sum(salary) from customers Group BY name
+----------+-------------+
| name | sum(salary) |
+----------+-------------+
| Ramesh | 21000 |
| Komal | 32000 |
| Hardik | 40000 |
| Khilan | 15000 |
| Chaitali | 37000 |
| kaushik | 30000 |
+----------+-------------+
Fetched 6 row(s) in 1.75s
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2402,
"s": 2285,
"text": "The Impala GROUP BY clause is used in collaboration with the SELECT statement to arrange identical data into groups."
},
{
"code": null,
"e": 2450,
"s": 2402,
"text": "Following is the syntax of the GROUP BY clause."
},
{
"code": null,
"e": 2498,
"s": 2450,
"text": "select data from table_name Group BY col_name;\n"
},
{
"code": null,
"e": 2593,
"s": 2498,
"text": "Assume we have a table named customers in the database my_db and its contents are as follows −"
},
{
"code": null,
"e": 3168,
"s": 2593,
"text": "[quickstart.cloudera:21000] > select * from customers; \nQuery: select * from customers \n+----+----------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+----------+-----+-----------+--------+ \n| 1 | Ramesh | 32 | Ahmedabad | 20000 | \n| 2 | Khilan | 25 | Delhi | 15000 | \n| 3 | kaushik | 23 | Kota | 30000 | \n| 4 | Chaitali | 25 | Mumbai | 35000 | \n| 5 | Hardik | 27 | Bhopal | 40000 | \n| 6 | Komal | 22 | MP | 32000 | \n+----+----------+-----+-----------+--------+ \nFetched 6 row(s) in 0.51s\n"
},
{
"code": null,
"e": 3261,
"s": 3168,
"text": "You can get the total amount of salary of each customer using GROUP BY query as shown below."
},
{
"code": null,
"e": 3347,
"s": 3261,
"text": "[quickstart.cloudera:21000] > Select name, sum(salary) from customers Group BY name;\n"
},
{
"code": null,
"e": 3405,
"s": 3347,
"text": "On executing, the above query gives the following output."
},
{
"code": null,
"e": 3773,
"s": 3405,
"text": "Query: select name, sum(salary) from customers Group BY name \n+----------+-------------+ \n| name | sum(salary) | \n+----------+-------------+ \n| Ramesh | 20000 | \n| Komal | 32000 | \n| Hardik | 40000 | \n| Khilan | 15000 | \n| Chaitali | 35000 | \n| kaushik | 30000 |\n+----------+-------------+ \nFetched 6 row(s) in 1.75s\n"
},
{
"code": null,
"e": 3833,
"s": 3773,
"text": "Assume that this table has multiple records as shown below."
},
{
"code": null,
"e": 4382,
"s": 3833,
"text": "+----+----------+-----+-----------+--------+ \n| id | name | age | address | salary | \n+----+----------+-----+-----------+--------+ \n| 1 | Ramesh | 32 | Ahmedabad | 20000 |\n| 2 | Ramesh | 32 | Ahmedabad | 1000| | \n| 3 | Khilan | 25 | Delhi | 15000 | \n| 4 | kaushik | 23 | Kota | 30000 | \n| 5 | Chaitali | 25 | Mumbai | 35000 |\n| 6 | Chaitali | 25 | Mumbai | 2000 |\n| 7 | Hardik | 27 | Bhopal | 40000 | \n| 8 | Komal | 22 | MP | 32000 | \n+----+----------+-----+-----------+--------+\n"
},
{
"code": null,
"e": 4539,
"s": 4382,
"text": "Now again, you can get the total amount of salaries of the employees, considering the repeated entries of records, using the Group By clause as shown below."
},
{
"code": null,
"e": 4595,
"s": 4539,
"text": "Select name, sum(salary) from customers Group BY name;\n"
},
{
"code": null,
"e": 4653,
"s": 4595,
"text": "On executing, the above query gives the following output."
},
{
"code": null,
"e": 5021,
"s": 4653,
"text": "Query: select name, sum(salary) from customers Group BY name \n+----------+-------------+ \n| name | sum(salary) | \n+----------+-------------+ \n| Ramesh | 21000 | \n| Komal | 32000 | \n| Hardik | 40000 | \n| Khilan | 15000 | \n| Chaitali | 37000 | \n| kaushik | 30000 | \n+----------+-------------+\nFetched 6 row(s) in 1.75s\n"
},
{
"code": null,
"e": 5028,
"s": 5021,
"text": " Print"
},
{
"code": null,
"e": 5039,
"s": 5028,
"text": " Add Notes"
}
] |
Android - Single Fragments | Single Frame Fragment
Single frame fragment is designed for small screen devices such as hand hold devices(mobiles) and it should be above android 3.0 version.
This example will explain you how to create your own Fragments. Here we will create two fragments and one of them will be used when device is in landscape mode and another fragment will be used in case of portrait mode. So let's follow the following steps to similar to what we followed while creating Hello World Example −
Following is the content of the modified main activity file MainActivity.java −
package com.example.myfragments;
import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.content.res.Configuration;
import android.os.Bundle;
public class MainActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Configuration config = getResources().getConfiguration();
FragmentManager fragmentManager = getFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
/**
* Check the device orientation and act accordingly
*/
if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {
/**
* Landscape mode of the device
*/
LM_Fragement ls_fragment = new LM_Fragement();
fragmentTransaction.replace(android.R.id.content, ls_fragment);
}else{
/**
* Portrait mode of the device
*/
PM_Fragement pm_fragment = new PM_Fragement();
fragmentTransaction.replace(android.R.id.content, pm_fragment);
}
fragmentTransaction.commit();
}
}
Create two fragment files LM_Fragement.java and PM_Fragment.java
Following is the content of LM_Fragement.java file −
package com.example.myfragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class LM_Fragement extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(R.layout.lm_fragment, container, false);
}
}
Following is the content of PM_Fragement.java file −
package com.example.myfragments;
import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
/**
* Created by TutorialsPoint7 on 8/23/2016.
*/
public class PM_Fragement extends Fragment {
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
/**
* Inflate the layout for this fragment
*/
return inflater.inflate(R.layout.pm_fragment, container, false);
}
}
Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory.
Following is the content of lm_fragement.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#7bae16">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/landscape_message"
android:textColor="#000000"
android:textSize="20px" />
<!-- More GUI components go here -->
</LinearLayout>
Following is the content of pm_fragment.xml file −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#666666">
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/portrait_message"
android:textColor="#000000"
android:textSize="20px" />
<!-- More GUI components go here -->
</LinearLayout>
Following will be the content of res/layout/activity_main.xml file which includes your fragments −
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="horizontal">
<fragment
android:name="com.example.fragments"
android:id="@+id/lm_fragment"
android:layout_weight="1"
android:layout_width="0dp"
android:layout_height="match_parent" />
<fragment
android:name="com.example.fragments"
android:id="@+id/pm_fragment"
android:layout_weight="2"
android:layout_width="0dp"
android:layout_height="match_parent" />
</LinearLayout>
Make sure you have following content of res/values/strings.xml file −
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">My Application</string>
<string name="landscape_message">This is Landscape mode fragment</string>
<string name="portrait_message">This is Portrait mode fragment></string>
</resources>
Let's try to run our modified MyFragments application we just created. I assume you had created your AVD while doing environment set-up. To run the app from Android Studio, open one of your project's activity files and click Run icon from the tool bar. Android Studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display Emulator window where you will click on Menu button to see the following window. Be patience because it may take sometime based on your computer speed −
To change the mode of the emulator screen, let's do the following −
fn+control+F11 on Mac to change the landscape to portrait and vice versa.
fn+control+F11 on Mac to change the landscape to portrait and vice versa.
ctrl+F11 on Windows.
ctrl+F11 on Windows.
ctrl+F11 on Linux.
ctrl+F11 on Linux.
Once you changed the mode, you will be able to see the GUI which you have implemented for landscape mode as below −
This way you can use same activity but different GUI's through different fragments. You can use different type of GUI components for different GUI's based on your requirements.
46 Lectures
7.5 hours
Aditya Dua
32 Lectures
3.5 hours
Sharad Kumar
9 Lectures
1 hours
Abhilash Nelson
14 Lectures
1.5 hours
Abhilash Nelson
15 Lectures
1.5 hours
Abhilash Nelson
10 Lectures
1 hours
Abhilash Nelson
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3629,
"s": 3607,
"text": "Single Frame Fragment"
},
{
"code": null,
"e": 3767,
"s": 3629,
"text": "Single frame fragment is designed for small screen devices such as hand hold devices(mobiles) and it should be above android 3.0 version."
},
{
"code": null,
"e": 4091,
"s": 3767,
"text": "This example will explain you how to create your own Fragments. Here we will create two fragments and one of them will be used when device is in landscape mode and another fragment will be used in case of portrait mode. So let's follow the following steps to similar to what we followed while creating Hello World Example −"
},
{
"code": null,
"e": 4171,
"s": 4091,
"text": "Following is the content of the modified main activity file MainActivity.java −"
},
{
"code": null,
"e": 5409,
"s": 4171,
"text": "package com.example.myfragments;\n\nimport android.app.Activity;\nimport android.app.FragmentManager;\nimport android.app.FragmentTransaction;\nimport android.content.res.Configuration;\nimport android.os.Bundle;\n\npublic class MainActivity extends Activity {\n\n /** Called when the activity is first created. */\n @Override\n public void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n Configuration config = getResources().getConfiguration();\n\n FragmentManager fragmentManager = getFragmentManager();\n FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();\n\n /**\n * Check the device orientation and act accordingly\n */\n\t\t\n if (config.orientation == Configuration.ORIENTATION_LANDSCAPE) {\n /**\n * Landscape mode of the device\n */\n LM_Fragement ls_fragment = new LM_Fragement();\n fragmentTransaction.replace(android.R.id.content, ls_fragment);\n }else{\n /**\n * Portrait mode of the device\n */\n PM_Fragement pm_fragment = new PM_Fragement();\n fragmentTransaction.replace(android.R.id.content, pm_fragment);\n }\n fragmentTransaction.commit();\n }\n\n}"
},
{
"code": null,
"e": 5474,
"s": 5409,
"text": "Create two fragment files LM_Fragement.java and PM_Fragment.java"
},
{
"code": null,
"e": 5527,
"s": 5474,
"text": "Following is the content of LM_Fragement.java file −"
},
{
"code": null,
"e": 6070,
"s": 5527,
"text": "package com.example.myfragments;\n\nimport android.app.Fragment;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\n\n/**\n * Created by TutorialsPoint7 on 8/23/2016.\n*/\n\npublic class LM_Fragement extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n /**\n * Inflate the layout for this fragment\n */\n return inflater.inflate(R.layout.lm_fragment, container, false);\n }\n}"
},
{
"code": null,
"e": 6123,
"s": 6070,
"text": "Following is the content of PM_Fragement.java file −"
},
{
"code": null,
"e": 6666,
"s": 6123,
"text": "package com.example.myfragments;\n\nimport android.app.Fragment;\nimport android.os.Bundle;\nimport android.view.LayoutInflater;\nimport android.view.View;\nimport android.view.ViewGroup;\n\n/**\n * Created by TutorialsPoint7 on 8/23/2016.\n*/\n\npublic class PM_Fragement extends Fragment {\n @Override\n public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {\n /**\n * Inflate the layout for this fragment\n */\n return inflater.inflate(R.layout.pm_fragment, container, false);\n }\n}"
},
{
"code": null,
"e": 6755,
"s": 6666,
"text": "Create two layout files lm_fragement.xml and pm_fragment.xml under res/layout directory."
},
{
"code": null,
"e": 6807,
"s": 6755,
"text": "Following is the content of lm_fragement.xml file −"
},
{
"code": null,
"e": 7355,
"s": 6807,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n <LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"vertical\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:background=\"#7bae16\">\n \n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/landscape_message\"\n android:textColor=\"#000000\"\n android:textSize=\"20px\" />\n\n<!-- More GUI components go here -->\n\n</LinearLayout>"
},
{
"code": null,
"e": 7406,
"s": 7355,
"text": "Following is the content of pm_fragment.xml file −"
},
{
"code": null,
"e": 7937,
"s": 7406,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout\n xmlns:android=\"http://schemas.android.com/apk/res/android\"\n android:orientation=\"horizontal\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:background=\"#666666\">\n \n <TextView\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"@string/portrait_message\"\n android:textColor=\"#000000\"\n android:textSize=\"20px\" />\n\n<!-- More GUI components go here -->\n\n</LinearLayout>"
},
{
"code": null,
"e": 8036,
"s": 7937,
"text": "Following will be the content of res/layout/activity_main.xml file which includes your fragments −"
},
{
"code": null,
"e": 8740,
"s": 8036,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<LinearLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n xmlns:tools=\"http://schemas.android.com/tools\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"fill_parent\"\n android:orientation=\"horizontal\">\n\n <fragment\n android:name=\"com.example.fragments\"\n android:id=\"@+id/lm_fragment\"\n android:layout_weight=\"1\"\n android:layout_width=\"0dp\"\n android:layout_height=\"match_parent\" />\n \n <fragment\n android:name=\"com.example.fragments\"\n android:id=\"@+id/pm_fragment\"\n android:layout_weight=\"2\"\n android:layout_width=\"0dp\"\n android:layout_height=\"match_parent\" />\n\n</LinearLayout>"
},
{
"code": null,
"e": 8810,
"s": 8740,
"text": "Make sure you have following content of res/values/strings.xml file −"
},
{
"code": null,
"e": 9078,
"s": 8810,
"text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n <string name=\"app_name\">My Application</string>\n <string name=\"landscape_message\">This is Landscape mode fragment</string>\n <string name=\"portrait_message\">This is Portrait mode fragment></string>\n</resources>"
},
{
"code": null,
"e": 9619,
"s": 9078,
"text": "Let's try to run our modified MyFragments application we just created. I assume you had created your AVD while doing environment set-up. To run the app from Android Studio, open one of your project's activity files and click Run icon from the tool bar. Android Studio installs the app on your AVD and starts it and if everything is fine with your set-up and application, it will display Emulator window where you will click on Menu button to see the following window. Be patience because it may take sometime based on your computer speed −"
},
{
"code": null,
"e": 9687,
"s": 9619,
"text": "To change the mode of the emulator screen, let's do the following −"
},
{
"code": null,
"e": 9761,
"s": 9687,
"text": "fn+control+F11 on Mac to change the landscape to portrait and vice versa."
},
{
"code": null,
"e": 9835,
"s": 9761,
"text": "fn+control+F11 on Mac to change the landscape to portrait and vice versa."
},
{
"code": null,
"e": 9856,
"s": 9835,
"text": "ctrl+F11 on Windows."
},
{
"code": null,
"e": 9877,
"s": 9856,
"text": "ctrl+F11 on Windows."
},
{
"code": null,
"e": 9896,
"s": 9877,
"text": "ctrl+F11 on Linux."
},
{
"code": null,
"e": 9915,
"s": 9896,
"text": "ctrl+F11 on Linux."
},
{
"code": null,
"e": 10031,
"s": 9915,
"text": "Once you changed the mode, you will be able to see the GUI which you have implemented for landscape mode as below −"
},
{
"code": null,
"e": 10208,
"s": 10031,
"text": "This way you can use same activity but different GUI's through different fragments. You can use different type of GUI components for different GUI's based on your requirements."
},
{
"code": null,
"e": 10243,
"s": 10208,
"text": "\n 46 Lectures \n 7.5 hours \n"
},
{
"code": null,
"e": 10255,
"s": 10243,
"text": " Aditya Dua"
},
{
"code": null,
"e": 10290,
"s": 10255,
"text": "\n 32 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 10304,
"s": 10290,
"text": " Sharad Kumar"
},
{
"code": null,
"e": 10336,
"s": 10304,
"text": "\n 9 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10353,
"s": 10336,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10388,
"s": 10353,
"text": "\n 14 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10405,
"s": 10388,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10440,
"s": 10405,
"text": "\n 15 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 10457,
"s": 10440,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10490,
"s": 10457,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 10507,
"s": 10490,
"text": " Abhilash Nelson"
},
{
"code": null,
"e": 10514,
"s": 10507,
"text": " Print"
},
{
"code": null,
"e": 10525,
"s": 10514,
"text": " Add Notes"
}
] |
How to change background color of Tkinter OptionMenu widget? - GeeksforGeeks | 16 Mar, 2021
Prerequisites: Tkinter
While creating GUI applications, there occur various instances in which you need to make selections among various options available. For making such choices, the Option Menu widget was introduced. In this article, we will be discussing the procedure of changing menu background color of Tkinter’s option Menu widget.
To achieve our required functionality a regular OptionMenu is first set up and then color is added and changed using config() method.
w = OptionMenu(app, #Options Menu widget name, “#Opton1”, “#Option2”, “#Option3”)
w.config(bg = “#Background Color of Options Menu”, fg=”#Text Color”)
OptionMenu() is used to create a dropdown menu
Syntax:
OptionMenu(master,options)
Parameters:
master: This parameter is used to represents the parent window.
options: Contain the Menu values
config() is used to set up the color change
Import module
Now, create a GUI app using tkinter
Next, give a title to the app(optional).
Then, create an Options Menu widget.
Moreover, create the Displayed Options for Options Menu widget.
Further, set the menu background color.
Assign the text you want to appear when Options Menu is not open
Set the background color of Displayed Options.
Display the Options Menu widget in GUI
Finally, make the loop for displaying the GUI app on the screen
Program:
Python
# Python program to change menu background# color of Tkinter's Option Menu # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give title to your GUI appapp.title("Vinayak App") # Construct the label in your appl1 = Label(app, text="Choose the the week day here") # Display the label l1l1.grid() # Construct the Options Menu widget in your apptext1 = StringVar() # Set the value you wish to see by defaulttext1.set("Choose here") # Create options from the Option Menuw = OptionMenu(app, text1, "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday") # Se the background color of Options Menu to greenw.config(bg="GREEN", fg="WHITE") # Set the background color of Displayed Options to Redw["menu"].config(bg="RED") # Display the Options Menuw.grid(pady=20) # Make the loop for displaying appapp.mainloop()
Output:
Picked
Python Tkinter-exercises
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Pandas dataframe.groupby()
Create a directory in Python
Defaultdict in Python
Python | Get unique values from a list | [
{
"code": null,
"e": 25673,
"s": 25645,
"text": "\n16 Mar, 2021"
},
{
"code": null,
"e": 25696,
"s": 25673,
"text": "Prerequisites: Tkinter"
},
{
"code": null,
"e": 26014,
"s": 25696,
"text": "While creating GUI applications, there occur various instances in which you need to make selections among various options available. For making such choices, the Option Menu widget was introduced. In this article, we will be discussing the procedure of changing menu background color of Tkinter’s option Menu widget. "
},
{
"code": null,
"e": 26148,
"s": 26014,
"text": "To achieve our required functionality a regular OptionMenu is first set up and then color is added and changed using config() method."
},
{
"code": null,
"e": 26230,
"s": 26148,
"text": "w = OptionMenu(app, #Options Menu widget name, “#Opton1”, “#Option2”, “#Option3”)"
},
{
"code": null,
"e": 26299,
"s": 26230,
"text": "w.config(bg = “#Background Color of Options Menu”, fg=”#Text Color”)"
},
{
"code": null,
"e": 26346,
"s": 26299,
"text": "OptionMenu() is used to create a dropdown menu"
},
{
"code": null,
"e": 26354,
"s": 26346,
"text": "Syntax:"
},
{
"code": null,
"e": 26381,
"s": 26354,
"text": "OptionMenu(master,options)"
},
{
"code": null,
"e": 26393,
"s": 26381,
"text": "Parameters:"
},
{
"code": null,
"e": 26457,
"s": 26393,
"text": "master: This parameter is used to represents the parent window."
},
{
"code": null,
"e": 26490,
"s": 26457,
"text": "options: Contain the Menu values"
},
{
"code": null,
"e": 26534,
"s": 26490,
"text": "config() is used to set up the color change"
},
{
"code": null,
"e": 26548,
"s": 26534,
"text": "Import module"
},
{
"code": null,
"e": 26584,
"s": 26548,
"text": "Now, create a GUI app using tkinter"
},
{
"code": null,
"e": 26625,
"s": 26584,
"text": "Next, give a title to the app(optional)."
},
{
"code": null,
"e": 26662,
"s": 26625,
"text": "Then, create an Options Menu widget."
},
{
"code": null,
"e": 26726,
"s": 26662,
"text": "Moreover, create the Displayed Options for Options Menu widget."
},
{
"code": null,
"e": 26766,
"s": 26726,
"text": "Further, set the menu background color."
},
{
"code": null,
"e": 26831,
"s": 26766,
"text": "Assign the text you want to appear when Options Menu is not open"
},
{
"code": null,
"e": 26878,
"s": 26831,
"text": "Set the background color of Displayed Options."
},
{
"code": null,
"e": 26917,
"s": 26878,
"text": "Display the Options Menu widget in GUI"
},
{
"code": null,
"e": 26981,
"s": 26917,
"text": "Finally, make the loop for displaying the GUI app on the screen"
},
{
"code": null,
"e": 26990,
"s": 26981,
"text": "Program:"
},
{
"code": null,
"e": 26997,
"s": 26990,
"text": "Python"
},
{
"code": "# Python program to change menu background# color of Tkinter's Option Menu # Import the library tkinterfrom tkinter import * # Create a GUI appapp = Tk() # Give title to your GUI appapp.title(\"Vinayak App\") # Construct the label in your appl1 = Label(app, text=\"Choose the the week day here\") # Display the label l1l1.grid() # Construct the Options Menu widget in your apptext1 = StringVar() # Set the value you wish to see by defaulttext1.set(\"Choose here\") # Create options from the Option Menuw = OptionMenu(app, text1, \"Sunday\", \"Monday\", \"Tuesday\", \"Wednesday\", \"Thursday\", \"Friday\", \"Saturday\") # Se the background color of Options Menu to greenw.config(bg=\"GREEN\", fg=\"WHITE\") # Set the background color of Displayed Options to Redw[\"menu\"].config(bg=\"RED\") # Display the Options Menuw.grid(pady=20) # Make the loop for displaying appapp.mainloop()",
"e": 27879,
"s": 26997,
"text": null
},
{
"code": null,
"e": 27887,
"s": 27879,
"text": "Output:"
},
{
"code": null,
"e": 27894,
"s": 27887,
"text": "Picked"
},
{
"code": null,
"e": 27919,
"s": 27894,
"text": "Python Tkinter-exercises"
},
{
"code": null,
"e": 27934,
"s": 27919,
"text": "Python-tkinter"
},
{
"code": null,
"e": 27941,
"s": 27934,
"text": "Python"
},
{
"code": null,
"e": 28039,
"s": 27941,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28071,
"s": 28039,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28113,
"s": 28071,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28155,
"s": 28113,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28211,
"s": 28155,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28238,
"s": 28211,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28269,
"s": 28238,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28305,
"s": 28269,
"text": "Python | Pandas dataframe.groupby()"
},
{
"code": null,
"e": 28334,
"s": 28305,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28356,
"s": 28334,
"text": "Defaultdict in Python"
}
] |
Program to find sum of series 1*2*3 + 2*3*4+ 3*4*5 + . . . + n*(n+1)*(n+2) - GeeksforGeeks | 25 Mar, 2021
Given a positive integer n and the task is to find the sum of series 1*2*3 + 2*3*4 + 4*5*6 + . . .+ n*(n+1)*(n+2).Examples:
Input : n = 10
Output : 4290
1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 + 5*6*7 + 6*7*8 +
7*8*9 + 8*9*10 + 9*10*11 + 10*11*12
= 6 + 24 + 60 + 120 + 210 + 336 + 504 +
720 + 990 + 1320
= 4290
Input : n = 7
Output : 1260
Method 1: In this case loop will run n times and calculate the sum.
C++
Java
Python3
C#
PHP
Javascript
// Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)#include <bits/stdc++.h>using namespace std;// Function to calculate sum of series.int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum;} // Driver functionint main(){ int n = 10; cout << sumOfSeries(n); return 0;}
// Java Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)public class GfG{ // Function to calculate sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum; } // Driver Code public static void main(String s[]) { int n = 10; System.out.println(sumOfSeries(n)); }} // This article is contributed by Gitanjali.
# Python program to find the# sum of series# 1*2*3 + 2*3*4 + . . .# + n*(n+1)*(n+1) # Function to calculate sum# of series.def sumOfSeries(n): sum = 0; i = 1; while i<=n: sum = sum + i * (i + 1) * ( i + 2) i = i + 1 return sum # Driver coden = 10print(sumOfSeries(n)) # This code is contributed by "Abhishek Sharma 44"
// C# Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)using System; public class GfG{ // Function to calculate sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum; } // Driver Code public static void Main() { int n = 10; Console.WriteLine(sumOfSeries(n)); }} // This article is contributed by vt_m.
<?php// PHP Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1) // Function to calculate sum of series.function sumOfSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + $i * ($i + 1) * ($i + 2); return $sum;} // Driver Code$n = 10;echo sumOfSeries($n); // This code is contributed by vt_m.?>
<script> // Javascript Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1) // Function to calculate sum of series. function sumOfSeries( n) { let sum = 0; for ( let i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum; } // Driver Code let n = 10; document.write(sumOfSeries(n)); // This code contributed by Princi Singh </script>
Output:
4290
Time Complexity: O(n)Method 2: In this case we use formula to add sum of series.
Given series 1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 + . . . + n*(n+1)*(n+2)
sum of series = (n * (n+1) * (n+2) * (n+3)) / 4
Put n = 10 then
sum = (10 * (10+1) * (10+2) * (10+3)) / 4
= (10 * 11 * 12 * 13) / 4
= 4290
C++
Java
Python3
C#
PHP
Javascript
// Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)#include <bits/stdc++.h>using namespace std; // Function to calculate sum of series.int sumOfSeries(int n){ return (n * (n + 1) * (n + 2) * (n + 3)) / 4;} // Driver functionint main(){ int n = 10; cout << sumOfSeries(n); return 0;}
// Program to find the// sum of series// 1*2*3 + 2*3*4 +// . . . + n*(n+1)*(n+1)import java.io.*; class GFG { // Function to calculate // sum of series. static int sumOfSeries(int n) { return (n * (n + 1) * (n + 2) * (n + 3)) / 4; } // Driver function public static void main (String[] args) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Nikita Tiwari.
# Python program to find the# sum of series# 1*2*3 + 2*3*4 + . . .# + n*(n+1)*(n+1) # Function to calculate sum# of series.def sumOfSeries(n): return (n * (n + 1) * (n + 2 ) * (n + 3)) / 4 #Driver coden = 10print(sumOfSeries(n)) # This code is contributed by "Abhishek Sharma 44"
// Program to find the// sum of series// 1*2*3 + 2*3*4 +// . . . + n*(n+1)*(n+1)using System; class GFG { // Function to calculate // sum of series. static int sumOfSeries(int n) { return (n * (n + 1) * (n + 2) * (n + 3)) / 4; } // Driver function public static void Main () { int n = 10; Console.WriteLine(sumOfSeries(n)); }} // This code is contributed by vt_m.
<?php// PHP Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1) // Function to calculate sum of series.function sumOfSeries($n){ return ($n * ($n + 1) * ($n + 2) * ($n + 3)) / 4;} // Driver Code$n = 10;echo sumOfSeries($n); // This code is contributed by vt_m.?>
<script>// Program to find the// sum of series// 1*2*3 + 2*3*4 +// . . . + n*(n+1)*(n+1) // Function to calculate // sum of series. function sumOfSeries(n) { return (n * (n + 1) * (n + 2) * (n + 3)) / 4; } // Driver function var n = 10; document.write(sumOfSeries(n)); // This code is contributed by Amit Katiyar</script>
Output:
4290
Time Complexity: O(1)How does this formula work?
We can prove working of this formula using
mathematical induction.
According to formula, sum of (k -1) terms is
((k - 1) * (k) * (k + 1) * (k + 2)) / 4
Sum of k terms
= sum of k-1 terms + value of k-th term
= ((k - 1) * (k) * (k + 1) * (k + 2)) / 4 +
k * (k + 1) * (k + 2)
Taking common term (k + 1) * (k + 2) out.
= (k + 1)*(k + 2) [k*(k-1)/4 + k]
= (k + 1)*(k + 2) * k * (k + 3)/4
= k * (k + 1) * (k + 2) * (k + 3)/4
vt_m
princi singh
amit143katiyar
number-theory
series
Mathematical
number-theory
Mathematical
series
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Program to print prime numbers from 1 to N.
Modular multiplicative inverse
Fizz Buzz Implementation
Singular Value Decomposition (SVD)
Check if a number is Palindrome
Segment Tree | Set 1 (Sum of given range)
How to check if a given point lies inside or outside a polygon?
Program to multiply two matrices
Count ways to reach the n'th stair
Merge two sorted arrays with O(1) extra space | [
{
"code": null,
"e": 26071,
"s": 26043,
"text": "\n25 Mar, 2021"
},
{
"code": null,
"e": 26197,
"s": 26071,
"text": "Given a positive integer n and the task is to find the sum of series 1*2*3 + 2*3*4 + 4*5*6 + . . .+ n*(n+1)*(n+2).Examples: "
},
{
"code": null,
"e": 26416,
"s": 26197,
"text": "Input : n = 10\nOutput : 4290\n 1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 + 5*6*7 + 6*7*8 + \n 7*8*9 + 8*9*10 + 9*10*11 + 10*11*12\n = 6 + 24 + 60 + 120 + 210 + 336 + 504 + \n 720 + 990 + 1320\n = 4290\n\nInput : n = 7\nOutput : 1260"
},
{
"code": null,
"e": 26488,
"s": 26418,
"text": "Method 1: In this case loop will run n times and calculate the sum. "
},
{
"code": null,
"e": 26492,
"s": 26488,
"text": "C++"
},
{
"code": null,
"e": 26497,
"s": 26492,
"text": "Java"
},
{
"code": null,
"e": 26505,
"s": 26497,
"text": "Python3"
},
{
"code": null,
"e": 26508,
"s": 26505,
"text": "C#"
},
{
"code": null,
"e": 26512,
"s": 26508,
"text": "PHP"
},
{
"code": null,
"e": 26523,
"s": 26512,
"text": "Javascript"
},
{
"code": "// Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)#include <bits/stdc++.h>using namespace std;// Function to calculate sum of series.int sumOfSeries(int n){ int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum;} // Driver functionint main(){ int n = 10; cout << sumOfSeries(n); return 0;}",
"e": 26898,
"s": 26523,
"text": null
},
{
"code": "// Java Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)public class GfG{ // Function to calculate sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum; } // Driver Code public static void main(String s[]) { int n = 10; System.out.println(sumOfSeries(n)); }} // This article is contributed by Gitanjali.",
"e": 27383,
"s": 26898,
"text": null
},
{
"code": "# Python program to find the# sum of series# 1*2*3 + 2*3*4 + . . .# + n*(n+1)*(n+1) # Function to calculate sum# of series.def sumOfSeries(n): sum = 0; i = 1; while i<=n: sum = sum + i * (i + 1) * ( i + 2) i = i + 1 return sum # Driver coden = 10print(sumOfSeries(n)) # This code is contributed by \"Abhishek Sharma 44\"",
"e": 27759,
"s": 27383,
"text": null
},
{
"code": "// C# Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)using System; public class GfG{ // Function to calculate sum of series. static int sumOfSeries(int n) { int sum = 0; for (int i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum; } // Driver Code public static void Main() { int n = 10; Console.WriteLine(sumOfSeries(n)); }} // This article is contributed by vt_m.",
"e": 28240,
"s": 27759,
"text": null
},
{
"code": "<?php// PHP Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1) // Function to calculate sum of series.function sumOfSeries($n){ $sum = 0; for ($i = 1; $i <= $n; $i++) $sum = $sum + $i * ($i + 1) * ($i + 2); return $sum;} // Driver Code$n = 10;echo sumOfSeries($n); // This code is contributed by vt_m.?>",
"e": 28609,
"s": 28240,
"text": null
},
{
"code": "<script> // Javascript Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1) // Function to calculate sum of series. function sumOfSeries( n) { let sum = 0; for ( let i = 1; i <= n; i++) sum = sum + i * (i + 1) * (i + 2); return sum; } // Driver Code let n = 10; document.write(sumOfSeries(n)); // This code contributed by Princi Singh </script>",
"e": 29033,
"s": 28609,
"text": null
},
{
"code": null,
"e": 29042,
"s": 29033,
"text": "Output: "
},
{
"code": null,
"e": 29047,
"s": 29042,
"text": "4290"
},
{
"code": null,
"e": 29130,
"s": 29047,
"text": "Time Complexity: O(n)Method 2: In this case we use formula to add sum of series. "
},
{
"code": null,
"e": 29354,
"s": 29130,
"text": " Given series 1*2*3 + 2*3*4 + 3*4*5 + 4*5*6 + . . . + n*(n+1)*(n+2)\n sum of series = (n * (n+1) * (n+2) * (n+3)) / 4 \n \n Put n = 10 then \n sum = (10 * (10+1) * (10+2) * (10+3)) / 4\n = (10 * 11 * 12 * 13) / 4\n = 4290"
},
{
"code": null,
"e": 29360,
"s": 29356,
"text": "C++"
},
{
"code": null,
"e": 29365,
"s": 29360,
"text": "Java"
},
{
"code": null,
"e": 29373,
"s": 29365,
"text": "Python3"
},
{
"code": null,
"e": 29376,
"s": 29373,
"text": "C#"
},
{
"code": null,
"e": 29380,
"s": 29376,
"text": "PHP"
},
{
"code": null,
"e": 29391,
"s": 29380,
"text": "Javascript"
},
{
"code": "// Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1)#include <bits/stdc++.h>using namespace std; // Function to calculate sum of series.int sumOfSeries(int n){ return (n * (n + 1) * (n + 2) * (n + 3)) / 4;} // Driver functionint main(){ int n = 10; cout << sumOfSeries(n); return 0;}",
"e": 29711,
"s": 29391,
"text": null
},
{
"code": "// Program to find the// sum of series// 1*2*3 + 2*3*4 +// . . . + n*(n+1)*(n+1)import java.io.*; class GFG { // Function to calculate // sum of series. static int sumOfSeries(int n) { return (n * (n + 1) * (n + 2) * (n + 3)) / 4; } // Driver function public static void main (String[] args) { int n = 10; System.out.println(sumOfSeries(n)); }} // This code is contributed by Nikita Tiwari.",
"e": 30173,
"s": 29711,
"text": null
},
{
"code": "# Python program to find the# sum of series# 1*2*3 + 2*3*4 + . . .# + n*(n+1)*(n+1) # Function to calculate sum# of series.def sumOfSeries(n): return (n * (n + 1) * (n + 2 ) * (n + 3)) / 4 #Driver coden = 10print(sumOfSeries(n)) # This code is contributed by \"Abhishek Sharma 44\"",
"e": 30475,
"s": 30173,
"text": null
},
{
"code": "// Program to find the// sum of series// 1*2*3 + 2*3*4 +// . . . + n*(n+1)*(n+1)using System; class GFG { // Function to calculate // sum of series. static int sumOfSeries(int n) { return (n * (n + 1) * (n + 2) * (n + 3)) / 4; } // Driver function public static void Main () { int n = 10; Console.WriteLine(sumOfSeries(n)); }} // This code is contributed by vt_m.",
"e": 30910,
"s": 30475,
"text": null
},
{
"code": "<?php// PHP Program to find the sum of series// 1*2*3 + 2*3*4 + . . . + n*(n+1)*(n+1) // Function to calculate sum of series.function sumOfSeries($n){ return ($n * ($n + 1) * ($n + 2) * ($n + 3)) / 4;} // Driver Code$n = 10;echo sumOfSeries($n); // This code is contributed by vt_m.?>",
"e": 31222,
"s": 30910,
"text": null
},
{
"code": "<script>// Program to find the// sum of series// 1*2*3 + 2*3*4 +// . . . + n*(n+1)*(n+1) // Function to calculate // sum of series. function sumOfSeries(n) { return (n * (n + 1) * (n + 2) * (n + 3)) / 4; } // Driver function var n = 10; document.write(sumOfSeries(n)); // This code is contributed by Amit Katiyar</script>",
"e": 31574,
"s": 31222,
"text": null
},
{
"code": null,
"e": 31584,
"s": 31574,
"text": "Output: "
},
{
"code": null,
"e": 31589,
"s": 31584,
"text": "4290"
},
{
"code": null,
"e": 31638,
"s": 31589,
"text": "Time Complexity: O(1)How does this formula work?"
},
{
"code": null,
"e": 32148,
"s": 31638,
"text": "We can prove working of this formula using\nmathematical induction.\n\nAccording to formula, sum of (k -1) terms is\n((k - 1) * (k) * (k + 1) * (k + 2)) / 4\n\nSum of k terms\n = sum of k-1 terms + value of k-th term\n = ((k - 1) * (k) * (k + 1) * (k + 2)) / 4 + \n k * (k + 1) * (k + 2)\nTaking common term (k + 1) * (k + 2) out.\n = (k + 1)*(k + 2) [k*(k-1)/4 + k]\n = (k + 1)*(k + 2) * k * (k + 3)/4\n = k * (k + 1) * (k + 2) * (k + 3)/4"
},
{
"code": null,
"e": 32155,
"s": 32150,
"text": "vt_m"
},
{
"code": null,
"e": 32168,
"s": 32155,
"text": "princi singh"
},
{
"code": null,
"e": 32183,
"s": 32168,
"text": "amit143katiyar"
},
{
"code": null,
"e": 32197,
"s": 32183,
"text": "number-theory"
},
{
"code": null,
"e": 32204,
"s": 32197,
"text": "series"
},
{
"code": null,
"e": 32217,
"s": 32204,
"text": "Mathematical"
},
{
"code": null,
"e": 32231,
"s": 32217,
"text": "number-theory"
},
{
"code": null,
"e": 32244,
"s": 32231,
"text": "Mathematical"
},
{
"code": null,
"e": 32251,
"s": 32244,
"text": "series"
},
{
"code": null,
"e": 32349,
"s": 32251,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 32393,
"s": 32349,
"text": "Program to print prime numbers from 1 to N."
},
{
"code": null,
"e": 32424,
"s": 32393,
"text": "Modular multiplicative inverse"
},
{
"code": null,
"e": 32449,
"s": 32424,
"text": "Fizz Buzz Implementation"
},
{
"code": null,
"e": 32484,
"s": 32449,
"text": "Singular Value Decomposition (SVD)"
},
{
"code": null,
"e": 32516,
"s": 32484,
"text": "Check if a number is Palindrome"
},
{
"code": null,
"e": 32558,
"s": 32516,
"text": "Segment Tree | Set 1 (Sum of given range)"
},
{
"code": null,
"e": 32622,
"s": 32558,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 32655,
"s": 32622,
"text": "Program to multiply two matrices"
},
{
"code": null,
"e": 32690,
"s": 32655,
"text": "Count ways to reach the n'th stair"
}
] |
Maximum sum rectangle in a 2D matrix | DP-27 - GeeksforGeeks | 11 Nov, 2021
Given a 2D array, find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29.
This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array.
The Naive Solution for this problem is to check every possible rectangle in the given 2D array. This solution requires 6 nested loops –
4 for start and end coordinate of the 2 axis O(n4)
and 2 for the summation of the sub-matrix O(n2).
The overall time complexity of this solution would be O(n6).
Efficient Approach – Kadane’s algorithm for 1D array can be used to reduce the time complexity to O(n^3). The idea is to fix the left and right columns one by one and find the maximum sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have maximum sum) for every fixed left and right column pair. To find the top and bottom row numbers, calculate the sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i. If we apply Kadane’s 1D algorithm on temp[], and get the maximum sum subarray of temp, this maximum sum would be the maximum possible sum with left and right as boundary columns. To get the overall maximum sum, we compare this sum with the maximum sum so far.
C++
C
Java
Python3
C#
Javascript
// Program to find maximum sum subarray// in a given 2D array#include <bits/stdc++.h>using namespace std; #define ROW 4#define COL 5 // Implementation of Kadane's algorithm for// 1D array. The function returns the maximum// sum and stores starting and ending indexes// of the maximum sum subarray at addresses// pointed by start and finish pointers// respectively.int kadane(int* arr, int* start, int* finish, int n){ // initialize sum, maxSum and int sum = 0, maxSum = INT_MIN, i; // Just some initial value to check // for all negative values case *finish = -1; // local variable int local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; *start = local_start; *finish = i; } } // There is at-least one // non-negative number if (*finish != -1) return maxSum; // Special Case: When all numbers // in arr[] are negative maxSum = arr[0]; *start = *finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; *start = *finish = i; } } return maxSum;} // The main function that finds// maximum sum rectangle in M[][]void findMaxSum(int M[][COL]){ // Variables to store the final output int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; int left, right, i; int temp[ROW], sum, start, finish; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left // column set by outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values // of start and finish. So 'sum' is sum of // rectangle between (start, left) and // (finish, right) which is the maximum sum // with boundary columns strictly as left // and right. sum = kadane(temp, &start, &finish, ROW); // Compare sum with maximum sum so far. // If sum is more, then update maxSum and // other output values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values cout << "(Top, Left) (" << finalTop << ", " << finalLeft << ")" << endl; cout << "(Bottom, Right) (" << finalBottom << ", " << finalRight << ")" << endl; cout << "Max sum is: " << maxSum << endl;} // Driver Codeint main(){ int M[ROW][COL] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSum(M); return 0;} // This code is contributed by// rathbhupendra
// Program to find maximum sum subarray// in a given 2D array#include <limits.h>#include <stdio.h>#include <string.h>#define ROW 4#define COL 5 // Implementation of Kadane's algorithm// for 1D array. The function returns the// maximum sum and stores starting and// ending indexes of the maximum sum subarray// at addresses pointed by start and finish// pointers respectively.int kadane(int* arr, int* start, int* finish, int n){ // initialize sum, maxSum and int sum = 0, maxSum = INT_MIN, i; // Just some initial value to check for all negative // values case *finish = -1; // local variable int local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; *start = local_start; *finish = i; } } // There is at-least one non-negative number if (*finish != -1) return maxSum; // Special Case: When all numbers in arr[] // are negative maxSum = arr[0]; *start = *finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; *start = *finish = i; } } return maxSum;} // The main function that finds maximum// sum rectangle in// M[][]void findMaxSum(int M[][COL]){ // Variables to store the final output int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; int left, right, i; int temp[ROW], sum, start, finish; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left column set by // outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left and right // for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values of // start and finish. So 'sum' is sum of // rectangle between (start, left) and (finish, // right) which is the maximum sum with boundary // columns strictly as left and right. sum = kadane(temp, &start, &finish, ROW); // Compare sum with maximum sum so far. If sum // is more, then update maxSum and other output // values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values printf("(Top, Left) (%d, %d)\n", finalTop, finalLeft); printf("(Bottom, Right) (%d, %d)\n", finalBottom, finalRight); printf("Max sum is: %d\n", maxSum);} // Driver Codeint main(){ int M[ROW][COL] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSum(M); return 0;}
// Java Program to find max sum rectangular submatrix import java.util.*;import java.lang.*;import java.io.*; class MaximumSumRectangle{ // Function to find maximum sum rectangular // submatrix private static int maxSumRectangle(int[][] mat) { int m = mat.length; int n = mat[0].length; int preSum[][] = new int[m + 1][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { preSum[i + 1][j] = preSum[i][j] + mat[i][j]; } } int maxSum = -1; int minSum = Integer.MIN_VALUE; int negRow = 0, negCol = 0; int rStart = 0, rEnd = 0, cStart = 0, cEnd = 0; for (int rowStart = 0; rowStart < m; rowStart++) { for (int row = rowStart; row < m; row++) { int sum = 0; int curColStart = 0; for (int col = 0; col < n; col++) { sum += preSum[row + 1][col] - preSum[rowStart][col]; if (sum < 0) { if (minSum < sum) { minSum = sum; negRow = row; negCol = col; } sum = 0; curColStart = col + 1; } else if (maxSum < sum) { maxSum = sum; rStart = rowStart; rEnd = row; cStart = curColStart; cEnd = col; } } } } // Printing final values if (maxSum == -1) { System.out.println("from row - " + negRow + " to row - " + negRow); System.out.println("from col - " + negCol + " to col - " + negCol); } else { System.out.println("from row - " + rStart + " to row - " + rEnd); System.out.println("from col - " + cStart + " to col - " + cEnd); } return maxSum == -1 ? minSum : maxSum; } // Driver Code public static void main(String[] args) { int arr[][] = new int[][] { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call System.out.println(maxSumRectangle(arr)); }} // This code is contributed by Nayanava De
# Python3 program to find maximum sum# subarray in a given 2D array # Implementation of Kadane's algorithm# for 1D array. The function returns the# maximum sum and stores starting and# ending indexes of the maximum sum subarray# at addresses pointed by start and finish# pointers respectively. def kadane(arr, start, finish, n): # initialize sum, maxSum and Sum = 0 maxSum = -999999999999 i = None # Just some initial value to check # for all negative values case finish[0] = -1 # local variable local_start = 0 for i in range(n): Sum += arr[i] if Sum < 0: Sum = 0 local_start = i + 1 elif Sum > maxSum: maxSum = Sum start[0] = local_start finish[0] = i # There is at-least one # non-negative number if finish[0] != -1: return maxSum # Special Case: When all numbers # in arr[] are negative maxSum = arr[0] start[0] = finish[0] = 0 # Find the maximum element in array for i in range(1, n): if arr[i] > maxSum: maxSum = arr[i] start[0] = finish[0] = i return maxSum # The main function that finds maximum# sum rectangle in M[][] def findMaxSum(M): global ROW, COL # Variables to store the final output maxSum, finalLeft = -999999999999, None finalRight, finalTop, finalBottom = None, None, None left, right, i = None, None, None temp = [None] * ROW Sum = 0 start = [0] finish = [0] # Set the left column for left in range(COL): # Initialize all elements of temp as 0 temp = [0] * ROW # Set the right column for the left # column set by outer loop for right in range(left, COL): # Calculate sum between current left # and right for every row 'i' for i in range(ROW): temp[i] += M[i][right] # Find the maximum sum subarray in # temp[]. The kadane() function also # sets values of start and finish. # So 'sum' is sum of rectangle between # (start, left) and (finish, right) which # is the maximum sum with boundary columns # strictly as left and right. Sum = kadane(temp, start, finish, ROW) # Compare sum with maximum sum so far. # If sum is more, then update maxSum # and other output values if Sum > maxSum: maxSum = Sum finalLeft = left finalRight = right finalTop = start[0] finalBottom = finish[0] # Prfinal values print("(Top, Left)", "(", finalTop, finalLeft, ")") print("(Bottom, Right)", "(", finalBottom, finalRight, ")") print("Max sum is:", maxSum) # Driver CodeROW = 4COL = 5M = [[1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6]] # Function callfindMaxSum(M) # This code is contributed by PranchalK
// C# Given a 2D array, find the// maximum sum subarray in itusing System; class GFG { /** * To find maxSum in 1d array * * return {maxSum, left, right} */ public static int[] kadane(int[] a) { int[] result = new int[] { int.MinValue, 0, -1 }; int currentSum = 0; int localStart = 0; for (int i = 0; i < a.Length; i++) { currentSum += a[i]; if (currentSum < 0) { currentSum = 0; localStart = i + 1; } else if (currentSum > result[0]) { result[0] = currentSum; result[1] = localStart; result[2] = i; } } // all numbers in a are negative if (result[2] == -1) { result[0] = 0; for (int i = 0; i < a.Length; i++) { if (a[i] > result[0]) { result[0] = a[i]; result[1] = i; result[2] = i; } } } return result; } /** * To find and print maxSum, (left, top),(right, bottom) */ public static void findMaxSubMatrix(int[, ] a) { int cols = a.GetLength(1); int rows = a.GetLength(0); int[] currentResult; int maxSum = int.MinValue; int left = 0; int top = 0; int right = 0; int bottom = 0; for (int leftCol = 0; leftCol < cols; leftCol++) { int[] tmp = new int[rows]; for (int rightCol = leftCol; rightCol < cols; rightCol++) { for (int i = 0; i < rows; i++) { tmp[i] += a[i, rightCol]; } currentResult = kadane(tmp); if (currentResult[0] > maxSum) { maxSum = currentResult[0]; left = leftCol; top = currentResult[1]; right = rightCol; bottom = currentResult[2]; } } } Console.Write("MaxSum: " + maxSum + ", range: [(" + left + ", " + top + ")(" + right + ", " + bottom + ")]"); } // Driver Code public static void Main() { int[, ] arr = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSubMatrix(arr); }} // This code is contributed// by PrinciRaj1992
<script> // Program to find maximum sum subarray// in a given 2D array var ROW = 4var COL = 5var start = 0var finish = 0 // Implementation of Kadane's algorithm for// 1D array. The function returns the maximum// sum and stores starting and ending indexes// of the maximum sum subarray at addresses// pointed by start and finish pointers// respectively.function kadane(arr, n){ // initialize sum, maxSum and var sum = 0, maxSum = -1000000000, i; // Just some initial value to check // for all negative values case finish = -1; // local variable var local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; start = local_start; finish = i; } } // There is at-least one // non-negative number if (finish != -1) return maxSum; // Special Case: When all numbers // in arr[] are negative maxSum = arr[0]; start = finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; start = finish = i; } } return maxSum;} // The main function that finds// maximum sum rectangle in M[][]function findMaxSum(M){ // Variables to store the final output var maxSum = -1000000000, finalLeft=0, finalRight=0, finalTop=0, finalBottom=0; var left, right, i; var temp = Array(ROW); var sum; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 temp = Array(ROW).fill(0); // Set the right column for the left // column set by outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values // of start and finish. So 'sum' is sum of // rectangle between (start, left) and // (finish, right) which is the maximum sum // with boundary columns strictly as left // and right. sum = kadane(temp, ROW); // Compare sum with maximum sum so far. // If sum is more, then update maxSum and // other output values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values document.write("(Top, Left) (" + finalTop + ", " + finalLeft + ")" + "<br>"); document.write("(Bottom, Right) (" + finalBottom + ", " + finalRight + ")" + "<br>"); document.write("Max sum is: " + maxSum + "<br>");} // Driver Codevar M = [ [ 1, 2, -1, -4, -20 ], [ -8, -3, 4, 2, 1 ], [ 3, 8, 10, 1, 3 ], [ -4, -1, 1, 7, -6 ] ];// Function callfindMaxSum(M); // This code is contributed by rutvik_56.</script>
(Top, Left) (1, 1)
(Bottom, Right) (3, 3)
Max sum is: 29
Time Complexity: O(n3)
This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Gaurav Kumar 33
princiraj1992
PranchalKatiyar
rathbhupendra
tonyshen
kushagra98
uchiha1101
rutvik_56
Accolite
Amazon
FactSet
Samsung
Arrays
Dynamic Programming
Matrix
Misc
Accolite
Amazon
Samsung
FactSet
Misc
Arrays
Dynamic Programming
Misc
Matrix
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Maximum and minimum of an array using minimum number of comparisons
Top 50 Array Coding Problems for Interviews
Stack Data Structure (Introduction and Program)
Introduction to Arrays
Multidimensional Arrays in Java
0-1 Knapsack Problem | DP-10
Program for Fibonacci numbers
Longest Common Subsequence | DP-4
Bellman–Ford Algorithm | DP-23
Floyd Warshall Algorithm | DP-16 | [
{
"code": null,
"e": 25290,
"s": 25262,
"text": "\n11 Nov, 2021"
},
{
"code": null,
"e": 25477,
"s": 25290,
"text": "Given a 2D array, find the maximum sum subarray in it. For example, in the following 2D array, the maximum sum subarray is highlighted with blue rectangle and sum of this subarray is 29."
},
{
"code": null,
"e": 25564,
"s": 25477,
"text": "This problem is mainly an extension of Largest Sum Contiguous Subarray for 1D array. "
},
{
"code": null,
"e": 25702,
"s": 25564,
"text": "The Naive Solution for this problem is to check every possible rectangle in the given 2D array. This solution requires 6 nested loops – "
},
{
"code": null,
"e": 25753,
"s": 25702,
"text": "4 for start and end coordinate of the 2 axis O(n4)"
},
{
"code": null,
"e": 25802,
"s": 25753,
"text": "and 2 for the summation of the sub-matrix O(n2)."
},
{
"code": null,
"e": 25863,
"s": 25802,
"text": "The overall time complexity of this solution would be O(n6)."
},
{
"code": null,
"e": 26692,
"s": 25863,
"text": "Efficient Approach – Kadane’s algorithm for 1D array can be used to reduce the time complexity to O(n^3). The idea is to fix the left and right columns one by one and find the maximum sum contiguous rows for every left and right column pair. We basically find top and bottom row numbers (which have maximum sum) for every fixed left and right column pair. To find the top and bottom row numbers, calculate the sum of elements in every row from left to right and store these sums in an array say temp[]. So temp[i] indicates sum of elements from left to right in row i. If we apply Kadane’s 1D algorithm on temp[], and get the maximum sum subarray of temp, this maximum sum would be the maximum possible sum with left and right as boundary columns. To get the overall maximum sum, we compare this sum with the maximum sum so far."
},
{
"code": null,
"e": 26696,
"s": 26692,
"text": "C++"
},
{
"code": null,
"e": 26698,
"s": 26696,
"text": "C"
},
{
"code": null,
"e": 26703,
"s": 26698,
"text": "Java"
},
{
"code": null,
"e": 26711,
"s": 26703,
"text": "Python3"
},
{
"code": null,
"e": 26714,
"s": 26711,
"text": "C#"
},
{
"code": null,
"e": 26725,
"s": 26714,
"text": "Javascript"
},
{
"code": "// Program to find maximum sum subarray// in a given 2D array#include <bits/stdc++.h>using namespace std; #define ROW 4#define COL 5 // Implementation of Kadane's algorithm for// 1D array. The function returns the maximum// sum and stores starting and ending indexes// of the maximum sum subarray at addresses// pointed by start and finish pointers// respectively.int kadane(int* arr, int* start, int* finish, int n){ // initialize sum, maxSum and int sum = 0, maxSum = INT_MIN, i; // Just some initial value to check // for all negative values case *finish = -1; // local variable int local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; *start = local_start; *finish = i; } } // There is at-least one // non-negative number if (*finish != -1) return maxSum; // Special Case: When all numbers // in arr[] are negative maxSum = arr[0]; *start = *finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; *start = *finish = i; } } return maxSum;} // The main function that finds// maximum sum rectangle in M[][]void findMaxSum(int M[][COL]){ // Variables to store the final output int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; int left, right, i; int temp[ROW], sum, start, finish; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left // column set by outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values // of start and finish. So 'sum' is sum of // rectangle between (start, left) and // (finish, right) which is the maximum sum // with boundary columns strictly as left // and right. sum = kadane(temp, &start, &finish, ROW); // Compare sum with maximum sum so far. // If sum is more, then update maxSum and // other output values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values cout << \"(Top, Left) (\" << finalTop << \", \" << finalLeft << \")\" << endl; cout << \"(Bottom, Right) (\" << finalBottom << \", \" << finalRight << \")\" << endl; cout << \"Max sum is: \" << maxSum << endl;} // Driver Codeint main(){ int M[ROW][COL] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSum(M); return 0;} // This code is contributed by// rathbhupendra",
"e": 30171,
"s": 26725,
"text": null
},
{
"code": "// Program to find maximum sum subarray// in a given 2D array#include <limits.h>#include <stdio.h>#include <string.h>#define ROW 4#define COL 5 // Implementation of Kadane's algorithm// for 1D array. The function returns the// maximum sum and stores starting and// ending indexes of the maximum sum subarray// at addresses pointed by start and finish// pointers respectively.int kadane(int* arr, int* start, int* finish, int n){ // initialize sum, maxSum and int sum = 0, maxSum = INT_MIN, i; // Just some initial value to check for all negative // values case *finish = -1; // local variable int local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; *start = local_start; *finish = i; } } // There is at-least one non-negative number if (*finish != -1) return maxSum; // Special Case: When all numbers in arr[] // are negative maxSum = arr[0]; *start = *finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; *start = *finish = i; } } return maxSum;} // The main function that finds maximum// sum rectangle in// M[][]void findMaxSum(int M[][COL]){ // Variables to store the final output int maxSum = INT_MIN, finalLeft, finalRight, finalTop, finalBottom; int left, right, i; int temp[ROW], sum, start, finish; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 memset(temp, 0, sizeof(temp)); // Set the right column for the left column set by // outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left and right // for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values of // start and finish. So 'sum' is sum of // rectangle between (start, left) and (finish, // right) which is the maximum sum with boundary // columns strictly as left and right. sum = kadane(temp, &start, &finish, ROW); // Compare sum with maximum sum so far. If sum // is more, then update maxSum and other output // values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values printf(\"(Top, Left) (%d, %d)\\n\", finalTop, finalLeft); printf(\"(Bottom, Right) (%d, %d)\\n\", finalBottom, finalRight); printf(\"Max sum is: %d\\n\", maxSum);} // Driver Codeint main(){ int M[ROW][COL] = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSum(M); return 0;}",
"e": 33510,
"s": 30171,
"text": null
},
{
"code": "// Java Program to find max sum rectangular submatrix import java.util.*;import java.lang.*;import java.io.*; class MaximumSumRectangle{ // Function to find maximum sum rectangular // submatrix private static int maxSumRectangle(int[][] mat) { int m = mat.length; int n = mat[0].length; int preSum[][] = new int[m + 1][n]; for (int i = 0; i < m; i++) { for (int j = 0; j < n; j++) { preSum[i + 1][j] = preSum[i][j] + mat[i][j]; } } int maxSum = -1; int minSum = Integer.MIN_VALUE; int negRow = 0, negCol = 0; int rStart = 0, rEnd = 0, cStart = 0, cEnd = 0; for (int rowStart = 0; rowStart < m; rowStart++) { for (int row = rowStart; row < m; row++) { int sum = 0; int curColStart = 0; for (int col = 0; col < n; col++) { sum += preSum[row + 1][col] - preSum[rowStart][col]; if (sum < 0) { if (minSum < sum) { minSum = sum; negRow = row; negCol = col; } sum = 0; curColStart = col + 1; } else if (maxSum < sum) { maxSum = sum; rStart = rowStart; rEnd = row; cStart = curColStart; cEnd = col; } } } } // Printing final values if (maxSum == -1) { System.out.println(\"from row - \" + negRow + \" to row - \" + negRow); System.out.println(\"from col - \" + negCol + \" to col - \" + negCol); } else { System.out.println(\"from row - \" + rStart + \" to row - \" + rEnd); System.out.println(\"from col - \" + cStart + \" to col - \" + cEnd); } return maxSum == -1 ? minSum : maxSum; } // Driver Code public static void main(String[] args) { int arr[][] = new int[][] { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call System.out.println(maxSumRectangle(arr)); }} // This code is contributed by Nayanava De",
"e": 36239,
"s": 33510,
"text": null
},
{
"code": "# Python3 program to find maximum sum# subarray in a given 2D array # Implementation of Kadane's algorithm# for 1D array. The function returns the# maximum sum and stores starting and# ending indexes of the maximum sum subarray# at addresses pointed by start and finish# pointers respectively. def kadane(arr, start, finish, n): # initialize sum, maxSum and Sum = 0 maxSum = -999999999999 i = None # Just some initial value to check # for all negative values case finish[0] = -1 # local variable local_start = 0 for i in range(n): Sum += arr[i] if Sum < 0: Sum = 0 local_start = i + 1 elif Sum > maxSum: maxSum = Sum start[0] = local_start finish[0] = i # There is at-least one # non-negative number if finish[0] != -1: return maxSum # Special Case: When all numbers # in arr[] are negative maxSum = arr[0] start[0] = finish[0] = 0 # Find the maximum element in array for i in range(1, n): if arr[i] > maxSum: maxSum = arr[i] start[0] = finish[0] = i return maxSum # The main function that finds maximum# sum rectangle in M[][] def findMaxSum(M): global ROW, COL # Variables to store the final output maxSum, finalLeft = -999999999999, None finalRight, finalTop, finalBottom = None, None, None left, right, i = None, None, None temp = [None] * ROW Sum = 0 start = [0] finish = [0] # Set the left column for left in range(COL): # Initialize all elements of temp as 0 temp = [0] * ROW # Set the right column for the left # column set by outer loop for right in range(left, COL): # Calculate sum between current left # and right for every row 'i' for i in range(ROW): temp[i] += M[i][right] # Find the maximum sum subarray in # temp[]. The kadane() function also # sets values of start and finish. # So 'sum' is sum of rectangle between # (start, left) and (finish, right) which # is the maximum sum with boundary columns # strictly as left and right. Sum = kadane(temp, start, finish, ROW) # Compare sum with maximum sum so far. # If sum is more, then update maxSum # and other output values if Sum > maxSum: maxSum = Sum finalLeft = left finalRight = right finalTop = start[0] finalBottom = finish[0] # Prfinal values print(\"(Top, Left)\", \"(\", finalTop, finalLeft, \")\") print(\"(Bottom, Right)\", \"(\", finalBottom, finalRight, \")\") print(\"Max sum is:\", maxSum) # Driver CodeROW = 4COL = 5M = [[1, 2, -1, -4, -20], [-8, -3, 4, 2, 1], [3, 8, 10, 1, 3], [-4, -1, 1, 7, -6]] # Function callfindMaxSum(M) # This code is contributed by PranchalK",
"e": 39232,
"s": 36239,
"text": null
},
{
"code": "// C# Given a 2D array, find the// maximum sum subarray in itusing System; class GFG { /** * To find maxSum in 1d array * * return {maxSum, left, right} */ public static int[] kadane(int[] a) { int[] result = new int[] { int.MinValue, 0, -1 }; int currentSum = 0; int localStart = 0; for (int i = 0; i < a.Length; i++) { currentSum += a[i]; if (currentSum < 0) { currentSum = 0; localStart = i + 1; } else if (currentSum > result[0]) { result[0] = currentSum; result[1] = localStart; result[2] = i; } } // all numbers in a are negative if (result[2] == -1) { result[0] = 0; for (int i = 0; i < a.Length; i++) { if (a[i] > result[0]) { result[0] = a[i]; result[1] = i; result[2] = i; } } } return result; } /** * To find and print maxSum, (left, top),(right, bottom) */ public static void findMaxSubMatrix(int[, ] a) { int cols = a.GetLength(1); int rows = a.GetLength(0); int[] currentResult; int maxSum = int.MinValue; int left = 0; int top = 0; int right = 0; int bottom = 0; for (int leftCol = 0; leftCol < cols; leftCol++) { int[] tmp = new int[rows]; for (int rightCol = leftCol; rightCol < cols; rightCol++) { for (int i = 0; i < rows; i++) { tmp[i] += a[i, rightCol]; } currentResult = kadane(tmp); if (currentResult[0] > maxSum) { maxSum = currentResult[0]; left = leftCol; top = currentResult[1]; right = rightCol; bottom = currentResult[2]; } } } Console.Write(\"MaxSum: \" + maxSum + \", range: [(\" + left + \", \" + top + \")(\" + right + \", \" + bottom + \")]\"); } // Driver Code public static void Main() { int[, ] arr = { { 1, 2, -1, -4, -20 }, { -8, -3, 4, 2, 1 }, { 3, 8, 10, 1, 3 }, { -4, -1, 1, 7, -6 } }; // Function call findMaxSubMatrix(arr); }} // This code is contributed// by PrinciRaj1992",
"e": 41890,
"s": 39232,
"text": null
},
{
"code": "<script> // Program to find maximum sum subarray// in a given 2D array var ROW = 4var COL = 5var start = 0var finish = 0 // Implementation of Kadane's algorithm for// 1D array. The function returns the maximum// sum and stores starting and ending indexes// of the maximum sum subarray at addresses// pointed by start and finish pointers// respectively.function kadane(arr, n){ // initialize sum, maxSum and var sum = 0, maxSum = -1000000000, i; // Just some initial value to check // for all negative values case finish = -1; // local variable var local_start = 0; for (i = 0; i < n; ++i) { sum += arr[i]; if (sum < 0) { sum = 0; local_start = i + 1; } else if (sum > maxSum) { maxSum = sum; start = local_start; finish = i; } } // There is at-least one // non-negative number if (finish != -1) return maxSum; // Special Case: When all numbers // in arr[] are negative maxSum = arr[0]; start = finish = 0; // Find the maximum element in array for (i = 1; i < n; i++) { if (arr[i] > maxSum) { maxSum = arr[i]; start = finish = i; } } return maxSum;} // The main function that finds// maximum sum rectangle in M[][]function findMaxSum(M){ // Variables to store the final output var maxSum = -1000000000, finalLeft=0, finalRight=0, finalTop=0, finalBottom=0; var left, right, i; var temp = Array(ROW); var sum; // Set the left column for (left = 0; left < COL; ++left) { // Initialize all elements of temp as 0 temp = Array(ROW).fill(0); // Set the right column for the left // column set by outer loop for (right = left; right < COL; ++right) { // Calculate sum between current left // and right for every row 'i' for (i = 0; i < ROW; ++i) temp[i] += M[i][right]; // Find the maximum sum subarray in temp[]. // The kadane() function also sets values // of start and finish. So 'sum' is sum of // rectangle between (start, left) and // (finish, right) which is the maximum sum // with boundary columns strictly as left // and right. sum = kadane(temp, ROW); // Compare sum with maximum sum so far. // If sum is more, then update maxSum and // other output values if (sum > maxSum) { maxSum = sum; finalLeft = left; finalRight = right; finalTop = start; finalBottom = finish; } } } // Print final values document.write(\"(Top, Left) (\" + finalTop + \", \" + finalLeft + \")\" + \"<br>\"); document.write(\"(Bottom, Right) (\" + finalBottom + \", \" + finalRight + \")\" + \"<br>\"); document.write(\"Max sum is: \" + maxSum + \"<br>\");} // Driver Codevar M = [ [ 1, 2, -1, -4, -20 ], [ -8, -3, 4, 2, 1 ], [ 3, 8, 10, 1, 3 ], [ -4, -1, 1, 7, -6 ] ];// Function callfindMaxSum(M); // This code is contributed by rutvik_56.</script>",
"e": 45236,
"s": 41890,
"text": null
},
{
"code": null,
"e": 45293,
"s": 45236,
"text": "(Top, Left) (1, 1)\n(Bottom, Right) (3, 3)\nMax sum is: 29"
},
{
"code": null,
"e": 45316,
"s": 45293,
"text": "Time Complexity: O(n3)"
},
{
"code": null,
"e": 45486,
"s": 45316,
"text": "This article is compiled by Aashish Barnwal. Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 45502,
"s": 45486,
"text": "Gaurav Kumar 33"
},
{
"code": null,
"e": 45516,
"s": 45502,
"text": "princiraj1992"
},
{
"code": null,
"e": 45532,
"s": 45516,
"text": "PranchalKatiyar"
},
{
"code": null,
"e": 45546,
"s": 45532,
"text": "rathbhupendra"
},
{
"code": null,
"e": 45555,
"s": 45546,
"text": "tonyshen"
},
{
"code": null,
"e": 45566,
"s": 45555,
"text": "kushagra98"
},
{
"code": null,
"e": 45577,
"s": 45566,
"text": "uchiha1101"
},
{
"code": null,
"e": 45587,
"s": 45577,
"text": "rutvik_56"
},
{
"code": null,
"e": 45596,
"s": 45587,
"text": "Accolite"
},
{
"code": null,
"e": 45603,
"s": 45596,
"text": "Amazon"
},
{
"code": null,
"e": 45611,
"s": 45603,
"text": "FactSet"
},
{
"code": null,
"e": 45619,
"s": 45611,
"text": "Samsung"
},
{
"code": null,
"e": 45626,
"s": 45619,
"text": "Arrays"
},
{
"code": null,
"e": 45646,
"s": 45626,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45653,
"s": 45646,
"text": "Matrix"
},
{
"code": null,
"e": 45658,
"s": 45653,
"text": "Misc"
},
{
"code": null,
"e": 45667,
"s": 45658,
"text": "Accolite"
},
{
"code": null,
"e": 45674,
"s": 45667,
"text": "Amazon"
},
{
"code": null,
"e": 45682,
"s": 45674,
"text": "Samsung"
},
{
"code": null,
"e": 45690,
"s": 45682,
"text": "FactSet"
},
{
"code": null,
"e": 45695,
"s": 45690,
"text": "Misc"
},
{
"code": null,
"e": 45702,
"s": 45695,
"text": "Arrays"
},
{
"code": null,
"e": 45722,
"s": 45702,
"text": "Dynamic Programming"
},
{
"code": null,
"e": 45727,
"s": 45722,
"text": "Misc"
},
{
"code": null,
"e": 45734,
"s": 45727,
"text": "Matrix"
},
{
"code": null,
"e": 45832,
"s": 45734,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 45900,
"s": 45832,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 45944,
"s": 45900,
"text": "Top 50 Array Coding Problems for Interviews"
},
{
"code": null,
"e": 45992,
"s": 45944,
"text": "Stack Data Structure (Introduction and Program)"
},
{
"code": null,
"e": 46015,
"s": 45992,
"text": "Introduction to Arrays"
},
{
"code": null,
"e": 46047,
"s": 46015,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 46076,
"s": 46047,
"text": "0-1 Knapsack Problem | DP-10"
},
{
"code": null,
"e": 46106,
"s": 46076,
"text": "Program for Fibonacci numbers"
},
{
"code": null,
"e": 46140,
"s": 46106,
"text": "Longest Common Subsequence | DP-4"
},
{
"code": null,
"e": 46171,
"s": 46140,
"text": "Bellman–Ford Algorithm | DP-23"
}
] |
How to extract extension from a filename using PHP ? - GeeksforGeeks | 06 Dec, 2021
In this article, we will see how to extract the filename extension in PHP, along with understanding their implementation through the examples. There are a few different ways to extract the extension from a filename with PHP, which is given below:
Using pathinfo() function: This function returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned. If the second parameter is true, it will return specific data.
Example: This example describes the use of the pathinfo() function that returns information about a path using an associative array or a string.
PHP
<?php $file_name = 'gfg.html'; $extension = pathinfo($file_name, PATHINFO_EXTENSION); echo $extension;?>
html
Using end() function: It explodes the file variable and gets the last array element to be the file extension. The PHP end() function is used to get the last element of the array.
Example: This example describes the use of the end() function that is used to find the last element of the given array.
PHP
<?php $file_name = 'gfg.html'; $temp= explode('.',$file_name); $extension = end($temp); echo $extension;?>
html
Using substr() and strrchr() functions:
substr(): A part of the string is returned.
strrchr(): The last occurrence of a string inside another string is determined.
Example: This example uses both substr() function & strchr() function.
PHP
<?php $file_name = 'gfg.html'; $extension = substr(strrchr($file_name, '.'), 1); echo $extension;?>
html
Using strrpos() function: This function is used to find the last occurrence position of a ‘.’ in a filename and enhances the file position by 1 to explode string (.)
Example: This example describes the use of the strrpos() function that finds the position of the last occurrence of a string in another string.
PHP
<?php $file_name = 'gfg.html'; $extension = substr($file_name, strrpos($file_name, '.') + 1); echo $extension;?>
html
Using preg_replace() function: Using regular expressions like replace and search. The first parameter of this function is the search pattern, the second parameter $1 is a reference to whatever matches the first (.*), and the third parameter is the file name.
Example: This example uses the preg_replace() function to perform a regular expression for search and replace the content.
PHP
<?php $file_name = 'gfg.html'; $extension = preg_replace('/^.*\.([^.]+)$/D', '$1', $file_name); echo $extension;?>
html
bhaskargeeksforgeeks
PHP-file-handling
PHP-function
PHP-Questions
PHP
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
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": 32677,
"s": 32649,
"text": "\n06 Dec, 2021"
},
{
"code": null,
"e": 32924,
"s": 32677,
"text": "In this article, we will see how to extract the filename extension in PHP, along with understanding their implementation through the examples. There are a few different ways to extract the extension from a filename with PHP, which is given below:"
},
{
"code": null,
"e": 33204,
"s": 32924,
"text": "Using pathinfo() function: This function returns information about a file. If the second optional parameter is omitted, an associative array containing dirname, basename, extension, and the filename will be returned. If the second parameter is true, it will return specific data."
},
{
"code": null,
"e": 33350,
"s": 33204,
"text": "Example: This example describes the use of the pathinfo() function that returns information about a path using an associative array or a string. "
},
{
"code": null,
"e": 33354,
"s": 33350,
"text": "PHP"
},
{
"code": "<?php $file_name = 'gfg.html'; $extension = pathinfo($file_name, PATHINFO_EXTENSION); echo $extension;?>",
"e": 33462,
"s": 33354,
"text": null
},
{
"code": null,
"e": 33467,
"s": 33462,
"text": "html"
},
{
"code": null,
"e": 33646,
"s": 33467,
"text": "Using end() function: It explodes the file variable and gets the last array element to be the file extension. The PHP end() function is used to get the last element of the array."
},
{
"code": null,
"e": 33766,
"s": 33646,
"text": "Example: This example describes the use of the end() function that is used to find the last element of the given array."
},
{
"code": null,
"e": 33770,
"s": 33766,
"text": "PHP"
},
{
"code": "<?php $file_name = 'gfg.html'; $temp= explode('.',$file_name); $extension = end($temp); echo $extension;?>",
"e": 33881,
"s": 33770,
"text": null
},
{
"code": null,
"e": 33886,
"s": 33881,
"text": "html"
},
{
"code": null,
"e": 33926,
"s": 33886,
"text": "Using substr() and strrchr() functions:"
},
{
"code": null,
"e": 33970,
"s": 33926,
"text": "substr(): A part of the string is returned."
},
{
"code": null,
"e": 34050,
"s": 33970,
"text": "strrchr(): The last occurrence of a string inside another string is determined."
},
{
"code": null,
"e": 34123,
"s": 34050,
"text": "Example: This example uses both substr() function & strchr() function. "
},
{
"code": null,
"e": 34127,
"s": 34123,
"text": "PHP"
},
{
"code": "<?php $file_name = 'gfg.html'; $extension = substr(strrchr($file_name, '.'), 1); echo $extension;?>",
"e": 34230,
"s": 34127,
"text": null
},
{
"code": null,
"e": 34235,
"s": 34230,
"text": "html"
},
{
"code": null,
"e": 34401,
"s": 34235,
"text": "Using strrpos() function: This function is used to find the last occurrence position of a ‘.’ in a filename and enhances the file position by 1 to explode string (.)"
},
{
"code": null,
"e": 34546,
"s": 34401,
"text": "Example: This example describes the use of the strrpos() function that finds the position of the last occurrence of a string in another string. "
},
{
"code": null,
"e": 34550,
"s": 34546,
"text": "PHP"
},
{
"code": "<?php $file_name = 'gfg.html'; $extension = substr($file_name, strrpos($file_name, '.') + 1); echo $extension;?>",
"e": 34666,
"s": 34550,
"text": null
},
{
"code": null,
"e": 34671,
"s": 34666,
"text": "html"
},
{
"code": null,
"e": 34930,
"s": 34671,
"text": "Using preg_replace() function: Using regular expressions like replace and search. The first parameter of this function is the search pattern, the second parameter $1 is a reference to whatever matches the first (.*), and the third parameter is the file name."
},
{
"code": null,
"e": 35053,
"s": 34930,
"text": "Example: This example uses the preg_replace() function to perform a regular expression for search and replace the content."
},
{
"code": null,
"e": 35057,
"s": 35053,
"text": "PHP"
},
{
"code": "<?php $file_name = 'gfg.html'; $extension = preg_replace('/^.*\\.([^.]+)$/D', '$1', $file_name); echo $extension;?>",
"e": 35175,
"s": 35057,
"text": null
},
{
"code": null,
"e": 35180,
"s": 35175,
"text": "html"
},
{
"code": null,
"e": 35201,
"s": 35180,
"text": "bhaskargeeksforgeeks"
},
{
"code": null,
"e": 35219,
"s": 35201,
"text": "PHP-file-handling"
},
{
"code": null,
"e": 35232,
"s": 35219,
"text": "PHP-function"
},
{
"code": null,
"e": 35246,
"s": 35232,
"text": "PHP-Questions"
},
{
"code": null,
"e": 35250,
"s": 35246,
"text": "PHP"
},
{
"code": null,
"e": 35267,
"s": 35250,
"text": "Web Technologies"
},
{
"code": null,
"e": 35271,
"s": 35267,
"text": "PHP"
},
{
"code": null,
"e": 35369,
"s": 35271,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 35414,
"s": 35369,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 35464,
"s": 35414,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 35488,
"s": 35464,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 35528,
"s": 35488,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 35580,
"s": 35528,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 35620,
"s": 35580,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 35653,
"s": 35620,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 35698,
"s": 35653,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 35741,
"s": 35698,
"text": "How to fetch data from an API in ReactJS ?"
}
] |
How to invoke the Chrome browser in Selenium with python? | We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package.
For invoking chrome browser, we have to select the Chrome class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation.
Every chrome browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser.
Next we need to download the chrome driver version as per our browser version. The path of the chromedriver.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser.
Code Implementation
from selenium import webdriver
#browser exposes an executable file
#Through Selenium test we will invoke the executable file which will then #invoke actual browser
driver = webdriver.Chrome(executable_path="C:\\chromedriver.exe")
# to maximize the browser window
driver.maximize_window()
#get method to launch the URL
driver.get("https://www.tutorialspoint.com/index.htm")
#to refresh the browser
driver.refresh()
#to close the browser
driver.close() | [
{
"code": null,
"e": 1309,
"s": 1062,
"text": "We can invoke any browsers with the help of the webdriver package. From this package we get access to numerous classes. Next we have to import the selenium.webdriver package. Then we shall be exposed to all the browsers belonging to that package."
},
{
"code": null,
"e": 1489,
"s": 1309,
"text": "For invoking chrome browser, we have to select the Chrome class. Then create the driver object of that class. This is the most important and mandatory step for browser invocation."
},
{
"code": null,
"e": 1653,
"s": 1489,
"text": "Every chrome browser gives an executable file. Through Selenium we need to invoke this executable file which is responsible for invoking the actual chrome browser."
},
{
"code": null,
"e": 1904,
"s": 1653,
"text": "Next we need to download the chrome driver version as per our browser version. The path of the chromedriver.exe file needs to be added in the executable file. Then we need to use the get () method to launch our application in that particular browser."
},
{
"code": null,
"e": 1924,
"s": 1904,
"text": "Code Implementation"
},
{
"code": null,
"e": 2375,
"s": 1924,
"text": "from selenium import webdriver\n#browser exposes an executable file\n#Through Selenium test we will invoke the executable file which will then #invoke actual browser\ndriver = webdriver.Chrome(executable_path=\"C:\\\\chromedriver.exe\")\n# to maximize the browser window\ndriver.maximize_window()\n#get method to launch the URL\ndriver.get(\"https://www.tutorialspoint.com/index.htm\")\n#to refresh the browser\ndriver.refresh()\n#to close the browser\ndriver.close()"
}
] |
Node.js fs.writeFile() Method - GeeksforGeeks | 11 Oct, 2021
The fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method.
Syntax:
fs.writeFile( file, data, options, callback )
Parameters: This method accept four parameters as mentioned above and described below:
file: It is a string, Buffer, URL or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similar to fs.write() method.
data: It is a string, Buffer, TypedArray or DataView that will be written to the file.
options: It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer value that specifies the file mode. The default value is 0o666.flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.
encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.
mode: It is an integer value that specifies the file mode. The default value is 0o666.
flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’.
callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails.
err: It is an error that would be thrown if the operation fails.
Below examples illustrate the fs.writeFile() method in Node.js:
Example 1:
// Node.js program to demonstrate the// fs.writeFile() method // Import the filesystem moduleconst fs = require('fs'); let data = "This is a file containing a collection of books."; fs.writeFile("books.txt", data, (err) => { if (err) console.log(err); else { console.log("File written successfully\n"); console.log("The written has the following contents:"); console.log(fs.readFileSync("books.txt", "utf8")); }});
Output:
File written successfully
The written has the following contents:
This is a file containing a collection of books.
Example 2:
// Node.js program to demonstrate the// fs.writeFile() method // Import the filesystem moduleconst fs = require('fs'); let data = "This is a file containing a collection of movies."; fs.writeFile("movies.txt", data, { encoding: "utf8", flag: "w", mode: 0o666 }, (err) => { if (err) console.log(err); else { console.log("File written successfully\n"); console.log("The written has the following contents:"); console.log(fs.readFileSync("movies.txt", "utf8")); }});
Output:
File written successfully
The written has the following contents:
This is a file containing a collection of movies.
Reference: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback
Node.js-fs-module
Picked
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
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?
How to read and write Excel file in Node.js ?
Express.js res.render() Function
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": 25819,
"s": 25791,
"text": "\n11 Oct, 2021"
},
{
"code": null,
"e": 26039,
"s": 25819,
"text": "The fs.writeFile() method is used to asynchronously write the specified data to a file. By default, the file would be replaced if it exists. The ‘options’ parameter can be used to modify the functionality of the method."
},
{
"code": null,
"e": 26047,
"s": 26039,
"text": "Syntax:"
},
{
"code": null,
"e": 26093,
"s": 26047,
"text": "fs.writeFile( file, data, options, callback )"
},
{
"code": null,
"e": 26180,
"s": 26093,
"text": "Parameters: This method accept four parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26378,
"s": 26180,
"text": "file: It is a string, Buffer, URL or file description integer that denotes the path of the file where it has to be written. Using a file descriptor will make it behave similar to fs.write() method."
},
{
"code": null,
"e": 26465,
"s": 26378,
"text": "data: It is a string, Buffer, TypedArray or DataView that will be written to the file."
},
{
"code": null,
"e": 26904,
"s": 26465,
"text": "options: It is an string or object that can be used to specify optional parameters that will affect the output. It has three optional parameter:encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’.mode: It is an integer value that specifies the file mode. The default value is 0o666.flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’."
},
{
"code": null,
"e": 27005,
"s": 26904,
"text": "encoding: It is a string value that specifies the encoding of the file. The default value is ‘utf8’."
},
{
"code": null,
"e": 27092,
"s": 27005,
"text": "mode: It is an integer value that specifies the file mode. The default value is 0o666."
},
{
"code": null,
"e": 27201,
"s": 27092,
"text": "flag: It is a string value that specifies the flag used while writing to the file. The default value is ‘w’."
},
{
"code": null,
"e": 27344,
"s": 27201,
"text": "callback: It is the function that would be called when the method is executed.err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 27409,
"s": 27344,
"text": "err: It is an error that would be thrown if the operation fails."
},
{
"code": null,
"e": 27473,
"s": 27409,
"text": "Below examples illustrate the fs.writeFile() method in Node.js:"
},
{
"code": null,
"e": 27484,
"s": 27473,
"text": "Example 1:"
},
{
"code": "// Node.js program to demonstrate the// fs.writeFile() method // Import the filesystem moduleconst fs = require('fs'); let data = \"This is a file containing a collection of books.\"; fs.writeFile(\"books.txt\", data, (err) => { if (err) console.log(err); else { console.log(\"File written successfully\\n\"); console.log(\"The written has the following contents:\"); console.log(fs.readFileSync(\"books.txt\", \"utf8\")); }});",
"e": 27917,
"s": 27484,
"text": null
},
{
"code": null,
"e": 27925,
"s": 27917,
"text": "Output:"
},
{
"code": null,
"e": 28041,
"s": 27925,
"text": "File written successfully\n\nThe written has the following contents:\nThis is a file containing a collection of books."
},
{
"code": null,
"e": 28052,
"s": 28041,
"text": "Example 2:"
},
{
"code": "// Node.js program to demonstrate the// fs.writeFile() method // Import the filesystem moduleconst fs = require('fs'); let data = \"This is a file containing a collection of movies.\"; fs.writeFile(\"movies.txt\", data, { encoding: \"utf8\", flag: \"w\", mode: 0o666 }, (err) => { if (err) console.log(err); else { console.log(\"File written successfully\\n\"); console.log(\"The written has the following contents:\"); console.log(fs.readFileSync(\"movies.txt\", \"utf8\")); }});",
"e": 28560,
"s": 28052,
"text": null
},
{
"code": null,
"e": 28568,
"s": 28560,
"text": "Output:"
},
{
"code": null,
"e": 28685,
"s": 28568,
"text": "File written successfully\n\nThe written has the following contents:\nThis is a file containing a collection of movies."
},
{
"code": null,
"e": 28770,
"s": 28685,
"text": "Reference: https://nodejs.org/api/fs.html#fs_fs_writefile_file_data_options_callback"
},
{
"code": null,
"e": 28788,
"s": 28770,
"text": "Node.js-fs-module"
},
{
"code": null,
"e": 28795,
"s": 28788,
"text": "Picked"
},
{
"code": null,
"e": 28803,
"s": 28795,
"text": "Node.js"
},
{
"code": null,
"e": 28820,
"s": 28803,
"text": "Web Technologies"
},
{
"code": null,
"e": 28918,
"s": 28820,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28975,
"s": 28918,
"text": "How to install the previous version of node.js and npm ?"
},
{
"code": null,
"e": 29029,
"s": 28975,
"text": "Difference between promise and async await in Node.js"
},
{
"code": null,
"e": 29066,
"s": 29029,
"text": "How to use an ES6 import in Node.js?"
},
{
"code": null,
"e": 29112,
"s": 29066,
"text": "How to read and write Excel file in Node.js ?"
},
{
"code": null,
"e": 29145,
"s": 29112,
"text": "Express.js res.render() Function"
},
{
"code": null,
"e": 29185,
"s": 29145,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 29230,
"s": 29185,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 29273,
"s": 29230,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 29323,
"s": 29273,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
Matplotlib.pyplot.margins() function in Python - GeeksforGeeks | 03 Jan, 2021
Prerequisites: Matplotlib
Matplotlib.pyplot.margins() is a function used to set the margins of the x and y axes. All input parameters must be a float that too within the range [0, 1]. We cannot pass both positional and keyword arguments at once as that will raise a TypeError. The padding added to each limit of the axes is the margin times the data interval for that axis. If no arguments are provided, the existing margins remain in place. Specifying margins changes auto-scaling.
If only one float value if provided, that is taken as margins for both x and y axes.
If two float values are provided, they will be taken to specify x-margin and y-margin axes respectively.
Syntax:
margins(x, y, tight)
Parameters
– x, y : Used to specify margin values for x and y axes. These can only be used individually.
– tight : Boolean
If this parameter is specified as True, then it is considered the specified margins require no additional padding to match tick marks.
If this parameter is set to None, it will preserve original setting.
Various implementation for using this function is given below:
Example: General application
Python3
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins()plt.show()
Output:
Example : Passing arguments to the margins() function
Python3
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(0.5)plt.show()
Output:
Example: Passing different values for x and y that are less than 1, the graph produced will be zoomed in
Python3
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(x=0.1, y=0.5)plt.show()
Output:
Example: Passing different values for x and y that are greater than , the graph produced will be zoomed out
Python3
import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(x=2, y=2)plt.show()
Output:
Matplotlib Pyplot-class
Picked
Python-matplotlib
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25581,
"s": 25553,
"text": "\n03 Jan, 2021"
},
{
"code": null,
"e": 25607,
"s": 25581,
"text": "Prerequisites: Matplotlib"
},
{
"code": null,
"e": 26065,
"s": 25607,
"text": "Matplotlib.pyplot.margins() is a function used to set the margins of the x and y axes. All input parameters must be a float that too within the range [0, 1]. We cannot pass both positional and keyword arguments at once as that will raise a TypeError. The padding added to each limit of the axes is the margin times the data interval for that axis. If no arguments are provided, the existing margins remain in place. Specifying margins changes auto-scaling. "
},
{
"code": null,
"e": 26150,
"s": 26065,
"text": "If only one float value if provided, that is taken as margins for both x and y axes."
},
{
"code": null,
"e": 26255,
"s": 26150,
"text": "If two float values are provided, they will be taken to specify x-margin and y-margin axes respectively."
},
{
"code": null,
"e": 26263,
"s": 26255,
"text": "Syntax:"
},
{
"code": null,
"e": 26284,
"s": 26263,
"text": "margins(x, y, tight)"
},
{
"code": null,
"e": 26295,
"s": 26284,
"text": "Parameters"
},
{
"code": null,
"e": 26389,
"s": 26295,
"text": "– x, y : Used to specify margin values for x and y axes. These can only be used individually."
},
{
"code": null,
"e": 26408,
"s": 26389,
"text": "– tight : Boolean "
},
{
"code": null,
"e": 26543,
"s": 26408,
"text": "If this parameter is specified as True, then it is considered the specified margins require no additional padding to match tick marks."
},
{
"code": null,
"e": 26612,
"s": 26543,
"text": "If this parameter is set to None, it will preserve original setting."
},
{
"code": null,
"e": 26675,
"s": 26612,
"text": "Various implementation for using this function is given below:"
},
{
"code": null,
"e": 26704,
"s": 26675,
"text": "Example: General application"
},
{
"code": null,
"e": 26712,
"s": 26704,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins()plt.show()",
"e": 26928,
"s": 26712,
"text": null
},
{
"code": null,
"e": 26936,
"s": 26928,
"text": "Output:"
},
{
"code": null,
"e": 26991,
"s": 26936,
"text": "Example : Passing arguments to the margins() function "
},
{
"code": null,
"e": 26999,
"s": 26991,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(0.5)plt.show()",
"e": 27218,
"s": 26999,
"text": null
},
{
"code": null,
"e": 27226,
"s": 27218,
"text": "Output:"
},
{
"code": null,
"e": 27331,
"s": 27226,
"text": "Example: Passing different values for x and y that are less than 1, the graph produced will be zoomed in"
},
{
"code": null,
"e": 27339,
"s": 27331,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(x=0.1, y=0.5)plt.show()",
"e": 27567,
"s": 27339,
"text": null
},
{
"code": null,
"e": 27575,
"s": 27567,
"text": "Output:"
},
{
"code": null,
"e": 27683,
"s": 27575,
"text": "Example: Passing different values for x and y that are greater than , the graph produced will be zoomed out"
},
{
"code": null,
"e": 27691,
"s": 27683,
"text": "Python3"
},
{
"code": "import matplotlib.pyplot as plt x = [1, 2, 3, 4, 5]labels = ['Radius 1', 'Radius 2', 'Radius 3', 'Radius 4', 'Radius 5']y = [i**2 for i in x] plt.plot(x, y)plt.xticks(x, labels, rotation=45)plt.margins(x=2, y=2)plt.show()",
"e": 27915,
"s": 27691,
"text": null
},
{
"code": null,
"e": 27923,
"s": 27915,
"text": "Output:"
},
{
"code": null,
"e": 27947,
"s": 27923,
"text": "Matplotlib Pyplot-class"
},
{
"code": null,
"e": 27954,
"s": 27947,
"text": "Picked"
},
{
"code": null,
"e": 27972,
"s": 27954,
"text": "Python-matplotlib"
},
{
"code": null,
"e": 27979,
"s": 27972,
"text": "Python"
},
{
"code": null,
"e": 28077,
"s": 27979,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28109,
"s": 28077,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 28151,
"s": 28109,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 28193,
"s": 28151,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 28249,
"s": 28193,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 28276,
"s": 28249,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 28307,
"s": 28276,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 28346,
"s": 28307,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 28375,
"s": 28346,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 28397,
"s": 28375,
"text": "Defaultdict in Python"
}
] |
Lodash _.forIn() Method - GeeksforGeeks | 14 Sep, 2020
The Lodash _.forIn() Method Iterates over keys and values of the given object and invokes iteratee function for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false.
Syntax:
_.forIn( object, iteratee_function)
Parameters: This method accepts two parameters as mentioned above and described below:
object: This is the object to find in.
iteratee_function: the function that is invoked per iteration.
Return Value: This method returns an object.
Example 1:
// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forIn(users, function(value, key) { console.log(key);});
Output:
a
b
c
Example 2:
// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forIn(users, function(value, key) { if(value > 1) { console.log(key, value); }});
Output:
b 2
c 3
Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using the following command:
npm install lodash
JavaScript-Lodash
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript | [
{
"code": null,
"e": 26545,
"s": 26517,
"text": "\n14 Sep, 2020"
},
{
"code": null,
"e": 26815,
"s": 26545,
"text": "The Lodash _.forIn() Method Iterates over keys and values of the given object and invokes iteratee function for each property. The iteratee is invoked with three arguments: (value, key, object). Iteratee functions may exit iteration early by explicitly returning false."
},
{
"code": null,
"e": 26823,
"s": 26815,
"text": "Syntax:"
},
{
"code": null,
"e": 26860,
"s": 26823,
"text": "_.forIn( object, iteratee_function)\n"
},
{
"code": null,
"e": 26947,
"s": 26860,
"text": "Parameters: This method accepts two parameters as mentioned above and described below:"
},
{
"code": null,
"e": 26986,
"s": 26947,
"text": "object: This is the object to find in."
},
{
"code": null,
"e": 27049,
"s": 26986,
"text": "iteratee_function: the function that is invoked per iteration."
},
{
"code": null,
"e": 27094,
"s": 27049,
"text": "Return Value: This method returns an object."
},
{
"code": null,
"e": 27105,
"s": 27094,
"text": "Example 1:"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forIn(users, function(value, key) { console.log(key);});",
"e": 27271,
"s": 27105,
"text": null
},
{
"code": null,
"e": 27279,
"s": 27271,
"text": "Output:"
},
{
"code": null,
"e": 27286,
"s": 27279,
"text": "a\nb\nc\n"
},
{
"code": null,
"e": 27297,
"s": 27286,
"text": "Example 2:"
},
{
"code": "// Defining Lodash variable const _ = require('lodash'); var users = { 'a': 1, 'b': 2, 'c': 3}; _.forIn(users, function(value, key) { if(value > 1) { console.log(key, value); }});",
"e": 27500,
"s": 27297,
"text": null
},
{
"code": null,
"e": 27508,
"s": 27500,
"text": "Output:"
},
{
"code": null,
"e": 27517,
"s": 27508,
"text": "b 2\nc 3\n"
},
{
"code": null,
"e": 27668,
"s": 27517,
"text": "Note: This will not work in normal JavaScript because it requires the lodash library to be installed and can be installed using the following command:"
},
{
"code": null,
"e": 27687,
"s": 27668,
"text": "npm install lodash"
},
{
"code": null,
"e": 27705,
"s": 27687,
"text": "JavaScript-Lodash"
},
{
"code": null,
"e": 27716,
"s": 27705,
"text": "JavaScript"
},
{
"code": null,
"e": 27733,
"s": 27716,
"text": "Web Technologies"
},
{
"code": null,
"e": 27831,
"s": 27733,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27871,
"s": 27831,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 27932,
"s": 27871,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27973,
"s": 27932,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27995,
"s": 27973,
"text": "JavaScript | Promises"
},
{
"code": null,
"e": 28049,
"s": 27995,
"text": "How to get character array from string in JavaScript?"
},
{
"code": null,
"e": 28089,
"s": 28049,
"text": "Remove elements from a JavaScript Array"
},
{
"code": null,
"e": 28122,
"s": 28089,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28165,
"s": 28122,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28215,
"s": 28165,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
How to merge two PHP objects? - GeeksforGeeks | 15 Nov, 2021
Given two objects of same class and the task is to merge both objects into single object.Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass.Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2. This may nullify the resulting elements in final object if array in argument2 has null values. Note: Functions are not copied using this approach. Only use this approach if class only contain variables.Example:
php
<?php// PHP program to merge two objects class Geeks { // Empty class} $objectA = new Geeks();$objectA->a = 1;$objectA->b = 2;$objectA->d = 3; $objectB = new Geeks();$objectB->d = 4;$objectB->e = 5;$objectB->f = 6; $obj_merged = (object) array_merge( (array) $objectA, (array) $objectB); print_r($obj_merged); ?>
stdClass Object
(
[a] => 1
[b] => 2
[d] => 4
[e] => 5
[f] => 6
)
Approach 2: Merge the object using array_merge() method and convert this merged array to object using convertObjectClass function. This function is used to convert object of the initial class into serialized data using serialize() method. Unserialize the serialized data into instance of the final class using unserialize() method. Using this approach obtain an object of user defined class Geeks rather the standard class stdClass.Example:
php
<?php// PHP program to merge two objects class Geeks { // Empty class} $objectA = new Geeks();$objectA->a = 1;$objectA->b = 2;$objectA->d = 3; $objectB = new Geeks();$objectB->d = 4;$objectB->e = 5;$objectB->f = 6; // Function to convert class of given objectfunction convertObjectClass($array, $final_class) { return unserialize(sprintf( 'O:%d:"%s"%s', strlen($final_class), $final_class, strstr(serialize($array), ':') ));} $obj_merged = convertObjectClass(array_merge( (array) $objectA, (array) $objectB), 'Geeks'); print_r($obj_merged); ?>
Geeks Object
(
[a] => 1
[b] => 2
[d] => 4
[e] => 5
[f] => 6
)
Approach 3: Create a new object of the original class and assign all the properties of both objects to this new object by using foreach loop. This is a simple and clean approach of merging two objects.Example:
php
<?php// PHP program to merge two objects class Geeks { // Empty class} $objectA = new Geeks();$objectA->a = 1;$objectA->b = 2;$objectA->d = 3; $objectB = new Geeks();$objectB->e = 4;$objectB->f = 5;$objectB->g = 6; // Function to convert class of given objectfunction convertObjectClass($objectA, $objectB, $final_class) { $new_object = new $final_class(); // Initializing class properties foreach($objectA as $property => $value) { $new_object->$property = $value; } foreach($objectB as $property => $value) { $new_object->$property = $value; } return $new_object;} $obj_merged = convertObjectClass($objectA, $objectB, 'Geeks'); print_r($obj_merged); ?>
Geeks Object
(
[a] => 1
[b] => 2
[d] => 3
[e] => 4
[f] => 5
[g] => 6
)
gulshankumarar231
PHP-OOP
Picked
PHP
PHP Programs
Web Technologies
PHP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
PHP in_array() Function
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
How to execute PHP code using command line ?
How to Insert Form Data into Database using PHP ?
How to convert array to string in PHP ?
How to delete an array element based on key in PHP?
How to pop an alert message box using PHP ? | [
{
"code": null,
"e": 32677,
"s": 32649,
"text": "\n15 Nov, 2021"
},
{
"code": null,
"e": 33266,
"s": 32677,
"text": "Given two objects of same class and the task is to merge both objects into single object.Approach 1: Convert object into data array and merge them using array_merge() function and convert this merged array back into object of class stdClass.Note: While merging the objects using array_merge(), elements of array in argument1 are overwritten by elements of array in argument2. This may nullify the resulting elements in final object if array in argument2 has null values. Note: Functions are not copied using this approach. Only use this approach if class only contain variables.Example: "
},
{
"code": null,
"e": 33270,
"s": 33266,
"text": "php"
},
{
"code": "<?php// PHP program to merge two objects class Geeks { // Empty class} $objectA = new Geeks();$objectA->a = 1;$objectA->b = 2;$objectA->d = 3; $objectB = new Geeks();$objectB->d = 4;$objectB->e = 5;$objectB->f = 6; $obj_merged = (object) array_merge( (array) $objectA, (array) $objectB); print_r($obj_merged); ?>",
"e": 33601,
"s": 33270,
"text": null
},
{
"code": null,
"e": 33686,
"s": 33601,
"text": "stdClass Object\n(\n [a] => 1\n [b] => 2\n [d] => 4\n [e] => 5\n [f] => 6\n)"
},
{
"code": null,
"e": 34131,
"s": 33688,
"text": "Approach 2: Merge the object using array_merge() method and convert this merged array to object using convertObjectClass function. This function is used to convert object of the initial class into serialized data using serialize() method. Unserialize the serialized data into instance of the final class using unserialize() method. Using this approach obtain an object of user defined class Geeks rather the standard class stdClass.Example: "
},
{
"code": null,
"e": 34135,
"s": 34131,
"text": "php"
},
{
"code": "<?php// PHP program to merge two objects class Geeks { // Empty class} $objectA = new Geeks();$objectA->a = 1;$objectA->b = 2;$objectA->d = 3; $objectB = new Geeks();$objectB->d = 4;$objectB->e = 5;$objectB->f = 6; // Function to convert class of given objectfunction convertObjectClass($array, $final_class) { return unserialize(sprintf( 'O:%d:\"%s\"%s', strlen($final_class), $final_class, strstr(serialize($array), ':') ));} $obj_merged = convertObjectClass(array_merge( (array) $objectA, (array) $objectB), 'Geeks'); print_r($obj_merged); ?>",
"e": 34723,
"s": 34135,
"text": null
},
{
"code": null,
"e": 34805,
"s": 34723,
"text": "Geeks Object\n(\n [a] => 1\n [b] => 2\n [d] => 4\n [e] => 5\n [f] => 6\n)"
},
{
"code": null,
"e": 35019,
"s": 34807,
"text": "Approach 3: Create a new object of the original class and assign all the properties of both objects to this new object by using foreach loop. This is a simple and clean approach of merging two objects.Example: "
},
{
"code": null,
"e": 35023,
"s": 35019,
"text": "php"
},
{
"code": "<?php// PHP program to merge two objects class Geeks { // Empty class} $objectA = new Geeks();$objectA->a = 1;$objectA->b = 2;$objectA->d = 3; $objectB = new Geeks();$objectB->e = 4;$objectB->f = 5;$objectB->g = 6; // Function to convert class of given objectfunction convertObjectClass($objectA, $objectB, $final_class) { $new_object = new $final_class(); // Initializing class properties foreach($objectA as $property => $value) { $new_object->$property = $value; } foreach($objectB as $property => $value) { $new_object->$property = $value; } return $new_object;} $obj_merged = convertObjectClass($objectA, $objectB, 'Geeks'); print_r($obj_merged); ?>",
"e": 35786,
"s": 35023,
"text": null
},
{
"code": null,
"e": 35881,
"s": 35786,
"text": "Geeks Object\n(\n [a] => 1\n [b] => 2\n [d] => 3\n [e] => 4\n [f] => 5\n [g] => 6\n)"
},
{
"code": null,
"e": 35901,
"s": 35883,
"text": "gulshankumarar231"
},
{
"code": null,
"e": 35909,
"s": 35901,
"text": "PHP-OOP"
},
{
"code": null,
"e": 35916,
"s": 35909,
"text": "Picked"
},
{
"code": null,
"e": 35920,
"s": 35916,
"text": "PHP"
},
{
"code": null,
"e": 35933,
"s": 35920,
"text": "PHP Programs"
},
{
"code": null,
"e": 35950,
"s": 35933,
"text": "Web Technologies"
},
{
"code": null,
"e": 35954,
"s": 35950,
"text": "PHP"
},
{
"code": null,
"e": 36052,
"s": 35954,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36097,
"s": 36052,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 36147,
"s": 36097,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 36171,
"s": 36147,
"text": "PHP in_array() Function"
},
{
"code": null,
"e": 36211,
"s": 36171,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 36263,
"s": 36211,
"text": "How to delete an array element based on key in PHP?"
},
{
"code": null,
"e": 36308,
"s": 36263,
"text": "How to execute PHP code using command line ?"
},
{
"code": null,
"e": 36358,
"s": 36308,
"text": "How to Insert Form Data into Database using PHP ?"
},
{
"code": null,
"e": 36398,
"s": 36358,
"text": "How to convert array to string in PHP ?"
},
{
"code": null,
"e": 36450,
"s": 36398,
"text": "How to delete an array element based on key in PHP?"
}
] |
Python program to find the sum of dictionary keys - GeeksforGeeks | 01 Oct, 2020
Given a dictionary with integer keys. The task is to find the sum of all the keys.
Examples:
Input : test_dict = {3 : 4, 9 : 10, 15 : 10, 5 : 7}
Output : 32
Explanation : 3 + 9 + 15 + 5 = 32, sum of keys.
Input : test_dict = {3 : 4, 9 : 10, 15 : 10}
Output : 27
Explanation : 3 + 9 + 15 = 27, sum of keys.
Method #1: Using loop
This is one of the ways in which this task can be performed. In this, we iterate all the keys in the dictionary and compute summation using a counter.
Python3
# Python3 code to demonstrate working of# Dictionary Keys Summation# Using loop # initializing dictionarytest_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) res = 0for key in test_dict: # adding keys res += key # printing resultprint("The dictionary keys summation : " + str(res))
The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
The dictionary keys summation : 38
Method #2 : Using keys() + sum()
This is shorthand with the help of which this task can be performed. In this, we extract all keys in list using keys(), and the summation is performed using sum().
Python3
# Python3 code to demonstrate working of# Dictionary Keys Summation# Using keys() + sum() # initializing dictionarytest_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7} # printing original dictionaryprint("The original dictionary is : " + str(test_dict)) # sum() performs summationres = sum(list(test_dict.keys())) # printing resultprint("The dictionary keys summation : " + str(res))
The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}
The dictionary keys summation : 38
Python dictionary-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Defaultdict in Python
Python | Get dictionary keys as a list
Python | Split string into list of characters
Python | Convert a list to dictionary
How to print without newline in Python? | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n01 Oct, 2020"
},
{
"code": null,
"e": 25620,
"s": 25537,
"text": "Given a dictionary with integer keys. The task is to find the sum of all the keys."
},
{
"code": null,
"e": 25630,
"s": 25620,
"text": "Examples:"
},
{
"code": null,
"e": 25849,
"s": 25630,
"text": "Input : test_dict = {3 : 4, 9 : 10, 15 : 10, 5 : 7} \nOutput : 32 \nExplanation : 3 + 9 + 15 + 5 = 32, sum of keys.\n\nInput : test_dict = {3 : 4, 9 : 10, 15 : 10} \nOutput : 27 \nExplanation : 3 + 9 + 15 = 27, sum of keys. "
},
{
"code": null,
"e": 25871,
"s": 25849,
"text": "Method #1: Using loop"
},
{
"code": null,
"e": 26022,
"s": 25871,
"text": "This is one of the ways in which this task can be performed. In this, we iterate all the keys in the dictionary and compute summation using a counter."
},
{
"code": null,
"e": 26030,
"s": 26022,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Dictionary Keys Summation# Using loop # initializing dictionarytest_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) res = 0for key in test_dict: # adding keys res += key # printing resultprint(\"The dictionary keys summation : \" + str(res))",
"e": 26403,
"s": 26030,
"text": null
},
{
"code": null,
"e": 26502,
"s": 26403,
"text": "The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}\nThe dictionary keys summation : 38\n"
},
{
"code": null,
"e": 26535,
"s": 26502,
"text": "Method #2 : Using keys() + sum()"
},
{
"code": null,
"e": 26699,
"s": 26535,
"text": "This is shorthand with the help of which this task can be performed. In this, we extract all keys in list using keys(), and the summation is performed using sum()."
},
{
"code": null,
"e": 26707,
"s": 26699,
"text": "Python3"
},
{
"code": "# Python3 code to demonstrate working of# Dictionary Keys Summation# Using keys() + sum() # initializing dictionarytest_dict = {3: 4, 9: 10, 15: 10, 5: 7, 6: 7} # printing original dictionaryprint(\"The original dictionary is : \" + str(test_dict)) # sum() performs summationres = sum(list(test_dict.keys())) # printing resultprint(\"The dictionary keys summation : \" + str(res))",
"e": 27088,
"s": 26707,
"text": null
},
{
"code": null,
"e": 27187,
"s": 27088,
"text": "The original dictionary is : {3: 4, 9: 10, 15: 10, 5: 7, 6: 7}\nThe dictionary keys summation : 38\n"
},
{
"code": null,
"e": 27216,
"s": 27189,
"text": "Python dictionary-programs"
},
{
"code": null,
"e": 27223,
"s": 27216,
"text": "Python"
},
{
"code": null,
"e": 27239,
"s": 27223,
"text": "Python Programs"
},
{
"code": null,
"e": 27337,
"s": 27239,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27369,
"s": 27337,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27411,
"s": 27369,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27453,
"s": 27411,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27509,
"s": 27453,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27536,
"s": 27509,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27558,
"s": 27536,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27597,
"s": 27558,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27643,
"s": 27597,
"text": "Python | Split string into list of characters"
},
{
"code": null,
"e": 27681,
"s": 27643,
"text": "Python | Convert a list to dictionary"
}
] |
Dynamic CheckedTextView in Kotlin - GeeksforGeeks | 18 Feb, 2021
CheckedTextView is used to implement checkable interface where one can tick or check the needed or required items and leave out the rest.In this article, we will be discussing how to make a CheckedTextView dynamically or programmatically.
The first step is to make or create a project in Android Studio. Here, we will be creating a project named DynamicCheckedTextView.For creating a new project:
Click on File, then New => New Project
Then, check Include Kotlin Support and click next button.
Select minimum SDK, whatever you need.
Select Empty activity and then click finish.
Now, we need to modify our layout. For doing so : Go to app > res > layout and paste the following code:
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/relativeLayout" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> </RelativeLayout>
Next step is to add the strings which will be displayed when we check or uncheck our CheckedTextView.Go to res/values/strings.xml and add the following lines.
<resources> <string name="app_name">DynamicCheckedTextView</string> <string name="checked">checked</string> <string name="unchecked">unchecked</string> <string name="pre_msg">TextView is</string></resources>
The final step is to code our CheckedTextView. Open app/src/main/java/yourPackageName/MainActivity.kt
package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.CheckedTextViewimport android.widget.RelativeLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //getting our layout val relativeLayout = findViewById<RelativeLayout>(R.id.relativeLayout) //using checktextview val checkedTextView = CheckedTextView(this) checkedTextView.layoutParams = RelativeLayout. LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) //using our strings.xml to set text checkedTextView.setText(R.string.app_name) //initially the checkbox in unchecked checkedTextView.isChecked = false checkedTextView.setCheckMarkDrawable(android.R.drawable. checkbox_off_background) //Onclick event for checkbox checkedTextView.setOnClickListener { checkedTextView.isChecked = !checkedTextView.isChecked checkedTextView.setCheckMarkDrawable(if (checkedTextView.isChecked) android.R.drawable.checkbox_on_background else android.R.drawable.checkbox_off_background) //using our strings.xml setting the starting message of the toast val message = getString(R.string.pre_msg) + " " + if (checkedTextView.isChecked) getString(R.string.checked) else getString(R.string.unchecked) Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show() } // Add Checkbox to RelativeLayout relativeLayout?.addView(checkedTextView) }}
<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.geeksforgeeks.myfirstkotlinapp"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>
Android-View
Kotlin Android
Picked
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Resource Raw Folder in Android Studio
Flutter - Custom Bottom Navigation Bar
How to Read Data from SQLite Database in Android?
Retrofit with Kotlin Coroutine in Android
How to Post Data to API using Retrofit in Android?
Android UI Layouts
Kotlin Array
Retrofit with Kotlin Coroutine in Android
How to Get Current Location in Android?
Kotlin Setters and Getters | [
{
"code": null,
"e": 26381,
"s": 26353,
"text": "\n18 Feb, 2021"
},
{
"code": null,
"e": 26620,
"s": 26381,
"text": "CheckedTextView is used to implement checkable interface where one can tick or check the needed or required items and leave out the rest.In this article, we will be discussing how to make a CheckedTextView dynamically or programmatically."
},
{
"code": null,
"e": 26778,
"s": 26620,
"text": "The first step is to make or create a project in Android Studio. Here, we will be creating a project named DynamicCheckedTextView.For creating a new project:"
},
{
"code": null,
"e": 26817,
"s": 26778,
"text": "Click on File, then New => New Project"
},
{
"code": null,
"e": 26875,
"s": 26817,
"text": "Then, check Include Kotlin Support and click next button."
},
{
"code": null,
"e": 26914,
"s": 26875,
"text": "Select minimum SDK, whatever you need."
},
{
"code": null,
"e": 26959,
"s": 26914,
"text": "Select Empty activity and then click finish."
},
{
"code": null,
"e": 27064,
"s": 26959,
"text": "Now, we need to modify our layout. For doing so : Go to app > res > layout and paste the following code:"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" android:id=\"@+id/relativeLayout\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> </RelativeLayout>",
"e": 27398,
"s": 27064,
"text": null
},
{
"code": null,
"e": 27557,
"s": 27398,
"text": "Next step is to add the strings which will be displayed when we check or uncheck our CheckedTextView.Go to res/values/strings.xml and add the following lines."
},
{
"code": "<resources> <string name=\"app_name\">DynamicCheckedTextView</string> <string name=\"checked\">checked</string> <string name=\"unchecked\">unchecked</string> <string name=\"pre_msg\">TextView is</string></resources>",
"e": 27777,
"s": 27557,
"text": null
},
{
"code": null,
"e": 27879,
"s": 27777,
"text": "The final step is to code our CheckedTextView. Open app/src/main/java/yourPackageName/MainActivity.kt"
},
{
"code": "package com.geeksforgeeks.myfirstkotlinapp import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.view.ViewGroupimport android.widget.CheckedTextViewimport android.widget.RelativeLayoutimport android.widget.Toast class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) //getting our layout val relativeLayout = findViewById<RelativeLayout>(R.id.relativeLayout) //using checktextview val checkedTextView = CheckedTextView(this) checkedTextView.layoutParams = RelativeLayout. LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT) //using our strings.xml to set text checkedTextView.setText(R.string.app_name) //initially the checkbox in unchecked checkedTextView.isChecked = false checkedTextView.setCheckMarkDrawable(android.R.drawable. checkbox_off_background) //Onclick event for checkbox checkedTextView.setOnClickListener { checkedTextView.isChecked = !checkedTextView.isChecked checkedTextView.setCheckMarkDrawable(if (checkedTextView.isChecked) android.R.drawable.checkbox_on_background else android.R.drawable.checkbox_off_background) //using our strings.xml setting the starting message of the toast val message = getString(R.string.pre_msg) + \" \" + if (checkedTextView.isChecked) getString(R.string.checked) else getString(R.string.unchecked) Toast.makeText(this@MainActivity, message, Toast.LENGTH_LONG).show() } // Add Checkbox to RelativeLayout relativeLayout?.addView(checkedTextView) }}",
"e": 29768,
"s": 27879,
"text": null
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><manifest xmlns:android=\"http://schemas.android.com/apk/res/android\" package=\"com.geeksforgeeks.myfirstkotlinapp\"> <application android:allowBackup=\"true\" android:icon=\"@mipmap/ic_launcher\" android:label=\"@string/app_name\" android:roundIcon=\"@mipmap/ic_launcher_round\" android:supportsRtl=\"true\" android:theme=\"@style/AppTheme\"> <activity android:name=\".MainActivity\"> <intent-filter> <action android:name=\"android.intent.action.MAIN\" /> <category android:name=\"android.intent.category.LAUNCHER\" /> </intent-filter> </activity> </application> </manifest>",
"e": 30483,
"s": 29768,
"text": null
},
{
"code": null,
"e": 30496,
"s": 30483,
"text": "Android-View"
},
{
"code": null,
"e": 30511,
"s": 30496,
"text": "Kotlin Android"
},
{
"code": null,
"e": 30518,
"s": 30511,
"text": "Picked"
},
{
"code": null,
"e": 30526,
"s": 30518,
"text": "Android"
},
{
"code": null,
"e": 30533,
"s": 30526,
"text": "Kotlin"
},
{
"code": null,
"e": 30541,
"s": 30533,
"text": "Android"
},
{
"code": null,
"e": 30639,
"s": 30541,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30677,
"s": 30639,
"text": "Resource Raw Folder in Android Studio"
},
{
"code": null,
"e": 30716,
"s": 30677,
"text": "Flutter - Custom Bottom Navigation Bar"
},
{
"code": null,
"e": 30766,
"s": 30716,
"text": "How to Read Data from SQLite Database in Android?"
},
{
"code": null,
"e": 30808,
"s": 30766,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30859,
"s": 30808,
"text": "How to Post Data to API using Retrofit in Android?"
},
{
"code": null,
"e": 30878,
"s": 30859,
"text": "Android UI Layouts"
},
{
"code": null,
"e": 30891,
"s": 30878,
"text": "Kotlin Array"
},
{
"code": null,
"e": 30933,
"s": 30891,
"text": "Retrofit with Kotlin Coroutine in Android"
},
{
"code": null,
"e": 30973,
"s": 30933,
"text": "How to Get Current Location in Android?"
}
] |
Maximum points of intersection n circles - GeeksforGeeks | 17 Dec, 2021
Given a number n, we need to find the maximum number of times n circles intersect.
Examples:
Input : n = 2
Output : 2
Input : n = 3
Output : 6
As we can see in above diagram, for each pair of circles, there can be maximum two intersection points. Therefore if we have n circles then there can be nC2 pairs of circles in which each pair will have two intersections. So by this, we can conclude that by looking at all possible pairs of circles the mathematical formula can be made for the maximum number of intersections by n circles is given by 2 * nC2. 2 * nC2 = 2 * n * (n – 1)/2 = n * (n-1)
C++
Java
Python3
C#
PHP
Javascript
// CPP program to find maximum number of// intersections of n circles#include <bits/stdc++.h>using namespace std; // Returns maximum number of intersectionsint intersection(int n){ return n * (n - 1);} int main(){ cout << intersection(3) << endl; return 0;}// This code is contributed by// Manish Kumar Rai.
// Java program to find maximum number of// intersections of n circlesimport java.io.*; public class GFG { // for the calculation of 2*(nC2) static int intersection(int n) { return n * (n - 1); } public static void main(String[] args) throws IOException { System.out.println(intersection(3)); }}// This code is contributed by// Manish Kumar Rai
# python program to find maximum number of# intersections of n circles# Returns maximum number of intersectionsdef intersection(n): return n * (n - 1); # Driver codeprint(intersection(3)) # This code is contributed by Sam007
// C# program to find maximum number of// intersections of n circlesusing System;class GFG { // for the calculation of 2*(nC2) static int intersection(int n) { return n * (n - 1); } // Driver Codepublic static void Main(){ Console.WriteLine(intersection(3));} } // This code is contributed by Sam007
<?php// php program to find maximum number of// intersections of n circles // Returns maximum number of intersectionsfunction intersection($n){ return $n * ($n - 1);} // Driver code echo intersection(3); // This code is contributed by Sam007?>
<script>// Javascript program to find maximum number of// intersections of n circles // Returns maximum number of intersectionsfunction intersection(n){ return n * (n - 1);} // Driver codedocument.write(intersection(3)); // This code is contributed by _saurabh_jaiswal </script>
6
Sam007
nidhi_biet
_saurabh_jaiswal
sagar0719kumar
sumitgumber28
circle
Combinatorial
Geometric
Mathematical
Mathematical
Combinatorial
Geometric
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Ways to sum to N using Natural Numbers up to K with repetitions allowed
Generate all possible combinations of K numbers that sums to N
Combinations with repetitions
Largest substring with same Characters
Generate all possible combinations of at most X characters from a given array
Closest Pair of Points using Divide and Conquer algorithm
How to check if a given point lies inside or outside a polygon?
Program for distance between two points on earth
How to check if two given line segments intersect?
Find if two rectangles overlap | [
{
"code": null,
"e": 26721,
"s": 26693,
"text": "\n17 Dec, 2021"
},
{
"code": null,
"e": 26804,
"s": 26721,
"text": "Given a number n, we need to find the maximum number of times n circles intersect."
},
{
"code": null,
"e": 26815,
"s": 26804,
"text": "Examples: "
},
{
"code": null,
"e": 26868,
"s": 26815,
"text": "Input : n = 2\nOutput : 2\n\nInput : n = 3\nOutput : 6"
},
{
"code": null,
"e": 27318,
"s": 26868,
"text": "As we can see in above diagram, for each pair of circles, there can be maximum two intersection points. Therefore if we have n circles then there can be nC2 pairs of circles in which each pair will have two intersections. So by this, we can conclude that by looking at all possible pairs of circles the mathematical formula can be made for the maximum number of intersections by n circles is given by 2 * nC2. 2 * nC2 = 2 * n * (n – 1)/2 = n * (n-1)"
},
{
"code": null,
"e": 27322,
"s": 27318,
"text": "C++"
},
{
"code": null,
"e": 27327,
"s": 27322,
"text": "Java"
},
{
"code": null,
"e": 27335,
"s": 27327,
"text": "Python3"
},
{
"code": null,
"e": 27338,
"s": 27335,
"text": "C#"
},
{
"code": null,
"e": 27342,
"s": 27338,
"text": "PHP"
},
{
"code": null,
"e": 27353,
"s": 27342,
"text": "Javascript"
},
{
"code": "// CPP program to find maximum number of// intersections of n circles#include <bits/stdc++.h>using namespace std; // Returns maximum number of intersectionsint intersection(int n){ return n * (n - 1);} int main(){ cout << intersection(3) << endl; return 0;}// This code is contributed by// Manish Kumar Rai.",
"e": 27669,
"s": 27353,
"text": null
},
{
"code": "// Java program to find maximum number of// intersections of n circlesimport java.io.*; public class GFG { // for the calculation of 2*(nC2) static int intersection(int n) { return n * (n - 1); } public static void main(String[] args) throws IOException { System.out.println(intersection(3)); }}// This code is contributed by// Manish Kumar Rai",
"e": 28050,
"s": 27669,
"text": null
},
{
"code": "# python program to find maximum number of# intersections of n circles# Returns maximum number of intersectionsdef intersection(n): return n * (n - 1); # Driver codeprint(intersection(3)) # This code is contributed by Sam007",
"e": 28282,
"s": 28050,
"text": null
},
{
"code": "// C# program to find maximum number of// intersections of n circlesusing System;class GFG { // for the calculation of 2*(nC2) static int intersection(int n) { return n * (n - 1); } // Driver Codepublic static void Main(){ Console.WriteLine(intersection(3));} } // This code is contributed by Sam007",
"e": 28605,
"s": 28282,
"text": null
},
{
"code": "<?php// php program to find maximum number of// intersections of n circles // Returns maximum number of intersectionsfunction intersection($n){ return $n * ($n - 1);} // Driver code echo intersection(3); // This code is contributed by Sam007?>",
"e": 28853,
"s": 28605,
"text": null
},
{
"code": "<script>// Javascript program to find maximum number of// intersections of n circles // Returns maximum number of intersectionsfunction intersection(n){ return n * (n - 1);} // Driver codedocument.write(intersection(3)); // This code is contributed by _saurabh_jaiswal </script>",
"e": 29135,
"s": 28853,
"text": null
},
{
"code": null,
"e": 29137,
"s": 29135,
"text": "6"
},
{
"code": null,
"e": 29146,
"s": 29139,
"text": "Sam007"
},
{
"code": null,
"e": 29157,
"s": 29146,
"text": "nidhi_biet"
},
{
"code": null,
"e": 29174,
"s": 29157,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 29189,
"s": 29174,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 29203,
"s": 29189,
"text": "sumitgumber28"
},
{
"code": null,
"e": 29210,
"s": 29203,
"text": "circle"
},
{
"code": null,
"e": 29224,
"s": 29210,
"text": "Combinatorial"
},
{
"code": null,
"e": 29234,
"s": 29224,
"text": "Geometric"
},
{
"code": null,
"e": 29247,
"s": 29234,
"text": "Mathematical"
},
{
"code": null,
"e": 29260,
"s": 29247,
"text": "Mathematical"
},
{
"code": null,
"e": 29274,
"s": 29260,
"text": "Combinatorial"
},
{
"code": null,
"e": 29284,
"s": 29274,
"text": "Geometric"
},
{
"code": null,
"e": 29382,
"s": 29284,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29454,
"s": 29382,
"text": "Ways to sum to N using Natural Numbers up to K with repetitions allowed"
},
{
"code": null,
"e": 29517,
"s": 29454,
"text": "Generate all possible combinations of K numbers that sums to N"
},
{
"code": null,
"e": 29547,
"s": 29517,
"text": "Combinations with repetitions"
},
{
"code": null,
"e": 29586,
"s": 29547,
"text": "Largest substring with same Characters"
},
{
"code": null,
"e": 29664,
"s": 29586,
"text": "Generate all possible combinations of at most X characters from a given array"
},
{
"code": null,
"e": 29722,
"s": 29664,
"text": "Closest Pair of Points using Divide and Conquer algorithm"
},
{
"code": null,
"e": 29786,
"s": 29722,
"text": "How to check if a given point lies inside or outside a polygon?"
},
{
"code": null,
"e": 29835,
"s": 29786,
"text": "Program for distance between two points on earth"
},
{
"code": null,
"e": 29886,
"s": 29835,
"text": "How to check if two given line segments intersect?"
}
] |
Design Dragon's World Game using HTML CSS and JavaScript - GeeksforGeeks | 14 Dec, 2020
Project Introduction: “Dragon’s World” is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon.
The project will contain HTML, CSS and JavaScript files. The HTML file adds structure to the game followed by styling using CSS. JavaScript adds functionality to the game.
File structure:
index.html
style.css
script.js
HTML Code:
Heading portion: It will show the name of the game.
Game over portion: It will be shown when you lose the game.
Obstacle portion: It will contain the obstacle from which the dragon has to save itself.
Dragon portion: It will contain the dragon which has to be saved from the obstacle i.e. the other dragon.
Score portion: It will show the current score of the game.
index.html
HTML
<!DOCTYPE html><html> <head> <meta charset="UTF-8"> <meta name="viewport" content= "width=device-width, initial-scale=1.0"> <link rel="stylesheet" href= "style.css?_cacheOverride=1606401798626"> <link href="https://fonts.googleapis.com/css2?family=Ubuntu:ital, wght@0, 300;1, 700&display=swap" rel="stylesheet"></head> <body> <h1 id="gameName">Welcome to Dragon's world</h1> <div class="container"> <div class="gameover">Game Over</div> <div id="scorecount">Your score : 0</div> <div class="obstacle animateobstacle"></div> <div class="dragon" style="left: 426px;"></div> </div></body> </html>
CSS code:
Positioning the game’s name: The name of the game is positioned by the absolute property of CSS.
Background image styling: In the container class, we have put the background image of the game with the background-size set to cover.
Score Card styling: We have positioned the scorecard to top right of the page and also provided it with a suitable background color to make it attractive. The text in it would be shown in white.
Obstacle image styling: We have positioned the obstacle to bottom left of the page and provided animation to it so that it could move towards left.
Dragon’s styling: We have positioned the dragon to bottom left of the page and provide animation to it so that it could jump up and save himself.
Game Over Styling: We have positioned the game over portion to the center of the page and it will appear when the dragon is hit by the obstacle.
style.css
/* CSS Reset */
*{
margin:0px;
padding:0px;
}
body {
/* Hides the bottom scrollbar */
overflow: hidden;
}
/* Styling of the Game's Name */
#gameName {
position: absolute;
top:30vh;
left:38vw;
}
/* Background image styling */
.container {
background-image: url(cover.png);
background-size: cover;
width:100vw;
height:100vh;
}
/* ScoreCard Styling */
#scorecount {
position: absolute;
top:20px;
right:20px;
background-color: black;
padding: 28px;
border-radius: 20px;
color: white;
}
/* Obstacle image styling and positioning */
.obstacle {
background-image: url(obstacle.png);
background-size: cover;
width:154px;
height: 126px;
position: absolute;
bottom:0px;
right:120px;
}
/* Applying animation to the obstacle
so that it can move towards left */
.animateobstacle {
animation: aniob 5s linear infinite;
}
@keyframes aniob {
0% {
left:100vw;
}
100% {
left:-10vw;
}
}
/* Dragon's styling */
.dragon {
background-image: url(dragon.png);
background-size: cover;
width: 194px;
height: 126px;
position: absolute;
bottom:0px;
left:90px;
}
/* Applying animation to the dragon so
that it can save himself by jumping up */
.animatedragon {
animation: ani 1s linear;
}
@keyframes ani {
0% {
bottom:0px;
}
25% {
bottom:150px;
}
50% {
bottom:300px;
}
75% {
bottom:211px;
}
100% {
bottom:0px;
}
}
/* gameover styling and positioning */
.gameover {
visibility: hidden;
font-family: 'Ubuntu', sans-serif;
position: absolute;
top: 50vh;
left: 35vw;
color: red;
font-weight: bold;
font-size: 6rem;
background-color: firebrick;
border-radius: 20px;
}
JavaScript Code:
1. Movement of the dragon: This is provided by the onkeydown event.
Up arrow key: On pressing it, the dragon will jump upwards (animation provide by CSS).
Left arrow key: On pressing it, the dragon will move to the left (animation provide by CSS).
Right arrow key: On pressing it, the dragon will move to the left (animation provide by CSS).
document.onkeydown = function(e) {
console.log(e.keyCode);
if (e.keyCode == 38) {
dragon = document.querySelector('.dragon');
dragon.classList.add('animatedragon');
setTimeout(() => {
dragon.classList.remove('animatedragon');
}, 700);
}
if (e.keyCode == 37) {
dragon = document.querySelector('.dragon');
dragonx = parseInt(window.getComputedStyle(dragon, null)
.getPropertyValue('left'));
dragon.style.left = dragonx - 112 + "px";
}
if (e.keyCode == 39) {
dragon = document.querySelector('.dragon');
dragonx = parseInt(window.getComputedStyle(
dragon, null).getPropertyValue('left'));
dragon.style.left = dragonx + 112 + "px";
}
}
2. Updating the score: The score is satisfied only when a given condition is satisfied. We will compute the left and bottom values of both the obstacle and the dragon and then increase the score based on a proper value which shows that the dragon has saved himself from the obstacle. For this, we have taken “cross” variable and assigned “true” to it. When the the dragon crosses the obstacle safely, we set the value to “false”. After approximately 1s we change the value of cross to “true”. We have also made the obstacle run faster after each cross and thus increasing the difficulty level.
setInterval(() => {
dragon = document.querySelector('.dragon');
gameover = document.querySelector('.gameover');
obstacle = document.querySelector('.obstacle');
dx = parseInt(window.getComputedStyle(
dragon, null).getPropertyValue('left'));
dy = parseInt(window.getComputedStyle(
dragon, null).getPropertyValue('bottom'));
ox = parseInt(window.getComputedStyle(
obstacle, null).getPropertyValue('left'));
oy = parseInt(window.getComputedStyle(
obstacle, null).getPropertyValue('bottom'));
offsetx = Math.abs(dx - ox);
offsety = Math.abs(dy - oy);
console.log(offsetx, offsety);
if (offsetx < 120 && offsety <= 144) {
gameover.style.visibility = 'visible';
obstacle.classList.remove('animateobstacle');
} else if (offsetx < 125 && cross) {
score += 1;
updateScore(score);
cross = false;
setTimeout(() => {
cross = true;
}, 1000);
setInterval(() => {
obsanidur = parseFloat(window
.getComputedStyle(obstacle, null)
.getPropertyValue('animation-duration'));
obstacle.style.animationDuration
= obsanidur - 0.01 + 's';
}, 500);
}
}, 10);
function updateScore(score) {
scorecount.innerHTML = "Your score : " + score;
}
script.js
<script> cross = true; score = 0; document.onkeydown = function(e) { console.log(e.keyCode); if (e.keyCode == 38) { dragon = document.querySelector('.dragon'); dragon.classList.add('animatedragon'); setTimeout(() => { dragon.classList.remove('animatedragon'); }, 700); } if (e.keyCode == 37) { dragon = document.querySelector('.dragon'); dragonx = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('left')); dragon.style.left = dragonx - 112 + "px"; } if (e.keyCode == 39) { dragon = document.querySelector('.dragon'); dragonx = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('left')); dragon.style.left = dragonx + 112 + "px"; } } setInterval(() => { dragon = document.querySelector('.dragon'); gameover = document.querySelector('.gameover'); obstacle = document.querySelector('.obstacle'); dx = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('left')); dy = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('bottom')); ox = parseInt(window.getComputedStyle( obstacle, null).getPropertyValue('left')); oy = parseInt(window.getComputedStyle( obstacle, null).getPropertyValue('bottom')); offsetx = Math.abs(dx - ox); offsety = Math.abs(dy - oy); console.log(offsetx, offsety); if (offsetx < 120 && offsety <= 144) { if (score != 0) scorecount.innerHTML = "Your score : " + score; gameover.style.visibility = 'visible'; obstacle.classList.remove('animateobstacle'); } else if (offsetx < 125 && cross) { score += 1; updateScore(score); cross = false; setTimeout(() => { cross = true; }, 1000); setInterval(() => { obsanidur = parseFloat(window .getComputedStyle(obstacle, null) .getPropertyValue('animation-duration')); obstacle.style.animationDuration = obsanidur - 0.01 + 's'; }, 500); } }, 10); function updateScore(score) { scorecount.innerHTML = "Your score : " + score; }</script>
Reference: Dragon game
Output:
CSS-Misc
HTML-Misc
JavaScript-Misc
Technical Scripter 2020
CSS
HTML
JavaScript
Technical Scripter
Web Technologies
Web technologies Questions
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a web page using HTML and CSS
How to set space between the flexbox ?
Form validation using jQuery
Search Bar using HTML, CSS and JavaScript
How to style a checkbox using CSS?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property
How to set input type date in dd-mm-yyyy format using HTML ?
REST API (Introduction)
How to Insert Form Data into Database using PHP ? | [
{
"code": null,
"e": 26647,
"s": 26619,
"text": "\n14 Dec, 2020"
},
{
"code": null,
"e": 26885,
"s": 26647,
"text": "Project Introduction: “Dragon’s World” is a game in which one dragon tries to save itself from the other dragon by jumping over the dragon which comes in its way. The score is updated when one dragon saves himself from the other dragon. "
},
{
"code": null,
"e": 27057,
"s": 26885,
"text": "The project will contain HTML, CSS and JavaScript files. The HTML file adds structure to the game followed by styling using CSS. JavaScript adds functionality to the game."
},
{
"code": null,
"e": 27073,
"s": 27057,
"text": "File structure:"
},
{
"code": null,
"e": 27084,
"s": 27073,
"text": "index.html"
},
{
"code": null,
"e": 27094,
"s": 27084,
"text": "style.css"
},
{
"code": null,
"e": 27104,
"s": 27094,
"text": "script.js"
},
{
"code": null,
"e": 27115,
"s": 27104,
"text": "HTML Code:"
},
{
"code": null,
"e": 27167,
"s": 27115,
"text": "Heading portion: It will show the name of the game."
},
{
"code": null,
"e": 27227,
"s": 27167,
"text": "Game over portion: It will be shown when you lose the game."
},
{
"code": null,
"e": 27316,
"s": 27227,
"text": "Obstacle portion: It will contain the obstacle from which the dragon has to save itself."
},
{
"code": null,
"e": 27422,
"s": 27316,
"text": "Dragon portion: It will contain the dragon which has to be saved from the obstacle i.e. the other dragon."
},
{
"code": null,
"e": 27481,
"s": 27422,
"text": "Score portion: It will show the current score of the game."
},
{
"code": null,
"e": 27492,
"s": 27481,
"text": "index.html"
},
{
"code": null,
"e": 27497,
"s": 27492,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <meta charset=\"UTF-8\"> <meta name=\"viewport\" content= \"width=device-width, initial-scale=1.0\"> <link rel=\"stylesheet\" href= \"style.css?_cacheOverride=1606401798626\"> <link href=\"https://fonts.googleapis.com/css2?family=Ubuntu:ital, wght@0, 300;1, 700&display=swap\" rel=\"stylesheet\"></head> <body> <h1 id=\"gameName\">Welcome to Dragon's world</h1> <div class=\"container\"> <div class=\"gameover\">Game Over</div> <div id=\"scorecount\">Your score : 0</div> <div class=\"obstacle animateobstacle\"></div> <div class=\"dragon\" style=\"left: 426px;\"></div> </div></body> </html>",
"e": 28176,
"s": 27497,
"text": null
},
{
"code": null,
"e": 28186,
"s": 28176,
"text": "CSS code:"
},
{
"code": null,
"e": 28283,
"s": 28186,
"text": "Positioning the game’s name: The name of the game is positioned by the absolute property of CSS."
},
{
"code": null,
"e": 28417,
"s": 28283,
"text": "Background image styling: In the container class, we have put the background image of the game with the background-size set to cover."
},
{
"code": null,
"e": 28612,
"s": 28417,
"text": "Score Card styling: We have positioned the scorecard to top right of the page and also provided it with a suitable background color to make it attractive. The text in it would be shown in white."
},
{
"code": null,
"e": 28760,
"s": 28612,
"text": "Obstacle image styling: We have positioned the obstacle to bottom left of the page and provided animation to it so that it could move towards left."
},
{
"code": null,
"e": 28906,
"s": 28760,
"text": "Dragon’s styling: We have positioned the dragon to bottom left of the page and provide animation to it so that it could jump up and save himself."
},
{
"code": null,
"e": 29051,
"s": 28906,
"text": "Game Over Styling: We have positioned the game over portion to the center of the page and it will appear when the dragon is hit by the obstacle."
},
{
"code": null,
"e": 29061,
"s": 29051,
"text": "style.css"
},
{
"code": null,
"e": 30887,
"s": 29061,
"text": "/* CSS Reset */\n*{\n margin:0px;\n padding:0px;\n}\nbody {\n /* Hides the bottom scrollbar */\n overflow: hidden;\n}\n/* Styling of the Game's Name */\n#gameName {\n position: absolute;\n top:30vh;\n left:38vw;\n}\n/* Background image styling */\n.container {\n background-image: url(cover.png);\n background-size: cover;\n width:100vw;\n height:100vh;\n}\n/* ScoreCard Styling */\n#scorecount {\n position: absolute;\n top:20px;\n right:20px;\n background-color: black;\n padding: 28px;\n border-radius: 20px;\n color: white;\n}\n/* Obstacle image styling and positioning */\n.obstacle {\n background-image: url(obstacle.png);\n background-size: cover;\n width:154px;\n height: 126px;\n position: absolute;\n bottom:0px;\n right:120px;\n}\n/* Applying animation to the obstacle\n so that it can move towards left */\n.animateobstacle {\n animation: aniob 5s linear infinite;\n}\n@keyframes aniob {\n 0% {\n left:100vw;\n }\n 100% {\n left:-10vw;\n }\n}\n/* Dragon's styling */\n.dragon {\n background-image: url(dragon.png);\n background-size: cover;\n width: 194px;\n height: 126px;\n position: absolute;\n bottom:0px;\n left:90px;\n}\n/* Applying animation to the dragon so \nthat it can save himself by jumping up */\n.animatedragon {\n animation: ani 1s linear;\n}\n@keyframes ani {\n 0% {\n bottom:0px;\n }\n 25% {\n bottom:150px;\n }\n 50% {\n bottom:300px;\n }\n 75% {\n bottom:211px;\n }\n 100% {\n bottom:0px;\n }\n}\n/* gameover styling and positioning */\n.gameover {\n visibility: hidden;\n font-family: 'Ubuntu', sans-serif;\n position: absolute;\n top: 50vh;\n left: 35vw;\n color: red;\n font-weight: bold;\n font-size: 6rem;\n background-color: firebrick;\n border-radius: 20px;\n}\n"
},
{
"code": null,
"e": 30904,
"s": 30887,
"text": "JavaScript Code:"
},
{
"code": null,
"e": 30972,
"s": 30904,
"text": "1. Movement of the dragon: This is provided by the onkeydown event."
},
{
"code": null,
"e": 31059,
"s": 30972,
"text": "Up arrow key: On pressing it, the dragon will jump upwards (animation provide by CSS)."
},
{
"code": null,
"e": 31152,
"s": 31059,
"text": "Left arrow key: On pressing it, the dragon will move to the left (animation provide by CSS)."
},
{
"code": null,
"e": 31246,
"s": 31152,
"text": "Right arrow key: On pressing it, the dragon will move to the left (animation provide by CSS)."
},
{
"code": null,
"e": 32022,
"s": 31246,
"text": "document.onkeydown = function(e) {\n console.log(e.keyCode);\n if (e.keyCode == 38) {\n dragon = document.querySelector('.dragon');\n dragon.classList.add('animatedragon');\n setTimeout(() => {\n dragon.classList.remove('animatedragon');\n }, 700);\n }\n if (e.keyCode == 37) {\n dragon = document.querySelector('.dragon');\n dragonx = parseInt(window.getComputedStyle(dragon, null)\n .getPropertyValue('left'));\n dragon.style.left = dragonx - 112 + \"px\";\n }\n if (e.keyCode == 39) {\n dragon = document.querySelector('.dragon');\n dragonx = parseInt(window.getComputedStyle(\n dragon, null).getPropertyValue('left'));\n dragon.style.left = dragonx + 112 + \"px\";\n }\n}\n"
},
{
"code": null,
"e": 32616,
"s": 32022,
"text": "2. Updating the score: The score is satisfied only when a given condition is satisfied. We will compute the left and bottom values of both the obstacle and the dragon and then increase the score based on a proper value which shows that the dragon has saved himself from the obstacle. For this, we have taken “cross” variable and assigned “true” to it. When the the dragon crosses the obstacle safely, we set the value to “false”. After approximately 1s we change the value of cross to “true”. We have also made the obstacle run faster after each cross and thus increasing the difficulty level."
},
{
"code": null,
"e": 33982,
"s": 32616,
"text": "setInterval(() => {\n dragon = document.querySelector('.dragon');\n gameover = document.querySelector('.gameover');\n obstacle = document.querySelector('.obstacle');\n\n dx = parseInt(window.getComputedStyle(\n dragon, null).getPropertyValue('left'));\n\n dy = parseInt(window.getComputedStyle(\n dragon, null).getPropertyValue('bottom'));\n\n ox = parseInt(window.getComputedStyle(\n obstacle, null).getPropertyValue('left'));\n\n oy = parseInt(window.getComputedStyle(\n obstacle, null).getPropertyValue('bottom'));\n\n offsetx = Math.abs(dx - ox);\n offsety = Math.abs(dy - oy);\n\n console.log(offsetx, offsety);\n\n if (offsetx < 120 && offsety <= 144) {\n gameover.style.visibility = 'visible';\n obstacle.classList.remove('animateobstacle');\n } else if (offsetx < 125 && cross) {\n score += 1;\n updateScore(score);\n cross = false;\n setTimeout(() => {\n cross = true;\n }, 1000);\n setInterval(() => {\n obsanidur = parseFloat(window\n .getComputedStyle(obstacle, null)\n .getPropertyValue('animation-duration'));\n\n obstacle.style.animationDuration\n = obsanidur - 0.01 + 's';\n }, 500);\n }\n}, 10);\n\nfunction updateScore(score) {\n scorecount.innerHTML = \"Your score : \" + score;\n}\n"
},
{
"code": null,
"e": 33992,
"s": 33982,
"text": "script.js"
},
{
"code": "<script> cross = true; score = 0; document.onkeydown = function(e) { console.log(e.keyCode); if (e.keyCode == 38) { dragon = document.querySelector('.dragon'); dragon.classList.add('animatedragon'); setTimeout(() => { dragon.classList.remove('animatedragon'); }, 700); } if (e.keyCode == 37) { dragon = document.querySelector('.dragon'); dragonx = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('left')); dragon.style.left = dragonx - 112 + \"px\"; } if (e.keyCode == 39) { dragon = document.querySelector('.dragon'); dragonx = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('left')); dragon.style.left = dragonx + 112 + \"px\"; } } setInterval(() => { dragon = document.querySelector('.dragon'); gameover = document.querySelector('.gameover'); obstacle = document.querySelector('.obstacle'); dx = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('left')); dy = parseInt(window.getComputedStyle( dragon, null).getPropertyValue('bottom')); ox = parseInt(window.getComputedStyle( obstacle, null).getPropertyValue('left')); oy = parseInt(window.getComputedStyle( obstacle, null).getPropertyValue('bottom')); offsetx = Math.abs(dx - ox); offsety = Math.abs(dy - oy); console.log(offsetx, offsety); if (offsetx < 120 && offsety <= 144) { if (score != 0) scorecount.innerHTML = \"Your score : \" + score; gameover.style.visibility = 'visible'; obstacle.classList.remove('animateobstacle'); } else if (offsetx < 125 && cross) { score += 1; updateScore(score); cross = false; setTimeout(() => { cross = true; }, 1000); setInterval(() => { obsanidur = parseFloat(window .getComputedStyle(obstacle, null) .getPropertyValue('animation-duration')); obstacle.style.animationDuration = obsanidur - 0.01 + 's'; }, 500); } }, 10); function updateScore(score) { scorecount.innerHTML = \"Your score : \" + score; }</script>",
"e": 36485,
"s": 33992,
"text": null
},
{
"code": null,
"e": 36508,
"s": 36485,
"text": "Reference: Dragon game"
},
{
"code": null,
"e": 36516,
"s": 36508,
"text": "Output:"
},
{
"code": null,
"e": 36525,
"s": 36516,
"text": "CSS-Misc"
},
{
"code": null,
"e": 36535,
"s": 36525,
"text": "HTML-Misc"
},
{
"code": null,
"e": 36551,
"s": 36535,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 36575,
"s": 36551,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 36579,
"s": 36575,
"text": "CSS"
},
{
"code": null,
"e": 36584,
"s": 36579,
"text": "HTML"
},
{
"code": null,
"e": 36595,
"s": 36584,
"text": "JavaScript"
},
{
"code": null,
"e": 36614,
"s": 36595,
"text": "Technical Scripter"
},
{
"code": null,
"e": 36631,
"s": 36614,
"text": "Web Technologies"
},
{
"code": null,
"e": 36658,
"s": 36631,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 36663,
"s": 36658,
"text": "HTML"
},
{
"code": null,
"e": 36761,
"s": 36663,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36798,
"s": 36761,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 36837,
"s": 36798,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 36866,
"s": 36837,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 36908,
"s": 36866,
"text": "Search Bar using HTML, CSS and JavaScript"
},
{
"code": null,
"e": 36943,
"s": 36908,
"text": "How to style a checkbox using CSS?"
},
{
"code": null,
"e": 37003,
"s": 36943,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 37056,
"s": 37003,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 37117,
"s": 37056,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
},
{
"code": null,
"e": 37141,
"s": 37117,
"text": "REST API (Introduction)"
}
] |
PyQt5 - QDial - GeeksforGeeks | 07 Jul, 2020
QDial is a class in PyQt5 which provide user to select the value within a program-definable range, and the range either wraps around (for example, with angles measured from 0 to 359 degrees). Also, it can be used to show the current value in a similar way of speedometer. Below is how the QDial looks like
Example :A window having a QDial and user can change the value it and when user change the value the current value will get displayed in the label
Below is the implementation
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating QDial object dial = QDial(self) # setting geometry to the dial dial.setGeometry(100, 100, 100, 100) # adding action to the dial dial.valueChanged.connect(lambda: dial_method()) # creating a label label = QLabel("GeeksforGeeks", self) # setting geometry to the label label.setGeometry(220, 125, 200, 60) # making label multiline label.setWordWrap(True) # method called by the dial def dial_method(): # getting dial value value = dial.value() # setting text to the label label.setText("Current Value : " + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
Python PyQt-QDial
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python Classes and Objects
How to drop one or multiple columns in Pandas Dataframe
Python | Get unique values from a list
Defaultdict in Python
Python | os.path.join() method
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25562,
"s": 25534,
"text": "\n07 Jul, 2020"
},
{
"code": null,
"e": 25868,
"s": 25562,
"text": "QDial is a class in PyQt5 which provide user to select the value within a program-definable range, and the range either wraps around (for example, with angles measured from 0 to 359 degrees). Also, it can be used to show the current value in a similar way of speedometer. Below is how the QDial looks like"
},
{
"code": null,
"e": 26015,
"s": 25868,
"text": "Example :A window having a QDial and user can change the value it and when user change the value the current value will get displayed in the label"
},
{
"code": null,
"e": 26043,
"s": 26015,
"text": "Below is the implementation"
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 500, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for components def UiComponents(self): # creating QDial object dial = QDial(self) # setting geometry to the dial dial.setGeometry(100, 100, 100, 100) # adding action to the dial dial.valueChanged.connect(lambda: dial_method()) # creating a label label = QLabel(\"GeeksforGeeks\", self) # setting geometry to the label label.setGeometry(220, 125, 200, 60) # making label multiline label.setWordWrap(True) # method called by the dial def dial_method(): # getting dial value value = dial.value() # setting text to the label label.setText(\"Current Value : \" + str(value)) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27396,
"s": 26043,
"text": null
},
{
"code": null,
"e": 27405,
"s": 27396,
"text": "Output :"
},
{
"code": null,
"e": 27423,
"s": 27405,
"text": "Python PyQt-QDial"
},
{
"code": null,
"e": 27434,
"s": 27423,
"text": "Python-gui"
},
{
"code": null,
"e": 27446,
"s": 27434,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27453,
"s": 27446,
"text": "Python"
},
{
"code": null,
"e": 27551,
"s": 27453,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27583,
"s": 27551,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27625,
"s": 27583,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27667,
"s": 27625,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27694,
"s": 27667,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27750,
"s": 27694,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27789,
"s": 27750,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27811,
"s": 27789,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27842,
"s": 27811,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27871,
"s": 27842,
"text": "Create a directory in Python"
}
] |
HTML | readonly Attribute - GeeksforGeeks | 25 Mar, 2020
It is a Boolean attribute that is used to specify that the text written in input or text area Element is read-only. It means that a user can not modify or changes a content already present in a particular Element (However, a user can tab to it, highlight it, and copy the text from it). Whereas a JavaScript can be used to change the read-only value and make the input field editable.
Elements: This attribute is used with two elements which are listed below:
<input>: It is used to readonly attribute to read the content only.
<text-area> It is used to hold the readonly attribute.
Example: 1
Syntax:<input readonly>
<input readonly>
Program:<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in Input Element</h2> <form action=""> Email: <input type="text" name="email"> <br> Country: <input type="text" name="country" value="Noida" readonly> <br> <input type="submit" value="Submit"> </form></body> </html>
<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in Input Element</h2> <form action=""> Email: <input type="text" name="email"> <br> Country: <input type="text" name="country" value="Noida" readonly> <br> <input type="submit" value="Submit"> </form></body> </html>
Output:Example:2
Example:2
Syntax:<textarea readonly>
<textarea readonly>
Example:<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center; } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in input Element</h2> <textarea rows="4" cols="40" readonly> GeeksForGeeks is a good website for learning computer science. It is a computer science portal for geeks. </textarea></body> </html>
<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center; } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in input Element</h2> <textarea rows="4" cols="40" readonly> GeeksForGeeks is a good website for learning computer science. It is a computer science portal for geeks. </textarea></body> </html>
Output:Supported Browsers: The browsers supported by readonly attribute are listed below:Google ChromeInternet ExplorerFirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes
arrow_drop_upSave
Supported Browsers: The browsers supported by readonly attribute are listed below:
Google Chrome
Internet Explorer
Firefox
Opera
Safari
Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.
HTML-Attributes
Technical Scripter 2018
CSS
HTML
Technical Scripter
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to create footer to stay at the bottom of a Web page?
How to apply style to parent if it has child with CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS?
How to update Node.js and NPM to next version ?
How to set the default value for an HTML <select> element ?
Hide or show elements in HTML using display property | [
{
"code": null,
"e": 25076,
"s": 25048,
"text": "\n25 Mar, 2020"
},
{
"code": null,
"e": 25461,
"s": 25076,
"text": "It is a Boolean attribute that is used to specify that the text written in input or text area Element is read-only. It means that a user can not modify or changes a content already present in a particular Element (However, a user can tab to it, highlight it, and copy the text from it). Whereas a JavaScript can be used to change the read-only value and make the input field editable."
},
{
"code": null,
"e": 25536,
"s": 25461,
"text": "Elements: This attribute is used with two elements which are listed below:"
},
{
"code": null,
"e": 25604,
"s": 25536,
"text": "<input>: It is used to readonly attribute to read the content only."
},
{
"code": null,
"e": 25659,
"s": 25604,
"text": "<text-area> It is used to hold the readonly attribute."
},
{
"code": null,
"e": 25670,
"s": 25659,
"text": "Example: 1"
},
{
"code": null,
"e": 25694,
"s": 25670,
"text": "Syntax:<input readonly>"
},
{
"code": null,
"e": 25711,
"s": 25694,
"text": "<input readonly>"
},
{
"code": null,
"e": 26317,
"s": 25711,
"text": "Program:<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in Input Element</h2> <form action=\"\"> Email: <input type=\"text\" name=\"email\"> <br> Country: <input type=\"text\" name=\"country\" value=\"Noida\" readonly> <br> <input type=\"submit\" value=\"Submit\"> </form></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in Input Element</h2> <form action=\"\"> Email: <input type=\"text\" name=\"email\"> <br> Country: <input type=\"text\" name=\"country\" value=\"Noida\" readonly> <br> <input type=\"submit\" value=\"Submit\"> </form></body> </html>",
"e": 26915,
"s": 26317,
"text": null
},
{
"code": null,
"e": 26932,
"s": 26915,
"text": "Output:Example:2"
},
{
"code": null,
"e": 26942,
"s": 26932,
"text": "Example:2"
},
{
"code": null,
"e": 26969,
"s": 26942,
"text": "Syntax:<textarea readonly>"
},
{
"code": null,
"e": 26989,
"s": 26969,
"text": "<textarea readonly>"
},
{
"code": null,
"e": 27524,
"s": 26989,
"text": "Example:<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center; } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in input Element</h2> <textarea rows=\"4\" cols=\"40\" readonly> GeeksForGeeks is a good website for learning computer science. It is a computer science portal for geeks. </textarea></body> </html>"
},
{
"code": "<!DOCTYPE html><html> <head> <title>readonly attribute</title> <style> body { text-align: center; } h1, h2 { color: green; font-style: italic; } </style></head> <body> <h1>GeeksForGeeks</h1> <h2>readonly attribute in input Element</h2> <textarea rows=\"4\" cols=\"40\" readonly> GeeksForGeeks is a good website for learning computer science. It is a computer science portal for geeks. </textarea></body> </html>",
"e": 28051,
"s": 27524,
"text": null
},
{
"code": null,
"e": 28360,
"s": 28051,
"text": "Output:Supported Browsers: The browsers supported by readonly attribute are listed below:Google ChromeInternet ExplorerFirefoxOperaSafariAttention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course.My Personal Notes\narrow_drop_upSave"
},
{
"code": null,
"e": 28443,
"s": 28360,
"text": "Supported Browsers: The browsers supported by readonly attribute are listed below:"
},
{
"code": null,
"e": 28457,
"s": 28443,
"text": "Google Chrome"
},
{
"code": null,
"e": 28475,
"s": 28457,
"text": "Internet Explorer"
},
{
"code": null,
"e": 28483,
"s": 28475,
"text": "Firefox"
},
{
"code": null,
"e": 28489,
"s": 28483,
"text": "Opera"
},
{
"code": null,
"e": 28496,
"s": 28489,
"text": "Safari"
},
{
"code": null,
"e": 28633,
"s": 28496,
"text": "Attention reader! Don’t stop learning now. Get hold of all the important HTML concepts with the Web Design for Beginners | HTML course."
},
{
"code": null,
"e": 28649,
"s": 28633,
"text": "HTML-Attributes"
},
{
"code": null,
"e": 28673,
"s": 28649,
"text": "Technical Scripter 2018"
},
{
"code": null,
"e": 28677,
"s": 28673,
"text": "CSS"
},
{
"code": null,
"e": 28682,
"s": 28677,
"text": "HTML"
},
{
"code": null,
"e": 28701,
"s": 28682,
"text": "Technical Scripter"
},
{
"code": null,
"e": 28718,
"s": 28701,
"text": "Web Technologies"
},
{
"code": null,
"e": 28723,
"s": 28718,
"text": "HTML"
},
{
"code": null,
"e": 28821,
"s": 28723,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 28883,
"s": 28821,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 28933,
"s": 28883,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 28981,
"s": 28933,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29039,
"s": 28981,
"text": "How to create footer to stay at the bottom of a Web page?"
},
{
"code": null,
"e": 29094,
"s": 29039,
"text": "How to apply style to parent if it has child with CSS?"
},
{
"code": null,
"e": 29156,
"s": 29094,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 29206,
"s": 29156,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
},
{
"code": null,
"e": 29254,
"s": 29206,
"text": "How to update Node.js and NPM to next version ?"
},
{
"code": null,
"e": 29314,
"s": 29254,
"text": "How to set the default value for an HTML <select> element ?"
}
] |
Connect MySQL database using MySQL-Connector Python - GeeksforGeeks | 13 Sep, 2021
While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies.
In the following example we will be connecting to MySQL database using connect()Example:
Python3
# Python program to connect# to mysql database import mysql.connector # Connecting from the serverconn = mysql.connector.connect(user = 'username', host = 'localhost', database = 'database_name') print(conn) # Disconnecting from the serverconn.close()
Output:
Also for the same, we can use connection.MySQLConnection() class instead of connect():Example:
Python3
# Python program to connect# to mysql database from mysql.connector import connection # Connecting to the serverconn = connection.MySQLConnection(user = 'username', host = 'localhost', database = 'database_name') print(conn) # Disconnecting from the serverconn.close()
Output:
Another way is to pass the dictionary in the connect() function using ‘**’ operator:Example:
Python3
# Python program to connect# to mysql database from mysql.connector import connection dict = { 'user': 'root', 'host': 'localhost', 'database': 'College'} # Connecting to the serverconn = connection.MySQLConnection(**dict) print(conn) # Disconnecting from the serverconn.close()
Output:
saurabh1990aror
Python-mySQL
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Read JSON file using Python
Adding new column to existing DataFrame in Pandas
Python map() function
How to get column names in Pandas dataframe
Read a file line by line in Python
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python String | replace() | [
{
"code": null,
"e": 42675,
"s": 42647,
"text": "\n13 Sep, 2021"
},
{
"code": null,
"e": 43132,
"s": 42675,
"text": "While working with Python we need to work with databases, they may be of different types like MySQL, SQLite, NoSQL, etc. In this article, we will be looking forward to how to connect MySQL databases using MySQL Connector/Python.MySQL Connector module of Python is used to connect MySQL databases with the Python programs, it does that using the Python Database API Specification v2.0 (PEP 249). It uses the Python standard library and has no dependencies. "
},
{
"code": null,
"e": 43222,
"s": 43132,
"text": "In the following example we will be connecting to MySQL database using connect()Example: "
},
{
"code": null,
"e": 43230,
"s": 43222,
"text": "Python3"
},
{
"code": "# Python program to connect# to mysql database import mysql.connector # Connecting from the serverconn = mysql.connector.connect(user = 'username', host = 'localhost', database = 'database_name') print(conn) # Disconnecting from the serverconn.close()",
"e": 43543,
"s": 43230,
"text": null
},
{
"code": null,
"e": 43552,
"s": 43543,
"text": "Output: "
},
{
"code": null,
"e": 43648,
"s": 43552,
"text": "Also for the same, we can use connection.MySQLConnection() class instead of connect():Example: "
},
{
"code": null,
"e": 43656,
"s": 43648,
"text": "Python3"
},
{
"code": "# Python program to connect# to mysql database from mysql.connector import connection # Connecting to the serverconn = connection.MySQLConnection(user = 'username', host = 'localhost', database = 'database_name') print(conn) # Disconnecting from the serverconn.close()",
"e": 43984,
"s": 43656,
"text": null
},
{
"code": null,
"e": 43993,
"s": 43984,
"text": "Output: "
},
{
"code": null,
"e": 44087,
"s": 43993,
"text": "Another way is to pass the dictionary in the connect() function using ‘**’ operator:Example: "
},
{
"code": null,
"e": 44095,
"s": 44087,
"text": "Python3"
},
{
"code": "# Python program to connect# to mysql database from mysql.connector import connection dict = { 'user': 'root', 'host': 'localhost', 'database': 'College'} # Connecting to the serverconn = connection.MySQLConnection(**dict) print(conn) # Disconnecting from the serverconn.close()",
"e": 44379,
"s": 44095,
"text": null
},
{
"code": null,
"e": 44388,
"s": 44379,
"text": "Output: "
},
{
"code": null,
"e": 44406,
"s": 44390,
"text": "saurabh1990aror"
},
{
"code": null,
"e": 44419,
"s": 44406,
"text": "Python-mySQL"
},
{
"code": null,
"e": 44426,
"s": 44419,
"text": "Python"
},
{
"code": null,
"e": 44524,
"s": 44426,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 44552,
"s": 44524,
"text": "Read JSON file using Python"
},
{
"code": null,
"e": 44602,
"s": 44552,
"text": "Adding new column to existing DataFrame in Pandas"
},
{
"code": null,
"e": 44624,
"s": 44602,
"text": "Python map() function"
},
{
"code": null,
"e": 44668,
"s": 44624,
"text": "How to get column names in Pandas dataframe"
},
{
"code": null,
"e": 44703,
"s": 44668,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 44735,
"s": 44703,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 44757,
"s": 44735,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 44799,
"s": 44757,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 44829,
"s": 44799,
"text": "Iterate over a list in Python"
}
] |
Minimum number of given operations required to convert a string to another string - GeeksforGeeks | 28 May, 2021
Given two strings S and T of equal length. Both strings contain only the characters ‘0’ and ‘1’. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S:
Swap any two characters of the string.
Replace a ‘0’ with a ‘1’ or vice versa.
Examples:
Input: S = “011”, T = “101” Output: 1 Swap the first and second character.
Input: S = “010”, T = “101” Output: 2 Swap the first and second character and replace the third character with ‘1’.
Approach: Find 2 values for the string S, the number of indices that have 0 but should be 1 and the number of indices that have 1 but should be 0. The result would be the maximum of these 2 values since we can use swaps on the minimum of these 2 values and the remaining unmatched characters can be inverted i.e. ‘0’ can be changed to ‘1’ and ‘1’ can be changed to ‘0’.
Below is the implementation of the above approach:
C++
Java
Python3
C#
PHP
Javascript
// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum operations// of the given type required to convert// string s to string tint minOperations(string s, string t, int n){ int ct0 = 0, ct1 = 0; for (int i = 0; i < n; i++) { // Characters are already equal if (s[i] == t[i]) continue; // Increment count of 0s if (s[i] == '0') ct0++; // Increment count of 1s else ct1++; } return max(ct0, ct1);} // Driver codeint main(){ string s = "010", t = "101"; int n = s.length(); cout << minOperations(s, t, n); return 0;}
// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum// operations of the given type required// to convert string s to string tstatic int minOperations(String s, String t, int n){ int ct0 = 0, ct1 = 0; for (int i = 0; i < n; i++) { // Characters are already equal if (s.charAt(i) == t.charAt(i)) continue; // Increment count of 0s if (s.charAt(i) == '0') ct0++; // Increment count of 1s else ct1++; } return Math.max(ct0, ct1);} // Driver codepublic static void main(String args[]){ String s = "010", t = "101"; int n = s.length(); System.out.println(minOperations(s, t, n));}} // This code is contributed by// Surendra_Gangwar
# Python 3 implementation of the approach # Function to return the minimum operations# of the given type required to convert# string s to string tdef minOperations(s, t, n): ct0 = 0 ct1 = 0 for i in range(n): # Characters are already equal if (s[i] == t[i]): continue # Increment count of 0s if (s[i] == '0'): ct0 += 1 # Increment count of 1s else: ct1 += 1 return max(ct0, ct1) # Driver codeif __name__ == "__main__": s = "010" t = "101" n = len(s) print(minOperations(s, t, n)) # This code is contributed by ita_c
// C# implementation of the approachusing System;class GFG{ // Function to return the minimum operations// of the given type required to convert// string s to string tstatic int minOperations(string s, string t, int n){ int ct0 = 0, ct1 = 0; for (int i = 0; i < n; i++) { // Characters are already equal if (s[i] == t[i]) continue; // Increment count of 0s if (s[i] == '0') ct0++; // Increment count of 1s else ct1++; } return Math.Max(ct0, ct1);} // Driver codepublic static void Main(){ string s = "010", t = "101"; int n = s.Length; Console.Write(minOperations(s, t, n));}} // This code is contributed// by Akanksha Rai
<?php// PHP implementation of the approach // Function to return the minimum operations// of the given type required to convert// string s to string tfunction minOperations($s, $t, $n){ $ct0 = 0 ; $ct1 = 0; for ($i = 0; $i < $n; $i++) { // Characters are already equal if ($s[$i] == $t[$i]) continue; // Increment count of 0s if ($s[$i] == '0') $ct0++; // Increment count of 1s else $ct1++; } return max($ct0, $ct1);} // Driver code$s = "010"; $t = "101";$n = strlen($s);echo minOperations($s, $t, $n); // This code is contributed by Ryuga?>
<script> // JavaScript implementation of the approach // Function to return the minimum operations// of the given type required to convert// string s to string tfunction minOperations(s, t, n){ var ct0 = 0, ct1 = 0; for(var i = 0; i < n; i++) { // Characters are already equal if (s[i] === t[i]) continue; // Increment count of 0s if (s[i] === "0") ct0++; // Increment count of 1s else ct1++; } return Math.max(ct0, ct1);} // Driver codevar s = "010",t = "101";var n = s.length; document.write(minOperations(s, t, n)); // This code is contributed by rdtank </script>
2
Time Complexity: O(N)
ankthon
ukasp
SURENDRA_GANGWAR
Akanksha_Rai
rdtank
array-traversal-question
binary-string
Strings
Strings
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Check for Balanced Brackets in an expression (well-formedness) using Stack
Python program to check if a string is palindrome or not
KMP Algorithm for Pattern Searching
Different methods to reverse a string in C/C++
Array of Strings in C++ (5 Different Ways to Create)
Convert string to char array in C++
Longest Palindromic Substring | Set 1
Caesar Cipher in Cryptography
Check whether two strings are anagram of each other
Top 50 String Coding Problems for Interviews | [
{
"code": null,
"e": 26191,
"s": 26163,
"text": "\n28 May, 2021"
},
{
"code": null,
"e": 26421,
"s": 26191,
"text": "Given two strings S and T of equal length. Both strings contain only the characters ‘0’ and ‘1’. The task is to find the minimum number of operations to convert string S to T. There are 2 types of operations allowed on string S: "
},
{
"code": null,
"e": 26460,
"s": 26421,
"text": "Swap any two characters of the string."
},
{
"code": null,
"e": 26500,
"s": 26460,
"text": "Replace a ‘0’ with a ‘1’ or vice versa."
},
{
"code": null,
"e": 26511,
"s": 26500,
"text": "Examples: "
},
{
"code": null,
"e": 26586,
"s": 26511,
"text": "Input: S = “011”, T = “101” Output: 1 Swap the first and second character."
},
{
"code": null,
"e": 26704,
"s": 26586,
"text": "Input: S = “010”, T = “101” Output: 2 Swap the first and second character and replace the third character with ‘1’. "
},
{
"code": null,
"e": 27074,
"s": 26704,
"text": "Approach: Find 2 values for the string S, the number of indices that have 0 but should be 1 and the number of indices that have 1 but should be 0. The result would be the maximum of these 2 values since we can use swaps on the minimum of these 2 values and the remaining unmatched characters can be inverted i.e. ‘0’ can be changed to ‘1’ and ‘1’ can be changed to ‘0’."
},
{
"code": null,
"e": 27127,
"s": 27074,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 27131,
"s": 27127,
"text": "C++"
},
{
"code": null,
"e": 27136,
"s": 27131,
"text": "Java"
},
{
"code": null,
"e": 27144,
"s": 27136,
"text": "Python3"
},
{
"code": null,
"e": 27147,
"s": 27144,
"text": "C#"
},
{
"code": null,
"e": 27151,
"s": 27147,
"text": "PHP"
},
{
"code": null,
"e": 27162,
"s": 27151,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include <bits/stdc++.h>using namespace std; // Function to return the minimum operations// of the given type required to convert// string s to string tint minOperations(string s, string t, int n){ int ct0 = 0, ct1 = 0; for (int i = 0; i < n; i++) { // Characters are already equal if (s[i] == t[i]) continue; // Increment count of 0s if (s[i] == '0') ct0++; // Increment count of 1s else ct1++; } return max(ct0, ct1);} // Driver codeint main(){ string s = \"010\", t = \"101\"; int n = s.length(); cout << minOperations(s, t, n); return 0;}",
"e": 27842,
"s": 27162,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; class GFG{ // Function to return the minimum// operations of the given type required// to convert string s to string tstatic int minOperations(String s, String t, int n){ int ct0 = 0, ct1 = 0; for (int i = 0; i < n; i++) { // Characters are already equal if (s.charAt(i) == t.charAt(i)) continue; // Increment count of 0s if (s.charAt(i) == '0') ct0++; // Increment count of 1s else ct1++; } return Math.max(ct0, ct1);} // Driver codepublic static void main(String args[]){ String s = \"010\", t = \"101\"; int n = s.length(); System.out.println(minOperations(s, t, n));}} // This code is contributed by// Surendra_Gangwar",
"e": 28645,
"s": 27842,
"text": null
},
{
"code": "# Python 3 implementation of the approach # Function to return the minimum operations# of the given type required to convert# string s to string tdef minOperations(s, t, n): ct0 = 0 ct1 = 0 for i in range(n): # Characters are already equal if (s[i] == t[i]): continue # Increment count of 0s if (s[i] == '0'): ct0 += 1 # Increment count of 1s else: ct1 += 1 return max(ct0, ct1) # Driver codeif __name__ == \"__main__\": s = \"010\" t = \"101\" n = len(s) print(minOperations(s, t, n)) # This code is contributed by ita_c",
"e": 29270,
"s": 28645,
"text": null
},
{
"code": "// C# implementation of the approachusing System;class GFG{ // Function to return the minimum operations// of the given type required to convert// string s to string tstatic int minOperations(string s, string t, int n){ int ct0 = 0, ct1 = 0; for (int i = 0; i < n; i++) { // Characters are already equal if (s[i] == t[i]) continue; // Increment count of 0s if (s[i] == '0') ct0++; // Increment count of 1s else ct1++; } return Math.Max(ct0, ct1);} // Driver codepublic static void Main(){ string s = \"010\", t = \"101\"; int n = s.Length; Console.Write(minOperations(s, t, n));}} // This code is contributed// by Akanksha Rai",
"e": 30021,
"s": 29270,
"text": null
},
{
"code": "<?php// PHP implementation of the approach // Function to return the minimum operations// of the given type required to convert// string s to string tfunction minOperations($s, $t, $n){ $ct0 = 0 ; $ct1 = 0; for ($i = 0; $i < $n; $i++) { // Characters are already equal if ($s[$i] == $t[$i]) continue; // Increment count of 0s if ($s[$i] == '0') $ct0++; // Increment count of 1s else $ct1++; } return max($ct0, $ct1);} // Driver code$s = \"010\"; $t = \"101\";$n = strlen($s);echo minOperations($s, $t, $n); // This code is contributed by Ryuga?>",
"e": 30657,
"s": 30021,
"text": null
},
{
"code": "<script> // JavaScript implementation of the approach // Function to return the minimum operations// of the given type required to convert// string s to string tfunction minOperations(s, t, n){ var ct0 = 0, ct1 = 0; for(var i = 0; i < n; i++) { // Characters are already equal if (s[i] === t[i]) continue; // Increment count of 0s if (s[i] === \"0\") ct0++; // Increment count of 1s else ct1++; } return Math.max(ct0, ct1);} // Driver codevar s = \"010\",t = \"101\";var n = s.length; document.write(minOperations(s, t, n)); // This code is contributed by rdtank </script>",
"e": 31339,
"s": 30657,
"text": null
},
{
"code": null,
"e": 31341,
"s": 31339,
"text": "2"
},
{
"code": null,
"e": 31366,
"s": 31343,
"text": "Time Complexity: O(N) "
},
{
"code": null,
"e": 31374,
"s": 31366,
"text": "ankthon"
},
{
"code": null,
"e": 31380,
"s": 31374,
"text": "ukasp"
},
{
"code": null,
"e": 31397,
"s": 31380,
"text": "SURENDRA_GANGWAR"
},
{
"code": null,
"e": 31410,
"s": 31397,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 31417,
"s": 31410,
"text": "rdtank"
},
{
"code": null,
"e": 31442,
"s": 31417,
"text": "array-traversal-question"
},
{
"code": null,
"e": 31456,
"s": 31442,
"text": "binary-string"
},
{
"code": null,
"e": 31464,
"s": 31456,
"text": "Strings"
},
{
"code": null,
"e": 31472,
"s": 31464,
"text": "Strings"
},
{
"code": null,
"e": 31570,
"s": 31472,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 31645,
"s": 31570,
"text": "Check for Balanced Brackets in an expression (well-formedness) using Stack"
},
{
"code": null,
"e": 31702,
"s": 31645,
"text": "Python program to check if a string is palindrome or not"
},
{
"code": null,
"e": 31738,
"s": 31702,
"text": "KMP Algorithm for Pattern Searching"
},
{
"code": null,
"e": 31785,
"s": 31738,
"text": "Different methods to reverse a string in C/C++"
},
{
"code": null,
"e": 31838,
"s": 31785,
"text": "Array of Strings in C++ (5 Different Ways to Create)"
},
{
"code": null,
"e": 31874,
"s": 31838,
"text": "Convert string to char array in C++"
},
{
"code": null,
"e": 31912,
"s": 31874,
"text": "Longest Palindromic Substring | Set 1"
},
{
"code": null,
"e": 31942,
"s": 31912,
"text": "Caesar Cipher in Cryptography"
},
{
"code": null,
"e": 31994,
"s": 31942,
"text": "Check whether two strings are anagram of each other"
}
] |
Strings in C | 09 Dec, 2020
Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\0’.
Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string.
char str_name[size];
In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store. Please keep in mind that there is an extra terminating character which is the Null character (‘\0’) used to indicate the termination of string which differs strings from normal character arrays.
Initializing a String: A string can be initialized in different ways. We will explain this with the help of an example. Below is an example to declare a string with name as str and initialize it with “GeeksforGeeks”.
1. char str[] = "GeeksforGeeks";
2. char str[50] = "GeeksforGeeks";
3. char str[] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
4. char str[14] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\0'};
Below is the memory representation of a string “Geeks”.
Let us now look at a sample program to get a clear understanding of declaring and initializing a string in C and also how to print a string.
// C program to illustrate strings #include<stdio.h> int main(){ // declare and initialize string char str[] = "Geeks"; // print string printf("%s",str); return 0;}
Output:
Geeks
We can see in the above program that strings can be printed using normal printf statements just like we print any other variable. Unlike arrays, we do not need to print a string, character by character. The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to directly print and read strings.
Below is a sample program to read a string from user:
// C program to read strings #include<stdio.h> int main(){ // declaring string char str[50]; // reading string scanf("%s",str); // print string printf("%s",str); return 0;}
You can see in the above program that string can also be read using a single scanf statement. Also, you might be thinking that why we have not used the ‘&’ sign with string name ‘str’ in scanf statement! To understand this you will have to recall your knowledge of scanf. We know that the ‘&’ sign is used to provide the address of the variable to the scanf() function to store the value read in memory. As str[] is a character array so using str without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case as we are already providing the base address of the string to scanf.
Passing strings to function: As strings are character arrays, so we can pass strings to function in a same way we pass an array to a function. Below is a sample program to do this:
// C program to illustrate how to // pass string to functions#include<stdio.h> void printStr(char str[]){ printf("String is : %s",str);} int main(){ // declare and initialize string char str[] = "GeeksforGeeks"; // print string by passing string // to a different function printStr(str); return 0;}
Output:
String is : GeeksforGeeks
Related Articles:
puts() vs printf() to print a string
Swap strings in C
Storage for strings in C
gets() is risky to use!
This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
C-String
cpp-string
C Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Header files in C/C++ and its uses
C Program to read contents of Whole File
How to return multiple values from a function in C or C++?
C++ Program to check Prime Number
Producer Consumer Problem in C
C Program to Swap two Numbers
C program to sort an array in ascending order
Program to find Prime Numbers Between given Interval
Set, Clear and Toggle a given bit of a number in C
time() function in C | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n09 Dec, 2020"
},
{
"code": null,
"e": 212,
"s": 52,
"text": "Strings are defined as an array of characters. The difference between a character array and a string is the string is terminated with a special character ‘\\0’."
},
{
"code": null,
"e": 356,
"s": 212,
"text": "Declaration of strings: Declaring a string is as simple as declaring a one-dimensional array. Below is the basic syntax for declaring a string."
},
{
"code": null,
"e": 378,
"s": 356,
"text": "char str_name[size];\n"
},
{
"code": null,
"e": 745,
"s": 378,
"text": "In the above syntax str_name is any name given to the string variable and size is used to define the length of the string, i.e the number of characters strings will store. Please keep in mind that there is an extra terminating character which is the Null character (‘\\0’) used to indicate the termination of string which differs strings from normal character arrays."
},
{
"code": null,
"e": 962,
"s": 745,
"text": "Initializing a String: A string can be initialized in different ways. We will explain this with the help of an example. Below is an example to declare a string with name as str and initialize it with “GeeksforGeeks”."
},
{
"code": null,
"e": 1188,
"s": 962,
"text": "1. char str[] = \"GeeksforGeeks\";\n\n2. char str[50] = \"GeeksforGeeks\";\n\n3. char str[] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\\0'};\n\n4. char str[14] = {'G','e','e','k','s','f','o','r','G','e','e','k','s','\\0'};\n"
},
{
"code": null,
"e": 1244,
"s": 1188,
"text": "Below is the memory representation of a string “Geeks”."
},
{
"code": null,
"e": 1385,
"s": 1244,
"text": "Let us now look at a sample program to get a clear understanding of declaring and initializing a string in C and also how to print a string."
},
{
"code": "// C program to illustrate strings #include<stdio.h> int main(){ // declare and initialize string char str[] = \"Geeks\"; // print string printf(\"%s\",str); return 0;}",
"e": 1582,
"s": 1385,
"text": null
},
{
"code": null,
"e": 1590,
"s": 1582,
"text": "Output:"
},
{
"code": null,
"e": 1597,
"s": 1590,
"text": "Geeks\n"
},
{
"code": null,
"e": 1955,
"s": 1597,
"text": "We can see in the above program that strings can be printed using normal printf statements just like we print any other variable. Unlike arrays, we do not need to print a string, character by character. The C language does not provide an inbuilt data type for strings but it has an access specifier “%s” which can be used to directly print and read strings."
},
{
"code": null,
"e": 2009,
"s": 1955,
"text": "Below is a sample program to read a string from user:"
},
{
"code": "// C program to read strings #include<stdio.h> int main(){ // declaring string char str[50]; // reading string scanf(\"%s\",str); // print string printf(\"%s\",str); return 0;}",
"e": 2222,
"s": 2009,
"text": null
},
{
"code": null,
"e": 2853,
"s": 2222,
"text": "You can see in the above program that string can also be read using a single scanf statement. Also, you might be thinking that why we have not used the ‘&’ sign with string name ‘str’ in scanf statement! To understand this you will have to recall your knowledge of scanf. We know that the ‘&’ sign is used to provide the address of the variable to the scanf() function to store the value read in memory. As str[] is a character array so using str without braces ‘[‘ and ‘]’ will give the base address of this string. That’s why we have not used ‘&’ in this case as we are already providing the base address of the string to scanf."
},
{
"code": null,
"e": 3034,
"s": 2853,
"text": "Passing strings to function: As strings are character arrays, so we can pass strings to function in a same way we pass an array to a function. Below is a sample program to do this:"
},
{
"code": "// C program to illustrate how to // pass string to functions#include<stdio.h> void printStr(char str[]){ printf(\"String is : %s\",str);} int main(){ // declare and initialize string char str[] = \"GeeksforGeeks\"; // print string by passing string // to a different function printStr(str); return 0;}",
"e": 3371,
"s": 3034,
"text": null
},
{
"code": null,
"e": 3379,
"s": 3371,
"text": "Output:"
},
{
"code": null,
"e": 3406,
"s": 3379,
"text": "String is : GeeksforGeeks\n"
},
{
"code": null,
"e": 3424,
"s": 3406,
"text": "Related Articles:"
},
{
"code": null,
"e": 3461,
"s": 3424,
"text": "puts() vs printf() to print a string"
},
{
"code": null,
"e": 3479,
"s": 3461,
"text": "Swap strings in C"
},
{
"code": null,
"e": 3504,
"s": 3479,
"text": "Storage for strings in C"
},
{
"code": null,
"e": 3528,
"s": 3504,
"text": "gets() is risky to use!"
},
{
"code": null,
"e": 3829,
"s": 3528,
"text": "This article is contributed by Harsh Agarwal. If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 3954,
"s": 3829,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 3963,
"s": 3954,
"text": "C-String"
},
{
"code": null,
"e": 3974,
"s": 3963,
"text": "cpp-string"
},
{
"code": null,
"e": 3985,
"s": 3974,
"text": "C Programs"
},
{
"code": null,
"e": 4083,
"s": 3985,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4118,
"s": 4083,
"text": "Header files in C/C++ and its uses"
},
{
"code": null,
"e": 4159,
"s": 4118,
"text": "C Program to read contents of Whole File"
},
{
"code": null,
"e": 4218,
"s": 4159,
"text": "How to return multiple values from a function in C or C++?"
},
{
"code": null,
"e": 4252,
"s": 4218,
"text": "C++ Program to check Prime Number"
},
{
"code": null,
"e": 4283,
"s": 4252,
"text": "Producer Consumer Problem in C"
},
{
"code": null,
"e": 4313,
"s": 4283,
"text": "C Program to Swap two Numbers"
},
{
"code": null,
"e": 4359,
"s": 4313,
"text": "C program to sort an array in ascending order"
},
{
"code": null,
"e": 4412,
"s": 4359,
"text": "Program to find Prime Numbers Between given Interval"
},
{
"code": null,
"e": 4463,
"s": 4412,
"text": "Set, Clear and Toggle a given bit of a number in C"
}
] |
numpy.diag() in Python | 09 Mar, 2022
numpy.diag(a, k=0) : Extracts and construct a diagonal array Parameters :
a : array_like
k : [int, optional, 0 by default]
Diagonal we require; k>0 means diagonal above main diagonal or vice versa.
Returns :
ndarray
Python
# Python Programming illustrating# numpy.diag method import numpy as geek # matrix creation by array inputa = geek.matrix([[1, 21, 30], [63 ,434, 3], [54, 54, 56]]) print("Main Diagonal elements : \n", geek.diag(a), "\n") print("Diagonal above main diagonal : \n", geek.diag(a, 1), "\n") print("Diagonal below main diagonal : \n", geek.diag(a, -1))
Output :
Main Diagonal elements :
[ 1 434 56]
Diagonal above main diagonal :
[21 3]
Diagonal below main diagonal :
[63 54]
References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.diagflat.html#numpy.diagflat Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
gabaa406
vinayedula
Python numpy-arrayCreation
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Mar, 2022"
},
{
"code": null,
"e": 103,
"s": 28,
"text": "numpy.diag(a, k=0) : Extracts and construct a diagonal array Parameters : "
},
{
"code": null,
"e": 238,
"s": 103,
"text": "a : array_like \nk : [int, optional, 0 by default]\n Diagonal we require; k>0 means diagonal above main diagonal or vice versa."
},
{
"code": null,
"e": 249,
"s": 238,
"text": "Returns : "
},
{
"code": null,
"e": 257,
"s": 249,
"text": "ndarray"
},
{
"code": null,
"e": 264,
"s": 257,
"text": "Python"
},
{
"code": "# Python Programming illustrating# numpy.diag method import numpy as geek # matrix creation by array inputa = geek.matrix([[1, 21, 30], [63 ,434, 3], [54, 54, 56]]) print(\"Main Diagonal elements : \\n\", geek.diag(a), \"\\n\") print(\"Diagonal above main diagonal : \\n\", geek.diag(a, 1), \"\\n\") print(\"Diagonal below main diagonal : \\n\", geek.diag(a, -1))",
"e": 652,
"s": 264,
"text": null
},
{
"code": null,
"e": 663,
"s": 652,
"text": "Output : "
},
{
"code": null,
"e": 790,
"s": 663,
"text": "Main Diagonal elements : \n [ 1 434 56] \n\nDiagonal above main diagonal : \n [21 3] \n\nDiagonal below main diagonal : \n [63 54]"
},
{
"code": null,
"e": 1424,
"s": 790,
"text": "References : https://docs.scipy.org/doc/numpy/reference/generated/numpy.diagflat.html#numpy.diagflat Note : These NumPy-Python programs won’t run on online IDE’s, so run them on your systems to explore them . This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above. "
},
{
"code": null,
"e": 1433,
"s": 1424,
"text": "gabaa406"
},
{
"code": null,
"e": 1444,
"s": 1433,
"text": "vinayedula"
},
{
"code": null,
"e": 1471,
"s": 1444,
"text": "Python numpy-arrayCreation"
},
{
"code": null,
"e": 1484,
"s": 1471,
"text": "Python-numpy"
},
{
"code": null,
"e": 1491,
"s": 1484,
"text": "Python"
}
] |
JavaFX | AnchorPane Class | 11 Sep, 2018
AnchorPane class is a part of JavaFX. AnchorPane allows the edges of child nodes to be anchored to an offset from the anchor pane’s edges. If the anchor pane has a border and/or padding set, the offsets will be measured from the inside edge of those insets. AnchorPane inherits Pane class.
Constructors of the class:
AnchorPane(): Creates a new AnchorPane.AnchorPane(Node... c): Creates a AnchorPane with specified nodes.
AnchorPane(): Creates a new AnchorPane.
AnchorPane(Node... c): Creates a AnchorPane with specified nodes.
Commonly Used Methods:
Below programs illustrate the use of the AnchorPane Class:
Java Program to create a AnchorPane and add label to it and add label to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane and set the top, bottom, left, right using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Now add the anchor_pane to the Scene. Then finally add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane and// add label to it and add label to the // stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("AnchorPane"); // create a label Label label = new Label("this is AnchorPane example"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 10.0); AnchorPane.setBottomAnchor(label, 10.0); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a AnchorPane, adding label and button to it and also setting the min height and width of AnchorPane then add it to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane. Also add a Button named button and set the top, bottom, left, right anchor using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Set the min height and width using the setMinHeight() and setMinWidth() function. Add the anchor_pane to the Scene. Finally, add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane, adding// label and button to it and also setting the // min height and width of AnchorPane then add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("AnchorPane"); // create a label Label label = new Label("this is AnchorPane example"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 120.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 230.0); AnchorPane.setBottomAnchor(label, 120.0); Button button = new Button("button "); // anchor to the button AnchorPane.setTopAnchor(button, 125.0); AnchorPane.setLeftAnchor(button, 220.0); AnchorPane.setRightAnchor(button, 110.0); AnchorPane.setBottomAnchor(button, 125.0); anchor_pane.getChildren().add(button); anchor_pane.setMinHeight(400); anchor_pane.setMinWidth(400); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
Java Program to create a AnchorPane and add label to it and add label to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane and set the top, bottom, left, right using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Now add the anchor_pane to the Scene. Then finally add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane and// add label to it and add label to the // stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("AnchorPane"); // create a label Label label = new Label("this is AnchorPane example"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 10.0); AnchorPane.setBottomAnchor(label, 10.0); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a AnchorPane and// add label to it and add label to the // stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("AnchorPane"); // create a label Label label = new Label("this is AnchorPane example"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 10.0); AnchorPane.setBottomAnchor(label, 10.0); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Java Program to create a AnchorPane, adding label and button to it and also setting the min height and width of AnchorPane then add it to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane. Also add a Button named button and set the top, bottom, left, right anchor using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Set the min height and width using the setMinHeight() and setMinWidth() function. Add the anchor_pane to the Scene. Finally, add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane, adding// label and button to it and also setting the // min height and width of AnchorPane then add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("AnchorPane"); // create a label Label label = new Label("this is AnchorPane example"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 120.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 230.0); AnchorPane.setBottomAnchor(label, 120.0); Button button = new Button("button "); // anchor to the button AnchorPane.setTopAnchor(button, 125.0); AnchorPane.setLeftAnchor(button, 220.0); AnchorPane.setRightAnchor(button, 110.0); AnchorPane.setBottomAnchor(button, 125.0); anchor_pane.getChildren().add(button); anchor_pane.setMinHeight(400); anchor_pane.setMinWidth(400); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:
// Java Program to create a AnchorPane, adding// label and button to it and also setting the // min height and width of AnchorPane then add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle("AnchorPane"); // create a label Label label = new Label("this is AnchorPane example"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 120.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 230.0); AnchorPane.setBottomAnchor(label, 120.0); Button button = new Button("button "); // anchor to the button AnchorPane.setTopAnchor(button, 125.0); AnchorPane.setLeftAnchor(button, 220.0); AnchorPane.setRightAnchor(button, 110.0); AnchorPane.setBottomAnchor(button, 125.0); anchor_pane.getChildren().add(button); anchor_pane.setMinHeight(400); anchor_pane.setMinWidth(400); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}
Output:
Note: The above programs might not run in an online IDE please use an offline compiler.
Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/AnchorPane.html
JavaFX
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Stream In Java
Introduction to Java
Constructors in Java
Exceptions in Java
Generics in Java
Functional Interfaces in Java
Strings in Java
Java Programming Examples
HashSet in Java
Abstraction in Java | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Sep, 2018"
},
{
"code": null,
"e": 318,
"s": 28,
"text": "AnchorPane class is a part of JavaFX. AnchorPane allows the edges of child nodes to be anchored to an offset from the anchor pane’s edges. If the anchor pane has a border and/or padding set, the offsets will be measured from the inside edge of those insets. AnchorPane inherits Pane class."
},
{
"code": null,
"e": 345,
"s": 318,
"text": "Constructors of the class:"
},
{
"code": null,
"e": 450,
"s": 345,
"text": "AnchorPane(): Creates a new AnchorPane.AnchorPane(Node... c): Creates a AnchorPane with specified nodes."
},
{
"code": null,
"e": 490,
"s": 450,
"text": "AnchorPane(): Creates a new AnchorPane."
},
{
"code": null,
"e": 556,
"s": 490,
"text": "AnchorPane(Node... c): Creates a AnchorPane with specified nodes."
},
{
"code": null,
"e": 579,
"s": 556,
"text": "Commonly Used Methods:"
},
{
"code": null,
"e": 638,
"s": 579,
"text": "Below programs illustrate the use of the AnchorPane Class:"
},
{
"code": null,
"e": 5223,
"s": 638,
"text": "Java Program to create a AnchorPane and add label to it and add label to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane and set the top, bottom, left, right using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Now add the anchor_pane to the Scene. Then finally add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane and// add label to it and add label to the // stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"AnchorPane\"); // create a label Label label = new Label(\"this is AnchorPane example\"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 10.0); AnchorPane.setBottomAnchor(label, 10.0); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:Java Program to create a AnchorPane, adding label and button to it and also setting the min height and width of AnchorPane then add it to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane. Also add a Button named button and set the top, bottom, left, right anchor using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Set the min height and width using the setMinHeight() and setMinWidth() function. Add the anchor_pane to the Scene. Finally, add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane, adding// label and button to it and also setting the // min height and width of AnchorPane then add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"AnchorPane\"); // create a label Label label = new Label(\"this is AnchorPane example\"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 120.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 230.0); AnchorPane.setBottomAnchor(label, 120.0); Button button = new Button(\"button \"); // anchor to the button AnchorPane.setTopAnchor(button, 125.0); AnchorPane.setLeftAnchor(button, 220.0); AnchorPane.setRightAnchor(button, 110.0); AnchorPane.setBottomAnchor(button, 125.0); anchor_pane.getChildren().add(button); anchor_pane.setMinHeight(400); anchor_pane.setMinWidth(400); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": null,
"e": 7174,
"s": 5223,
"text": "Java Program to create a AnchorPane and add label to it and add label to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane and set the top, bottom, left, right using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Now add the anchor_pane to the Scene. Then finally add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane and// add label to it and add label to the // stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"AnchorPane\"); // create a label Label label = new Label(\"this is AnchorPane example\"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 10.0); AnchorPane.setBottomAnchor(label, 10.0); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a AnchorPane and// add label to it and add label to the // stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_1 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"AnchorPane\"); // create a label Label label = new Label(\"this is AnchorPane example\"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 10.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 10.0); AnchorPane.setBottomAnchor(label, 10.0); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 8658,
"s": 7174,
"text": null
},
{
"code": null,
"e": 8666,
"s": 8658,
"text": "Output:"
},
{
"code": null,
"e": 11301,
"s": 8666,
"text": "Java Program to create a AnchorPane, adding label and button to it and also setting the min height and width of AnchorPane then add it to the stage: In this program we will create a AnchorPane named anchor_pane. Add a Label named label to the anchor_pane. Also add a Button named button and set the top, bottom, left, right anchor using the setTopAnchor(), setBottomAnchor(), setLeftAnchor(), setRightAnchor() functions respectively. Set the min height and width using the setMinHeight() and setMinWidth() function. Add the anchor_pane to the Scene. Finally, add the scene to the stage and call the show() function to display the results.// Java Program to create a AnchorPane, adding// label and button to it and also setting the // min height and width of AnchorPane then add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"AnchorPane\"); // create a label Label label = new Label(\"this is AnchorPane example\"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 120.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 230.0); AnchorPane.setBottomAnchor(label, 120.0); Button button = new Button(\"button \"); // anchor to the button AnchorPane.setTopAnchor(button, 125.0); AnchorPane.setLeftAnchor(button, 220.0); AnchorPane.setRightAnchor(button, 110.0); AnchorPane.setBottomAnchor(button, 125.0); anchor_pane.getChildren().add(button); anchor_pane.setMinHeight(400); anchor_pane.setMinWidth(400); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}Output:"
},
{
"code": "// Java Program to create a AnchorPane, adding// label and button to it and also setting the // min height and width of AnchorPane then add// it to the stageimport javafx.application.Application;import javafx.scene.Scene;import javafx.scene.control.*;import javafx.scene.layout.*;import javafx.stage.Stage;import javafx.event.ActionEvent;import javafx.event.EventHandler;import javafx.scene.canvas.*;import javafx.scene.web.*;import javafx.scene.layout.AnchorPane;import javafx.scene.shape.*; public class AnchorPane_2 extends Application { // launch the application public void start(Stage stage) { try { // set title for the stage stage.setTitle(\"AnchorPane\"); // create a label Label label = new Label(\"this is AnchorPane example\"); // create a AnchorPane AnchorPane anchor_pane = new AnchorPane(label); // anchor to the label AnchorPane.setTopAnchor(label, 120.0); AnchorPane.setLeftAnchor(label, 10.0); AnchorPane.setRightAnchor(label, 230.0); AnchorPane.setBottomAnchor(label, 120.0); Button button = new Button(\"button \"); // anchor to the button AnchorPane.setTopAnchor(button, 125.0); AnchorPane.setLeftAnchor(button, 220.0); AnchorPane.setRightAnchor(button, 110.0); AnchorPane.setBottomAnchor(button, 125.0); anchor_pane.getChildren().add(button); anchor_pane.setMinHeight(400); anchor_pane.setMinWidth(400); // create a scene Scene scene = new Scene(anchor_pane, 400, 300); // set the scene stage.setScene(scene); stage.show(); } catch (Exception e) { System.out.println(e.getMessage()); } } // Main Method public static void main(String args[]) { // launch the application launch(args); }}",
"e": 13291,
"s": 11301,
"text": null
},
{
"code": null,
"e": 13299,
"s": 13291,
"text": "Output:"
},
{
"code": null,
"e": 13387,
"s": 13299,
"text": "Note: The above programs might not run in an online IDE please use an offline compiler."
},
{
"code": null,
"e": 13478,
"s": 13387,
"text": "Reference: https://docs.oracle.com/javase/8/javafx/api/javafx/scene/layout/AnchorPane.html"
},
{
"code": null,
"e": 13485,
"s": 13478,
"text": "JavaFX"
},
{
"code": null,
"e": 13490,
"s": 13485,
"text": "Java"
},
{
"code": null,
"e": 13495,
"s": 13490,
"text": "Java"
},
{
"code": null,
"e": 13593,
"s": 13495,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13608,
"s": 13593,
"text": "Stream In Java"
},
{
"code": null,
"e": 13629,
"s": 13608,
"text": "Introduction to Java"
},
{
"code": null,
"e": 13650,
"s": 13629,
"text": "Constructors in Java"
},
{
"code": null,
"e": 13669,
"s": 13650,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 13686,
"s": 13669,
"text": "Generics in Java"
},
{
"code": null,
"e": 13716,
"s": 13686,
"text": "Functional Interfaces in Java"
},
{
"code": null,
"e": 13732,
"s": 13716,
"text": "Strings in Java"
},
{
"code": null,
"e": 13758,
"s": 13732,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 13774,
"s": 13758,
"text": "HashSet in Java"
}
] |
How can we find the employees from MySQL table whose age is greater than say 30 years, providing the only date of birth on the table? | To understand this concept, we are using the data from table ‘emp_tbl’ as follows −
mysql> Select * from emp_tbl;
+--------+------------+
| Name | DOB |
+--------+------------+
| Gaurav | 1984-01-17 |
| Gaurav | 1990-01-17 |
| Rahul | 1980-05-22 |
| Gurdas | 1981-05-25 |
| Naveen | 1991-04-25 |
| Sohan | 1987-12-26 |
+--------+------------+
6 rows in set (0.00 sec)
mysql> SELECT Name,SYSDATE(),DOB,DATEDIFF(SYSDATE(),DOB)/365 AS AGE from emp_tbl WHERE(DATEDIFF(SYSDATE(), DOB)/365)>30;
+--------+---------------------+------------+---------+
| Name | SYSDATE() | DOB | AGE |
+--------+---------------------+------------+---------+
| Gaurav | 2017-12-26 22:33:24 | 1984-01-17 | 33.9644 |
| Rahul | 2017-12-26 22:33:24 | 1980-05-22 | 37.6219 |
| Gurdas | 2017-12-26 22:33:24 | 1981-05-25 | 36.6137 |
| Sohan | 2017-12-26 22:33:24 | 1987-12-26 | 30.0219 |
+--------+---------------------+------------+---------+
4 rows in set (0.10 sec) | [
{
"code": null,
"e": 1271,
"s": 1187,
"text": "To understand this concept, we are using the data from table ‘emp_tbl’ as follows −"
},
{
"code": null,
"e": 2161,
"s": 1271,
"text": "mysql> Select * from emp_tbl;\n+--------+------------+\n| Name | DOB |\n+--------+------------+\n| Gaurav | 1984-01-17 |\n| Gaurav | 1990-01-17 |\n| Rahul | 1980-05-22 |\n| Gurdas | 1981-05-25 |\n| Naveen | 1991-04-25 |\n| Sohan | 1987-12-26 |\n+--------+------------+\n6 rows in set (0.00 sec)\n\nmysql> SELECT Name,SYSDATE(),DOB,DATEDIFF(SYSDATE(),DOB)/365 AS AGE from emp_tbl WHERE(DATEDIFF(SYSDATE(), DOB)/365)>30;\n+--------+---------------------+------------+---------+\n| Name | SYSDATE() | DOB | AGE |\n+--------+---------------------+------------+---------+\n| Gaurav | 2017-12-26 22:33:24 | 1984-01-17 | 33.9644 |\n| Rahul | 2017-12-26 22:33:24 | 1980-05-22 | 37.6219 |\n| Gurdas | 2017-12-26 22:33:24 | 1981-05-25 | 36.6137 |\n| Sohan | 2017-12-26 22:33:24 | 1987-12-26 | 30.0219 |\n+--------+---------------------+------------+---------+\n4 rows in set (0.10 sec)"
}
] |
How to use :: Namespace Alias Qualifier in C# | 06 Mar, 2019
Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global. Thus it doesn’t invoke a lookup in the aliased namespace but in the global namespace.
Syntax:
alias_name::class-name;
Example:
// C# program to illustrate how to use// the :: Namespace Alias Qualifierusing System; // creating aliased nameusing first = firstnamespace;using sec = secondnamespace; namespace Geeks { class GFG { // Main Method static void Main() { // use of Namespace alias qualifier(::) first::GFG1 obj1 = new first::GFG1(); obj1.display(); }}} // Both namespaces have a // class named GFG1namespace firstnamespace { class GFG1 { public void display() { Console.WriteLine("It is the first namespace."); }}} namespace secondnamespace { class GFG1 { public void display() { Console.WriteLine("It is the second namespace."); }}}
It is the first namespace.
Note: The namespace alias qualifier :: is only used for the namespaces or aliases and cannot be used for subclasses.
Example:
System.Collections::lists obj= new System.Collections.lists() // illegal
aliasname = System.Collections;
aliasname::lists obj = new aliasname::lists(); // Legal
// C# program to illustrate how to use// the :: Namespace Alias Qualifierusing aliasname = System.Collections; namespace Geeks { class GFG { // Main Method static void Main() { // using :: Namespace Alias Qualifier aliasname::Hashtable obj = new aliasname::Hashtable(); // Add items to the table. obj.Add("ASCII value of A is:", "65"); obj.Add("ASCII value of B is:", "66"); // displaying the result foreach(string i in obj.Keys) { System.Console.WriteLine(i + " " + obj[i]); } }}}
ASCII value of A is: 65
ASCII value of B is: 66
Picked
C#
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n06 Mar, 2019"
},
{
"code": null,
"e": 416,
"s": 28,
"text": "Namespace Alias Qualifier(::) makes the use of alias name in place of longer namespace and it provides a way to avoid ambiguous definitions of the classes. It is always positioned between two identifiers. The qualifier looks like two colons(::) with an alias name and the class name. It can be global. Thus it doesn’t invoke a lookup in the aliased namespace but in the global namespace."
},
{
"code": null,
"e": 424,
"s": 416,
"text": "Syntax:"
},
{
"code": null,
"e": 448,
"s": 424,
"text": "alias_name::class-name;"
},
{
"code": null,
"e": 457,
"s": 448,
"text": "Example:"
},
{
"code": "// C# program to illustrate how to use// the :: Namespace Alias Qualifierusing System; // creating aliased nameusing first = firstnamespace;using sec = secondnamespace; namespace Geeks { class GFG { // Main Method static void Main() { // use of Namespace alias qualifier(::) first::GFG1 obj1 = new first::GFG1(); obj1.display(); }}} // Both namespaces have a // class named GFG1namespace firstnamespace { class GFG1 { public void display() { Console.WriteLine(\"It is the first namespace.\"); }}} namespace secondnamespace { class GFG1 { public void display() { Console.WriteLine(\"It is the second namespace.\"); }}}",
"e": 1152,
"s": 457,
"text": null
},
{
"code": null,
"e": 1180,
"s": 1152,
"text": "It is the first namespace.\n"
},
{
"code": null,
"e": 1297,
"s": 1180,
"text": "Note: The namespace alias qualifier :: is only used for the namespaces or aliases and cannot be used for subclasses."
},
{
"code": null,
"e": 1306,
"s": 1297,
"text": "Example:"
},
{
"code": null,
"e": 1468,
"s": 1306,
"text": "System.Collections::lists obj= new System.Collections.lists() // illegal\naliasname = System.Collections;\naliasname::lists obj = new aliasname::lists(); // Legal\n"
},
{
"code": "// C# program to illustrate how to use// the :: Namespace Alias Qualifierusing aliasname = System.Collections; namespace Geeks { class GFG { // Main Method static void Main() { // using :: Namespace Alias Qualifier aliasname::Hashtable obj = new aliasname::Hashtable(); // Add items to the table. obj.Add(\"ASCII value of A is:\", \"65\"); obj.Add(\"ASCII value of B is:\", \"66\"); // displaying the result foreach(string i in obj.Keys) { System.Console.WriteLine(i + \" \" + obj[i]); } }}}",
"e": 2044,
"s": 1468,
"text": null
},
{
"code": null,
"e": 2093,
"s": 2044,
"text": "ASCII value of A is: 65\nASCII value of B is: 66\n"
},
{
"code": null,
"e": 2100,
"s": 2093,
"text": "Picked"
},
{
"code": null,
"e": 2103,
"s": 2100,
"text": "C#"
}
] |
How to combine two vectors in R ? | 05 Apr, 2021
In this article, we will learn how to combine two vectors in R Programming Language. We can combine two or more vectors using function c() itself. While using function c() All arguments are coerced to a common type which is the type of the returned value.
Syntax: c(...)
Parameters:
...: arguments to be combined
Returns: A vector
Steps –
Create vectors to be combined
Combine them using c()
Display combined result
Example 1: Vectors of the same data type will give the vector of input data type as result.
R
a <- c(1, 2, 8) b <- c(5, 8, 9, 10) c <- c(a,b)c cat("typeof a", typeof(a), " typeof b", typeof(b), "typeof c",typeof(c) , "\n") a <- c("geek","for","geek")b <- c("hello","coder")c <- c(a,b)c cat("typeof a", typeof(a), " typeof b", typeof(b), "typeof c",typeof(c) , "\n") a <- c(TRUE, FALSE, NA)b <- c(TRUE, FALSE)c <- c(a,b)c cat("typeof a", typeof(a), " typeof b", typeof(b), "typeof c",typeof(c) , "\n")
Output:
[1] 1 2 8 5 8 9 10
typeof a double typeof b double typeof c double
[1] “geek” “for” “geek” “hello” “coder”
typeof a character typeof b character typeof c character
[1] TRUE FALSE NA TRUE FALSE
typeof a logical typeof b logical typeof c logical
While combining vectors of type double and character, character and logical, double and logical c() function return vector of a type character, character, double respectively.
Example 2:
R
a <- c(1, 2, 8) b <- c("hello","coder")c <- c(a,b) # a vector of type double and b vector of type # character result c vector of type characterc cat("typeof a", typeof(a), " typeof b", typeof(b), "typeof c",typeof(c) , "\n") a <- c("geek","for","geek")b <- c(TRUE, FALSE) # a vector of type character and b vector of type logical# result c vector of type characterc <- c(a,b)c cat("typeof a", typeof(a), " typeof b", typeof(b), "typeof c",typeof(c) , "\n") a <- c(1, 2, 8) b <- c(TRUE, FALSE)c <- c(a,b) # a vector of type double and b vector of type # logical result c vector of type doublec cat("typeof a", typeof(a), " typeof b", typeof(b), "typeof c",typeof(c) , "\n")
Output:
[1] “1” “2” “8” “hello” “coder”
typeof a double typeof b character typeof c character
[1] “geek” “for” “geek” “TRUE” “FALSE”
typeof a character typeof b logical typeof c character
[1] 1 2 8 1 0
typeof a double typeof b logical typeof c double
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. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n05 Apr, 2021"
},
{
"code": null,
"e": 284,
"s": 28,
"text": "In this article, we will learn how to combine two vectors in R Programming Language. We can combine two or more vectors using function c() itself. While using function c() All arguments are coerced to a common type which is the type of the returned value."
},
{
"code": null,
"e": 299,
"s": 284,
"text": "Syntax: c(...)"
},
{
"code": null,
"e": 311,
"s": 299,
"text": "Parameters:"
},
{
"code": null,
"e": 341,
"s": 311,
"text": "...: arguments to be combined"
},
{
"code": null,
"e": 359,
"s": 341,
"text": "Returns: A vector"
},
{
"code": null,
"e": 367,
"s": 359,
"text": "Steps –"
},
{
"code": null,
"e": 397,
"s": 367,
"text": "Create vectors to be combined"
},
{
"code": null,
"e": 420,
"s": 397,
"text": "Combine them using c()"
},
{
"code": null,
"e": 444,
"s": 420,
"text": "Display combined result"
},
{
"code": null,
"e": 537,
"s": 444,
"text": "Example 1: Vectors of the same data type will give the vector of input data type as result. "
},
{
"code": null,
"e": 539,
"s": 537,
"text": "R"
},
{
"code": "a <- c(1, 2, 8) b <- c(5, 8, 9, 10) c <- c(a,b)c cat(\"typeof a\", typeof(a), \" typeof b\", typeof(b), \"typeof c\",typeof(c) , \"\\n\") a <- c(\"geek\",\"for\",\"geek\")b <- c(\"hello\",\"coder\")c <- c(a,b)c cat(\"typeof a\", typeof(a), \" typeof b\", typeof(b), \"typeof c\",typeof(c) , \"\\n\") a <- c(TRUE, FALSE, NA)b <- c(TRUE, FALSE)c <- c(a,b)c cat(\"typeof a\", typeof(a), \" typeof b\", typeof(b), \"typeof c\",typeof(c) , \"\\n\")",
"e": 960,
"s": 539,
"text": null
},
{
"code": null,
"e": 968,
"s": 960,
"text": "Output:"
},
{
"code": null,
"e": 993,
"s": 968,
"text": "[1] 1 2 8 5 8 9 10"
},
{
"code": null,
"e": 1043,
"s": 993,
"text": "typeof a double typeof b double typeof c double "
},
{
"code": null,
"e": 1087,
"s": 1043,
"text": "[1] “geek” “for” “geek” “hello” “coder”"
},
{
"code": null,
"e": 1146,
"s": 1087,
"text": "typeof a character typeof b character typeof c character "
},
{
"code": null,
"e": 1180,
"s": 1146,
"text": "[1] TRUE FALSE NA TRUE FALSE"
},
{
"code": null,
"e": 1233,
"s": 1180,
"text": "typeof a logical typeof b logical typeof c logical "
},
{
"code": null,
"e": 1409,
"s": 1233,
"text": "While combining vectors of type double and character, character and logical, double and logical c() function return vector of a type character, character, double respectively."
},
{
"code": null,
"e": 1421,
"s": 1409,
"text": "Example 2: "
},
{
"code": null,
"e": 1423,
"s": 1421,
"text": "R"
},
{
"code": "a <- c(1, 2, 8) b <- c(\"hello\",\"coder\")c <- c(a,b) # a vector of type double and b vector of type # character result c vector of type characterc cat(\"typeof a\", typeof(a), \" typeof b\", typeof(b), \"typeof c\",typeof(c) , \"\\n\") a <- c(\"geek\",\"for\",\"geek\")b <- c(TRUE, FALSE) # a vector of type character and b vector of type logical# result c vector of type characterc <- c(a,b)c cat(\"typeof a\", typeof(a), \" typeof b\", typeof(b), \"typeof c\",typeof(c) , \"\\n\") a <- c(1, 2, 8) b <- c(TRUE, FALSE)c <- c(a,b) # a vector of type double and b vector of type # logical result c vector of type doublec cat(\"typeof a\", typeof(a), \" typeof b\", typeof(b), \"typeof c\",typeof(c) , \"\\n\")",
"e": 2115,
"s": 1423,
"text": null
},
{
"code": null,
"e": 2123,
"s": 2115,
"text": "Output:"
},
{
"code": null,
"e": 2167,
"s": 2123,
"text": "[1] “1” “2” “8” “hello” “coder”"
},
{
"code": null,
"e": 2223,
"s": 2167,
"text": "typeof a double typeof b character typeof c character "
},
{
"code": null,
"e": 2267,
"s": 2223,
"text": "[1] “geek” “for” “geek” “TRUE” “FALSE”"
},
{
"code": null,
"e": 2324,
"s": 2267,
"text": "typeof a character typeof b logical typeof c character "
},
{
"code": null,
"e": 2338,
"s": 2324,
"text": "[1] 1 2 8 1 0"
},
{
"code": null,
"e": 2389,
"s": 2338,
"text": "typeof a double typeof b logical typeof c double "
},
{
"code": null,
"e": 2396,
"s": 2389,
"text": "Picked"
},
{
"code": null,
"e": 2414,
"s": 2396,
"text": "R Vector-Programs"
},
{
"code": null,
"e": 2424,
"s": 2414,
"text": "R-Vectors"
},
{
"code": null,
"e": 2435,
"s": 2424,
"text": "R Language"
},
{
"code": null,
"e": 2446,
"s": 2435,
"text": "R Programs"
}
] |
Print bitwise AND set of a number N | 03 May, 2021
Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i.
Examples :
Input : N = 5
Output : 0, 1, 4, 5
Explanation: 0 & 5 = 0
1 & 5 = 1
2 & 5 = 0
3 & 5 = 1
4 & 5 = 4
5 & 5 = 5
So we get 0, 1, 4 and 5 in the
bitwise subsets of N.
Input : N = 9
Output : 0, 1, 8, 9
Simple Approach: A naive approach is to iterate from all numbers from 0 to N and check if (N&i == i). Print the numbers which satisfy the specified condition.
Below is the implementation of above idea:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print all bitwise// subsets of N (Naive approach)#include <bits/stdc++.h>using namespace std; // function to find bitwise subsets// Naive approachvoid printSubsets(int n) { for (int i = 0; i <= n; i++) if ((n & i) == i) cout << i << " ";} // Driver Codeint main() { int n = 9; printSubsets(n); return 0;}
// JAVA program to print all bitwise// subsets of N (Naive approach)class GFG { // function to find bitwise subsets // Naive approach static void printSubsets(int n) { for (int i = 0; i <= n; i++) if ((n & i) == i) System.out.print(i + " "); } // Driver function public static void main(String[] args) { int n = 9; printSubsets(n); }} // This code is contributed by Anant Agarwal.
# Python program to print all bitwise# subsets of N (Naive approach)def printSubsets(n): for i in range(n + 1): if ((n & i) == i): print(i ," ", end = "") # Driver coden = 9printSubsets(n) # This code is contributed by Anant Agarwal.
// C# program to print all bitwise// subsets of N (Naive approach)using System; class GFG { // function to find bitwise subsets // Naive approach static void printSubsets(int n) { for (int i = 0; i <= n; i++) if ((n & i) == i) Console.Write(i + " "); } // Driver function public static void Main() { int n = 9; printSubsets(n); }} // This code is contributed by vt_m.
<?php// PHP program to print all bitwise// subsets of N (Naive approach) // function to find bitwise subsets// Naive approachfunction printSubsets($n){for ($i = 0; $i <= $n; $i++) if (($n & $i) == $i) echo $i." ";} // Driver Code$n = 9;printSubsets($n); // This code is contributed by mits?>
<script> // JavaScript program to print all bitwise// subsets of N (Efficient approach) // function to find bitwise // subsets Efficient approach function printSubsets(n) { for (let i = n; i > 0; i = (i - 1) & n) document.write(i + " "); document.write(" 0 "); }// Driver code let n = 9; printSubsets(n); // This code is contributed by souravghosh0416.</script>
Output :
0 1 8 9
Time Complexity : O(N)
Efficient Solution: An efficient solution is to use bitwise operators to find the subsets. Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating backward for i=(i-1)&n gives us every bitwise subset, where i starts from n and ends at 1.
Below is the implementation of above idea:
C++
Java
Python3
C#
PHP
Javascript
// CPP program to print all bitwise// subsets of N (Efficient approach) #include <bits/stdc++.h>using namespace std; // function to find bitwise subsets// Efficient approachvoid printSubsets(int n) { for (int i = n; i > 0; i = (i - 1) & n) cout << i << " "; cout << 0;} // Driver Codeint main() { int n = 9; printSubsets(n); return 0;}
// Java program to print all bitwise// subsets of N (Efficient approach) class GFG{ // function to find bitwise // subsets Efficient approach static void printSubsets(int n) { for (int i = n; i > 0; i = (i - 1) & n) System.out.print(i + " "); System.out.print(" 0 "); } // Driver Codepublic static void main(String[] args){ int n = 9; printSubsets(n);}} // This code is contributed by ajit.
# Python 3 program to# print all bitwise# subsets of N# (Efficient approach) # function to find# bitwise subsets# Efficient approachdef printSubsets(n): i=n while(i != 0): print(i,end=" ") i=(i - 1) & n print("0") # Driver Coden = 9printSubsets(n) # This code is contributed by# Smith Dinesh Semwal
// C# program to print all bitwise// subsets of N (Efficient approach)using System; public class GFG { // function to find bitwise subsets // Efficient approach static void printSubsets(int n) { for (int i = n; i > 0; i = (i - 1) & n) Console.Write(i +" "); Console.WriteLine("0"); } // Driver Code static public void Main () { int n = 9; printSubsets(n); }} // This code is contributed by vt_m.
<?php// PHP program to print all bitwise// subsets of N (Efficient approach) // function to find bitwise subsets// Efficient approachfunction printSubsets($n){ for ($i = $n; $i > 0; $i = ($i - 1) & $n) echo $i." "; echo "0";} // Driver Code$n = 9;printSubsets($n); // This code is contributed by mits?>
<script> // Javascript program to print all bitwise// subsets of N (Efficient approach) // Function to find bitwise subsets// Efficient approachfunction printSubsets(n){ for(let i = n; i > 0; i = (i - 1) & n) document.write(i +" "); document.write("0" + "</br>");} // Driver codelet n = 9; printSubsets(n); // This code is contributed by divyesh072019 </script>
Output :
9 8 1 0
Time Complexity: O(K), where K is the number of bitwise subsets of N.
Mithun Kumar
jit_t
Akanksha_Rai
souravghosh0416
divyesh072019
Bit Algorithms
Bit Magic
Bit Magic
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Set, Clear and Toggle a given bit of a number in C
Builtin functions of GCC compiler
Calculate XOR from 1 to n.
Google Online Challenge 2020
Find two numbers from their sum and XOR
Highest power of 2 less than or equal to given number
Calculate square of a number without using *, / and pow()
Reverse actual bits of the given number
Count number of bits to be flipped to convert A to B
Find XOR of two number without using XOR operator | [
{
"code": null,
"e": 54,
"s": 26,
"text": "\n03 May, 2021"
},
{
"code": null,
"e": 287,
"s": 54,
"text": "Given a number N, print all the numbers which are a bitwise AND set of the binary representation of N. Bitwise AND set of a number N is all possible numbers x smaller than or equal N such that N & i is equal to x for some number i. "
},
{
"code": null,
"e": 299,
"s": 287,
"text": "Examples : "
},
{
"code": null,
"e": 565,
"s": 299,
"text": "Input : N = 5\nOutput : 0, 1, 4, 5 \nExplanation: 0 & 5 = 0 \n 1 & 5 = 1\n 2 & 5 = 0\n 3 & 5 = 1\n 4 & 5 = 4\n 5 & 5 = 5 \nSo we get 0, 1, 4 and 5 in the \nbitwise subsets of N.\n\nInput : N = 9\nOutput : 0, 1, 8, 9 "
},
{
"code": null,
"e": 725,
"s": 565,
"text": "Simple Approach: A naive approach is to iterate from all numbers from 0 to N and check if (N&i == i). Print the numbers which satisfy the specified condition. "
},
{
"code": null,
"e": 770,
"s": 725,
"text": "Below is the implementation of above idea: "
},
{
"code": null,
"e": 774,
"s": 770,
"text": "C++"
},
{
"code": null,
"e": 779,
"s": 774,
"text": "Java"
},
{
"code": null,
"e": 787,
"s": 779,
"text": "Python3"
},
{
"code": null,
"e": 790,
"s": 787,
"text": "C#"
},
{
"code": null,
"e": 794,
"s": 790,
"text": "PHP"
},
{
"code": null,
"e": 805,
"s": 794,
"text": "Javascript"
},
{
"code": "// CPP program to print all bitwise// subsets of N (Naive approach)#include <bits/stdc++.h>using namespace std; // function to find bitwise subsets// Naive approachvoid printSubsets(int n) { for (int i = 0; i <= n; i++) if ((n & i) == i) cout << i << \" \";} // Driver Codeint main() { int n = 9; printSubsets(n); return 0;}",
"e": 1143,
"s": 805,
"text": null
},
{
"code": "// JAVA program to print all bitwise// subsets of N (Naive approach)class GFG { // function to find bitwise subsets // Naive approach static void printSubsets(int n) { for (int i = 0; i <= n; i++) if ((n & i) == i) System.out.print(i + \" \"); } // Driver function public static void main(String[] args) { int n = 9; printSubsets(n); }} // This code is contributed by Anant Agarwal.",
"e": 1626,
"s": 1143,
"text": null
},
{
"code": "# Python program to print all bitwise# subsets of N (Naive approach)def printSubsets(n): for i in range(n + 1): if ((n & i) == i): print(i ,\" \", end = \"\") # Driver coden = 9printSubsets(n) # This code is contributed by Anant Agarwal.",
"e": 1895,
"s": 1626,
"text": null
},
{
"code": "// C# program to print all bitwise// subsets of N (Naive approach)using System; class GFG { // function to find bitwise subsets // Naive approach static void printSubsets(int n) { for (int i = 0; i <= n; i++) if ((n & i) == i) Console.Write(i + \" \"); } // Driver function public static void Main() { int n = 9; printSubsets(n); }} // This code is contributed by vt_m.",
"e": 2365,
"s": 1895,
"text": null
},
{
"code": "<?php// PHP program to print all bitwise// subsets of N (Naive approach) // function to find bitwise subsets// Naive approachfunction printSubsets($n){for ($i = 0; $i <= $n; $i++) if (($n & $i) == $i) echo $i.\" \";} // Driver Code$n = 9;printSubsets($n); // This code is contributed by mits?>",
"e": 2663,
"s": 2365,
"text": null
},
{
"code": "<script> // JavaScript program to print all bitwise// subsets of N (Efficient approach) // function to find bitwise // subsets Efficient approach function printSubsets(n) { for (let i = n; i > 0; i = (i - 1) & n) document.write(i + \" \"); document.write(\" 0 \"); }// Driver code let n = 9; printSubsets(n); // This code is contributed by souravghosh0416.</script>",
"e": 3071,
"s": 2663,
"text": null
},
{
"code": null,
"e": 3081,
"s": 3071,
"text": "Output : "
},
{
"code": null,
"e": 3089,
"s": 3081,
"text": "0 1 8 9"
},
{
"code": null,
"e": 3112,
"s": 3089,
"text": "Time Complexity : O(N)"
},
{
"code": null,
"e": 3391,
"s": 3112,
"text": "Efficient Solution: An efficient solution is to use bitwise operators to find the subsets. Instead of iterating for every i, we can simply iterate for the bitwise subsets only. Iterating backward for i=(i-1)&n gives us every bitwise subset, where i starts from n and ends at 1. "
},
{
"code": null,
"e": 3436,
"s": 3391,
"text": "Below is the implementation of above idea: "
},
{
"code": null,
"e": 3440,
"s": 3436,
"text": "C++"
},
{
"code": null,
"e": 3445,
"s": 3440,
"text": "Java"
},
{
"code": null,
"e": 3453,
"s": 3445,
"text": "Python3"
},
{
"code": null,
"e": 3456,
"s": 3453,
"text": "C#"
},
{
"code": null,
"e": 3460,
"s": 3456,
"text": "PHP"
},
{
"code": null,
"e": 3471,
"s": 3460,
"text": "Javascript"
},
{
"code": "// CPP program to print all bitwise// subsets of N (Efficient approach) #include <bits/stdc++.h>using namespace std; // function to find bitwise subsets// Efficient approachvoid printSubsets(int n) { for (int i = n; i > 0; i = (i - 1) & n) cout << i << \" \"; cout << 0;} // Driver Codeint main() { int n = 9; printSubsets(n); return 0;}",
"e": 3821,
"s": 3471,
"text": null
},
{
"code": "// Java program to print all bitwise// subsets of N (Efficient approach) class GFG{ // function to find bitwise // subsets Efficient approach static void printSubsets(int n) { for (int i = n; i > 0; i = (i - 1) & n) System.out.print(i + \" \"); System.out.print(\" 0 \"); } // Driver Codepublic static void main(String[] args){ int n = 9; printSubsets(n);}} // This code is contributed by ajit.",
"e": 4257,
"s": 3821,
"text": null
},
{
"code": "# Python 3 program to# print all bitwise# subsets of N# (Efficient approach) # function to find# bitwise subsets# Efficient approachdef printSubsets(n): i=n while(i != 0): print(i,end=\" \") i=(i - 1) & n print(\"0\") # Driver Coden = 9printSubsets(n) # This code is contributed by# Smith Dinesh Semwal",
"e": 4579,
"s": 4257,
"text": null
},
{
"code": "// C# program to print all bitwise// subsets of N (Efficient approach)using System; public class GFG { // function to find bitwise subsets // Efficient approach static void printSubsets(int n) { for (int i = n; i > 0; i = (i - 1) & n) Console.Write(i +\" \"); Console.WriteLine(\"0\"); } // Driver Code static public void Main () { int n = 9; printSubsets(n); }} // This code is contributed by vt_m.",
"e": 5056,
"s": 4579,
"text": null
},
{
"code": "<?php// PHP program to print all bitwise// subsets of N (Efficient approach) // function to find bitwise subsets// Efficient approachfunction printSubsets($n){ for ($i = $n; $i > 0; $i = ($i - 1) & $n) echo $i.\" \"; echo \"0\";} // Driver Code$n = 9;printSubsets($n); // This code is contributed by mits?>",
"e": 5391,
"s": 5056,
"text": null
},
{
"code": "<script> // Javascript program to print all bitwise// subsets of N (Efficient approach) // Function to find bitwise subsets// Efficient approachfunction printSubsets(n){ for(let i = n; i > 0; i = (i - 1) & n) document.write(i +\" \"); document.write(\"0\" + \"</br>\");} // Driver codelet n = 9; printSubsets(n); // This code is contributed by divyesh072019 </script>",
"e": 5775,
"s": 5391,
"text": null
},
{
"code": null,
"e": 5785,
"s": 5775,
"text": "Output : "
},
{
"code": null,
"e": 5793,
"s": 5785,
"text": "9 8 1 0"
},
{
"code": null,
"e": 5864,
"s": 5793,
"text": "Time Complexity: O(K), where K is the number of bitwise subsets of N. "
},
{
"code": null,
"e": 5877,
"s": 5864,
"text": "Mithun Kumar"
},
{
"code": null,
"e": 5883,
"s": 5877,
"text": "jit_t"
},
{
"code": null,
"e": 5896,
"s": 5883,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 5912,
"s": 5896,
"text": "souravghosh0416"
},
{
"code": null,
"e": 5926,
"s": 5912,
"text": "divyesh072019"
},
{
"code": null,
"e": 5941,
"s": 5926,
"text": "Bit Algorithms"
},
{
"code": null,
"e": 5951,
"s": 5941,
"text": "Bit Magic"
},
{
"code": null,
"e": 5961,
"s": 5951,
"text": "Bit Magic"
},
{
"code": null,
"e": 6059,
"s": 5961,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6110,
"s": 6059,
"text": "Set, Clear and Toggle a given bit of a number in C"
},
{
"code": null,
"e": 6144,
"s": 6110,
"text": "Builtin functions of GCC compiler"
},
{
"code": null,
"e": 6171,
"s": 6144,
"text": "Calculate XOR from 1 to n."
},
{
"code": null,
"e": 6200,
"s": 6171,
"text": "Google Online Challenge 2020"
},
{
"code": null,
"e": 6240,
"s": 6200,
"text": "Find two numbers from their sum and XOR"
},
{
"code": null,
"e": 6294,
"s": 6240,
"text": "Highest power of 2 less than or equal to given number"
},
{
"code": null,
"e": 6352,
"s": 6294,
"text": "Calculate square of a number without using *, / and pow()"
},
{
"code": null,
"e": 6392,
"s": 6352,
"text": "Reverse actual bits of the given number"
},
{
"code": null,
"e": 6445,
"s": 6392,
"text": "Count number of bits to be flipped to convert A to B"
}
] |
Count of Unique elements in a very large sorted Array | 28 Feb, 2022
Given a sorted array arr[] of size N, the task is to find the number of unique elements in this array.
Note: The array is very large, and unique numbers are significantly less. i.e., (unique elements <<size of the array).
Examples:
Input: arr[] = {1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12}Output: 10Explanation: 10 unique elements are: 1, 2, 3, 5, 7, 8, 9, 10, 11, 12
Input: arr[] = {1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 9, 9, 9, 10, 10, 10}Output: 7Explanation: 7 unique elements are: 1, 2, 3, 4, 5, 9, 10
Naive Approach: As the given array is sorted, one of the simple approaches will be traversing through all over the element and comparing them with the previous ones. If it is different, then count that element.
Time Complexity: O(N)Auxiliary Space: O(1).
Approach based on Binary Search: The idea is the use Binary search because the array is sorted. Follow the steps mentioned below:
Take the first number, then find its last occurrence or upper bound using binary search.
Then count it as one unique element.
Place pointer to next different element and repeat the same step.
Note: This algorithm is only effective when very few unique elements.
Below is the implementation of the above approach.
C++
Java
Python3
C#
Javascript
// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Binary search to find the last occurrenceint nextIndex(int arr[], int N, int l, int target){ int result = -1; int r = N - 1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1;} // Function to find the number// of unique elementsint unique(int arr[], int N){ int i = 0; int count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count;} // Driver Codeint main(){ int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = sizeof(arr) / sizeof(arr[0]); cout << unique(arr, N); return 0;}
// Java code to implement above approach class GFG { // Binary search to find the last occurrence static int nextIndex(int arr[], int N, int l, int target) { int result = -1; int r = N - 1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1; } // Function to find the number // of unique elements static int unique(int arr[], int N) { int i = 0; int count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.length; System.out.println(unique(arr, N)); }}
# Python code for the above approach # Binary search to find the last occurrencedef nextIndex(arr, N, l, target): result = -1 r = N - 1 while (l <= r): mid = l + (r - l) // 2 if (arr[mid] == target): result = mid l = mid + 1 elif (arr[mid] > target): r = mid - 1 else: l = mid + 1 # Result will give the last occurrence & # adding one will return next element return result + 1 # Function to find the number# of unique elementsdef unique(arr, N): i = 0 count = 0 while (i < N): # Returns the next element i = nextIndex(arr, N, i, arr[i]) count += 1 return count # Driver Codearr = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12]N = len(arr)print(unique(arr, N)) # This code is contributed by gfgking
// C# program for above approachusing System;using System.Collections.Generic; public class GFG{ // Binary search to find the last occurrence static int nextIndex(int[] arr, int N, int l, int target) { int result = -1; int r = N - 1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1; } // Function to find the number // of unique elements static int unique(int[] arr, int N) { int i = 0; int count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count; } // Driver Code static public void Main (){ int[] arr = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.Length; Console.WriteLine(unique(arr, N)); }} // This code is contributed by hrithikgarg03188
<script> // JavaScript code for the above approach // Binary search to find the last occurrence function nextIndex(arr, N, l, target) { let result = -1; let r = N - 1; while (l <= r) { let mid = l + Math.floor((r - l) / 2); if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1; } // Function to find the number // of unique elements function unique(arr, N) { let i = 0; let count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count; } // Driver Code let arr = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12]; let N = arr.length; document.write(unique(arr, N)); // This code is contributed by Potta Lokesh </script>
10
Time Complexity: K * logO(N). where K = no. of unique elements.Auxiliary Space: O(1).
Approach based on Divide and Conquer: This problem can be solved using divide and conquer. Idea is:
As duplicate elements are large, look at the first and last elements of this sorted array.If both are equal, it means only this element is present in the entire array, and it will be counted as one.If they are different, divide the array into two halves and repeat the above step for each array.
If both are equal, it means only this element is present in the entire array, and it will be counted as one.
If they are different, divide the array into two halves and repeat the above step for each array.
The final count is the number of unique elements.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Variable to store the number// of unique elementsint cnt = 0; // Function to find the number// of unique elementsvoid UniqueElements(int arr[], int s, int e, bool isDuplicate){ // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { int mid = s + (e - s) / 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); }} // Function to count the number// of unique elementsint unique(int arr[], int N){ UniqueElements(arr, 0, N - 1, 0); return cnt;} // Driver Codeint main(){ int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = sizeof(arr) / sizeof(arr[0]); cout << unique(arr, N); return 0;}
// Java code to implement the above approachimport java.util.*;class GFG{ // Variable to store the number // of unique elements static int cnt = 0; // Function to find the number // of unique elements static void UniqueElements(int arr[], int s, int e, boolean isDuplicate) { // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { int mid = s + (e - s) / 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); } } // Function to count the number // of unique elements static int unique(int arr[], int N) { UniqueElements(arr, 0, N - 1, false); return cnt; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.length; System.out.print(unique(arr, N)); }} // This code is contributed by 29AjayKumar
# Python code to implement the above approach # Variable to store the number# of unique elementscnt = 0; # Function to find the number# of unique elementsdef UniqueElements(arr, s, e, isDuplicate): global cnt # Both start and end are same if (arr[s] == arr[e]): # If the element is duplicate if (isDuplicate == False): cnt += 1; else: mid = s + (e - s) // 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); # Function to count the number# of unique elementsdef unique(arr, N): UniqueElements(arr, 0, N - 1, False); return cnt; # Driver Codeif __name__ == '__main__': arr = [ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 ]; N = len(arr); print(unique(arr, N)); # This code is contributed by Rajput-Ji
// C# code to implement the above approachusing System;public class GFG{ // Variable to store the number // of unique elements static int cnt = 0; // Function to find the number // of unique elements static void UniqueElements(int []arr, int s, int e, bool isDuplicate) { // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { int mid = s + (e - s) / 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); } } // Function to count the number // of unique elements static int unique(int []arr, int N) { UniqueElements(arr, 0, N - 1, false); return cnt; } // Driver Code public static void Main(String[] args) { int []arr = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.Length; Console.Write(unique(arr, N)); }} // This code is contributed by shikhasingrajput
<script>// javascript code to implement the above approach // Variable to store the number // of unique elements var cnt = 0; // Function to find the number // of unique elements function UniqueElements(arr , s,e, isDuplicate) { // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { var mid = s + parseInt((e - s) / 2); UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); } } // Function to count the number // of unique elements function unique(arr , N) { UniqueElements(arr, 0, N - 1, false); return cnt; } // Driver Code var arr = [ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 ]; var N = arr.length; document.write(unique(arr, N)); // This code is contributed by shikhasingrajput</script>
10
Time Complexity: O(log(N)) for the average case.The worst case will be O(N).Auxiliary Space: O(1)
lokeshpotta20
gfgking
sagar0719kumar
_saurabh_jaiswal
hrithikgarg03188
29AjayKumar
shikhasingrajput
Rajput-Ji
Binary Search
Arrays
Searching
Sorting
Arrays
Searching
Sorting
Binary Search
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
Binary Search
Search, insert and delete in an unsorted array
Median of two sorted arrays of different sizes
Two Pointers Technique
Find the missing and repeating number | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n28 Feb, 2022"
},
{
"code": null,
"e": 156,
"s": 52,
"text": "Given a sorted array arr[] of size N, the task is to find the number of unique elements in this array. "
},
{
"code": null,
"e": 275,
"s": 156,
"text": "Note: The array is very large, and unique numbers are significantly less. i.e., (unique elements <<size of the array)."
},
{
"code": null,
"e": 286,
"s": 275,
"text": "Examples: "
},
{
"code": null,
"e": 449,
"s": 286,
"text": "Input: arr[] = {1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12}Output: 10Explanation: 10 unique elements are: 1, 2, 3, 5, 7, 8, 9, 10, 11, 12"
},
{
"code": null,
"e": 596,
"s": 449,
"text": "Input: arr[] = {1, 1, 1, 2, 2, 2, 2, 3, 3, 4, 4, 5, 5, 5, 5, 9, 9, 9, 10, 10, 10}Output: 7Explanation: 7 unique elements are: 1, 2, 3, 4, 5, 9, 10"
},
{
"code": null,
"e": 807,
"s": 596,
"text": "Naive Approach: As the given array is sorted, one of the simple approaches will be traversing through all over the element and comparing them with the previous ones. If it is different, then count that element."
},
{
"code": null,
"e": 851,
"s": 807,
"text": "Time Complexity: O(N)Auxiliary Space: O(1)."
},
{
"code": null,
"e": 981,
"s": 851,
"text": "Approach based on Binary Search: The idea is the use Binary search because the array is sorted. Follow the steps mentioned below:"
},
{
"code": null,
"e": 1070,
"s": 981,
"text": "Take the first number, then find its last occurrence or upper bound using binary search."
},
{
"code": null,
"e": 1107,
"s": 1070,
"text": "Then count it as one unique element."
},
{
"code": null,
"e": 1173,
"s": 1107,
"text": "Place pointer to next different element and repeat the same step."
},
{
"code": null,
"e": 1243,
"s": 1173,
"text": "Note: This algorithm is only effective when very few unique elements."
},
{
"code": null,
"e": 1294,
"s": 1243,
"text": "Below is the implementation of the above approach."
},
{
"code": null,
"e": 1298,
"s": 1294,
"text": "C++"
},
{
"code": null,
"e": 1303,
"s": 1298,
"text": "Java"
},
{
"code": null,
"e": 1311,
"s": 1303,
"text": "Python3"
},
{
"code": null,
"e": 1314,
"s": 1311,
"text": "C#"
},
{
"code": null,
"e": 1325,
"s": 1314,
"text": "Javascript"
},
{
"code": "// C++ code to implement above approach#include <bits/stdc++.h>using namespace std; // Binary search to find the last occurrenceint nextIndex(int arr[], int N, int l, int target){ int result = -1; int r = N - 1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1;} // Function to find the number// of unique elementsint unique(int arr[], int N){ int i = 0; int count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count;} // Driver Codeint main(){ int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = sizeof(arr) / sizeof(arr[0]); cout << unique(arr, N); return 0;}",
"e": 2390,
"s": 1325,
"text": null
},
{
"code": "// Java code to implement above approach class GFG { // Binary search to find the last occurrence static int nextIndex(int arr[], int N, int l, int target) { int result = -1; int r = N - 1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1; } // Function to find the number // of unique elements static int unique(int arr[], int N) { int i = 0; int count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count; } // Driver Code public static void main(String args[]) { int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.length; System.out.println(unique(arr, N)); }}",
"e": 3571,
"s": 2390,
"text": null
},
{
"code": "# Python code for the above approach # Binary search to find the last occurrencedef nextIndex(arr, N, l, target): result = -1 r = N - 1 while (l <= r): mid = l + (r - l) // 2 if (arr[mid] == target): result = mid l = mid + 1 elif (arr[mid] > target): r = mid - 1 else: l = mid + 1 # Result will give the last occurrence & # adding one will return next element return result + 1 # Function to find the number# of unique elementsdef unique(arr, N): i = 0 count = 0 while (i < N): # Returns the next element i = nextIndex(arr, N, i, arr[i]) count += 1 return count # Driver Codearr = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12]N = len(arr)print(unique(arr, N)) # This code is contributed by gfgking",
"e": 4442,
"s": 3571,
"text": null
},
{
"code": "// C# program for above approachusing System;using System.Collections.Generic; public class GFG{ // Binary search to find the last occurrence static int nextIndex(int[] arr, int N, int l, int target) { int result = -1; int r = N - 1; while (l <= r) { int mid = l + (r - l) / 2; if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1; } // Function to find the number // of unique elements static int unique(int[] arr, int N) { int i = 0; int count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count; } // Driver Code static public void Main (){ int[] arr = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.Length; Console.WriteLine(unique(arr, N)); }} // This code is contributed by hrithikgarg03188",
"e": 5552,
"s": 4442,
"text": null
},
{
"code": "<script> // JavaScript code for the above approach // Binary search to find the last occurrence function nextIndex(arr, N, l, target) { let result = -1; let r = N - 1; while (l <= r) { let mid = l + Math.floor((r - l) / 2); if (arr[mid] == target) { result = mid; l = mid + 1; } else if (arr[mid] > target) r = mid - 1; else l = mid + 1; } // Result will give the last occurrence & // adding one will return next element return result + 1; } // Function to find the number // of unique elements function unique(arr, N) { let i = 0; let count = 0; while (i < N) { // Returns the next element i = nextIndex(arr, N, i, arr[i]); count++; } return count; } // Driver Code let arr = [1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12]; let N = arr.length; document.write(unique(arr, N)); // This code is contributed by Potta Lokesh </script>",
"e": 6861,
"s": 5552,
"text": null
},
{
"code": null,
"e": 6867,
"s": 6864,
"text": "10"
},
{
"code": null,
"e": 6955,
"s": 6869,
"text": "Time Complexity: K * logO(N). where K = no. of unique elements.Auxiliary Space: O(1)."
},
{
"code": null,
"e": 7057,
"s": 6957,
"text": "Approach based on Divide and Conquer: This problem can be solved using divide and conquer. Idea is:"
},
{
"code": null,
"e": 7355,
"s": 7059,
"text": "As duplicate elements are large, look at the first and last elements of this sorted array.If both are equal, it means only this element is present in the entire array, and it will be counted as one.If they are different, divide the array into two halves and repeat the above step for each array."
},
{
"code": null,
"e": 7464,
"s": 7355,
"text": "If both are equal, it means only this element is present in the entire array, and it will be counted as one."
},
{
"code": null,
"e": 7562,
"s": 7464,
"text": "If they are different, divide the array into two halves and repeat the above step for each array."
},
{
"code": null,
"e": 7612,
"s": 7562,
"text": "The final count is the number of unique elements."
},
{
"code": null,
"e": 7665,
"s": 7614,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 7671,
"s": 7667,
"text": "C++"
},
{
"code": null,
"e": 7676,
"s": 7671,
"text": "Java"
},
{
"code": null,
"e": 7684,
"s": 7676,
"text": "Python3"
},
{
"code": null,
"e": 7687,
"s": 7684,
"text": "C#"
},
{
"code": null,
"e": 7698,
"s": 7687,
"text": "Javascript"
},
{
"code": "// C++ code to implement the above approach#include <bits/stdc++.h>using namespace std; // Variable to store the number// of unique elementsint cnt = 0; // Function to find the number// of unique elementsvoid UniqueElements(int arr[], int s, int e, bool isDuplicate){ // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { int mid = s + (e - s) / 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); }} // Function to count the number// of unique elementsint unique(int arr[], int N){ UniqueElements(arr, 0, N - 1, 0); return cnt;} // Driver Codeint main(){ int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = sizeof(arr) / sizeof(arr[0]); cout << unique(arr, N); return 0;}",
"e": 8704,
"s": 7698,
"text": null
},
{
"code": "// Java code to implement the above approachimport java.util.*;class GFG{ // Variable to store the number // of unique elements static int cnt = 0; // Function to find the number // of unique elements static void UniqueElements(int arr[], int s, int e, boolean isDuplicate) { // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { int mid = s + (e - s) / 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); } } // Function to count the number // of unique elements static int unique(int arr[], int N) { UniqueElements(arr, 0, N - 1, false); return cnt; } // Driver Code public static void main(String[] args) { int arr[] = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.length; System.out.print(unique(arr, N)); }} // This code is contributed by 29AjayKumar",
"e": 9798,
"s": 8704,
"text": null
},
{
"code": "# Python code to implement the above approach # Variable to store the number# of unique elementscnt = 0; # Function to find the number# of unique elementsdef UniqueElements(arr, s, e, isDuplicate): global cnt # Both start and end are same if (arr[s] == arr[e]): # If the element is duplicate if (isDuplicate == False): cnt += 1; else: mid = s + (e - s) // 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); # Function to count the number# of unique elementsdef unique(arr, N): UniqueElements(arr, 0, N - 1, False); return cnt; # Driver Codeif __name__ == '__main__': arr = [ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 ]; N = len(arr); print(unique(arr, N)); # This code is contributed by Rajput-Ji",
"e": 10674,
"s": 9798,
"text": null
},
{
"code": "// C# code to implement the above approachusing System;public class GFG{ // Variable to store the number // of unique elements static int cnt = 0; // Function to find the number // of unique elements static void UniqueElements(int []arr, int s, int e, bool isDuplicate) { // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { int mid = s + (e - s) / 2; UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); } } // Function to count the number // of unique elements static int unique(int []arr, int N) { UniqueElements(arr, 0, N - 1, false); return cnt; } // Driver Code public static void Main(String[] args) { int []arr = { 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 }; int N = arr.Length; Console.Write(unique(arr, N)); }} // This code is contributed by shikhasingrajput",
"e": 11771,
"s": 10674,
"text": null
},
{
"code": "<script>// javascript code to implement the above approach // Variable to store the number // of unique elements var cnt = 0; // Function to find the number // of unique elements function UniqueElements(arr , s,e, isDuplicate) { // Both start and end are same if (arr[s] == arr[e]) { // If the element is duplicate if (isDuplicate == false) { cnt++; } } else { var mid = s + parseInt((e - s) / 2); UniqueElements(arr, s, mid, isDuplicate); UniqueElements(arr, mid + 1, e, arr[mid] == arr[mid + 1]); } } // Function to count the number // of unique elements function unique(arr , N) { UniqueElements(arr, 0, N - 1, false); return cnt; } // Driver Code var arr = [ 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 5, 5, 7, 7, 8, 8, 9, 9, 10, 11, 12 ]; var N = arr.length; document.write(unique(arr, N)); // This code is contributed by shikhasingrajput</script>",
"e": 12753,
"s": 11771,
"text": null
},
{
"code": null,
"e": 12756,
"s": 12753,
"text": "10"
},
{
"code": null,
"e": 12860,
"s": 12761,
"text": "Time Complexity: O(log(N)) for the average case.The worst case will be O(N).Auxiliary Space: O(1)"
},
{
"code": null,
"e": 12876,
"s": 12862,
"text": "lokeshpotta20"
},
{
"code": null,
"e": 12884,
"s": 12876,
"text": "gfgking"
},
{
"code": null,
"e": 12899,
"s": 12884,
"text": "sagar0719kumar"
},
{
"code": null,
"e": 12916,
"s": 12899,
"text": "_saurabh_jaiswal"
},
{
"code": null,
"e": 12933,
"s": 12916,
"text": "hrithikgarg03188"
},
{
"code": null,
"e": 12945,
"s": 12933,
"text": "29AjayKumar"
},
{
"code": null,
"e": 12962,
"s": 12945,
"text": "shikhasingrajput"
},
{
"code": null,
"e": 12972,
"s": 12962,
"text": "Rajput-Ji"
},
{
"code": null,
"e": 12986,
"s": 12972,
"text": "Binary Search"
},
{
"code": null,
"e": 12993,
"s": 12986,
"text": "Arrays"
},
{
"code": null,
"e": 13003,
"s": 12993,
"text": "Searching"
},
{
"code": null,
"e": 13011,
"s": 13003,
"text": "Sorting"
},
{
"code": null,
"e": 13018,
"s": 13011,
"text": "Arrays"
},
{
"code": null,
"e": 13028,
"s": 13018,
"text": "Searching"
},
{
"code": null,
"e": 13036,
"s": 13028,
"text": "Sorting"
},
{
"code": null,
"e": 13050,
"s": 13036,
"text": "Binary Search"
},
{
"code": null,
"e": 13148,
"s": 13050,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 13180,
"s": 13148,
"text": "Introduction to Data Structures"
},
{
"code": null,
"e": 13205,
"s": 13180,
"text": "Window Sliding Technique"
},
{
"code": null,
"e": 13252,
"s": 13205,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 13316,
"s": 13252,
"text": "What is Data Structure: Types, Classifications and Applications"
},
{
"code": null,
"e": 13347,
"s": 13316,
"text": "Chocolate Distribution Problem"
},
{
"code": null,
"e": 13361,
"s": 13347,
"text": "Binary Search"
},
{
"code": null,
"e": 13408,
"s": 13361,
"text": "Search, insert and delete in an unsorted array"
},
{
"code": null,
"e": 13455,
"s": 13408,
"text": "Median of two sorted arrays of different sizes"
},
{
"code": null,
"e": 13478,
"s": 13455,
"text": "Two Pointers Technique"
}
] |
Understanding constexpr Specifier in C++ | 03 Jun, 2022
constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time (similar to template metaprogramming). constexpr specifies that the value of an object or a function can be evaluated at compile-time and the expression can be used in other constant expressions.
Example:
CPP
// C++ program to demonstrate constexpr function for product// of two numbers. By specifying constexpr, we suggest// compiler to to evaluate value at compile time#include <iostream> constexpr int product(int x, int y) { return (x * y); } int main(){ constexpr int x = product(10, 20); std::cout << x; return 0;}
Output :
200
A function be declared as constexpr
In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement.constexpr function should refer only to constant global variables.constexpr function can call only other constexpr function not simple function.The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function.
In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement.
constexpr function should refer only to constant global variables.
constexpr function can call only other constexpr function not simple function.
The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function.
Constexpr
Inline Functions
Example of performance improvement by constexpr:
CPP
// A C++ program to demonstrate the use of constexpr #include<iostream> using namespace std; constexpr long int fib(int n) { return (n <= 1)? n : fib(n-1) + fib(n-2); } int main () { // value of res is computed at compile time. constexpr long int res = fib(30); cout << res; return 0; }
Output:
832040
When the above program is run on GCC, it takes 0.003 seconds (We can measure time using the time command) If we remove const from the below line, then the value of fib(5) is not evaluated at compile-time, because the result of constexpr is not used in a const expression.
Change,
const long int res = fib(30);
To,
long int res = fib(30);
After making the above change, the time taken by the program becomes higher by 0.017 seconds.
constexpr with constructors: A constructor that is declared with a constexpr specifier is a constexpr constructor also constexpr can be used in the making of constructors and objects. A constexpr constructor is implicitly inline.
Restrictions on constructors that can use constexpr:
No virtual base class
Each parameter should be literal
It is not a try block function
Example:
CPP
// C++ program to demonstrate uses // of constexpr in constructor #include <bits/stdc++.h> using namespace std; // A class with constexpr // constructor and function class Rectangle { int _h, _w; public: // A constexpr constructor constexpr Rectangle (int h, int w) : _h(h), _w(w) {} constexpr int getArea () { return _h * _w; } }; // driver program to test function int main() { // Below object is initialized at compile time constexpr Rectangle obj(10, 20); cout << obj.getArea(); return 0; }
Output :
200
They serve different purposes. constexpr is mainly for optimization while const is for practically const objects like the value of Pi. Both of them can be applied to member methods. Member methods are made const to make sure that there are no accidental changes in the method. On the other hand, the idea of using constexpr is to compute expressions at compile time so that time can be saved when the code is run. const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types.
This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above.
Shun Xian Cai
nidhi_biet
preethibr1
mahdiarfaoui5477
harsh_shokeen
CPP-Library
C Language
C++
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Substring in C++
Function Pointer in C
Left Shift and Right Shift Operators in C/C++
Different Methods to Reverse a String in C++
std::string class in C++
Map in C++ Standard Template Library (STL)
Initialize a vector in C++ (7 different ways)
Set in C++ Standard Template Library (STL)
vector erase() and clear() in C++
unordered_map in C++ STL | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n03 Jun, 2022"
},
{
"code": null,
"e": 576,
"s": 52,
"text": "constexpr is a feature added in C++ 11. The main idea is a performance improvement of programs by doing computations at compile time rather than run time. Note that once a program is compiled and finalized by the developer, it is run multiple times by users. The idea is to spend time in compilation and save time at run time (similar to template metaprogramming). constexpr specifies that the value of an object or a function can be evaluated at compile-time and the expression can be used in other constant expressions. "
},
{
"code": null,
"e": 585,
"s": 576,
"text": "Example:"
},
{
"code": null,
"e": 589,
"s": 585,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate constexpr function for product// of two numbers. By specifying constexpr, we suggest// compiler to to evaluate value at compile time#include <iostream> constexpr int product(int x, int y) { return (x * y); } int main(){ constexpr int x = product(10, 20); std::cout << x; return 0;}",
"e": 912,
"s": 589,
"text": null
},
{
"code": null,
"e": 921,
"s": 912,
"text": "Output :"
},
{
"code": null,
"e": 925,
"s": 921,
"text": "200"
},
{
"code": null,
"e": 961,
"s": 925,
"text": "A function be declared as constexpr"
},
{
"code": null,
"e": 1345,
"s": 961,
"text": "In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement.constexpr function should refer only to constant global variables.constexpr function can call only other constexpr function not simple function.The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function."
},
{
"code": null,
"e": 1458,
"s": 1345,
"text": "In C++ 11, a constexpr function should contain only one return statement. C++ 14 allows more than one statement."
},
{
"code": null,
"e": 1525,
"s": 1458,
"text": "constexpr function should refer only to constant global variables."
},
{
"code": null,
"e": 1604,
"s": 1525,
"text": "constexpr function can call only other constexpr function not simple function."
},
{
"code": null,
"e": 1732,
"s": 1604,
"text": "The function should not be of a void type and some operators like prefix increment (++v) are not allowed in constexpr function."
},
{
"code": null,
"e": 1742,
"s": 1732,
"text": "Constexpr"
},
{
"code": null,
"e": 1759,
"s": 1742,
"text": "Inline Functions"
},
{
"code": null,
"e": 1809,
"s": 1759,
"text": "Example of performance improvement by constexpr: "
},
{
"code": null,
"e": 1813,
"s": 1809,
"text": "CPP"
},
{
"code": "// A C++ program to demonstrate the use of constexpr #include<iostream> using namespace std; constexpr long int fib(int n) { return (n <= 1)? n : fib(n-1) + fib(n-2); } int main () { // value of res is computed at compile time. constexpr long int res = fib(30); cout << res; return 0; } ",
"e": 2125,
"s": 1813,
"text": null
},
{
"code": null,
"e": 2133,
"s": 2125,
"text": "Output:"
},
{
"code": null,
"e": 2140,
"s": 2133,
"text": "832040"
},
{
"code": null,
"e": 2412,
"s": 2140,
"text": "When the above program is run on GCC, it takes 0.003 seconds (We can measure time using the time command) If we remove const from the below line, then the value of fib(5) is not evaluated at compile-time, because the result of constexpr is not used in a const expression."
},
{
"code": null,
"e": 2484,
"s": 2412,
"text": "Change,\n const long int res = fib(30); \nTo,\n long int res = fib(30);"
},
{
"code": null,
"e": 2578,
"s": 2484,
"text": "After making the above change, the time taken by the program becomes higher by 0.017 seconds."
},
{
"code": null,
"e": 2808,
"s": 2578,
"text": "constexpr with constructors: A constructor that is declared with a constexpr specifier is a constexpr constructor also constexpr can be used in the making of constructors and objects. A constexpr constructor is implicitly inline."
},
{
"code": null,
"e": 2861,
"s": 2808,
"text": "Restrictions on constructors that can use constexpr:"
},
{
"code": null,
"e": 2883,
"s": 2861,
"text": "No virtual base class"
},
{
"code": null,
"e": 2916,
"s": 2883,
"text": "Each parameter should be literal"
},
{
"code": null,
"e": 2947,
"s": 2916,
"text": "It is not a try block function"
},
{
"code": null,
"e": 2956,
"s": 2947,
"text": "Example:"
},
{
"code": null,
"e": 2960,
"s": 2956,
"text": "CPP"
},
{
"code": "// C++ program to demonstrate uses // of constexpr in constructor #include <bits/stdc++.h> using namespace std; // A class with constexpr // constructor and function class Rectangle { int _h, _w; public: // A constexpr constructor constexpr Rectangle (int h, int w) : _h(h), _w(w) {} constexpr int getArea () { return _h * _w; } }; // driver program to test function int main() { // Below object is initialized at compile time constexpr Rectangle obj(10, 20); cout << obj.getArea(); return 0; } ",
"e": 3498,
"s": 2960,
"text": null
},
{
"code": null,
"e": 3507,
"s": 3498,
"text": "Output :"
},
{
"code": null,
"e": 3511,
"s": 3507,
"text": "200"
},
{
"code": null,
"e": 4148,
"s": 3511,
"text": "They serve different purposes. constexpr is mainly for optimization while const is for practically const objects like the value of Pi. Both of them can be applied to member methods. Member methods are made const to make sure that there are no accidental changes in the method. On the other hand, the idea of using constexpr is to compute expressions at compile time so that time can be saved when the code is run. const can only be used with non-static member functions whereas constexpr can be used with member and non-member functions, even with constructors but with condition that argument and return type must be of literal types. "
},
{
"code": null,
"e": 4324,
"s": 4148,
"text": "This article is contributed by Utkarsh Trivedi. Please write comments if you find anything incorrect, or if you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4338,
"s": 4324,
"text": "Shun Xian Cai"
},
{
"code": null,
"e": 4349,
"s": 4338,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4360,
"s": 4349,
"text": "preethibr1"
},
{
"code": null,
"e": 4377,
"s": 4360,
"text": "mahdiarfaoui5477"
},
{
"code": null,
"e": 4391,
"s": 4377,
"text": "harsh_shokeen"
},
{
"code": null,
"e": 4403,
"s": 4391,
"text": "CPP-Library"
},
{
"code": null,
"e": 4414,
"s": 4403,
"text": "C Language"
},
{
"code": null,
"e": 4418,
"s": 4414,
"text": "C++"
},
{
"code": null,
"e": 4422,
"s": 4418,
"text": "CPP"
},
{
"code": null,
"e": 4520,
"s": 4422,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 4537,
"s": 4520,
"text": "Substring in C++"
},
{
"code": null,
"e": 4559,
"s": 4537,
"text": "Function Pointer in C"
},
{
"code": null,
"e": 4605,
"s": 4559,
"text": "Left Shift and Right Shift Operators in C/C++"
},
{
"code": null,
"e": 4650,
"s": 4605,
"text": "Different Methods to Reverse a String in C++"
},
{
"code": null,
"e": 4675,
"s": 4650,
"text": "std::string class in C++"
},
{
"code": null,
"e": 4718,
"s": 4675,
"text": "Map in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4764,
"s": 4718,
"text": "Initialize a vector in C++ (7 different ways)"
},
{
"code": null,
"e": 4807,
"s": 4764,
"text": "Set in C++ Standard Template Library (STL)"
},
{
"code": null,
"e": 4841,
"s": 4807,
"text": "vector erase() and clear() in C++"
}
] |
Count of subarrays having exactly K distinct elements | 20 Dec, 2021
Given an array arr[] of size N and an integer K. The task is to find the count of subarrays such that each subarray has exactly K distinct elements.
Examples:
Input: arr[] = {2, 1, 2, 1, 6}, K = 2 Output: 7 {2, 1}, {1, 2}, {2, 1}, {1, 6}, {2, 1, 2}, {1, 2, 1} and {2, 1, 2, 1} are the only valid subarrays.
Input: arr[] = {1, 2, 3, 4, 5}, K = 1 Output: 5
Approach: To directly count the subarrays with exactly K different integers is hard but to find the count of subarrays with at most K different integers is easy. So the idea is to find the count of subarrays with at most K different integers, let it be C(K), and the count of subarrays with at most (K – 1) different integers, let it be C(K – 1) and finally take their difference, C(K) – C(K – 1) which is the required answer. Count of subarrays with at most K different elements can be easily calculated through the sliding window technique. The idea is to keep expanding the right boundary of the window till the count of distinct elements in the window is less than or equal to K and when the count of distinct elements inside the window becomes more than K, start shrinking the window from the left till the count becomes less than or equal to K. Also for every expansion, keep counting the subarrays as right – left + 1 where right and left are the boundaries of the current window.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ implementation of the approach#include<bits/stdc++.h>#include<map>using namespace std; // Function to return the count of subarrays// with at most K distinct elements using// the sliding window techniqueint atMostK(int arr[], int n, int k){ // To store the result int count = 0; // Left boundary of window int left = 0; // Right boundary of window int right = 0; // Map to keep track of number of distinct // elements in the current window unordered_map<int,int> map; // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window if (map.find(arr[right])==map.end()) map[arr[right]]=0; map[arr[right]]++; // Shrinking the window from left if the // count of distinct elements exceeds K while (map.size() > k) { map[arr[left]]= map[arr[left]] - 1; if (map[arr[left]] == 0) map.erase(arr[left]); left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count;} // Function to return the count of subarrays// with exactly K distinct elementsint exactlyK(int arr[], int n, int k){ // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1));} // Driver codeint main(){ int arr[] = { 2, 1, 2, 1, 6 }; int n = sizeof(arr)/sizeof(arr[0]); int k = 2; cout<<(exactlyK(arr, n, k));}
// Java implementation of the approachimport java.util.*; public class GfG { // Function to return the count of subarrays // with at most K distinct elements using // the sliding window technique private static int atMostK(int arr[], int n, int k) { // To store the result int count = 0; // Left boundary of window int left = 0; // Right boundary of window int right = 0; // Map to keep track of number of distinct // elements in the current window HashMap<Integer, Integer> map = new HashMap<>(); // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window map.put(arr[right], map.getOrDefault(arr[right], 0) + 1); // Shrinking the window from left if the // count of distinct elements exceeds K while (map.size() > k) { map.put(arr[left], map.get(arr[left]) - 1); if (map.get(arr[left]) == 0) map.remove(arr[left]); left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count; } // Function to return the count of subarrays // with exactly K distinct elements private static int exactlyK(int arr[], int n, int k) { // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1)); } // Driver code public static void main(String[] args) { int arr[] = { 2, 1, 2, 1, 6 }; int n = arr.length; int k = 2; System.out.print(exactlyK(arr, n, k)); }}
# Python3 implementation of the above approach # Function to return the count of subarrays# with at most K distinct elements using# the sliding window technique def atMostK(arr, n, k): # To store the result count = 0 # Left boundary of window left = 0 # Right boundary of window right = 0 # Map to keep track of number of distinct # elements in the current window map = {} # Loop to calculate the count while(right < n): if arr[right] not in map: map[arr[right]] = 0 # Calculating the frequency of each # element in the current window map[arr[right]] += 1 # Shrinking the window from left if the # count of distinct elements exceeds K while(len(map) > k): if arr[left] not in map: map[arr[left]] = 0 map[arr[left]] -= 1 if map[arr[left]] == 0: del map[arr[left]] left += 1 # Adding the count of subarrays with at most # K distinct elements in the current window count += right - left + 1 right += 1 return count # Function to return the count of subarrays# with exactly K distinct elements def exactlyK(arr, n, k): # Count of subarrays with exactly k distinct # elements is equal to the difference of the # count of subarrays with at most K distinct # elements and the count of subararys with # at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1)) # Driver codeif __name__ == "__main__": arr = [2, 1, 2, 1, 6] n = len(arr) k = 2 print(exactlyK(arr, n, k)) # This code is contributed by AnkitRai01
// C# implementation of the approachusing System;using System.Collections.Generic; class GfG { // Function to return the count of subarrays // with at most K distinct elements using // the sliding window technique private static int atMostK(int[] arr, int n, int k) { // To store the result int count = 0; // Left boundary of window int left = 0; // Right boundary of window int right = 0; // Map to keep track of number of distinct // elements in the current window Dictionary<int, int> map = new Dictionary<int, int>(); // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window if (map.ContainsKey(arr[right])) map[arr[right]] = map[arr[right]] + 1; else map.Add(arr[right], 1); // Shrinking the window from left if the // count of distinct elements exceeds K while (map.Count > k) { if (map.ContainsKey(arr[left])) { map[arr[left]] = map[arr[left]] - 1; if (map[arr[left]] == 0) map.Remove(arr[left]); } left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count; } // Function to return the count of subarrays // with exactly K distinct elements private static int exactlyK(int[] arr, int n, int k) { // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1)); } // Driver code public static void Main(String[] args) { int[] arr = { 2, 1, 2, 1, 6 }; int n = arr.Length; int k = 2; Console.Write(exactlyK(arr, n, k)); }} // This code is contributed by 29AjayKumar
<script> // Javascript implementation of the approach // Function to return the count of subarrays// with at most K distinct elements using// the sliding window techniquefunction atMostK(arr, n, k){ // To store the result let count = 0; // Left boundary of window let left = 0; // Right boundary of window let right = 0; // Map to keep track of number of distinct // elements in the current window let map = new Map(); // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window if (map.has(arr[right])) map.set(arr[right], map.get(arr[right]) + 1); else map.set(arr[right], 1); // Shrinking the window from left if the // count of distinct elements exceeds K while (map.size > k) { map.set(arr[left], map.get(arr[left]) - 1); if (map.get(arr[left]) == 0) map.delete(arr[left]); left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count;} // Function to return the count of subarrays// with exactly K distinct elementsfunction exactlyK(arr, n, k){ // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1));} // Driver codelet arr = [ 2, 1, 2, 1, 6 ];let n = arr.length;let k = 2; document.write(exactlyK(arr, n, k)); // This code is contributed by avanitrachhadiya2155 </script>
7
Time Complexity: O(N) Space Complexity: O(N)
Another Approach: When you move the right cursor, keep tracking whether we have reach a count of K distinct integers, if yes, we process left cursor, here is how we process left cursor:
check whether the element pointed by the left cursor is duplicated in the window, if yes, we remove it, and use a variable (e.g. prefix) to record that we have removed an element from the window). keep this process until we reduce the window size from to exactly K. now we can calculate the number of the valid good array as res += prefix;
after process left cursor and all the stuff, the outer loop will continue and the right cursor will move forward, and then the window size will exceed K, we can simply drop the leftmost element of the window and reset prefix to 0. and continue on.
Below is the implementation of the above approach:
C++
Java
Python3
C#
Javascript
// C++ program to calculate number// of subarrays with distinct elements of size k#include <bits/stdc++.h>#include <map>#include <vector>using namespace std; int subarraysWithKDistinct(vector<int>& A, int K){ // declare a map for the frequency unordered_map<int, int> mapp; int begin = 0, end = 0, prefix = 0, cnt = 0; int res = 0; // traverse the array while (end < A.size()) { // increase the frequency mapp[A[end]]++; if (mapp[A[end]] == 1) { cnt++; } end++; if (cnt > K) { mapp[A[begin]]--; begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp[A[begin]] > 1) { mapp[A[begin]]--; begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // return the final count return res;}// Driver codeint main(){ vector<int> arr{ 2, 1, 2, 1, 6 }; int k = 2; // Function call cout << (subarraysWithKDistinct(arr, k));}// This code is contributed by Harman Singh
// Java program to calculate number// of subarrays with distinct elements of size kimport java.util.*;class GFG{ static int subarraysWithKDistinct(int A[], int K) { // declare a map for the frequency HashMap<Integer, Integer> mapp = new HashMap<>(); int begin = 0, end = 0, prefix = 0, cnt = 0; int res = 0; // traverse the array while (end < A.length) { // increase the frequency if(mapp.containsKey(A[end])) { mapp.put(A[end], mapp.get(A[end]) + 1); } else { mapp.put(A[end], 1); } if (mapp.get(A[end]) == 1) { cnt++; } end++; if (cnt > K) { if(mapp.containsKey(A[begin])) { mapp.put(A[begin], mapp.get(A[begin]) - 1); } else { mapp.put(A[begin], -1); } begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp.get(A[begin]) > 1) { if(mapp.containsKey(A[begin])) { mapp.put(A[begin], mapp.get(A[begin]) - 1); } else { mapp.put(A[begin], -1); } begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // return the final count return res; } // Driver code public static void main(String[] args) { int arr[] = { 2, 1, 2, 1, 6 }; int k = 2; // Function call System.out.println(subarraysWithKDistinct(arr, k)); }} // This code is contributed by divyeshrabadiya07
# Python3 program to calculate number of# subarrays with distinct elements of size kdef subarraysWithKDistinct(A, K): # Declare a map for the frequency mapp = {} begin, end, prefix, cnt = 0, 0, 0, 0 res = 0 # Traverse the array while (end < len(A)): # Increase the frequency mapp[A[end]] = mapp.get(A[end], 0) + 1 if (mapp[A[end]] == 1): cnt += 1 end += 1 if (cnt > K): mapp[A[begin]] -= 1 begin += 1 cnt -= 1 prefix = 0 # Loop until mapp[A[begin]] > 1 while (mapp[A[begin]] > 1): mapp[A[begin]] -= 1 begin += 1 prefix += 1 if (cnt == K): res += prefix + 1 # Return the final count return res # Driver codeif __name__ == '__main__': arr = [ 2, 1, 2, 1, 6 ] k = 2 # Function call print (subarraysWithKDistinct(arr, k)) # This code is contributed by Mohit kumar
// C# program to calculate number// of subarrays with distinct elements of size kusing System;using System.Collections.Generic;class GFG { static int subarraysWithKDistinct(List<int> A, int K) { // declare a map for the frequency Dictionary<int, int> mapp = new Dictionary<int, int>(); int begin = 0, end = 0, prefix = 0, cnt = 0; int res = 0; // traverse the array while (end < A.Count) { // increase the frequency if(mapp.ContainsKey(A[end])) { mapp[A[end]]++; } else{ mapp[A[end]] = 1; } if (mapp[A[end]] == 1) { cnt++; } end++; if (cnt > K) { if(mapp.ContainsKey(A[begin])) { mapp[A[begin]]--; } else{ mapp[A[begin]] = -1; } begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp[A[begin]] > 1) { mapp[A[begin]]--; begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // return the final count return res; } // Driver code static void Main() { List<int> arr = new List<int>(new int[] { 2, 1, 2, 1, 6 }); int k = 2; // Function call Console.Write(subarraysWithKDistinct(arr, k)); }} // This code is contributed by divyesh072019
<script> // Javascript program to calculate number// of subarrays with distinct elements of size kfunction subarraysWithKDistinct(A, K){ // Declare a map for the frequency let mapp = new Map(); let begin = 0, end = 0, prefix = 0, cnt = 0; let res = 0; // Traverse the array while (end < A.length) { // increase the frequency if (mapp.has(A[end])) { mapp.set(A[end], mapp.get(A[end]) + 1); } else { mapp.set(A[end], 1); } if (mapp.get(A[end]) == 1) { cnt++; } end++; if (cnt > K) { if (mapp.has(A[begin])) { mapp.set(A[begin], mapp.get(A[begin]) - 1); } else { mapp.set(A[begin], -1); } begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp.get(A[begin]) > 1) { if(mapp.has(A[begin])) { mapp.set(A[begin], mapp.get(A[begin]) - 1); } else { mapp.set(A[begin], -1); } begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // Return the final count return res;} // Driver codelet arr = [ 2, 1, 2, 1, 6 ];let k = 2; // Function calldocument.write(subarraysWithKDistinct(arr, k)); // This code is contributed by rag2127 </script>
7
Time Complexity: O(N)Auxiliary Space: O(N)
29AjayKumar
ankthon
ukasp
harmansinghh
mohit kumar 29
divyesh072019
divyeshrabadiya07
avanitrachhadiya2155
rag2127
sooda367
pankajsharmagfg
ashutoshsinghgeeksforgeeks
amartyaghoshgfg
sliding-window
subarray
Algorithms
Arrays
sliding-window
Arrays
Algorithms
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
DSA Sheet by Love Babbar
SDE SHEET - A Complete Guide for SDE Preparation
What is Hashing | A Complete Tutorial
Find if there is a path between two vertices in an undirected graph
CPU Scheduling in Operating Systems
Arrays in Java
Write a program to reverse an array or string
Maximum and minimum of an array using minimum number of comparisons
Largest Sum Contiguous Subarray
Arrays in C/C++ | [
{
"code": null,
"e": 52,
"s": 24,
"text": "\n20 Dec, 2021"
},
{
"code": null,
"e": 201,
"s": 52,
"text": "Given an array arr[] of size N and an integer K. The task is to find the count of subarrays such that each subarray has exactly K distinct elements."
},
{
"code": null,
"e": 211,
"s": 201,
"text": "Examples:"
},
{
"code": null,
"e": 359,
"s": 211,
"text": "Input: arr[] = {2, 1, 2, 1, 6}, K = 2 Output: 7 {2, 1}, {1, 2}, {2, 1}, {1, 6}, {2, 1, 2}, {1, 2, 1} and {2, 1, 2, 1} are the only valid subarrays."
},
{
"code": null,
"e": 408,
"s": 359,
"text": "Input: arr[] = {1, 2, 3, 4, 5}, K = 1 Output: 5 "
},
{
"code": null,
"e": 1396,
"s": 408,
"text": "Approach: To directly count the subarrays with exactly K different integers is hard but to find the count of subarrays with at most K different integers is easy. So the idea is to find the count of subarrays with at most K different integers, let it be C(K), and the count of subarrays with at most (K – 1) different integers, let it be C(K – 1) and finally take their difference, C(K) – C(K – 1) which is the required answer. Count of subarrays with at most K different elements can be easily calculated through the sliding window technique. The idea is to keep expanding the right boundary of the window till the count of distinct elements in the window is less than or equal to K and when the count of distinct elements inside the window becomes more than K, start shrinking the window from the left till the count becomes less than or equal to K. Also for every expansion, keep counting the subarrays as right – left + 1 where right and left are the boundaries of the current window."
},
{
"code": null,
"e": 1447,
"s": 1396,
"text": "Below is the implementation of the above approach:"
},
{
"code": null,
"e": 1451,
"s": 1447,
"text": "C++"
},
{
"code": null,
"e": 1456,
"s": 1451,
"text": "Java"
},
{
"code": null,
"e": 1464,
"s": 1456,
"text": "Python3"
},
{
"code": null,
"e": 1467,
"s": 1464,
"text": "C#"
},
{
"code": null,
"e": 1478,
"s": 1467,
"text": "Javascript"
},
{
"code": "// C++ implementation of the approach#include<bits/stdc++.h>#include<map>using namespace std; // Function to return the count of subarrays// with at most K distinct elements using// the sliding window techniqueint atMostK(int arr[], int n, int k){ // To store the result int count = 0; // Left boundary of window int left = 0; // Right boundary of window int right = 0; // Map to keep track of number of distinct // elements in the current window unordered_map<int,int> map; // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window if (map.find(arr[right])==map.end()) map[arr[right]]=0; map[arr[right]]++; // Shrinking the window from left if the // count of distinct elements exceeds K while (map.size() > k) { map[arr[left]]= map[arr[left]] - 1; if (map[arr[left]] == 0) map.erase(arr[left]); left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count;} // Function to return the count of subarrays// with exactly K distinct elementsint exactlyK(int arr[], int n, int k){ // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1));} // Driver codeint main(){ int arr[] = { 2, 1, 2, 1, 6 }; int n = sizeof(arr)/sizeof(arr[0]); int k = 2; cout<<(exactlyK(arr, n, k));}",
"e": 3240,
"s": 1478,
"text": null
},
{
"code": "// Java implementation of the approachimport java.util.*; public class GfG { // Function to return the count of subarrays // with at most K distinct elements using // the sliding window technique private static int atMostK(int arr[], int n, int k) { // To store the result int count = 0; // Left boundary of window int left = 0; // Right boundary of window int right = 0; // Map to keep track of number of distinct // elements in the current window HashMap<Integer, Integer> map = new HashMap<>(); // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window map.put(arr[right], map.getOrDefault(arr[right], 0) + 1); // Shrinking the window from left if the // count of distinct elements exceeds K while (map.size() > k) { map.put(arr[left], map.get(arr[left]) - 1); if (map.get(arr[left]) == 0) map.remove(arr[left]); left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count; } // Function to return the count of subarrays // with exactly K distinct elements private static int exactlyK(int arr[], int n, int k) { // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1)); } // Driver code public static void main(String[] args) { int arr[] = { 2, 1, 2, 1, 6 }; int n = arr.length; int k = 2; System.out.print(exactlyK(arr, n, k)); }}",
"e": 5283,
"s": 3240,
"text": null
},
{
"code": "# Python3 implementation of the above approach # Function to return the count of subarrays# with at most K distinct elements using# the sliding window technique def atMostK(arr, n, k): # To store the result count = 0 # Left boundary of window left = 0 # Right boundary of window right = 0 # Map to keep track of number of distinct # elements in the current window map = {} # Loop to calculate the count while(right < n): if arr[right] not in map: map[arr[right]] = 0 # Calculating the frequency of each # element in the current window map[arr[right]] += 1 # Shrinking the window from left if the # count of distinct elements exceeds K while(len(map) > k): if arr[left] not in map: map[arr[left]] = 0 map[arr[left]] -= 1 if map[arr[left]] == 0: del map[arr[left]] left += 1 # Adding the count of subarrays with at most # K distinct elements in the current window count += right - left + 1 right += 1 return count # Function to return the count of subarrays# with exactly K distinct elements def exactlyK(arr, n, k): # Count of subarrays with exactly k distinct # elements is equal to the difference of the # count of subarrays with at most K distinct # elements and the count of subararys with # at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1)) # Driver codeif __name__ == \"__main__\": arr = [2, 1, 2, 1, 6] n = len(arr) k = 2 print(exactlyK(arr, n, k)) # This code is contributed by AnkitRai01",
"e": 6972,
"s": 5283,
"text": null
},
{
"code": "// C# implementation of the approachusing System;using System.Collections.Generic; class GfG { // Function to return the count of subarrays // with at most K distinct elements using // the sliding window technique private static int atMostK(int[] arr, int n, int k) { // To store the result int count = 0; // Left boundary of window int left = 0; // Right boundary of window int right = 0; // Map to keep track of number of distinct // elements in the current window Dictionary<int, int> map = new Dictionary<int, int>(); // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window if (map.ContainsKey(arr[right])) map[arr[right]] = map[arr[right]] + 1; else map.Add(arr[right], 1); // Shrinking the window from left if the // count of distinct elements exceeds K while (map.Count > k) { if (map.ContainsKey(arr[left])) { map[arr[left]] = map[arr[left]] - 1; if (map[arr[left]] == 0) map.Remove(arr[left]); } left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count; } // Function to return the count of subarrays // with exactly K distinct elements private static int exactlyK(int[] arr, int n, int k) { // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1)); } // Driver code public static void Main(String[] args) { int[] arr = { 2, 1, 2, 1, 6 }; int n = arr.Length; int k = 2; Console.Write(exactlyK(arr, n, k)); }} // This code is contributed by 29AjayKumar",
"e": 9221,
"s": 6972,
"text": null
},
{
"code": "<script> // Javascript implementation of the approach // Function to return the count of subarrays// with at most K distinct elements using// the sliding window techniquefunction atMostK(arr, n, k){ // To store the result let count = 0; // Left boundary of window let left = 0; // Right boundary of window let right = 0; // Map to keep track of number of distinct // elements in the current window let map = new Map(); // Loop to calculate the count while (right < n) { // Calculating the frequency of each // element in the current window if (map.has(arr[right])) map.set(arr[right], map.get(arr[right]) + 1); else map.set(arr[right], 1); // Shrinking the window from left if the // count of distinct elements exceeds K while (map.size > k) { map.set(arr[left], map.get(arr[left]) - 1); if (map.get(arr[left]) == 0) map.delete(arr[left]); left++; } // Adding the count of subarrays with at most // K distinct elements in the current window count += right - left + 1; right++; } return count;} // Function to return the count of subarrays// with exactly K distinct elementsfunction exactlyK(arr, n, k){ // Count of subarrays with exactly k distinct // elements is equal to the difference of the // count of subarrays with at most K distinct // elements and the count of subararys with // at most (K - 1) distinct elements return (atMostK(arr, n, k) - atMostK(arr, n, k - 1));} // Driver codelet arr = [ 2, 1, 2, 1, 6 ];let n = arr.length;let k = 2; document.write(exactlyK(arr, n, k)); // This code is contributed by avanitrachhadiya2155 </script>",
"e": 11049,
"s": 9221,
"text": null
},
{
"code": null,
"e": 11051,
"s": 11049,
"text": "7"
},
{
"code": null,
"e": 11096,
"s": 11051,
"text": "Time Complexity: O(N) Space Complexity: O(N)"
},
{
"code": null,
"e": 11282,
"s": 11096,
"text": "Another Approach: When you move the right cursor, keep tracking whether we have reach a count of K distinct integers, if yes, we process left cursor, here is how we process left cursor:"
},
{
"code": null,
"e": 11622,
"s": 11282,
"text": "check whether the element pointed by the left cursor is duplicated in the window, if yes, we remove it, and use a variable (e.g. prefix) to record that we have removed an element from the window). keep this process until we reduce the window size from to exactly K. now we can calculate the number of the valid good array as res += prefix;"
},
{
"code": null,
"e": 11872,
"s": 11622,
"text": "after process left cursor and all the stuff, the outer loop will continue and the right cursor will move forward, and then the window size will exceed K, we can simply drop the leftmost element of the window and reset prefix to 0. and continue on. "
},
{
"code": null,
"e": 11926,
"s": 11874,
"text": "Below is the implementation of the above approach: "
},
{
"code": null,
"e": 11930,
"s": 11926,
"text": "C++"
},
{
"code": null,
"e": 11935,
"s": 11930,
"text": "Java"
},
{
"code": null,
"e": 11943,
"s": 11935,
"text": "Python3"
},
{
"code": null,
"e": 11946,
"s": 11943,
"text": "C#"
},
{
"code": null,
"e": 11957,
"s": 11946,
"text": "Javascript"
},
{
"code": "// C++ program to calculate number// of subarrays with distinct elements of size k#include <bits/stdc++.h>#include <map>#include <vector>using namespace std; int subarraysWithKDistinct(vector<int>& A, int K){ // declare a map for the frequency unordered_map<int, int> mapp; int begin = 0, end = 0, prefix = 0, cnt = 0; int res = 0; // traverse the array while (end < A.size()) { // increase the frequency mapp[A[end]]++; if (mapp[A[end]] == 1) { cnt++; } end++; if (cnt > K) { mapp[A[begin]]--; begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp[A[begin]] > 1) { mapp[A[begin]]--; begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // return the final count return res;}// Driver codeint main(){ vector<int> arr{ 2, 1, 2, 1, 6 }; int k = 2; // Function call cout << (subarraysWithKDistinct(arr, k));}// This code is contributed by Harman Singh",
"e": 13098,
"s": 11957,
"text": null
},
{
"code": "// Java program to calculate number// of subarrays with distinct elements of size kimport java.util.*;class GFG{ static int subarraysWithKDistinct(int A[], int K) { // declare a map for the frequency HashMap<Integer, Integer> mapp = new HashMap<>(); int begin = 0, end = 0, prefix = 0, cnt = 0; int res = 0; // traverse the array while (end < A.length) { // increase the frequency if(mapp.containsKey(A[end])) { mapp.put(A[end], mapp.get(A[end]) + 1); } else { mapp.put(A[end], 1); } if (mapp.get(A[end]) == 1) { cnt++; } end++; if (cnt > K) { if(mapp.containsKey(A[begin])) { mapp.put(A[begin], mapp.get(A[begin]) - 1); } else { mapp.put(A[begin], -1); } begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp.get(A[begin]) > 1) { if(mapp.containsKey(A[begin])) { mapp.put(A[begin], mapp.get(A[begin]) - 1); } else { mapp.put(A[begin], -1); } begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // return the final count return res; } // Driver code public static void main(String[] args) { int arr[] = { 2, 1, 2, 1, 6 }; int k = 2; // Function call System.out.println(subarraysWithKDistinct(arr, k)); }} // This code is contributed by divyeshrabadiya07",
"e": 14625,
"s": 13098,
"text": null
},
{
"code": "# Python3 program to calculate number of# subarrays with distinct elements of size kdef subarraysWithKDistinct(A, K): # Declare a map for the frequency mapp = {} begin, end, prefix, cnt = 0, 0, 0, 0 res = 0 # Traverse the array while (end < len(A)): # Increase the frequency mapp[A[end]] = mapp.get(A[end], 0) + 1 if (mapp[A[end]] == 1): cnt += 1 end += 1 if (cnt > K): mapp[A[begin]] -= 1 begin += 1 cnt -= 1 prefix = 0 # Loop until mapp[A[begin]] > 1 while (mapp[A[begin]] > 1): mapp[A[begin]] -= 1 begin += 1 prefix += 1 if (cnt == K): res += prefix + 1 # Return the final count return res # Driver codeif __name__ == '__main__': arr = [ 2, 1, 2, 1, 6 ] k = 2 # Function call print (subarraysWithKDistinct(arr, k)) # This code is contributed by Mohit kumar",
"e": 15631,
"s": 14625,
"text": null
},
{
"code": "// C# program to calculate number// of subarrays with distinct elements of size kusing System;using System.Collections.Generic;class GFG { static int subarraysWithKDistinct(List<int> A, int K) { // declare a map for the frequency Dictionary<int, int> mapp = new Dictionary<int, int>(); int begin = 0, end = 0, prefix = 0, cnt = 0; int res = 0; // traverse the array while (end < A.Count) { // increase the frequency if(mapp.ContainsKey(A[end])) { mapp[A[end]]++; } else{ mapp[A[end]] = 1; } if (mapp[A[end]] == 1) { cnt++; } end++; if (cnt > K) { if(mapp.ContainsKey(A[begin])) { mapp[A[begin]]--; } else{ mapp[A[begin]] = -1; } begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp[A[begin]] > 1) { mapp[A[begin]]--; begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // return the final count return res; } // Driver code static void Main() { List<int> arr = new List<int>(new int[] { 2, 1, 2, 1, 6 }); int k = 2; // Function call Console.Write(subarraysWithKDistinct(arr, k)); }} // This code is contributed by divyesh072019",
"e": 17313,
"s": 15631,
"text": null
},
{
"code": "<script> // Javascript program to calculate number// of subarrays with distinct elements of size kfunction subarraysWithKDistinct(A, K){ // Declare a map for the frequency let mapp = new Map(); let begin = 0, end = 0, prefix = 0, cnt = 0; let res = 0; // Traverse the array while (end < A.length) { // increase the frequency if (mapp.has(A[end])) { mapp.set(A[end], mapp.get(A[end]) + 1); } else { mapp.set(A[end], 1); } if (mapp.get(A[end]) == 1) { cnt++; } end++; if (cnt > K) { if (mapp.has(A[begin])) { mapp.set(A[begin], mapp.get(A[begin]) - 1); } else { mapp.set(A[begin], -1); } begin++; cnt--; prefix = 0; } // loop until mapp[A[begin]] > 1 while (mapp.get(A[begin]) > 1) { if(mapp.has(A[begin])) { mapp.set(A[begin], mapp.get(A[begin]) - 1); } else { mapp.set(A[begin], -1); } begin++; prefix++; } if (cnt == K) { res += prefix + 1; } } // Return the final count return res;} // Driver codelet arr = [ 2, 1, 2, 1, 6 ];let k = 2; // Function calldocument.write(subarraysWithKDistinct(arr, k)); // This code is contributed by rag2127 </script>",
"e": 18896,
"s": 17313,
"text": null
},
{
"code": null,
"e": 18898,
"s": 18896,
"text": "7"
},
{
"code": null,
"e": 18941,
"s": 18898,
"text": "Time Complexity: O(N)Auxiliary Space: O(N)"
},
{
"code": null,
"e": 18953,
"s": 18941,
"text": "29AjayKumar"
},
{
"code": null,
"e": 18961,
"s": 18953,
"text": "ankthon"
},
{
"code": null,
"e": 18967,
"s": 18961,
"text": "ukasp"
},
{
"code": null,
"e": 18980,
"s": 18967,
"text": "harmansinghh"
},
{
"code": null,
"e": 18995,
"s": 18980,
"text": "mohit kumar 29"
},
{
"code": null,
"e": 19009,
"s": 18995,
"text": "divyesh072019"
},
{
"code": null,
"e": 19027,
"s": 19009,
"text": "divyeshrabadiya07"
},
{
"code": null,
"e": 19048,
"s": 19027,
"text": "avanitrachhadiya2155"
},
{
"code": null,
"e": 19056,
"s": 19048,
"text": "rag2127"
},
{
"code": null,
"e": 19065,
"s": 19056,
"text": "sooda367"
},
{
"code": null,
"e": 19081,
"s": 19065,
"text": "pankajsharmagfg"
},
{
"code": null,
"e": 19108,
"s": 19081,
"text": "ashutoshsinghgeeksforgeeks"
},
{
"code": null,
"e": 19124,
"s": 19108,
"text": "amartyaghoshgfg"
},
{
"code": null,
"e": 19139,
"s": 19124,
"text": "sliding-window"
},
{
"code": null,
"e": 19148,
"s": 19139,
"text": "subarray"
},
{
"code": null,
"e": 19159,
"s": 19148,
"text": "Algorithms"
},
{
"code": null,
"e": 19166,
"s": 19159,
"text": "Arrays"
},
{
"code": null,
"e": 19181,
"s": 19166,
"text": "sliding-window"
},
{
"code": null,
"e": 19188,
"s": 19181,
"text": "Arrays"
},
{
"code": null,
"e": 19199,
"s": 19188,
"text": "Algorithms"
},
{
"code": null,
"e": 19297,
"s": 19199,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 19322,
"s": 19297,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 19371,
"s": 19322,
"text": "SDE SHEET - A Complete Guide for SDE Preparation"
},
{
"code": null,
"e": 19409,
"s": 19371,
"text": "What is Hashing | A Complete Tutorial"
},
{
"code": null,
"e": 19477,
"s": 19409,
"text": "Find if there is a path between two vertices in an undirected graph"
},
{
"code": null,
"e": 19513,
"s": 19477,
"text": "CPU Scheduling in Operating Systems"
},
{
"code": null,
"e": 19528,
"s": 19513,
"text": "Arrays in Java"
},
{
"code": null,
"e": 19574,
"s": 19528,
"text": "Write a program to reverse an array or string"
},
{
"code": null,
"e": 19642,
"s": 19574,
"text": "Maximum and minimum of an array using minimum number of comparisons"
},
{
"code": null,
"e": 19674,
"s": 19642,
"text": "Largest Sum Contiguous Subarray"
}
] |
How to dynamically insert id into table element using JavaScript ? | 29 May, 2021
This article explains how to dynamically insert “id” into the table element. This can be done by simply looping over the tables and add “id”s dynamically.
Syntax:
The setAttribute() method adds the specified attribute to an element and gives the specified value.table.setAttribute("id", "Dynamically Generated ID")
table.setAttribute("id", "Dynamically Generated ID")
It can also be done by accessing the “id” of the selected element (table).table.id = "Dynamically Generated ID";
table.id = "Dynamically Generated ID";
Example:
HTML
<!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; margin: auto; width: 50%; text-align: center; } </style></head> <body> <h1 style="color:green;text-align: center;"> GeeksForGeeks </h1> <table> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <tr> <td>Jill</td> <td>Smith</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> </tr> </table> <br> <table> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <tr> <td>John</td> <td>Doe</td> </tr> <tr> <td>Emma</td> <td>Allen</td> </tr> </table> <script> // Getting the table element var tables = document .getElementsByTagName("table"); // Looping over tables for (var i = 0; i < tables.length; i++) { // Get the ith table var table = tables[i]; // Set the id dynamically table.setAttribute("id", i + 1); // The line below will also give id // dynamically to the tables //table.id = i+1; } </script></body> </html>
Output: The two tables will be created with “id”s 1 and 2 respectively.
sweetyty
CSS-Misc
HTML-Misc
JavaScript-Misc
CSS
HTML
JavaScript
Web Technologies
HTML
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Design a Tribute Page using HTML & CSS
How to set space between the flexbox ?
Build a Survey Form using HTML and CSS
Design a web page using HTML and CSS
Form validation using jQuery
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": 28,
"s": 0,
"text": "\n29 May, 2021"
},
{
"code": null,
"e": 183,
"s": 28,
"text": "This article explains how to dynamically insert “id” into the table element. This can be done by simply looping over the tables and add “id”s dynamically."
},
{
"code": null,
"e": 191,
"s": 183,
"text": "Syntax:"
},
{
"code": null,
"e": 343,
"s": 191,
"text": "The setAttribute() method adds the specified attribute to an element and gives the specified value.table.setAttribute(\"id\", \"Dynamically Generated ID\")"
},
{
"code": null,
"e": 396,
"s": 343,
"text": "table.setAttribute(\"id\", \"Dynamically Generated ID\")"
},
{
"code": null,
"e": 509,
"s": 396,
"text": "It can also be done by accessing the “id” of the selected element (table).table.id = \"Dynamically Generated ID\";"
},
{
"code": null,
"e": 548,
"s": 509,
"text": "table.id = \"Dynamically Generated ID\";"
},
{
"code": null,
"e": 557,
"s": 548,
"text": "Example:"
},
{
"code": null,
"e": 562,
"s": 557,
"text": "HTML"
},
{
"code": "<!DOCTYPE html><html> <head> <style> table, th, td { border: 1px solid black; border-collapse: collapse; margin: auto; width: 50%; text-align: center; } </style></head> <body> <h1 style=\"color:green;text-align: center;\"> GeeksForGeeks </h1> <table> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <tr> <td>Jill</td> <td>Smith</td> </tr> <tr> <td>Eve</td> <td>Jackson</td> </tr> </table> <br> <table> <tr> <th>Firstname</th> <th>Lastname</th> </tr> <tr> <td>John</td> <td>Doe</td> </tr> <tr> <td>Emma</td> <td>Allen</td> </tr> </table> <script> // Getting the table element var tables = document .getElementsByTagName(\"table\"); // Looping over tables for (var i = 0; i < tables.length; i++) { // Get the ith table var table = tables[i]; // Set the id dynamically table.setAttribute(\"id\", i + 1); // The line below will also give id // dynamically to the tables //table.id = i+1; } </script></body> </html>",
"e": 1940,
"s": 562,
"text": null
},
{
"code": null,
"e": 2012,
"s": 1940,
"text": "Output: The two tables will be created with “id”s 1 and 2 respectively."
},
{
"code": null,
"e": 2021,
"s": 2012,
"text": "sweetyty"
},
{
"code": null,
"e": 2030,
"s": 2021,
"text": "CSS-Misc"
},
{
"code": null,
"e": 2040,
"s": 2030,
"text": "HTML-Misc"
},
{
"code": null,
"e": 2056,
"s": 2040,
"text": "JavaScript-Misc"
},
{
"code": null,
"e": 2060,
"s": 2056,
"text": "CSS"
},
{
"code": null,
"e": 2065,
"s": 2060,
"text": "HTML"
},
{
"code": null,
"e": 2076,
"s": 2065,
"text": "JavaScript"
},
{
"code": null,
"e": 2093,
"s": 2076,
"text": "Web Technologies"
},
{
"code": null,
"e": 2098,
"s": 2093,
"text": "HTML"
},
{
"code": null,
"e": 2196,
"s": 2098,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 2235,
"s": 2196,
"text": "Design a Tribute Page using HTML & CSS"
},
{
"code": null,
"e": 2274,
"s": 2235,
"text": "How to set space between the flexbox ?"
},
{
"code": null,
"e": 2313,
"s": 2274,
"text": "Build a Survey Form using HTML and CSS"
},
{
"code": null,
"e": 2350,
"s": 2313,
"text": "Design a web page using HTML and CSS"
},
{
"code": null,
"e": 2379,
"s": 2350,
"text": "Form validation using jQuery"
},
{
"code": null,
"e": 2403,
"s": 2379,
"text": "REST API (Introduction)"
},
{
"code": null,
"e": 2456,
"s": 2403,
"text": "Hide or show elements in HTML using display property"
},
{
"code": null,
"e": 2516,
"s": 2456,
"text": "How to set the default value for an HTML <select> element ?"
},
{
"code": null,
"e": 2577,
"s": 2516,
"text": "How to set input type date in dd-mm-yyyy format using HTML ?"
}
] |
Single and Double Quotes | Python | 14 Jul, 2019
Python string functions are very popular. There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct depending upon the requirement. Sometimes we have to use quotes (single or double quotes) together in the same string, in such cases, we use single and double quotes alternatively so that they can be distinguished.
Example #1:Check below example and analyze the error –
#Gives Error
print('It's python')
Explanation –It gives an invalid syntax error. Because single quote after “it” is considered as the end of the string and rest part is not the part of a string.
It can be corrected as:
print("It's Python !")
Output:
It's Python!
Example #2:If you want to print ‘WithQuotes’ in python, this can’t be done with only single (or double) quotes alone, it requires simultaneous use of both.
# this code prints the output within quotes.# print WithQuotes within single quotesprint("'WithQuotes'")print("Hello 'Python'") # print WithQuotes within single quotesprint('"WithQuotes"')print('Hello "Python"')
Output –
'WithQuotes'
Hello 'Python'
"WithQuotes"
Hello "Python"
Conclusion –The choice between both the types (single quotes and double quotes) depends on the programmer’s choice. Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it’s sometimes our need to use one type over the other.
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Rotate axis tick labels in Seaborn and Matplotlib
Deque in Python
Stack in Python
Python Dictionary
sum() function in Python
Different ways to create Pandas Dataframe
Queue in Python
Read a file line by line in Python
Defaultdict in Python
How to iterate through Excel rows in Python? | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n14 Jul, 2019"
},
{
"code": null,
"e": 476,
"s": 53,
"text": "Python string functions are very popular. There are two ways to represent strings in python. String is enclosed either with single quotes or double quotes. Both the ways (single or double quotes) are correct depending upon the requirement. Sometimes we have to use quotes (single or double quotes) together in the same string, in such cases, we use single and double quotes alternatively so that they can be distinguished."
},
{
"code": null,
"e": 531,
"s": 476,
"text": "Example #1:Check below example and analyze the error –"
},
{
"code": null,
"e": 567,
"s": 531,
"text": "#Gives Error\nprint('It's python')\n\n"
},
{
"code": null,
"e": 728,
"s": 567,
"text": "Explanation –It gives an invalid syntax error. Because single quote after “it” is considered as the end of the string and rest part is not the part of a string."
},
{
"code": null,
"e": 752,
"s": 728,
"text": "It can be corrected as:"
},
{
"code": "print(\"It's Python !\")",
"e": 775,
"s": 752,
"text": null
},
{
"code": null,
"e": 783,
"s": 775,
"text": "Output:"
},
{
"code": null,
"e": 797,
"s": 783,
"text": "It's Python!\n"
},
{
"code": null,
"e": 953,
"s": 797,
"text": "Example #2:If you want to print ‘WithQuotes’ in python, this can’t be done with only single (or double) quotes alone, it requires simultaneous use of both."
},
{
"code": "# this code prints the output within quotes.# print WithQuotes within single quotesprint(\"'WithQuotes'\")print(\"Hello 'Python'\") # print WithQuotes within single quotesprint('\"WithQuotes\"')print('Hello \"Python\"')",
"e": 1166,
"s": 953,
"text": null
},
{
"code": null,
"e": 1175,
"s": 1166,
"text": "Output –"
},
{
"code": null,
"e": 1232,
"s": 1175,
"text": "'WithQuotes'\nHello 'Python'\n\"WithQuotes\"\nHello \"Python\"\n"
},
{
"code": null,
"e": 1604,
"s": 1232,
"text": "Conclusion –The choice between both the types (single quotes and double quotes) depends on the programmer’s choice. Generally, double quotes are used for string representation and single quotes are used for regular expressions, dict keys or SQL. Hence both single quote and double quotes depict string in python but it’s sometimes our need to use one type over the other."
},
{
"code": null,
"e": 1611,
"s": 1604,
"text": "Python"
},
{
"code": null,
"e": 1709,
"s": 1611,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 1759,
"s": 1709,
"text": "Rotate axis tick labels in Seaborn and Matplotlib"
},
{
"code": null,
"e": 1775,
"s": 1759,
"text": "Deque in Python"
},
{
"code": null,
"e": 1791,
"s": 1775,
"text": "Stack in Python"
},
{
"code": null,
"e": 1809,
"s": 1791,
"text": "Python Dictionary"
},
{
"code": null,
"e": 1834,
"s": 1809,
"text": "sum() function in Python"
},
{
"code": null,
"e": 1876,
"s": 1834,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 1892,
"s": 1876,
"text": "Queue in Python"
},
{
"code": null,
"e": 1927,
"s": 1892,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 1949,
"s": 1927,
"text": "Defaultdict in Python"
}
] |
Converting Pandas Crosstab into Stacked DataFrame | 11 Jan, 2022
In this article, we will discuss how to convert a pandas crosstab to a stacked dataframe.
A stacked DataFrame is a multi-level index with one or more new inner levels as compared to the original DataFrame. If the columns have a single level, then the result is a series object.
The panda’s crosstab function is a frequency table that shows the relationship between two or more variables by building a cross-tabulation table that computes the frequency among certain groups of data.
Syntax:
pandas.crosstab(index, columns, rownames=None, colnames=None)
Parameters:
index – array or series or list of array-like objects. this value is used to group in rows
columns – array or series or list of array-like objects. this value is used to group in columns
rownames – the name specified here must match the number of row arrays passed.
colnames – the name specified here must match the number of column arrays passed.
Example:
In this example, we are creating 3 sample arrays namely car_brand, version, fuel_type as shown. Now, we are passing these arrays as the index, columns, and row and column names to the crosstab function as shown.
Finally, crosstab dataframe can also be visualized using the python plot.bar() function
Python3
# import the numpy and pandas packageimport numpy as npimport pandas as pd # create three separate arrays namely car_brand,# version, fuel_type as showncar_brand = np.array(["bmw", "bmw", "bmw", "bmw", "benz", "benz", "bmw", "bmw", "benz", "benz", "benz", "benz", "bmw", "bmw", "bmw", "benz", "benz", ], dtype=object) version = np.array(["one", "one", "one", "two", "one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "one", "two", "one"], dtype=object) fuel_type = np.array(["petrol", "petrol", "petrol", "diesel", "diesel", "petrol", "diesel", "diesel", "diesel", "petrol", "petrol", "diesel", "petrol", "petrol", "petrol", "diesel", "diesel", ], dtype=object) # use pandas crosstab and pass the three arrays# as index and columns to create a crosstab table.cross_tab_data = pd.crosstab(index=car_brand, columns=[version, fuel_type], rownames=['car_brand'], colnames=['version', 'fuel_type']) print(cross_tab_data) barplot = cross_tab_data.plot.bar()
Output:
Here we are going to specify the number of the levels to be stacked. This will convert based on the axis levels on the particular columns of the pandas DataFrame.
Syntax:
pandas.DataFrame.stack(level, dropna)
Parameters:
level – specifies the levels to be stacked from the column axis to the index axis in the resulting dataframe
dropna – a bool type. Whether to drop or not the rows in the resulting DataFrame/Series with missing values
Example 1:
Here, We will convert the crosstab to a stacked dataframe. The fuel_type level will be stacked as a column in the resulting dataframe.
Python3
# import the numpy and pandas packageimport numpy as npimport pandas as pd # create three separate arrays namely car_brand,# version, fuel_type as showncar_brand = np.array(["bmw", "bmw", "bmw", "bmw", "benz", "benz", "bmw", "bmw", "benz", "benz", "benz", "benz", "bmw", "bmw", "bmw", "benz", "benz", ], dtype=object) version = np.array(["one", "one", "one", "two", "one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "one", "two", "one"], dtype=object) fuel_type = np.array(["petrol", "petrol", "petrol", "diesel", "diesel", "petrol", "diesel", "diesel", "diesel", "petrol", "petrol", "diesel", "petrol", "petrol", "petrol", "diesel", "diesel", ], dtype=object) # use pandas crosstab and pass the three# arrays as index and columns# to create a crosstab table.cross_tab_data = pd.crosstab(index=car_brand, columns=[version, fuel_type], rownames=['car_brand'], colnames=['version', 'fuel_type']) barplot = cross_tab_data.plot.bar() # use the created sample crosstab data# to convert it to a stacked dataframestacked_data = cross_tab_data.stack(level=1) print(stacked_data)
Output:
Example 2:
In this example, we have shown the results for two levels 1 and 2.
Python3
# import the numpy and pandas packageimport numpy as npimport pandas as pd # create three separate arrays namely car_brand,# version, fuel_type as showncar_brand = np.array(["bmw", "bmw", "bmw", "bmw", "benz", "benz", "bmw", "bmw", "benz", "benz", "benz", "benz", "bmw", "bmw", "bmw", "benz", "benz", ], dtype=object) version = np.array(["one", "one", "one", "two", "one", "one", "one", "two", "one", "one", "one", "two", "two", "two", "one", "two", "one"], dtype=object) fuel_type = np.array(["petrol", "petrol", "petrol", "diesel", "diesel", "petrol", "diesel", "diesel", "diesel", "petrol", "petrol", "diesel", "petrol", "petrol", "petrol", "diesel", "diesel", ], dtype=object) year_release = np.array([2000, 2005, 2000, 2007, 2000, 2005, 2007, 2005, 2005, 2000, 2007, 2000, 2007, 2005, 2005, 2007, 2000], dtype=object) # use pandas crosstab and pass the three arrays# as index and columns to create a crosstab table.cross_tab_data = pd.crosstab(index=car_brand, columns=[version, fuel_type, year_release], rownames=['car_brand'], colnames=['version', 'fuel_type', 'year_release']) barplot = cross_tab_data.plot.bar() # use the created sample crosstab data to# convert it to a stacked dataframe with# level 1stacked_data = cross_tab_data.stack(level=1) barplot = stacked_data.plot.bar() # use the created sample crosstab data to# convert it to a stacked dataframe with# level 2stacked_data = cross_tab_data.stack(level=2) barplot = stacked_data.plot.bar()
Output:
sweetyty
sumitgumber28
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
Python | os.path.join() method
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
Python | Get unique values from a list
Python | datetime.timedelta() function | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Jan, 2022"
},
{
"code": null,
"e": 118,
"s": 28,
"text": "In this article, we will discuss how to convert a pandas crosstab to a stacked dataframe."
},
{
"code": null,
"e": 308,
"s": 118,
"text": "A stacked DataFrame is a multi-level index with one or more new inner levels as compared to the original DataFrame. If the columns have a single level, then the result is a series object. "
},
{
"code": null,
"e": 512,
"s": 308,
"text": "The panda’s crosstab function is a frequency table that shows the relationship between two or more variables by building a cross-tabulation table that computes the frequency among certain groups of data."
},
{
"code": null,
"e": 520,
"s": 512,
"text": "Syntax:"
},
{
"code": null,
"e": 582,
"s": 520,
"text": "pandas.crosstab(index, columns, rownames=None, colnames=None)"
},
{
"code": null,
"e": 594,
"s": 582,
"text": "Parameters:"
},
{
"code": null,
"e": 685,
"s": 594,
"text": "index – array or series or list of array-like objects. this value is used to group in rows"
},
{
"code": null,
"e": 781,
"s": 685,
"text": "columns – array or series or list of array-like objects. this value is used to group in columns"
},
{
"code": null,
"e": 860,
"s": 781,
"text": "rownames – the name specified here must match the number of row arrays passed."
},
{
"code": null,
"e": 942,
"s": 860,
"text": "colnames – the name specified here must match the number of column arrays passed."
},
{
"code": null,
"e": 951,
"s": 942,
"text": "Example:"
},
{
"code": null,
"e": 1163,
"s": 951,
"text": "In this example, we are creating 3 sample arrays namely car_brand, version, fuel_type as shown. Now, we are passing these arrays as the index, columns, and row and column names to the crosstab function as shown."
},
{
"code": null,
"e": 1251,
"s": 1163,
"text": "Finally, crosstab dataframe can also be visualized using the python plot.bar() function"
},
{
"code": null,
"e": 1259,
"s": 1251,
"text": "Python3"
},
{
"code": "# import the numpy and pandas packageimport numpy as npimport pandas as pd # create three separate arrays namely car_brand,# version, fuel_type as showncar_brand = np.array([\"bmw\", \"bmw\", \"bmw\", \"bmw\", \"benz\", \"benz\", \"bmw\", \"bmw\", \"benz\", \"benz\", \"benz\", \"benz\", \"bmw\", \"bmw\", \"bmw\", \"benz\", \"benz\", ], dtype=object) version = np.array([\"one\", \"one\", \"one\", \"two\", \"one\", \"one\", \"one\", \"two\", \"one\", \"one\", \"one\", \"two\", \"two\", \"two\", \"one\", \"two\", \"one\"], dtype=object) fuel_type = np.array([\"petrol\", \"petrol\", \"petrol\", \"diesel\", \"diesel\", \"petrol\", \"diesel\", \"diesel\", \"diesel\", \"petrol\", \"petrol\", \"diesel\", \"petrol\", \"petrol\", \"petrol\", \"diesel\", \"diesel\", ], dtype=object) # use pandas crosstab and pass the three arrays# as index and columns to create a crosstab table.cross_tab_data = pd.crosstab(index=car_brand, columns=[version, fuel_type], rownames=['car_brand'], colnames=['version', 'fuel_type']) print(cross_tab_data) barplot = cross_tab_data.plot.bar()",
"e": 2497,
"s": 1259,
"text": null
},
{
"code": null,
"e": 2505,
"s": 2497,
"text": "Output:"
},
{
"code": null,
"e": 2668,
"s": 2505,
"text": "Here we are going to specify the number of the levels to be stacked. This will convert based on the axis levels on the particular columns of the pandas DataFrame."
},
{
"code": null,
"e": 2676,
"s": 2668,
"text": "Syntax:"
},
{
"code": null,
"e": 2714,
"s": 2676,
"text": "pandas.DataFrame.stack(level, dropna)"
},
{
"code": null,
"e": 2726,
"s": 2714,
"text": "Parameters:"
},
{
"code": null,
"e": 2835,
"s": 2726,
"text": "level – specifies the levels to be stacked from the column axis to the index axis in the resulting dataframe"
},
{
"code": null,
"e": 2943,
"s": 2835,
"text": "dropna – a bool type. Whether to drop or not the rows in the resulting DataFrame/Series with missing values"
},
{
"code": null,
"e": 2954,
"s": 2943,
"text": "Example 1:"
},
{
"code": null,
"e": 3089,
"s": 2954,
"text": "Here, We will convert the crosstab to a stacked dataframe. The fuel_type level will be stacked as a column in the resulting dataframe."
},
{
"code": null,
"e": 3097,
"s": 3089,
"text": "Python3"
},
{
"code": "# import the numpy and pandas packageimport numpy as npimport pandas as pd # create three separate arrays namely car_brand,# version, fuel_type as showncar_brand = np.array([\"bmw\", \"bmw\", \"bmw\", \"bmw\", \"benz\", \"benz\", \"bmw\", \"bmw\", \"benz\", \"benz\", \"benz\", \"benz\", \"bmw\", \"bmw\", \"bmw\", \"benz\", \"benz\", ], dtype=object) version = np.array([\"one\", \"one\", \"one\", \"two\", \"one\", \"one\", \"one\", \"two\", \"one\", \"one\", \"one\", \"two\", \"two\", \"two\", \"one\", \"two\", \"one\"], dtype=object) fuel_type = np.array([\"petrol\", \"petrol\", \"petrol\", \"diesel\", \"diesel\", \"petrol\", \"diesel\", \"diesel\", \"diesel\", \"petrol\", \"petrol\", \"diesel\", \"petrol\", \"petrol\", \"petrol\", \"diesel\", \"diesel\", ], dtype=object) # use pandas crosstab and pass the three# arrays as index and columns# to create a crosstab table.cross_tab_data = pd.crosstab(index=car_brand, columns=[version, fuel_type], rownames=['car_brand'], colnames=['version', 'fuel_type']) barplot = cross_tab_data.plot.bar() # use the created sample crosstab data# to convert it to a stacked dataframestacked_data = cross_tab_data.stack(level=1) print(stacked_data)",
"e": 4455,
"s": 3097,
"text": null
},
{
"code": null,
"e": 4463,
"s": 4455,
"text": "Output:"
},
{
"code": null,
"e": 4475,
"s": 4463,
"text": "Example 2: "
},
{
"code": null,
"e": 4542,
"s": 4475,
"text": "In this example, we have shown the results for two levels 1 and 2."
},
{
"code": null,
"e": 4550,
"s": 4542,
"text": "Python3"
},
{
"code": "# import the numpy and pandas packageimport numpy as npimport pandas as pd # create three separate arrays namely car_brand,# version, fuel_type as showncar_brand = np.array([\"bmw\", \"bmw\", \"bmw\", \"bmw\", \"benz\", \"benz\", \"bmw\", \"bmw\", \"benz\", \"benz\", \"benz\", \"benz\", \"bmw\", \"bmw\", \"bmw\", \"benz\", \"benz\", ], dtype=object) version = np.array([\"one\", \"one\", \"one\", \"two\", \"one\", \"one\", \"one\", \"two\", \"one\", \"one\", \"one\", \"two\", \"two\", \"two\", \"one\", \"two\", \"one\"], dtype=object) fuel_type = np.array([\"petrol\", \"petrol\", \"petrol\", \"diesel\", \"diesel\", \"petrol\", \"diesel\", \"diesel\", \"diesel\", \"petrol\", \"petrol\", \"diesel\", \"petrol\", \"petrol\", \"petrol\", \"diesel\", \"diesel\", ], dtype=object) year_release = np.array([2000, 2005, 2000, 2007, 2000, 2005, 2007, 2005, 2005, 2000, 2007, 2000, 2007, 2005, 2005, 2007, 2000], dtype=object) # use pandas crosstab and pass the three arrays# as index and columns to create a crosstab table.cross_tab_data = pd.crosstab(index=car_brand, columns=[version, fuel_type, year_release], rownames=['car_brand'], colnames=['version', 'fuel_type', 'year_release']) barplot = cross_tab_data.plot.bar() # use the created sample crosstab data to# convert it to a stacked dataframe with# level 1stacked_data = cross_tab_data.stack(level=1) barplot = stacked_data.plot.bar() # use the created sample crosstab data to# convert it to a stacked dataframe with# level 2stacked_data = cross_tab_data.stack(level=2) barplot = stacked_data.plot.bar()",
"e": 6368,
"s": 4550,
"text": null
},
{
"code": null,
"e": 6376,
"s": 6368,
"text": "Output:"
},
{
"code": null,
"e": 6385,
"s": 6376,
"text": "sweetyty"
},
{
"code": null,
"e": 6399,
"s": 6385,
"text": "sumitgumber28"
},
{
"code": null,
"e": 6406,
"s": 6399,
"text": "Picked"
},
{
"code": null,
"e": 6430,
"s": 6406,
"text": "Python pandas-dataFrame"
},
{
"code": null,
"e": 6444,
"s": 6430,
"text": "Python-pandas"
},
{
"code": null,
"e": 6451,
"s": 6444,
"text": "Python"
},
{
"code": null,
"e": 6549,
"s": 6451,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 6581,
"s": 6549,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 6608,
"s": 6581,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 6629,
"s": 6608,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 6652,
"s": 6629,
"text": "Introduction To PYTHON"
},
{
"code": null,
"e": 6708,
"s": 6652,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 6739,
"s": 6708,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 6781,
"s": 6739,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 6823,
"s": 6781,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 6862,
"s": 6823,
"text": "Python | Get unique values from a list"
}
] |
Swipe to Delete and Undo in Android RecyclerView | 05 Oct, 2021
We have seen many apps having a RecyclerView present in them and along with that, we have seen many functionalities in that RecyclerView for swipe to delete and many more. We have seen this type of feature in Gmail apps where we can swipe or item right or left to delete or add to the archive. In this article, we will take a look at the implementation of Swipe to Delete RecyclerView items in Android with Undo functionality in it.
We will be building a simple application in which we will be displaying a simple RecyclerView which displays a list of courses along with its description and we will be adding functionality for swipe to delete and undo to it. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language.
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include:
Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view.
View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data.
Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View.
Step 2: Create a Card Layout for RecyclerView Card Items
Go to the app > res > layout> right-click > New > Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--XML implementation of Card Layout--><androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="5dp" app:cardCornerRadius="5dp" app:cardElevation="5dp"> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="3dp" android:orientation="vertical"> <!--text view for displaying our course name--> <TextView android:id="@+id/idTVCourseName" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:padding="5dp" android:text="Course Name" android:textColor="@color/black" /> <!--text view for displaying our course description--> <TextView android:id="@+id/idTVCourseDesc" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="2dp" android:padding="5dp" android:text="Course Description" android:textColor="@color/black" /> </LinearLayout> </androidx.cardview.widget.CardView>
Step 3: Create a Java class for Modal Data
Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file.
Java
public class RecyclerData { // string for displaying // title and description. private String title; private String description; // constructor for our title and description. public RecyclerData(String title, String description) { this.title = title; this.description = description; } // creating getter and setter methods. public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }
Step 4: Create a new java class for the Adapter
Similarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView.
Note: View Holder Class is also implemented in Adapter Class itself.
These methods to handle Recycler View includes:
onCreateViewHolder: This method inflates card layout items for Recycler View.
onBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view.
getItemCount: This method returns the length of the RecyclerView.
Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { // creating a variable for our array list and context. private ArrayList<RecyclerData> courseDataArrayList; private Context mcontext; // creating a constructor class. public RecyclerViewAdapter(ArrayList<RecyclerData> recyclerDataArrayList, Context mcontext) { this.courseDataArrayList = recyclerDataArrayList; this.mcontext = mcontext; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflate Layout View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { // Set the data to textview from our modal class. RecyclerData recyclerData = courseDataArrayList.get(position); holder.courseNameTV.setText(recyclerData.getTitle()); holder.courseDescTV.setText(recyclerData.getDescription()); } @Override public int getItemCount() { // this method returns // the size of recyclerview return courseDataArrayList.size(); } // View Holder Class to handle Recycler View. public class RecyclerViewHolder extends RecyclerView.ViewHolder { // creating a variable for our text view. private TextView courseNameTV; private TextView courseDescTV; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDesc); } }}
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_gravity="center" android:gravity="center" android:orientation="vertical" tools:context=".MainActivity"> <!--creating a recycler view for displaying our list of courses--> <androidx.recyclerview.widget.RecyclerView android:id="@+id/idRVCourse" android:layout_width="match_parent" android:layout_height="match_parent" /> </RelativeLayout>
Step 6: Working with the MainActivity.java file
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
Java
import android.os.Bundle;import android.view.View; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.ItemTouchHelper;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.snackbar.Snackbar; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating a variable for recycler view, // array list and adapter class. private RecyclerView courseRV; private ArrayList<RecyclerData> recyclerDataArrayList; private RecyclerViewAdapter recyclerViewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseRV = findViewById(R.id.idRVCourse); // creating new array list. recyclerDataArrayList = new ArrayList<>(); // in below line we are adding data to our array list. recyclerDataArrayList.add(new RecyclerData("DSA Course", "DSA Self Paced Course")); recyclerDataArrayList.add(new RecyclerData("C++ Course", "C++ Self Paced Course")); recyclerDataArrayList.add(new RecyclerData("Java Course", "Java Self Paced Course")); recyclerDataArrayList.add(new RecyclerData("Python Course", "Python Self Paced Course")); recyclerDataArrayList.add(new RecyclerData("Fork CPP", "Fork CPP Self Paced Course")); recyclerDataArrayList.add(new RecyclerData("Amazon SDE", "Amazon SDE Test Questions")); // initializing our adapter class with our array list and context. recyclerViewAdapter = new RecyclerViewAdapter(recyclerDataArrayList, this); // below line is to set layout manager for our recycler view. LinearLayoutManager manager = new LinearLayoutManager(this); // setting layout manager for our recycler view. courseRV.setLayoutManager(manager); // below line is to set adapter // to our recycler view. courseRV.setAdapter(recyclerViewAdapter); // on below line we are creating a method to create item touch helper // method for adding swipe to delete functionality. // in this we are specifying drag direction and position to right new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { // this method is called // when the item is moved. return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { // this method is called when we swipe our item to right direction. // on below line we are getting the item at a particular position. RecyclerData deletedCourse = recyclerDataArrayList.get(viewHolder.getAdapterPosition()); // below line is to get the position // of the item at that position. int position = viewHolder.getAdapterPosition(); // this method is called when item is swiped. // below line is to remove item from our array list. recyclerDataArrayList.remove(viewHolder.getAdapterPosition()); // below line is to notify our item is removed from adapter. recyclerViewAdapter.notifyItemRemoved(viewHolder.getAdapterPosition()); // below line is to display our snackbar with action. Snackbar.make(courseRV, deletedCourse.getTitle(), Snackbar.LENGTH_LONG).setAction("Undo", new View.OnClickListener() { @Override public void onClick(View v) { // adding on click listener to our action of snack bar. // below line is to add our item to array list with a position. recyclerDataArrayList.add(position, deletedCourse); // below line is to notify item is // added to our adapter class. recyclerViewAdapter.notifyItemInserted(position); } }).show(); } // at last we are adding this // to our recycler view. }).attachToRecyclerView(courseRV); }}
Now run your app and see the output of the app.
varshagumber28
android
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 53,
"s": 25,
"text": "\n05 Oct, 2021"
},
{
"code": null,
"e": 487,
"s": 53,
"text": "We have seen many apps having a RecyclerView present in them and along with that, we have seen many functionalities in that RecyclerView for swipe to delete and many more. We have seen this type of feature in Gmail apps where we can swipe or item right or left to delete or add to the archive. In this article, we will take a look at the implementation of Swipe to Delete RecyclerView items in Android with Undo functionality in it. "
},
{
"code": null,
"e": 878,
"s": 487,
"text": "We will be building a simple application in which we will be displaying a simple RecyclerView which displays a list of courses along with its description and we will be adding functionality for swipe to delete and undo to it. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. "
},
{
"code": null,
"e": 907,
"s": 878,
"text": "Step 1: Create a New Project"
},
{
"code": null,
"e": 1069,
"s": 907,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language."
},
{
"code": null,
"e": 1198,
"s": 1069,
"text": "To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include: "
},
{
"code": null,
"e": 1315,
"s": 1198,
"text": "Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view."
},
{
"code": null,
"e": 1522,
"s": 1315,
"text": "View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data."
},
{
"code": null,
"e": 1672,
"s": 1522,
"text": "Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View."
},
{
"code": null,
"e": 1729,
"s": 1672,
"text": "Step 2: Create a Card Layout for RecyclerView Card Items"
},
{
"code": null,
"e": 1963,
"s": 1729,
"text": "Go to the app > res > layout> right-click > New > Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file."
},
{
"code": null,
"e": 1967,
"s": 1963,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><!--XML implementation of Card Layout--><androidx.cardview.widget.CardView xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"5dp\" app:cardCornerRadius=\"5dp\" app:cardElevation=\"5dp\"> <LinearLayout android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"3dp\" android:orientation=\"vertical\"> <!--text view for displaying our course name--> <TextView android:id=\"@+id/idTVCourseName\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"2dp\" android:padding=\"5dp\" android:text=\"Course Name\" android:textColor=\"@color/black\" /> <!--text view for displaying our course description--> <TextView android:id=\"@+id/idTVCourseDesc\" android:layout_width=\"match_parent\" android:layout_height=\"wrap_content\" android:layout_margin=\"2dp\" android:padding=\"5dp\" android:text=\"Course Description\" android:textColor=\"@color/black\" /> </LinearLayout> </androidx.cardview.widget.CardView>",
"e": 3364,
"s": 1967,
"text": null
},
{
"code": null,
"e": 3411,
"s": 3368,
"text": "Step 3: Create a Java class for Modal Data"
},
{
"code": null,
"e": 3656,
"s": 3413,
"text": "Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file."
},
{
"code": null,
"e": 3663,
"s": 3658,
"text": "Java"
},
{
"code": "public class RecyclerData { // string for displaying // title and description. private String title; private String description; // constructor for our title and description. public RecyclerData(String title, String description) { this.title = title; this.description = description; } // creating getter and setter methods. public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } }",
"e": 4325,
"s": 3663,
"text": null
},
{
"code": null,
"e": 4377,
"s": 4329,
"text": "Step 4: Create a new java class for the Adapter"
},
{
"code": null,
"e": 4581,
"s": 4379,
"text": "Similarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView. "
},
{
"code": null,
"e": 4654,
"s": 4583,
"text": "Note: View Holder Class is also implemented in Adapter Class itself. "
},
{
"code": null,
"e": 4706,
"s": 4656,
"text": "These methods to handle Recycler View includes: "
},
{
"code": null,
"e": 4786,
"s": 4708,
"text": "onCreateViewHolder: This method inflates card layout items for Recycler View."
},
{
"code": null,
"e": 4932,
"s": 4786,
"text": "onBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view."
},
{
"code": null,
"e": 4998,
"s": 4932,
"text": "getItemCount: This method returns the length of the RecyclerView."
},
{
"code": null,
"e": 5131,
"s": 5000,
"text": "Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 5138,
"s": 5133,
"text": "Java"
},
{
"code": "import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> { // creating a variable for our array list and context. private ArrayList<RecyclerData> courseDataArrayList; private Context mcontext; // creating a constructor class. public RecyclerViewAdapter(ArrayList<RecyclerData> recyclerDataArrayList, Context mcontext) { this.courseDataArrayList = recyclerDataArrayList; this.mcontext = mcontext; } @NonNull @Override public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) { // Inflate Layout View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false); return new RecyclerViewHolder(view); } @Override public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) { // Set the data to textview from our modal class. RecyclerData recyclerData = courseDataArrayList.get(position); holder.courseNameTV.setText(recyclerData.getTitle()); holder.courseDescTV.setText(recyclerData.getDescription()); } @Override public int getItemCount() { // this method returns // the size of recyclerview return courseDataArrayList.size(); } // View Holder Class to handle Recycler View. public class RecyclerViewHolder extends RecyclerView.ViewHolder { // creating a variable for our text view. private TextView courseNameTV; private TextView courseDescTV; public RecyclerViewHolder(@NonNull View itemView) { super(itemView); // initializing our text views. courseNameTV = itemView.findViewById(R.id.idTVCourseName); courseDescTV = itemView.findViewById(R.id.idTVCourseDesc); } }}",
"e": 7232,
"s": 5138,
"text": null
},
{
"code": null,
"e": 7284,
"s": 7236,
"text": "Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 7429,
"s": 7286,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. "
},
{
"code": null,
"e": 7435,
"s": 7431,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" android:layout_gravity=\"center\" android:gravity=\"center\" android:orientation=\"vertical\" tools:context=\".MainActivity\"> <!--creating a recycler view for displaying our list of courses--> <androidx.recyclerview.widget.RecyclerView android:id=\"@+id/idRVCourse\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" /> </RelativeLayout>",
"e": 8083,
"s": 7435,
"text": null
},
{
"code": null,
"e": 8135,
"s": 8087,
"text": "Step 6: Working with the MainActivity.java file"
},
{
"code": null,
"e": 8327,
"s": 8137,
"text": "Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 8334,
"s": 8329,
"text": "Java"
},
{
"code": "import android.os.Bundle;import android.view.View; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.ItemTouchHelper;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.snackbar.Snackbar; import java.util.ArrayList; public class MainActivity extends AppCompatActivity { // creating a variable for recycler view, // array list and adapter class. private RecyclerView courseRV; private ArrayList<RecyclerData> recyclerDataArrayList; private RecyclerViewAdapter recyclerViewAdapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // initializing our variables. courseRV = findViewById(R.id.idRVCourse); // creating new array list. recyclerDataArrayList = new ArrayList<>(); // in below line we are adding data to our array list. recyclerDataArrayList.add(new RecyclerData(\"DSA Course\", \"DSA Self Paced Course\")); recyclerDataArrayList.add(new RecyclerData(\"C++ Course\", \"C++ Self Paced Course\")); recyclerDataArrayList.add(new RecyclerData(\"Java Course\", \"Java Self Paced Course\")); recyclerDataArrayList.add(new RecyclerData(\"Python Course\", \"Python Self Paced Course\")); recyclerDataArrayList.add(new RecyclerData(\"Fork CPP\", \"Fork CPP Self Paced Course\")); recyclerDataArrayList.add(new RecyclerData(\"Amazon SDE\", \"Amazon SDE Test Questions\")); // initializing our adapter class with our array list and context. recyclerViewAdapter = new RecyclerViewAdapter(recyclerDataArrayList, this); // below line is to set layout manager for our recycler view. LinearLayoutManager manager = new LinearLayoutManager(this); // setting layout manager for our recycler view. courseRV.setLayoutManager(manager); // below line is to set adapter // to our recycler view. courseRV.setAdapter(recyclerViewAdapter); // on below line we are creating a method to create item touch helper // method for adding swipe to delete functionality. // in this we are specifying drag direction and position to right new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) { @Override public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) { // this method is called // when the item is moved. return false; } @Override public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) { // this method is called when we swipe our item to right direction. // on below line we are getting the item at a particular position. RecyclerData deletedCourse = recyclerDataArrayList.get(viewHolder.getAdapterPosition()); // below line is to get the position // of the item at that position. int position = viewHolder.getAdapterPosition(); // this method is called when item is swiped. // below line is to remove item from our array list. recyclerDataArrayList.remove(viewHolder.getAdapterPosition()); // below line is to notify our item is removed from adapter. recyclerViewAdapter.notifyItemRemoved(viewHolder.getAdapterPosition()); // below line is to display our snackbar with action. Snackbar.make(courseRV, deletedCourse.getTitle(), Snackbar.LENGTH_LONG).setAction(\"Undo\", new View.OnClickListener() { @Override public void onClick(View v) { // adding on click listener to our action of snack bar. // below line is to add our item to array list with a position. recyclerDataArrayList.add(position, deletedCourse); // below line is to notify item is // added to our adapter class. recyclerViewAdapter.notifyItemInserted(position); } }).show(); } // at last we are adding this // to our recycler view. }).attachToRecyclerView(courseRV); }}",
"e": 13034,
"s": 8334,
"text": null
},
{
"code": null,
"e": 13087,
"s": 13038,
"text": "Now run your app and see the output of the app. "
},
{
"code": null,
"e": 13106,
"s": 13091,
"text": "varshagumber28"
},
{
"code": null,
"e": 13114,
"s": 13106,
"text": "android"
},
{
"code": null,
"e": 13121,
"s": 13114,
"text": "Picked"
},
{
"code": null,
"e": 13145,
"s": 13121,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 13153,
"s": 13145,
"text": "Android"
},
{
"code": null,
"e": 13158,
"s": 13153,
"text": "Java"
},
{
"code": null,
"e": 13177,
"s": 13158,
"text": "Technical Scripter"
},
{
"code": null,
"e": 13182,
"s": 13177,
"text": "Java"
},
{
"code": null,
"e": 13190,
"s": 13182,
"text": "Android"
}
] |
rand vs normal in Numpy.random in Python | 17 Nov, 2020
In this article, we will look into the principal difference between the Numpy.random.rand() method and the Numpy.random.normal() method in detail.
About random: For random we are taking .rand()numpy.random.rand(d0, d1, ..., dn) :creates an array of specified shape andfills it with random values.Parameters :d0, d1, ..., dn : [int, optional]
Dimension of the returned array we require,
If no argument is given a single Python float
is returned.
Return :Array of defined shape, filled with random values.
d0, d1, ..., dn : [int, optional]
Dimension of the returned array we require,
If no argument is given a single Python float
is returned.
Return :
Array of defined shape, filled with random values.
About normal: For random we are taking .normal()numpy.random.normal(loc = 0.0, scale = 1.0, size = None) : creates an array of specified shape and fills it with random values which is actually a part of Normal(Gaussian)Distribution. This is Distribution is also known as Bell Curve because of its characteristics shape.Parameters :loc : [float or array_like]Mean of
the distribution.
scale : [float or array_like]Standard
Derivation of the distribution.
size : [int or int tuples].
Output shape given as (m, n, k) then
m*n*k samples are drawn. If size is
None(by default), then a single value
is returned.
Return :Array of defined shape, filled with
random values following normal
distribution.
loc : [float or array_like]Mean of
the distribution.
scale : [float or array_like]Standard
Derivation of the distribution.
size : [int or int tuples].
Output shape given as (m, n, k) then
m*n*k samples are drawn. If size is
None(by default), then a single value
is returned.
Return :
Array of defined shape, filled with
random values following normal
distribution.
Code 1 : Randomly constructing 1D array
# Python Program illustrating# numpy.random.rand() method import numpy as geek # 1D Arrayarray = geek.random.rand(5)print("1D Array filled with random values : \n", array)
Output :
1D Array filled with random values :
[ 0.84503968 0.61570994 0.7619945 0.34994803 0.40113761]
Code 2 : Randomly constructing 1D array following Gaussian Distribution
# Python Program illustrating# numpy.random.normal() method import numpy as geek # 1D Arrayarray = geek.random.normal(0.0, 1.0, 5)print("1D Array filled with random values " "as per gaussian distribution : \n", array)# 3D arrayarray = geek.random.normal(0.0, 1.0, (2, 1, 2))print("\n\n3D Array filled with random values " "as per gaussian distribution : \n", array)
Output :
1D Array filled with random values as per gaussian distribution :
[-0.99013172 -1.52521808 0.37955684 0.57859283 1.34336863]
3D Array filled with random values as per gaussian distribution :
[[[-0.0320374 2.14977849]]
[[ 0.3789585 0.17692125]]]
Code3 : Python Program illustrating graphical representation of random vs normal in NumPy
# Python Program illustrating# graphical representation of # numpy.random.normal() method# numpy.random.rand() method import numpy as geekimport matplotlib.pyplot as plot # 1D Array as per Gaussian Distributionmean = 0 std = 0.1array = geek.random.normal(0, 0.1, 1000)print("1D Array filled with random values " "as per gaussian distribution : \n", array); # Source Code : # https://docs.scipy.org/doc/numpy-1.13.0/reference/# generated/numpy-random-normal-1.pycount, bins, ignored = plot.hist(array, 30, normed=True)plot.plot(bins, 1/(std * geek.sqrt(2 * geek.pi)) * geek.exp( - (bins - mean)**2 / (2 * std**2) ), linewidth=2, color='r')plot.show() # 1D Array constructed Randomlyrandom_array = geek.random.rand(5)print("1D Array filled with random values : \n", random_array) plot.plot(random_array)plot.show()
Output :
1D Array filled with random values as per gaussian distribution :
[ 0.12413355 0.01868444 0.08841698 ..., -0.01523021 -0.14621625
-0.09157214]
1D Array filled with random values :
[ 0.72654409 0.26955422 0.19500427 0.37178803 0.10196284]
Important :In code 3, plot 1 clearly shows Gaussian Distribution as it is being created from the values generated through random.normal() method thus following Gaussian Distribution.plot 2 doesn’t follow any distribution as it is being created from random values generated by random.rand() method.
Note :Code 3 won’t run on online-ID. Please run them on your systems to explore the working..This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Python numpy-Random sampling
Python-numpy
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
Different ways to create Pandas Dataframe
Enumerate() in Python
Read a file line by line in Python
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": 28,
"s": 0,
"text": "\n17 Nov, 2020"
},
{
"code": null,
"e": 175,
"s": 28,
"text": "In this article, we will look into the principal difference between the Numpy.random.rand() method and the Numpy.random.normal() method in detail."
},
{
"code": null,
"e": 536,
"s": 175,
"text": "About random: For random we are taking .rand()numpy.random.rand(d0, d1, ..., dn) :creates an array of specified shape andfills it with random values.Parameters :d0, d1, ..., dn : [int, optional]\nDimension of the returned array we require, \n\nIf no argument is given a single Python float \nis returned.\nReturn :Array of defined shape, filled with random values.\n"
},
{
"code": null,
"e": 677,
"s": 536,
"text": "d0, d1, ..., dn : [int, optional]\nDimension of the returned array we require, \n\nIf no argument is given a single Python float \nis returned.\n"
},
{
"code": null,
"e": 686,
"s": 677,
"text": "Return :"
},
{
"code": null,
"e": 738,
"s": 686,
"text": "Array of defined shape, filled with random values.\n"
},
{
"code": null,
"e": 1446,
"s": 738,
"text": "About normal: For random we are taking .normal()numpy.random.normal(loc = 0.0, scale = 1.0, size = None) : creates an array of specified shape and fills it with random values which is actually a part of Normal(Gaussian)Distribution. This is Distribution is also known as Bell Curve because of its characteristics shape.Parameters :loc : [float or array_like]Mean of \nthe distribution. \nscale : [float or array_like]Standard \nDerivation of the distribution. \nsize : [int or int tuples]. \nOutput shape given as (m, n, k) then\nm*n*k samples are drawn. If size is \nNone(by default), then a single value\nis returned. \nReturn :Array of defined shape, filled with \nrandom values following normal \ndistribution.\n"
},
{
"code": null,
"e": 1732,
"s": 1446,
"text": "loc : [float or array_like]Mean of \nthe distribution. \nscale : [float or array_like]Standard \nDerivation of the distribution. \nsize : [int or int tuples]. \nOutput shape given as (m, n, k) then\nm*n*k samples are drawn. If size is \nNone(by default), then a single value\nis returned. \n"
},
{
"code": null,
"e": 1741,
"s": 1732,
"text": "Return :"
},
{
"code": null,
"e": 1825,
"s": 1741,
"text": "Array of defined shape, filled with \nrandom values following normal \ndistribution.\n"
},
{
"code": null,
"e": 1865,
"s": 1825,
"text": "Code 1 : Randomly constructing 1D array"
},
{
"code": "# Python Program illustrating# numpy.random.rand() method import numpy as geek # 1D Arrayarray = geek.random.rand(5)print(\"1D Array filled with random values : \\n\", array)",
"e": 2041,
"s": 1865,
"text": null
},
{
"code": null,
"e": 2050,
"s": 2041,
"text": "Output :"
},
{
"code": null,
"e": 2153,
"s": 2050,
"text": "1D Array filled with random values : \n [ 0.84503968 0.61570994 0.7619945 0.34994803 0.40113761]\n\n"
},
{
"code": null,
"e": 2225,
"s": 2153,
"text": "Code 2 : Randomly constructing 1D array following Gaussian Distribution"
},
{
"code": "# Python Program illustrating# numpy.random.normal() method import numpy as geek # 1D Arrayarray = geek.random.normal(0.0, 1.0, 5)print(\"1D Array filled with random values \" \"as per gaussian distribution : \\n\", array)# 3D arrayarray = geek.random.normal(0.0, 1.0, (2, 1, 2))print(\"\\n\\n3D Array filled with random values \" \"as per gaussian distribution : \\n\", array)",
"e": 2605,
"s": 2225,
"text": null
},
{
"code": null,
"e": 2614,
"s": 2605,
"text": "Output :"
},
{
"code": null,
"e": 2874,
"s": 2614,
"text": "1D Array filled with random values as per gaussian distribution : \n [-0.99013172 -1.52521808 0.37955684 0.57859283 1.34336863]\n\n3D Array filled with random values as per gaussian distribution : \n [[[-0.0320374 2.14977849]]\n\n [[ 0.3789585 0.17692125]]]\n"
},
{
"code": null,
"e": 2964,
"s": 2874,
"text": "Code3 : Python Program illustrating graphical representation of random vs normal in NumPy"
},
{
"code": "# Python Program illustrating# graphical representation of # numpy.random.normal() method# numpy.random.rand() method import numpy as geekimport matplotlib.pyplot as plot # 1D Array as per Gaussian Distributionmean = 0 std = 0.1array = geek.random.normal(0, 0.1, 1000)print(\"1D Array filled with random values \" \"as per gaussian distribution : \\n\", array); # Source Code : # https://docs.scipy.org/doc/numpy-1.13.0/reference/# generated/numpy-random-normal-1.pycount, bins, ignored = plot.hist(array, 30, normed=True)plot.plot(bins, 1/(std * geek.sqrt(2 * geek.pi)) * geek.exp( - (bins - mean)**2 / (2 * std**2) ), linewidth=2, color='r')plot.show() # 1D Array constructed Randomlyrandom_array = geek.random.rand(5)print(\"1D Array filled with random values : \\n\", random_array) plot.plot(random_array)plot.show()",
"e": 3809,
"s": 2964,
"text": null
},
{
"code": null,
"e": 3818,
"s": 3809,
"text": "Output :"
},
{
"code": null,
"e": 4073,
"s": 3818,
"text": "1D Array filled with random values as per gaussian distribution : \n [ 0.12413355 0.01868444 0.08841698 ..., -0.01523021 -0.14621625\n -0.09157214]\n\n\n\n1D Array filled with random values : \n [ 0.72654409 0.26955422 0.19500427 0.37178803 0.10196284]\n\n\n"
},
{
"code": null,
"e": 4371,
"s": 4073,
"text": "Important :In code 3, plot 1 clearly shows Gaussian Distribution as it is being created from the values generated through random.normal() method thus following Gaussian Distribution.plot 2 doesn’t follow any distribution as it is being created from random values generated by random.rand() method."
},
{
"code": null,
"e": 4768,
"s": 4371,
"text": "Note :Code 3 won’t run on online-ID. Please run them on your systems to explore the working..This article is contributed by Mohit Gupta_OMG . If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to [email protected]. See your article appearing on the GeeksforGeeks main page and help other Geeks."
},
{
"code": null,
"e": 4893,
"s": 4768,
"text": "Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above."
},
{
"code": null,
"e": 4922,
"s": 4893,
"text": "Python numpy-Random sampling"
},
{
"code": null,
"e": 4935,
"s": 4922,
"text": "Python-numpy"
},
{
"code": null,
"e": 4942,
"s": 4935,
"text": "Python"
},
{
"code": null,
"e": 5040,
"s": 4942,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5058,
"s": 5040,
"text": "Python Dictionary"
},
{
"code": null,
"e": 5100,
"s": 5058,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 5122,
"s": 5100,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 5157,
"s": 5122,
"text": "Read a file line by line in Python"
},
{
"code": null,
"e": 5183,
"s": 5157,
"text": "Python String | replace()"
},
{
"code": null,
"e": 5215,
"s": 5183,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 5244,
"s": 5215,
"text": "*args and **kwargs in Python"
},
{
"code": null,
"e": 5271,
"s": 5244,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 5301,
"s": 5271,
"text": "Iterate over a list in Python"
}
] |
What is the syntax for input parameters (variables) in a MySQL query? | To set a variable in MySQL, you need to use the SET command. Following is the syntax:
set @yourVariableName:=yourValue;
select *from yourTableName where yourColumnName=@yourVariableName;
Let us first create a table:
mysql> create table DemoTable
(
Id int,
FirstName varchar(20),
LastName varchar(20)
);
Query OK, 0 rows affected (0.83 sec)
Following is the query to insert some records in the table using insert command:
mysql> insert into DemoTable values(10,'Carol','Taylor');
Query OK, 1 row affected (0.18 sec)
mysql> insert into DemoTable values(20,'John','Doe');
Query OK, 1 row affected (0.19 sec)
mysql> insert into DemoTable values(30,'John','Smith');
Query OK, 1 row affected (0.11 sec)
mysql> insert into DemoTable values(40,'David','Miller');
Query OK, 1 row affected (0.18 sec)
Following is the query to display records from the table using select command:
mysql> select *from DemoTable;
This will produce the following output:
+------+-----------+----------+
| Id | FirstName | LastName |
+------+-----------+----------+
| 10 | Carol | Taylor |
| 20 | John | Doe |
| 30 | John | Smith |
| 40 | David | Miller |
+------+-----------+----------+
4 rows in set (0.00 sec)
Let us now see how to set user defined variables in MySQL:
mysql> set @myId:=30;
Query OK, 0 rows affected (0.00 sec)
mysql> select *from DemoTable where Id=@myId;
This will produce the following output
+------+-----------+----------+
| Id | FirstName | LastName |
+------+-----------+----------+
| 30 | John | Smith |
+------+-----------+----------+
1 row in set (0.00 sec) | [
{
"code": null,
"e": 1148,
"s": 1062,
"text": "To set a variable in MySQL, you need to use the SET command. Following is the syntax:"
},
{
"code": null,
"e": 1249,
"s": 1148,
"text": "set @yourVariableName:=yourValue;\nselect *from yourTableName where yourColumnName=@yourVariableName;"
},
{
"code": null,
"e": 1278,
"s": 1249,
"text": "Let us first create a table:"
},
{
"code": null,
"e": 1411,
"s": 1278,
"text": "mysql> create table DemoTable\n(\n Id int,\n FirstName varchar(20),\n LastName varchar(20)\n);\nQuery OK, 0 rows affected (0.83 sec)"
},
{
"code": null,
"e": 1492,
"s": 1411,
"text": "Following is the query to insert some records in the table using insert command:"
},
{
"code": null,
"e": 1862,
"s": 1492,
"text": "mysql> insert into DemoTable values(10,'Carol','Taylor');\nQuery OK, 1 row affected (0.18 sec)\nmysql> insert into DemoTable values(20,'John','Doe');\nQuery OK, 1 row affected (0.19 sec)\nmysql> insert into DemoTable values(30,'John','Smith');\nQuery OK, 1 row affected (0.11 sec)\nmysql> insert into DemoTable values(40,'David','Miller');\nQuery OK, 1 row affected (0.18 sec)"
},
{
"code": null,
"e": 1941,
"s": 1862,
"text": "Following is the query to display records from the table using select command:"
},
{
"code": null,
"e": 1972,
"s": 1941,
"text": "mysql> select *from DemoTable;"
},
{
"code": null,
"e": 2012,
"s": 1972,
"text": "This will produce the following output:"
},
{
"code": null,
"e": 2293,
"s": 2012,
"text": "+------+-----------+----------+\n| Id | FirstName | LastName |\n+------+-----------+----------+\n| 10 | Carol | Taylor |\n| 20 | John | Doe |\n| 30 | John | Smith |\n| 40 | David | Miller |\n+------+-----------+----------+\n4 rows in set (0.00 sec)"
},
{
"code": null,
"e": 2352,
"s": 2293,
"text": "Let us now see how to set user defined variables in MySQL:"
},
{
"code": null,
"e": 2457,
"s": 2352,
"text": "mysql> set @myId:=30;\nQuery OK, 0 rows affected (0.00 sec)\nmysql> select *from DemoTable where Id=@myId;"
},
{
"code": null,
"e": 2496,
"s": 2457,
"text": "This will produce the following output"
},
{
"code": null,
"e": 2680,
"s": 2496,
"text": "+------+-----------+----------+\n| Id | FirstName | LastName |\n+------+-----------+----------+\n| 30 | John | Smith |\n+------+-----------+----------+\n1 row in set (0.00 sec)"
}
] |
PySpark and SparkSQL Basics. How to implement Spark with Python... | by Pınar Ersoy | Towards Data Science | Python is revealed the Spark programming model to work with structured data by the Spark Python API which is called as PySpark.
This post’s objective is to demonstrate how to run Spark with PySpark and execute common functions.
Python programming language requires an installed IDE. The easiest way to use Python with Anaconda since it installs sufficient IDE’s and crucial packages along with itself.
With the help of this link, you can download Anaconda. After the suitable Anaconda version is downloaded, click on it to proceed with the installation procedure which is explained step by step in the Anaconda Documentation.
When the installation is completed, the Anaconda Navigator Homepage will be opened. In order to use Python, simply click on the “Launch” button of the “Notebook” module.
To be able to use Spark through Anaconda, the following package installation steps shall be followed.
Anaconda Prompt terminal
conda install pyspark
conda install pyarrow
After PySpark and PyArrow package installations are completed, simply close the terminal and go back to Jupyter Notebook and import the required packages at the top of your code.
import pandas as pdfrom pyspark.sql import SparkSessionfrom pyspark.context import SparkContextfrom pyspark.sql.functions import *from pyspark.sql.types import *from datetime import date, timedelta, datetimeimport time
First of all, a Spark session needs to be initialized. With the help of SparkSession, DataFrame can be created and registered as tables. Moreover, SQL tables are executed, tables can be cached, and parquet/JSON/CSV/Avro data formatted files can be read.
sc = SparkSession.builder.appName("PysparkExample")\ .config ("spark.sql.shuffle.partitions", "50")\ .config("spark.driver.maxResultSize","5g")\ .config ("spark.sql.execution.arrow.enabled", "true")\ .getOrCreate()
For detailed explanations for each parameter of SparkSession, kindly visit pyspark.sql.SparkSession.
A DataFrame can be accepted as a distributed and tabulated collection of titled columns which is similar to a table in a relational database. In this post, we will be using DataFrame operations on PySpark API while working with datasets.
You can download the Kaggle dataset from this link.
3.1. From Spark Data Sources
DataFrames can be created by reading text, CSV, JSON, and Parquet file formats. In our example, we will be using a .json formatted file. You can also find and read text, CSV, and Parquet file formats by using the related read functions as shown below.
#Creates a spark data frame called as raw_data.#JSONdataframe = sc.read.json('dataset/nyt2.json')#TXT FILES# dataframe_txt = sc.read.text('text_data.txt')#CSV FILES# dataframe_csv = sc.read.csv('csv_data.csv')#PARQUET FILES# dataframe_parquet = sc.read.load('parquet_data.parquet')
Duplicate values in a table can be eliminated by using dropDuplicates() function.
dataframe = sc.read.json('dataset/nyt2.json') dataframe.show(10)
After dropDuplicates() function is applied, we can observe that duplicates are removed from the dataset.
dataframe_dropdup = dataframe.dropDuplicates() dataframe_dropdup.show(10)
Querying operations can be used for various purposes such as subsetting columns with “select”, adding conditions with “when” and filtering column contents with “like”. Below, some of the most commonly used operations are exemplified. For the complete list of query operations, see the Apache Spark doc.
5.1. “Select” Operation
It is possible to obtain columns by attribute (“author”) or by indexing (dataframe[‘author’]).
#Show all entries in title columndataframe.select("author").show(10)#Show all entries in title, author, rank, price columnsdataframe.select("author", "title", "rank", "price").show(10)
5.2. “When” Operation
In the first example, the “title” column is selected and a condition is added with a “when” condition.
# Show title and assign 0 or 1 depending on titledataframe.select("title",when(dataframe.title != 'ODD HOURS', 1).otherwise(0)).show(10)
In the second example, the “isin” operation is applied instead of “when” which can be also used to define some conditions to rows.
# Show rows with specified authors if in the given optionsdataframe [dataframe.author.isin("John Sandford", "Emily Giffin")].show(5)
5.3. “Like” Operation
In the brackets of the “Like” function, the % character is used to filter out all titles having the “ THE ” word. If the condition we are looking for is the exact match, then no % character shall be used.
# Show author and title is TRUE if title has " THE " word in titlesdataframe.select("author", "title",dataframe.title.like("% THE %")).show(15)
5.4. “Startswith” — “ Endswith”
StartsWith scans from the beginning of word/content with specified criteria in the brackets. In parallel, EndsWith processes the word/content starting from the end. Both of the functions are case-sensitive.
dataframe.select("author", "title", dataframe.title.startswith("THE")).show(5)dataframe.select("author", "title", dataframe.title.endswith("NT")).show(5)
5.5. “Substring” Operation
Substring functions to extract the text between specified indexes. In the following examples, texts are extracted from the index numbers (1, 3), (3, 6), and (1, 6).
dataframe.select(dataframe.author.substr(1, 3).alias("title")).show(5)dataframe.select(dataframe.author.substr(3, 6).alias("title")).show(5)dataframe.select(dataframe.author.substr(1, 6).alias("title")).show(5)
Data manipulation functions are also available in the DataFrame API. Below, you can find examples to add/update/remove column operations.
6.1. Adding Columns
# Lit() is required while we are creating columns with exact values.dataframe = dataframe.withColumn('new_column', F.lit('This is a new column'))display(dataframe)
6.2. Updating Columns
For updated operations of DataFrame API, withColumnRenamed() function is used with two parameters.
# Update column 'amazon_product_url' with 'URL'dataframe = dataframe.withColumnRenamed('amazon_product_url', 'URL')dataframe.show(5)
6.3. Removing Columns
Removal of a column can be achieved in two ways: adding the list of column names in the drop() function or specifying columns by pointing in the drop function. Both examples are shown below.
dataframe_remove = dataframe.drop("publisher", "published_date").show(5)dataframe_remove2 = dataframe \ .drop(dataframe.publisher).drop(dataframe.published_date).show(5)
There exist several types of functions to inspect data. Below, you can find some of the commonly used ones. For a deeper look, visit the Apache Spark doc.
# Returns dataframe column names and data typesdataframe.dtypes# Displays the content of dataframedataframe.show()# Return first n rowsdataframe.head()# Returns first rowdataframe.first()# Return first n rowsdataframe.take(5)# Computes summary statisticsdataframe.describe().show()# Returns columns of dataframedataframe.columns# Counts the number of rows in dataframedataframe.count()# Counts the number of distinct rows in dataframedataframe.distinct().count()# Prints plans including physical and logicaldataframe.explain(4)
The grouping process is applied with GroupBy() function by adding column name in function.
# Group by author, count the books of the authors in the groupsdataframe.groupBy("author").count().show(10)
Filtering is applied by using the filter() function with a condition parameter added inside of it. This function is case-sensitive.
# Filtering entries of title# Only keeps records having value 'THE HOST'dataframe.filter(dataframe["title"] == 'THE HOST').show(5)
For every dataset, there is always a need for replacing, existing values, dropping unnecessary columns, and filling missing values in data preprocessing stages. pyspark.sql.DataFrameNaFunction library helps us to manipulate data in this respect. Some examples are added below.
# Replacing null valuesdataframe.na.fill()dataFrame.fillna()dataFrameNaFunctions.fill()# Returning new dataframe restricting rows with null valuesdataframe.na.drop()dataFrame.dropna()dataFrameNaFunctions.drop()# Return new dataframe replacing one value with anotherdataframe.na.replace(5, 15)dataFrame.replace()dataFrameNaFunctions.replace()
It is possible to increase or decrease the existing level of partitioning in RDD Increasing can be actualized by using the repartition(self, numPartitions) function which results in a new RDD that obtains the higher number of partitions. Decreasing can be processed with coalesce(self, numPartitions, shuffle=False) function that results in a new RDD with a reduced number of partitions to a specified number. For more info, please visit the Apache Spark docs.
# Dataframe with 10 partitionsdataframe.repartition(10).rdd.getNumPartitions()# Dataframe with 1 partitiondataframe.coalesce(1).rdd.getNumPartitions()
Raw SQL queries can also be used by enabling the “sql” operation on our SparkSession to run SQL queries programmatically and return the result sets as DataFrame structures. For more detailed information, kindly visit Apache Spark docs.
# Registering a tabledataframe.registerTempTable("df")sc.sql("select * from df").show(3)sc.sql("select \ CASE WHEN description LIKE '%love%' THEN 'Love_Theme' \ WHEN description LIKE '%hate%' THEN 'Hate_Theme' \ WHEN description LIKE '%happy%' THEN 'Happiness_Theme' \ WHEN description LIKE '%anger%' THEN 'Anger_Theme' \ WHEN description LIKE '%horror%' THEN 'Horror_Theme' \ WHEN description LIKE '%death%' THEN 'Criminal_Theme' \ WHEN description LIKE '%detective%' THEN 'Mystery_Theme' \ ELSE 'Other_Themes' \ END Themes \ from df").groupBy('Themes').count().show()
13.1. Data Structures
DataFrame API uses RDD as a base and it converts SQL queries into low-level RDD functions. By using the .rdd operation, a dataframe can be converted into RDD. It is also possible to convert Spark Dataframe into a string of RDD and Pandas formats.
# Converting dataframe into an RDDrdd_convert = dataframe.rdd# Converting dataframe into a RDD of string dataframe.toJSON().first()# Obtaining contents of df as Pandas dataFramedataframe.toPandas()
13.2. Write & Save to Files
Any data source type that is loaded to our code as data frames can easily be converted and saved into other types including .parquet and .json. For more save, load, write function details, please visit Apache Spark doc.
# Write & Save File in .parquet formatdataframe.select("author", "title", "rank", "description") \.write \.save("Rankings_Descriptions.parquet")
# Write & Save File in .json formatdataframe.select("author", "title") \.write \.save("Authors_Titles.json",format="json")
13.3. Stopping SparkSession
Spark Session can be stopped by running the stop() function as follows.
# End Spark Sessionsc.stop()
The code and Jupyter Notebook are available on my GitHub.
Questions and comments are highly appreciated! | [
{
"code": null,
"e": 300,
"s": 172,
"text": "Python is revealed the Spark programming model to work with structured data by the Spark Python API which is called as PySpark."
},
{
"code": null,
"e": 400,
"s": 300,
"text": "This post’s objective is to demonstrate how to run Spark with PySpark and execute common functions."
},
{
"code": null,
"e": 574,
"s": 400,
"text": "Python programming language requires an installed IDE. The easiest way to use Python with Anaconda since it installs sufficient IDE’s and crucial packages along with itself."
},
{
"code": null,
"e": 798,
"s": 574,
"text": "With the help of this link, you can download Anaconda. After the suitable Anaconda version is downloaded, click on it to proceed with the installation procedure which is explained step by step in the Anaconda Documentation."
},
{
"code": null,
"e": 968,
"s": 798,
"text": "When the installation is completed, the Anaconda Navigator Homepage will be opened. In order to use Python, simply click on the “Launch” button of the “Notebook” module."
},
{
"code": null,
"e": 1070,
"s": 968,
"text": "To be able to use Spark through Anaconda, the following package installation steps shall be followed."
},
{
"code": null,
"e": 1095,
"s": 1070,
"text": "Anaconda Prompt terminal"
},
{
"code": null,
"e": 1117,
"s": 1095,
"text": "conda install pyspark"
},
{
"code": null,
"e": 1139,
"s": 1117,
"text": "conda install pyarrow"
},
{
"code": null,
"e": 1318,
"s": 1139,
"text": "After PySpark and PyArrow package installations are completed, simply close the terminal and go back to Jupyter Notebook and import the required packages at the top of your code."
},
{
"code": null,
"e": 1537,
"s": 1318,
"text": "import pandas as pdfrom pyspark.sql import SparkSessionfrom pyspark.context import SparkContextfrom pyspark.sql.functions import *from pyspark.sql.types import *from datetime import date, timedelta, datetimeimport time"
},
{
"code": null,
"e": 1791,
"s": 1537,
"text": "First of all, a Spark session needs to be initialized. With the help of SparkSession, DataFrame can be created and registered as tables. Moreover, SQL tables are executed, tables can be cached, and parquet/JSON/CSV/Avro data formatted files can be read."
},
{
"code": null,
"e": 2018,
"s": 1791,
"text": "sc = SparkSession.builder.appName(\"PysparkExample\")\\ .config (\"spark.sql.shuffle.partitions\", \"50\")\\ .config(\"spark.driver.maxResultSize\",\"5g\")\\ .config (\"spark.sql.execution.arrow.enabled\", \"true\")\\ .getOrCreate()"
},
{
"code": null,
"e": 2119,
"s": 2018,
"text": "For detailed explanations for each parameter of SparkSession, kindly visit pyspark.sql.SparkSession."
},
{
"code": null,
"e": 2357,
"s": 2119,
"text": "A DataFrame can be accepted as a distributed and tabulated collection of titled columns which is similar to a table in a relational database. In this post, we will be using DataFrame operations on PySpark API while working with datasets."
},
{
"code": null,
"e": 2409,
"s": 2357,
"text": "You can download the Kaggle dataset from this link."
},
{
"code": null,
"e": 2438,
"s": 2409,
"text": "3.1. From Spark Data Sources"
},
{
"code": null,
"e": 2690,
"s": 2438,
"text": "DataFrames can be created by reading text, CSV, JSON, and Parquet file formats. In our example, we will be using a .json formatted file. You can also find and read text, CSV, and Parquet file formats by using the related read functions as shown below."
},
{
"code": null,
"e": 2972,
"s": 2690,
"text": "#Creates a spark data frame called as raw_data.#JSONdataframe = sc.read.json('dataset/nyt2.json')#TXT FILES# dataframe_txt = sc.read.text('text_data.txt')#CSV FILES# dataframe_csv = sc.read.csv('csv_data.csv')#PARQUET FILES# dataframe_parquet = sc.read.load('parquet_data.parquet')"
},
{
"code": null,
"e": 3054,
"s": 2972,
"text": "Duplicate values in a table can be eliminated by using dropDuplicates() function."
},
{
"code": null,
"e": 3119,
"s": 3054,
"text": "dataframe = sc.read.json('dataset/nyt2.json') dataframe.show(10)"
},
{
"code": null,
"e": 3224,
"s": 3119,
"text": "After dropDuplicates() function is applied, we can observe that duplicates are removed from the dataset."
},
{
"code": null,
"e": 3298,
"s": 3224,
"text": "dataframe_dropdup = dataframe.dropDuplicates() dataframe_dropdup.show(10)"
},
{
"code": null,
"e": 3601,
"s": 3298,
"text": "Querying operations can be used for various purposes such as subsetting columns with “select”, adding conditions with “when” and filtering column contents with “like”. Below, some of the most commonly used operations are exemplified. For the complete list of query operations, see the Apache Spark doc."
},
{
"code": null,
"e": 3625,
"s": 3601,
"text": "5.1. “Select” Operation"
},
{
"code": null,
"e": 3720,
"s": 3625,
"text": "It is possible to obtain columns by attribute (“author”) or by indexing (dataframe[‘author’])."
},
{
"code": null,
"e": 3905,
"s": 3720,
"text": "#Show all entries in title columndataframe.select(\"author\").show(10)#Show all entries in title, author, rank, price columnsdataframe.select(\"author\", \"title\", \"rank\", \"price\").show(10)"
},
{
"code": null,
"e": 3927,
"s": 3905,
"text": "5.2. “When” Operation"
},
{
"code": null,
"e": 4030,
"s": 3927,
"text": "In the first example, the “title” column is selected and a condition is added with a “when” condition."
},
{
"code": null,
"e": 4167,
"s": 4030,
"text": "# Show title and assign 0 or 1 depending on titledataframe.select(\"title\",when(dataframe.title != 'ODD HOURS', 1).otherwise(0)).show(10)"
},
{
"code": null,
"e": 4298,
"s": 4167,
"text": "In the second example, the “isin” operation is applied instead of “when” which can be also used to define some conditions to rows."
},
{
"code": null,
"e": 4431,
"s": 4298,
"text": "# Show rows with specified authors if in the given optionsdataframe [dataframe.author.isin(\"John Sandford\", \"Emily Giffin\")].show(5)"
},
{
"code": null,
"e": 4453,
"s": 4431,
"text": "5.3. “Like” Operation"
},
{
"code": null,
"e": 4658,
"s": 4453,
"text": "In the brackets of the “Like” function, the % character is used to filter out all titles having the “ THE ” word. If the condition we are looking for is the exact match, then no % character shall be used."
},
{
"code": null,
"e": 4802,
"s": 4658,
"text": "# Show author and title is TRUE if title has \" THE \" word in titlesdataframe.select(\"author\", \"title\",dataframe.title.like(\"% THE %\")).show(15)"
},
{
"code": null,
"e": 4834,
"s": 4802,
"text": "5.4. “Startswith” — “ Endswith”"
},
{
"code": null,
"e": 5041,
"s": 4834,
"text": "StartsWith scans from the beginning of word/content with specified criteria in the brackets. In parallel, EndsWith processes the word/content starting from the end. Both of the functions are case-sensitive."
},
{
"code": null,
"e": 5195,
"s": 5041,
"text": "dataframe.select(\"author\", \"title\", dataframe.title.startswith(\"THE\")).show(5)dataframe.select(\"author\", \"title\", dataframe.title.endswith(\"NT\")).show(5)"
},
{
"code": null,
"e": 5222,
"s": 5195,
"text": "5.5. “Substring” Operation"
},
{
"code": null,
"e": 5387,
"s": 5222,
"text": "Substring functions to extract the text between specified indexes. In the following examples, texts are extracted from the index numbers (1, 3), (3, 6), and (1, 6)."
},
{
"code": null,
"e": 5598,
"s": 5387,
"text": "dataframe.select(dataframe.author.substr(1, 3).alias(\"title\")).show(5)dataframe.select(dataframe.author.substr(3, 6).alias(\"title\")).show(5)dataframe.select(dataframe.author.substr(1, 6).alias(\"title\")).show(5)"
},
{
"code": null,
"e": 5736,
"s": 5598,
"text": "Data manipulation functions are also available in the DataFrame API. Below, you can find examples to add/update/remove column operations."
},
{
"code": null,
"e": 5756,
"s": 5736,
"text": "6.1. Adding Columns"
},
{
"code": null,
"e": 5920,
"s": 5756,
"text": "# Lit() is required while we are creating columns with exact values.dataframe = dataframe.withColumn('new_column', F.lit('This is a new column'))display(dataframe)"
},
{
"code": null,
"e": 5942,
"s": 5920,
"text": "6.2. Updating Columns"
},
{
"code": null,
"e": 6041,
"s": 5942,
"text": "For updated operations of DataFrame API, withColumnRenamed() function is used with two parameters."
},
{
"code": null,
"e": 6174,
"s": 6041,
"text": "# Update column 'amazon_product_url' with 'URL'dataframe = dataframe.withColumnRenamed('amazon_product_url', 'URL')dataframe.show(5)"
},
{
"code": null,
"e": 6196,
"s": 6174,
"text": "6.3. Removing Columns"
},
{
"code": null,
"e": 6387,
"s": 6196,
"text": "Removal of a column can be achieved in two ways: adding the list of column names in the drop() function or specifying columns by pointing in the drop function. Both examples are shown below."
},
{
"code": null,
"e": 6557,
"s": 6387,
"text": "dataframe_remove = dataframe.drop(\"publisher\", \"published_date\").show(5)dataframe_remove2 = dataframe \\ .drop(dataframe.publisher).drop(dataframe.published_date).show(5)"
},
{
"code": null,
"e": 6712,
"s": 6557,
"text": "There exist several types of functions to inspect data. Below, you can find some of the commonly used ones. For a deeper look, visit the Apache Spark doc."
},
{
"code": null,
"e": 7240,
"s": 6712,
"text": "# Returns dataframe column names and data typesdataframe.dtypes# Displays the content of dataframedataframe.show()# Return first n rowsdataframe.head()# Returns first rowdataframe.first()# Return first n rowsdataframe.take(5)# Computes summary statisticsdataframe.describe().show()# Returns columns of dataframedataframe.columns# Counts the number of rows in dataframedataframe.count()# Counts the number of distinct rows in dataframedataframe.distinct().count()# Prints plans including physical and logicaldataframe.explain(4)"
},
{
"code": null,
"e": 7331,
"s": 7240,
"text": "The grouping process is applied with GroupBy() function by adding column name in function."
},
{
"code": null,
"e": 7439,
"s": 7331,
"text": "# Group by author, count the books of the authors in the groupsdataframe.groupBy(\"author\").count().show(10)"
},
{
"code": null,
"e": 7571,
"s": 7439,
"text": "Filtering is applied by using the filter() function with a condition parameter added inside of it. This function is case-sensitive."
},
{
"code": null,
"e": 7702,
"s": 7571,
"text": "# Filtering entries of title# Only keeps records having value 'THE HOST'dataframe.filter(dataframe[\"title\"] == 'THE HOST').show(5)"
},
{
"code": null,
"e": 7979,
"s": 7702,
"text": "For every dataset, there is always a need for replacing, existing values, dropping unnecessary columns, and filling missing values in data preprocessing stages. pyspark.sql.DataFrameNaFunction library helps us to manipulate data in this respect. Some examples are added below."
},
{
"code": null,
"e": 8321,
"s": 7979,
"text": "# Replacing null valuesdataframe.na.fill()dataFrame.fillna()dataFrameNaFunctions.fill()# Returning new dataframe restricting rows with null valuesdataframe.na.drop()dataFrame.dropna()dataFrameNaFunctions.drop()# Return new dataframe replacing one value with anotherdataframe.na.replace(5, 15)dataFrame.replace()dataFrameNaFunctions.replace()"
},
{
"code": null,
"e": 8782,
"s": 8321,
"text": "It is possible to increase or decrease the existing level of partitioning in RDD Increasing can be actualized by using the repartition(self, numPartitions) function which results in a new RDD that obtains the higher number of partitions. Decreasing can be processed with coalesce(self, numPartitions, shuffle=False) function that results in a new RDD with a reduced number of partitions to a specified number. For more info, please visit the Apache Spark docs."
},
{
"code": null,
"e": 8933,
"s": 8782,
"text": "# Dataframe with 10 partitionsdataframe.repartition(10).rdd.getNumPartitions()# Dataframe with 1 partitiondataframe.coalesce(1).rdd.getNumPartitions()"
},
{
"code": null,
"e": 9169,
"s": 8933,
"text": "Raw SQL queries can also be used by enabling the “sql” operation on our SparkSession to run SQL queries programmatically and return the result sets as DataFrame structures. For more detailed information, kindly visit Apache Spark docs."
},
{
"code": null,
"e": 9871,
"s": 9169,
"text": "# Registering a tabledataframe.registerTempTable(\"df\")sc.sql(\"select * from df\").show(3)sc.sql(\"select \\ CASE WHEN description LIKE '%love%' THEN 'Love_Theme' \\ WHEN description LIKE '%hate%' THEN 'Hate_Theme' \\ WHEN description LIKE '%happy%' THEN 'Happiness_Theme' \\ WHEN description LIKE '%anger%' THEN 'Anger_Theme' \\ WHEN description LIKE '%horror%' THEN 'Horror_Theme' \\ WHEN description LIKE '%death%' THEN 'Criminal_Theme' \\ WHEN description LIKE '%detective%' THEN 'Mystery_Theme' \\ ELSE 'Other_Themes' \\ END Themes \\ from df\").groupBy('Themes').count().show()"
},
{
"code": null,
"e": 9893,
"s": 9871,
"text": "13.1. Data Structures"
},
{
"code": null,
"e": 10140,
"s": 9893,
"text": "DataFrame API uses RDD as a base and it converts SQL queries into low-level RDD functions. By using the .rdd operation, a dataframe can be converted into RDD. It is also possible to convert Spark Dataframe into a string of RDD and Pandas formats."
},
{
"code": null,
"e": 10338,
"s": 10140,
"text": "# Converting dataframe into an RDDrdd_convert = dataframe.rdd# Converting dataframe into a RDD of string dataframe.toJSON().first()# Obtaining contents of df as Pandas dataFramedataframe.toPandas()"
},
{
"code": null,
"e": 10366,
"s": 10338,
"text": "13.2. Write & Save to Files"
},
{
"code": null,
"e": 10586,
"s": 10366,
"text": "Any data source type that is loaded to our code as data frames can easily be converted and saved into other types including .parquet and .json. For more save, load, write function details, please visit Apache Spark doc."
},
{
"code": null,
"e": 10731,
"s": 10586,
"text": "# Write & Save File in .parquet formatdataframe.select(\"author\", \"title\", \"rank\", \"description\") \\.write \\.save(\"Rankings_Descriptions.parquet\")"
},
{
"code": null,
"e": 10854,
"s": 10731,
"text": "# Write & Save File in .json formatdataframe.select(\"author\", \"title\") \\.write \\.save(\"Authors_Titles.json\",format=\"json\")"
},
{
"code": null,
"e": 10882,
"s": 10854,
"text": "13.3. Stopping SparkSession"
},
{
"code": null,
"e": 10954,
"s": 10882,
"text": "Spark Session can be stopped by running the stop() function as follows."
},
{
"code": null,
"e": 10983,
"s": 10954,
"text": "# End Spark Sessionsc.stop()"
},
{
"code": null,
"e": 11041,
"s": 10983,
"text": "The code and Jupyter Notebook are available on my GitHub."
}
] |
What is getContext in HTML5 Canvas? | The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d.
Following is the code to get required context along with a check if your browser supports <canvas> element:
var canvas = document.getElementById("mycanvas");
if (canvas.getContext){
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
} | [
{
"code": null,
"e": 1240,
"s": 1062,
"text": "The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context 2d."
},
{
"code": null,
"e": 1348,
"s": 1240,
"text": "Following is the code to get required context along with a check if your browser supports <canvas> element:"
},
{
"code": null,
"e": 1535,
"s": 1348,
"text": "var canvas = document.getElementById(\"mycanvas\");\nif (canvas.getContext){\n var ctx = canvas.getContext('2d');\n\n // drawing code here\n } else {\n\n // canvas-unsupported code here\n}"
}
] |
C++ Program to Perform Fermat Primality Test | Fermat Primality test performs to check a given number is prime or not. Here is a C++ code of this algorithm.
Begin
modulo(base, e, mod)
a = 1
b = base
while (e > 0)
if (e mod 2 == 1)
a = (a * b) % mod
b = (b * b) % mod
e = e / 2
return a % mod
End
Begin
Fermat(ll m, int iterations)
if (m == 1)
return false
done
for (int i = 0; i < iterations; i++)
ll x = rand() mod (m - 1) + 1
if (modulo(x, m - 1, m) != 1)
return false
done
return true
End
#include <cstring>
#include <iostream>
#include <cstdlib>
#define ll long long
using namespace std;
ll modulo(ll base, ll e, ll mod) {
ll a = 1;
ll b = base;
while (e > 0) {
if (e % 2 == 1)
a = (a * b) % mod;
b = (b * b) % mod;
e = e / 2;
}
return a % mod;
}
bool Fermat(ll m, int iterations) {
if (m == 1) {
return false;
}
for (int i = 0; i < iterations; i++) {
ll x = rand() % (m - 1) + 1;
if (modulo(x, m - 1, m) != 1) {
return false;
}
}
return true;
}
int main() {
int iteration = 70;
ll num;
cout<<"Enter integer to test primality: ";
cin>>num;
if (Fermat(num, iteration))
cout<<num<<" is prime"<<endl;
else
cout<<num<<" is not prime"<<endl;
return 0;
}
Enter integer to test primality: 13 is prime | [
{
"code": null,
"e": 1172,
"s": 1062,
"text": "Fermat Primality test performs to check a given number is prime or not. Here is a C++ code of this algorithm."
},
{
"code": null,
"e": 1607,
"s": 1172,
"text": "Begin\n modulo(base, e, mod)\n a = 1\n b = base\n while (e > 0)\n if (e mod 2 == 1)\n a = (a * b) % mod\n b = (b * b) % mod\n e = e / 2\n return a % mod\nEnd\n\nBegin\n Fermat(ll m, int iterations)\n if (m == 1)\n return false\n done\n for (int i = 0; i < iterations; i++)\n ll x = rand() mod (m - 1) + 1\n if (modulo(x, m - 1, m) != 1)\n return false\n done\n return true\nEnd"
},
{
"code": null,
"e": 2397,
"s": 1607,
"text": "#include <cstring>\n#include <iostream>\n#include <cstdlib>\n#define ll long long\nusing namespace std;\nll modulo(ll base, ll e, ll mod) {\n ll a = 1;\n ll b = base;\n while (e > 0) {\n if (e % 2 == 1)\n a = (a * b) % mod;\n b = (b * b) % mod;\n e = e / 2;\n }\n return a % mod;\n}\nbool Fermat(ll m, int iterations) {\n if (m == 1) {\n return false;\n }\n for (int i = 0; i < iterations; i++) {\n ll x = rand() % (m - 1) + 1;\n if (modulo(x, m - 1, m) != 1) {\n return false;\n }\n }\n return true;\n}\nint main() {\n int iteration = 70;\n ll num;\n cout<<\"Enter integer to test primality: \";\n cin>>num;\n if (Fermat(num, iteration))\n cout<<num<<\" is prime\"<<endl;\n else\n cout<<num<<\" is not prime\"<<endl;\n return 0;\n}"
},
{
"code": null,
"e": 2442,
"s": 2397,
"text": "Enter integer to test primality: 13 is prime"
}
] |
C++ Program to Implement a Heuristic to Find the Vertex Cover of a Graph | Vertex Cover of a Graph is to find a set of vertices V, such that for every edge connecting M to N in graph, either M or N (or both) are present in V. In this program, we Implement a Heuristic to Find the Vertex Cover of a Graph.
Begin
1) Initialize a set S as empty.
2) Take an edge E of the connecting graph Say M and N.
3) Add both vertex to the set S.
4) Discard all edges in the graph with endpoints at M or N.
5) If some edge is still left in the graph Go to step 2,
6) Print the final set S is a vertex cover of the graph.
End
#include<bits/stdc++.h>
using namespace std;
vector<vector<int> > g;
bool v[11110];
int i,j;
vector<int> sol_vertex(int n,int e) {
vector<int> S;
for(i=0;i<n;i++) {
if(!v[i]) {
for(j=0;j<(int)g[i].size();j++) {
if(!v[g[i][j]]) {
v[i]=true;
v[g[i][j]]=true;
break;
}
}
}
}
for(i=0;i<n;i++)
if(v[i])
S.push_back(i);
return S;
}
int main() {
int n,e,a,b;
cout<<"Enter number of vertices:";
cin>>n;
cout<<"Enter number of Edges:";
cin>>e;
g.resize(n);
memset(v,0,sizeof(v));
for(i=0;i<e;i++) {
cout<<"Enter the end-points of edge "<<i+1<<" : ";
cin>>a>>b;
a--; b--;
g[a].push_back(b);
g[b].push_back(a);
}
vector<int> S = sol_vertex(n,e);
cout<<"The required vertex cover is as follows:\n";
for(i=0;i<(int)S.size();i++)
cout<<S[i]+1<<" ";
return 0;
}
Enter number of vertices:4
Enter number of Edges:5
Enter the end-points of edge 1 : 2 1
Enter the end-points of edge 2 : 3 2
Enter the end-points of edge 3 : 4 3
Enter the end-points of edge 4 : 1 4
Enter the end-points of edge 5 : 1 3
The required vertex cover is as follows:
1 2 3 4 | [
{
"code": null,
"e": 1292,
"s": 1062,
"text": "Vertex Cover of a Graph is to find a set of vertices V, such that for every edge connecting M to N in graph, either M or N (or both) are present in V. In this program, we Implement a Heuristic to Find the Vertex Cover of a Graph."
},
{
"code": null,
"e": 1614,
"s": 1292,
"text": "Begin\n 1) Initialize a set S as empty.\n 2) Take an edge E of the connecting graph Say M and N.\n 3) Add both vertex to the set S.\n 4) Discard all edges in the graph with endpoints at M or N.\n 5) If some edge is still left in the graph Go to step 2,\n 6) Print the final set S is a vertex cover of the graph.\nEnd"
},
{
"code": null,
"e": 2559,
"s": 1614,
"text": "#include<bits/stdc++.h>\nusing namespace std;\nvector<vector<int> > g;\nbool v[11110];\nint i,j;\nvector<int> sol_vertex(int n,int e) {\n vector<int> S;\n for(i=0;i<n;i++) {\n if(!v[i]) {\n for(j=0;j<(int)g[i].size();j++) {\n if(!v[g[i][j]]) {\n v[i]=true;\n v[g[i][j]]=true;\n break;\n }\n }\n }\n }\n for(i=0;i<n;i++)\n if(v[i])\n S.push_back(i);\n return S;\n}\nint main() {\n int n,e,a,b;\n cout<<\"Enter number of vertices:\";\n cin>>n;\n cout<<\"Enter number of Edges:\";\n cin>>e;\n g.resize(n);\n memset(v,0,sizeof(v));\n for(i=0;i<e;i++) {\n cout<<\"Enter the end-points of edge \"<<i+1<<\" : \";\n cin>>a>>b;\n a--; b--;\n g[a].push_back(b);\n g[b].push_back(a);\n }\n vector<int> S = sol_vertex(n,e);\n cout<<\"The required vertex cover is as follows:\\n\";\n for(i=0;i<(int)S.size();i++)\n cout<<S[i]+1<<\" \";\n return 0;\n}"
},
{
"code": null,
"e": 2844,
"s": 2559,
"text": "Enter number of vertices:4\nEnter number of Edges:5\nEnter the end-points of edge 1 : 2 1\nEnter the end-points of edge 2 : 3 2\nEnter the end-points of edge 3 : 4 3\nEnter the end-points of edge 4 : 1 4\nEnter the end-points of edge 5 : 1 3\nThe required vertex cover is as follows:\n1 2 3 4"
}
] |
Bootstrap Dropdowns | A dropdown menu is a toggleable menu that allows the user to choose one value
from a predefined list:
HTML
CSS
JavaScript
About Us
The .dropdown class indicates a dropdown menu.
To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and
the
data-toggle="dropdown" attribute.
The .caret class creates a caret arrow icon (), which indicates that the
button is a dropdown.
Add the .dropdown-menu class to a <ul> element to actually build the dropdown menu.
The .divider class is used to separate links inside the dropdown menu with a thin horizontal border:
Dropdown header 1
HTML
CSS
JavaScript
Dropdown header 2
About Us
The .dropdown-header class is used to add headers inside the dropdown menu:
Normal
Disabled
Active
Highlight a specific dropdown item with the .active class (adds a blue background color).
To disable an item in the dropdown menu, use the .disabled class (gets a light-grey text color and a "no-parking-sign" icon on hover):
HTML
CSS
JavaScript
About Us
To right-align the dropdown, add the .dropdown-menu-right class to the element
with .dropdown-menu:
HTML
CSS
JavaScript
About Us
If you want the dropdown menu to expand upwards instead of downwards, change
the <div> element with class="dropdown" to "dropup":
To help improve accessibility for people using screen readers, you should
include the following role and aria-* attributes, when creating a dropdown menu:
Add the required classes and attributes to create a dropdown list.
<div class="">
<button
class="btn btn-primary ">
Dropdown Example
<span class="caret"></span></button>
<ul class="">
<li><a href="#">HTML</a></li>
<li><a href="#">CSS</a></li>
<li><a href="#">JavaScript</a></li>
</ul>
</div>
Start the Exercise
For a complete reference of all dropdown options, methods and events, go to our
Bootstrap JS Dropdown Reference.
We just launchedW3Schools videos
Get certifiedby completinga course today!
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
[email protected]
Your message has been sent to W3Schools. | [
{
"code": null,
"e": 103,
"s": 0,
"text": "A dropdown menu is a toggleable menu that allows the user to choose one value \nfrom a predefined list:"
},
{
"code": null,
"e": 108,
"s": 103,
"text": "HTML"
},
{
"code": null,
"e": 112,
"s": 108,
"text": "CSS"
},
{
"code": null,
"e": 123,
"s": 112,
"text": "JavaScript"
},
{
"code": null,
"e": 132,
"s": 123,
"text": "About Us"
},
{
"code": null,
"e": 179,
"s": 132,
"text": "The .dropdown class indicates a dropdown menu."
},
{
"code": null,
"e": 306,
"s": 179,
"text": "To open the dropdown menu, use a button or a link with a class of .dropdown-toggle and \nthe \ndata-toggle=\"dropdown\" attribute."
},
{
"code": null,
"e": 402,
"s": 306,
"text": "The .caret class creates a caret arrow icon (), which indicates that the \nbutton is a dropdown."
},
{
"code": null,
"e": 486,
"s": 402,
"text": "Add the .dropdown-menu class to a <ul> element to actually build the dropdown menu."
},
{
"code": null,
"e": 587,
"s": 486,
"text": "The .divider class is used to separate links inside the dropdown menu with a thin horizontal border:"
},
{
"code": null,
"e": 605,
"s": 587,
"text": "Dropdown header 1"
},
{
"code": null,
"e": 610,
"s": 605,
"text": "HTML"
},
{
"code": null,
"e": 614,
"s": 610,
"text": "CSS"
},
{
"code": null,
"e": 625,
"s": 614,
"text": "JavaScript"
},
{
"code": null,
"e": 643,
"s": 625,
"text": "Dropdown header 2"
},
{
"code": null,
"e": 652,
"s": 643,
"text": "About Us"
},
{
"code": null,
"e": 728,
"s": 652,
"text": "The .dropdown-header class is used to add headers inside the dropdown menu:"
},
{
"code": null,
"e": 735,
"s": 728,
"text": "Normal"
},
{
"code": null,
"e": 744,
"s": 735,
"text": "Disabled"
},
{
"code": null,
"e": 751,
"s": 744,
"text": "Active"
},
{
"code": null,
"e": 841,
"s": 751,
"text": "Highlight a specific dropdown item with the .active class (adds a blue background color)."
},
{
"code": null,
"e": 976,
"s": 841,
"text": "To disable an item in the dropdown menu, use the .disabled class (gets a light-grey text color and a \"no-parking-sign\" icon on hover):"
},
{
"code": null,
"e": 981,
"s": 976,
"text": "HTML"
},
{
"code": null,
"e": 985,
"s": 981,
"text": "CSS"
},
{
"code": null,
"e": 996,
"s": 985,
"text": "JavaScript"
},
{
"code": null,
"e": 1005,
"s": 996,
"text": "About Us"
},
{
"code": null,
"e": 1106,
"s": 1005,
"text": "To right-align the dropdown, add the .dropdown-menu-right class to the element \nwith .dropdown-menu:"
},
{
"code": null,
"e": 1111,
"s": 1106,
"text": "HTML"
},
{
"code": null,
"e": 1115,
"s": 1111,
"text": "CSS"
},
{
"code": null,
"e": 1126,
"s": 1115,
"text": "JavaScript"
},
{
"code": null,
"e": 1135,
"s": 1126,
"text": "About Us"
},
{
"code": null,
"e": 1266,
"s": 1135,
"text": "If you want the dropdown menu to expand upwards instead of downwards, change \nthe <div> element with class=\"dropdown\" to \"dropup\":"
},
{
"code": null,
"e": 1422,
"s": 1266,
"text": "To help improve accessibility for people using screen readers, you should \ninclude the following role and aria-* attributes, when creating a dropdown menu:"
},
{
"code": null,
"e": 1489,
"s": 1422,
"text": "Add the required classes and attributes to create a dropdown list."
},
{
"code": null,
"e": 1740,
"s": 1489,
"text": "<div class=\"\">\n <button \n class=\"btn btn-primary \">\n Dropdown Example\n <span class=\"caret\"></span></button>\n <ul class=\"\">\n <li><a href=\"#\">HTML</a></li>\n <li><a href=\"#\">CSS</a></li>\n <li><a href=\"#\">JavaScript</a></li>\n </ul>\n</div>\n"
},
{
"code": null,
"e": 1759,
"s": 1740,
"text": "Start the Exercise"
},
{
"code": null,
"e": 1872,
"s": 1759,
"text": "For a complete reference of all dropdown options, methods and events, go to our\nBootstrap JS Dropdown Reference."
},
{
"code": null,
"e": 1905,
"s": 1872,
"text": "We just launchedW3Schools videos"
},
{
"code": null,
"e": 1947,
"s": 1905,
"text": "Get certifiedby completinga course today!"
},
{
"code": null,
"e": 2054,
"s": 1947,
"text": "If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:"
},
{
"code": null,
"e": 2073,
"s": 2054,
"text": "[email protected]"
}
] |
How to Change Column Type in PySpark Dataframe ? - GeeksforGeeks | 18 Jul, 2021
In this article, we are going to see how to change the column type of pyspark dataframe.
Creating dataframe for demonstration:
Python
# Create a spark sessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframecolumns = ["Name", "Course_Name", "Duration_Months", "Course_Fees", "Start_Date", "Payment_Done"]data = [ ("Amit Pathak", "Python", 3, 10000, "02-07-2021", True), ("Shikhar Mishra", "Soft skills", 2, 8000, "07-10-2021", False), ("Shivani Suvarna", "Accounting", 6, 15000, "20-08-2021", True), ("Pooja Jain", "Data Science", 12, 60000, "02-12-2021", False),]course_df = spark.createDataFrame(data).toDF(*columns) # View the dataframecourse_df.show()
Output:
Let’s see the schema of dataframe:
Python
# View the column datatypescourse_df.printSchema()
Output:
The DataFrame.withColumn(colName, col) returns a new DataFrame by adding a column or replacing the existing column that has the same name.
We will make use of cast(x, dataType) method to casts the column to a different data type. Here, the parameter “x” is the column name and dataType is the datatype in which you want to change the respective column to.
Example 1: Change datatype of single columns.
Python
# Cast Course_Fees from integer type to float typecourse_df2 = course_df.withColumn("Course_Fees", course_df["Course_Fees"] .cast('float'))course_df2.printSchema()
Output:
root
|-- Name: string (nullable = true)
|-- Course_Name: string (nullable = true)
|-- Duration_Months: long (nullable = true)
|-- Course_Fees: float (nullable = true)
|-- Start_Date: string (nullable = true)
|-- Payment_Done: boolean (nullable = true)
In the above example, we can observe that the “Course_Fees” column datatype is changed to float from long.
Example 2: Change datatype of multiple columns.
Python
# We can also make use of datatypes from # pyspark.sql.typesfrom pyspark.sql.types import StringType, DateType, FloatType course_df3 = course_df \ .withColumn("Course_Fees" , course_df["Course_Fees"] .cast(FloatType())) \ .withColumn("Payment_Done", course_df["Payment_Done"] .cast(StringType())) \ .withColumn("Start_Date" , course_df["Start_Date"] .cast(DateType())) \ course_df3.printSchema()
Output:
root
|-- Name: string (nullable = true)
|-- Course_Name: string (nullable = true)
|-- Duration_Months: long (nullable = true)
|-- Course_Fees: float (nullable = true)
|-- Start_Date: date (nullable = true)
|-- Payment_Done: string (nullable = true)
In the above example, we changed the datatype of columns “Course_Fees”, “Payment_Done”, and “Start_Date” to “float”, “str” and “datetype” respectively.
Here we will use select() function, this function is used to select the columns from the dataframe
Syntax: dataframe.select(columns)
Where dataframe is the input dataframe and columns are the input columns
Example 1: Change a single column.
Let us convert the `course_df3` from the above schema structure, back to the original schema.
Python
from pyspark.sql.types import StringType, BooleanType, IntegerType course_df4 = course_df3.select( course_df3.Name, course_df3.Course_Name, course_df3.Duration_Months, (course_df3.Course_Fees.cast(IntegerType())) .alias('Course_Fees'), (course_df3.Start_Date.cast(StringType())) .alias('Start_Date'), (course_df3.Payment_Done.cast(BooleanType())) .alias('Payment_Done'),) course_df4.printSchema()
Output:
root
|-- Name: string (nullable = true)
|-- Course_Name: string (nullable = true)
|-- Duration_Months: long (nullable = true)
|-- Course_Fees: integer (nullable = true)
|-- Start_Date: string (nullable = true)
|-- Payment_Done: boolean (nullable = true)
Example 2: Changing multiple columns to the same datatype.
Python
# Changing datatype of all the columns# to string typefrom pyspark.sql.types import StringType course_df5 = course_df.select( [course_df.cast(StringType()) .alias(c) for c in course_df.columns])course_df5.printSchema()
Output:
root
|-- Name: string (nullable = true)
|-- Course_Name: string (nullable = true)
|-- Duration_Months: string (nullable = true)
|-- Course_Fees: string (nullable = true)
|-- Start_Date: string (nullable = true)
|-- Payment_Done: string (nullable = true)
Example 3: Changing multiple columns to the different datatypes.
Let us use the `course_df5` which has all the column type as `string`. We will change the column types to a respective format.
Python
from pyspark.sql.types import ( StringType, BooleanType, IntegerType, FloatType, DateType) coltype_map = { "Name": StringType(), "Course_Name": StringType(), "Duration_Months": IntegerType(), "Course_Fees": FloatType(), "Start_Date": DateType(), "Payment_Done": BooleanType(),} # course_df6 has all the column# types as stringcourse_df6 = course_df5.select( [course_df5.cast(coltype_map) .alias(c) for c in course_df5.columns])course_df6.printSchema()
Output:
root
|-- Name: string (nullable = true)
|-- Course_Name: string (nullable = true)
|-- Duration_Months: integer (nullable = true)
|-- Course_Fees: float (nullable = true)
|-- Start_Date: date (nullable = true)
|-- Payment_Done: boolean (nullable = true)
Here we will use SQL query to change the column type.
Syntax: spark.sql(“sql Query”)
Example: Using spark.sql()
Python
# course_df5 has all the column datatypes as stringcourse_df5.createOrReplaceTempView("course_view") course_df7 = spark.sql('''SELECT Name, Course_Name, INT(Duration_Months), FLOAT(Course_Fees), DATE(Start_Date), BOOLEAN(Payment_Done)FROM course_view''') course_df7.printSchema()
Output:
root
|-- Name: string (nullable = true)
|-- Course_Name: string (nullable = true)
|-- Duration_Months: integer (nullable = true)
|-- Course_Fees: float (nullable = true)
|-- Start_Date: date (nullable = true)
|-- Payment_Done: boolean (nullable = true)
Picked
Python-Pyspark
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
Python OOPs Concepts
Python | Get unique values from a list
Check if element exists in list in Python
Python Classes and Objects
Python | os.path.join() method
How To Convert Python Dictionary To JSON?
Python | Pandas dataframe.groupby()
Create a directory in Python | [
{
"code": null,
"e": 24238,
"s": 24210,
"text": "\n18 Jul, 2021"
},
{
"code": null,
"e": 24327,
"s": 24238,
"text": "In this article, we are going to see how to change the column type of pyspark dataframe."
},
{
"code": null,
"e": 24365,
"s": 24327,
"text": "Creating dataframe for demonstration:"
},
{
"code": null,
"e": 24372,
"s": 24365,
"text": "Python"
},
{
"code": "# Create a spark sessionfrom pyspark.sql import SparkSessionspark = SparkSession.builder.appName('SparkExamples').getOrCreate() # Create a spark dataframecolumns = [\"Name\", \"Course_Name\", \"Duration_Months\", \"Course_Fees\", \"Start_Date\", \"Payment_Done\"]data = [ (\"Amit Pathak\", \"Python\", 3, 10000, \"02-07-2021\", True), (\"Shikhar Mishra\", \"Soft skills\", 2, 8000, \"07-10-2021\", False), (\"Shivani Suvarna\", \"Accounting\", 6, 15000, \"20-08-2021\", True), (\"Pooja Jain\", \"Data Science\", 12, 60000, \"02-12-2021\", False),]course_df = spark.createDataFrame(data).toDF(*columns) # View the dataframecourse_df.show()",
"e": 25035,
"s": 24372,
"text": null
},
{
"code": null,
"e": 25043,
"s": 25035,
"text": "Output:"
},
{
"code": null,
"e": 25078,
"s": 25043,
"text": "Let’s see the schema of dataframe:"
},
{
"code": null,
"e": 25085,
"s": 25078,
"text": "Python"
},
{
"code": "# View the column datatypescourse_df.printSchema()",
"e": 25136,
"s": 25085,
"text": null
},
{
"code": null,
"e": 25144,
"s": 25136,
"text": "Output:"
},
{
"code": null,
"e": 25283,
"s": 25144,
"text": "The DataFrame.withColumn(colName, col) returns a new DataFrame by adding a column or replacing the existing column that has the same name."
},
{
"code": null,
"e": 25500,
"s": 25283,
"text": "We will make use of cast(x, dataType) method to casts the column to a different data type. Here, the parameter “x” is the column name and dataType is the datatype in which you want to change the respective column to."
},
{
"code": null,
"e": 25546,
"s": 25500,
"text": "Example 1: Change datatype of single columns."
},
{
"code": null,
"e": 25553,
"s": 25546,
"text": "Python"
},
{
"code": "# Cast Course_Fees from integer type to float typecourse_df2 = course_df.withColumn(\"Course_Fees\", course_df[\"Course_Fees\"] .cast('float'))course_df2.printSchema()",
"e": 25784,
"s": 25553,
"text": null
},
{
"code": null,
"e": 25792,
"s": 25784,
"text": "Output:"
},
{
"code": null,
"e": 26050,
"s": 25792,
"text": "root\n |-- Name: string (nullable = true)\n |-- Course_Name: string (nullable = true)\n |-- Duration_Months: long (nullable = true)\n |-- Course_Fees: float (nullable = true)\n |-- Start_Date: string (nullable = true)\n |-- Payment_Done: boolean (nullable = true)"
},
{
"code": null,
"e": 26158,
"s": 26050,
"text": "In the above example, we can observe that the “Course_Fees” column datatype is changed to float from long. "
},
{
"code": null,
"e": 26206,
"s": 26158,
"text": "Example 2: Change datatype of multiple columns."
},
{
"code": null,
"e": 26213,
"s": 26206,
"text": "Python"
},
{
"code": "# We can also make use of datatypes from # pyspark.sql.typesfrom pyspark.sql.types import StringType, DateType, FloatType course_df3 = course_df \\ .withColumn(\"Course_Fees\" , course_df[\"Course_Fees\"] .cast(FloatType())) \\ .withColumn(\"Payment_Done\", course_df[\"Payment_Done\"] .cast(StringType())) \\ .withColumn(\"Start_Date\" , course_df[\"Start_Date\"] .cast(DateType())) \\ course_df3.printSchema()",
"e": 26698,
"s": 26213,
"text": null
},
{
"code": null,
"e": 26706,
"s": 26698,
"text": "Output:"
},
{
"code": null,
"e": 26961,
"s": 26706,
"text": "root\n |-- Name: string (nullable = true)\n |-- Course_Name: string (nullable = true)\n |-- Duration_Months: long (nullable = true)\n |-- Course_Fees: float (nullable = true)\n |-- Start_Date: date (nullable = true)\n |-- Payment_Done: string (nullable = true)"
},
{
"code": null,
"e": 27113,
"s": 26961,
"text": "In the above example, we changed the datatype of columns “Course_Fees”, “Payment_Done”, and “Start_Date” to “float”, “str” and “datetype” respectively."
},
{
"code": null,
"e": 27212,
"s": 27113,
"text": "Here we will use select() function, this function is used to select the columns from the dataframe"
},
{
"code": null,
"e": 27246,
"s": 27212,
"text": "Syntax: dataframe.select(columns)"
},
{
"code": null,
"e": 27319,
"s": 27246,
"text": "Where dataframe is the input dataframe and columns are the input columns"
},
{
"code": null,
"e": 27354,
"s": 27319,
"text": "Example 1: Change a single column."
},
{
"code": null,
"e": 27448,
"s": 27354,
"text": "Let us convert the `course_df3` from the above schema structure, back to the original schema."
},
{
"code": null,
"e": 27455,
"s": 27448,
"text": "Python"
},
{
"code": "from pyspark.sql.types import StringType, BooleanType, IntegerType course_df4 = course_df3.select( course_df3.Name, course_df3.Course_Name, course_df3.Duration_Months, (course_df3.Course_Fees.cast(IntegerType())) .alias('Course_Fees'), (course_df3.Start_Date.cast(StringType())) .alias('Start_Date'), (course_df3.Payment_Done.cast(BooleanType())) .alias('Payment_Done'),) course_df4.printSchema()",
"e": 27881,
"s": 27455,
"text": null
},
{
"code": null,
"e": 27889,
"s": 27881,
"text": "Output:"
},
{
"code": null,
"e": 28149,
"s": 27889,
"text": "root\n |-- Name: string (nullable = true)\n |-- Course_Name: string (nullable = true)\n |-- Duration_Months: long (nullable = true)\n |-- Course_Fees: integer (nullable = true)\n |-- Start_Date: string (nullable = true)\n |-- Payment_Done: boolean (nullable = true)"
},
{
"code": null,
"e": 28208,
"s": 28149,
"text": "Example 2: Changing multiple columns to the same datatype."
},
{
"code": null,
"e": 28215,
"s": 28208,
"text": "Python"
},
{
"code": "# Changing datatype of all the columns# to string typefrom pyspark.sql.types import StringType course_df5 = course_df.select( [course_df.cast(StringType()) .alias(c) for c in course_df.columns])course_df5.printSchema()",
"e": 28438,
"s": 28215,
"text": null
},
{
"code": null,
"e": 28446,
"s": 28438,
"text": "Output:"
},
{
"code": null,
"e": 28706,
"s": 28446,
"text": "root\n |-- Name: string (nullable = true)\n |-- Course_Name: string (nullable = true)\n |-- Duration_Months: string (nullable = true)\n |-- Course_Fees: string (nullable = true)\n |-- Start_Date: string (nullable = true)\n |-- Payment_Done: string (nullable = true)"
},
{
"code": null,
"e": 28771,
"s": 28706,
"text": "Example 3: Changing multiple columns to the different datatypes."
},
{
"code": null,
"e": 28898,
"s": 28771,
"text": "Let us use the `course_df5` which has all the column type as `string`. We will change the column types to a respective format."
},
{
"code": null,
"e": 28905,
"s": 28898,
"text": "Python"
},
{
"code": "from pyspark.sql.types import ( StringType, BooleanType, IntegerType, FloatType, DateType) coltype_map = { \"Name\": StringType(), \"Course_Name\": StringType(), \"Duration_Months\": IntegerType(), \"Course_Fees\": FloatType(), \"Start_Date\": DateType(), \"Payment_Done\": BooleanType(),} # course_df6 has all the column# types as stringcourse_df6 = course_df5.select( [course_df5.cast(coltype_map) .alias(c) for c in course_df5.columns])course_df6.printSchema()",
"e": 29387,
"s": 28905,
"text": null
},
{
"code": null,
"e": 29395,
"s": 29387,
"text": "Output:"
},
{
"code": null,
"e": 29654,
"s": 29395,
"text": "root\n |-- Name: string (nullable = true)\n |-- Course_Name: string (nullable = true)\n |-- Duration_Months: integer (nullable = true)\n |-- Course_Fees: float (nullable = true)\n |-- Start_Date: date (nullable = true)\n |-- Payment_Done: boolean (nullable = true)"
},
{
"code": null,
"e": 29708,
"s": 29654,
"text": "Here we will use SQL query to change the column type."
},
{
"code": null,
"e": 29739,
"s": 29708,
"text": "Syntax: spark.sql(“sql Query”)"
},
{
"code": null,
"e": 29766,
"s": 29739,
"text": "Example: Using spark.sql()"
},
{
"code": null,
"e": 29773,
"s": 29766,
"text": "Python"
},
{
"code": "# course_df5 has all the column datatypes as stringcourse_df5.createOrReplaceTempView(\"course_view\") course_df7 = spark.sql('''SELECT Name, Course_Name, INT(Duration_Months), FLOAT(Course_Fees), DATE(Start_Date), BOOLEAN(Payment_Done)FROM course_view''') course_df7.printSchema()",
"e": 30062,
"s": 29773,
"text": null
},
{
"code": null,
"e": 30070,
"s": 30062,
"text": "Output:"
},
{
"code": null,
"e": 30329,
"s": 30070,
"text": "root\n |-- Name: string (nullable = true)\n |-- Course_Name: string (nullable = true)\n |-- Duration_Months: integer (nullable = true)\n |-- Course_Fees: float (nullable = true)\n |-- Start_Date: date (nullable = true)\n |-- Payment_Done: boolean (nullable = true)"
},
{
"code": null,
"e": 30336,
"s": 30329,
"text": "Picked"
},
{
"code": null,
"e": 30351,
"s": 30336,
"text": "Python-Pyspark"
},
{
"code": null,
"e": 30358,
"s": 30351,
"text": "Python"
},
{
"code": null,
"e": 30456,
"s": 30358,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 30465,
"s": 30456,
"text": "Comments"
},
{
"code": null,
"e": 30478,
"s": 30465,
"text": "Old Comments"
},
{
"code": null,
"e": 30510,
"s": 30478,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 30566,
"s": 30510,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 30587,
"s": 30566,
"text": "Python OOPs Concepts"
},
{
"code": null,
"e": 30626,
"s": 30587,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 30668,
"s": 30626,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 30695,
"s": 30668,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 30726,
"s": 30695,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 30768,
"s": 30726,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 30804,
"s": 30768,
"text": "Python | Pandas dataframe.groupby()"
}
] |
Inorder Traversal | Practice | GeeksforGeeks | Given a Binary Tree, find the In-Order Traversal of it.
Example 1:
Input:
1
/ \
3 2
Output: 3 1 2
Example 2:
Input:
10
/ \
20 30
/ \ /
40 60 50
Output: 40 20 60 10 50 30
Your Task:
You don't need to read input or print anything. Your task is to complete the function inOrder() that takes root node of the tree as input and returns a list containing the In-Order Traversal of the given Binary Tree.
Expected Time Complexity: O(N).
Expected Auxiliary Space: O(N).
Constraints:
1 <= Number of nodes <= 105
0 <= Data of a node <= 105
0
shubham2110199750 minutes ago
static ArrayList<Integer> arr=new ArrayList<Integer>(); static void helper(Node root){ if(root==null) return; helper(root.left); arr.add(root.data); helper(root.right); } ArrayList<Integer> inOrder(Node root) { helper(root); ArrayList<Integer> arr1=new ArrayList<Integer>(); for(int i=0;i<arr.size();i++){ arr1.add(arr.get(i)); } arr.clear(); return arr1; }
0
superrhitik4583 days ago
class Solution { public: // Function to return a list containing the inorder traversal of the tree. vector<int> vi;void in(Node* root){ if(root!=NULL){ in(root->left); vi.push_back(root->data); in(root->right);} return;}vector <int> inOrder(Node* root){ // Your code herein(root); vector<int> res=vi;vi.clear();return res;}};
0
harshbhan261 week ago
class Solution { public: // Function to return a list containing the inorder traversal of the tree. vector<int>ans; vector<int> inOrder(Node* root) { if(root!=NULL){ inOrder(root->left); ans.push_back(root->data); inOrder(root->right); } return ans; }};
+1
itachinamikaze2211 week ago
ArrayList<Integer> inOrder(Node root) { ArrayList<Integer>res= new ArrayList<>(); Stack<Node> st= new Stack<Node>(); Node n=root; while(true) { if(n!=null) { st.push(n); n=n.left; } else { if(st.isEmpty()) break; n=st.pop(); res.add(n.data); n=n.right; } } return res;}
0
adivp72 weeks ago
void inorder(Node* node, vector<int>& r)
{
if(node)
{
inorder(node->left,r);
r.push_back(node->data);
inorder(node->right,r);
}
}
vector<int> inOrder(Node* root) {
vector<int> r;
inorder(root,r);
return r;
}
-1
ykc070814 weeks ago
C Solution
int arr[100000];
void inorder(struct Node* root, int* i)
{
if(root == NULL)
return;
inorder(root->left,i);
arr[(*i)]=root->data;
(*i) = (*i)+1;
inorder(root->right,i);
}
int* inOrder(struct Node* root)
{
int ind=0;
inorder(root,&ind);
return arr;
}
0
bsbh20is1 month ago
int arr[100000];void inorder(struct Node *node,int *i){ if(node==NULL) return; inorder(node->left,i); arr[(*i)]=node->data; (*i)=(*i)+1; inorder(node->right,i); }
int* inOrder(struct Node* root) { // code here int ind=0; inorder(root,&ind); return arr; }
0
subhashishde081 month ago
class Solution {
public:
// Function to return a list containing the inorder traversal of the tree.
void helper(Node* root,vector<int> &vc){
if(root==NULL) return;
helper(root->left,vc);
vc.push_back(root->data);
helper(root->right,vc);
}
vector<int> inOrder(Node* root) {
// Your code here
vector<int> vc;
helper(root,vc);
return vc;
}
};
+1
chamoliabhishek0071 month ago
res=[] if not root: return [] res+=self.InOrder(root.left) res.append(root.data) res+=self.InOrder(root.right) return res
0
jyotikaushal3351 month ago
def InOrder(self,root): # code here if root is None: return [] stack = [] result = [] while root is not None or stack != []: while root is not None: stack.append(root) root = root.left root = stack.pop() result.append(root.data) root = root.right return result
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": 282,
"s": 226,
"text": "Given a Binary Tree, find the In-Order Traversal of it."
},
{
"code": null,
"e": 293,
"s": 282,
"text": "Example 1:"
},
{
"code": null,
"e": 346,
"s": 293,
"text": "Input:\n 1\n / \\\n 3 2\nOutput: 3 1 2\n\n"
},
{
"code": null,
"e": 357,
"s": 346,
"text": "Example 2:"
},
{
"code": null,
"e": 463,
"s": 357,
"text": "Input:\n 10\n / \\ \n 20 30 \n / \\ /\n 40 60 50\nOutput: 40 20 60 10 50 30\n\n"
},
{
"code": null,
"e": 691,
"s": 463,
"text": "Your Task:\nYou don't need to read input or print anything. Your task is to complete the function inOrder() that takes root node of the tree as input and returns a list containing the In-Order Traversal of the given Binary Tree."
},
{
"code": null,
"e": 755,
"s": 691,
"text": "Expected Time Complexity: O(N).\nExpected Auxiliary Space: O(N)."
},
{
"code": null,
"e": 825,
"s": 755,
"text": "Constraints:\n1 <= Number of nodes <= 105\n0 <= Data of a node <= 105\n "
},
{
"code": null,
"e": 827,
"s": 825,
"text": "0"
},
{
"code": null,
"e": 857,
"s": 827,
"text": "shubham2110199750 minutes ago"
},
{
"code": null,
"e": 1282,
"s": 857,
"text": "static ArrayList<Integer> arr=new ArrayList<Integer>(); static void helper(Node root){ if(root==null) return; helper(root.left); arr.add(root.data); helper(root.right); } ArrayList<Integer> inOrder(Node root) { helper(root); ArrayList<Integer> arr1=new ArrayList<Integer>(); for(int i=0;i<arr.size();i++){ arr1.add(arr.get(i)); } arr.clear(); return arr1; }"
},
{
"code": null,
"e": 1284,
"s": 1282,
"text": "0"
},
{
"code": null,
"e": 1309,
"s": 1284,
"text": "superrhitik4583 days ago"
},
{
"code": null,
"e": 1649,
"s": 1309,
"text": "class Solution { public: // Function to return a list containing the inorder traversal of the tree. vector<int> vi;void in(Node* root){ if(root!=NULL){ in(root->left); vi.push_back(root->data); in(root->right);} return;}vector <int> inOrder(Node* root){ // Your code herein(root); vector<int> res=vi;vi.clear();return res;}};"
},
{
"code": null,
"e": 1651,
"s": 1649,
"text": "0"
},
{
"code": null,
"e": 1673,
"s": 1651,
"text": "harshbhan261 week ago"
},
{
"code": null,
"e": 1997,
"s": 1673,
"text": "class Solution { public: // Function to return a list containing the inorder traversal of the tree. vector<int>ans; vector<int> inOrder(Node* root) { if(root!=NULL){ inOrder(root->left); ans.push_back(root->data); inOrder(root->right); } return ans; }};"
},
{
"code": null,
"e": 2000,
"s": 1997,
"text": "+1"
},
{
"code": null,
"e": 2028,
"s": 2000,
"text": "itachinamikaze2211 week ago"
},
{
"code": null,
"e": 2422,
"s": 2028,
"text": "ArrayList<Integer> inOrder(Node root) { ArrayList<Integer>res= new ArrayList<>(); Stack<Node> st= new Stack<Node>(); Node n=root; while(true) { if(n!=null) { st.push(n); n=n.left; } else { if(st.isEmpty()) break; n=st.pop(); res.add(n.data); n=n.right; } } return res;}"
},
{
"code": null,
"e": 2424,
"s": 2422,
"text": "0"
},
{
"code": null,
"e": 2442,
"s": 2424,
"text": "adivp72 weeks ago"
},
{
"code": null,
"e": 2750,
"s": 2442,
"text": "void inorder(Node* node, vector<int>& r)\n {\n if(node)\n {\n inorder(node->left,r);\n r.push_back(node->data);\n inorder(node->right,r);\n }\n }\n vector<int> inOrder(Node* root) {\n vector<int> r;\n inorder(root,r);\n return r;\n }"
},
{
"code": null,
"e": 2753,
"s": 2750,
"text": "-1"
},
{
"code": null,
"e": 2773,
"s": 2753,
"text": "ykc070814 weeks ago"
},
{
"code": null,
"e": 2784,
"s": 2773,
"text": "C Solution"
},
{
"code": null,
"e": 3076,
"s": 2784,
"text": "int arr[100000];\n\nvoid inorder(struct Node* root, int* i)\n{\n if(root == NULL)\n return;\n inorder(root->left,i);\n arr[(*i)]=root->data;\n (*i) = (*i)+1;\n inorder(root->right,i);\n}\n\nint* inOrder(struct Node* root) \n{\n int ind=0;\n inorder(root,&ind);\n return arr;\n}"
},
{
"code": null,
"e": 3078,
"s": 3076,
"text": "0"
},
{
"code": null,
"e": 3098,
"s": 3078,
"text": "bsbh20is1 month ago"
},
{
"code": null,
"e": 3279,
"s": 3098,
"text": "int arr[100000];void inorder(struct Node *node,int *i){ if(node==NULL) return; inorder(node->left,i); arr[(*i)]=node->data; (*i)=(*i)+1; inorder(node->right,i); }"
},
{
"code": null,
"e": 3382,
"s": 3279,
"text": "int* inOrder(struct Node* root) { // code here int ind=0; inorder(root,&ind); return arr; }"
},
{
"code": null,
"e": 3384,
"s": 3382,
"text": "0"
},
{
"code": null,
"e": 3410,
"s": 3384,
"text": "subhashishde081 month ago"
},
{
"code": null,
"e": 3836,
"s": 3410,
"text": "class Solution {\n public:\n // Function to return a list containing the inorder traversal of the tree.\n void helper(Node* root,vector<int> &vc){\n if(root==NULL) return;\n helper(root->left,vc);\n vc.push_back(root->data);\n helper(root->right,vc);\n }\n vector<int> inOrder(Node* root) {\n // Your code here\n vector<int> vc;\n helper(root,vc);\n return vc;\n }\n};"
},
{
"code": null,
"e": 3839,
"s": 3836,
"text": "+1"
},
{
"code": null,
"e": 3869,
"s": 3839,
"text": "chamoliabhishek0071 month ago"
},
{
"code": null,
"e": 4038,
"s": 3869,
"text": " res=[] if not root: return [] res+=self.InOrder(root.left) res.append(root.data) res+=self.InOrder(root.right) return res"
},
{
"code": null,
"e": 4042,
"s": 4040,
"text": "0"
},
{
"code": null,
"e": 4069,
"s": 4042,
"text": "jyotikaushal3351 month ago"
},
{
"code": null,
"e": 4468,
"s": 4069,
"text": "def InOrder(self,root): # code here if root is None: return [] stack = [] result = [] while root is not None or stack != []: while root is not None: stack.append(root) root = root.left root = stack.pop() result.append(root.data) root = root.right return result"
},
{
"code": null,
"e": 4614,
"s": 4468,
"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": 4650,
"s": 4614,
"text": " Login to access your submissions. "
},
{
"code": null,
"e": 4660,
"s": 4650,
"text": "\nProblem\n"
},
{
"code": null,
"e": 4670,
"s": 4660,
"text": "\nContest\n"
},
{
"code": null,
"e": 4733,
"s": 4670,
"text": "Reset the IDE using the second button on the top right corner."
},
{
"code": null,
"e": 4881,
"s": 4733,
"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": 5089,
"s": 4881,
"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": 5195,
"s": 5089,
"text": "You can access the hints to get an idea about what is expected of you as well as the final solution code."
}
] |
Minimum Number of Jumps Problem | In this problem, a list of positive integers is given. Each integer is denoting that how many maximum steps that can be made from the current element. Starting from the first element, we have to find the minimum number of jumps to reach the end item of the list.
For the dynamic programming approach, a jumps array is defined to store the minimum number of jumps required. Like for a value of jumps[i], it indicates that how many minimum jumps are needed to reach the ith index of the array from the 0th index.
Input:
A list of integers. {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}
Output:
The minimum number of jumps to reach the end location. It is 3.
Start from value 1, go to 3. then jumps 3 values and reach 8. then jump 8 values and reach the last element.
minPossibleJump(list, n)
Input: Number array, number of elements in the array.
Output: Minimum number of jumps required to reach at the end.
Begin
define an array named jump of size n
if n = 0 or list[0] = 0, then
return ∞
jump[0] := 0
for i := 1 to n, do
jumps[i] := ∞
for j := 0 to i, do
if i <= j + list[j] and jump[j] ≠ ∞, then
jump[i] := minimum of jump[i] and (jump[j] + 1)
break the loop
done
done
return jump[n-1]
End
#include<iostream>
using namespace std;
int min(int x, int y) {
return (x < y)? x: y;
}
int minPossibleJump(int list[], int n) {
int *jumps = new int[n]; // dynamically create jumps array to store steps
if (n == 0 || list[0] == 0)
return INT_MAX;
jumps[0] = 0;
for (int i = 1; i < n; i++) {
jumps[i] = INT_MAX; //initially set jumps as infinity
for (int j = 0; j < i; j++) {
if (i <= j + list[j] && jumps[j] != INT_MAX) {
jumps[i] = min(jumps[i], jumps[j] + 1);
break;
}
}
}
return jumps[n-1];
}
int main() {
int list[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};
int size = 11;
cout << "Minimum number of jumps to reach end is: "<< minPossibleJump(list,size);
return 0;
}
Minimum number of jumps to reach end is: 3 | [
{
"code": null,
"e": 1325,
"s": 1062,
"text": "In this problem, a list of positive integers is given. Each integer is denoting that how many maximum steps that can be made from the current element. Starting from the first element, we have to find the minimum number of jumps to reach the end item of the list."
},
{
"code": null,
"e": 1573,
"s": 1325,
"text": "For the dynamic programming approach, a jumps array is defined to store the minimum number of jumps required. Like for a value of jumps[i], it indicates that how many minimum jumps are needed to reach the ith index of the array from the 0th index."
},
{
"code": null,
"e": 1815,
"s": 1573,
"text": "Input:\nA list of integers. {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9}\nOutput:\nThe minimum number of jumps to reach the end location. It is 3.\nStart from value 1, go to 3. then jumps 3 values and reach 8. then jump 8 values and reach the last element."
},
{
"code": null,
"e": 1840,
"s": 1815,
"text": "minPossibleJump(list, n)"
},
{
"code": null,
"e": 1894,
"s": 1840,
"text": "Input: Number array, number of elements in the array."
},
{
"code": null,
"e": 1956,
"s": 1894,
"text": "Output: Minimum number of jumps required to reach at the end."
},
{
"code": null,
"e": 2319,
"s": 1956,
"text": "Begin\n define an array named jump of size n\n if n = 0 or list[0] = 0, then\n return ∞\n jump[0] := 0\n\n for i := 1 to n, do\n jumps[i] := ∞\n for j := 0 to i, do\n if i <= j + list[j] and jump[j] ≠ ∞, then\n jump[i] := minimum of jump[i] and (jump[j] + 1)\n break the loop\n done\n done\n\n return jump[n-1]\nEnd"
},
{
"code": null,
"e": 3096,
"s": 2319,
"text": "#include<iostream>\nusing namespace std;\n\nint min(int x, int y) {\n return (x < y)? x: y;\n}\n\nint minPossibleJump(int list[], int n) {\n int *jumps = new int[n]; // dynamically create jumps array to store steps\n if (n == 0 || list[0] == 0)\n return INT_MAX;\n jumps[0] = 0;\n\n for (int i = 1; i < n; i++) {\n jumps[i] = INT_MAX; //initially set jumps as infinity\n for (int j = 0; j < i; j++) {\n if (i <= j + list[j] && jumps[j] != INT_MAX) {\n jumps[i] = min(jumps[i], jumps[j] + 1);\n break;\n }\n }\n }\n return jumps[n-1];\n}\n\nint main() {\n int list[] = {1, 3, 5, 8, 9, 2, 6, 7, 6, 8, 9};\n int size = 11;\n cout << \"Minimum number of jumps to reach end is: \"<< minPossibleJump(list,size);\n return 0;\n}"
},
{
"code": null,
"e": 3139,
"s": 3096,
"text": "Minimum number of jumps to reach end is: 3"
}
] |
Apache IVY - Environment Setup | Apache Ivy needs Java and ANT installed on your machine as the only requirement.
Apache Ant is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative.
The latest Apache Ant version, including its full-source code, class files, and documentation can be found at http://ant.apache.org
It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions here.
Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed.
Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed.
Download the binaries from https://ant.apache.org
Download the binaries from https://ant.apache.org
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\apache-ant-1.10.12-bin folder.
Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\apache-ant-1.10.12-bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\apache-ant-1.10.12-bin\bin folder.
Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\apache-ant-1.10.12-bin\bin folder.
To verify the successful installation of Apache Ant on your computer, type ant on your command prompt.
You should see an output similar to −
C:\>ant -version
Apache Ant(TM) version 1.10.12 compiled on October 13 2021
If you do not see the above output, then please verify that you have followed the installation steps properly.
Download the binaries from https://ant.apache.org/ivy
Download the binaries from https://ant.apache.org/ivy
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Unzip the zip file to a convenient location c:\folder. using Winzip, winRAR, 7-zip or similar tools.
Copy the ivy-2.5.0.jar to c:\apache-ant-1.10.12-bin/lib folder.
Copy the ivy-2.5.0.jar to c:\apache-ant-1.10.12-bin/lib folder.
To verify the successful installation of Apache Ivy on your computer, create following build file in a folder E: > ivy.
<project name="test ivy installation"
default="test" xmlns:ivy="antlib:org.apache.ivy.ant">
<target name="test" description="Test ivy installation">
<ivy:settings />
</target>
</project>
You should see an output similar to −
C:\>ant
Buildfile: E:\ivy\build.xml
test:
BUILD SUCCESSFUL
Total time: 2 seconds
This tutorial also covers integration of Ant with Eclipse IDE. Hence, if you have not installed Eclipse already, please download and install Eclipse.
To install Eclipse −
Download the latest Eclipse binaries from www.eclipse.org
Download the latest Eclipse binaries from www.eclipse.org
Unzip the Eclipse binaries to a convenient location, say c:\folder
Unzip the Eclipse binaries to a convenient location, say c:\folder
Run Eclipse from c:\eclipse\eclipse.exe
Run Eclipse from c:\eclipse\eclipse.exe
46 Lectures
3.5 hours
Arnab Chakraborty
23 Lectures
1.5 hours
Mukund Kumar Mishra
16 Lectures
1 hours
Nilay Mehta
52 Lectures
1.5 hours
Bigdata Engineer
14 Lectures
1 hours
Bigdata Engineer
23 Lectures
1 hours
Bigdata Engineer
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2085,
"s": 2004,
"text": "Apache Ivy needs Java and ANT installed on your machine as the only requirement."
},
{
"code": null,
"e": 2223,
"s": 2085,
"text": "Apache Ant is distributed under the Apache Software License, a fully-fledged open source license certified by the open source initiative."
},
{
"code": null,
"e": 2355,
"s": 2223,
"text": "The latest Apache Ant version, including its full-source code, class files, and documentation can be found at http://ant.apache.org"
},
{
"code": null,
"e": 2506,
"s": 2355,
"text": "It is assumed that you have already downloaded and installed Java Development Kit (JDK) on your computer. If not, please follow the instructions here."
},
{
"code": null,
"e": 2603,
"s": 2506,
"text": "Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed."
},
{
"code": null,
"e": 2700,
"s": 2603,
"text": "Ensure that the JAVA_HOME environment variable is set to the folder where your JDK is installed."
},
{
"code": null,
"e": 2750,
"s": 2700,
"text": "Download the binaries from https://ant.apache.org"
},
{
"code": null,
"e": 2800,
"s": 2750,
"text": "Download the binaries from https://ant.apache.org"
},
{
"code": null,
"e": 2901,
"s": 2800,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 3002,
"s": 2901,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 3143,
"s": 3002,
"text": "Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\\apache-ant-1.10.12-bin folder."
},
{
"code": null,
"e": 3284,
"s": 3143,
"text": "Create a new environment variable called ANT_HOME that points to the Ant installation folder, in this case c:\\apache-ant-1.10.12-bin folder."
},
{
"code": null,
"e": 3431,
"s": 3284,
"text": "Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\\apache-ant-1.10.12-bin\\bin folder."
},
{
"code": null,
"e": 3578,
"s": 3431,
"text": "Append the path to the Apache Ant batch file to the PATH environment variable. In our case this would be the c:\\apache-ant-1.10.12-bin\\bin folder."
},
{
"code": null,
"e": 3681,
"s": 3578,
"text": "To verify the successful installation of Apache Ant on your computer, type ant on your command prompt."
},
{
"code": null,
"e": 3719,
"s": 3681,
"text": "You should see an output similar to −"
},
{
"code": null,
"e": 3796,
"s": 3719,
"text": "C:\\>ant -version\nApache Ant(TM) version 1.10.12 compiled on October 13 2021\n"
},
{
"code": null,
"e": 3907,
"s": 3796,
"text": "If you do not see the above output, then please verify that you have followed the installation steps properly."
},
{
"code": null,
"e": 3961,
"s": 3907,
"text": "Download the binaries from https://ant.apache.org/ivy"
},
{
"code": null,
"e": 4015,
"s": 3961,
"text": "Download the binaries from https://ant.apache.org/ivy"
},
{
"code": null,
"e": 4116,
"s": 4015,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 4217,
"s": 4116,
"text": "Unzip the zip file to a convenient location c:\\folder. using Winzip, winRAR, 7-zip or similar tools."
},
{
"code": null,
"e": 4281,
"s": 4217,
"text": "Copy the ivy-2.5.0.jar to c:\\apache-ant-1.10.12-bin/lib folder."
},
{
"code": null,
"e": 4345,
"s": 4281,
"text": "Copy the ivy-2.5.0.jar to c:\\apache-ant-1.10.12-bin/lib folder."
},
{
"code": null,
"e": 4465,
"s": 4345,
"text": "To verify the successful installation of Apache Ivy on your computer, create following build file in a folder E: > ivy."
},
{
"code": null,
"e": 4668,
"s": 4465,
"text": "<project name=\"test ivy installation\" \n default=\"test\" xmlns:ivy=\"antlib:org.apache.ivy.ant\">\n <target name=\"test\" description=\"Test ivy installation\">\n <ivy:settings />\n </target>\n</project>"
},
{
"code": null,
"e": 4706,
"s": 4668,
"text": "You should see an output similar to −"
},
{
"code": null,
"e": 4790,
"s": 4706,
"text": "C:\\>ant\nBuildfile: E:\\ivy\\build.xml\n\ntest:\n\nBUILD SUCCESSFUL\nTotal time: 2 seconds\n"
},
{
"code": null,
"e": 4940,
"s": 4790,
"text": "This tutorial also covers integration of Ant with Eclipse IDE. Hence, if you have not installed Eclipse already, please download and install Eclipse."
},
{
"code": null,
"e": 4961,
"s": 4940,
"text": "To install Eclipse −"
},
{
"code": null,
"e": 5019,
"s": 4961,
"text": "Download the latest Eclipse binaries from www.eclipse.org"
},
{
"code": null,
"e": 5077,
"s": 5019,
"text": "Download the latest Eclipse binaries from www.eclipse.org"
},
{
"code": null,
"e": 5144,
"s": 5077,
"text": "Unzip the Eclipse binaries to a convenient location, say c:\\folder"
},
{
"code": null,
"e": 5211,
"s": 5144,
"text": "Unzip the Eclipse binaries to a convenient location, say c:\\folder"
},
{
"code": null,
"e": 5251,
"s": 5211,
"text": "Run Eclipse from c:\\eclipse\\eclipse.exe"
},
{
"code": null,
"e": 5291,
"s": 5251,
"text": "Run Eclipse from c:\\eclipse\\eclipse.exe"
},
{
"code": null,
"e": 5326,
"s": 5291,
"text": "\n 46 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 5345,
"s": 5326,
"text": " Arnab Chakraborty"
},
{
"code": null,
"e": 5380,
"s": 5345,
"text": "\n 23 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5401,
"s": 5380,
"text": " Mukund Kumar Mishra"
},
{
"code": null,
"e": 5434,
"s": 5401,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5447,
"s": 5434,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 5482,
"s": 5447,
"text": "\n 52 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 5500,
"s": 5482,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5533,
"s": 5500,
"text": "\n 14 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5551,
"s": 5533,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5584,
"s": 5551,
"text": "\n 23 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5602,
"s": 5584,
"text": " Bigdata Engineer"
},
{
"code": null,
"e": 5609,
"s": 5602,
"text": " Print"
},
{
"code": null,
"e": 5620,
"s": 5609,
"text": " Add Notes"
}
] |
Building an Image Cartoonization Web App with Python | by Ruben Winastwan | Towards Data Science | As an avid street-photography person who spend almost every weekend wandering around the city to hunt some photos, Adobe Lightroom is always my go-to software to edit my raw photos to make it more “instagrammable”.
This got me thinking, wouldn’t it be awesome if I can somehow create my own simple image editing software?
The emergence of open source computer vision library like OpenCV and open source app framework like Streamlit enables me to realize this idea. With under 100 lines of code, you can build your own image cartooning web app that somehow mimicking the functionality of Adobe Lightroom.
In this article, I want to show you how to build a simple web app to turn your image into cartoon-like image, depending on the filters, using OpenCV and Streamlit.
There are two main steps that we often need to do to convert an image into a cartoon: edge detection and region smoothing.
The main purpose of edge detection is obviously to emphasize the edge of an image, because normally a cartoon image has well-defined edges. Meanwhile, the main purpose of region smoothing is to remove the insignificant color boundaries and to reduce the noise or grain of the image, making the image less pixelated.
Depending on the filters, we can obtain different image cartoonization result. In this article, there are going to be four different filters:
Pencil SketchDetail EnhancementBilateral FilterPencil Edges
Pencil Sketch
Detail Enhancement
Bilateral Filter
Pencil Edges
Next, I want to show you how to apply each filters and what kind of result that you would expect from each of them.
With Pencil Sketch filter, your image will be converted into a sketch as if your image has been drawn using a pencil. Below is the entire code to convert your image into a pencil sketch using OpenCV.
It’s amazing that we can convert our image into a pencil sketch-like picture with only three lines of code using OpenCV. Now let me explain what actually happens with our image line-by-line.
In the first line, we convert our image from color into grayscale with cvtColor() function from OpenCV. I think this is pretty straightforward that the result from this line is that our image turns into its grayscale representation.
Next, we blur the image using Gaussian Blur. By blurring the grayscale image, we are basically smoothing the image, trying to reduce the noise of the image. Plus, blurring is the necessary step for us to detect the edge of the image.
To blur the image, we can use GaussianBlur() function from OpenCV. The (25, 25) that I put in the GaussianBlur() function there is the size of the kernel.
Since we use Gaussian Blur, the distribution of the pixel value in a kernel follows a normal distribution. The larger the number the kernel, the larger the standard deviation would be and hence, the stronger the blurring effect will be. Below is the example of the blurring result with different kernel size.
The final step would be dividing the original grayscale image with the blurred grayscale image. Dividing the image gives us a ratio of change between each pixel of two images. The stronger the blurry effects, the more the value of each pixel changes with respect to its origin and hence, it gives us sharper pencil sketch.
Below is the result of using Pencil Sketch filter.
In short, Detail Enhancement filter gives us a cartoon effect by sharpening the image, smoothing the colors, and enhancing the edges. Below is the entire code to convert your image into cartoon with this filter.
The first step is the same as before, that we need to convert the image into a grayscale image.
Next, instead of using Gaussian Blur, Median Blur is applied. To do this, we use medianBlur() function from OpenCV. Median Blur works by computing the median of pixel values that overlaps with the kernel, and then replacing its central pixel value with the computed median value. However, you can use Gaussian Blur if you wish.
Next, we need to detect the edges of the image. To do this, adaptive threshold is applied with adaptiveThreshold() function from OpenCV. The main goal of adaptive threshold is to convert each pixel values in each region of an image into either completely black or completely white, depending on the mean value of the pixel overlapped by the kernel.
Below is the visualization of what adaptive threshold does to the blurred image.
To make the image looks sharper, we can use detailEnhance() filter from OpenCV. There are two parameters that you need to specify as an argument:
sigma_s: This controls the size of the neighborhood that the value will be weighted to replace a pixel value in an image. The higher the value, the bigger the neighborhood. This leads to smoother image.
sigma_r: This is important if you want to preserve edges while smoothing the image. Small value yields in only very similar colors to be averaged (i.e. smoothed), while colors that differ much will stay intact.
Finally, we use the result of adaptive threshold as a mask. Then, merge the result of detail enhancement based on the value of the mask to create a sharp effect with well-defined edge.
Below is the example result of Detail Enhancement filters.
One big advantage of using Bilateral Filter is that we can smooth the image and the colors while preserving the edge at the same time. Below is the entire code to convert your image into cartoon-like with bilateral filtering.
If you take a closer look, all of the steps are similar with the one from Detail Enhancement filter, however this time instead of using detailEnhance() function, we use bilateralFilter()function from openCV.
The argument that you need to pass when you call this function is the same as the one with detailEnhance(), with only one additional parameter, which is the kernel size d. First, you need to specify the image source, then d, sigma_s, and sigma_r values that controls the smoothing effect and to preserve the edge.
Below is the result example of using Bilateral Filter.
Pencil Edges filter creates a new image that contains only significant edges and white background. To apply this filter, below is the complete code.
The first two steps are the same as the other filters. First, we convert the image into a grayscale image. Next, we blur the image with the kernel size of 25.
Now what’s different is the next step, in which we apply Laplacian filter to detect the edges. Depending on the size of the kernel, the value in a Laplacian filter can be different. If you want to know more about the value of Laplacian filter with different kernel size, you can read it here.
What Laplacian filter does is that it will emphasize the edge of an object with brighter and darker intensity than the gray-level inside of the object and the background of the image. Below is the example of before and after the application of Laplacian filter.
Next, we invert the result of Laplacian filter so that the darker gray color become brighter and vice versa. Finally, by applying the threshold() function from openCV, we can convert the grayscale image into either completely black or completely white, depending on the threshold value that we specified.
Below is the result example of Pencil Edge filter.
After we created the code for image cartoonization filters, now we are ready to create an image cartoonization web app.
As a first step, we need to put all of the codes for image cartoonization filters we have created into one function for an easy access. Notice that so far, we have hard-coded every parameter values like the size of the kernel and so on.
Now instead of hard-coding every parameter values, we can actually let the user to specify a value based on their preference using a slider. To do this, we can use streamlit.slider() function from Streamlit. Below is the example of its implementation.
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)scale_val = st.slider('Tune the brightness of your sketch (the higher the value, the brighter your sketch)', 0.0, 300.0, 250.0)kernel = st.slider('Tune the boldness of the edges of your sketch (the higher the value, the bolder the edges)', 1, 99, 25, step=2)gray_blur = cv2.GaussianBlur(gray, (kernel, kernel), 0)cartoon = cv2.divide(gray, gray_blur, scale= scale_val)
With this slider, you can create an interactive image cartoonization web app, just like Adobe Lightroom. The result of your image cartoonization will be changed and updated in real-time every time you tweak the value of the kernel and other parameters.
We can apply this streamlit.slider() in each of image cartoonization filter we have created above to replace the hard-coded parameter values.
Next, we need to add a widget such that the user can upload their own image that they want to convert into a cartoon. For this purpose, we can use streamlit.file_uploader() function from Streamlit. To add some texts into our web app, we can use streamlit.text() or streamlit.write() function from Streamlit.
After the user have uploaded their image, now we need to display the image, edit the image using one of the image cartoonization filter, and display the cartoonized image so that the user knows whether they want to tweak the slider further. To display the image, we can use streamlit.image() function from Streamlit.
Below is the implementation of how you can build an image cartoonization web app in under 100 lines of code.
Now you can open your Prompt, then head up into the working directory of your Python file which contains the code above. Next, you need to run the code with the following command.
streamlit run your_app_name.py
Finally, you’re able to play around with your image cartoonization web app on your local computer! Below is the sample of the web app.
This section is totally optional, but if you want to deploy your web app such that other people can also access your web app, you can deploy your web app using Heroku.
To deploy your web app to Heroku, the first thing is to create a Heroku account for free and then download the Heroku CLI.
The next thing you need to do is to create four additional files in the same directory as your Python file, which are:
requirements.txt: this is the text file to tell Heroku which dependencies you need to build the web app. Since in our web app we use four different libraries: opencv, numpy , Pillow , and streamlit , then we can write all of these libraries and their versions into requirements.txt
opencv-python==4.3.0.36streamlit==0.63.0Pillow==7.0.0numpy==1.18.1
setup.sh: this is the file to setup your configuration on Heroku. Write the following for this setup.sh file.
mkdir -p ~/.streamlit/ echo "\ [server]\n\ headless = true\n\ port = $PORT\n\ enableCORS = false\n\ \n\ " > ~/.streamlit/config.toml
Procfile: this is the file to tell Heroku which and how the files should be executed. Write the following for the Procfile.
web: sh setup.sh && streamlit run cartoon_app.py
Aptfile: this is the file for Heroku buildpacks to enable OpenCV to operate within Heroku. Write the following for the Aptfile.
libsm6 libxrender1 libfontconfig1 libice6
Next, open your Command Prompt, then heads up to the working directory of your Python file and these four additional files. In it, type heroku login in order for you to be logged into your Heroku account.
Now you can create a new app by typing heroku create your-app-name . To make sure that you’re inside of your newly created app, type the following:
heroku git:remote -a your-app-name
Next, you need to add a buildpack in your newly created app for OpenCV to be able to operate on Heroku. To add the necessary buildpack, type the following on your Heroku CLI.
heroku create --buildpack https://github.com/heroku/heroku-buildpack-apt.git
Now you are set. Next you need to initialize an empty git by typing git init followed by git add ., git commit , and git push heroku master commands.
git initgit add .git commit -m "Add your messages"git push heroku master
After that, the deployment process will begin and it may take some time to wait for this deployment process. At the end, Heroku will generate an URL of your newly deployed web app.
And that’s it! Now you’ve built your own image cartoonization web app that mimicking the functionality of Adobe Lightroom.
You can see the example of the deployed version of this image cartoonization web app here
or you can see the full code of this image cartoonization on my GitHub page. | [
{
"code": null,
"e": 387,
"s": 172,
"text": "As an avid street-photography person who spend almost every weekend wandering around the city to hunt some photos, Adobe Lightroom is always my go-to software to edit my raw photos to make it more “instagrammable”."
},
{
"code": null,
"e": 494,
"s": 387,
"text": "This got me thinking, wouldn’t it be awesome if I can somehow create my own simple image editing software?"
},
{
"code": null,
"e": 776,
"s": 494,
"text": "The emergence of open source computer vision library like OpenCV and open source app framework like Streamlit enables me to realize this idea. With under 100 lines of code, you can build your own image cartooning web app that somehow mimicking the functionality of Adobe Lightroom."
},
{
"code": null,
"e": 940,
"s": 776,
"text": "In this article, I want to show you how to build a simple web app to turn your image into cartoon-like image, depending on the filters, using OpenCV and Streamlit."
},
{
"code": null,
"e": 1063,
"s": 940,
"text": "There are two main steps that we often need to do to convert an image into a cartoon: edge detection and region smoothing."
},
{
"code": null,
"e": 1379,
"s": 1063,
"text": "The main purpose of edge detection is obviously to emphasize the edge of an image, because normally a cartoon image has well-defined edges. Meanwhile, the main purpose of region smoothing is to remove the insignificant color boundaries and to reduce the noise or grain of the image, making the image less pixelated."
},
{
"code": null,
"e": 1521,
"s": 1379,
"text": "Depending on the filters, we can obtain different image cartoonization result. In this article, there are going to be four different filters:"
},
{
"code": null,
"e": 1581,
"s": 1521,
"text": "Pencil SketchDetail EnhancementBilateral FilterPencil Edges"
},
{
"code": null,
"e": 1595,
"s": 1581,
"text": "Pencil Sketch"
},
{
"code": null,
"e": 1614,
"s": 1595,
"text": "Detail Enhancement"
},
{
"code": null,
"e": 1631,
"s": 1614,
"text": "Bilateral Filter"
},
{
"code": null,
"e": 1644,
"s": 1631,
"text": "Pencil Edges"
},
{
"code": null,
"e": 1760,
"s": 1644,
"text": "Next, I want to show you how to apply each filters and what kind of result that you would expect from each of them."
},
{
"code": null,
"e": 1960,
"s": 1760,
"text": "With Pencil Sketch filter, your image will be converted into a sketch as if your image has been drawn using a pencil. Below is the entire code to convert your image into a pencil sketch using OpenCV."
},
{
"code": null,
"e": 2151,
"s": 1960,
"text": "It’s amazing that we can convert our image into a pencil sketch-like picture with only three lines of code using OpenCV. Now let me explain what actually happens with our image line-by-line."
},
{
"code": null,
"e": 2384,
"s": 2151,
"text": "In the first line, we convert our image from color into grayscale with cvtColor() function from OpenCV. I think this is pretty straightforward that the result from this line is that our image turns into its grayscale representation."
},
{
"code": null,
"e": 2618,
"s": 2384,
"text": "Next, we blur the image using Gaussian Blur. By blurring the grayscale image, we are basically smoothing the image, trying to reduce the noise of the image. Plus, blurring is the necessary step for us to detect the edge of the image."
},
{
"code": null,
"e": 2773,
"s": 2618,
"text": "To blur the image, we can use GaussianBlur() function from OpenCV. The (25, 25) that I put in the GaussianBlur() function there is the size of the kernel."
},
{
"code": null,
"e": 3082,
"s": 2773,
"text": "Since we use Gaussian Blur, the distribution of the pixel value in a kernel follows a normal distribution. The larger the number the kernel, the larger the standard deviation would be and hence, the stronger the blurring effect will be. Below is the example of the blurring result with different kernel size."
},
{
"code": null,
"e": 3405,
"s": 3082,
"text": "The final step would be dividing the original grayscale image with the blurred grayscale image. Dividing the image gives us a ratio of change between each pixel of two images. The stronger the blurry effects, the more the value of each pixel changes with respect to its origin and hence, it gives us sharper pencil sketch."
},
{
"code": null,
"e": 3456,
"s": 3405,
"text": "Below is the result of using Pencil Sketch filter."
},
{
"code": null,
"e": 3668,
"s": 3456,
"text": "In short, Detail Enhancement filter gives us a cartoon effect by sharpening the image, smoothing the colors, and enhancing the edges. Below is the entire code to convert your image into cartoon with this filter."
},
{
"code": null,
"e": 3764,
"s": 3668,
"text": "The first step is the same as before, that we need to convert the image into a grayscale image."
},
{
"code": null,
"e": 4092,
"s": 3764,
"text": "Next, instead of using Gaussian Blur, Median Blur is applied. To do this, we use medianBlur() function from OpenCV. Median Blur works by computing the median of pixel values that overlaps with the kernel, and then replacing its central pixel value with the computed median value. However, you can use Gaussian Blur if you wish."
},
{
"code": null,
"e": 4441,
"s": 4092,
"text": "Next, we need to detect the edges of the image. To do this, adaptive threshold is applied with adaptiveThreshold() function from OpenCV. The main goal of adaptive threshold is to convert each pixel values in each region of an image into either completely black or completely white, depending on the mean value of the pixel overlapped by the kernel."
},
{
"code": null,
"e": 4522,
"s": 4441,
"text": "Below is the visualization of what adaptive threshold does to the blurred image."
},
{
"code": null,
"e": 4668,
"s": 4522,
"text": "To make the image looks sharper, we can use detailEnhance() filter from OpenCV. There are two parameters that you need to specify as an argument:"
},
{
"code": null,
"e": 4871,
"s": 4668,
"text": "sigma_s: This controls the size of the neighborhood that the value will be weighted to replace a pixel value in an image. The higher the value, the bigger the neighborhood. This leads to smoother image."
},
{
"code": null,
"e": 5082,
"s": 4871,
"text": "sigma_r: This is important if you want to preserve edges while smoothing the image. Small value yields in only very similar colors to be averaged (i.e. smoothed), while colors that differ much will stay intact."
},
{
"code": null,
"e": 5267,
"s": 5082,
"text": "Finally, we use the result of adaptive threshold as a mask. Then, merge the result of detail enhancement based on the value of the mask to create a sharp effect with well-defined edge."
},
{
"code": null,
"e": 5326,
"s": 5267,
"text": "Below is the example result of Detail Enhancement filters."
},
{
"code": null,
"e": 5552,
"s": 5326,
"text": "One big advantage of using Bilateral Filter is that we can smooth the image and the colors while preserving the edge at the same time. Below is the entire code to convert your image into cartoon-like with bilateral filtering."
},
{
"code": null,
"e": 5760,
"s": 5552,
"text": "If you take a closer look, all of the steps are similar with the one from Detail Enhancement filter, however this time instead of using detailEnhance() function, we use bilateralFilter()function from openCV."
},
{
"code": null,
"e": 6074,
"s": 5760,
"text": "The argument that you need to pass when you call this function is the same as the one with detailEnhance(), with only one additional parameter, which is the kernel size d. First, you need to specify the image source, then d, sigma_s, and sigma_r values that controls the smoothing effect and to preserve the edge."
},
{
"code": null,
"e": 6129,
"s": 6074,
"text": "Below is the result example of using Bilateral Filter."
},
{
"code": null,
"e": 6278,
"s": 6129,
"text": "Pencil Edges filter creates a new image that contains only significant edges and white background. To apply this filter, below is the complete code."
},
{
"code": null,
"e": 6437,
"s": 6278,
"text": "The first two steps are the same as the other filters. First, we convert the image into a grayscale image. Next, we blur the image with the kernel size of 25."
},
{
"code": null,
"e": 6730,
"s": 6437,
"text": "Now what’s different is the next step, in which we apply Laplacian filter to detect the edges. Depending on the size of the kernel, the value in a Laplacian filter can be different. If you want to know more about the value of Laplacian filter with different kernel size, you can read it here."
},
{
"code": null,
"e": 6992,
"s": 6730,
"text": "What Laplacian filter does is that it will emphasize the edge of an object with brighter and darker intensity than the gray-level inside of the object and the background of the image. Below is the example of before and after the application of Laplacian filter."
},
{
"code": null,
"e": 7297,
"s": 6992,
"text": "Next, we invert the result of Laplacian filter so that the darker gray color become brighter and vice versa. Finally, by applying the threshold() function from openCV, we can convert the grayscale image into either completely black or completely white, depending on the threshold value that we specified."
},
{
"code": null,
"e": 7348,
"s": 7297,
"text": "Below is the result example of Pencil Edge filter."
},
{
"code": null,
"e": 7468,
"s": 7348,
"text": "After we created the code for image cartoonization filters, now we are ready to create an image cartoonization web app."
},
{
"code": null,
"e": 7705,
"s": 7468,
"text": "As a first step, we need to put all of the codes for image cartoonization filters we have created into one function for an easy access. Notice that so far, we have hard-coded every parameter values like the size of the kernel and so on."
},
{
"code": null,
"e": 7957,
"s": 7705,
"text": "Now instead of hard-coding every parameter values, we can actually let the user to specify a value based on their preference using a slider. To do this, we can use streamlit.slider() function from Streamlit. Below is the example of its implementation."
},
{
"code": null,
"e": 8370,
"s": 7957,
"text": "gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)scale_val = st.slider('Tune the brightness of your sketch (the higher the value, the brighter your sketch)', 0.0, 300.0, 250.0)kernel = st.slider('Tune the boldness of the edges of your sketch (the higher the value, the bolder the edges)', 1, 99, 25, step=2)gray_blur = cv2.GaussianBlur(gray, (kernel, kernel), 0)cartoon = cv2.divide(gray, gray_blur, scale= scale_val)"
},
{
"code": null,
"e": 8623,
"s": 8370,
"text": "With this slider, you can create an interactive image cartoonization web app, just like Adobe Lightroom. The result of your image cartoonization will be changed and updated in real-time every time you tweak the value of the kernel and other parameters."
},
{
"code": null,
"e": 8765,
"s": 8623,
"text": "We can apply this streamlit.slider() in each of image cartoonization filter we have created above to replace the hard-coded parameter values."
},
{
"code": null,
"e": 9073,
"s": 8765,
"text": "Next, we need to add a widget such that the user can upload their own image that they want to convert into a cartoon. For this purpose, we can use streamlit.file_uploader() function from Streamlit. To add some texts into our web app, we can use streamlit.text() or streamlit.write() function from Streamlit."
},
{
"code": null,
"e": 9390,
"s": 9073,
"text": "After the user have uploaded their image, now we need to display the image, edit the image using one of the image cartoonization filter, and display the cartoonized image so that the user knows whether they want to tweak the slider further. To display the image, we can use streamlit.image() function from Streamlit."
},
{
"code": null,
"e": 9499,
"s": 9390,
"text": "Below is the implementation of how you can build an image cartoonization web app in under 100 lines of code."
},
{
"code": null,
"e": 9679,
"s": 9499,
"text": "Now you can open your Prompt, then head up into the working directory of your Python file which contains the code above. Next, you need to run the code with the following command."
},
{
"code": null,
"e": 9710,
"s": 9679,
"text": "streamlit run your_app_name.py"
},
{
"code": null,
"e": 9845,
"s": 9710,
"text": "Finally, you’re able to play around with your image cartoonization web app on your local computer! Below is the sample of the web app."
},
{
"code": null,
"e": 10013,
"s": 9845,
"text": "This section is totally optional, but if you want to deploy your web app such that other people can also access your web app, you can deploy your web app using Heroku."
},
{
"code": null,
"e": 10136,
"s": 10013,
"text": "To deploy your web app to Heroku, the first thing is to create a Heroku account for free and then download the Heroku CLI."
},
{
"code": null,
"e": 10255,
"s": 10136,
"text": "The next thing you need to do is to create four additional files in the same directory as your Python file, which are:"
},
{
"code": null,
"e": 10537,
"s": 10255,
"text": "requirements.txt: this is the text file to tell Heroku which dependencies you need to build the web app. Since in our web app we use four different libraries: opencv, numpy , Pillow , and streamlit , then we can write all of these libraries and their versions into requirements.txt"
},
{
"code": null,
"e": 10604,
"s": 10537,
"text": "opencv-python==4.3.0.36streamlit==0.63.0Pillow==7.0.0numpy==1.18.1"
},
{
"code": null,
"e": 10714,
"s": 10604,
"text": "setup.sh: this is the file to setup your configuration on Heroku. Write the following for this setup.sh file."
},
{
"code": null,
"e": 11001,
"s": 10714,
"text": "mkdir -p ~/.streamlit/ echo \"\\ [server]\\n\\ headless = true\\n\\ port = $PORT\\n\\ enableCORS = false\\n\\ \\n\\ \" > ~/.streamlit/config.toml"
},
{
"code": null,
"e": 11125,
"s": 11001,
"text": "Procfile: this is the file to tell Heroku which and how the files should be executed. Write the following for the Procfile."
},
{
"code": null,
"e": 11174,
"s": 11125,
"text": "web: sh setup.sh && streamlit run cartoon_app.py"
},
{
"code": null,
"e": 11302,
"s": 11174,
"text": "Aptfile: this is the file for Heroku buildpacks to enable OpenCV to operate within Heroku. Write the following for the Aptfile."
},
{
"code": null,
"e": 11410,
"s": 11302,
"text": "libsm6 libxrender1 libfontconfig1 libice6"
},
{
"code": null,
"e": 11615,
"s": 11410,
"text": "Next, open your Command Prompt, then heads up to the working directory of your Python file and these four additional files. In it, type heroku login in order for you to be logged into your Heroku account."
},
{
"code": null,
"e": 11763,
"s": 11615,
"text": "Now you can create a new app by typing heroku create your-app-name . To make sure that you’re inside of your newly created app, type the following:"
},
{
"code": null,
"e": 11798,
"s": 11763,
"text": "heroku git:remote -a your-app-name"
},
{
"code": null,
"e": 11973,
"s": 11798,
"text": "Next, you need to add a buildpack in your newly created app for OpenCV to be able to operate on Heroku. To add the necessary buildpack, type the following on your Heroku CLI."
},
{
"code": null,
"e": 12050,
"s": 11973,
"text": "heroku create --buildpack https://github.com/heroku/heroku-buildpack-apt.git"
},
{
"code": null,
"e": 12200,
"s": 12050,
"text": "Now you are set. Next you need to initialize an empty git by typing git init followed by git add ., git commit , and git push heroku master commands."
},
{
"code": null,
"e": 12273,
"s": 12200,
"text": "git initgit add .git commit -m \"Add your messages\"git push heroku master"
},
{
"code": null,
"e": 12454,
"s": 12273,
"text": "After that, the deployment process will begin and it may take some time to wait for this deployment process. At the end, Heroku will generate an URL of your newly deployed web app."
},
{
"code": null,
"e": 12577,
"s": 12454,
"text": "And that’s it! Now you’ve built your own image cartoonization web app that mimicking the functionality of Adobe Lightroom."
},
{
"code": null,
"e": 12667,
"s": 12577,
"text": "You can see the example of the deployed version of this image cartoonization web app here"
}
] |
C# program to check if all the values in a list that are greater than a given value | Let’s say you need to find the elements in the following list to be greater than 80.
int[] arr = new int[] {55, 100, 87, 45};
For that, loop until the array length. Here, res = 80 i.e. the given element.
for (int i = 0; i < arr.Length; i++) {
if(arr[i]<res) {
Console.WriteLine(arr[i]);
}
}
The following is the complete code −
using System;
namespace Demo {
public class Program {
public static void Main(string[] args) {
int[] arr = new int[] {
55,
100,
87,
45
};
// given integer
int res = 80;
Console.WriteLine("Given Integer {0}: ", res);
Console.WriteLine("Numbers larger than {0} = ", res);
for (int i = 0; i < arr.Length; i++) {
if (arr[i] > res) {
Console.WriteLine(arr[i]);
}
}
}
}
} | [
{
"code": null,
"e": 1147,
"s": 1062,
"text": "Let’s say you need to find the elements in the following list to be greater than 80."
},
{
"code": null,
"e": 1188,
"s": 1147,
"text": "int[] arr = new int[] {55, 100, 87, 45};"
},
{
"code": null,
"e": 1266,
"s": 1188,
"text": "For that, loop until the array length. Here, res = 80 i.e. the given element."
},
{
"code": null,
"e": 1365,
"s": 1266,
"text": "for (int i = 0; i < arr.Length; i++) {\n if(arr[i]<res) {\n Console.WriteLine(arr[i]);\n }\n}"
},
{
"code": null,
"e": 1402,
"s": 1365,
"text": "The following is the complete code −"
},
{
"code": null,
"e": 1945,
"s": 1402,
"text": "using System;\nnamespace Demo {\n public class Program {\n public static void Main(string[] args) {\n int[] arr = new int[] {\n 55,\n 100,\n 87,\n 45\n };\n // given integer\n int res = 80;\n Console.WriteLine(\"Given Integer {0}: \", res);\n Console.WriteLine(\"Numbers larger than {0} = \", res);\n for (int i = 0; i < arr.Length; i++) {\n if (arr[i] > res) {\n Console.WriteLine(arr[i]);\n }\n }\n }\n }\n}"
}
] |
Calendar setTime() Method in Java with Examples - GeeksforGeeks | 06 Mar, 2019
The setTime(Date dt) method in Calendar class is used to set Calendars time represented by this Calendar’s time value, with the given or passed date as a parameter.
Syntax:
public final void setTime(Date dt))
Parameters: The method takes one parameter dt of Date type and refers to the given date that is to be set.
Return Value: The method does not return any value.
Below programs illustrate the working of setTime() Method of Calendar class:Example 1:
// Java code to illustrate// setTime() method import java.util.*;public class Calendar_Demo extends GregorianCalendar { public static void main(String[] args) { // Creating calendar objects Calendar calndr1 = (Calendar)Calendar.getInstance(); Calendar calndr2 = (Calendar)Calendar.getInstance(); // Displaying the current date System.out.println("The Current" + " System Date: " + calndr1.getTime()); // Setting to a different date calndr1.set(Calendar.MONTH, 5); calndr1.set(Calendar.YEAR, 2006); calndr1.set(Calendar.DAY_OF_WEEK, 15); Date dt = calndr1.getTime(); // Setting the timevalue calndr2.setTime(dt); // Displaying the new date System.out.println("The modified" + " Date:" + calndr2.getTime()); }}
The Current System Date: Fri Feb 22 07:33:13 UTC 2019
The modified Date:Sun Jun 18 07:33:13 UTC 2006
Example 2:
// Java code to illustrate// setTime() method import java.util.*; public class Calendar_Demo extends GregorianCalendar { public static void main(String[] args) { // Creating calendar objects Calendar calndr1 = (Calendar)Calendar.getInstance(); Calendar calndr2 = (Calendar)Calendar.getInstance(); // Displaying the current date System.out.println("The Current" + " System Date: " + calndr1.getTime()); // Setting to a different date calndr1.set(Calendar.MONTH, 10); calndr1.set(Calendar.YEAR, 1995); calndr1.set(Calendar.DAY_OF_WEEK, 20); Date dt = calndr1.getTime(); // Setting the timevalue calndr2.setTime(dt); // Displaying the new date System.out.println("The modified" + " Date: " + calndr2.getTime()); }}
The Current System Date: Fri Feb 22 07:33:20 UTC 2019
The modified Date: Fri Nov 24 07:33:20 UTC 1995
Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime(java.util.Date)
Java - util package
Java-Calendar
Java-Functions
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
How to iterate any Map in Java
Interfaces in Java
Initialize an ArrayList in Java
ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java
LinkedList in Java | [
{
"code": null,
"e": 24149,
"s": 24121,
"text": "\n06 Mar, 2019"
},
{
"code": null,
"e": 24314,
"s": 24149,
"text": "The setTime(Date dt) method in Calendar class is used to set Calendars time represented by this Calendar’s time value, with the given or passed date as a parameter."
},
{
"code": null,
"e": 24322,
"s": 24314,
"text": "Syntax:"
},
{
"code": null,
"e": 24358,
"s": 24322,
"text": "public final void setTime(Date dt))"
},
{
"code": null,
"e": 24465,
"s": 24358,
"text": "Parameters: The method takes one parameter dt of Date type and refers to the given date that is to be set."
},
{
"code": null,
"e": 24517,
"s": 24465,
"text": "Return Value: The method does not return any value."
},
{
"code": null,
"e": 24604,
"s": 24517,
"text": "Below programs illustrate the working of setTime() Method of Calendar class:Example 1:"
},
{
"code": "// Java code to illustrate// setTime() method import java.util.*;public class Calendar_Demo extends GregorianCalendar { public static void main(String[] args) { // Creating calendar objects Calendar calndr1 = (Calendar)Calendar.getInstance(); Calendar calndr2 = (Calendar)Calendar.getInstance(); // Displaying the current date System.out.println(\"The Current\" + \" System Date: \" + calndr1.getTime()); // Setting to a different date calndr1.set(Calendar.MONTH, 5); calndr1.set(Calendar.YEAR, 2006); calndr1.set(Calendar.DAY_OF_WEEK, 15); Date dt = calndr1.getTime(); // Setting the timevalue calndr2.setTime(dt); // Displaying the new date System.out.println(\"The modified\" + \" Date:\" + calndr2.getTime()); }}",
"e": 25558,
"s": 24604,
"text": null
},
{
"code": null,
"e": 25660,
"s": 25558,
"text": "The Current System Date: Fri Feb 22 07:33:13 UTC 2019\nThe modified Date:Sun Jun 18 07:33:13 UTC 2006\n"
},
{
"code": null,
"e": 25671,
"s": 25660,
"text": "Example 2:"
},
{
"code": "// Java code to illustrate// setTime() method import java.util.*; public class Calendar_Demo extends GregorianCalendar { public static void main(String[] args) { // Creating calendar objects Calendar calndr1 = (Calendar)Calendar.getInstance(); Calendar calndr2 = (Calendar)Calendar.getInstance(); // Displaying the current date System.out.println(\"The Current\" + \" System Date: \" + calndr1.getTime()); // Setting to a different date calndr1.set(Calendar.MONTH, 10); calndr1.set(Calendar.YEAR, 1995); calndr1.set(Calendar.DAY_OF_WEEK, 20); Date dt = calndr1.getTime(); // Setting the timevalue calndr2.setTime(dt); // Displaying the new date System.out.println(\"The modified\" + \" Date: \" + calndr2.getTime()); }}",
"e": 26631,
"s": 25671,
"text": null
},
{
"code": null,
"e": 26734,
"s": 26631,
"text": "The Current System Date: Fri Feb 22 07:33:20 UTC 2019\nThe modified Date: Fri Nov 24 07:33:20 UTC 1995\n"
},
{
"code": null,
"e": 26835,
"s": 26734,
"text": "Reference: https://docs.oracle.com/javase/7/docs/api/java/util/Calendar.html#setTime(java.util.Date)"
},
{
"code": null,
"e": 26855,
"s": 26835,
"text": "Java - util package"
},
{
"code": null,
"e": 26869,
"s": 26855,
"text": "Java-Calendar"
},
{
"code": null,
"e": 26884,
"s": 26869,
"text": "Java-Functions"
},
{
"code": null,
"e": 26889,
"s": 26884,
"text": "Java"
},
{
"code": null,
"e": 26894,
"s": 26889,
"text": "Java"
},
{
"code": null,
"e": 26992,
"s": 26894,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27001,
"s": 26992,
"text": "Comments"
},
{
"code": null,
"e": 27014,
"s": 27001,
"text": "Old Comments"
},
{
"code": null,
"e": 27065,
"s": 27014,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 27095,
"s": 27065,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 27126,
"s": 27095,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 27145,
"s": 27126,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 27177,
"s": 27145,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 27195,
"s": 27177,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 27215,
"s": 27195,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 27247,
"s": 27215,
"text": "Multidimensional Arrays in Java"
},
{
"code": null,
"e": 27271,
"s": 27247,
"text": "Singleton Class in Java"
}
] |
JSON with Ajax | AJAX is Asynchronous JavaScript and XML, which is used on the client side as a group of interrelated web development techniques, in order to create asynchronous web applications. According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page.
Many developers use JSON to pass AJAX updates between the client and the server. Websites updating live sports scores can be considered as an example of AJAX. If these scores have to be updated on the website, then they must be stored on the server so that the webpage can retrieve the score when it is required. This is where we can make use of JSON formatted data.
Any data that is updated using AJAX can be stored using the JSON format on the web server. AJAX is used so that javascript can retrieve these JSON files when necessary, parse them, and perform one of the following operations −
Store the parsed values in the variables for further processing before displaying them on the webpage.
Store the parsed values in the variables for further processing before displaying them on the webpage.
It directly assigns the data to the DOM elements in the webpage, so that they are displayed on the website.
It directly assigns the data to the DOM elements in the webpage, so that they are displayed on the website.
The following code shows JSON with AJAX. Save it as ajax.htm file. Here the loading function loadJSON() is used asynchronously to upload JSON data.
<html>
<head>
<meta content = "text/html; charset = ISO-8859-1" http-equiv = "content-type">
<script type = "application/javascript">
function loadJSON() {
var data_file = "http://www.tutorialspoint.com/json/data.json";
var http_request = new XMLHttpRequest();
try{
// Opera 8.0+, Firefox, Chrome, Safari
http_request = new XMLHttpRequest();
}catch (e) {
// Internet Explorer Browsers
try{
http_request = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
http_request = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e) {
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
http_request.onreadystatechange = function() {
if (http_request.readyState == 4 ) {
// Javascript function JSON.parse to parse JSON data
var jsonObj = JSON.parse(http_request.responseText);
// jsonObj variable now contains the data structure and can
// be accessed as jsonObj.name and jsonObj.country.
document.getElementById("Name").innerHTML = jsonObj.name;
document.getElementById("Country").innerHTML = jsonObj.country;
}
}
http_request.open("GET", data_file, true);
http_request.send();
}
</script>
<title>tutorialspoint.com JSON</title>
</head>
<body>
<h1>Cricketer Details</h1>
<table class = "src">
<tr><th>Name</th><th>Country</th></tr>
<tr><td><div id = "Name">Sachin</div></td>
<td><div id = "Country">India</div></td></tr>
</table>
<div class = "central">
<button type = "button" onclick = "loadJSON()">Update Details </button>
</div>
</body>
</html>
Given below is the input file data.json, having data in JSON format which will be uploaded asynchronously when we click the Update Detail button. This file is being kept in http://www.tutorialspoint.com/json/
{"name": "Brett", "country": "Australia"}
The above HTML code will generate the following screen, where you can check AJAX in action −
When you click on the Update Detail button, you should get a result something as follows. You can try JSON with AJAX yourself, provided your browser supports Javascript.
20 Lectures
1 hours
Laurence Svekis
16 Lectures
1 hours
Laurence Svekis
10 Lectures
1 hours
Laurence Svekis
23 Lectures
2.5 hours
Laurence Svekis
9 Lectures
48 mins
Nilay Mehta
18 Lectures
2.5 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2137,
"s": 1780,
"text": "AJAX is Asynchronous JavaScript and XML, which is used on the client side as a group of interrelated web development techniques, in order to create asynchronous web applications. According to the AJAX model, web applications can send and retrieve data from a server asynchronously without interfering with the display and the behavior of the existing page."
},
{
"code": null,
"e": 2504,
"s": 2137,
"text": "Many developers use JSON to pass AJAX updates between the client and the server. Websites updating live sports scores can be considered as an example of AJAX. If these scores have to be updated on the website, then they must be stored on the server so that the webpage can retrieve the score when it is required. This is where we can make use of JSON formatted data."
},
{
"code": null,
"e": 2731,
"s": 2504,
"text": "Any data that is updated using AJAX can be stored using the JSON format on the web server. AJAX is used so that javascript can retrieve these JSON files when necessary, parse them, and perform one of the following operations −"
},
{
"code": null,
"e": 2834,
"s": 2731,
"text": "Store the parsed values in the variables for further processing before displaying them on the webpage."
},
{
"code": null,
"e": 2937,
"s": 2834,
"text": "Store the parsed values in the variables for further processing before displaying them on the webpage."
},
{
"code": null,
"e": 3045,
"s": 2937,
"text": "It directly assigns the data to the DOM elements in the webpage, so that they are displayed on the website."
},
{
"code": null,
"e": 3153,
"s": 3045,
"text": "It directly assigns the data to the DOM elements in the webpage, so that they are displayed on the website."
},
{
"code": null,
"e": 3301,
"s": 3153,
"text": "The following code shows JSON with AJAX. Save it as ajax.htm file. Here the loading function loadJSON() is used asynchronously to upload JSON data."
},
{
"code": null,
"e": 5429,
"s": 3301,
"text": "<html>\n <head>\n <meta content = \"text/html; charset = ISO-8859-1\" http-equiv = \"content-type\">\n\t\t\n <script type = \"application/javascript\">\n function loadJSON() {\n var data_file = \"http://www.tutorialspoint.com/json/data.json\";\n var http_request = new XMLHttpRequest();\n try{\n // Opera 8.0+, Firefox, Chrome, Safari\n http_request = new XMLHttpRequest();\n }catch (e) {\n // Internet Explorer Browsers\n try{\n http_request = new ActiveXObject(\"Msxml2.XMLHTTP\");\n\t\t\t\t\t\n }catch (e) {\n\t\t\t\t\n try{\n http_request = new ActiveXObject(\"Microsoft.XMLHTTP\");\n }catch (e) {\n // Something went wrong\n alert(\"Your browser broke!\");\n return false;\n }\n\t\t\t\t\t\n }\n }\n\t\t\t\n http_request.onreadystatechange = function() {\n\t\t\t\n if (http_request.readyState == 4 ) {\n // Javascript function JSON.parse to parse JSON data\n var jsonObj = JSON.parse(http_request.responseText);\n\n // jsonObj variable now contains the data structure and can\n // be accessed as jsonObj.name and jsonObj.country.\n document.getElementById(\"Name\").innerHTML = jsonObj.name;\n document.getElementById(\"Country\").innerHTML = jsonObj.country;\n }\n }\n\t\t\t\n http_request.open(\"GET\", data_file, true);\n http_request.send();\n }\n\t\t\n </script>\n\t\n <title>tutorialspoint.com JSON</title>\n </head>\n\t\n <body>\n <h1>Cricketer Details</h1>\n\t\t\n <table class = \"src\">\n <tr><th>Name</th><th>Country</th></tr>\n <tr><td><div id = \"Name\">Sachin</div></td>\n <td><div id = \"Country\">India</div></td></tr>\n </table>\n\n <div class = \"central\">\n <button type = \"button\" onclick = \"loadJSON()\">Update Details </button>\n </div>\n\t\t\n </body>\n\t\t\n</html>"
},
{
"code": null,
"e": 5638,
"s": 5429,
"text": "Given below is the input file data.json, having data in JSON format which will be uploaded asynchronously when we click the Update Detail button. This file is being kept in http://www.tutorialspoint.com/json/"
},
{
"code": null,
"e": 5681,
"s": 5638,
"text": "{\"name\": \"Brett\", \"country\": \"Australia\"}\n"
},
{
"code": null,
"e": 5774,
"s": 5681,
"text": "The above HTML code will generate the following screen, where you can check AJAX in action −"
},
{
"code": null,
"e": 5944,
"s": 5774,
"text": "When you click on the Update Detail button, you should get a result something as follows. You can try JSON with AJAX yourself, provided your browser supports Javascript."
},
{
"code": null,
"e": 5977,
"s": 5944,
"text": "\n 20 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 5994,
"s": 5977,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6027,
"s": 5994,
"text": "\n 16 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6044,
"s": 6027,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6077,
"s": 6044,
"text": "\n 10 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6094,
"s": 6077,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6129,
"s": 6094,
"text": "\n 23 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6146,
"s": 6129,
"text": " Laurence Svekis"
},
{
"code": null,
"e": 6177,
"s": 6146,
"text": "\n 9 Lectures \n 48 mins\n"
},
{
"code": null,
"e": 6190,
"s": 6177,
"text": " Nilay Mehta"
},
{
"code": null,
"e": 6225,
"s": 6190,
"text": "\n 18 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 6248,
"s": 6225,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 6255,
"s": 6248,
"text": " Print"
},
{
"code": null,
"e": 6266,
"s": 6255,
"text": " Add Notes"
}
] |
Using Jupyter Notebook in Virtual Environments for Python Data Science Projects | by Christine Egan | Towards Data Science | This blog is part of a series of tutorials called Data in Day. Follow these tutorials to create your first end-to-end data science project in just one day. This is a fun easy project that will teach you the basics of setting up your computer for a data science project and introduce you to some of the most popular tools available. It is a great way to get acquainted with the data science workflow. Check this space for updates about this ongoing project.
In the Creating Virtual Environments for Python Data Science Projects, I explained how to install Pyenv and Virtualenv to manage your Python versions and virtual environments on mac OS Big Sur.
With that scaffolding in place, the next step will be to create a project directory, activate a new environment, and install some popular data science packages, like Pandas, Matplotlib, Seaborn, and Jupyter. Then, we will install a kernelspec so that these libraries will be available to use in Jupyter Notebook.
First, we need to install the desired version of Python. Even though Python is already installed on your computer in multiple locations, Pyenv needs its own copy of the version your project will use. Unless you have a reason to use an older version, the newest stable release is a good place to start.
% pyenv install 3.9.1
In the future, if you would like to use Python 3.9.1 for another environment, there is no need to reinstall it. You will only need to install each version of Python one time to use it.
Now that Pyenv has a copy of the Python version that you wish to use, you can create a virtual environment and assign it to that version.
% pyenv virtualenv 3.9.1 project_env
The syntax is as follows:
% pyenv virtualenv [python version] [environment name]
Next, your project will need a directory. You can create one by entering:
% mkdir project_dir
Enter your directory:
% cd project_dir
Then, assign the virtual environment as the local environment for that directory. Now the environment will open whenever you enter your project directory:
% pyenv local project_env
If you wish to activate this environment somewhere else, you can enter that directory in the terminal and use:
% pyenv activate project_env
The next task is to install popular data science packages with Pip into our virtual environment. This step is important because only the specific package versions that are installed to the environment will run in that environment. Every time you create a new environment, you will have to install all of the packages that you need, even if they have already been installed to another environment.
Right now we are installing:
Pandas — so we can manipulate data
Jupyter, Notebook and Ipykernel — so that we can use Jupyter Notebooks to write, execute and annotate code
Matplotlib and Seaborn for data visualizations.
Inside of your project directory, you can start the installation with Pip:
% pip install pandas jupyter notebook ipykernal matplotlib seaborn
Now, you will be able to use these packages within this environment.
Jupyter notebooks are an interactive environment where you can write and execute Python code, as well as add markdown cells to explain your methods and code. We are going to use Ipykernel to link our virtual environment to Jupyter so that we can easily use that environment in a notebook.
A kernelspec is a is a JSON file within ~/Library/Jupyter /kernels directory that was installed when you installed Jupyter. In the kernels directory is a folder for each virtual environment that you have installed. Inside each of those folders is kernel.json.
If you open up it up, it looks like this:
To create a kernelspec for your virtual environment, enter the following in your project folder and make sure the environment is activated when you do it:
% python -m ipykernel install --user --name myenv --display-name "Python (myenv)"
Lets break down the syntax:
python: indicates the command should be executed by Python
-m : an option that means run the module as a program
ipykernel: the module to run
install: instructs ipykernel
— user: indicates that it should be installed in the directory of the current user
— name my_project_env: assigns “my_project_env” as the name of the kernelspec directory
— display-name "Python (myenv)": assigns the name that will be displayed in Jupyter to represent the environment.
If this plan worked, the terminal should display something like this:
Installed kernelspec my_project_env in /Users/myusername/Library/Jupyter/kernels/my_project_env
With your kernelspec installed, we can open Jupyter Notebook and use our new environment.
% jupyter notebook
This launches Jupyter Notebook. Your project directory will be displayed in your browser. In the top right corner, you’ll see a drop down menu that says ‘New’. Click the button and select the drop down to see a list of virtual environments with an installed kernelspec. Click on the display name for your new environment to open a new notebook.
Let’s test the notebook out and make sure our preliminary package installations were successful by trying to import them into our notebook.
Type the import statement into the first cell to import any packages that are available in the selected environment for use in the notebook.
import pandas
If the notebook did not output an error message, the installation has been a success! Now you can start coding your project. If you did get an error message, I suggest carefully reading the first and second tutorials in this series, just to make sure that you did not miss a step.
1. Created a new virtual environment that activates when we open our project directory with Pyenv and Virtualenv.2. Installed popular data science packages Pandas, Jupyter, Notebook, Ipykernel, Matplotlib, and Seaborn.3. Generated a kernelspec for Ipykernel to link our environment to our notebooks.4. Used Terminal to open a Jupyter Notebook directory in our browser.
5. Created a new notebook that will use our new virtual environment.
6. Learned the import statement to import Pandas and check the installation.
Hi. I’m Christine. A relentlessly curious data scientist with a degree in linguistics and an interest in natural language processing.
📅 Data in a Day 📰 christineegan42.medium.com/ 📫 How to reach me: 📧 [email protected] | [
{
"code": null,
"e": 628,
"s": 171,
"text": "This blog is part of a series of tutorials called Data in Day. Follow these tutorials to create your first end-to-end data science project in just one day. This is a fun easy project that will teach you the basics of setting up your computer for a data science project and introduce you to some of the most popular tools available. It is a great way to get acquainted with the data science workflow. Check this space for updates about this ongoing project."
},
{
"code": null,
"e": 822,
"s": 628,
"text": "In the Creating Virtual Environments for Python Data Science Projects, I explained how to install Pyenv and Virtualenv to manage your Python versions and virtual environments on mac OS Big Sur."
},
{
"code": null,
"e": 1135,
"s": 822,
"text": "With that scaffolding in place, the next step will be to create a project directory, activate a new environment, and install some popular data science packages, like Pandas, Matplotlib, Seaborn, and Jupyter. Then, we will install a kernelspec so that these libraries will be available to use in Jupyter Notebook."
},
{
"code": null,
"e": 1437,
"s": 1135,
"text": "First, we need to install the desired version of Python. Even though Python is already installed on your computer in multiple locations, Pyenv needs its own copy of the version your project will use. Unless you have a reason to use an older version, the newest stable release is a good place to start."
},
{
"code": null,
"e": 1459,
"s": 1437,
"text": "% pyenv install 3.9.1"
},
{
"code": null,
"e": 1644,
"s": 1459,
"text": "In the future, if you would like to use Python 3.9.1 for another environment, there is no need to reinstall it. You will only need to install each version of Python one time to use it."
},
{
"code": null,
"e": 1782,
"s": 1644,
"text": "Now that Pyenv has a copy of the Python version that you wish to use, you can create a virtual environment and assign it to that version."
},
{
"code": null,
"e": 1819,
"s": 1782,
"text": "% pyenv virtualenv 3.9.1 project_env"
},
{
"code": null,
"e": 1845,
"s": 1819,
"text": "The syntax is as follows:"
},
{
"code": null,
"e": 1900,
"s": 1845,
"text": "% pyenv virtualenv [python version] [environment name]"
},
{
"code": null,
"e": 1974,
"s": 1900,
"text": "Next, your project will need a directory. You can create one by entering:"
},
{
"code": null,
"e": 1994,
"s": 1974,
"text": "% mkdir project_dir"
},
{
"code": null,
"e": 2016,
"s": 1994,
"text": "Enter your directory:"
},
{
"code": null,
"e": 2033,
"s": 2016,
"text": "% cd project_dir"
},
{
"code": null,
"e": 2188,
"s": 2033,
"text": "Then, assign the virtual environment as the local environment for that directory. Now the environment will open whenever you enter your project directory:"
},
{
"code": null,
"e": 2214,
"s": 2188,
"text": "% pyenv local project_env"
},
{
"code": null,
"e": 2325,
"s": 2214,
"text": "If you wish to activate this environment somewhere else, you can enter that directory in the terminal and use:"
},
{
"code": null,
"e": 2354,
"s": 2325,
"text": "% pyenv activate project_env"
},
{
"code": null,
"e": 2751,
"s": 2354,
"text": "The next task is to install popular data science packages with Pip into our virtual environment. This step is important because only the specific package versions that are installed to the environment will run in that environment. Every time you create a new environment, you will have to install all of the packages that you need, even if they have already been installed to another environment."
},
{
"code": null,
"e": 2780,
"s": 2751,
"text": "Right now we are installing:"
},
{
"code": null,
"e": 2815,
"s": 2780,
"text": "Pandas — so we can manipulate data"
},
{
"code": null,
"e": 2922,
"s": 2815,
"text": "Jupyter, Notebook and Ipykernel — so that we can use Jupyter Notebooks to write, execute and annotate code"
},
{
"code": null,
"e": 2970,
"s": 2922,
"text": "Matplotlib and Seaborn for data visualizations."
},
{
"code": null,
"e": 3045,
"s": 2970,
"text": "Inside of your project directory, you can start the installation with Pip:"
},
{
"code": null,
"e": 3112,
"s": 3045,
"text": "% pip install pandas jupyter notebook ipykernal matplotlib seaborn"
},
{
"code": null,
"e": 3181,
"s": 3112,
"text": "Now, you will be able to use these packages within this environment."
},
{
"code": null,
"e": 3470,
"s": 3181,
"text": "Jupyter notebooks are an interactive environment where you can write and execute Python code, as well as add markdown cells to explain your methods and code. We are going to use Ipykernel to link our virtual environment to Jupyter so that we can easily use that environment in a notebook."
},
{
"code": null,
"e": 3730,
"s": 3470,
"text": "A kernelspec is a is a JSON file within ~/Library/Jupyter /kernels directory that was installed when you installed Jupyter. In the kernels directory is a folder for each virtual environment that you have installed. Inside each of those folders is kernel.json."
},
{
"code": null,
"e": 3772,
"s": 3730,
"text": "If you open up it up, it looks like this:"
},
{
"code": null,
"e": 3927,
"s": 3772,
"text": "To create a kernelspec for your virtual environment, enter the following in your project folder and make sure the environment is activated when you do it:"
},
{
"code": null,
"e": 4009,
"s": 3927,
"text": "% python -m ipykernel install --user --name myenv --display-name \"Python (myenv)\""
},
{
"code": null,
"e": 4037,
"s": 4009,
"text": "Lets break down the syntax:"
},
{
"code": null,
"e": 4096,
"s": 4037,
"text": "python: indicates the command should be executed by Python"
},
{
"code": null,
"e": 4150,
"s": 4096,
"text": "-m : an option that means run the module as a program"
},
{
"code": null,
"e": 4179,
"s": 4150,
"text": "ipykernel: the module to run"
},
{
"code": null,
"e": 4208,
"s": 4179,
"text": "install: instructs ipykernel"
},
{
"code": null,
"e": 4291,
"s": 4208,
"text": "— user: indicates that it should be installed in the directory of the current user"
},
{
"code": null,
"e": 4379,
"s": 4291,
"text": "— name my_project_env: assigns “my_project_env” as the name of the kernelspec directory"
},
{
"code": null,
"e": 4493,
"s": 4379,
"text": "— display-name \"Python (myenv)\": assigns the name that will be displayed in Jupyter to represent the environment."
},
{
"code": null,
"e": 4563,
"s": 4493,
"text": "If this plan worked, the terminal should display something like this:"
},
{
"code": null,
"e": 4659,
"s": 4563,
"text": "Installed kernelspec my_project_env in /Users/myusername/Library/Jupyter/kernels/my_project_env"
},
{
"code": null,
"e": 4749,
"s": 4659,
"text": "With your kernelspec installed, we can open Jupyter Notebook and use our new environment."
},
{
"code": null,
"e": 4768,
"s": 4749,
"text": "% jupyter notebook"
},
{
"code": null,
"e": 5113,
"s": 4768,
"text": "This launches Jupyter Notebook. Your project directory will be displayed in your browser. In the top right corner, you’ll see a drop down menu that says ‘New’. Click the button and select the drop down to see a list of virtual environments with an installed kernelspec. Click on the display name for your new environment to open a new notebook."
},
{
"code": null,
"e": 5253,
"s": 5113,
"text": "Let’s test the notebook out and make sure our preliminary package installations were successful by trying to import them into our notebook."
},
{
"code": null,
"e": 5394,
"s": 5253,
"text": "Type the import statement into the first cell to import any packages that are available in the selected environment for use in the notebook."
},
{
"code": null,
"e": 5408,
"s": 5394,
"text": "import pandas"
},
{
"code": null,
"e": 5689,
"s": 5408,
"text": "If the notebook did not output an error message, the installation has been a success! Now you can start coding your project. If you did get an error message, I suggest carefully reading the first and second tutorials in this series, just to make sure that you did not miss a step."
},
{
"code": null,
"e": 6058,
"s": 5689,
"text": "1. Created a new virtual environment that activates when we open our project directory with Pyenv and Virtualenv.2. Installed popular data science packages Pandas, Jupyter, Notebook, Ipykernel, Matplotlib, and Seaborn.3. Generated a kernelspec for Ipykernel to link our environment to our notebooks.4. Used Terminal to open a Jupyter Notebook directory in our browser."
},
{
"code": null,
"e": 6127,
"s": 6058,
"text": "5. Created a new notebook that will use our new virtual environment."
},
{
"code": null,
"e": 6204,
"s": 6127,
"text": "6. Learned the import statement to import Pandas and check the installation."
},
{
"code": null,
"e": 6338,
"s": 6204,
"text": "Hi. I’m Christine. A relentlessly curious data scientist with a degree in linguistics and an interest in natural language processing."
}
] |
Powershell - Regular Expression - Match Quantifiers | Following is the example of supported quantifiers in Windows PowerShell
#Format: *
#Logic Specifies zero or more matches; for example, \wor (abc). Equivalent
# to {0,}.
"abc" -match "\w*"
#Format: +
#Logic: Matches repeating instances of the preceding characters.
"xyxyxy" -match "xy+"
#Format: ?
#Logic: Specifies zero or one matches; for example, \w? or (abc)?.
# Equivalent to {0,1}.
"abc" -match "\w?"
#Format: {n}
#Logic: Specifies exactly n matches; for example, (pizza){2}.
"abc" -match "\w{2}"
#Format: {n,}
#Logic: Specifies at least n matches; for example, (abc){2,}.
"abc" -match "\w{2,}"
#Format: {n,m}
#Logic: Specifies at least n, but no more than m, matches.
"abc" -match "\w{2,3}"
Output of all the above commands is True.
15 Lectures
3.5 hours
Fabrice Chrzanowski
35 Lectures
2.5 hours
Vijay Saini
145 Lectures
12.5 hours
Fettah Ben
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2106,
"s": 2034,
"text": "Following is the example of supported quantifiers in Windows PowerShell"
},
{
"code": null,
"e": 2777,
"s": 2106,
"text": "#Format: *\n#Logic Specifies zero or more matches; for example, \\wor (abc). Equivalent\n# to {0,}.\n \"abc\" -match \"\\w*\"\n\n#Format: +\n#Logic: Matches repeating instances of the preceding characters.\n \"xyxyxy\" -match \"xy+\"\n\n#Format: ?\n#Logic: Specifies zero or one matches; for example, \\w? or (abc)?.\n# Equivalent to {0,1}.\n \"abc\" -match \"\\w?\"\n\n#Format: {n}\n#Logic: Specifies exactly n matches; for example, (pizza){2}.\n \"abc\" -match \"\\w{2}\"\n\n#Format: {n,}\n#Logic: Specifies at least n matches; for example, (abc){2,}.\n \"abc\" -match \"\\w{2,}\"\n\n#Format: {n,m}\n#Logic: Specifies at least n, but no more than m, matches.\n \"abc\" -match \"\\w{2,3}\""
},
{
"code": null,
"e": 2819,
"s": 2777,
"text": "Output of all the above commands is True."
},
{
"code": null,
"e": 2854,
"s": 2819,
"text": "\n 15 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 2875,
"s": 2854,
"text": " Fabrice Chrzanowski"
},
{
"code": null,
"e": 2910,
"s": 2875,
"text": "\n 35 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 2923,
"s": 2910,
"text": " Vijay Saini"
},
{
"code": null,
"e": 2960,
"s": 2923,
"text": "\n 145 Lectures \n 12.5 hours \n"
},
{
"code": null,
"e": 2972,
"s": 2960,
"text": " Fettah Ben"
},
{
"code": null,
"e": 2979,
"s": 2972,
"text": " Print"
},
{
"code": null,
"e": 2990,
"s": 2979,
"text": " Add Notes"
}
] |
Calculate interest amount by using formula in C language | Write a C program to calculate the deposited amount incremented after some years with interest
The formula for calculating interest is −
M=((r/100) * t);
A=P*exp(M);
Where r= rate of interest
t=no. of years
P=amount to be deposited
M=temporary variable
A= Final amount after interest
START
Step 1: declare double variables
Step 2: read amount to be deposited
Step 3: read rate of interest
Step 4: read years you want to deposit
Step 5: Calculate final amount with interest
I. M=((r/100) * t);
II. A=P*exp(M);
Step 6: Print final amount
STOP
#include<stdio.h>
#include<math.h>
#include<ctype.h>
int main(){
double P,r,t,A,M;
printf("amount to be deposit in the bank: ");
scanf("%lf",&P);
printf("\n enter the rate of interest:");
scanf("%lf",&r);
printf("\n How many years you want to deposit:");
scanf("%lf",&t);
M=((r/100) * t);
A=P*exp(M);
printf("\n amount after %0.1lf years with interest is:%0.2lf",t,A);
return 0;
}
amount to be deposit in the bank: 50000
enter the rate of interest:6.5
How many years you want to deposit:5
amount after 5.0 years with interest is:69201.53 | [
{
"code": null,
"e": 1157,
"s": 1062,
"text": "Write a C program to calculate the deposited amount incremented after some years with interest"
},
{
"code": null,
"e": 1199,
"s": 1157,
"text": "The formula for calculating interest is −"
},
{
"code": null,
"e": 1228,
"s": 1199,
"text": "M=((r/100) * t);\nA=P*exp(M);"
},
{
"code": null,
"e": 1254,
"s": 1228,
"text": "Where r= rate of interest"
},
{
"code": null,
"e": 1281,
"s": 1254,
"text": " t=no. of years"
},
{
"code": null,
"e": 1318,
"s": 1281,
"text": " P=amount to be deposited"
},
{
"code": null,
"e": 1351,
"s": 1318,
"text": " M=temporary variable"
},
{
"code": null,
"e": 1394,
"s": 1351,
"text": " A= Final amount after interest"
},
{
"code": null,
"e": 1669,
"s": 1394,
"text": "START\nStep 1: declare double variables\nStep 2: read amount to be deposited\nStep 3: read rate of interest\nStep 4: read years you want to deposit\nStep 5: Calculate final amount with interest\n I. M=((r/100) * t);\n II. A=P*exp(M);\nStep 6: Print final amount\nSTOP"
},
{
"code": null,
"e": 2083,
"s": 1669,
"text": "#include<stdio.h>\n#include<math.h>\n#include<ctype.h>\nint main(){\n double P,r,t,A,M;\n printf(\"amount to be deposit in the bank: \");\n scanf(\"%lf\",&P);\n printf(\"\\n enter the rate of interest:\");\n scanf(\"%lf\",&r);\n printf(\"\\n How many years you want to deposit:\");\n scanf(\"%lf\",&t);\n M=((r/100) * t);\n A=P*exp(M);\n printf(\"\\n amount after %0.1lf years with interest is:%0.2lf\",t,A);\n return 0;\n}"
},
{
"code": null,
"e": 2240,
"s": 2083,
"text": "amount to be deposit in the bank: 50000\nenter the rate of interest:6.5\nHow many years you want to deposit:5\namount after 5.0 years with interest is:69201.53"
}
] |
How to list out the hidden files in a Directory using Java program? | The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories.
The isHidden() method of the File class verifies weather the (abstract path of) file/directory represented by the current File object, is hidden.
The ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object.
Therefore, to list all the hidden files in a directory get all the file objects using the ListFiles() method, verify weather each file is hidden using the isHidden() method.
Following Java program prints the file name and path of all the hidden files and directories in the specified directory −
import java.io.File;
public class ListingHiddenDirectories {
public static void main(String args[]) {
String filePath = "D://ExampleDirectory//";
//Creating the File object
File directory = new File(filePath);
//List of all files and directories
File filesList[] = directory.listFiles();
System.out.println("List of files and directories in the specified directory:");
for(File file : filesList) {
if(file.isHidden()) {
System.out.println("File name: "+file.getName());
System.out.println("File path: "+file.getAbsolutePath());
}
}
}
}
List of files and directories in the specified directory:
File name: hidden_directory1
File path: D:\ExampleDirectory\hidden_directory1
File name: hidden_directory2
File path: D:\ExampleDirectory\hidden_directory2
File name: SampleHiddenfile1.txt
File path: D:\ExampleDirectory\SampleHiddenfile1.txt
File name: SampleHiddenfile2.txt
File path: D:\ExampleDirectory\SampleHiddenfile2.txt
File name: SampleHiddenfile3.txt
File path: D:\ExampleDirectory\SampleHiddenfile3.txt | [
{
"code": null,
"e": 1253,
"s": 1062,
"text": "The class named File of the java.io package represents a file or directory (path names) in the system. This class provides various methods to perform various operations on files/directories."
},
{
"code": null,
"e": 1399,
"s": 1253,
"text": "The isHidden() method of the File class verifies weather the (abstract path of) file/directory represented by the current File object, is hidden."
},
{
"code": null,
"e": 1583,
"s": 1399,
"text": "The ListFiles() method of the File class returns an array holding the objects (abstract paths) of all the files (and directories) in the path represented by the current (File) object."
},
{
"code": null,
"e": 1757,
"s": 1583,
"text": "Therefore, to list all the hidden files in a directory get all the file objects using the ListFiles() method, verify weather each file is hidden using the isHidden() method."
},
{
"code": null,
"e": 1879,
"s": 1757,
"text": "Following Java program prints the file name and path of all the hidden files and directories in the specified directory −"
},
{
"code": null,
"e": 2511,
"s": 1879,
"text": "import java.io.File;\npublic class ListingHiddenDirectories {\n public static void main(String args[]) {\n String filePath = \"D://ExampleDirectory//\";\n //Creating the File object\n File directory = new File(filePath);\n //List of all files and directories\n File filesList[] = directory.listFiles();\n System.out.println(\"List of files and directories in the specified directory:\");\n for(File file : filesList) {\n if(file.isHidden()) {\n System.out.println(\"File name: \"+file.getName());\n System.out.println(\"File path: \"+file.getAbsolutePath());\n }\n }\n }\n}"
},
{
"code": null,
"e": 2983,
"s": 2511,
"text": "List of files and directories in the specified directory:\nFile name: hidden_directory1\nFile path: D:\\ExampleDirectory\\hidden_directory1\nFile name: hidden_directory2\nFile path: D:\\ExampleDirectory\\hidden_directory2\nFile name: SampleHiddenfile1.txt\nFile path: D:\\ExampleDirectory\\SampleHiddenfile1.txt\nFile name: SampleHiddenfile2.txt\nFile path: D:\\ExampleDirectory\\SampleHiddenfile2.txt\nFile name: SampleHiddenfile3.txt\nFile path: D:\\ExampleDirectory\\SampleHiddenfile3.txt"
}
] |
Full Stack Deep Learning Steps and Tools | by Haryo Akbarianto Wibowo | Towards Data Science | Hi everyone, How’s everything? Today, I’m going to write article about what I have learned from seeing the Full Stack Deep Learning (FSDL) March 2019 courses. It is a great online courses that tell us to do project with Full Stack Deep Learning. What I love the most is how they teach us a project and teach us not only how to create the Deep Learning architecture, but tell us the Software Engineering stuffs that should be concerned when doing project about Deep Learning.
When we do a Deep Learning project, we need to know what are the steps and technology that we should use. We need to know these to enhance the quality of the project. This will be useful especially when we want to do the project in a team. We do not want the project become messy when the team collaborates.
This article will focus on the tools and what to do in every steps of a full stack Deep Learning project according to FSDL course (plus a few addition about the tools that I know). There will be a brief description what to do on each steps. This article will only show the tools that I lay my eyes on in that course. Programming language that will be focused in this article is Python.
UPDATE 12 July 2020: Full Stack Deep Learning Course can be accessed here https://course.fullstackdeeplearning.com/ . Check it out :).
StepsPlanning and Project SetupData Collection and LabelingCodebase DevelopmentTraining and DebuggingDeploymentConclusionAfterwords
Steps
Planning and Project Setup
Data Collection and Labeling
Codebase Development
Training and Debugging
Deployment
Conclusion
Afterwords
These are the steps that FSDL course tell us:
Planning and Project SetupData Collection and LabelingTraining and DebuggingDeploying and Testing
Planning and Project Setup
Data Collection and Labeling
Training and Debugging
Deploying and Testing
Where each of the steps can be done which can come back to previous step or forth (not waterfall). The course also suggest that we do the process iteratively, meaning that we start from small progress and increase it continuously. For example, we start using simple model with small data then improve it as time goes by.
This step will be the first step that you will do. We need to state what the project going to make and the goal of the project. We also need to state the metric and baseline of the project. The substeps of this step are as follow:
First, we need to define what is the project is going to make. There are two consideration on picking what to make. They are are Impact and Feasibility.
We need to make sure that the project is Impactful. What are the values of your application that we want to make in the project. Two questions that you need to answer are
Where can you take advantages of cheap prediction ?Where can you automate complicated manual software pipeline ?
Where can you take advantages of cheap prediction ?
Where can you automate complicated manual software pipeline ?
Where for cheap prediction produced by our chosen application that we want to make, we can produce great value which can reduce the cost of other tasks.
Feasibility is also thing that we need to watch out. Since Deep Learning focus on data, We need to make sure that the data is available and fit to the project requirement and cost budget.
We need to consider the accuracy requirement where we need to set the minimum target. Since the project costs will tend to correlate super linearly with the project costs, again, we need to considerate our requirement and maximum cost that we tolerate. Also consider that there might be some cases where it is not important to fail the prediction and some cases where the model must have a low error as possible.
Finally, we need to see the problem difficulty. How hard is the project is. To measure the difficulty, we can see some published works on similar problem. For example, search some papers in ARXIV or any conferences that have similar problem with the project. With these, we can grasp the difficulty of the project.
See Figure 4 for more detail on assessing the feasibility of the project.
Metric is a measurement of particular characteristic of the performance or efficiency of the system.
Since system in Machine Learning work best on optimizing a single number , we need to define a metric which satisfy the requirement with a single number even there might be a lot of metrics that should be calculated. For a problem where there are a lot of metrics that we need to use, we need to pick a formula for combining these metrics. There are:
Simple average / weighted averageThreshold n-1 metrics, evaluate the nth metricDomain specific formula (for example mAP)
Simple average / weighted average
Threshold n-1 metrics, evaluate the nth metric
Domain specific formula (for example mAP)
Here are some example how to combine two metrics (Precision and Recall):
After we choose the metric, we need to choose our baseline. Baseline is an expected value or condition which the performance will be measured to be compared to our work. It will give us a lower bound on a expected model performance. The tighter the baseline is the more useful the baseline is.
So why is the baseline is important? Why not skip this step ? We can measure our model how good it is by comparing to the baseline. By knowing how good or bad the model is, we can choose our next move on what to tweak.
To look for the baseline, there are several sources that you can use:
External baseline , where you form the baseline from the business or engineering requirement. You can also use published work results as the baseline.Internal baseline , Use scripted baseline or create simple Machine Learning (ML) model such as using standard feature based word or using simple model.
External baseline , where you form the baseline from the business or engineering requirement. You can also use published work results as the baseline.
Internal baseline , Use scripted baseline or create simple Machine Learning (ML) model such as using standard feature based word or using simple model.
The baseline is chosen according to your need. For example if you want a system that surpass human, you need to add a human baseline.
Create your codebase that will be the core how to do the further steps. The source code in the codebase can be developed according to the current need of what the project currently going to do. For example, if the current step is collecting the data, we will write the code used to collect the data (if needed). We will mostly go to this step back and forth.
We should make sure that the source code in the codebase is reproducible and scalable, especially for doing the project in a group. To make it happen, you need to use the right tools. This article will tell us about it later.
After we define what we are going to create, baseline, and metrics in the project, the most painful of the step will begin, data collection and labeling.
Most of Deep Learning applications will require a lot of data which need to be labeled. Time will be mostly consumed in this process. Although you can also use public dataset, often that labeled dataset needed for our project is not available publicly.
Here is the substeps:
We need to plan how to obtain the complete dataset. There are multiple ways to obtain the data. One that you should be considered that the data need to align according to what we want to create in the project.
If the strategy to obtain data is through the internet by scraping and crawling some websites, we need to use some tools to do it. Scrapy is one of the tool that can be helpful for the project
Scrapy
This is a Python scrapper and data crawler library that can be used to scrap and crawl websites. It can be used to collect data such as images and texts on the websites. We can also scrap images from Bing, Google, or Instagram with this. To use this library, we need to learn from the tutorial that is also available in its website. Do not worry, it is not hard to learn.
After we collect the data, the next problem that you need to think is where to send your collected data. Since you are doing the project not alone, you need to make sure that the data can be accessed by everyone. Also, we need to choose the format of the data which will be saved. Below is a solution when we want to save our data in cloud.
Object Storage
For storing your binary data such as images and videos, You can use cloud storage such as AmazonS3 or GCP to build the object storage with API over the file system. We can also built versioning into the service. See their website for more detail. You need to pay to use it (there is also a free plan).
Database
Database is used for persistent, fast, scalable storage, and retrieval of structured data. Database is used to save the data that often will be accessed continuously which is not binary data. You will save the metadata (labels, user activity) here. There are some tools that you can use. One that is recommended is PostgresSQl.
It can store structured SQL database and also can be used to save unstructured json data. It is still actively maintaned.
Data Lake
When you have data which is the unstructured aggregation from multiple source and multiple format which has high cost transformation, you can use data lake. Basically, you dump every data on it and it will transform it into specific needs.
Amazon Redshift is one of cannonical solution to the Data Lake.
When we are doing the training process, we need to move the data that is needed for your model to your file system.
The data should be versioned to make sure the progress can be revertible. The version control does not only apply to the source code, it also apply to the data. We will dive into data version control after we talk about Data Labeling.
In this section, we will know how to label the data. There are source of labors that you can use to label the data:
Hire annotators by yourselfCrowdsource (Mechanical Turk)Use full-service data labeling companies such as FigureEight, Scale.ai, and LabelBox
Hire annotators by yourself
Crowdsource (Mechanical Turk)
Use full-service data labeling companies such as FigureEight, Scale.ai, and LabelBox
If you want the team to annotate it , Here are several tools that you can use:
Dataturks
Online Collaboration Annotation tool , Data Turks. For the free plan, it is limited to 10000 annotations and the data must be public. It offers several annotation tools for several tasks on NLP (Sequence tagging, classification, etc) and Computer Vision (Image segmentation, Image bounding box, classification, etc). The FSDL course uses this as the tool for labeling.
doccano
Free open source Annotation tool for NLP tasks. It also support sequence tagging, classification, and machine translation tasks. Can also be set up as a collaborative annotation tools, but it need a server.
CVAT
Offline annotation tool for Computer Vision tasks. It is released by Intel as Open Source. It can label bounding boxes and image segmentations.
If you want to search any public datasets, see this article created by Stacy Stanford for to know any list of public dataset.
medium.com
It is still actively been updated and maintaned.
There are level on how to do data versioning :
Level 0 : Unversioned. We should not attempt this. Deployment need to be versioned. If the data is not versioned, the deployed models are also not versioned. There will be a problem if we use unversioned one, which is inability to get back to previous result.Level 1 : Versioned via snapshot. We store all of the data used on different version. Which we could say that it is a bit hacky. We still need to version data as easy as version the codeLevel 2 : Data is versioned as a mix of code and assets. The heavy files will be stored in other server (such as Amazon S3) where there is a JSON or similar type as reference of the relevant metadata. The relevant metadata can contains labels, user activity, and etc. The JSON file will be versioned. The JSON files can become big. To make it easier, we can use git-lfs to version it. This level should be acceptable to do the project.Level 3 : Use specialized software solution for versioning the data. If you think that level 2 is not enough for your project, you can do this. One of tool for data versioning is DVC.
Level 0 : Unversioned. We should not attempt this. Deployment need to be versioned. If the data is not versioned, the deployed models are also not versioned. There will be a problem if we use unversioned one, which is inability to get back to previous result.
Level 1 : Versioned via snapshot. We store all of the data used on different version. Which we could say that it is a bit hacky. We still need to version data as easy as version the code
Level 2 : Data is versioned as a mix of code and assets. The heavy files will be stored in other server (such as Amazon S3) where there is a JSON or similar type as reference of the relevant metadata. The relevant metadata can contains labels, user activity, and etc. The JSON file will be versioned. The JSON files can become big. To make it easier, we can use git-lfs to version it. This level should be acceptable to do the project.
Level 3 : Use specialized software solution for versioning the data. If you think that level 2 is not enough for your project, you can do this. One of tool for data versioning is DVC.
DVC
DVC is built to make ML models shareable and reproducible. It is designed to handle large files, data sets, machine learning models, and metrics as well as code. It is a solution for versioning ML models with its dataset. We can connect the version control into the cloud storage such as Amazon S3 and GCP.
When we do the project, expect to write codebase on doing every steps. Reproducibility is one thing that we must concern when writing the code. we need to make sure that our codebase has reproducibility on it.
Before we dive into tools, we need to choose the language and framework of our codebase.
For choosing programming language, I prefer Python over anything else. Python has the largest community for data science and great to develop. The popular Deep Learning software also mostly supported by Python. The language is also easy to learn.
There are several choices that you can made for the Deep Learning Framework. The most popular framework in Python are Tensorflow, Keras, and PyTorch. Use the one that you like.
For easier debugging, you can use PyTorch as the Deep Learning Framework. Keras is also easy to use and have good UX. It is a wrapper of Tensorflow, Theano and other Deep Learning framework and make it easier to use. Tensorflow is also a choice if you like their environment. Tensorflow can be wise decision because of the support of its community and have great tools for deployment.
Do not worry about the deployment. There is exists a software that can convert the model format to another format. For example, you can convert the model that is produced by Pytorch to Tensorflow. We will see this later.
I think the factor of choosing the language and framework is how active the community behind it. Since it will give birth of high number of custom package that can be integrated into it.
One of the important things when doing the project is version control. When we do the project, we don’t want the inability to redo our code base when someone accidentally wreck it. We also need to keep track the code on each update to see what are the changes updated by someone else. This will not be possible if we do not use some tools do it. Git is one of the solution to do it.
Okay, we know that version control is important, especially on doing collaboration work. Currently, git is one of the best solution to do version control. It also be used to share your code to other people in your team. Without this, I don’t think that you can collaborate well with others in the project.
There are several services that you can use that use Git such as GitHub, BitBucket, and GitLab.
There is also important thing that should be done, which is Code Review. Code reviews are an early protection against incorrect code or bad quality code which pass the unit or integration tests. When you do collaboration, make someone check your code and review it. Most of the version control services should support this feature.
When we first create the project structure folder, we must be wondering how to create the folder structure. Then, we give up and put all the code in the root project folder. It’s a bad practice that give bad quality code.
One of the solution that I found is cookiecutter-data-science. It give a template how should we create the project structure. It also give how to give a name to the created file and where you should put it. Be sure to use it to make your codebase not become messy. Consider reading the website to use it.
IDE is one of the tools that you can use to accelerate to write the code. It has integrated tools which can be useful for developing. There are several IDEs that you can use:
Pycharm
IDE that is released by JetBrains. This IDE can be used not only for doing Deep Learning project, but doing other project such as web development. Pycharm has auto code completion, code cleaning, refactor, and have many integrations to other tools which is important on developing with Python (you need to install the plugin first). It has nice environment for doing debugging. It can also run notebook (.ipynb) file in it.
JupyterLab
Jupyter Lab is one of IDE which is easy to use, interactive data science environment tools which not only be used as an IDE, but also be used as presentation tools. The User Interface (UI) is best to make this as a visualization tools or a tutorial tools. We can make the documentation with markdown format and also insert picture to the notebook.
Personally, I code the source code using Pycharm. When I create some tutorials to test something or doing Exploratory Data Analysis (EDA), I use Jupyter Lab to do it. Just do not put your reusable code into your notebook file, it has bad reproducibility.
“Hey, what the hell !? Why I cannot run the training process at this version” — A
“Idk, I just push my code, and I think it works on my notebook.. wait a minute.. I got an error on this line.. I didn’t copy all of my code into my implementation” — B
“So why did you push !?!?” — A
Before we push our work to the repository, we need to make sure that the code is really works and do not have error. To do that, we should test the code before the model and the code pushed to the repository. Unit or Integration Tests must be done.
Unit tests tests that the code should pass for its module functionality. Integration tests test the integration of modules. It will check whether your logic is correct or not. Do this in order to find your mistakes before doing the experiment.
CircleCI is one of the solution to do the Continuous Integration. It can do unit tests and integration tests. It can uses Docker Image (we will dive into it later) as a containerization of the environment (which we should use it) . The similar tools that can do that are Jenkins and TravisCI.
Here are several library that you can use if you want to test your code in Python:
pipenv check : scans our Python package dependency graph for known security vulnerabilities
pylint : does static analysis of Python files and reports both style and bug problems.
mypy : does static analysis checking of Python files
bandit : performs static analysis to find common security vulnerabilities in Python code
shellcheck : finds bugs and potential bugs in shell scripts ( if you use it)
pytest : Python testing library for doing unit and integration test
Write them into your CI and make sure to pass these tests. If it fails, then rewrite your code and know where the error in your code is.
Here is one of the example on writing unit test on Deep Learning System.
“Hey, I’ve tested it on my computer and it works well”
“What ? No dude, it fails on my computer ? How the hell it works on your computer !?”
Ever experienced that ? I have. One of the problem that create that situation caused by the difference of your working environment with the others. For example, you work on Windows and the other work in Linux. The difference of your library and their library can also be the trigger of the problem.
To solve that, you need to write your library dependencies explicitly in a text called requirements.txt. Then run Python virtual environment such as pipenv. This will solve the library dependencies. Nevertheless, it still cannot solve the difference of enviroment and OS of the team. To solve it, you can use Docker.
Docker is a container which can be setup to be able to make virtual environment. We can install library dependencies and other environment variables that we set in the Docker. With this, you won’t have to fear on having error that is caused by the difference of the environment. Docker can also be a vital tools when we want to deploy the application. It will force the place of the deployment use the desired environment.
To share the container, First, we need write all of the step on creating the environment into the Dockerfile and then create a DockerImage. It can be pushed into DockerHub. Then the other person can pull the DockerImage from DockerHub and run it from his/her machine.
To learn more about Docker, There is a good article that is beginner friendly written by Preethi Kasireddy.
medium.freecodecamp.org
Figure 17 is an example how to create the Dockerfile.
Now we are in Training and Debugging step. This is the step where you do the experiment and produce the model. Here are the substeps for this step:
With your chosen Deep Learning Framework, code the Neural Network with a simple architecture (e.g : Neural Network with 1 hidden layer). Then use defaults hyperparameters such as no regularization and default Adam Optimizer. Do not forget to normalize the input if needed. Finally, use simple version of the model (e.g : small dataset).
To implement the neural network, there are several trick that you should follow sequentially.
Get the model to run
Get the model to run
The things that we should do is to get the model that you create with your DL framework to run. It means that to make sure no exception occurred until the process of updating the weight.
The exception that often occurs as follow:
Shape MismatchCasting IssueOut of Memory
Shape Mismatch
Casting Issue
Out of Memory
2. Overfit a Single Batch
After that, we should overfit a single batch to see that the whether the model can learn or not. Overfit means that we do not care about the validation at all and focus whether our model can learn according to our needs or not. We do this until the quality of the model become overfit (~100%). Here are common issues that occurs in this process:
Error goes up (Can be caused by : Learning Rate too high, wrong loss function sign, etc)Error explodes / goes NaN (Can be caused by : Numerical Issues like the operation of log, exp or high learning rate, etc)Error Oscilates (Can be caused by : Corrupted data label, Learning rate too high, etc)Error Plateaus (Can be caused by : Learning rate too low, Corrupted data label, etc)
Error goes up (Can be caused by : Learning Rate too high, wrong loss function sign, etc)
Error explodes / goes NaN (Can be caused by : Numerical Issues like the operation of log, exp or high learning rate, etc)
Error Oscilates (Can be caused by : Corrupted data label, Learning rate too high, etc)
Error Plateaus (Can be caused by : Learning rate too low, Corrupted data label, etc)
3. Compare to a known result
After we make sure that our model train well, we need to compare the result to other known result. Here is the hierarchy of known result:
We do this to make sure that our model can really learn the data and see the model is in the right track on learning the task. We will need to keep iterating until the model can perform up to expectation.
We will calculate the bias-variance decomposition from calculating the error with the chosen metric of our current best model. The formula of calculating the bias-variance decomposition is as follow:
Where:
irreducible error = the error of the baselinebias = training error - iredducible errorvariance = validation error - train errorvalidation overfitting = test error - validation error
Here is some example on implementing the bias-variance decomposition.
By knowing the value of bias, variance, and validation overfitting , it can help us the choice to do in the next step what to improve.
If the model has met the requirement, then deploy the model. If not, then address the issues whether to improve the data or tune the hyperparameter by using the result of the evaluation. Consider seeing what is wrong with the model when predicting some group of instances. Iterate until it satisfy the requirement (or give up).
Here are some tools that can be helpful on this step:
Here we go again, the version control. Yep, we have a version control for code and data now it is time to version control the model. Here are the tools that can be used to do version control:
WANDB
A version control of the model’s results. It has nice User Interface and Experience. Then, It can save the parameter used on the model, sample of the result of the model, and also save the weight and bias of the model which will be versioned. Furthermore, It can visualize the result of the model in real time. Moreover, we can also revert back the model to previous run (also change the weight of the model to that previous run) , which make it easier to reproduce the models. It can run anytime you want. It also scales well since it can integrate with Kubeflow (Kubernetes for ML which manages resources and services for containerized application).
Losswise
It is also a version control to versioning the model. It also saves the result of the model and the hyperparameter used for an experiment in a real time. It can also estimates when the model will finish the training . It will train the model every time you push your code to the repository (on designated branch). It also visualizes the result of the model in real time.
When optimizing or tuning the hyperparameter such as learning rate, there are some libraries and tools available to do it. There are:
For Keras DL Framework : Hyperas,
For Pytorch DL Framework : Hypersearch
Others : Hyperopt
WANDB also offer a solution to do the hyperparameter optimization. You need to contact them first to enable it though.
The final step will be this one. The substeps are as follow:
Pilot in production means that you will verify the system by testing it on selected group of end user. By doing that, we hope that we can gain a feedback on the system before fully deploy it. For Testing, There are several testing that you can do to your system beside Unit and Integration test, for example : Penetration Testing, Stress Testing, etc.
After we are sure that the model and the system has met the requirement, time to deploy the model. First of all, there are several way to deploy the model. There are :
Web Server DeploymentEmbedded System and Mobile
Web Server Deployment
Embedded System and Mobile
Web Server Deployment
There are several strategies we can use if we want to deploy to the website. Before that, we need to make sure that we create a RESTful API which serve the predictions in response of HTTP requests (GET, POST, DELETE, etc). The strategies are as follow:
Deploy code to cloud instances. scale by adding instances.Deploy code as containers (Docker), scale via orchestration. App code are packaged into Docker containers. Example : AWS Fargate.Deploy code as “Serverless function”. App code are packaged into zip files. The serverless function will manage everything . e.g : instant scale, request per second, load balancing, etc. It’s different from these two above, Serverless Function only pay for compute time rather than uptime. Example : AWS Lambda, Google Cloud Functions, and Azure Functions
Deploy code to cloud instances. scale by adding instances.
Deploy code as containers (Docker), scale via orchestration. App code are packaged into Docker containers. Example : AWS Fargate.
Deploy code as “Serverless function”. App code are packaged into zip files. The serverless function will manage everything . e.g : instant scale, request per second, load balancing, etc. It’s different from these two above, Serverless Function only pay for compute time rather than uptime. Example : AWS Lambda, Google Cloud Functions, and Azure Functions
Embedded System and Mobile
To deploy to the embedded system or Mobile, we can use Tensorflow Lite. It has smaller, faster, and has less dependencies than the Tensorflow, thus can be deployed into Embedded System or Mobile. Unfortunately it has limited set of operators.
There is also a tool called TensorRT. It optimized the inference engine used on prediction, thus sped up the inference process. It is built on CUDA. On embedding systems, NVIDIA Jetson TX2 works well with it.
On Apple, there is a tools called CoreML to make it easier to integrate ML System to the IPhone. There is also similar tools called MLKit which can be used to help deploying ML System to Android.
ONNX (Open Neural Network Exchange) is a open source format for Deep Learning models that can easily convert model into supported Deep Learning frameworks. ONNX supports Tensorflow, Pytorch, and Caffe2 . It can mix different frameworks such that frameworks that are good for developing (Pytorch) don’t need to be good at the deployment and inference (Tensorflow / Caffe2).
If you deploy the application to cloud server, there should be a solution of the monitoring system. We can set the alarm when things go wrong by writing the record about it in the monitoring system. With this, we will know what can be improved with the model and fix the problem.
In this article, we get to know the steps on doing the Full Stack Deep Learning according to the FSDL course on March 2019. First, we need to setup and plan the project. We need to define the goals, metrics, and baseline in this step. Then, we collect the data and label it with available tools. In building the codebase, there are some tools that can maintain the quality of the project that have been described above. Then we do modeling with testing and debugging. After the model met the requirement, finally we know the step and tools for deploying and monitoring the application to the desired interface.
That’s it, my article about tools and steps introduced by the course that I’ve learned. Why do I write this article ? I found out that my brain can easily remember and make me understand better about the content of something that I need if I write it. Moreover, In the process of my writing, I get to have a chance to review the content of the course. Furthermore, It can make me to share my knowledge to everyone. I am happy to share something good to everyone :).
I gain a lot of new things in following that course, especially about the tools of the Deep Learning Stacks. I also get to know how to troubleshoot model in Deep Learning since it is not easy to debug it. It also taught me the tools , steps, and tricks on doing the Full Stack Deep Learning. To sum it up, It’s a great courses and free to access. Therefore, I recommend it to anyone who want to learn about doing project in Deep Learning.
To be honest, I haven’t tried all the tools written in this article. The tools and its description that this article presents are taken from the FSDL course and some sources that I’ve read. You can tell me if there are some misinformation, especially about the tools.
Thus,
I welcome any feedback that can improve myself and this article. I’m in the process of learning on writing and learning to become better. I apreciate a feedback to make me become better. Make sure to give feedback in a proper manner 😄.
See ya in my next article.
Sources
www.guru99.com
medium.com
by DataKitchen
https://docs.google.com/presentation/d/1yHLPvPhUs2KGI5ZWo0sU-PKU3GimAk3iTsI38Z-B5Gw/ (Presentation in ICLR 2019 about Reproducibility by Joel Grus). Figure 14 and 16 are taken from this source.
fullstackdeeplearning.com
Others figure are taken from this source. | [
{
"code": null,
"e": 647,
"s": 172,
"text": "Hi everyone, How’s everything? Today, I’m going to write article about what I have learned from seeing the Full Stack Deep Learning (FSDL) March 2019 courses. It is a great online courses that tell us to do project with Full Stack Deep Learning. What I love the most is how they teach us a project and teach us not only how to create the Deep Learning architecture, but tell us the Software Engineering stuffs that should be concerned when doing project about Deep Learning."
},
{
"code": null,
"e": 955,
"s": 647,
"text": "When we do a Deep Learning project, we need to know what are the steps and technology that we should use. We need to know these to enhance the quality of the project. This will be useful especially when we want to do the project in a team. We do not want the project become messy when the team collaborates."
},
{
"code": null,
"e": 1341,
"s": 955,
"text": "This article will focus on the tools and what to do in every steps of a full stack Deep Learning project according to FSDL course (plus a few addition about the tools that I know). There will be a brief description what to do on each steps. This article will only show the tools that I lay my eyes on in that course. Programming language that will be focused in this article is Python."
},
{
"code": null,
"e": 1476,
"s": 1341,
"text": "UPDATE 12 July 2020: Full Stack Deep Learning Course can be accessed here https://course.fullstackdeeplearning.com/ . Check it out :)."
},
{
"code": null,
"e": 1608,
"s": 1476,
"text": "StepsPlanning and Project SetupData Collection and LabelingCodebase DevelopmentTraining and DebuggingDeploymentConclusionAfterwords"
},
{
"code": null,
"e": 1614,
"s": 1608,
"text": "Steps"
},
{
"code": null,
"e": 1641,
"s": 1614,
"text": "Planning and Project Setup"
},
{
"code": null,
"e": 1670,
"s": 1641,
"text": "Data Collection and Labeling"
},
{
"code": null,
"e": 1691,
"s": 1670,
"text": "Codebase Development"
},
{
"code": null,
"e": 1714,
"s": 1691,
"text": "Training and Debugging"
},
{
"code": null,
"e": 1725,
"s": 1714,
"text": "Deployment"
},
{
"code": null,
"e": 1736,
"s": 1725,
"text": "Conclusion"
},
{
"code": null,
"e": 1747,
"s": 1736,
"text": "Afterwords"
},
{
"code": null,
"e": 1793,
"s": 1747,
"text": "These are the steps that FSDL course tell us:"
},
{
"code": null,
"e": 1891,
"s": 1793,
"text": "Planning and Project SetupData Collection and LabelingTraining and DebuggingDeploying and Testing"
},
{
"code": null,
"e": 1918,
"s": 1891,
"text": "Planning and Project Setup"
},
{
"code": null,
"e": 1947,
"s": 1918,
"text": "Data Collection and Labeling"
},
{
"code": null,
"e": 1970,
"s": 1947,
"text": "Training and Debugging"
},
{
"code": null,
"e": 1992,
"s": 1970,
"text": "Deploying and Testing"
},
{
"code": null,
"e": 2313,
"s": 1992,
"text": "Where each of the steps can be done which can come back to previous step or forth (not waterfall). The course also suggest that we do the process iteratively, meaning that we start from small progress and increase it continuously. For example, we start using simple model with small data then improve it as time goes by."
},
{
"code": null,
"e": 2544,
"s": 2313,
"text": "This step will be the first step that you will do. We need to state what the project going to make and the goal of the project. We also need to state the metric and baseline of the project. The substeps of this step are as follow:"
},
{
"code": null,
"e": 2697,
"s": 2544,
"text": "First, we need to define what is the project is going to make. There are two consideration on picking what to make. They are are Impact and Feasibility."
},
{
"code": null,
"e": 2868,
"s": 2697,
"text": "We need to make sure that the project is Impactful. What are the values of your application that we want to make in the project. Two questions that you need to answer are"
},
{
"code": null,
"e": 2981,
"s": 2868,
"text": "Where can you take advantages of cheap prediction ?Where can you automate complicated manual software pipeline ?"
},
{
"code": null,
"e": 3033,
"s": 2981,
"text": "Where can you take advantages of cheap prediction ?"
},
{
"code": null,
"e": 3095,
"s": 3033,
"text": "Where can you automate complicated manual software pipeline ?"
},
{
"code": null,
"e": 3248,
"s": 3095,
"text": "Where for cheap prediction produced by our chosen application that we want to make, we can produce great value which can reduce the cost of other tasks."
},
{
"code": null,
"e": 3436,
"s": 3248,
"text": "Feasibility is also thing that we need to watch out. Since Deep Learning focus on data, We need to make sure that the data is available and fit to the project requirement and cost budget."
},
{
"code": null,
"e": 3849,
"s": 3436,
"text": "We need to consider the accuracy requirement where we need to set the minimum target. Since the project costs will tend to correlate super linearly with the project costs, again, we need to considerate our requirement and maximum cost that we tolerate. Also consider that there might be some cases where it is not important to fail the prediction and some cases where the model must have a low error as possible."
},
{
"code": null,
"e": 4164,
"s": 3849,
"text": "Finally, we need to see the problem difficulty. How hard is the project is. To measure the difficulty, we can see some published works on similar problem. For example, search some papers in ARXIV or any conferences that have similar problem with the project. With these, we can grasp the difficulty of the project."
},
{
"code": null,
"e": 4238,
"s": 4164,
"text": "See Figure 4 for more detail on assessing the feasibility of the project."
},
{
"code": null,
"e": 4339,
"s": 4238,
"text": "Metric is a measurement of particular characteristic of the performance or efficiency of the system."
},
{
"code": null,
"e": 4690,
"s": 4339,
"text": "Since system in Machine Learning work best on optimizing a single number , we need to define a metric which satisfy the requirement with a single number even there might be a lot of metrics that should be calculated. For a problem where there are a lot of metrics that we need to use, we need to pick a formula for combining these metrics. There are:"
},
{
"code": null,
"e": 4811,
"s": 4690,
"text": "Simple average / weighted averageThreshold n-1 metrics, evaluate the nth metricDomain specific formula (for example mAP)"
},
{
"code": null,
"e": 4845,
"s": 4811,
"text": "Simple average / weighted average"
},
{
"code": null,
"e": 4892,
"s": 4845,
"text": "Threshold n-1 metrics, evaluate the nth metric"
},
{
"code": null,
"e": 4934,
"s": 4892,
"text": "Domain specific formula (for example mAP)"
},
{
"code": null,
"e": 5007,
"s": 4934,
"text": "Here are some example how to combine two metrics (Precision and Recall):"
},
{
"code": null,
"e": 5301,
"s": 5007,
"text": "After we choose the metric, we need to choose our baseline. Baseline is an expected value or condition which the performance will be measured to be compared to our work. It will give us a lower bound on a expected model performance. The tighter the baseline is the more useful the baseline is."
},
{
"code": null,
"e": 5520,
"s": 5301,
"text": "So why is the baseline is important? Why not skip this step ? We can measure our model how good it is by comparing to the baseline. By knowing how good or bad the model is, we can choose our next move on what to tweak."
},
{
"code": null,
"e": 5590,
"s": 5520,
"text": "To look for the baseline, there are several sources that you can use:"
},
{
"code": null,
"e": 5892,
"s": 5590,
"text": "External baseline , where you form the baseline from the business or engineering requirement. You can also use published work results as the baseline.Internal baseline , Use scripted baseline or create simple Machine Learning (ML) model such as using standard feature based word or using simple model."
},
{
"code": null,
"e": 6043,
"s": 5892,
"text": "External baseline , where you form the baseline from the business or engineering requirement. You can also use published work results as the baseline."
},
{
"code": null,
"e": 6195,
"s": 6043,
"text": "Internal baseline , Use scripted baseline or create simple Machine Learning (ML) model such as using standard feature based word or using simple model."
},
{
"code": null,
"e": 6329,
"s": 6195,
"text": "The baseline is chosen according to your need. For example if you want a system that surpass human, you need to add a human baseline."
},
{
"code": null,
"e": 6688,
"s": 6329,
"text": "Create your codebase that will be the core how to do the further steps. The source code in the codebase can be developed according to the current need of what the project currently going to do. For example, if the current step is collecting the data, we will write the code used to collect the data (if needed). We will mostly go to this step back and forth."
},
{
"code": null,
"e": 6914,
"s": 6688,
"text": "We should make sure that the source code in the codebase is reproducible and scalable, especially for doing the project in a group. To make it happen, you need to use the right tools. This article will tell us about it later."
},
{
"code": null,
"e": 7068,
"s": 6914,
"text": "After we define what we are going to create, baseline, and metrics in the project, the most painful of the step will begin, data collection and labeling."
},
{
"code": null,
"e": 7321,
"s": 7068,
"text": "Most of Deep Learning applications will require a lot of data which need to be labeled. Time will be mostly consumed in this process. Although you can also use public dataset, often that labeled dataset needed for our project is not available publicly."
},
{
"code": null,
"e": 7343,
"s": 7321,
"text": "Here is the substeps:"
},
{
"code": null,
"e": 7553,
"s": 7343,
"text": "We need to plan how to obtain the complete dataset. There are multiple ways to obtain the data. One that you should be considered that the data need to align according to what we want to create in the project."
},
{
"code": null,
"e": 7746,
"s": 7553,
"text": "If the strategy to obtain data is through the internet by scraping and crawling some websites, we need to use some tools to do it. Scrapy is one of the tool that can be helpful for the project"
},
{
"code": null,
"e": 7753,
"s": 7746,
"text": "Scrapy"
},
{
"code": null,
"e": 8125,
"s": 7753,
"text": "This is a Python scrapper and data crawler library that can be used to scrap and crawl websites. It can be used to collect data such as images and texts on the websites. We can also scrap images from Bing, Google, or Instagram with this. To use this library, we need to learn from the tutorial that is also available in its website. Do not worry, it is not hard to learn."
},
{
"code": null,
"e": 8466,
"s": 8125,
"text": "After we collect the data, the next problem that you need to think is where to send your collected data. Since you are doing the project not alone, you need to make sure that the data can be accessed by everyone. Also, we need to choose the format of the data which will be saved. Below is a solution when we want to save our data in cloud."
},
{
"code": null,
"e": 8481,
"s": 8466,
"text": "Object Storage"
},
{
"code": null,
"e": 8783,
"s": 8481,
"text": "For storing your binary data such as images and videos, You can use cloud storage such as AmazonS3 or GCP to build the object storage with API over the file system. We can also built versioning into the service. See their website for more detail. You need to pay to use it (there is also a free plan)."
},
{
"code": null,
"e": 8792,
"s": 8783,
"text": "Database"
},
{
"code": null,
"e": 9120,
"s": 8792,
"text": "Database is used for persistent, fast, scalable storage, and retrieval of structured data. Database is used to save the data that often will be accessed continuously which is not binary data. You will save the metadata (labels, user activity) here. There are some tools that you can use. One that is recommended is PostgresSQl."
},
{
"code": null,
"e": 9242,
"s": 9120,
"text": "It can store structured SQL database and also can be used to save unstructured json data. It is still actively maintaned."
},
{
"code": null,
"e": 9252,
"s": 9242,
"text": "Data Lake"
},
{
"code": null,
"e": 9492,
"s": 9252,
"text": "When you have data which is the unstructured aggregation from multiple source and multiple format which has high cost transformation, you can use data lake. Basically, you dump every data on it and it will transform it into specific needs."
},
{
"code": null,
"e": 9556,
"s": 9492,
"text": "Amazon Redshift is one of cannonical solution to the Data Lake."
},
{
"code": null,
"e": 9672,
"s": 9556,
"text": "When we are doing the training process, we need to move the data that is needed for your model to your file system."
},
{
"code": null,
"e": 9907,
"s": 9672,
"text": "The data should be versioned to make sure the progress can be revertible. The version control does not only apply to the source code, it also apply to the data. We will dive into data version control after we talk about Data Labeling."
},
{
"code": null,
"e": 10023,
"s": 9907,
"text": "In this section, we will know how to label the data. There are source of labors that you can use to label the data:"
},
{
"code": null,
"e": 10164,
"s": 10023,
"text": "Hire annotators by yourselfCrowdsource (Mechanical Turk)Use full-service data labeling companies such as FigureEight, Scale.ai, and LabelBox"
},
{
"code": null,
"e": 10192,
"s": 10164,
"text": "Hire annotators by yourself"
},
{
"code": null,
"e": 10222,
"s": 10192,
"text": "Crowdsource (Mechanical Turk)"
},
{
"code": null,
"e": 10307,
"s": 10222,
"text": "Use full-service data labeling companies such as FigureEight, Scale.ai, and LabelBox"
},
{
"code": null,
"e": 10386,
"s": 10307,
"text": "If you want the team to annotate it , Here are several tools that you can use:"
},
{
"code": null,
"e": 10396,
"s": 10386,
"text": "Dataturks"
},
{
"code": null,
"e": 10765,
"s": 10396,
"text": "Online Collaboration Annotation tool , Data Turks. For the free plan, it is limited to 10000 annotations and the data must be public. It offers several annotation tools for several tasks on NLP (Sequence tagging, classification, etc) and Computer Vision (Image segmentation, Image bounding box, classification, etc). The FSDL course uses this as the tool for labeling."
},
{
"code": null,
"e": 10773,
"s": 10765,
"text": "doccano"
},
{
"code": null,
"e": 10980,
"s": 10773,
"text": "Free open source Annotation tool for NLP tasks. It also support sequence tagging, classification, and machine translation tasks. Can also be set up as a collaborative annotation tools, but it need a server."
},
{
"code": null,
"e": 10985,
"s": 10980,
"text": "CVAT"
},
{
"code": null,
"e": 11129,
"s": 10985,
"text": "Offline annotation tool for Computer Vision tasks. It is released by Intel as Open Source. It can label bounding boxes and image segmentations."
},
{
"code": null,
"e": 11255,
"s": 11129,
"text": "If you want to search any public datasets, see this article created by Stacy Stanford for to know any list of public dataset."
},
{
"code": null,
"e": 11266,
"s": 11255,
"text": "medium.com"
},
{
"code": null,
"e": 11315,
"s": 11266,
"text": "It is still actively been updated and maintaned."
},
{
"code": null,
"e": 11362,
"s": 11315,
"text": "There are level on how to do data versioning :"
},
{
"code": null,
"e": 12426,
"s": 11362,
"text": "Level 0 : Unversioned. We should not attempt this. Deployment need to be versioned. If the data is not versioned, the deployed models are also not versioned. There will be a problem if we use unversioned one, which is inability to get back to previous result.Level 1 : Versioned via snapshot. We store all of the data used on different version. Which we could say that it is a bit hacky. We still need to version data as easy as version the codeLevel 2 : Data is versioned as a mix of code and assets. The heavy files will be stored in other server (such as Amazon S3) where there is a JSON or similar type as reference of the relevant metadata. The relevant metadata can contains labels, user activity, and etc. The JSON file will be versioned. The JSON files can become big. To make it easier, we can use git-lfs to version it. This level should be acceptable to do the project.Level 3 : Use specialized software solution for versioning the data. If you think that level 2 is not enough for your project, you can do this. One of tool for data versioning is DVC."
},
{
"code": null,
"e": 12686,
"s": 12426,
"text": "Level 0 : Unversioned. We should not attempt this. Deployment need to be versioned. If the data is not versioned, the deployed models are also not versioned. There will be a problem if we use unversioned one, which is inability to get back to previous result."
},
{
"code": null,
"e": 12873,
"s": 12686,
"text": "Level 1 : Versioned via snapshot. We store all of the data used on different version. Which we could say that it is a bit hacky. We still need to version data as easy as version the code"
},
{
"code": null,
"e": 13309,
"s": 12873,
"text": "Level 2 : Data is versioned as a mix of code and assets. The heavy files will be stored in other server (such as Amazon S3) where there is a JSON or similar type as reference of the relevant metadata. The relevant metadata can contains labels, user activity, and etc. The JSON file will be versioned. The JSON files can become big. To make it easier, we can use git-lfs to version it. This level should be acceptable to do the project."
},
{
"code": null,
"e": 13493,
"s": 13309,
"text": "Level 3 : Use specialized software solution for versioning the data. If you think that level 2 is not enough for your project, you can do this. One of tool for data versioning is DVC."
},
{
"code": null,
"e": 13497,
"s": 13493,
"text": "DVC"
},
{
"code": null,
"e": 13804,
"s": 13497,
"text": "DVC is built to make ML models shareable and reproducible. It is designed to handle large files, data sets, machine learning models, and metrics as well as code. It is a solution for versioning ML models with its dataset. We can connect the version control into the cloud storage such as Amazon S3 and GCP."
},
{
"code": null,
"e": 14014,
"s": 13804,
"text": "When we do the project, expect to write codebase on doing every steps. Reproducibility is one thing that we must concern when writing the code. we need to make sure that our codebase has reproducibility on it."
},
{
"code": null,
"e": 14103,
"s": 14014,
"text": "Before we dive into tools, we need to choose the language and framework of our codebase."
},
{
"code": null,
"e": 14350,
"s": 14103,
"text": "For choosing programming language, I prefer Python over anything else. Python has the largest community for data science and great to develop. The popular Deep Learning software also mostly supported by Python. The language is also easy to learn."
},
{
"code": null,
"e": 14527,
"s": 14350,
"text": "There are several choices that you can made for the Deep Learning Framework. The most popular framework in Python are Tensorflow, Keras, and PyTorch. Use the one that you like."
},
{
"code": null,
"e": 14912,
"s": 14527,
"text": "For easier debugging, you can use PyTorch as the Deep Learning Framework. Keras is also easy to use and have good UX. It is a wrapper of Tensorflow, Theano and other Deep Learning framework and make it easier to use. Tensorflow is also a choice if you like their environment. Tensorflow can be wise decision because of the support of its community and have great tools for deployment."
},
{
"code": null,
"e": 15133,
"s": 14912,
"text": "Do not worry about the deployment. There is exists a software that can convert the model format to another format. For example, you can convert the model that is produced by Pytorch to Tensorflow. We will see this later."
},
{
"code": null,
"e": 15320,
"s": 15133,
"text": "I think the factor of choosing the language and framework is how active the community behind it. Since it will give birth of high number of custom package that can be integrated into it."
},
{
"code": null,
"e": 15703,
"s": 15320,
"text": "One of the important things when doing the project is version control. When we do the project, we don’t want the inability to redo our code base when someone accidentally wreck it. We also need to keep track the code on each update to see what are the changes updated by someone else. This will not be possible if we do not use some tools do it. Git is one of the solution to do it."
},
{
"code": null,
"e": 16009,
"s": 15703,
"text": "Okay, we know that version control is important, especially on doing collaboration work. Currently, git is one of the best solution to do version control. It also be used to share your code to other people in your team. Without this, I don’t think that you can collaborate well with others in the project."
},
{
"code": null,
"e": 16105,
"s": 16009,
"text": "There are several services that you can use that use Git such as GitHub, BitBucket, and GitLab."
},
{
"code": null,
"e": 16437,
"s": 16105,
"text": "There is also important thing that should be done, which is Code Review. Code reviews are an early protection against incorrect code or bad quality code which pass the unit or integration tests. When you do collaboration, make someone check your code and review it. Most of the version control services should support this feature."
},
{
"code": null,
"e": 16659,
"s": 16437,
"text": "When we first create the project structure folder, we must be wondering how to create the folder structure. Then, we give up and put all the code in the root project folder. It’s a bad practice that give bad quality code."
},
{
"code": null,
"e": 16964,
"s": 16659,
"text": "One of the solution that I found is cookiecutter-data-science. It give a template how should we create the project structure. It also give how to give a name to the created file and where you should put it. Be sure to use it to make your codebase not become messy. Consider reading the website to use it."
},
{
"code": null,
"e": 17139,
"s": 16964,
"text": "IDE is one of the tools that you can use to accelerate to write the code. It has integrated tools which can be useful for developing. There are several IDEs that you can use:"
},
{
"code": null,
"e": 17147,
"s": 17139,
"text": "Pycharm"
},
{
"code": null,
"e": 17571,
"s": 17147,
"text": "IDE that is released by JetBrains. This IDE can be used not only for doing Deep Learning project, but doing other project such as web development. Pycharm has auto code completion, code cleaning, refactor, and have many integrations to other tools which is important on developing with Python (you need to install the plugin first). It has nice environment for doing debugging. It can also run notebook (.ipynb) file in it."
},
{
"code": null,
"e": 17582,
"s": 17571,
"text": "JupyterLab"
},
{
"code": null,
"e": 17930,
"s": 17582,
"text": "Jupyter Lab is one of IDE which is easy to use, interactive data science environment tools which not only be used as an IDE, but also be used as presentation tools. The User Interface (UI) is best to make this as a visualization tools or a tutorial tools. We can make the documentation with markdown format and also insert picture to the notebook."
},
{
"code": null,
"e": 18185,
"s": 17930,
"text": "Personally, I code the source code using Pycharm. When I create some tutorials to test something or doing Exploratory Data Analysis (EDA), I use Jupyter Lab to do it. Just do not put your reusable code into your notebook file, it has bad reproducibility."
},
{
"code": null,
"e": 18267,
"s": 18185,
"text": "“Hey, what the hell !? Why I cannot run the training process at this version” — A"
},
{
"code": null,
"e": 18435,
"s": 18267,
"text": "“Idk, I just push my code, and I think it works on my notebook.. wait a minute.. I got an error on this line.. I didn’t copy all of my code into my implementation” — B"
},
{
"code": null,
"e": 18466,
"s": 18435,
"text": "“So why did you push !?!?” — A"
},
{
"code": null,
"e": 18715,
"s": 18466,
"text": "Before we push our work to the repository, we need to make sure that the code is really works and do not have error. To do that, we should test the code before the model and the code pushed to the repository. Unit or Integration Tests must be done."
},
{
"code": null,
"e": 18959,
"s": 18715,
"text": "Unit tests tests that the code should pass for its module functionality. Integration tests test the integration of modules. It will check whether your logic is correct or not. Do this in order to find your mistakes before doing the experiment."
},
{
"code": null,
"e": 19252,
"s": 18959,
"text": "CircleCI is one of the solution to do the Continuous Integration. It can do unit tests and integration tests. It can uses Docker Image (we will dive into it later) as a containerization of the environment (which we should use it) . The similar tools that can do that are Jenkins and TravisCI."
},
{
"code": null,
"e": 19335,
"s": 19252,
"text": "Here are several library that you can use if you want to test your code in Python:"
},
{
"code": null,
"e": 19427,
"s": 19335,
"text": "pipenv check : scans our Python package dependency graph for known security vulnerabilities"
},
{
"code": null,
"e": 19514,
"s": 19427,
"text": "pylint : does static analysis of Python files and reports both style and bug problems."
},
{
"code": null,
"e": 19567,
"s": 19514,
"text": "mypy : does static analysis checking of Python files"
},
{
"code": null,
"e": 19656,
"s": 19567,
"text": "bandit : performs static analysis to find common security vulnerabilities in Python code"
},
{
"code": null,
"e": 19733,
"s": 19656,
"text": "shellcheck : finds bugs and potential bugs in shell scripts ( if you use it)"
},
{
"code": null,
"e": 19801,
"s": 19733,
"text": "pytest : Python testing library for doing unit and integration test"
},
{
"code": null,
"e": 19938,
"s": 19801,
"text": "Write them into your CI and make sure to pass these tests. If it fails, then rewrite your code and know where the error in your code is."
},
{
"code": null,
"e": 20011,
"s": 19938,
"text": "Here is one of the example on writing unit test on Deep Learning System."
},
{
"code": null,
"e": 20066,
"s": 20011,
"text": "“Hey, I’ve tested it on my computer and it works well”"
},
{
"code": null,
"e": 20152,
"s": 20066,
"text": "“What ? No dude, it fails on my computer ? How the hell it works on your computer !?”"
},
{
"code": null,
"e": 20451,
"s": 20152,
"text": "Ever experienced that ? I have. One of the problem that create that situation caused by the difference of your working environment with the others. For example, you work on Windows and the other work in Linux. The difference of your library and their library can also be the trigger of the problem."
},
{
"code": null,
"e": 20768,
"s": 20451,
"text": "To solve that, you need to write your library dependencies explicitly in a text called requirements.txt. Then run Python virtual environment such as pipenv. This will solve the library dependencies. Nevertheless, it still cannot solve the difference of enviroment and OS of the team. To solve it, you can use Docker."
},
{
"code": null,
"e": 21191,
"s": 20768,
"text": "Docker is a container which can be setup to be able to make virtual environment. We can install library dependencies and other environment variables that we set in the Docker. With this, you won’t have to fear on having error that is caused by the difference of the environment. Docker can also be a vital tools when we want to deploy the application. It will force the place of the deployment use the desired environment."
},
{
"code": null,
"e": 21459,
"s": 21191,
"text": "To share the container, First, we need write all of the step on creating the environment into the Dockerfile and then create a DockerImage. It can be pushed into DockerHub. Then the other person can pull the DockerImage from DockerHub and run it from his/her machine."
},
{
"code": null,
"e": 21567,
"s": 21459,
"text": "To learn more about Docker, There is a good article that is beginner friendly written by Preethi Kasireddy."
},
{
"code": null,
"e": 21591,
"s": 21567,
"text": "medium.freecodecamp.org"
},
{
"code": null,
"e": 21645,
"s": 21591,
"text": "Figure 17 is an example how to create the Dockerfile."
},
{
"code": null,
"e": 21793,
"s": 21645,
"text": "Now we are in Training and Debugging step. This is the step where you do the experiment and produce the model. Here are the substeps for this step:"
},
{
"code": null,
"e": 22130,
"s": 21793,
"text": "With your chosen Deep Learning Framework, code the Neural Network with a simple architecture (e.g : Neural Network with 1 hidden layer). Then use defaults hyperparameters such as no regularization and default Adam Optimizer. Do not forget to normalize the input if needed. Finally, use simple version of the model (e.g : small dataset)."
},
{
"code": null,
"e": 22224,
"s": 22130,
"text": "To implement the neural network, there are several trick that you should follow sequentially."
},
{
"code": null,
"e": 22245,
"s": 22224,
"text": "Get the model to run"
},
{
"code": null,
"e": 22266,
"s": 22245,
"text": "Get the model to run"
},
{
"code": null,
"e": 22453,
"s": 22266,
"text": "The things that we should do is to get the model that you create with your DL framework to run. It means that to make sure no exception occurred until the process of updating the weight."
},
{
"code": null,
"e": 22496,
"s": 22453,
"text": "The exception that often occurs as follow:"
},
{
"code": null,
"e": 22537,
"s": 22496,
"text": "Shape MismatchCasting IssueOut of Memory"
},
{
"code": null,
"e": 22552,
"s": 22537,
"text": "Shape Mismatch"
},
{
"code": null,
"e": 22566,
"s": 22552,
"text": "Casting Issue"
},
{
"code": null,
"e": 22580,
"s": 22566,
"text": "Out of Memory"
},
{
"code": null,
"e": 22606,
"s": 22580,
"text": "2. Overfit a Single Batch"
},
{
"code": null,
"e": 22952,
"s": 22606,
"text": "After that, we should overfit a single batch to see that the whether the model can learn or not. Overfit means that we do not care about the validation at all and focus whether our model can learn according to our needs or not. We do this until the quality of the model become overfit (~100%). Here are common issues that occurs in this process:"
},
{
"code": null,
"e": 23332,
"s": 22952,
"text": "Error goes up (Can be caused by : Learning Rate too high, wrong loss function sign, etc)Error explodes / goes NaN (Can be caused by : Numerical Issues like the operation of log, exp or high learning rate, etc)Error Oscilates (Can be caused by : Corrupted data label, Learning rate too high, etc)Error Plateaus (Can be caused by : Learning rate too low, Corrupted data label, etc)"
},
{
"code": null,
"e": 23421,
"s": 23332,
"text": "Error goes up (Can be caused by : Learning Rate too high, wrong loss function sign, etc)"
},
{
"code": null,
"e": 23543,
"s": 23421,
"text": "Error explodes / goes NaN (Can be caused by : Numerical Issues like the operation of log, exp or high learning rate, etc)"
},
{
"code": null,
"e": 23630,
"s": 23543,
"text": "Error Oscilates (Can be caused by : Corrupted data label, Learning rate too high, etc)"
},
{
"code": null,
"e": 23715,
"s": 23630,
"text": "Error Plateaus (Can be caused by : Learning rate too low, Corrupted data label, etc)"
},
{
"code": null,
"e": 23744,
"s": 23715,
"text": "3. Compare to a known result"
},
{
"code": null,
"e": 23882,
"s": 23744,
"text": "After we make sure that our model train well, we need to compare the result to other known result. Here is the hierarchy of known result:"
},
{
"code": null,
"e": 24087,
"s": 23882,
"text": "We do this to make sure that our model can really learn the data and see the model is in the right track on learning the task. We will need to keep iterating until the model can perform up to expectation."
},
{
"code": null,
"e": 24287,
"s": 24087,
"text": "We will calculate the bias-variance decomposition from calculating the error with the chosen metric of our current best model. The formula of calculating the bias-variance decomposition is as follow:"
},
{
"code": null,
"e": 24294,
"s": 24287,
"text": "Where:"
},
{
"code": null,
"e": 24476,
"s": 24294,
"text": "irreducible error = the error of the baselinebias = training error - iredducible errorvariance = validation error - train errorvalidation overfitting = test error - validation error"
},
{
"code": null,
"e": 24546,
"s": 24476,
"text": "Here is some example on implementing the bias-variance decomposition."
},
{
"code": null,
"e": 24681,
"s": 24546,
"text": "By knowing the value of bias, variance, and validation overfitting , it can help us the choice to do in the next step what to improve."
},
{
"code": null,
"e": 25009,
"s": 24681,
"text": "If the model has met the requirement, then deploy the model. If not, then address the issues whether to improve the data or tune the hyperparameter by using the result of the evaluation. Consider seeing what is wrong with the model when predicting some group of instances. Iterate until it satisfy the requirement (or give up)."
},
{
"code": null,
"e": 25063,
"s": 25009,
"text": "Here are some tools that can be helpful on this step:"
},
{
"code": null,
"e": 25255,
"s": 25063,
"text": "Here we go again, the version control. Yep, we have a version control for code and data now it is time to version control the model. Here are the tools that can be used to do version control:"
},
{
"code": null,
"e": 25261,
"s": 25255,
"text": "WANDB"
},
{
"code": null,
"e": 25913,
"s": 25261,
"text": "A version control of the model’s results. It has nice User Interface and Experience. Then, It can save the parameter used on the model, sample of the result of the model, and also save the weight and bias of the model which will be versioned. Furthermore, It can visualize the result of the model in real time. Moreover, we can also revert back the model to previous run (also change the weight of the model to that previous run) , which make it easier to reproduce the models. It can run anytime you want. It also scales well since it can integrate with Kubeflow (Kubernetes for ML which manages resources and services for containerized application)."
},
{
"code": null,
"e": 25922,
"s": 25913,
"text": "Losswise"
},
{
"code": null,
"e": 26293,
"s": 25922,
"text": "It is also a version control to versioning the model. It also saves the result of the model and the hyperparameter used for an experiment in a real time. It can also estimates when the model will finish the training . It will train the model every time you push your code to the repository (on designated branch). It also visualizes the result of the model in real time."
},
{
"code": null,
"e": 26427,
"s": 26293,
"text": "When optimizing or tuning the hyperparameter such as learning rate, there are some libraries and tools available to do it. There are:"
},
{
"code": null,
"e": 26461,
"s": 26427,
"text": "For Keras DL Framework : Hyperas,"
},
{
"code": null,
"e": 26500,
"s": 26461,
"text": "For Pytorch DL Framework : Hypersearch"
},
{
"code": null,
"e": 26518,
"s": 26500,
"text": "Others : Hyperopt"
},
{
"code": null,
"e": 26637,
"s": 26518,
"text": "WANDB also offer a solution to do the hyperparameter optimization. You need to contact them first to enable it though."
},
{
"code": null,
"e": 26698,
"s": 26637,
"text": "The final step will be this one. The substeps are as follow:"
},
{
"code": null,
"e": 27050,
"s": 26698,
"text": "Pilot in production means that you will verify the system by testing it on selected group of end user. By doing that, we hope that we can gain a feedback on the system before fully deploy it. For Testing, There are several testing that you can do to your system beside Unit and Integration test, for example : Penetration Testing, Stress Testing, etc."
},
{
"code": null,
"e": 27218,
"s": 27050,
"text": "After we are sure that the model and the system has met the requirement, time to deploy the model. First of all, there are several way to deploy the model. There are :"
},
{
"code": null,
"e": 27266,
"s": 27218,
"text": "Web Server DeploymentEmbedded System and Mobile"
},
{
"code": null,
"e": 27288,
"s": 27266,
"text": "Web Server Deployment"
},
{
"code": null,
"e": 27315,
"s": 27288,
"text": "Embedded System and Mobile"
},
{
"code": null,
"e": 27337,
"s": 27315,
"text": "Web Server Deployment"
},
{
"code": null,
"e": 27590,
"s": 27337,
"text": "There are several strategies we can use if we want to deploy to the website. Before that, we need to make sure that we create a RESTful API which serve the predictions in response of HTTP requests (GET, POST, DELETE, etc). The strategies are as follow:"
},
{
"code": null,
"e": 28133,
"s": 27590,
"text": "Deploy code to cloud instances. scale by adding instances.Deploy code as containers (Docker), scale via orchestration. App code are packaged into Docker containers. Example : AWS Fargate.Deploy code as “Serverless function”. App code are packaged into zip files. The serverless function will manage everything . e.g : instant scale, request per second, load balancing, etc. It’s different from these two above, Serverless Function only pay for compute time rather than uptime. Example : AWS Lambda, Google Cloud Functions, and Azure Functions"
},
{
"code": null,
"e": 28192,
"s": 28133,
"text": "Deploy code to cloud instances. scale by adding instances."
},
{
"code": null,
"e": 28322,
"s": 28192,
"text": "Deploy code as containers (Docker), scale via orchestration. App code are packaged into Docker containers. Example : AWS Fargate."
},
{
"code": null,
"e": 28678,
"s": 28322,
"text": "Deploy code as “Serverless function”. App code are packaged into zip files. The serverless function will manage everything . e.g : instant scale, request per second, load balancing, etc. It’s different from these two above, Serverless Function only pay for compute time rather than uptime. Example : AWS Lambda, Google Cloud Functions, and Azure Functions"
},
{
"code": null,
"e": 28705,
"s": 28678,
"text": "Embedded System and Mobile"
},
{
"code": null,
"e": 28948,
"s": 28705,
"text": "To deploy to the embedded system or Mobile, we can use Tensorflow Lite. It has smaller, faster, and has less dependencies than the Tensorflow, thus can be deployed into Embedded System or Mobile. Unfortunately it has limited set of operators."
},
{
"code": null,
"e": 29157,
"s": 28948,
"text": "There is also a tool called TensorRT. It optimized the inference engine used on prediction, thus sped up the inference process. It is built on CUDA. On embedding systems, NVIDIA Jetson TX2 works well with it."
},
{
"code": null,
"e": 29353,
"s": 29157,
"text": "On Apple, there is a tools called CoreML to make it easier to integrate ML System to the IPhone. There is also similar tools called MLKit which can be used to help deploying ML System to Android."
},
{
"code": null,
"e": 29726,
"s": 29353,
"text": "ONNX (Open Neural Network Exchange) is a open source format for Deep Learning models that can easily convert model into supported Deep Learning frameworks. ONNX supports Tensorflow, Pytorch, and Caffe2 . It can mix different frameworks such that frameworks that are good for developing (Pytorch) don’t need to be good at the deployment and inference (Tensorflow / Caffe2)."
},
{
"code": null,
"e": 30006,
"s": 29726,
"text": "If you deploy the application to cloud server, there should be a solution of the monitoring system. We can set the alarm when things go wrong by writing the record about it in the monitoring system. With this, we will know what can be improved with the model and fix the problem."
},
{
"code": null,
"e": 30617,
"s": 30006,
"text": "In this article, we get to know the steps on doing the Full Stack Deep Learning according to the FSDL course on March 2019. First, we need to setup and plan the project. We need to define the goals, metrics, and baseline in this step. Then, we collect the data and label it with available tools. In building the codebase, there are some tools that can maintain the quality of the project that have been described above. Then we do modeling with testing and debugging. After the model met the requirement, finally we know the step and tools for deploying and monitoring the application to the desired interface."
},
{
"code": null,
"e": 31083,
"s": 30617,
"text": "That’s it, my article about tools and steps introduced by the course that I’ve learned. Why do I write this article ? I found out that my brain can easily remember and make me understand better about the content of something that I need if I write it. Moreover, In the process of my writing, I get to have a chance to review the content of the course. Furthermore, It can make me to share my knowledge to everyone. I am happy to share something good to everyone :)."
},
{
"code": null,
"e": 31522,
"s": 31083,
"text": "I gain a lot of new things in following that course, especially about the tools of the Deep Learning Stacks. I also get to know how to troubleshoot model in Deep Learning since it is not easy to debug it. It also taught me the tools , steps, and tricks on doing the Full Stack Deep Learning. To sum it up, It’s a great courses and free to access. Therefore, I recommend it to anyone who want to learn about doing project in Deep Learning."
},
{
"code": null,
"e": 31790,
"s": 31522,
"text": "To be honest, I haven’t tried all the tools written in this article. The tools and its description that this article presents are taken from the FSDL course and some sources that I’ve read. You can tell me if there are some misinformation, especially about the tools."
},
{
"code": null,
"e": 31796,
"s": 31790,
"text": "Thus,"
},
{
"code": null,
"e": 32032,
"s": 31796,
"text": "I welcome any feedback that can improve myself and this article. I’m in the process of learning on writing and learning to become better. I apreciate a feedback to make me become better. Make sure to give feedback in a proper manner 😄."
},
{
"code": null,
"e": 32059,
"s": 32032,
"text": "See ya in my next article."
},
{
"code": null,
"e": 32067,
"s": 32059,
"text": "Sources"
},
{
"code": null,
"e": 32082,
"s": 32067,
"text": "www.guru99.com"
},
{
"code": null,
"e": 32093,
"s": 32082,
"text": "medium.com"
},
{
"code": null,
"e": 32108,
"s": 32093,
"text": "by DataKitchen"
},
{
"code": null,
"e": 32302,
"s": 32108,
"text": "https://docs.google.com/presentation/d/1yHLPvPhUs2KGI5ZWo0sU-PKU3GimAk3iTsI38Z-B5Gw/ (Presentation in ICLR 2019 about Reproducibility by Joel Grus). Figure 14 and 16 are taken from this source."
},
{
"code": null,
"e": 32328,
"s": 32302,
"text": "fullstackdeeplearning.com"
}
] |
Jupyter Notebook in a AWS EC2 Instance using Docker Image | Towards Data Science | Most of the data science and machine learning professionals are in love with the Jupyter notebook. Barring few anomalies, most of the data science and machine learning works are happening in the cloud. So there is no option but to use Jupyter on the cloud.
In my previous article, I explained how you can download the Jupyter notebook on AWS Linux instance and access it on your client machine using Xming and X11 forwarding. Below is the link to that article
towardsdatascience.com
In this article, I am explaining how to access the Jupyter notebook in AWS EC2 instance directly through a Docker image. No need to install Anaconda or Jupyter in the AWS EC2 instance.
I am assuming that you already have an AWS EC2 instance and know how to access it through Putty
Prerequisite Tools
Make sure you have the latest version of the default OS packages. Especially check if firewall related packages are installed and configured. I am using a Redhat Linux instance on AWS EC2.
The first thing to confirm is iptables-services are installed. If not, install it through yum
sudo yum install iptables-services
Now you are ready to install the Docker engine. I have followed instructions from the below link for installing the Docker engine on my Red Hat Linux instance. If you have an instance with a different operating system, please check the steps for that operating system in the below link.
docs.docker.com
a. First thing first; run the below command to install all the yum utilities
sudo yum install -y yum-utils
b. Get the latest docker repository
sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo
c. And now install the latest version of docker engine and container
sudo yum install docker-ce docker-ce-cli containerd.io
d. Start the docker service.
sudo systemctl start docker.service
If you do not get any error message, your docker service has started successfully.
e. You can also check the status of the docker service.
sudo systemctl status docker.service
Congratulations!! You have successfully installed a docker engine. Now you are ready to pull the Jupyter Notebook image.
It’s time to pull the Jupyter notebook image.
a. Run the below command to pull the docker image and start Jupyter notebook.
sudo docker run -p 8888:8888 jupyter/scipy-notebook
Wait for the image download and pull to complete.
You will get the message indicating Jupyter notebook is running and it will contain a link to Jupyter notebook.
b. Copy the link and remove the 127.0.0.1 with the public IP address of your instance. You can see the public IP address for your instance in EC2 Instance Connect tab.
c. If you get time out a message or a site can’t be reached message, your instance might not be allowing connection at port 8888.
d. Go to the security tab of your AWS instance and click on the security groups name.
e. Click on Edi inbound rules button.
e. Add a rule for port 8888 as shown below and save the rule.
f. Now refresh your browser. Jupyter notebook will come up.
Congratulations!! Your Jupyter notebook is waiting for your next data science or machine learning adventure!
Cloud and Docker images are becoming an inevitable part of data science and machine learning professionals' life. Docker images are like work already done for you. Use it as much as possible to reduce your turnaround time in projects. | [
{
"code": null,
"e": 429,
"s": 172,
"text": "Most of the data science and machine learning professionals are in love with the Jupyter notebook. Barring few anomalies, most of the data science and machine learning works are happening in the cloud. So there is no option but to use Jupyter on the cloud."
},
{
"code": null,
"e": 632,
"s": 429,
"text": "In my previous article, I explained how you can download the Jupyter notebook on AWS Linux instance and access it on your client machine using Xming and X11 forwarding. Below is the link to that article"
},
{
"code": null,
"e": 655,
"s": 632,
"text": "towardsdatascience.com"
},
{
"code": null,
"e": 840,
"s": 655,
"text": "In this article, I am explaining how to access the Jupyter notebook in AWS EC2 instance directly through a Docker image. No need to install Anaconda or Jupyter in the AWS EC2 instance."
},
{
"code": null,
"e": 936,
"s": 840,
"text": "I am assuming that you already have an AWS EC2 instance and know how to access it through Putty"
},
{
"code": null,
"e": 955,
"s": 936,
"text": "Prerequisite Tools"
},
{
"code": null,
"e": 1144,
"s": 955,
"text": "Make sure you have the latest version of the default OS packages. Especially check if firewall related packages are installed and configured. I am using a Redhat Linux instance on AWS EC2."
},
{
"code": null,
"e": 1238,
"s": 1144,
"text": "The first thing to confirm is iptables-services are installed. If not, install it through yum"
},
{
"code": null,
"e": 1273,
"s": 1238,
"text": "sudo yum install iptables-services"
},
{
"code": null,
"e": 1560,
"s": 1273,
"text": "Now you are ready to install the Docker engine. I have followed instructions from the below link for installing the Docker engine on my Red Hat Linux instance. If you have an instance with a different operating system, please check the steps for that operating system in the below link."
},
{
"code": null,
"e": 1576,
"s": 1560,
"text": "docs.docker.com"
},
{
"code": null,
"e": 1653,
"s": 1576,
"text": "a. First thing first; run the below command to install all the yum utilities"
},
{
"code": null,
"e": 1683,
"s": 1653,
"text": "sudo yum install -y yum-utils"
},
{
"code": null,
"e": 1719,
"s": 1683,
"text": "b. Get the latest docker repository"
},
{
"code": null,
"e": 1811,
"s": 1719,
"text": "sudo yum-config-manager --add-repo https://download.docker.com/linux/centos/docker-ce.repo"
},
{
"code": null,
"e": 1880,
"s": 1811,
"text": "c. And now install the latest version of docker engine and container"
},
{
"code": null,
"e": 1935,
"s": 1880,
"text": "sudo yum install docker-ce docker-ce-cli containerd.io"
},
{
"code": null,
"e": 1964,
"s": 1935,
"text": "d. Start the docker service."
},
{
"code": null,
"e": 2000,
"s": 1964,
"text": "sudo systemctl start docker.service"
},
{
"code": null,
"e": 2083,
"s": 2000,
"text": "If you do not get any error message, your docker service has started successfully."
},
{
"code": null,
"e": 2139,
"s": 2083,
"text": "e. You can also check the status of the docker service."
},
{
"code": null,
"e": 2176,
"s": 2139,
"text": "sudo systemctl status docker.service"
},
{
"code": null,
"e": 2297,
"s": 2176,
"text": "Congratulations!! You have successfully installed a docker engine. Now you are ready to pull the Jupyter Notebook image."
},
{
"code": null,
"e": 2343,
"s": 2297,
"text": "It’s time to pull the Jupyter notebook image."
},
{
"code": null,
"e": 2421,
"s": 2343,
"text": "a. Run the below command to pull the docker image and start Jupyter notebook."
},
{
"code": null,
"e": 2473,
"s": 2421,
"text": "sudo docker run -p 8888:8888 jupyter/scipy-notebook"
},
{
"code": null,
"e": 2523,
"s": 2473,
"text": "Wait for the image download and pull to complete."
},
{
"code": null,
"e": 2635,
"s": 2523,
"text": "You will get the message indicating Jupyter notebook is running and it will contain a link to Jupyter notebook."
},
{
"code": null,
"e": 2803,
"s": 2635,
"text": "b. Copy the link and remove the 127.0.0.1 with the public IP address of your instance. You can see the public IP address for your instance in EC2 Instance Connect tab."
},
{
"code": null,
"e": 2933,
"s": 2803,
"text": "c. If you get time out a message or a site can’t be reached message, your instance might not be allowing connection at port 8888."
},
{
"code": null,
"e": 3019,
"s": 2933,
"text": "d. Go to the security tab of your AWS instance and click on the security groups name."
},
{
"code": null,
"e": 3057,
"s": 3019,
"text": "e. Click on Edi inbound rules button."
},
{
"code": null,
"e": 3119,
"s": 3057,
"text": "e. Add a rule for port 8888 as shown below and save the rule."
},
{
"code": null,
"e": 3179,
"s": 3119,
"text": "f. Now refresh your browser. Jupyter notebook will come up."
},
{
"code": null,
"e": 3288,
"s": 3179,
"text": "Congratulations!! Your Jupyter notebook is waiting for your next data science or machine learning adventure!"
}
] |
Get the Current Working Directory in Java | The method java.lang.System.getProperty() is used to obtain the system property. This system property is specified by the key which is the parameter for the method. To obtain the current working directory, the key used is user.dir.
A program that demonstrates this is given as follows −
Live Demo
public class Demo {
public static void main(String[] argv) throws Exception {
String currentDirectory = System.getProperty("user.dir");
System.out.println("The current working directory is " + currentDirectory);
}
}
The output of the above program is as follows −
The current working directory is c:\JavaProgram
Now let us understand the above program.
The current working directory is obtained by using the key user.dir with the method java.lang.System.getProperty(). Then the current working directory is printed. A code snippet that demonstrates this is given as follows −
String currentDirectory = System.getProperty("user.dir");
System.out.println("The current working directory is " + currentDirectory); | [
{
"code": null,
"e": 1294,
"s": 1062,
"text": "The method java.lang.System.getProperty() is used to obtain the system property. This system property is specified by the key which is the parameter for the method. To obtain the current working directory, the key used is user.dir."
},
{
"code": null,
"e": 1349,
"s": 1294,
"text": "A program that demonstrates this is given as follows −"
},
{
"code": null,
"e": 1360,
"s": 1349,
"text": " Live Demo"
},
{
"code": null,
"e": 1594,
"s": 1360,
"text": "public class Demo {\n public static void main(String[] argv) throws Exception {\n String currentDirectory = System.getProperty(\"user.dir\");\n System.out.println(\"The current working directory is \" + currentDirectory);\n }\n}"
},
{
"code": null,
"e": 1642,
"s": 1594,
"text": "The output of the above program is as follows −"
},
{
"code": null,
"e": 1690,
"s": 1642,
"text": "The current working directory is c:\\JavaProgram"
},
{
"code": null,
"e": 1731,
"s": 1690,
"text": "Now let us understand the above program."
},
{
"code": null,
"e": 1954,
"s": 1731,
"text": "The current working directory is obtained by using the key user.dir with the method java.lang.System.getProperty(). Then the current working directory is printed. A code snippet that demonstrates this is given as follows −"
},
{
"code": null,
"e": 2088,
"s": 1954,
"text": "String currentDirectory = System.getProperty(\"user.dir\");\nSystem.out.println(\"The current working directory is \" + currentDirectory);"
}
] |
JavaScript Number - valueOf() | This method returns the primitive value of the specified number object.
Its syntax is as follows −
number.valueOf()
Returns the primitive value of the specified number object.
Try the following example.
<html>
<head>
<title>JavaScript valueOf() Method </title>
</head>
<body>
<script type = "text/javascript">
var num = new Number(15.11234);
document.write("num.valueOf() is " + num.valueOf());
</script>
</body>
</html>
num.valueOf() is 15.11234
25 Lectures
2.5 hours
Anadi Sharma
74 Lectures
10 hours
Lets Kode It
72 Lectures
4.5 hours
Frahaan Hussain
70 Lectures
4.5 hours
Frahaan Hussain
46 Lectures
6 hours
Eduonix Learning Solutions
88 Lectures
14 hours
Eduonix Learning Solutions
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2538,
"s": 2466,
"text": "This method returns the primitive value of the specified number object."
},
{
"code": null,
"e": 2565,
"s": 2538,
"text": "Its syntax is as follows −"
},
{
"code": null,
"e": 2583,
"s": 2565,
"text": "number.valueOf()\n"
},
{
"code": null,
"e": 2643,
"s": 2583,
"text": "Returns the primitive value of the specified number object."
},
{
"code": null,
"e": 2670,
"s": 2643,
"text": "Try the following example."
},
{
"code": null,
"e": 2952,
"s": 2670,
"text": "<html>\n <head>\n <title>JavaScript valueOf() Method </title>\n </head>\n \n <body> \n <script type = \"text/javascript\">\n var num = new Number(15.11234);\n document.write(\"num.valueOf() is \" + num.valueOf());\n </script> \n </body>\n</html>"
},
{
"code": null,
"e": 2980,
"s": 2952,
"text": "num.valueOf() is 15.11234 \n"
},
{
"code": null,
"e": 3015,
"s": 2980,
"text": "\n 25 Lectures \n 2.5 hours \n"
},
{
"code": null,
"e": 3029,
"s": 3015,
"text": " Anadi Sharma"
},
{
"code": null,
"e": 3063,
"s": 3029,
"text": "\n 74 Lectures \n 10 hours \n"
},
{
"code": null,
"e": 3077,
"s": 3063,
"text": " Lets Kode It"
},
{
"code": null,
"e": 3112,
"s": 3077,
"text": "\n 72 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3129,
"s": 3112,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3164,
"s": 3129,
"text": "\n 70 Lectures \n 4.5 hours \n"
},
{
"code": null,
"e": 3181,
"s": 3164,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 3214,
"s": 3181,
"text": "\n 46 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3242,
"s": 3214,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3276,
"s": 3242,
"text": "\n 88 Lectures \n 14 hours \n"
},
{
"code": null,
"e": 3304,
"s": 3276,
"text": " Eduonix Learning Solutions"
},
{
"code": null,
"e": 3311,
"s": 3304,
"text": " Print"
},
{
"code": null,
"e": 3322,
"s": 3311,
"text": " Add Notes"
}
] |
7 Tips To Write Clean And Better Code in 2020 - GeeksforGeeks | 16 Dec, 2019
Software engineering is not just all about learning a language and building some software. As a software engineer or software developer, you are expected to write good software. So the question is what makes good software?. Good software can be judged by reading some piece of code written in the project. If the code is easy to understand and easy to change then definitely it’s a good software and developers love to work on that.
It’s a common thing in development that nobody wants to continue a project with horrible or messy code (It becomes a nightmare for sometimes...). Sometimes developers avoid writing clean code due to deadline pressure. They rush to go faster but what happens actually is they end up with going slower. It creates more bugs which they need to fix later going back on the same piece of code. This process takes much more time than the amount of time spent on writing the code. A study has revealed that the ratio of time spent reading code versus writing is well over 10 to 1.
It doesn’t matter if you are a beginner or an experienced programmer, you should always try to become a good programmer (not just a programmer...). Remember that you are responsible for the quality of your code so make your program good enough so that other developers can understand and they don’t mock you every time to understand the messy code you wrote in your project.
What Makes a Clean Code: Before we discuss the art of writing clean and better code let’s see some characteristics of it...
Clean code should be readable. If someone is reading your code they should have feeling of reading a poetry or prose.Clean code should be elegant. It should be pleasing to read and it should make you smile.Clean code should be simple and easy to understand. It should follow single responsibility principle (SRP).Clean code should be easy to understand, easy to change and easy to taken care of.Clean code should run all the tests.
Clean code should be readable. If someone is reading your code they should have feeling of reading a poetry or prose.
Clean code should be elegant. It should be pleasing to read and it should make you smile.
Clean code should be simple and easy to understand. It should follow single responsibility principle (SRP).
Clean code should be easy to understand, easy to change and easy to taken care of.
Clean code should run all the tests.
“Clean code is simple and direct. Clean code reads like a well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”-Grady Booch (Author of Object-Oriented Analysis and Design with Applications)
You will be writing a lot of names for variables, functions, classes, arguments, modules, packages, directories and things like that. Make a habit to use meaningful names in your code. Whatever names you mention in your code it should fulfill three purposes...what it does, why it exists and how it is used. For Example:
int b; // number of users.
In the above example, you need to mention a comment along with the name declaration of a variable which is not a characteristic of a good code. The name that you specify in your code should reveal it’s intent. It should specify the purpose of a variable, function or methods. So for the above example, a better variable name would be:- int number_of_users. It may take some time to choose meaningful names but it makes your code much cleaner and easy to read for other developers as well as for yourself. Also, try to limit the names to three or four words.
Classes, Functions or methods are a good way to organize the code in any programming language so when you are writing the code you really need to take care that how to write a function that communicates it’s intent. Most of the beginners do this mistake that they write a function that can handle and do almost everything (perform multiple tasks). It makes your code more confusing for developers and creates problems when they need to fix some bugs or find some piece of code. So when you are writing a function you should remember two things to make your function clean and easy to understand...
They should be small.They should do only one thing and they should do it well.
They should be small.
They should do only one thing and they should do it well.
The above two points clearly mention that your function should follow single responsibility principle. Which means it shouldn’t have nested structure or it should not have more than two indent level. Following this technique make your code much more readable and other developers can easily understand or implement another feature if your function fulfills a specific task.Also, make sure that your function should not have more than three arguments. More arguments perform more tasks so try to keep the arguments as less as possible. Passing more than three arguments makes your code confusing, quite large and hard to debug if any problem would be there. If your function has try/catch/finally statement then make a separate function containing just the try-catch-finally statements.Take care of your function name as well. Use a descriptive name for your function which should clearly specify that what it does.
Example:
function subtract(x, y) {
return x - y;
}
In the above example the function name clearly shows that it’s purpose is to perform subtraction for two numbers, also it has only two arguments. Read more about writing a good function from the link 7 Common Programming Principles That Every Developer Must Follow and SOLID Principle.
It’s a common thing that developers use comments to specify the purpose of a line in their code. It’s true that comments are really helpful in explaining the code what it does but it also requires more maintenance of your code. In development code move here and there but if the comment remains at the same place then it can create a big problem. It can create confusion among developers and they get distracted as well due to useless comments. It’s not like that you shouldn’t use comments at all, sometimes it is important, for example...if you are dealing with third party API where you need to explain some behavior there you can use comments to explain your code but don’t write comments where it’s not necessary.Today modern programming languages syntax are English like through and that’s good enough to explain the purpose of a line in your code. To avoid comments in your code use meaningful names for variables, functions or files.
Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer.-Steve McConnell
A lot of people especially beginners make mistake while writing a code that they write everything in a single line and don’t give proper whitespace, indentation or line breaks in their code. It makes their code messy and difficult to maintain. There’s always a chance that another human will get to your code and they will have to work with it. It wastes other developers’ time when they try to read and understand the messy code. So always pay attention to the formatting of your code. You will also save your time and energy when you will get back to your own code after a couple of days to make some changes. So make sure that your code should have a proper indentation, space and line breaks to make it readable for other people. The coding style and formatting affect the maintainability of your code. A software developer is always remembered for the coding style he/she follow in his/her code.
// Bad Codeclass CarouselRightArrow extends Component{render(){return ( <a href="#" className="carousel__arrow carousel__arrow--left" onClick={this.props.onClick}> <span className="fa fa-2x fa-angle-left"/> </a> );}}; // Good Codeclass CarouselRightArrow extends Component { render() { return ( <a href="#" className="carousel__arrow carousel__arrow--left" onClick={this.props.onClick} > <span className="fa fa-2x fa-angle-left" /> </a> ); }};
Code formatting is about communication, and communication is the professional developer’s first order of business.-Robert C. Martin (Uncle Bob)
Writing Unit test is very important in development. It makes your code clean, flexible and maintainable. Making changes in code and reducing bugs becomes easier. There is a process in software development which is called Test Driven Development (TDD) in which requirements are turned into some specific test cases then the software is improved to pass new tests. According to Robert C. Martin (Uncle Bob), the three laws of TDD demonstrate...
You are not allowed to write any production code unless it is to make a failing unit test pass.You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures.You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
You are not allowed to write any production code unless it is to make a failing unit test pass.
You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures.
You are not allowed to write any more production code than is sufficient to pass the one failing unit test.
After I jumped on board the unit testing bandwagon, the quality of what I deliver has increased to the point that the amount of respect I get from my colleagues makes me feel awkward. They think I’m blessed or something. I’m not gifted or blessed or even that talented, I just test my code.– Justin Yancey, Senior Systems Development Engineer, Amazon
In software development, you really need to be careful about your dependencies. If possible your dependencies should always be a singular direction. It means....let’s say we have a kitchen class which is dependent on a dishwasher class. As long as the dishwasher doesn’t also dependent on the kitchen class this is a one-directional dependency. The kitchen class is just using the dishwasher but the dishwasher doesn’t really care and anyone can use it. It doesn’t have to be a kitchen. This example of one-directional dependency is easier to manage however it’s impossible to always have one-directional dependency but we should try to have as many as possible. When dependency goes in multiple directions, things get much more complicated. In bidirectional dependency both the entities depend on each other, so they have to exist together even though they are separate. It becomes hard to update some systems when their dependencies don’t form a singular direction. So always be careful about managing your dependencies.
This is a very common problem in software development that we add and delete so many files or directories in our project and sometimes it becomes complicated and annoying for other developers to understand the project and work on that. We agree that you can not design a perfect organization of folders or files on day one but later on, when your project becomes larger you really need to be careful about the organization of your folder, files, and directories. A well-structured folder and file make everything clear and it becomes easier to understand a complete project, search some specific folder and make changes in it. So make sure that your directory or folder structure should be in an organized manner (Same applies for your code as well).
Best Books For Understanding How to Write Clean and Better Code:
Clean Code
Code Complete
GBlog
Programming Language
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Top 10 Front End Developer Skills That You Need in 2022
DSA Sheet by Love Babbar
6 Best IDE's For Python in 2022
GET and POST requests using Python
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Arrow operator -> in C/C++ with Examples
Modulo Operator (%) in C/C++ with Examples
Structures in C++
Differences between Procedural and Object Oriented Programming
Top 10 Programming Languages to Learn in 2022 | [
{
"code": null,
"e": 24533,
"s": 24505,
"text": "\n16 Dec, 2019"
},
{
"code": null,
"e": 24966,
"s": 24533,
"text": "Software engineering is not just all about learning a language and building some software. As a software engineer or software developer, you are expected to write good software. So the question is what makes good software?. Good software can be judged by reading some piece of code written in the project. If the code is easy to understand and easy to change then definitely it’s a good software and developers love to work on that."
},
{
"code": null,
"e": 25540,
"s": 24966,
"text": "It’s a common thing in development that nobody wants to continue a project with horrible or messy code (It becomes a nightmare for sometimes...). Sometimes developers avoid writing clean code due to deadline pressure. They rush to go faster but what happens actually is they end up with going slower. It creates more bugs which they need to fix later going back on the same piece of code. This process takes much more time than the amount of time spent on writing the code. A study has revealed that the ratio of time spent reading code versus writing is well over 10 to 1."
},
{
"code": null,
"e": 25915,
"s": 25540,
"text": "It doesn’t matter if you are a beginner or an experienced programmer, you should always try to become a good programmer (not just a programmer...). Remember that you are responsible for the quality of your code so make your program good enough so that other developers can understand and they don’t mock you every time to understand the messy code you wrote in your project."
},
{
"code": null,
"e": 26039,
"s": 25915,
"text": "What Makes a Clean Code: Before we discuss the art of writing clean and better code let’s see some characteristics of it..."
},
{
"code": null,
"e": 26471,
"s": 26039,
"text": "Clean code should be readable. If someone is reading your code they should have feeling of reading a poetry or prose.Clean code should be elegant. It should be pleasing to read and it should make you smile.Clean code should be simple and easy to understand. It should follow single responsibility principle (SRP).Clean code should be easy to understand, easy to change and easy to taken care of.Clean code should run all the tests."
},
{
"code": null,
"e": 26589,
"s": 26471,
"text": "Clean code should be readable. If someone is reading your code they should have feeling of reading a poetry or prose."
},
{
"code": null,
"e": 26679,
"s": 26589,
"text": "Clean code should be elegant. It should be pleasing to read and it should make you smile."
},
{
"code": null,
"e": 26787,
"s": 26679,
"text": "Clean code should be simple and easy to understand. It should follow single responsibility principle (SRP)."
},
{
"code": null,
"e": 26870,
"s": 26787,
"text": "Clean code should be easy to understand, easy to change and easy to taken care of."
},
{
"code": null,
"e": 26907,
"s": 26870,
"text": "Clean code should run all the tests."
},
{
"code": null,
"e": 27191,
"s": 26907,
"text": "“Clean code is simple and direct. Clean code reads like a well-written prose. Clean code never obscures the designer’s intent but rather is full of crisp abstractions and straightforward lines of control.”-Grady Booch (Author of Object-Oriented Analysis and Design with Applications)"
},
{
"code": null,
"e": 27512,
"s": 27191,
"text": "You will be writing a lot of names for variables, functions, classes, arguments, modules, packages, directories and things like that. Make a habit to use meaningful names in your code. Whatever names you mention in your code it should fulfill three purposes...what it does, why it exists and how it is used. For Example:"
},
{
"code": null,
"e": 27539,
"s": 27512,
"text": "int b; // number of users."
},
{
"code": null,
"e": 28097,
"s": 27539,
"text": "In the above example, you need to mention a comment along with the name declaration of a variable which is not a characteristic of a good code. The name that you specify in your code should reveal it’s intent. It should specify the purpose of a variable, function or methods. So for the above example, a better variable name would be:- int number_of_users. It may take some time to choose meaningful names but it makes your code much cleaner and easy to read for other developers as well as for yourself. Also, try to limit the names to three or four words."
},
{
"code": null,
"e": 28695,
"s": 28097,
"text": "Classes, Functions or methods are a good way to organize the code in any programming language so when you are writing the code you really need to take care that how to write a function that communicates it’s intent. Most of the beginners do this mistake that they write a function that can handle and do almost everything (perform multiple tasks). It makes your code more confusing for developers and creates problems when they need to fix some bugs or find some piece of code. So when you are writing a function you should remember two things to make your function clean and easy to understand..."
},
{
"code": null,
"e": 28774,
"s": 28695,
"text": "They should be small.They should do only one thing and they should do it well."
},
{
"code": null,
"e": 28796,
"s": 28774,
"text": "They should be small."
},
{
"code": null,
"e": 28854,
"s": 28796,
"text": "They should do only one thing and they should do it well."
},
{
"code": null,
"e": 29769,
"s": 28854,
"text": "The above two points clearly mention that your function should follow single responsibility principle. Which means it shouldn’t have nested structure or it should not have more than two indent level. Following this technique make your code much more readable and other developers can easily understand or implement another feature if your function fulfills a specific task.Also, make sure that your function should not have more than three arguments. More arguments perform more tasks so try to keep the arguments as less as possible. Passing more than three arguments makes your code confusing, quite large and hard to debug if any problem would be there. If your function has try/catch/finally statement then make a separate function containing just the try-catch-finally statements.Take care of your function name as well. Use a descriptive name for your function which should clearly specify that what it does."
},
{
"code": null,
"e": 29778,
"s": 29769,
"text": "Example:"
},
{
"code": null,
"e": 29825,
"s": 29778,
"text": "function subtract(x, y) {\n return x - y;\n}\n"
},
{
"code": null,
"e": 30111,
"s": 29825,
"text": "In the above example the function name clearly shows that it’s purpose is to perform subtraction for two numbers, also it has only two arguments. Read more about writing a good function from the link 7 Common Programming Principles That Every Developer Must Follow and SOLID Principle."
},
{
"code": null,
"e": 31053,
"s": 30111,
"text": "It’s a common thing that developers use comments to specify the purpose of a line in their code. It’s true that comments are really helpful in explaining the code what it does but it also requires more maintenance of your code. In development code move here and there but if the comment remains at the same place then it can create a big problem. It can create confusion among developers and they get distracted as well due to useless comments. It’s not like that you shouldn’t use comments at all, sometimes it is important, for example...if you are dealing with third party API where you need to explain some behavior there you can use comments to explain your code but don’t write comments where it’s not necessary.Today modern programming languages syntax are English like through and that’s good enough to explain the purpose of a line in your code. To avoid comments in your code use meaningful names for variables, functions or files."
},
{
"code": null,
"e": 31285,
"s": 31053,
"text": "Good code is its own best documentation. As you’re about to add a comment, ask yourself, “How can I improve the code so that this comment isn’t needed?” Improve the code and then document it to make it even clearer.-Steve McConnell"
},
{
"code": null,
"e": 32186,
"s": 31285,
"text": "A lot of people especially beginners make mistake while writing a code that they write everything in a single line and don’t give proper whitespace, indentation or line breaks in their code. It makes their code messy and difficult to maintain. There’s always a chance that another human will get to your code and they will have to work with it. It wastes other developers’ time when they try to read and understand the messy code. So always pay attention to the formatting of your code. You will also save your time and energy when you will get back to your own code after a couple of days to make some changes. So make sure that your code should have a proper indentation, space and line breaks to make it readable for other people. The coding style and formatting affect the maintainability of your code. A software developer is always remembered for the coding style he/she follow in his/her code."
},
{
"code": "// Bad Codeclass CarouselRightArrow extends Component{render(){return ( <a href=\"#\" className=\"carousel__arrow carousel__arrow--left\" onClick={this.props.onClick}> <span className=\"fa fa-2x fa-angle-left\"/> </a> );}}; // Good Codeclass CarouselRightArrow extends Component { render() { return ( <a href=\"#\" className=\"carousel__arrow carousel__arrow--left\" onClick={this.props.onClick} > <span className=\"fa fa-2x fa-angle-left\" /> </a> ); }};",
"e": 32682,
"s": 32186,
"text": null
},
{
"code": null,
"e": 32826,
"s": 32682,
"text": "Code formatting is about communication, and communication is the professional developer’s first order of business.-Robert C. Martin (Uncle Bob)"
},
{
"code": null,
"e": 33269,
"s": 32826,
"text": "Writing Unit test is very important in development. It makes your code clean, flexible and maintainable. Making changes in code and reducing bugs becomes easier. There is a process in software development which is called Test Driven Development (TDD) in which requirements are turned into some specific test cases then the software is improved to pass new tests. According to Robert C. Martin (Uncle Bob), the three laws of TDD demonstrate..."
},
{
"code": null,
"e": 33591,
"s": 33269,
"text": "You are not allowed to write any production code unless it is to make a failing unit test pass.You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures.You are not allowed to write any more production code than is sufficient to pass the one failing unit test."
},
{
"code": null,
"e": 33687,
"s": 33591,
"text": "You are not allowed to write any production code unless it is to make a failing unit test pass."
},
{
"code": null,
"e": 33807,
"s": 33687,
"text": "You are not allowed to write any more of a unit test than is sufficient to fail, and compilation failures are failures."
},
{
"code": null,
"e": 33915,
"s": 33807,
"text": "You are not allowed to write any more production code than is sufficient to pass the one failing unit test."
},
{
"code": null,
"e": 34266,
"s": 33915,
"text": "After I jumped on board the unit testing bandwagon, the quality of what I deliver has increased to the point that the amount of respect I get from my colleagues makes me feel awkward. They think I’m blessed or something. I’m not gifted or blessed or even that talented, I just test my code.– Justin Yancey, Senior Systems Development Engineer, Amazon"
},
{
"code": null,
"e": 35289,
"s": 34266,
"text": "In software development, you really need to be careful about your dependencies. If possible your dependencies should always be a singular direction. It means....let’s say we have a kitchen class which is dependent on a dishwasher class. As long as the dishwasher doesn’t also dependent on the kitchen class this is a one-directional dependency. The kitchen class is just using the dishwasher but the dishwasher doesn’t really care and anyone can use it. It doesn’t have to be a kitchen. This example of one-directional dependency is easier to manage however it’s impossible to always have one-directional dependency but we should try to have as many as possible. When dependency goes in multiple directions, things get much more complicated. In bidirectional dependency both the entities depend on each other, so they have to exist together even though they are separate. It becomes hard to update some systems when their dependencies don’t form a singular direction. So always be careful about managing your dependencies."
},
{
"code": null,
"e": 36040,
"s": 35289,
"text": "This is a very common problem in software development that we add and delete so many files or directories in our project and sometimes it becomes complicated and annoying for other developers to understand the project and work on that. We agree that you can not design a perfect organization of folders or files on day one but later on, when your project becomes larger you really need to be careful about the organization of your folder, files, and directories. A well-structured folder and file make everything clear and it becomes easier to understand a complete project, search some specific folder and make changes in it. So make sure that your directory or folder structure should be in an organized manner (Same applies for your code as well)."
},
{
"code": null,
"e": 36105,
"s": 36040,
"text": "Best Books For Understanding How to Write Clean and Better Code:"
},
{
"code": null,
"e": 36116,
"s": 36105,
"text": "Clean Code"
},
{
"code": null,
"e": 36130,
"s": 36116,
"text": "Code Complete"
},
{
"code": null,
"e": 36136,
"s": 36130,
"text": "GBlog"
},
{
"code": null,
"e": 36157,
"s": 36136,
"text": "Programming Language"
},
{
"code": null,
"e": 36255,
"s": 36157,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 36264,
"s": 36255,
"text": "Comments"
},
{
"code": null,
"e": 36277,
"s": 36264,
"text": "Old Comments"
},
{
"code": null,
"e": 36333,
"s": 36277,
"text": "Top 10 Front End Developer Skills That You Need in 2022"
},
{
"code": null,
"e": 36358,
"s": 36333,
"text": "DSA Sheet by Love Babbar"
},
{
"code": null,
"e": 36390,
"s": 36358,
"text": "6 Best IDE's For Python in 2022"
},
{
"code": null,
"e": 36425,
"s": 36390,
"text": "GET and POST requests using Python"
},
{
"code": null,
"e": 36487,
"s": 36425,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 36528,
"s": 36487,
"text": "Arrow operator -> in C/C++ with Examples"
},
{
"code": null,
"e": 36571,
"s": 36528,
"text": "Modulo Operator (%) in C/C++ with Examples"
},
{
"code": null,
"e": 36589,
"s": 36571,
"text": "Structures in C++"
},
{
"code": null,
"e": 36652,
"s": 36589,
"text": "Differences between Procedural and Object Oriented Programming"
}
] |
C# program to check if string is panagram or not | A pangram has all the 26 letters of an alphabet.
Below, we have entered a string, and will check whether it is a pangram or not −
string str = "The quick brown fox jumps over the lazy dog";
Now, check using the ToLower(), isLetter() and Count() functions that the string has all the 26 letters of not since pangram has all the 26 letters of an alphabet.
You can try to run the following code to check whether a string is pangram or not.
Live Demo
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace Demo {
public class Program {
public static void Main(string []arg) {
string str = "The quick brown fox jumps over the lazy dog";
Console.WriteLine("{0}: \"{1}\" is pangram", checkPangram(str), str);
Console.ReadKey();
}
static bool checkPangram(string str) {
return str.ToLower().Where(ch => Char.IsLetter(ch)).GroupBy(ch => ch).Count() == 26;
}
}
}
True: "The quick brown fox jumps over the lazy dog" is pangram | [
{
"code": null,
"e": 1111,
"s": 1062,
"text": "A pangram has all the 26 letters of an alphabet."
},
{
"code": null,
"e": 1192,
"s": 1111,
"text": "Below, we have entered a string, and will check whether it is a pangram or not −"
},
{
"code": null,
"e": 1252,
"s": 1192,
"text": "string str = \"The quick brown fox jumps over the lazy dog\";"
},
{
"code": null,
"e": 1416,
"s": 1252,
"text": "Now, check using the ToLower(), isLetter() and Count() functions that the string has all the 26 letters of not since pangram has all the 26 letters of an alphabet."
},
{
"code": null,
"e": 1499,
"s": 1416,
"text": "You can try to run the following code to check whether a string is pangram or not."
},
{
"code": null,
"e": 1509,
"s": 1499,
"text": "Live Demo"
},
{
"code": null,
"e": 2041,
"s": 1509,
"text": "using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text.RegularExpressions;\nnamespace Demo {\n public class Program {\n public static void Main(string []arg) {\n string str = \"The quick brown fox jumps over the lazy dog\";\n Console.WriteLine(\"{0}: \\\"{1}\\\" is pangram\", checkPangram(str), str);\n Console.ReadKey();\n }\n static bool checkPangram(string str) {\n return str.ToLower().Where(ch => Char.IsLetter(ch)).GroupBy(ch => ch).Count() == 26;\n }\n }\n}"
},
{
"code": null,
"e": 2104,
"s": 2041,
"text": "True: \"The quick brown fox jumps over the lazy dog\" is pangram"
}
] |
QlikView - Dimensions and Measures | Dimensions and Measures are fundamental entities, which are always used in data analysis. For example, consider the result of the analysis, “what is the percentage change in volume of sales for each quarter?” In this case, each quarter represents the Dimensions, which is the name of the quarter. The percentage change in volume represents the Measures, which is a calculation with respect to each value in the dimension. Below are some widely accepted definition of these two terms.
Dimension − It is a descriptive field in the data set which represents few distinct values. Examples − Month, Year, Product ID etc.
Measures − It is a numeric field on which some calculations are performed for each distinct value of dimension.
Let us consider the following input data, which represents the sales volume and Revenue of different product lines and product categories in different regions. Save the data into a .csv file.
ProductID,ProductCategory,Region,SalesVolume, Revenue
1,Outdoor Recreation,Europe,457,25841
2,Clothing,Europe,125,54281
3,Costumes & Accessories,South Asia,781,54872
4,Athletics,South Asia,839,87361
5,Personal Care,Australia,473,15425
6,Arts & Entertainment,North AMerica,625,84151
7,Hardware,South America,772,45812
The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into the QlikView's memory
We can see the structure of the table by following the menu File → Table Viewer or pressing Control+T. The following screen comes up in which we have marked the dimensions inside a green box and the measures inside a red box.
Let us create a straight table chart showing the calculation using above dimensions and measures. Click on the Quick Chart Wizard as shown below.
Next, click on the Straight Table option. Click Next.
In this screen, we choose Region as the dimension as we want to select the total revenue for each region.
The Next screen prompts for applying the calculation on a measure field. We choose to apply Sum on the field Revenue.
On completing the above steps, we get the final chart which shows the total revenue(Measure) for each region(Dimension).
70 Lectures
5 hours
Arthur Fong
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 3404,
"s": 2920,
"text": "Dimensions and Measures are fundamental entities, which are always used in data analysis. For example, consider the result of the analysis, “what is the percentage change in volume of sales for each quarter?” In this case, each quarter represents the Dimensions, which is the name of the quarter. The percentage change in volume represents the Measures, which is a calculation with respect to each value in the dimension. Below are some widely accepted definition of these two terms."
},
{
"code": null,
"e": 3536,
"s": 3404,
"text": "Dimension − It is a descriptive field in the data set which represents few distinct values. Examples − Month, Year, Product ID etc."
},
{
"code": null,
"e": 3648,
"s": 3536,
"text": "Measures − It is a numeric field on which some calculations are performed for each distinct value of dimension."
},
{
"code": null,
"e": 3840,
"s": 3648,
"text": "Let us consider the following input data, which represents the sales volume and Revenue of different product lines and product categories in different regions. Save the data into a .csv file."
},
{
"code": null,
"e": 4158,
"s": 3840,
"text": "ProductID,ProductCategory,Region,SalesVolume, Revenue\n1,Outdoor Recreation,Europe,457,25841\n2,Clothing,Europe,125,54281\n3,Costumes & Accessories,South Asia,781,54872\n4,Athletics,South Asia,839,87361\n5,Personal Care,Australia,473,15425\n6,Arts & Entertainment,North AMerica,625,84151\n7,Hardware,South America,772,45812\n"
},
{
"code": null,
"e": 4479,
"s": 4158,
"text": "The above data is loaded to the QlikView memory by using the script editor. Open the Script editor from the File menu or press Control+E. Choose the Table Files option from the Data from Files tab and browse for the file containing the above data. Click OK and press Control+R to load the data into the QlikView's memory"
},
{
"code": null,
"e": 4705,
"s": 4479,
"text": "We can see the structure of the table by following the menu File → Table Viewer or pressing Control+T. The following screen comes up in which we have marked the dimensions inside a green box and the measures inside a red box."
},
{
"code": null,
"e": 4851,
"s": 4705,
"text": "Let us create a straight table chart showing the calculation using above dimensions and measures. Click on the Quick Chart Wizard as shown below."
},
{
"code": null,
"e": 4905,
"s": 4851,
"text": "Next, click on the Straight Table option. Click Next."
},
{
"code": null,
"e": 5011,
"s": 4905,
"text": "In this screen, we choose Region as the dimension as we want to select the total revenue for each region."
},
{
"code": null,
"e": 5129,
"s": 5011,
"text": "The Next screen prompts for applying the calculation on a measure field. We choose to apply Sum on the field Revenue."
},
{
"code": null,
"e": 5250,
"s": 5129,
"text": "On completing the above steps, we get the final chart which shows the total revenue(Measure) for each region(Dimension)."
},
{
"code": null,
"e": 5283,
"s": 5250,
"text": "\n 70 Lectures \n 5 hours \n"
},
{
"code": null,
"e": 5296,
"s": 5283,
"text": " Arthur Fong"
},
{
"code": null,
"e": 5303,
"s": 5296,
"text": " Print"
},
{
"code": null,
"e": 5314,
"s": 5303,
"text": " Add Notes"
}
] |
3-Way Radix Quicksort in Java - GeeksforGeeks | 28 Jan, 2022
Basically, as the name suggests that 3-Way Radix Quicksort is a combination of both radix and 3-way quicksort. It is a hybrid sort which is in between of both radix and 3-way quicksort. This algorithm is mainly used to sort strings.
The main idea behind the radix sort is to use the digits (beginning from LSD to MSD) of all the integers to perform hashing and dividing them into a separate list and them joining. In the same way, we will be using the MSD character of the strings and then using these characters we go on performing what is known as 3-way quicksort.
3-way quicksort is basically a case of general quicksort only. The idea is that if we use quicksort then there can be a situation that we would get the same characters in the array of characters(here we are sorting strings using radix sort idea, to take all the Characters one by one to sort).
So to handle such a situation we divide the array into three parts:
The partition contains characters less than the pivot character.The partition for characters that are equal to that of the pivot character.The last partition contains characters that are greater than the pivot character.
The partition contains characters less than the pivot character.
The partition for characters that are equal to that of the pivot character.
The last partition contains characters that are greater than the pivot character.
So basically what is going to happen is :
We would consider the MSD character of each string(the idea of radix sort).Then we will perform quicksort on this array of characters, which will result in the partition of the array into 3 parts(as discussed above).
We would consider the MSD character of each string(the idea of radix sort).
Then we will perform quicksort on this array of characters, which will result in the partition of the array into 3 parts(as discussed above).
This division is shown in the below figure.
Explanation of image:
So basically as shown that there are 11 strings in the array, and we have to sort them. So now considering the first character of all strings gives an array of {s,a,h,s,s,z,b,t,c,u,s}. This is the idea got from radix sort. Now we are to sort this array of characters on the basis of the idea of quick sort.
So here the pivot element we are considering is first element of array i.e. ‘s’. Now we are using quicksort to make partition. Partitions are done on the basis that :
First we are considering the first character as the pivot and also we have to pointers ‘i’ and ‘j’. Pointer ‘i’ moves form start to end and ‘j’ moves from end to start. Initially i=1 and j =n-1; this would help us to get the two boundary index of the second partition.
Ranges of partition than would be 1st one form 0 – i , 2nd form i+1 – j-1 and third form j to n-1;
if arr[i]<pivot: pivot is swapped with arr[i] (please Note that here string are swapped and not the characters of the string)if arr[i]==pivot it is remained there only, and the pointer is incremented to next one.if arr[i]>pivot, the string at j is swapped with arr[i] string and j is decremented.
if arr[i]<pivot: pivot is swapped with arr[i] (please Note that here string are swapped and not the characters of the string)
if arr[i]==pivot it is remained there only, and the pointer is incremented to next one.
if arr[i]>pivot, the string at j is swapped with arr[i] string and j is decremented.
So after performing these operations we will get the three partitioned array as shown.
After getting the partitions we can see that in the second one we are not able to recursively perform quicksort on the first character of string since in that partition all the strings are having the same first character(here in this example it is ‘s’). So we will be going for doing partition on the basis of the next character. And for the other two, we will recall the same sort again starting from the first character. This is the whole idea about 3-way quicksort.
The main thing here to notice that is all string are not of the same length so at some step we can have a condition that there will be no further characters of the pivot string and other strings are having characters and hence swapping and comparisons of the characters are not possible in that case.
So to handle that case we would first find the max length of strings in the array and then append each string with a character that has ASCII value smaller than the alphabet.
Why smaller?
consider an example:
Array is a={hero, heroes, her}
Here if we give each string with fewer characters than the max amount needed(i.e. 6) a character which is greater than alphabets (say ‘~’), then a will become a={hero~~, heroes, her~~~}.
sorting this array would give the result as {heroes, hero~~, her~~~} but the real answer should be {her, hero, heroes}.
Performing the above algorithm recursively will generate a sorted array and hence we will be able to sort the array of strings.
Recursive Implementation:
Java
// Java program for 3-Way Radix Quicksort import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Scanner;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipInputStream; public class GFG { // swapping method. public static void swp(String[] s, int x, int y) { String tmp = s[x]; s[x] = s[y]; s[y] = tmp; } // sort method. public static void srt(String[] s, int start, int last, int character_index) { // base condition if no further index possible. if (start >= last) return; // first making a start pointer for dividing the // list from start to start_pointer. int start_pointer = start; // last_pointer and last are the boundaries for the // third list. int last_pointer = last; // taking the ascii value of the pivot at the index // given. int char_ascii_value_pivot = s[start].charAt(character_index); int pointer = start + 1; // starting a pointer to scan the whole array to // sort. while (pointer <= last) { // ASCII value of char at the position of all // the strings to compare with that of the pivot // char. int char_ascii_value_element = s[pointer].charAt(character_index); // if the element has char less than pivot than // swapping it with the top element and // incrementing the top boundary of the first // list. if (char_ascii_value_pivot > char_ascii_value_element) { swp(s, start_pointer, pointer); start_pointer++; // incrementing the pointer to check for // next string. pointer++; } else // if found larger character than it is // replaced by the element at last_pointer // and lower boundary is raised by // decrementing it. if (char_ascii_value_pivot < char_ascii_value_element) { swp(s, last_pointer, pointer); last_pointer--; pointer++; } // if character is the same as that of the pivot // then no need to swap and move the pointer on else { pointer++; } } // now performing same sort on the first list // bounded by start and start_pointer with same // character_index srt(s, start, start_pointer - 1, character_index); // if we have more character left in the pivot // element than recall quicksort on the second list // bounded by start_pointer and last_pointer and // next character_index. if (char_ascii_value_pivot >= 0) srt(s, start_pointer, last_pointer, character_index + 1); // lastly the third list with boundaries as // last_pointer and last. srt(s, last_pointer + 1, last, character_index); } public static void main(String[] args) throws Exception { // predefined array of five element all of same // length. String s[] = { "some", "same", "hero", "make", "zero" }; // calling sort function to sort the array using // 3-way-radix-quicksort. srt(s, 0, 4, 0); // printing the sorted array; // here w are calling function by passing parameters // using references . for (int i = 0; i < 5; ++i) System.out.println(s[i]); }}
hero
make
same
some
zero
Example 2: To sort strings with different lengths.
Java
// Java program for 3-Way radix QuickSort import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Scanner;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipInputStream; public class GFG { // swapping method. public static void swp(String[] s, int x, int y) { String tmp = s[x]; s[x] = s[y]; s[y] = tmp; } // sort method. public static void srt(String[] s, int start, int last, int character_index) { // base condition if no further index possible. if (start >= last) return; // first making a start pointer for dividing the // list from start to start_pointer. int start_pointer = start; // last_pointer and last are the boundaries for the // third list. int last_pointer = last; // taking the ASCII value of the pivot at the index // given. int char_ascii_value_pivot = s[start].charAt(character_index); int pointer = start + 1; // starting a pointer to scan the whole array to // sort. while (pointer <= last) { // ASCII value of char at the position of all // the strings to compare with that of the pivot // char. int char_ascii_value_element = s[pointer].charAt(character_index); // if the element has char less than pivot than // swapping it with the top element and // incrementing the top boundary of the first // list. if (char_ascii_value_pivot> char_ascii_value_element) { swp(s, start_pointer, pointer); start_pointer++; // incrementing the pointer to check for // next string. pointer++; } else // if found larger character than it is // replaced by the element at last_pointer // and lower boundary is raised by // decrementing it. if (char_ascii_value_pivot< char_ascii_value_element) { swp(s, last_pointer, pointer); last_pointer--; pointer++; } // if character is same as that of the pivot then // no need to swap and move the pointer on else { pointer++; } } // now performing same sort on the first list // bounded by start and start_pointer with same // character_index srt(s, start, start_pointer - 1, character_index); // if we have more character left in the pivot // element than recall quicksort on the second list // bounded by start_pointer and last_pointer and // next character_index. if (char_ascii_value_pivot >= 0) srt(s, start_pointer, last_pointer,character_index + 1); // lastly the third list with boundaries as // last_pointer and last. srt(s, last_pointer + 1, last, character_index); } public static void main(String[] args) throws Exception { // predefined array of five element all of different // length. String s[] = { "sam", "same", "her", "make", "zebra" }; int max_character_index = 0; // finding max_character_index for (int i = 0; i < 5; ++i) if (s[i].length() > max_character_index) max_character_index = s[i].length(); // adding each string with a character having less // ascii value than alphabets. for (int i = 0; i < 5; ++i) if (s[i].length() < max_character_index) while (s[i].length() < max_character_index) s[i] += '?'; // calling sort function to sort the array using // 3-way-radix-quicksort. srt(s, 0, 4, 0); // printing the sorted array; // here we are calling function by passing // parameters using references . printing without the // appended character. for (int i = 0; i < 5; ++i) { String ans = ""; for (int j = 0; j < s[i].length(); ++j) if (s[i].charAt(j) != '?') ans += s[i].charAt(j); else break; System.out.println(ans); } }}
her
make
sam
same
zebra
simmytarika5
rs1686740
surindertarika1234
Picked
Technical Scripter 2020
Java
Java Programs
Technical Scripter
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Different ways of Reading a text file in Java
Constructors in Java
Stream In Java
Exceptions in Java
StringBuilder Class in Java with Examples
Convert a String to Character array in Java
Java Programming Examples
Implementing a Linked List in Java using Class
Convert Double to Integer in Java
How to Iterate HashMap in Java? | [
{
"code": null,
"e": 23894,
"s": 23866,
"text": "\n28 Jan, 2022"
},
{
"code": null,
"e": 24127,
"s": 23894,
"text": "Basically, as the name suggests that 3-Way Radix Quicksort is a combination of both radix and 3-way quicksort. It is a hybrid sort which is in between of both radix and 3-way quicksort. This algorithm is mainly used to sort strings."
},
{
"code": null,
"e": 24461,
"s": 24127,
"text": "The main idea behind the radix sort is to use the digits (beginning from LSD to MSD) of all the integers to perform hashing and dividing them into a separate list and them joining. In the same way, we will be using the MSD character of the strings and then using these characters we go on performing what is known as 3-way quicksort."
},
{
"code": null,
"e": 24756,
"s": 24461,
"text": "3-way quicksort is basically a case of general quicksort only. The idea is that if we use quicksort then there can be a situation that we would get the same characters in the array of characters(here we are sorting strings using radix sort idea, to take all the Characters one by one to sort). "
},
{
"code": null,
"e": 24824,
"s": 24756,
"text": "So to handle such a situation we divide the array into three parts:"
},
{
"code": null,
"e": 25045,
"s": 24824,
"text": "The partition contains characters less than the pivot character.The partition for characters that are equal to that of the pivot character.The last partition contains characters that are greater than the pivot character."
},
{
"code": null,
"e": 25110,
"s": 25045,
"text": "The partition contains characters less than the pivot character."
},
{
"code": null,
"e": 25186,
"s": 25110,
"text": "The partition for characters that are equal to that of the pivot character."
},
{
"code": null,
"e": 25268,
"s": 25186,
"text": "The last partition contains characters that are greater than the pivot character."
},
{
"code": null,
"e": 25310,
"s": 25268,
"text": "So basically what is going to happen is :"
},
{
"code": null,
"e": 25527,
"s": 25310,
"text": "We would consider the MSD character of each string(the idea of radix sort).Then we will perform quicksort on this array of characters, which will result in the partition of the array into 3 parts(as discussed above)."
},
{
"code": null,
"e": 25603,
"s": 25527,
"text": "We would consider the MSD character of each string(the idea of radix sort)."
},
{
"code": null,
"e": 25745,
"s": 25603,
"text": "Then we will perform quicksort on this array of characters, which will result in the partition of the array into 3 parts(as discussed above)."
},
{
"code": null,
"e": 25789,
"s": 25745,
"text": "This division is shown in the below figure."
},
{
"code": null,
"e": 25812,
"s": 25789,
"text": "Explanation of image: "
},
{
"code": null,
"e": 26119,
"s": 25812,
"text": "So basically as shown that there are 11 strings in the array, and we have to sort them. So now considering the first character of all strings gives an array of {s,a,h,s,s,z,b,t,c,u,s}. This is the idea got from radix sort. Now we are to sort this array of characters on the basis of the idea of quick sort."
},
{
"code": null,
"e": 26286,
"s": 26119,
"text": "So here the pivot element we are considering is first element of array i.e. ‘s’. Now we are using quicksort to make partition. Partitions are done on the basis that :"
},
{
"code": null,
"e": 26555,
"s": 26286,
"text": "First we are considering the first character as the pivot and also we have to pointers ‘i’ and ‘j’. Pointer ‘i’ moves form start to end and ‘j’ moves from end to start. Initially i=1 and j =n-1; this would help us to get the two boundary index of the second partition."
},
{
"code": null,
"e": 26654,
"s": 26555,
"text": "Ranges of partition than would be 1st one form 0 – i , 2nd form i+1 – j-1 and third form j to n-1;"
},
{
"code": null,
"e": 26951,
"s": 26654,
"text": "if arr[i]<pivot: pivot is swapped with arr[i] (please Note that here string are swapped and not the characters of the string)if arr[i]==pivot it is remained there only, and the pointer is incremented to next one.if arr[i]>pivot, the string at j is swapped with arr[i] string and j is decremented."
},
{
"code": null,
"e": 27077,
"s": 26951,
"text": "if arr[i]<pivot: pivot is swapped with arr[i] (please Note that here string are swapped and not the characters of the string)"
},
{
"code": null,
"e": 27165,
"s": 27077,
"text": "if arr[i]==pivot it is remained there only, and the pointer is incremented to next one."
},
{
"code": null,
"e": 27250,
"s": 27165,
"text": "if arr[i]>pivot, the string at j is swapped with arr[i] string and j is decremented."
},
{
"code": null,
"e": 27337,
"s": 27250,
"text": "So after performing these operations we will get the three partitioned array as shown."
},
{
"code": null,
"e": 27806,
"s": 27337,
"text": "After getting the partitions we can see that in the second one we are not able to recursively perform quicksort on the first character of string since in that partition all the strings are having the same first character(here in this example it is ‘s’). So we will be going for doing partition on the basis of the next character. And for the other two, we will recall the same sort again starting from the first character. This is the whole idea about 3-way quicksort."
},
{
"code": null,
"e": 28107,
"s": 27806,
"text": "The main thing here to notice that is all string are not of the same length so at some step we can have a condition that there will be no further characters of the pivot string and other strings are having characters and hence swapping and comparisons of the characters are not possible in that case."
},
{
"code": null,
"e": 28282,
"s": 28107,
"text": "So to handle that case we would first find the max length of strings in the array and then append each string with a character that has ASCII value smaller than the alphabet."
},
{
"code": null,
"e": 28296,
"s": 28282,
"text": "Why smaller? "
},
{
"code": null,
"e": 28317,
"s": 28296,
"text": "consider an example:"
},
{
"code": null,
"e": 28348,
"s": 28317,
"text": "Array is a={hero, heroes, her}"
},
{
"code": null,
"e": 28535,
"s": 28348,
"text": "Here if we give each string with fewer characters than the max amount needed(i.e. 6) a character which is greater than alphabets (say ‘~’), then a will become a={hero~~, heroes, her~~~}."
},
{
"code": null,
"e": 28655,
"s": 28535,
"text": "sorting this array would give the result as {heroes, hero~~, her~~~} but the real answer should be {her, hero, heroes}."
},
{
"code": null,
"e": 28783,
"s": 28655,
"text": "Performing the above algorithm recursively will generate a sorted array and hence we will be able to sort the array of strings."
},
{
"code": null,
"e": 28809,
"s": 28783,
"text": "Recursive Implementation:"
},
{
"code": null,
"e": 28814,
"s": 28809,
"text": "Java"
},
{
"code": "// Java program for 3-Way Radix Quicksort import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Scanner;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipInputStream; public class GFG { // swapping method. public static void swp(String[] s, int x, int y) { String tmp = s[x]; s[x] = s[y]; s[y] = tmp; } // sort method. public static void srt(String[] s, int start, int last, int character_index) { // base condition if no further index possible. if (start >= last) return; // first making a start pointer for dividing the // list from start to start_pointer. int start_pointer = start; // last_pointer and last are the boundaries for the // third list. int last_pointer = last; // taking the ascii value of the pivot at the index // given. int char_ascii_value_pivot = s[start].charAt(character_index); int pointer = start + 1; // starting a pointer to scan the whole array to // sort. while (pointer <= last) { // ASCII value of char at the position of all // the strings to compare with that of the pivot // char. int char_ascii_value_element = s[pointer].charAt(character_index); // if the element has char less than pivot than // swapping it with the top element and // incrementing the top boundary of the first // list. if (char_ascii_value_pivot > char_ascii_value_element) { swp(s, start_pointer, pointer); start_pointer++; // incrementing the pointer to check for // next string. pointer++; } else // if found larger character than it is // replaced by the element at last_pointer // and lower boundary is raised by // decrementing it. if (char_ascii_value_pivot < char_ascii_value_element) { swp(s, last_pointer, pointer); last_pointer--; pointer++; } // if character is the same as that of the pivot // then no need to swap and move the pointer on else { pointer++; } } // now performing same sort on the first list // bounded by start and start_pointer with same // character_index srt(s, start, start_pointer - 1, character_index); // if we have more character left in the pivot // element than recall quicksort on the second list // bounded by start_pointer and last_pointer and // next character_index. if (char_ascii_value_pivot >= 0) srt(s, start_pointer, last_pointer, character_index + 1); // lastly the third list with boundaries as // last_pointer and last. srt(s, last_pointer + 1, last, character_index); } public static void main(String[] args) throws Exception { // predefined array of five element all of same // length. String s[] = { \"some\", \"same\", \"hero\", \"make\", \"zero\" }; // calling sort function to sort the array using // 3-way-radix-quicksort. srt(s, 0, 4, 0); // printing the sorted array; // here w are calling function by passing parameters // using references . for (int i = 0; i < 5; ++i) System.out.println(s[i]); }}",
"e": 32657,
"s": 28814,
"text": null
},
{
"code": null,
"e": 32682,
"s": 32657,
"text": "hero\nmake\nsame\nsome\nzero"
},
{
"code": null,
"e": 32733,
"s": 32682,
"text": "Example 2: To sort strings with different lengths."
},
{
"code": null,
"e": 32738,
"s": 32733,
"text": "Java"
},
{
"code": "// Java program for 3-Way radix QuickSort import java.io.BufferedInputStream;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.util.Enumeration;import java.util.Scanner;import java.util.zip.ZipEntry;import java.util.zip.ZipFile;import java.util.zip.ZipInputStream; public class GFG { // swapping method. public static void swp(String[] s, int x, int y) { String tmp = s[x]; s[x] = s[y]; s[y] = tmp; } // sort method. public static void srt(String[] s, int start, int last, int character_index) { // base condition if no further index possible. if (start >= last) return; // first making a start pointer for dividing the // list from start to start_pointer. int start_pointer = start; // last_pointer and last are the boundaries for the // third list. int last_pointer = last; // taking the ASCII value of the pivot at the index // given. int char_ascii_value_pivot = s[start].charAt(character_index); int pointer = start + 1; // starting a pointer to scan the whole array to // sort. while (pointer <= last) { // ASCII value of char at the position of all // the strings to compare with that of the pivot // char. int char_ascii_value_element = s[pointer].charAt(character_index); // if the element has char less than pivot than // swapping it with the top element and // incrementing the top boundary of the first // list. if (char_ascii_value_pivot> char_ascii_value_element) { swp(s, start_pointer, pointer); start_pointer++; // incrementing the pointer to check for // next string. pointer++; } else // if found larger character than it is // replaced by the element at last_pointer // and lower boundary is raised by // decrementing it. if (char_ascii_value_pivot< char_ascii_value_element) { swp(s, last_pointer, pointer); last_pointer--; pointer++; } // if character is same as that of the pivot then // no need to swap and move the pointer on else { pointer++; } } // now performing same sort on the first list // bounded by start and start_pointer with same // character_index srt(s, start, start_pointer - 1, character_index); // if we have more character left in the pivot // element than recall quicksort on the second list // bounded by start_pointer and last_pointer and // next character_index. if (char_ascii_value_pivot >= 0) srt(s, start_pointer, last_pointer,character_index + 1); // lastly the third list with boundaries as // last_pointer and last. srt(s, last_pointer + 1, last, character_index); } public static void main(String[] args) throws Exception { // predefined array of five element all of different // length. String s[] = { \"sam\", \"same\", \"her\", \"make\", \"zebra\" }; int max_character_index = 0; // finding max_character_index for (int i = 0; i < 5; ++i) if (s[i].length() > max_character_index) max_character_index = s[i].length(); // adding each string with a character having less // ascii value than alphabets. for (int i = 0; i < 5; ++i) if (s[i].length() < max_character_index) while (s[i].length() < max_character_index) s[i] += '?'; // calling sort function to sort the array using // 3-way-radix-quicksort. srt(s, 0, 4, 0); // printing the sorted array; // here we are calling function by passing // parameters using references . printing without the // appended character. for (int i = 0; i < 5; ++i) { String ans = \"\"; for (int j = 0; j < s[i].length(); ++j) if (s[i].charAt(j) != '?') ans += s[i].charAt(j); else break; System.out.println(ans); } }}",
"e": 37407,
"s": 32738,
"text": null
},
{
"code": null,
"e": 37431,
"s": 37407,
"text": "her\nmake\nsam\nsame\nzebra"
},
{
"code": null,
"e": 37444,
"s": 37431,
"text": "simmytarika5"
},
{
"code": null,
"e": 37454,
"s": 37444,
"text": "rs1686740"
},
{
"code": null,
"e": 37473,
"s": 37454,
"text": "surindertarika1234"
},
{
"code": null,
"e": 37480,
"s": 37473,
"text": "Picked"
},
{
"code": null,
"e": 37504,
"s": 37480,
"text": "Technical Scripter 2020"
},
{
"code": null,
"e": 37509,
"s": 37504,
"text": "Java"
},
{
"code": null,
"e": 37523,
"s": 37509,
"text": "Java Programs"
},
{
"code": null,
"e": 37542,
"s": 37523,
"text": "Technical Scripter"
},
{
"code": null,
"e": 37547,
"s": 37542,
"text": "Java"
},
{
"code": null,
"e": 37645,
"s": 37547,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 37654,
"s": 37645,
"text": "Comments"
},
{
"code": null,
"e": 37667,
"s": 37654,
"text": "Old Comments"
},
{
"code": null,
"e": 37713,
"s": 37667,
"text": "Different ways of Reading a text file in Java"
},
{
"code": null,
"e": 37734,
"s": 37713,
"text": "Constructors in Java"
},
{
"code": null,
"e": 37749,
"s": 37734,
"text": "Stream In Java"
},
{
"code": null,
"e": 37768,
"s": 37749,
"text": "Exceptions in Java"
},
{
"code": null,
"e": 37810,
"s": 37768,
"text": "StringBuilder Class in Java with Examples"
},
{
"code": null,
"e": 37854,
"s": 37810,
"text": "Convert a String to Character array in Java"
},
{
"code": null,
"e": 37880,
"s": 37854,
"text": "Java Programming Examples"
},
{
"code": null,
"e": 37927,
"s": 37880,
"text": "Implementing a Linked List in Java using Class"
},
{
"code": null,
"e": 37961,
"s": 37927,
"text": "Convert Double to Integer in Java"
}
] |
PHP - Function openssl_public_encrypt() | The openssl_public_encrypt() function will encrypt the data with public key.
Using function openssl_public_encrypt() the data will be encrypted and it can be decrypted using openssl_private_decrypt().
openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool
data
.
encrypted
It will have the data that is encrypted.
key
The public key.
padding
The padding you can apply are : OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING.
PHP openssl_public_encrypt() function returns TRUE on success or FALSE on failure.
This function will work from PHP Version greater than 5.0.0.
Using openssl_public_encrypt() to Encrpt Data using Public Key:
<?php
// Save Private Key
$privkey = openssl_pkey_new();
openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
//Save Public Key
$dn = array(
"countryName" => "IN",
"stateOrProvinceName" => "Karnataka",
"localityName" => "test1",
"organizationName" => "test2",
"organizationalUnitName" => "test3",
"commonName" => "www.test.com",
"emailAddress" => "[email protected]"
);
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 365);
openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
// To encrpt data
$data = 'Welcome To TuorialsPoint';
$isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data encryption : ".$crypted;
?>
This will produce the following result:
Data encryption : ��u001cE �wC�ݭf�+c��f*��o�u001b��u000eW�7�Eu0005W��$�p�.rng�_N�u0016�A1u001d��2Uݴu0002~su0015�ap۳)w��=� ��#��g;�u0001��u001eu��_%�Z�bb�u0002&��mu0002�u0005�v&��u0010��q��k
To encrypt data using openssl_public_encrypt() and decrypt using openssl_private_decrypt():
<?php
// Save Private Key
$privkey = openssl_pkey_new();
openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');
//Save Public Key
$dn = array(
"countryName" => "IN",
"stateOrProvinceName" => "Karnataka",
"localityName" => "test1",
"organizationName" => "test2",
"organizationalUnitName" => "test3",
"commonName" => "www.test.com",
"emailAddress" => "[email protected]"
);
$cert = openssl_csr_new($dn, $privkey);
$cert = openssl_csr_sign($cert, null, $privkey, 365);
openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem');
// To encrpt data
$data = 'Welcome To TuorialsPoint';
$isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data encryption : ".$crypted;
echo ">br/<>br/<";
if ($isvalid) {
openssl_private_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/privatekey.pem'),OPENSSL_PKCS1_PADDING);
echo "Data decryption : ".$decrypted;
}
?>
This will produce the following result:
Data encryption : L�_}{�E*?��9[w��7p �u001d\ϸI�?ݟ'��ݹ�n��!��ɿu001f�*��Xcw�u0005��u001eՒ�)��/��{�u0011�!j�L��I*Ï"9eV�u0018u00149�=u001aY\�m�i䁦�M(�0PJ��Ԇ�9�u000e�C�`�au001e�ݧ�bu0014��au0014��?�m�G$i��eUu001f/[u001f�feU��u0017��\=�zLdŌn"�u0005�u001fu0013:[\u0013u001fu0005�Uu0014A��ԭ�ힲ2u0011@f-u0007"u0004du001c��s�=2�nx�hu0006��q5U��浿��9�{ݼ�u000b�|�NE�u000ea!
Data decryption : Welcome To TuorialsPoint
45 Lectures
9 hours
Malhar Lathkar
34 Lectures
4 hours
Syed Raza
84 Lectures
5.5 hours
Frahaan Hussain
17 Lectures
1 hours
Nivedita Jain
100 Lectures
34 hours
Azaz Patel
43 Lectures
5.5 hours
Vijay Kumar Parvatha Reddy
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2834,
"s": 2757,
"text": "The openssl_public_encrypt() function will encrypt the data with public key."
},
{
"code": null,
"e": 2958,
"s": 2834,
"text": "Using function openssl_public_encrypt() the data will be encrypted and it can be decrypted using openssl_private_decrypt()."
},
{
"code": null,
"e": 3080,
"s": 2958,
"text": "openssl_public_encrypt ( string $data , string &$crypted , mixed $key [, int $padding = OPENSSL_PKCS1_PADDING ] ) : bool\n"
},
{
"code": null,
"e": 3085,
"s": 3080,
"text": "data"
},
{
"code": null,
"e": 3087,
"s": 3085,
"text": "."
},
{
"code": null,
"e": 3097,
"s": 3087,
"text": "encrypted"
},
{
"code": null,
"e": 3138,
"s": 3097,
"text": "It will have the data that is encrypted."
},
{
"code": null,
"e": 3142,
"s": 3138,
"text": "key"
},
{
"code": null,
"e": 3158,
"s": 3142,
"text": "The public key."
},
{
"code": null,
"e": 3166,
"s": 3158,
"text": "padding"
},
{
"code": null,
"e": 3293,
"s": 3166,
"text": "The padding you can apply are : OPENSSL_PKCS1_PADDING, OPENSSL_SSLV23_PADDING, OPENSSL_PKCS1_OAEP_PADDING, OPENSSL_NO_PADDING."
},
{
"code": null,
"e": 3376,
"s": 3293,
"text": "PHP openssl_public_encrypt() function returns TRUE on success or FALSE on failure."
},
{
"code": null,
"e": 3437,
"s": 3376,
"text": "This function will work from PHP Version greater than 5.0.0."
},
{
"code": null,
"e": 3501,
"s": 3437,
"text": "Using openssl_public_encrypt() to Encrpt Data using Public Key:"
},
{
"code": null,
"e": 4406,
"s": 3501,
"text": "<?php\n // Save Private Key\n $privkey = openssl_pkey_new();\n openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');\n\t\n //Save Public Key\n $dn = array(\n \"countryName\" => \"IN\",\n \"stateOrProvinceName\" => \"Karnataka\",\n \"localityName\" => \"test1\",\n \"organizationName\" => \"test2\",\n \"organizationalUnitName\" => \"test3\",\n \"commonName\" => \"www.test.com\",\n \"emailAddress\" => \"[email protected]\"\n );\n $cert = openssl_csr_new($dn, $privkey);\n $cert = openssl_csr_sign($cert, null, $privkey, 365);\n openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem');\n\t\n\t\n // To encrpt data\n $data = 'Welcome To TuorialsPoint';\n $isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);\t\n echo \"Data encryption : \".$crypted;\n?>"
},
{
"code": null,
"e": 4446,
"s": 4406,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 4637,
"s": 4446,
"text": "Data encryption : ��u001cE �wC�ݭf�+c��f*��o�u001b��u000eW�7�Eu0005W��$�p�.rng�_N�u0016�A1u001d��2Uݴu0002~su0015�ap۳)w��=� ��#��g;�u0001��u001eu��_%�Z�bb�u0002&��mu0002�u0005�v&��u0010��q��k\n"
},
{
"code": null,
"e": 4730,
"s": 4637,
"text": "To encrypt data using openssl_public_encrypt() and decrypt using openssl_private_decrypt():"
},
{
"code": null,
"e": 5875,
"s": 4730,
"text": "<?php\n // Save Private Key\n $privkey = openssl_pkey_new();\n openssl_pkey_export_to_file($privkey, 'C:/xampp/htdocs/modules/openssl/privatekey.pem');\n\t\n //Save Public Key\n $dn = array(\n \"countryName\" => \"IN\",\n \"stateOrProvinceName\" => \"Karnataka\",\n \"localityName\" => \"test1\",\n \"organizationName\" => \"test2\",\n \"organizationalUnitName\" => \"test3\",\n \"commonName\" => \"www.test.com\",\n \"emailAddress\" => \"[email protected]\"\n );\n $cert = openssl_csr_new($dn, $privkey);\n $cert = openssl_csr_sign($cert, null, $privkey, 365);\n openssl_x509_export_to_file($cert, 'C:/xampp/htdocs/modules/openssl/publickey.pem');\n\t\n\t\n // To encrpt data\n $data = 'Welcome To TuorialsPoint';\n $isvalid = openssl_public_encrypt ($data, $crypted , file_get_contents('C:/xampp/htdocs/modules/openssl/publickey.pem'),OPENSSL_PKCS1_PADDING);\t\n echo \"Data encryption : \".$crypted;\n echo \">br/<>br/<\";\n\t\n if ($isvalid) {\t\n openssl_private_decrypt ($crypted, $decrypted , file_get_contents('C:/xampp/htdocs/modules/openssl/privatekey.pem'),OPENSSL_PKCS1_PADDING);\t\n echo \"Data decryption : \".$decrypted;\n }\n?>"
},
{
"code": null,
"e": 5915,
"s": 5875,
"text": "This will produce the following result:"
},
{
"code": null,
"e": 6321,
"s": 5915,
"text": "Data encryption : L�_}{�E*?��9[w��7p �u001d\\ϸI�?ݟ'��ݹ�n��!��ɿu001f�*��Xcw�u0005��u001eՒ�)��/��{�u0011�!j�L��I*Ï\"9eV�u0018u00149�=u001aY\\�m�i䁦�M(�0PJ��Ԇ�9�u000e�C�`�au001e�ݧ�bu0014��au0014��?�m�G$i��eUu001f/[u001f�feU��u0017��\\=�zLdŌn\"�u0005�u001fu0013:[\\u0013u001fu0005�Uu0014A��ԭ�ힲ2u0011@f-u0007\"u0004du001c��s�=2�nx�hu0006��q5U��浿��9�{ݼ�u000b�|�NE�u000ea!\n\nData decryption : Welcome To TuorialsPoint\n"
},
{
"code": null,
"e": 6354,
"s": 6321,
"text": "\n 45 Lectures \n 9 hours \n"
},
{
"code": null,
"e": 6370,
"s": 6354,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 6403,
"s": 6370,
"text": "\n 34 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 6414,
"s": 6403,
"text": " Syed Raza"
},
{
"code": null,
"e": 6449,
"s": 6414,
"text": "\n 84 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6466,
"s": 6449,
"text": " Frahaan Hussain"
},
{
"code": null,
"e": 6499,
"s": 6466,
"text": "\n 17 Lectures \n 1 hours \n"
},
{
"code": null,
"e": 6514,
"s": 6499,
"text": " Nivedita Jain"
},
{
"code": null,
"e": 6549,
"s": 6514,
"text": "\n 100 Lectures \n 34 hours \n"
},
{
"code": null,
"e": 6561,
"s": 6549,
"text": " Azaz Patel"
},
{
"code": null,
"e": 6596,
"s": 6561,
"text": "\n 43 Lectures \n 5.5 hours \n"
},
{
"code": null,
"e": 6624,
"s": 6596,
"text": " Vijay Kumar Parvatha Reddy"
},
{
"code": null,
"e": 6631,
"s": 6624,
"text": " Print"
},
{
"code": null,
"e": 6642,
"s": 6631,
"text": " Add Notes"
}
] |
Adding Glitches to Images using Python - GeeksforGeeks | 08 Sep, 2021
One of the filters currently popular is to add random glitches to the images. These create a random effect that comes out to be a natural glitch. Usually, glitches are introduced by the corruption of frames of images or adding a layer over them. In this article, we will use the two different modules of Python to add glitches to the image.
This Python library adds random glitch effects to Images. It does this by distorting or Corrupting JPEG frames of some random bytes of Images, to not harm the File. Internally it uses Pillow library to perform tasks.
To install this module type the below command in the terminal.
pip3 install glitchart
After installation, the glitchart library is imported and jpeg() or png() is invoked depending upon the extension of the image to be glitched. Just run the script and a new glitched file will be created with the name <filename>_glitch in the same path.
Function Used:
png(): Add glitches to png images.
Syntax:
png(photo, seed=random_val, min_amount=0, max_amount=10, inplace=False):
Parameters:
photo : The required .png format photo to add glitch to.
seed : Random number, if we wish to add similar amount of glitch to next photo, can have same seed value.
min_amount : Minimum amount of glitch required, defaults to 0.
max_amount : Maximum amount of glitch required, defaults to 10.
inplace : boolean field, if True, changes original photo, not creating new one.
Example:
Input Image:
Python3
import glitchart glitchart.png('gfg.png')
Output:
Example 2: Controlling Glitch amount.
Python3
import glitchart glitchart.png('gfg.png', max_amount=3)
Output :
Using glitch-this Module
Using this, we can perform the task of glitching images using command line by supplying image path and levels and certain image and file management parameters.
To install this module type the below command in the terminal
pip install glitch-this
Command Line Parameters Explanation
glitch_this [-h] [–version] [-c] [-s] [-g] [-ig] [-f] [-o Outfile_path] Image_Path Glitch_Level
Parameters:Image_Path : The image path to perform glitch on.Glitch_Level : Level of Glitch to be applied, from 0.1 to 10.0 [inclusive].-h : Getting pull description-o Outfile_path :Explicitly supply full/relative path to output file.-g : Output image as gif.-ig : Include if input is gif.-f : If output file has to be overwritten.-c : If color effect has to be added.-s. : If sideline effect has to be added.
Example: Controlling Glitch amount.
Example of Glitching using glitch-this
Output :
Glitched Image Output
surinderdawra388
Image-Processing
python-modules
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
How to drop one or multiple columns in Pandas Dataframe
How To Convert Python Dictionary To JSON?
Check if element exists in list in Python
Defaultdict in Python
Python | os.path.join() method
Python | Get unique values from a list
Selecting rows in pandas DataFrame based on conditions
Create a directory in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 24292,
"s": 24264,
"text": "\n08 Sep, 2021"
},
{
"code": null,
"e": 24633,
"s": 24292,
"text": "One of the filters currently popular is to add random glitches to the images. These create a random effect that comes out to be a natural glitch. Usually, glitches are introduced by the corruption of frames of images or adding a layer over them. In this article, we will use the two different modules of Python to add glitches to the image."
},
{
"code": null,
"e": 24851,
"s": 24633,
"text": "This Python library adds random glitch effects to Images. It does this by distorting or Corrupting JPEG frames of some random bytes of Images, to not harm the File. Internally it uses Pillow library to perform tasks. "
},
{
"code": null,
"e": 24914,
"s": 24851,
"text": "To install this module type the below command in the terminal."
},
{
"code": null,
"e": 24937,
"s": 24914,
"text": "pip3 install glitchart"
},
{
"code": null,
"e": 25190,
"s": 24937,
"text": "After installation, the glitchart library is imported and jpeg() or png() is invoked depending upon the extension of the image to be glitched. Just run the script and a new glitched file will be created with the name <filename>_glitch in the same path."
},
{
"code": null,
"e": 25205,
"s": 25190,
"text": "Function Used:"
},
{
"code": null,
"e": 25240,
"s": 25205,
"text": "png(): Add glitches to png images."
},
{
"code": null,
"e": 25248,
"s": 25240,
"text": "Syntax:"
},
{
"code": null,
"e": 25321,
"s": 25248,
"text": "png(photo, seed=random_val, min_amount=0, max_amount=10, inplace=False):"
},
{
"code": null,
"e": 25333,
"s": 25321,
"text": "Parameters:"
},
{
"code": null,
"e": 25391,
"s": 25333,
"text": "photo : The required .png format photo to add glitch to."
},
{
"code": null,
"e": 25497,
"s": 25391,
"text": "seed : Random number, if we wish to add similar amount of glitch to next photo, can have same seed value."
},
{
"code": null,
"e": 25560,
"s": 25497,
"text": "min_amount : Minimum amount of glitch required, defaults to 0."
},
{
"code": null,
"e": 25624,
"s": 25560,
"text": "max_amount : Maximum amount of glitch required, defaults to 10."
},
{
"code": null,
"e": 25704,
"s": 25624,
"text": "inplace : boolean field, if True, changes original photo, not creating new one."
},
{
"code": null,
"e": 25713,
"s": 25704,
"text": "Example:"
},
{
"code": null,
"e": 25726,
"s": 25713,
"text": "Input Image:"
},
{
"code": null,
"e": 25734,
"s": 25726,
"text": "Python3"
},
{
"code": "import glitchart glitchart.png('gfg.png')",
"e": 25776,
"s": 25734,
"text": null
},
{
"code": null,
"e": 25788,
"s": 25780,
"text": "Output:"
},
{
"code": null,
"e": 25830,
"s": 25792,
"text": "Example 2: Controlling Glitch amount."
},
{
"code": null,
"e": 25840,
"s": 25832,
"text": "Python3"
},
{
"code": "import glitchart glitchart.png('gfg.png', max_amount=3)",
"e": 25896,
"s": 25840,
"text": null
},
{
"code": null,
"e": 25906,
"s": 25896,
"text": "Output : "
},
{
"code": null,
"e": 25932,
"s": 25906,
"text": "Using glitch-this Module "
},
{
"code": null,
"e": 26092,
"s": 25932,
"text": "Using this, we can perform the task of glitching images using command line by supplying image path and levels and certain image and file management parameters."
},
{
"code": null,
"e": 26154,
"s": 26092,
"text": "To install this module type the below command in the terminal"
},
{
"code": null,
"e": 26178,
"s": 26154,
"text": "pip install glitch-this"
},
{
"code": null,
"e": 26214,
"s": 26178,
"text": "Command Line Parameters Explanation"
},
{
"code": null,
"e": 26310,
"s": 26214,
"text": "glitch_this [-h] [–version] [-c] [-s] [-g] [-ig] [-f] [-o Outfile_path] Image_Path Glitch_Level"
},
{
"code": null,
"e": 26720,
"s": 26310,
"text": "Parameters:Image_Path : The image path to perform glitch on.Glitch_Level : Level of Glitch to be applied, from 0.1 to 10.0 [inclusive].-h : Getting pull description-o Outfile_path :Explicitly supply full/relative path to output file.-g : Output image as gif.-ig : Include if input is gif.-f : If output file has to be overwritten.-c : If color effect has to be added.-s. : If sideline effect has to be added."
},
{
"code": null,
"e": 26756,
"s": 26720,
"text": "Example: Controlling Glitch amount."
},
{
"code": null,
"e": 26795,
"s": 26756,
"text": "Example of Glitching using glitch-this"
},
{
"code": null,
"e": 26805,
"s": 26795,
"text": "Output : "
},
{
"code": null,
"e": 26827,
"s": 26805,
"text": "Glitched Image Output"
},
{
"code": null,
"e": 26844,
"s": 26827,
"text": "surinderdawra388"
},
{
"code": null,
"e": 26861,
"s": 26844,
"text": "Image-Processing"
},
{
"code": null,
"e": 26876,
"s": 26861,
"text": "python-modules"
},
{
"code": null,
"e": 26883,
"s": 26876,
"text": "Python"
},
{
"code": null,
"e": 26981,
"s": 26883,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27013,
"s": 26981,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27069,
"s": 27013,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27111,
"s": 27069,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27153,
"s": 27111,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27175,
"s": 27153,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27206,
"s": 27175,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27245,
"s": 27206,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27300,
"s": 27245,
"text": "Selecting rows in pandas DataFrame based on conditions"
},
{
"code": null,
"e": 27329,
"s": 27300,
"text": "Create a directory in Python"
}
] |
Flask â Static Files | A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application.
A special endpoint ‘static’ is used to generate URL for static files.
In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application.
from flask import Flask, render_template
app = Flask(__name__)
@app.route("/")
def index():
return render_template("index.html")
if __name__ == '__main__':
app.run(debug = True)
The HTML script of index.html is given below.
<html>
<head>
<script type = "text/javascript"
src = "{{ url_for('static', filename = 'hello.js') }}" ></script>
</head>
<body>
<input type = "button" onclick = "sayHello()" value = "Say Hello" />
</body>
</html>
hello.js contains sayHello() function.
function sayHello() {
alert("Hello World")
}
22 Lectures
6 hours
Malhar Lathkar
21 Lectures
1.5 hours
Jack Chan
16 Lectures
4 hours
Malhar Lathkar
54 Lectures
6 hours
Srikanth Guskra
88 Lectures
3.5 hours
Jorge Escobar
80 Lectures
12 hours
Stone River ELearning
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2384,
"s": 2033,
"text": "A web application often requires a static file such as a javascript file or a CSS file supporting the display of a web page. Usually, the web server is configured to serve them for you, but during the development, these files are served from static folder in your package or next to your module and it will be available at /static on the application."
},
{
"code": null,
"e": 2454,
"s": 2384,
"text": "A special endpoint ‘static’ is used to generate URL for static files."
},
{
"code": null,
"e": 2634,
"s": 2454,
"text": "In the following example, a javascript function defined in hello.js is called on OnClick event of HTML button in index.html, which is rendered on ‘/’ URL of the Flask application."
},
{
"code": null,
"e": 2820,
"s": 2634,
"text": "from flask import Flask, render_template\napp = Flask(__name__)\n\[email protected](\"/\")\ndef index():\n return render_template(\"index.html\")\n\nif __name__ == '__main__':\n app.run(debug = True)"
},
{
"code": null,
"e": 2866,
"s": 2820,
"text": "The HTML script of index.html is given below."
},
{
"code": null,
"e": 3117,
"s": 2866,
"text": "<html>\n <head>\n <script type = \"text/javascript\" \n src = \"{{ url_for('static', filename = 'hello.js') }}\" ></script>\n </head>\n \n <body>\n <input type = \"button\" onclick = \"sayHello()\" value = \"Say Hello\" />\n </body>\n</html>"
},
{
"code": null,
"e": 3156,
"s": 3117,
"text": "hello.js contains sayHello() function."
},
{
"code": null,
"e": 3204,
"s": 3156,
"text": "function sayHello() {\n alert(\"Hello World\")\n}"
},
{
"code": null,
"e": 3237,
"s": 3204,
"text": "\n 22 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3253,
"s": 3237,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3288,
"s": 3253,
"text": "\n 21 Lectures \n 1.5 hours \n"
},
{
"code": null,
"e": 3299,
"s": 3288,
"text": " Jack Chan"
},
{
"code": null,
"e": 3332,
"s": 3299,
"text": "\n 16 Lectures \n 4 hours \n"
},
{
"code": null,
"e": 3348,
"s": 3332,
"text": " Malhar Lathkar"
},
{
"code": null,
"e": 3381,
"s": 3348,
"text": "\n 54 Lectures \n 6 hours \n"
},
{
"code": null,
"e": 3398,
"s": 3381,
"text": " Srikanth Guskra"
},
{
"code": null,
"e": 3433,
"s": 3398,
"text": "\n 88 Lectures \n 3.5 hours \n"
},
{
"code": null,
"e": 3448,
"s": 3433,
"text": " Jorge Escobar"
},
{
"code": null,
"e": 3482,
"s": 3448,
"text": "\n 80 Lectures \n 12 hours \n"
},
{
"code": null,
"e": 3505,
"s": 3482,
"text": " Stone River ELearning"
},
{
"code": null,
"e": 3512,
"s": 3505,
"text": " Print"
},
{
"code": null,
"e": 3523,
"s": 3512,
"text": " Add Notes"
}
] |
How to find all the foreign keys of a DB2 table TAB1? | The foreign key of a DB2 table can be found using SYSIBM.SYSFOREIGNKEYS table and SYSIBM.SYSRELS table. The SYSFOREIGNKEYS is a DB2 system table which contains one row for every column of every foreign key. The SYSRELS table contains details about the referential constraints. In order to find out the foreign key(s) of any table, we can use the below SQL query.
SELECT B.REFTBNAME AS PARENTTABLE,COLNAME
FROM SYSIBM.SYSFOREIGNKEYS A, SYSIBM.SYSRELS B
WHERE A.RELNAME = B.RELNAME
AND B.TBNAME = 'TAB1'
AND B.REFTBCREATOR = A.CREATOR
We will join SYSFOREIGNKEYS and SYSRELS table for the columns RELNAME which stores the details regarding constraint name for the constraint for which the column is part of the foreign key. | [
{
"code": null,
"e": 1425,
"s": 1062,
"text": "The foreign key of a DB2 table can be found using SYSIBM.SYSFOREIGNKEYS table and SYSIBM.SYSRELS table. The SYSFOREIGNKEYS is a DB2 system table which contains one row for every column of every foreign key. The SYSRELS table contains details about the referential constraints. In order to find out the foreign key(s) of any table, we can use the below SQL query."
},
{
"code": null,
"e": 1595,
"s": 1425,
"text": "SELECT B.REFTBNAME AS PARENTTABLE,COLNAME\nFROM SYSIBM.SYSFOREIGNKEYS A, SYSIBM.SYSRELS B\nWHERE A.RELNAME = B.RELNAME\nAND B.TBNAME = 'TAB1'\nAND B.REFTBCREATOR = A.CREATOR"
},
{
"code": null,
"e": 1784,
"s": 1595,
"text": "We will join SYSFOREIGNKEYS and SYSRELS table for the columns RELNAME which stores the details regarding constraint name for the constraint for which the column is part of the foreign key."
}
] |
Mining Twitter Data for Sentiment Analysis of Events | by Sanket Gupta | Towards Data Science | Twitter is a rich source for information. From minute-to-minute trends to general discussions around topics, Twitter is a great source of data for a project. Also, Twitter has built an amazing API for developers to use this data. Could we track an event and see what people are thinking? Is it possible to run sentiment analysis on what the world is thinking as an event unfolds over time? Could we track Twitter data and see if it correlates to news that affects stock market movements? These were some of the questions in my mind as I began to dig into Twitter data recently.
If you prefer to listen to the audio version of this blog, I have also recorded a podcast episode for this blog post — where I go into more details of each of the step including caveats and things to avoid. You can listen to it on Apple Podcasts, Spotify or Anchor.fm, or on one of my favorite podcast apps: Overcast.
Let’s get right into the steps to use Twitter data for sentiment analysis of events:
First, visit this link and get access to a developer account.
Once you register, you will have access to Consumer Token, Consumer Secret, Access Key as well as Access Secret. You will need to mention the reason for applying for API access, and you can mention reasons such as “student learning project” or “learning to use Python for data science” as reasons.
Save your credentials in a config file and run source ./config to load the keys as environment variables. This is so as to not expose your keys in a Python script. Make sure to not commit this config file into Github. We will tweepy library in Python to get access to Twitter API. It is a nice wrapper over the raw Twitter API and provides a lot of heavy lifting for creating API URLs and http requests. We just need to provide our keys from Step 1, and Tweepy takes care of talking with Twitter API — which is pretty cool.Run pip install tweepy to get the tweepy package in your virtual environment. (I’ve been using pyenv to manage different versions of Python, and have been very impressed. You’ll also need pyenv-virtualenv package to manage virtual environments for you — but this is another blog in itself)In Python you can type:
import osimport jsonimport tweepyfrom tweepy import Stream # Useful in Step 3from tweepy.streaming import StreamListener # Useful in Step 3consumer_key = os.getenv(“CONSUMER_KEY_TWITTER”)consumer_secret = os.getenv(“CONSUMER_SECRET_TWITTER”)access_token = os.getenv(“ACCESS_KEY_TWITTER”)access_token_secret = os.getenv(“ACCESS_SECRET_TWITTER”)auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)
This will setup your environment variables and also setup api object that can be used to access Twitter API data.
Having setup the credentials, now it’s time to get Tweet data via API. I like using Streaming API to filter real time tweets on my topic of interest. There is also Search API which allows you to search for historic data, but as you can see from this chart, it can be little restrictive for free access, with maximum access to data of last 7 days. For the paid plan, based on what I saw online, the price can range anywhere from $149 to $2499/month (or even more) — I couldn’t find a page for exact pricing on Twitter website.
To setup the Streaming API, you will need to define your own class method on_data that does something from the data object from Streaming API.
class listener(StreamListener): def on_data(self, data): data = json.loads(data) # Filter out non-English Tweets if data.get("lang") != "en": return True try: timestamp = data['timestamp_ms'] # Get longer 280 char tweets if possible if data.get("extended_tweet"): tweet = data['extended_tweet']["full_text"] else: tweet = data["text"] url = "https://www.twitter.com/i/web/status/" + data["id_str"] user = data["user"]["screen_name"] verified = data["user"]["verified"] write_to_csv([timestamp, tweet, user, verified, url]) except KeyError as e: print("Keyerror:", e) return True def on_error(self, status): print(status)
I have not included write_to_csv function but it can be implemented using csv library, and some examples can be seen here.
You could also save the tweets into a SQLite database esp. if there are several hundred thousand tweets. SQLite will also allow you to have command line access to all the information via SQL commands. For CSV you will have to load into a Pandas dataframe in a notebook. It just depends on which workflow you prefer. Typically you can just save into the SQLite database, and use read_sql command in pandas to make it into a dataframe object. This allows me to access data both from command line as well as pandas.
Finally, run this function stream_and_write to start the Streaming API and call the listener we have written above. The main thing is to call Stream API using extended mode as it will give you access to longer and potentially informative tweets.
def stream_and_write(table, track=None): try: twitterStream = Stream(auth, listener(), tweet_mode='extended') twitterStream.filter(track=["AAPL", "AMZN", "UBER"]) except Exception as e: print("Error:", str(e)) time.sleep(5)
Another important thing to note is the number of items that you can track using Streaming API. From my testing, I was not able to track more than 400 or so items in the track list. Keep this in mind while building out your ideas.
Sentiment Analysis can be done either in the listener above or off-line once we have collected all the tweet data.We can use out-of-the-box Sentiment processing libraries in Python. From what I saw, I liked TextBlob and Vader Sentiment.TextBlob provides a subjectivity score along with a polarity score. Vader provides a pos, neu, neg and a compound score. For single sentiment score between -1 and 1 for both libraries, use polarity from TextBlob and compound from Vader Sentiment.As per the Github page of Vader Sentiment,
VADER Sentiment Analysis. VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media, and works well on texts from other domains.
For TextBlob,
from textblob import TextBlobts = TextBlob(tweet).sentimentprint(ts.subjectivity, ts.polarity) # Subjectivity, Sentiment Scores
For Vader:
from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzeranalyzer = SentimentIntensityAnalyzer()vs = analyzer.polarity_scores(tweet)print(vs["compound"], vs["pos"], vs["neu"], vs["neg"])
Saving the sentiment information along with tweets, allows you to build plots for sentiment score for different stocks or events over time. Vader vs TextBlob will depend on your own project, I also tried ensemble of the two above libraries, but somehow liked the simplicity of just using one library for different tasks. Ideally, you’d train your own sentiment analysis model with things that matter to you, but that’d need collecting your own training data and building and evaluating a machine learning model. For being able to capture negative emotion in sentences like “I expected an amazing movie, but it turned out not to be”, we will need models that can work with sequence data and recognize that the not to be is negating the earlier amazing , this needs models built from Long Short Term Memory (LSTM) cells in neural networks. Training and setting up a LSTM network for sentiment analysis could be another blog post of its own, leave comments below if you are interested to read about this.
I plotted the sentiment when Manchester United lost to Barcelona 3–0 in their Champions League Quarter-Finals. As you can see, the sentiment drops over time, and as the teams played on 16th Apr around the afternoon mark, the sentiment starts to drop.
While the sentiment score worked quite well for a sports event, what about stock market? Below is the Qualcomm (QCOM) performance during the week when Apple dropped their lawsuits with Qualcomm (exact news of this came on April 16th). We’d expect a significant increase in positive sentiment around this news, but it is very hard to conclusively see it below:
This makes the challenge of extracting alpha from sentiment analysis much more challenging. I feel that it is a great tool for seeing sentiment around news events or sports activities but trying to co-relate sentiments with stock market performance is harder as it involves filtering out noisy tweets and also doing a lot of feature engineering work to get signal.
You don’t want to be running the Streaming API on your computer, because when you shut it, the script will also stop. You should run this on a AWS EC2 instance or on Google Cloud Platform server. I am not going into the details on how to set that up, there are fantastic resources [AWS and GCP] for it. Run the above script using tmux or screen and get access to topics of your interest on Twitter!
It was great fun getting data from Twitter and building a sentiment analysis engine. It is very satisfying to see downward or upward sentiment trends for events as you expect them to be. The next step would be to plot the sentiment exactly as they unfold instead of saving the tweets first, this would need a library like dash.
Good luck exploring Twitter data — may you see the trends as you expect them to be! Thanks for reading.
Resources:1. TextBlob: https://textblob.readthedocs.io/en/dev/ 2. Vader: https://github.com/cjhutto/vaderSentiment 3. Get Twitter API Access: https://developer.twitter.com/en/apply-for-access4. Blog that compares some of these libraries: https://neptune.ai/blog/sentiment-analysis-python-textblob-vs-vader-vs-flair | [
{
"code": null,
"e": 750,
"s": 172,
"text": "Twitter is a rich source for information. From minute-to-minute trends to general discussions around topics, Twitter is a great source of data for a project. Also, Twitter has built an amazing API for developers to use this data. Could we track an event and see what people are thinking? Is it possible to run sentiment analysis on what the world is thinking as an event unfolds over time? Could we track Twitter data and see if it correlates to news that affects stock market movements? These were some of the questions in my mind as I began to dig into Twitter data recently."
},
{
"code": null,
"e": 1068,
"s": 750,
"text": "If you prefer to listen to the audio version of this blog, I have also recorded a podcast episode for this blog post — where I go into more details of each of the step including caveats and things to avoid. You can listen to it on Apple Podcasts, Spotify or Anchor.fm, or on one of my favorite podcast apps: Overcast."
},
{
"code": null,
"e": 1153,
"s": 1068,
"text": "Let’s get right into the steps to use Twitter data for sentiment analysis of events:"
},
{
"code": null,
"e": 1215,
"s": 1153,
"text": "First, visit this link and get access to a developer account."
},
{
"code": null,
"e": 1513,
"s": 1215,
"text": "Once you register, you will have access to Consumer Token, Consumer Secret, Access Key as well as Access Secret. You will need to mention the reason for applying for API access, and you can mention reasons such as “student learning project” or “learning to use Python for data science” as reasons."
},
{
"code": null,
"e": 2349,
"s": 1513,
"text": "Save your credentials in a config file and run source ./config to load the keys as environment variables. This is so as to not expose your keys in a Python script. Make sure to not commit this config file into Github. We will tweepy library in Python to get access to Twitter API. It is a nice wrapper over the raw Twitter API and provides a lot of heavy lifting for creating API URLs and http requests. We just need to provide our keys from Step 1, and Tweepy takes care of talking with Twitter API — which is pretty cool.Run pip install tweepy to get the tweepy package in your virtual environment. (I’ve been using pyenv to manage different versions of Python, and have been very impressed. You’ll also need pyenv-virtualenv package to manage virtual environments for you — but this is another blog in itself)In Python you can type:"
},
{
"code": null,
"e": 2846,
"s": 2349,
"text": "import osimport jsonimport tweepyfrom tweepy import Stream # Useful in Step 3from tweepy.streaming import StreamListener # Useful in Step 3consumer_key = os.getenv(“CONSUMER_KEY_TWITTER”)consumer_secret = os.getenv(“CONSUMER_SECRET_TWITTER”)access_token = os.getenv(“ACCESS_KEY_TWITTER”)access_token_secret = os.getenv(“ACCESS_SECRET_TWITTER”)auth = tweepy.OAuthHandler(consumer_key, consumer_secret)auth.set_access_token(access_token, access_token_secret)api = tweepy.API(auth)"
},
{
"code": null,
"e": 2960,
"s": 2846,
"text": "This will setup your environment variables and also setup api object that can be used to access Twitter API data."
},
{
"code": null,
"e": 3486,
"s": 2960,
"text": "Having setup the credentials, now it’s time to get Tweet data via API. I like using Streaming API to filter real time tweets on my topic of interest. There is also Search API which allows you to search for historic data, but as you can see from this chart, it can be little restrictive for free access, with maximum access to data of last 7 days. For the paid plan, based on what I saw online, the price can range anywhere from $149 to $2499/month (or even more) — I couldn’t find a page for exact pricing on Twitter website."
},
{
"code": null,
"e": 3629,
"s": 3486,
"text": "To setup the Streaming API, you will need to define your own class method on_data that does something from the data object from Streaming API."
},
{
"code": null,
"e": 4510,
"s": 3629,
"text": "class listener(StreamListener): def on_data(self, data): data = json.loads(data) # Filter out non-English Tweets if data.get(\"lang\") != \"en\": return True try: timestamp = data['timestamp_ms'] # Get longer 280 char tweets if possible if data.get(\"extended_tweet\"): tweet = data['extended_tweet'][\"full_text\"] else: tweet = data[\"text\"] url = \"https://www.twitter.com/i/web/status/\" + data[\"id_str\"] user = data[\"user\"][\"screen_name\"] verified = data[\"user\"][\"verified\"] write_to_csv([timestamp, tweet, user, verified, url]) except KeyError as e: print(\"Keyerror:\", e) return True def on_error(self, status): print(status)"
},
{
"code": null,
"e": 4633,
"s": 4510,
"text": "I have not included write_to_csv function but it can be implemented using csv library, and some examples can be seen here."
},
{
"code": null,
"e": 5146,
"s": 4633,
"text": "You could also save the tweets into a SQLite database esp. if there are several hundred thousand tweets. SQLite will also allow you to have command line access to all the information via SQL commands. For CSV you will have to load into a Pandas dataframe in a notebook. It just depends on which workflow you prefer. Typically you can just save into the SQLite database, and use read_sql command in pandas to make it into a dataframe object. This allows me to access data both from command line as well as pandas."
},
{
"code": null,
"e": 5392,
"s": 5146,
"text": "Finally, run this function stream_and_write to start the Streaming API and call the listener we have written above. The main thing is to call Stream API using extended mode as it will give you access to longer and potentially informative tweets."
},
{
"code": null,
"e": 5681,
"s": 5392,
"text": "def stream_and_write(table, track=None): try: twitterStream = Stream(auth, listener(), tweet_mode='extended') twitterStream.filter(track=[\"AAPL\", \"AMZN\", \"UBER\"]) except Exception as e: print(\"Error:\", str(e)) time.sleep(5)"
},
{
"code": null,
"e": 5911,
"s": 5681,
"text": "Another important thing to note is the number of items that you can track using Streaming API. From my testing, I was not able to track more than 400 or so items in the track list. Keep this in mind while building out your ideas."
},
{
"code": null,
"e": 6436,
"s": 5911,
"text": "Sentiment Analysis can be done either in the listener above or off-line once we have collected all the tweet data.We can use out-of-the-box Sentiment processing libraries in Python. From what I saw, I liked TextBlob and Vader Sentiment.TextBlob provides a subjectivity score along with a polarity score. Vader provides a pos, neu, neg and a compound score. For single sentiment score between -1 and 1 for both libraries, use polarity from TextBlob and compound from Vader Sentiment.As per the Github page of Vader Sentiment,"
},
{
"code": null,
"e": 6684,
"s": 6436,
"text": "VADER Sentiment Analysis. VADER (Valence Aware Dictionary and sEntiment Reasoner) is a lexicon and rule-based sentiment analysis tool that is specifically attuned to sentiments expressed in social media, and works well on texts from other domains."
},
{
"code": null,
"e": 6698,
"s": 6684,
"text": "For TextBlob,"
},
{
"code": null,
"e": 6826,
"s": 6698,
"text": "from textblob import TextBlobts = TextBlob(tweet).sentimentprint(ts.subjectivity, ts.polarity) # Subjectivity, Sentiment Scores"
},
{
"code": null,
"e": 6837,
"s": 6826,
"text": "For Vader:"
},
{
"code": null,
"e": 7035,
"s": 6837,
"text": "from vaderSentiment.vaderSentiment import SentimentIntensityAnalyzeranalyzer = SentimentIntensityAnalyzer()vs = analyzer.polarity_scores(tweet)print(vs[\"compound\"], vs[\"pos\"], vs[\"neu\"], vs[\"neg\"])"
},
{
"code": null,
"e": 8037,
"s": 7035,
"text": "Saving the sentiment information along with tweets, allows you to build plots for sentiment score for different stocks or events over time. Vader vs TextBlob will depend on your own project, I also tried ensemble of the two above libraries, but somehow liked the simplicity of just using one library for different tasks. Ideally, you’d train your own sentiment analysis model with things that matter to you, but that’d need collecting your own training data and building and evaluating a machine learning model. For being able to capture negative emotion in sentences like “I expected an amazing movie, but it turned out not to be”, we will need models that can work with sequence data and recognize that the not to be is negating the earlier amazing , this needs models built from Long Short Term Memory (LSTM) cells in neural networks. Training and setting up a LSTM network for sentiment analysis could be another blog post of its own, leave comments below if you are interested to read about this."
},
{
"code": null,
"e": 8288,
"s": 8037,
"text": "I plotted the sentiment when Manchester United lost to Barcelona 3–0 in their Champions League Quarter-Finals. As you can see, the sentiment drops over time, and as the teams played on 16th Apr around the afternoon mark, the sentiment starts to drop."
},
{
"code": null,
"e": 8648,
"s": 8288,
"text": "While the sentiment score worked quite well for a sports event, what about stock market? Below is the Qualcomm (QCOM) performance during the week when Apple dropped their lawsuits with Qualcomm (exact news of this came on April 16th). We’d expect a significant increase in positive sentiment around this news, but it is very hard to conclusively see it below:"
},
{
"code": null,
"e": 9013,
"s": 8648,
"text": "This makes the challenge of extracting alpha from sentiment analysis much more challenging. I feel that it is a great tool for seeing sentiment around news events or sports activities but trying to co-relate sentiments with stock market performance is harder as it involves filtering out noisy tweets and also doing a lot of feature engineering work to get signal."
},
{
"code": null,
"e": 9412,
"s": 9013,
"text": "You don’t want to be running the Streaming API on your computer, because when you shut it, the script will also stop. You should run this on a AWS EC2 instance or on Google Cloud Platform server. I am not going into the details on how to set that up, there are fantastic resources [AWS and GCP] for it. Run the above script using tmux or screen and get access to topics of your interest on Twitter!"
},
{
"code": null,
"e": 9740,
"s": 9412,
"text": "It was great fun getting data from Twitter and building a sentiment analysis engine. It is very satisfying to see downward or upward sentiment trends for events as you expect them to be. The next step would be to plot the sentiment exactly as they unfold instead of saving the tweets first, this would need a library like dash."
},
{
"code": null,
"e": 9844,
"s": 9740,
"text": "Good luck exploring Twitter data — may you see the trends as you expect them to be! Thanks for reading."
}
] |
JavaScript Number toFixed( ) Method - GeeksforGeeks | 22 Dec, 2021
Below is the example of the Number toFixed( ) Method.
Example:<script type="text/javascript"> var test=213.73145; document.write(test.toFixed(1)); </script>
<script type="text/javascript"> var test=213.73145; document.write(test.toFixed(1)); </script>
Output:213.7
213.7
The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal.
Syntax:
number.toFixed( value )
The toFixed() method is used with a number as shown in above syntax using the ‘.’ operator. This method will format a number using fixed-point notation.
Parameters: This method accepts a single parameter value . It signifies the number of digits to appear after the decimal point.
Return Value: It returns a number in the string representation. The number has the exact number of digits after the decimal place as mentioned in the toFixed() method.
Example
Using toFixed() method without any parameter: If there is no parameter specified in the toFixed() method then it doesn’t display any digits after the decimal place.<script type="text/javascript"> var test=213.73145; document.write(test.toFixed()); </script>Output:214
<script type="text/javascript"> var test=213.73145; document.write(test.toFixed()); </script>
Output:
214
Using toFixed() method with a parameter: If there is a parameter specified in the toFixed() method will return a number represented as string which will have exactly that number of digits after the decimal place.<script type="text/javascript"> var test=213.73145; document.write(test.toFixed(3)); </script>Output:214.731
<script type="text/javascript"> var test=213.73145; document.write(test.toFixed(3)); </script>
Output:
214.731
Using toFixed() method where the number is in exponential form: The toFixed() method can be used to convert an exponential number into a string representation with a specific number of digits after the decimal place.<script type="text/javascript"> var test=2.13e+15; document.write(test.toFixed(2)); </script>Output:2130000000000000.00
<script type="text/javascript"> var test=2.13e+15; document.write(test.toFixed(2)); </script>
Output:
2130000000000000.00
Supported Browsers:
Google Chrome 1 and above
Internet Explorer 5.5 and above
Firefox 1 and above
Apple Safari 2 and above
Opera 7 and above
ysachin2314
JavaScript-Methods
JavaScript-Numbers
JavaScript
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Comments
Old Comments
Convert a string to an integer in JavaScript
Difference between var, let and const keywords in JavaScript
Differences between Functional Components and Class Components in React
Difference Between PUT and PATCH Request
Set the value of an input field in JavaScript
Roadmap to Become a Web Developer in 2022
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
How to insert spaces/tabs in text using HTML/CSS? | [
{
"code": null,
"e": 24960,
"s": 24932,
"text": "\n22 Dec, 2021"
},
{
"code": null,
"e": 25014,
"s": 24960,
"text": "Below is the example of the Number toFixed( ) Method."
},
{
"code": null,
"e": 25132,
"s": 25014,
"text": "Example:<script type=\"text/javascript\"> var test=213.73145; document.write(test.toFixed(1)); </script>"
},
{
"code": "<script type=\"text/javascript\"> var test=213.73145; document.write(test.toFixed(1)); </script>",
"e": 25242,
"s": 25132,
"text": null
},
{
"code": null,
"e": 25255,
"s": 25242,
"text": "Output:213.7"
},
{
"code": null,
"e": 25261,
"s": 25255,
"text": "213.7"
},
{
"code": null,
"e": 25447,
"s": 25261,
"text": "The toFixed() method in JavaScript is used to format a number using fixed-point notation. It can be used to format a number with a specific number of digits to the right of the decimal."
},
{
"code": null,
"e": 25455,
"s": 25447,
"text": "Syntax:"
},
{
"code": null,
"e": 25479,
"s": 25455,
"text": "number.toFixed( value )"
},
{
"code": null,
"e": 25632,
"s": 25479,
"text": "The toFixed() method is used with a number as shown in above syntax using the ‘.’ operator. This method will format a number using fixed-point notation."
},
{
"code": null,
"e": 25760,
"s": 25632,
"text": "Parameters: This method accepts a single parameter value . It signifies the number of digits to appear after the decimal point."
},
{
"code": null,
"e": 25928,
"s": 25760,
"text": "Return Value: It returns a number in the string representation. The number has the exact number of digits after the decimal place as mentioned in the toFixed() method."
},
{
"code": null,
"e": 25936,
"s": 25928,
"text": "Example"
},
{
"code": null,
"e": 26219,
"s": 25936,
"text": "Using toFixed() method without any parameter: If there is no parameter specified in the toFixed() method then it doesn’t display any digits after the decimal place.<script type=\"text/javascript\"> var test=213.73145; document.write(test.toFixed()); </script>Output:214"
},
{
"code": "<script type=\"text/javascript\"> var test=213.73145; document.write(test.toFixed()); </script>",
"e": 26328,
"s": 26219,
"text": null
},
{
"code": null,
"e": 26336,
"s": 26328,
"text": "Output:"
},
{
"code": null,
"e": 26340,
"s": 26336,
"text": "214"
},
{
"code": null,
"e": 26676,
"s": 26340,
"text": "Using toFixed() method with a parameter: If there is a parameter specified in the toFixed() method will return a number represented as string which will have exactly that number of digits after the decimal place.<script type=\"text/javascript\"> var test=213.73145; document.write(test.toFixed(3)); </script>Output:214.731"
},
{
"code": "<script type=\"text/javascript\"> var test=213.73145; document.write(test.toFixed(3)); </script>",
"e": 26786,
"s": 26676,
"text": null
},
{
"code": null,
"e": 26794,
"s": 26786,
"text": "Output:"
},
{
"code": null,
"e": 26802,
"s": 26794,
"text": "214.731"
},
{
"code": null,
"e": 27153,
"s": 26802,
"text": "Using toFixed() method where the number is in exponential form: The toFixed() method can be used to convert an exponential number into a string representation with a specific number of digits after the decimal place.<script type=\"text/javascript\"> var test=2.13e+15; document.write(test.toFixed(2)); </script>Output:2130000000000000.00"
},
{
"code": "<script type=\"text/javascript\"> var test=2.13e+15; document.write(test.toFixed(2)); </script>",
"e": 27262,
"s": 27153,
"text": null
},
{
"code": null,
"e": 27270,
"s": 27262,
"text": "Output:"
},
{
"code": null,
"e": 27290,
"s": 27270,
"text": "2130000000000000.00"
},
{
"code": null,
"e": 27310,
"s": 27290,
"text": "Supported Browsers:"
},
{
"code": null,
"e": 27336,
"s": 27310,
"text": "Google Chrome 1 and above"
},
{
"code": null,
"e": 27368,
"s": 27336,
"text": "Internet Explorer 5.5 and above"
},
{
"code": null,
"e": 27388,
"s": 27368,
"text": "Firefox 1 and above"
},
{
"code": null,
"e": 27413,
"s": 27388,
"text": "Apple Safari 2 and above"
},
{
"code": null,
"e": 27431,
"s": 27413,
"text": "Opera 7 and above"
},
{
"code": null,
"e": 27443,
"s": 27431,
"text": "ysachin2314"
},
{
"code": null,
"e": 27462,
"s": 27443,
"text": "JavaScript-Methods"
},
{
"code": null,
"e": 27481,
"s": 27462,
"text": "JavaScript-Numbers"
},
{
"code": null,
"e": 27492,
"s": 27481,
"text": "JavaScript"
},
{
"code": null,
"e": 27509,
"s": 27492,
"text": "Web Technologies"
},
{
"code": null,
"e": 27607,
"s": 27509,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27616,
"s": 27607,
"text": "Comments"
},
{
"code": null,
"e": 27629,
"s": 27616,
"text": "Old Comments"
},
{
"code": null,
"e": 27674,
"s": 27629,
"text": "Convert a string to an integer in JavaScript"
},
{
"code": null,
"e": 27735,
"s": 27674,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 27807,
"s": 27735,
"text": "Differences between Functional Components and Class Components in React"
},
{
"code": null,
"e": 27848,
"s": 27807,
"text": "Difference Between PUT and PATCH Request"
},
{
"code": null,
"e": 27894,
"s": 27848,
"text": "Set the value of an input field in JavaScript"
},
{
"code": null,
"e": 27936,
"s": 27894,
"text": "Roadmap to Become a Web Developer in 2022"
},
{
"code": null,
"e": 27969,
"s": 27936,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 28012,
"s": 27969,
"text": "How to fetch data from an API in ReactJS ?"
},
{
"code": null,
"e": 28074,
"s": 28012,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
}
] |
Two cool features of Python NumPy: Mutating by slicing and Broadcasting | by Tirthajyoti Sarkar | Towards Data Science | It turns out that if you use simple slicing/indexing with NumPy to create a sub-array, the sub-array actually points to the main array. Simply put, the in-memory diagram looks like,
Therefore, if the sliced array is changed, it affects the parent array too. This could be a useful feature to propagate the desired chain up the food chain but sometimes could also be a nuisance where you to keep the main data set immutable and effect your changes on the subset only. In those cases, you have to explicitly call np.array method to define the sliced array, not just slice it out by indexing. The following code illustrates the point,
mat = np.array([[11,12,13],[21,22,23],[31,32,33]])print("Original matrix")print(mat)mat_slice = mat[:2,:2] # Simple indexingprint ("\nSliced matrix")print(mat_slice)print ("\nChange the sliced matrix")mat_slice[0,0] = 1000print (mat_slice)print("\nBut the original matrix? WHOA! It got changed too!")print(mat)
The result looks like,
Original matrix[[11 12 13] [21 22 23] [31 32 33]]Sliced matrix[[11 12] [21 22]]Change the sliced matrix[[1000 12] [ 21 22]]But the original matrix? WHOA! It got changed too![[1000 12 13] [ 21 22 23] [ 31 32 33]]
To stop this from happening, this is what you should do,
# Little different way to create a copy of the sliced matrixprint ("\nDoing it again little differently now...\n")mat = np.array([[11,12,13],[21,22,23],[31,32,33]])print("Original matrix")print(mat)mat_slice = np.array(mat[:2,:2]) # Notice the np.array methodprint ("\nSliced matrix")print(mat_slice)print ("\nChange the sliced matrix")mat_slice[0,0] = 1000print (mat_slice)print("\nBut the original matrix? NO CHANGE this time:)")print(mat)
Now the original matrix is not mutated by any change in the sub-matrix,
Original matrix[[11 12 13] [21 22 23] [31 32 33]]Sliced matrix[[11 12] [21 22]]Change the sliced matrix[[1000 12] [ 21 22]]But the original matrix? NO CHANGE this time:)[[11 12 13] [21 22 23] [31 32 33]]
NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the general case, the two arrays must have exactly the same shape (or for matrix multiplication the inner dimension must conform).
NumPy’s broadcasting rule relaxes this constraint when the arrays’ shapes meet certain constraints. When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when
they are equal, or
one of them is 1
If these conditions are not met, a ValueError: frames are not aligned exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays.
For more detail, please look up: https://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html.
Following code block illustrates the idea step-by-step,
Initialize a ‘start’ matrix with zeroes
start = np.zeros((4,3))print(start)[[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]
Create a row matrix (vector),
# create a rank 1 ndarray with 3 valuesadd_rows = np.array([1, 0, 2])print(add_rows)[1 0 2]
Add the zero-matrix (4x3) to the (1x3) vector. Automatically, the 1x3 vector is duplicated 4 times to match the row dimension of the zero matrix and those values are added to the 4x3 matrix.
y = start + add_rows # add to each row of 'start'print(y)[[ 1. 0. 2.] [ 1. 0. 2.] [ 1. 0. 2.] [ 1. 0. 2.]]
Create a column matrix (vector),
# create an ndarray which is 4 x 1 to broadcast across columnsadd_cols = np.array([[0,1,2,3]])add_cols = add_cols.Tprint(add_cols)[[0] [1] [2] [3]]
Add the zero-matrix (4x3) to the (4x1) vector. Automatically, the 4x1 vector is duplicated 3 times to match the column dimension of the zero matrix and those values are added to the 4x3 matrix.
# add to each column of 'start' using broadcastingy = start + add_cols print(y)[[ 0. 0. 0.] [ 1. 1. 1.] [ 2. 2. 2.] [ 3. 3. 3.]]
Finally, a scalar is treated like a 1x1 matrix and duplicated exactly to the size of the additive matrix to execute the operation.
# this will just broadcast in both dimensionsadd_scalar = np.array([100]) print(start+add_scalar)[[ 100. 100. 100.] [ 100. 100. 100.] [ 100. 100. 100.] [ 100. 100. 100.]]
Utility of broadcasting is best realized when you use NumPy arrays to write vectorized code for an algorithm like gradient descent. Andrew Ng spends a full video lecture explaining the concept of broadcasting in Python in his new Deep Learning course. It makes the implementation of the forward and back-propagation algorithm for deep neural network relatively painless.
You can check out this video also about demonstration of broadcasting feature...
If you have any questions or ideas to share, please contact the author at tirthajyoti[AT]gmail.com. Also you can check author’s GitHub repositories for other fun code snippets in Python, R, or MATLAB and machine learning resources. You can also follow me on LinkedIn. | [
{
"code": null,
"e": 354,
"s": 172,
"text": "It turns out that if you use simple slicing/indexing with NumPy to create a sub-array, the sub-array actually points to the main array. Simply put, the in-memory diagram looks like,"
},
{
"code": null,
"e": 804,
"s": 354,
"text": "Therefore, if the sliced array is changed, it affects the parent array too. This could be a useful feature to propagate the desired chain up the food chain but sometimes could also be a nuisance where you to keep the main data set immutable and effect your changes on the subset only. In those cases, you have to explicitly call np.array method to define the sliced array, not just slice it out by indexing. The following code illustrates the point,"
},
{
"code": null,
"e": 1115,
"s": 804,
"text": "mat = np.array([[11,12,13],[21,22,23],[31,32,33]])print(\"Original matrix\")print(mat)mat_slice = mat[:2,:2] # Simple indexingprint (\"\\nSliced matrix\")print(mat_slice)print (\"\\nChange the sliced matrix\")mat_slice[0,0] = 1000print (mat_slice)print(\"\\nBut the original matrix? WHOA! It got changed too!\")print(mat)"
},
{
"code": null,
"e": 1138,
"s": 1115,
"text": "The result looks like,"
},
{
"code": null,
"e": 1369,
"s": 1138,
"text": "Original matrix[[11 12 13] [21 22 23] [31 32 33]]Sliced matrix[[11 12] [21 22]]Change the sliced matrix[[1000 12] [ 21 22]]But the original matrix? WHOA! It got changed too![[1000 12 13] [ 21 22 23] [ 31 32 33]]"
},
{
"code": null,
"e": 1426,
"s": 1369,
"text": "To stop this from happening, this is what you should do,"
},
{
"code": null,
"e": 1868,
"s": 1426,
"text": "# Little different way to create a copy of the sliced matrixprint (\"\\nDoing it again little differently now...\\n\")mat = np.array([[11,12,13],[21,22,23],[31,32,33]])print(\"Original matrix\")print(mat)mat_slice = np.array(mat[:2,:2]) # Notice the np.array methodprint (\"\\nSliced matrix\")print(mat_slice)print (\"\\nChange the sliced matrix\")mat_slice[0,0] = 1000print (mat_slice)print(\"\\nBut the original matrix? NO CHANGE this time:)\")print(mat)"
},
{
"code": null,
"e": 1940,
"s": 1868,
"text": "Now the original matrix is not mutated by any change in the sub-matrix,"
},
{
"code": null,
"e": 2149,
"s": 1940,
"text": "Original matrix[[11 12 13] [21 22 23] [31 32 33]]Sliced matrix[[11 12] [21 22]]Change the sliced matrix[[1000 12] [ 21 22]]But the original matrix? NO CHANGE this time:)[[11 12 13] [21 22 23] [31 32 33]]"
},
{
"code": null,
"e": 2368,
"s": 2149,
"text": "NumPy operations are usually done on pairs of arrays on an element-by-element basis. In the general case, the two arrays must have exactly the same shape (or for matrix multiplication the inner dimension must conform)."
},
{
"code": null,
"e": 2642,
"s": 2368,
"text": "NumPy’s broadcasting rule relaxes this constraint when the arrays’ shapes meet certain constraints. When operating on two arrays, NumPy compares their shapes element-wise. It starts with the trailing dimensions, and works its way forward. Two dimensions are compatible when"
},
{
"code": null,
"e": 2661,
"s": 2642,
"text": "they are equal, or"
},
{
"code": null,
"e": 2678,
"s": 2661,
"text": "one of them is 1"
},
{
"code": null,
"e": 2916,
"s": 2678,
"text": "If these conditions are not met, a ValueError: frames are not aligned exception is thrown, indicating that the arrays have incompatible shapes. The size of the resulting array is the maximum size along each dimension of the input arrays."
},
{
"code": null,
"e": 3020,
"s": 2916,
"text": "For more detail, please look up: https://docs.scipy.org/doc/numpy-1.10.1/user/basics.broadcasting.html."
},
{
"code": null,
"e": 3076,
"s": 3020,
"text": "Following code block illustrates the idea step-by-step,"
},
{
"code": null,
"e": 3116,
"s": 3076,
"text": "Initialize a ‘start’ matrix with zeroes"
},
{
"code": null,
"e": 3209,
"s": 3116,
"text": "start = np.zeros((4,3))print(start)[[ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.] [ 0. 0. 0.]]"
},
{
"code": null,
"e": 3239,
"s": 3209,
"text": "Create a row matrix (vector),"
},
{
"code": null,
"e": 3331,
"s": 3239,
"text": "# create a rank 1 ndarray with 3 valuesadd_rows = np.array([1, 0, 2])print(add_rows)[1 0 2]"
},
{
"code": null,
"e": 3522,
"s": 3331,
"text": "Add the zero-matrix (4x3) to the (1x3) vector. Automatically, the 1x3 vector is duplicated 4 times to match the row dimension of the zero matrix and those values are added to the 4x3 matrix."
},
{
"code": null,
"e": 3638,
"s": 3522,
"text": "y = start + add_rows # add to each row of 'start'print(y)[[ 1. 0. 2.] [ 1. 0. 2.] [ 1. 0. 2.] [ 1. 0. 2.]]"
},
{
"code": null,
"e": 3671,
"s": 3638,
"text": "Create a column matrix (vector),"
},
{
"code": null,
"e": 3819,
"s": 3671,
"text": "# create an ndarray which is 4 x 1 to broadcast across columnsadd_cols = np.array([[0,1,2,3]])add_cols = add_cols.Tprint(add_cols)[[0] [1] [2] [3]]"
},
{
"code": null,
"e": 4013,
"s": 3819,
"text": "Add the zero-matrix (4x3) to the (4x1) vector. Automatically, the 4x1 vector is duplicated 3 times to match the column dimension of the zero matrix and those values are added to the 4x3 matrix."
},
{
"code": null,
"e": 4150,
"s": 4013,
"text": "# add to each column of 'start' using broadcastingy = start + add_cols print(y)[[ 0. 0. 0.] [ 1. 1. 1.] [ 2. 2. 2.] [ 3. 3. 3.]]"
},
{
"code": null,
"e": 4281,
"s": 4150,
"text": "Finally, a scalar is treated like a 1x1 matrix and duplicated exactly to the size of the additive matrix to execute the operation."
},
{
"code": null,
"e": 4461,
"s": 4281,
"text": "# this will just broadcast in both dimensionsadd_scalar = np.array([100]) print(start+add_scalar)[[ 100. 100. 100.] [ 100. 100. 100.] [ 100. 100. 100.] [ 100. 100. 100.]]"
},
{
"code": null,
"e": 4832,
"s": 4461,
"text": "Utility of broadcasting is best realized when you use NumPy arrays to write vectorized code for an algorithm like gradient descent. Andrew Ng spends a full video lecture explaining the concept of broadcasting in Python in his new Deep Learning course. It makes the implementation of the forward and back-propagation algorithm for deep neural network relatively painless."
},
{
"code": null,
"e": 4913,
"s": 4832,
"text": "You can check out this video also about demonstration of broadcasting feature..."
}
] |
The Bechdel Test: Analyzing gender disparity in Hollywood | by Natassha Selvaraj | Towards Data Science | What is the Bechdel test?
The Bechdel test is named after cartoonist Alison Bechdel, who introduced the idea in a comic strip in the year 1985. To pass the test, a story needs to have:
At least two women
The women need to talk to each other
They need to talk to each other about something other than a man
I first heard about the Bechdel test when watching Jane the Virgin, and it caught my interest. To me, it seemed like the standards of the test were too low, and should be ridiculously easy for movies to pass.
However, a simple Google search told me otherwise. Apparently, there were a large number of movies that did not fulfill the requirements to pass the Bechdel test, including:
Slumdog Millionaire
The Blind Side
Tarzan
The Imitation Game
The Social Network
After doing some reading on the Bechdel test, I was struck with inspiration. I decided to conduct data analysis on movie datasets to check whether or not they passed the test!
The Data Question
My aim was to collect data from various different sources, and answer the following questions about the Bechdel test:
Have the Bechdel scores of movies improved over the years?Do movies with higher IMDB ratings have higher Bechdel scores?Do movies with female directors have higher Bechdel scores?Does the budget of a movie have any impact on its Bechdel score?Do movies with higher Bechdel scores generate a larger revenue?
Have the Bechdel scores of movies improved over the years?
Do movies with higher IMDB ratings have higher Bechdel scores?
Do movies with female directors have higher Bechdel scores?
Does the budget of a movie have any impact on its Bechdel score?
Do movies with higher Bechdel scores generate a larger revenue?
Data Collection
I collected data from three different sources: bechdeltest.com, Kaggle, and this movies dataset.
Data Analysis
I will use Python to perform all data analysis and visualization.
First, I used data from bechdeltest.com, which was pretty easy to grab because of their API.
# importsimport urllib, jsonimport pandas as pddf = pd.read_json('http://bechdeltest.com/api/v1/getAllMovies')
Now, I will take a look at the head of the data frame:
df.head()
There are five variables in the data frame:
rating: Bechdel Score of the movie from 0 to 3. A Bechdel score lower than 3 means the movie failed the Bechdel test, and a Bechdel score of 3 means the movie passed.
imdbid: The movie’s IMDB number
title: Movie title
id: Unique movie ID
year: Year the movie was released
Taking a look at the column ‘year’, you can see that there are movies present from the 19th century, and a lot of those movies have a Bechdel score of 0.
I am going to create a new data frame with movies released after the year 1967, and will be using this new data frame for the rest of my analysis.
dfNew = df[df['year']>=1967]
Taking a look at the new data frame:
dfNew.head()
I am now going to rename the column ‘rating’ to ‘Bechdel Score’, to make things clearer for the rest of the analysis.
dfNew.rename(columns={'rating':'Bechdel Score'}, inplace=True)
Now, I am going to convert the ‘year’ column into a datetime object.
dfNew['year'] = pd.to_datetime(dfNew['year'], format='%Y')
Next, I will change the Bechdel Scores to categorical variables.
dfNew['Bechdel Score'] = dfNew['Bechdel Score'].astype('category',copy=False)
Finally, the data is prepared and can be used to do some data visualization.
I will first create a count plot using Seaborn, to visualize the Bechdel scores.
sns.countplot(x='Bechdel Score',data=dfNew)
Most movies after the year 1967 seem to have higher Bechdel scores, but do they pass the Bechdel test?
li = []for i in dfNew['Bechdel Score']: if(i<3): li.append(0) else: li.append(1)dfNew['pass_test'] = lidfNew
Now, there is a dataframe called pass test, with a value of 1 for all the movies that pass the Bechdel test, and a value of 0 for the movies that don’t.
I will visualize this using Seaborn.
sns.countplot(x='pass_test',data=dfNew)
There are more movies that have passed the Bechdel test as opposed to the ones that haven’t, since the year 1967.
However, this difference is not as significant as I expected it to be. There still seems to be a very large number of movies that didn’t pass the test.
Now, I will take a look at how the Bechdel scores changes with time.
Has there been an improvement in the representation of women in the film industry? Are things still the same? Did they get worse?
To do this, I will use the Plotnine library.
from plotnine import *(ggplot(dfNew)+geom_point(aes('year',color=dfNew['Bechdel Score']),stat='count',show_legend=False)+geom_line(aes('year',color=dfNew['Bechdel Score']),stat='count',show_legend=False))
In the 1970s and 1980s, there were a few movies that passed the Bechdel test. During this time, there was no significant difference between movies that passed the test and movies that didn’t.
The years following the 1980s and 1990s saw a spike in the number of movies that passed the Bechdel test, and there is massive improvement going into the 21st century.
Now, I want to visualize the relationship between IMDB rating and the Bechdel scores. Are movies with higher Bechdel scores more likely to have higher IMDB ratings, or is it the other way round?
To do so, I will use a different dataset called movies.csv, and merge it with my existing data frame.
imdb = pd.read_csv('movies.csv')imdbNew = imdb[['title','rating']]dfNew = pd.merge(dfNew, imdbNew, how='left', left_on=['title'], right_on=['title'])dfNew.head()
The ‘rating’ column in the dataframe represents the IMBD movie ratings. This column has a few null values, and these rows will be dropped.
I will then create a new data frame with only the year, Bechdel score, and IMDB rating, so I can visualize the relationship between the three.
# Dropping rows with null values:dfNew = dfNew.dropna()dfNew = dfNew.drop('id',axis=1)# Creating a new dataframe with only year, Bechdel scores, and imdb rating:new = dfNew.groupby(['year','Bechdel Score']).agg({'rating':'mean'}).reset_index()new.head()
Perfect! Now, I will visualize this relationship:
# Plot year against IMDB rating and Bechdel Score:ggplot(new,aes(x='year',y='rating',color='Bechdel Score'))+ geom_point()+geom_smooth()+scale_y_continuous(name="imdb rating")+labs( colour='Bechdel Score' )
It appears as though movies that pass the Bechdel test have significantly lower IMDB ratings compared to movies that don’t, which was pretty surprising to me.
Now, I will try to visualize the relationship between the gender of the director and Bechdel scores. I assume that movies with female directors are more likely to have higher Bechdel scores, which I will try to plot here.
To do so, I will use a different movie dataset from Kaggle. I will then use a gender prediction library to predict the gender of the director from their name, and merge this with the previous dataframe.
import gender_guesser.detector as genlatest = pd.read_csv('movielatest.csv',encoding = "latin")dfLatest = latest[['name','director']]dfLatest.rename(columns={'name':'title'}, inplace=True)dfLatest = pd.merge(dfNew, dfLatest, how='left', left_on=['title'], right_on=['title'])dfLatest = dfLatest.dropna()dfLatest.head()
The newly created data frame now has an additional variable in it; director. I will now try to predict the gender of the director given their first name, and append it to the data frame.
# Predicting gender of director from first name:d = gen.Detector()genders = []firstNames = dfLatest['director'].str.split().str.get(0)for i in firstNames[0:len(firstNames)]: if d.get_gender(i) == 'male': genders.append('male') elif d.get_gender(i) == 'female': genders.append('female') else: genders.append('unknown')dfLatest['gender'] = gendersdfLatest = dfLatest[dfLatest['gender'] != 'unknown']# Encode the variable gender into a new dataframe:dfLatest['Male'] = dfLatest['gender'].map( {'male':1, 'female':0} )dfLatest.head()
The data frame has two additional variables; gender and male. Gender represents the gender of the director. The variable male has a value of 1 if the director is male, and 0 if she is female.
Now that I have this information, I will go ahead and visualize some more trends in the data.
I will create a count plot of the variable gender, to visualize the number of males to females in the dataset:
sns.countplot(x='gender',data=dfLatest)
It appears as though almost all the movies in the dataset have male directors. Again, this was something I expected, since Hollywood is known to employ a very small number of female directors.
Next, I will visualize the gender of the director with the Bechdel score, to see if movies with female directors have a higher score.
sns.countplot(x='Bechdel Score',hue='gender',data=dfLatest)
ggplot(aes(x = 'year', y = 'Bechdel Score',color='gender'), data = dfLatest)+geom_point()
Almost all the movies with female directors seem to pass the Bechdel test!
Next, I will take a look at the variable budget, to see if there is any kind of correlation between the budget of a movie and it’s Bechdel score.
dfLatest['budget']=latest['budget']ggplot(aes(x='year', y='budget',color='Bechdel Score'), data = dfLatest)+geom_point()+geom_smooth()
One thing that can be seen here is a significant increase in a movie’s budget with time. Also, movies that pass the Bechdel test seem to have a slightly higher budget than movies that score a zero, but there is no strong correlation that can be observed here.
Now, I will visualize the relationship between budget and gender of the director:
ggplot(aes(x = 'year', y = 'budget',color='gender'), data = dfLatest)+geom_point()+geom_smooth()
The gender of the director does not appear to have any kind of relationship or impact on the budget of a movie.
Visualizing the relationship between a movie’s budget, Bechdel score, and gender of director:
sns.violinplot(x='Bechdel Score',y='budget',hue='Male',data=dfLatest)
Next, I will visualize the genre of a movie and Bechdel scores, and any changes with time.
dfLatest['genre'] = latest['genre']ggplot(aes(x = 'year', y = 'genre',color='Bechdel Score'), data = dfLatest)+geom_point()
Finally, I will take a look at the movie grossings, along with year, Bechdel scores, and gender:
dfLatest['gross'] = latest['gross']# Movie grossing with Bechdel score and gender:sns.violinplot(x='Bechdel Score',y='gross',hue='Male',data=dfLatest)
# Movie grossing with year and gender:ggplot(aes(x = 'year', y = 'gross',color='gender'), data = dfLatest)+geom_point()
And that’s it! I managed to visualize relationships and answer all the data questions I set out to find answers to.
Some interesting data findings include:
Movies that fail the Bechdel test tend to have higher IMDB ratings.Over the years, there has been an increasing number of movies that pass the Bechdel test.Movies with female directors have higher Bechdel scores.There is no clear correlation between the budget or revenue of a movie and its Bechdel score.
Movies that fail the Bechdel test tend to have higher IMDB ratings.
Over the years, there has been an increasing number of movies that pass the Bechdel test.
Movies with female directors have higher Bechdel scores.
There is no clear correlation between the budget or revenue of a movie and its Bechdel score.
Of course, this analysis was only done with the data I gathered from three places, and might not represent the entire population of movies out there.
Furthermore, there may have been other variables present that affected the outcome of this analysis, and it might be a good idea to experiment with data from a couple of other places before coming to a conclusion.
Finally, I would like to mention that the Bechdel test is not necessarily the best benchmark to measure female representation in movies. It does not take into consideration how well written a female character is, neither does it measure meaningful depth of character.
However, it is one of the most well-known metrics used to expose gender bias and is the only test we have this kind of data on.
The datasets and complete code can be found here. | [
{
"code": null,
"e": 197,
"s": 171,
"text": "What is the Bechdel test?"
},
{
"code": null,
"e": 356,
"s": 197,
"text": "The Bechdel test is named after cartoonist Alison Bechdel, who introduced the idea in a comic strip in the year 1985. To pass the test, a story needs to have:"
},
{
"code": null,
"e": 375,
"s": 356,
"text": "At least two women"
},
{
"code": null,
"e": 412,
"s": 375,
"text": "The women need to talk to each other"
},
{
"code": null,
"e": 477,
"s": 412,
"text": "They need to talk to each other about something other than a man"
},
{
"code": null,
"e": 686,
"s": 477,
"text": "I first heard about the Bechdel test when watching Jane the Virgin, and it caught my interest. To me, it seemed like the standards of the test were too low, and should be ridiculously easy for movies to pass."
},
{
"code": null,
"e": 860,
"s": 686,
"text": "However, a simple Google search told me otherwise. Apparently, there were a large number of movies that did not fulfill the requirements to pass the Bechdel test, including:"
},
{
"code": null,
"e": 880,
"s": 860,
"text": "Slumdog Millionaire"
},
{
"code": null,
"e": 895,
"s": 880,
"text": "The Blind Side"
},
{
"code": null,
"e": 902,
"s": 895,
"text": "Tarzan"
},
{
"code": null,
"e": 921,
"s": 902,
"text": "The Imitation Game"
},
{
"code": null,
"e": 940,
"s": 921,
"text": "The Social Network"
},
{
"code": null,
"e": 1116,
"s": 940,
"text": "After doing some reading on the Bechdel test, I was struck with inspiration. I decided to conduct data analysis on movie datasets to check whether or not they passed the test!"
},
{
"code": null,
"e": 1134,
"s": 1116,
"text": "The Data Question"
},
{
"code": null,
"e": 1252,
"s": 1134,
"text": "My aim was to collect data from various different sources, and answer the following questions about the Bechdel test:"
},
{
"code": null,
"e": 1559,
"s": 1252,
"text": "Have the Bechdel scores of movies improved over the years?Do movies with higher IMDB ratings have higher Bechdel scores?Do movies with female directors have higher Bechdel scores?Does the budget of a movie have any impact on its Bechdel score?Do movies with higher Bechdel scores generate a larger revenue?"
},
{
"code": null,
"e": 1618,
"s": 1559,
"text": "Have the Bechdel scores of movies improved over the years?"
},
{
"code": null,
"e": 1681,
"s": 1618,
"text": "Do movies with higher IMDB ratings have higher Bechdel scores?"
},
{
"code": null,
"e": 1741,
"s": 1681,
"text": "Do movies with female directors have higher Bechdel scores?"
},
{
"code": null,
"e": 1806,
"s": 1741,
"text": "Does the budget of a movie have any impact on its Bechdel score?"
},
{
"code": null,
"e": 1870,
"s": 1806,
"text": "Do movies with higher Bechdel scores generate a larger revenue?"
},
{
"code": null,
"e": 1886,
"s": 1870,
"text": "Data Collection"
},
{
"code": null,
"e": 1983,
"s": 1886,
"text": "I collected data from three different sources: bechdeltest.com, Kaggle, and this movies dataset."
},
{
"code": null,
"e": 1997,
"s": 1983,
"text": "Data Analysis"
},
{
"code": null,
"e": 2063,
"s": 1997,
"text": "I will use Python to perform all data analysis and visualization."
},
{
"code": null,
"e": 2156,
"s": 2063,
"text": "First, I used data from bechdeltest.com, which was pretty easy to grab because of their API."
},
{
"code": null,
"e": 2267,
"s": 2156,
"text": "# importsimport urllib, jsonimport pandas as pddf = pd.read_json('http://bechdeltest.com/api/v1/getAllMovies')"
},
{
"code": null,
"e": 2322,
"s": 2267,
"text": "Now, I will take a look at the head of the data frame:"
},
{
"code": null,
"e": 2332,
"s": 2322,
"text": "df.head()"
},
{
"code": null,
"e": 2376,
"s": 2332,
"text": "There are five variables in the data frame:"
},
{
"code": null,
"e": 2543,
"s": 2376,
"text": "rating: Bechdel Score of the movie from 0 to 3. A Bechdel score lower than 3 means the movie failed the Bechdel test, and a Bechdel score of 3 means the movie passed."
},
{
"code": null,
"e": 2575,
"s": 2543,
"text": "imdbid: The movie’s IMDB number"
},
{
"code": null,
"e": 2594,
"s": 2575,
"text": "title: Movie title"
},
{
"code": null,
"e": 2614,
"s": 2594,
"text": "id: Unique movie ID"
},
{
"code": null,
"e": 2648,
"s": 2614,
"text": "year: Year the movie was released"
},
{
"code": null,
"e": 2802,
"s": 2648,
"text": "Taking a look at the column ‘year’, you can see that there are movies present from the 19th century, and a lot of those movies have a Bechdel score of 0."
},
{
"code": null,
"e": 2949,
"s": 2802,
"text": "I am going to create a new data frame with movies released after the year 1967, and will be using this new data frame for the rest of my analysis."
},
{
"code": null,
"e": 2978,
"s": 2949,
"text": "dfNew = df[df['year']>=1967]"
},
{
"code": null,
"e": 3015,
"s": 2978,
"text": "Taking a look at the new data frame:"
},
{
"code": null,
"e": 3028,
"s": 3015,
"text": "dfNew.head()"
},
{
"code": null,
"e": 3146,
"s": 3028,
"text": "I am now going to rename the column ‘rating’ to ‘Bechdel Score’, to make things clearer for the rest of the analysis."
},
{
"code": null,
"e": 3209,
"s": 3146,
"text": "dfNew.rename(columns={'rating':'Bechdel Score'}, inplace=True)"
},
{
"code": null,
"e": 3278,
"s": 3209,
"text": "Now, I am going to convert the ‘year’ column into a datetime object."
},
{
"code": null,
"e": 3337,
"s": 3278,
"text": "dfNew['year'] = pd.to_datetime(dfNew['year'], format='%Y')"
},
{
"code": null,
"e": 3402,
"s": 3337,
"text": "Next, I will change the Bechdel Scores to categorical variables."
},
{
"code": null,
"e": 3480,
"s": 3402,
"text": "dfNew['Bechdel Score'] = dfNew['Bechdel Score'].astype('category',copy=False)"
},
{
"code": null,
"e": 3557,
"s": 3480,
"text": "Finally, the data is prepared and can be used to do some data visualization."
},
{
"code": null,
"e": 3638,
"s": 3557,
"text": "I will first create a count plot using Seaborn, to visualize the Bechdel scores."
},
{
"code": null,
"e": 3682,
"s": 3638,
"text": "sns.countplot(x='Bechdel Score',data=dfNew)"
},
{
"code": null,
"e": 3785,
"s": 3682,
"text": "Most movies after the year 1967 seem to have higher Bechdel scores, but do they pass the Bechdel test?"
},
{
"code": null,
"e": 3914,
"s": 3785,
"text": "li = []for i in dfNew['Bechdel Score']: if(i<3): li.append(0) else: li.append(1)dfNew['pass_test'] = lidfNew"
},
{
"code": null,
"e": 4067,
"s": 3914,
"text": "Now, there is a dataframe called pass test, with a value of 1 for all the movies that pass the Bechdel test, and a value of 0 for the movies that don’t."
},
{
"code": null,
"e": 4104,
"s": 4067,
"text": "I will visualize this using Seaborn."
},
{
"code": null,
"e": 4144,
"s": 4104,
"text": "sns.countplot(x='pass_test',data=dfNew)"
},
{
"code": null,
"e": 4258,
"s": 4144,
"text": "There are more movies that have passed the Bechdel test as opposed to the ones that haven’t, since the year 1967."
},
{
"code": null,
"e": 4410,
"s": 4258,
"text": "However, this difference is not as significant as I expected it to be. There still seems to be a very large number of movies that didn’t pass the test."
},
{
"code": null,
"e": 4479,
"s": 4410,
"text": "Now, I will take a look at how the Bechdel scores changes with time."
},
{
"code": null,
"e": 4609,
"s": 4479,
"text": "Has there been an improvement in the representation of women in the film industry? Are things still the same? Did they get worse?"
},
{
"code": null,
"e": 4654,
"s": 4609,
"text": "To do this, I will use the Plotnine library."
},
{
"code": null,
"e": 4859,
"s": 4654,
"text": "from plotnine import *(ggplot(dfNew)+geom_point(aes('year',color=dfNew['Bechdel Score']),stat='count',show_legend=False)+geom_line(aes('year',color=dfNew['Bechdel Score']),stat='count',show_legend=False))"
},
{
"code": null,
"e": 5051,
"s": 4859,
"text": "In the 1970s and 1980s, there were a few movies that passed the Bechdel test. During this time, there was no significant difference between movies that passed the test and movies that didn’t."
},
{
"code": null,
"e": 5219,
"s": 5051,
"text": "The years following the 1980s and 1990s saw a spike in the number of movies that passed the Bechdel test, and there is massive improvement going into the 21st century."
},
{
"code": null,
"e": 5414,
"s": 5219,
"text": "Now, I want to visualize the relationship between IMDB rating and the Bechdel scores. Are movies with higher Bechdel scores more likely to have higher IMDB ratings, or is it the other way round?"
},
{
"code": null,
"e": 5516,
"s": 5414,
"text": "To do so, I will use a different dataset called movies.csv, and merge it with my existing data frame."
},
{
"code": null,
"e": 5678,
"s": 5516,
"text": "imdb = pd.read_csv('movies.csv')imdbNew = imdb[['title','rating']]dfNew = pd.merge(dfNew, imdbNew, how='left', left_on=['title'], right_on=['title'])dfNew.head()"
},
{
"code": null,
"e": 5817,
"s": 5678,
"text": "The ‘rating’ column in the dataframe represents the IMBD movie ratings. This column has a few null values, and these rows will be dropped."
},
{
"code": null,
"e": 5960,
"s": 5817,
"text": "I will then create a new data frame with only the year, Bechdel score, and IMDB rating, so I can visualize the relationship between the three."
},
{
"code": null,
"e": 6214,
"s": 5960,
"text": "# Dropping rows with null values:dfNew = dfNew.dropna()dfNew = dfNew.drop('id',axis=1)# Creating a new dataframe with only year, Bechdel scores, and imdb rating:new = dfNew.groupby(['year','Bechdel Score']).agg({'rating':'mean'}).reset_index()new.head()"
},
{
"code": null,
"e": 6264,
"s": 6214,
"text": "Perfect! Now, I will visualize this relationship:"
},
{
"code": null,
"e": 6471,
"s": 6264,
"text": "# Plot year against IMDB rating and Bechdel Score:ggplot(new,aes(x='year',y='rating',color='Bechdel Score'))+ geom_point()+geom_smooth()+scale_y_continuous(name=\"imdb rating\")+labs( colour='Bechdel Score' )"
},
{
"code": null,
"e": 6630,
"s": 6471,
"text": "It appears as though movies that pass the Bechdel test have significantly lower IMDB ratings compared to movies that don’t, which was pretty surprising to me."
},
{
"code": null,
"e": 6852,
"s": 6630,
"text": "Now, I will try to visualize the relationship between the gender of the director and Bechdel scores. I assume that movies with female directors are more likely to have higher Bechdel scores, which I will try to plot here."
},
{
"code": null,
"e": 7055,
"s": 6852,
"text": "To do so, I will use a different movie dataset from Kaggle. I will then use a gender prediction library to predict the gender of the director from their name, and merge this with the previous dataframe."
},
{
"code": null,
"e": 7374,
"s": 7055,
"text": "import gender_guesser.detector as genlatest = pd.read_csv('movielatest.csv',encoding = \"latin\")dfLatest = latest[['name','director']]dfLatest.rename(columns={'name':'title'}, inplace=True)dfLatest = pd.merge(dfNew, dfLatest, how='left', left_on=['title'], right_on=['title'])dfLatest = dfLatest.dropna()dfLatest.head()"
},
{
"code": null,
"e": 7561,
"s": 7374,
"text": "The newly created data frame now has an additional variable in it; director. I will now try to predict the gender of the director given their first name, and append it to the data frame."
},
{
"code": null,
"e": 8121,
"s": 7561,
"text": "# Predicting gender of director from first name:d = gen.Detector()genders = []firstNames = dfLatest['director'].str.split().str.get(0)for i in firstNames[0:len(firstNames)]: if d.get_gender(i) == 'male': genders.append('male') elif d.get_gender(i) == 'female': genders.append('female') else: genders.append('unknown')dfLatest['gender'] = gendersdfLatest = dfLatest[dfLatest['gender'] != 'unknown']# Encode the variable gender into a new dataframe:dfLatest['Male'] = dfLatest['gender'].map( {'male':1, 'female':0} )dfLatest.head()"
},
{
"code": null,
"e": 8313,
"s": 8121,
"text": "The data frame has two additional variables; gender and male. Gender represents the gender of the director. The variable male has a value of 1 if the director is male, and 0 if she is female."
},
{
"code": null,
"e": 8407,
"s": 8313,
"text": "Now that I have this information, I will go ahead and visualize some more trends in the data."
},
{
"code": null,
"e": 8518,
"s": 8407,
"text": "I will create a count plot of the variable gender, to visualize the number of males to females in the dataset:"
},
{
"code": null,
"e": 8558,
"s": 8518,
"text": "sns.countplot(x='gender',data=dfLatest)"
},
{
"code": null,
"e": 8751,
"s": 8558,
"text": "It appears as though almost all the movies in the dataset have male directors. Again, this was something I expected, since Hollywood is known to employ a very small number of female directors."
},
{
"code": null,
"e": 8885,
"s": 8751,
"text": "Next, I will visualize the gender of the director with the Bechdel score, to see if movies with female directors have a higher score."
},
{
"code": null,
"e": 8945,
"s": 8885,
"text": "sns.countplot(x='Bechdel Score',hue='gender',data=dfLatest)"
},
{
"code": null,
"e": 9035,
"s": 8945,
"text": "ggplot(aes(x = 'year', y = 'Bechdel Score',color='gender'), data = dfLatest)+geom_point()"
},
{
"code": null,
"e": 9110,
"s": 9035,
"text": "Almost all the movies with female directors seem to pass the Bechdel test!"
},
{
"code": null,
"e": 9256,
"s": 9110,
"text": "Next, I will take a look at the variable budget, to see if there is any kind of correlation between the budget of a movie and it’s Bechdel score."
},
{
"code": null,
"e": 9391,
"s": 9256,
"text": "dfLatest['budget']=latest['budget']ggplot(aes(x='year', y='budget',color='Bechdel Score'), data = dfLatest)+geom_point()+geom_smooth()"
},
{
"code": null,
"e": 9651,
"s": 9391,
"text": "One thing that can be seen here is a significant increase in a movie’s budget with time. Also, movies that pass the Bechdel test seem to have a slightly higher budget than movies that score a zero, but there is no strong correlation that can be observed here."
},
{
"code": null,
"e": 9733,
"s": 9651,
"text": "Now, I will visualize the relationship between budget and gender of the director:"
},
{
"code": null,
"e": 9830,
"s": 9733,
"text": "ggplot(aes(x = 'year', y = 'budget',color='gender'), data = dfLatest)+geom_point()+geom_smooth()"
},
{
"code": null,
"e": 9942,
"s": 9830,
"text": "The gender of the director does not appear to have any kind of relationship or impact on the budget of a movie."
},
{
"code": null,
"e": 10036,
"s": 9942,
"text": "Visualizing the relationship between a movie’s budget, Bechdel score, and gender of director:"
},
{
"code": null,
"e": 10106,
"s": 10036,
"text": "sns.violinplot(x='Bechdel Score',y='budget',hue='Male',data=dfLatest)"
},
{
"code": null,
"e": 10197,
"s": 10106,
"text": "Next, I will visualize the genre of a movie and Bechdel scores, and any changes with time."
},
{
"code": null,
"e": 10321,
"s": 10197,
"text": "dfLatest['genre'] = latest['genre']ggplot(aes(x = 'year', y = 'genre',color='Bechdel Score'), data = dfLatest)+geom_point()"
},
{
"code": null,
"e": 10418,
"s": 10321,
"text": "Finally, I will take a look at the movie grossings, along with year, Bechdel scores, and gender:"
},
{
"code": null,
"e": 10569,
"s": 10418,
"text": "dfLatest['gross'] = latest['gross']# Movie grossing with Bechdel score and gender:sns.violinplot(x='Bechdel Score',y='gross',hue='Male',data=dfLatest)"
},
{
"code": null,
"e": 10689,
"s": 10569,
"text": "# Movie grossing with year and gender:ggplot(aes(x = 'year', y = 'gross',color='gender'), data = dfLatest)+geom_point()"
},
{
"code": null,
"e": 10805,
"s": 10689,
"text": "And that’s it! I managed to visualize relationships and answer all the data questions I set out to find answers to."
},
{
"code": null,
"e": 10845,
"s": 10805,
"text": "Some interesting data findings include:"
},
{
"code": null,
"e": 11151,
"s": 10845,
"text": "Movies that fail the Bechdel test tend to have higher IMDB ratings.Over the years, there has been an increasing number of movies that pass the Bechdel test.Movies with female directors have higher Bechdel scores.There is no clear correlation between the budget or revenue of a movie and its Bechdel score."
},
{
"code": null,
"e": 11219,
"s": 11151,
"text": "Movies that fail the Bechdel test tend to have higher IMDB ratings."
},
{
"code": null,
"e": 11309,
"s": 11219,
"text": "Over the years, there has been an increasing number of movies that pass the Bechdel test."
},
{
"code": null,
"e": 11366,
"s": 11309,
"text": "Movies with female directors have higher Bechdel scores."
},
{
"code": null,
"e": 11460,
"s": 11366,
"text": "There is no clear correlation between the budget or revenue of a movie and its Bechdel score."
},
{
"code": null,
"e": 11610,
"s": 11460,
"text": "Of course, this analysis was only done with the data I gathered from three places, and might not represent the entire population of movies out there."
},
{
"code": null,
"e": 11824,
"s": 11610,
"text": "Furthermore, there may have been other variables present that affected the outcome of this analysis, and it might be a good idea to experiment with data from a couple of other places before coming to a conclusion."
},
{
"code": null,
"e": 12092,
"s": 11824,
"text": "Finally, I would like to mention that the Bechdel test is not necessarily the best benchmark to measure female representation in movies. It does not take into consideration how well written a female character is, neither does it measure meaningful depth of character."
},
{
"code": null,
"e": 12220,
"s": 12092,
"text": "However, it is one of the most well-known metrics used to expose gender bias and is the only test we have this kind of data on."
}
] |
PL/SQL - Records | In this chapter, we will discuss Records in PL/SQL. A record is a data structure that can hold data items of different kinds. Records consist of different fields, similar to a row of a database table.
For example, you want to keep track of your books in a library. You might want to track the following attributes about each book, such as Title, Author, Subject, Book ID. A record containing a field for each of these items allows treating a BOOK as a logical unit and allows you to organize and represent its information in a better way.
PL/SQL can handle the following types of records −
Table-based
Cursor-based records
User-defined records
The %ROWTYPE attribute enables a programmer to create table-based and cursorbased records.
The following example illustrates the concept of table-based records. We will be using the CUSTOMERS table we had created and used in the previous chapters −
DECLARE
customer_rec customers%rowtype;
BEGIN
SELECT * into customer_rec
FROM customers
WHERE id = 5;
dbms_output.put_line('Customer ID: ' || customer_rec.id);
dbms_output.put_line('Customer Name: ' || customer_rec.name);
dbms_output.put_line('Customer Address: ' || customer_rec.address);
dbms_output.put_line('Customer Salary: ' || customer_rec.salary);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Customer ID: 5
Customer Name: Hardik
Customer Address: Bhopal
Customer Salary: 9000
PL/SQL procedure successfully completed.
The following example illustrates the concept of cursor-based records. We will be using the CUSTOMERS table we had created and used in the previous chapters −
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal
PL/SQL procedure successfully completed.
PL/SQL provides a user-defined record type that allows you to define the different record structures. These records consist of different fields. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −
Title
Author
Subject
Book ID
The record type is defined as −
TYPE
type_name IS RECORD
( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION],
field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION],
...
field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION);
record-name type_name;
The Book record is declared in the following way −
DECLARE
TYPE books IS RECORD
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
To access any field of a record, we use the dot (.) operator. The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is an example to explain the usage of record −
DECLARE
type books is record
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
BEGIN
-- Book 1 specification
book1.title := 'C Programming';
book1.author := 'Nuha Ali ';
book1.subject := 'C Programming Tutorial';
book1.book_id := 6495407;
-- Book 2 specification
book2.title := 'Telecom Billing';
book2.author := 'Zara Ali';
book2.subject := 'Telecom Billing Tutorial';
book2.book_id := 6495700;
-- Print book 1 record
dbms_output.put_line('Book 1 title : '|| book1.title);
dbms_output.put_line('Book 1 author : '|| book1.author);
dbms_output.put_line('Book 1 subject : '|| book1.subject);
dbms_output.put_line('Book 1 book_id : ' || book1.book_id);
-- Print book 2 record
dbms_output.put_line('Book 2 title : '|| book2.title);
dbms_output.put_line('Book 2 author : '|| book2.author);
dbms_output.put_line('Book 2 subject : '|| book2.subject);
dbms_output.put_line('Book 2 book_id : '|| book2.book_id);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Book 1 title : C Programming
Book 1 author : Nuha Ali
Book 1 subject : C Programming Tutorial
Book 1 book_id : 6495407
Book 2 title : Telecom Billing
Book 2 author : Zara Ali
Book 2 subject : Telecom Billing Tutorial
Book 2 book_id : 6495700
PL/SQL procedure successfully completed.
You can pass a record as a subprogram parameter just as you pass any other variable. You can also access the record fields in the same way as you accessed in the above example −
DECLARE
type books is record
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
PROCEDURE printbook (book books) IS
BEGIN
dbms_output.put_line ('Book title : ' || book.title);
dbms_output.put_line('Book author : ' || book.author);
dbms_output.put_line( 'Book subject : ' || book.subject);
dbms_output.put_line( 'Book book_id : ' || book.book_id);
END;
BEGIN
-- Book 1 specification
book1.title := 'C Programming';
book1.author := 'Nuha Ali ';
book1.subject := 'C Programming Tutorial';
book1.book_id := 6495407;
-- Book 2 specification
book2.title := 'Telecom Billing';
book2.author := 'Zara Ali';
book2.subject := 'Telecom Billing Tutorial';
book2.book_id := 6495700;
-- Use procedure to print book info
printbook(book1);
printbook(book2);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Book title : C Programming
Book author : Nuha Ali
Book subject : C Programming Tutorial
Book book_id : 6495407
Book title : Telecom Billing
Book author : Zara Ali
Book subject : Telecom Billing Tutorial
Book book_id : 6495700
PL/SQL procedure successfully completed.
Print
Add Notes
Bookmark this page | [
{
"code": null,
"e": 2266,
"s": 2065,
"text": "In this chapter, we will discuss Records in PL/SQL. A record is a data structure that can hold data items of different kinds. Records consist of different fields, similar to a row of a database table."
},
{
"code": null,
"e": 2604,
"s": 2266,
"text": "For example, you want to keep track of your books in a library. You might want to track the following attributes about each book, such as Title, Author, Subject, Book ID. A record containing a field for each of these items allows treating a BOOK as a logical unit and allows you to organize and represent its information in a better way."
},
{
"code": null,
"e": 2655,
"s": 2604,
"text": "PL/SQL can handle the following types of records −"
},
{
"code": null,
"e": 2667,
"s": 2655,
"text": "Table-based"
},
{
"code": null,
"e": 2688,
"s": 2667,
"text": "Cursor-based records"
},
{
"code": null,
"e": 2709,
"s": 2688,
"text": "User-defined records"
},
{
"code": null,
"e": 2800,
"s": 2709,
"text": "The %ROWTYPE attribute enables a programmer to create table-based and cursorbased records."
},
{
"code": null,
"e": 2958,
"s": 2800,
"text": "The following example illustrates the concept of table-based records. We will be using the CUSTOMERS table we had created and used in the previous chapters −"
},
{
"code": null,
"e": 3357,
"s": 2958,
"text": "DECLARE \n customer_rec customers%rowtype; \nBEGIN \n SELECT * into customer_rec \n FROM customers \n WHERE id = 5; \n dbms_output.put_line('Customer ID: ' || customer_rec.id); \n dbms_output.put_line('Customer Name: ' || customer_rec.name); \n dbms_output.put_line('Customer Address: ' || customer_rec.address); \n dbms_output.put_line('Customer Salary: ' || customer_rec.salary); \nEND; \n/"
},
{
"code": null,
"e": 3443,
"s": 3357,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 3575,
"s": 3443,
"text": "Customer ID: 5 \nCustomer Name: Hardik \nCustomer Address: Bhopal \nCustomer Salary: 9000 \n \nPL/SQL procedure successfully completed.\n"
},
{
"code": null,
"e": 3734,
"s": 3575,
"text": "The following example illustrates the concept of cursor-based records. We will be using the CUSTOMERS table we had created and used in the previous chapters −"
},
{
"code": null,
"e": 4085,
"s": 3734,
"text": "DECLARE \n CURSOR customer_cur is \n SELECT id, name, address \n FROM customers; \n customer_rec customer_cur%rowtype; \nBEGIN \n OPEN customer_cur; \n LOOP \n FETCH customer_cur into customer_rec; \n EXIT WHEN customer_cur%notfound; \n DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name); \n END LOOP; \nEND; \n/"
},
{
"code": null,
"e": 4171,
"s": 4085,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 4278,
"s": 4171,
"text": "1 Ramesh \n2 Khilan \n3 kaushik \n4 Chaitali \n5 Hardik \n6 Komal \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 4549,
"s": 4278,
"text": "PL/SQL provides a user-defined record type that allows you to define the different record structures. These records consist of different fields. Suppose you want to keep track of your books in a library. You might want to track the following attributes about each book −"
},
{
"code": null,
"e": 4555,
"s": 4549,
"text": "Title"
},
{
"code": null,
"e": 4562,
"s": 4555,
"text": "Author"
},
{
"code": null,
"e": 4570,
"s": 4562,
"text": "Subject"
},
{
"code": null,
"e": 4578,
"s": 4570,
"text": "Book ID"
},
{
"code": null,
"e": 4610,
"s": 4578,
"text": "The record type is defined as −"
},
{
"code": null,
"e": 4868,
"s": 4610,
"text": "TYPE \ntype_name IS RECORD \n ( field_name1 datatype1 [NOT NULL] [:= DEFAULT EXPRESSION], \n field_name2 datatype2 [NOT NULL] [:= DEFAULT EXPRESSION], \n ... \n field_nameN datatypeN [NOT NULL] [:= DEFAULT EXPRESSION); \nrecord-name type_name;\n"
},
{
"code": null,
"e": 4919,
"s": 4868,
"text": "The Book record is declared in the following way −"
},
{
"code": null,
"e": 5074,
"s": 4919,
"text": "DECLARE \nTYPE books IS RECORD \n(title varchar(50), \n author varchar(50), \n subject varchar(100), \n book_id number); \nbook1 books; \nbook2 books; "
},
{
"code": null,
"e": 5312,
"s": 5074,
"text": "To access any field of a record, we use the dot (.) operator. The member access operator is coded as a period between the record variable name and the field that we wish to access. Following is an example to explain the usage of record −"
},
{
"code": null,
"e": 6410,
"s": 5312,
"text": "DECLARE \n type books is record \n (title varchar(50), \n author varchar(50), \n subject varchar(100), \n book_id number); \n book1 books; \n book2 books; \nBEGIN \n -- Book 1 specification \n book1.title := 'C Programming'; \n book1.author := 'Nuha Ali '; \n book1.subject := 'C Programming Tutorial'; \n book1.book_id := 6495407; \n -- Book 2 specification \n book2.title := 'Telecom Billing'; \n book2.author := 'Zara Ali'; \n book2.subject := 'Telecom Billing Tutorial'; \n book2.book_id := 6495700; \n \n -- Print book 1 record \n dbms_output.put_line('Book 1 title : '|| book1.title); \n dbms_output.put_line('Book 1 author : '|| book1.author); \n dbms_output.put_line('Book 1 subject : '|| book1.subject); \n dbms_output.put_line('Book 1 book_id : ' || book1.book_id); \n \n -- Print book 2 record \n dbms_output.put_line('Book 2 title : '|| book2.title); \n dbms_output.put_line('Book 2 author : '|| book2.author); \n dbms_output.put_line('Book 2 subject : '|| book2.subject); \n dbms_output.put_line('Book 2 book_id : '|| book2.book_id); \nEND; \n/"
},
{
"code": null,
"e": 6496,
"s": 6410,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 6791,
"s": 6496,
"text": "Book 1 title : C Programming \nBook 1 author : Nuha Ali \nBook 1 subject : C Programming Tutorial \nBook 1 book_id : 6495407 \nBook 2 title : Telecom Billing \nBook 2 author : Zara Ali \nBook 2 subject : Telecom Billing Tutorial \nBook 2 book_id : 6495700 \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 6969,
"s": 6791,
"text": "You can pass a record as a subprogram parameter just as you pass any other variable. You can also access the record fields in the same way as you accessed in the above example −"
},
{
"code": null,
"e": 7910,
"s": 6969,
"text": "DECLARE \n type books is record \n (title varchar(50), \n author varchar(50), \n subject varchar(100), \n book_id number); \n book1 books; \n book2 books; \nPROCEDURE printbook (book books) IS \nBEGIN \n dbms_output.put_line ('Book title : ' || book.title); \n dbms_output.put_line('Book author : ' || book.author); \n dbms_output.put_line( 'Book subject : ' || book.subject); \n dbms_output.put_line( 'Book book_id : ' || book.book_id); \nEND; \n \nBEGIN \n -- Book 1 specification \n book1.title := 'C Programming'; \n book1.author := 'Nuha Ali '; \n book1.subject := 'C Programming Tutorial'; \n book1.book_id := 6495407;\n \n -- Book 2 specification \n book2.title := 'Telecom Billing'; \n book2.author := 'Zara Ali'; \n book2.subject := 'Telecom Billing Tutorial'; \n book2.book_id := 6495700; \n \n -- Use procedure to print book info \n printbook(book1); \n printbook(book2); \nEND; \n/ "
},
{
"code": null,
"e": 7996,
"s": 7910,
"text": "When the above code is executed at the SQL prompt, it produces the following result −"
},
{
"code": null,
"e": 8278,
"s": 7996,
"text": "Book title : C Programming \nBook author : Nuha Ali \nBook subject : C Programming Tutorial \nBook book_id : 6495407 \nBook title : Telecom Billing \nBook author : Zara Ali \nBook subject : Telecom Billing Tutorial \nBook book_id : 6495700 \n\nPL/SQL procedure successfully completed. \n"
},
{
"code": null,
"e": 8285,
"s": 8278,
"text": " Print"
},
{
"code": null,
"e": 8296,
"s": 8285,
"text": " Add Notes"
}
] |
How can I create a dropdown menu from a List in Tkinter? | Let us suppose we want to create a dropdown menu of a list in an application using tkinter. In this case, we can use the Tkinter OptionMenu(win, menu_to_set, options) function.
First, we will instantiate an object of StringVar(), then we will set the initial value of the dropdown menu. We will create the dropdown menu by creating an object of OptionMenu and passing the value of window, menu object, and options which are to be displayed.
#Import the required libraries
from tkinter import *
#Create an instance of tkinter frame
win= Tk()
#Define the size of window or frame
win.geometry("715x250")
#Set the Menu initially
menu= StringVar()
menu.set("Select Any Language")
#Create a dropdown Menu
drop= OptionMenu(win, menu,"C++", "Java","Python","JavaScript","Rust","GoLang")
drop.pack()
win.mainloop()
In the output window, you can select an option by clicking over “Select Any Language” and it will show a list in the dropdown menu. | [
{
"code": null,
"e": 1239,
"s": 1062,
"text": "Let us suppose we want to create a dropdown menu of a list in an application using tkinter. In this case, we can use the Tkinter OptionMenu(win, menu_to_set, options) function."
},
{
"code": null,
"e": 1503,
"s": 1239,
"text": "First, we will instantiate an object of StringVar(), then we will set the initial value of the dropdown menu. We will create the dropdown menu by creating an object of OptionMenu and passing the value of window, menu object, and options which are to be displayed."
},
{
"code": null,
"e": 1873,
"s": 1503,
"text": "#Import the required libraries\nfrom tkinter import *\n\n#Create an instance of tkinter frame\nwin= Tk()\n\n#Define the size of window or frame\nwin.geometry(\"715x250\")\n\n#Set the Menu initially\nmenu= StringVar()\nmenu.set(\"Select Any Language\")\n\n#Create a dropdown Menu\ndrop= OptionMenu(win, menu,\"C++\", \"Java\",\"Python\",\"JavaScript\",\"Rust\",\"GoLang\")\ndrop.pack()\n\nwin.mainloop()"
},
{
"code": null,
"e": 2005,
"s": 1873,
"text": "In the output window, you can select an option by clicking over “Select Any Language” and it will show a list in the dropdown menu."
}
] |
Collapsible Pane in Tkinter | Python | 07 Jul, 2022
A collapsible pane, as the name suggests, is a pane which can be collapsed. User can expand pane so that they can perform some task and when task is completed, pane can be collapsed. In Tkinter, Collapsible pane is a container with an embedded button-like control which is used to expand or collapse this container.Prerequisites:
Frame Class
Checkbutton Class
Styling in widgets
configure() method
CollapsiblePane class – CollapsiblePane widget is used to store any other widgets inside of it. It can be toggled on or off, so widgets inside of it aren’t always shown.
Parameters: parent = The parent of the widget. expanded_text = The text shown on the Button when the pane is open. collapsed_text = The text shown on the Button when the pane is closed.Functions: _activate() = Checks the value of variable and shows or hides the Frame. toggle() = Switches the LabelFrame to the opposite state.Widgets: self_button = The Button that toggles the Frame. frame = The Frame that holds the widget. _separator = The Separator.
Python3
# Implementation of Collapsible Pane container # importing tkinter and ttk modulesimport tkinter as tkfrom tkinter import ttk class CollapsiblePane(ttk.Frame): """ -----USAGE----- collapsiblePane = CollapsiblePane(parent, expanded_text =[string], collapsed_text =[string]) collapsiblePane.pack() button = Button(collapsiblePane.frame).pack() """ def __init__(self, parent, expanded_text ="Collapse <<", collapsed_text ="Expand >>"): ttk.Frame.__init__(self, parent) # These are the class variable # see a underscore in expanded_text and _collapsed_text # this means these are private to class self.parent = parent self._expanded_text = expanded_text self._collapsed_text = collapsed_text # Here weight implies that it can grow it's # size if extra space is available # default weight is 0 self.columnconfigure(1, weight = 1) # Tkinter variable storing integer value self._variable = tk.IntVar() # Checkbutton is created but will behave as Button # cause in style, Button is passed # main reason to do this is Button do not support # variable option but checkbutton do self._button = ttk.Checkbutton(self, variable = self._variable, command = self._activate, style ="TButton") self._button.grid(row = 0, column = 0) # This wil create a separator # A separator is a line, we can also set thickness self._separator = ttk.Separator(self, orient ="horizontal") self._separator.grid(row = 0, column = 1, sticky ="we") self.frame = ttk.Frame(self) # This will call activate function of class self._activate() def _activate(self): if not self._variable.get(): # As soon as button is pressed it removes this widget # but is not destroyed means can be displayed again self.frame.grid_forget() # This will change the text of the checkbutton self._button.configure(text = self._collapsed_text) elif self._variable.get(): # increasing the frame area so new widgets # could reside in this container self.frame.grid(row = 1, column = 0, columnspan = 2) self._button.configure(text = self._expanded_text) def toggle(self): """Switches the label frame to the opposite state.""" self._variable.set(not self._variable.get()) self._activate()
Program to demonstrate use of CollapsiblePane –
Python3
# Importing tkinter and ttk modulesfrom tkinter import * from tkinter.ttk import * # Importing Collapsible Pane class that we have# created in separate filefrom collapsiblepane import CollapsiblePane as cp # Making root window or parent windowroot = Tk()root.geometry('200x200') # Creating Object of Collapsible Pane Container# If we do not pass these strings in# parameter the default strings will appear# on button that were, expand >>, collapse <<cpane = cp(root, 'Expanded', 'Collapsed')cpane.grid(row = 0, column = 0) # Button and checkbutton, these will# appear in collapsible pane containerb1 = Button(cpane.frame, text ="GFG").grid( row = 1, column = 2, pady = 10) cb1 = Checkbutton(cpane.frame, text ="GFG").grid( row = 2, column = 3, pady = 10) mainloop()
Output:
nidhi_biet
sweetyty
surindertarika1234
surinderdawra388
Python-gui
Python-tkinter
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n07 Jul, 2022"
},
{
"code": null,
"e": 360,
"s": 28,
"text": "A collapsible pane, as the name suggests, is a pane which can be collapsed. User can expand pane so that they can perform some task and when task is completed, pane can be collapsed. In Tkinter, Collapsible pane is a container with an embedded button-like control which is used to expand or collapse this container.Prerequisites: "
},
{
"code": null,
"e": 428,
"s": 360,
"text": "Frame Class\nCheckbutton Class\nStyling in widgets\nconfigure() method"
},
{
"code": null,
"e": 600,
"s": 428,
"text": "CollapsiblePane class – CollapsiblePane widget is used to store any other widgets inside of it. It can be toggled on or off, so widgets inside of it aren’t always shown. "
},
{
"code": null,
"e": 1053,
"s": 600,
"text": "Parameters: parent = The parent of the widget. expanded_text = The text shown on the Button when the pane is open. collapsed_text = The text shown on the Button when the pane is closed.Functions: _activate() = Checks the value of variable and shows or hides the Frame. toggle() = Switches the LabelFrame to the opposite state.Widgets: self_button = The Button that toggles the Frame. frame = The Frame that holds the widget. _separator = The Separator."
},
{
"code": null,
"e": 1063,
"s": 1055,
"text": "Python3"
},
{
"code": "# Implementation of Collapsible Pane container # importing tkinter and ttk modulesimport tkinter as tkfrom tkinter import ttk class CollapsiblePane(ttk.Frame): \"\"\" -----USAGE----- collapsiblePane = CollapsiblePane(parent, expanded_text =[string], collapsed_text =[string]) collapsiblePane.pack() button = Button(collapsiblePane.frame).pack() \"\"\" def __init__(self, parent, expanded_text =\"Collapse <<\", collapsed_text =\"Expand >>\"): ttk.Frame.__init__(self, parent) # These are the class variable # see a underscore in expanded_text and _collapsed_text # this means these are private to class self.parent = parent self._expanded_text = expanded_text self._collapsed_text = collapsed_text # Here weight implies that it can grow it's # size if extra space is available # default weight is 0 self.columnconfigure(1, weight = 1) # Tkinter variable storing integer value self._variable = tk.IntVar() # Checkbutton is created but will behave as Button # cause in style, Button is passed # main reason to do this is Button do not support # variable option but checkbutton do self._button = ttk.Checkbutton(self, variable = self._variable, command = self._activate, style =\"TButton\") self._button.grid(row = 0, column = 0) # This wil create a separator # A separator is a line, we can also set thickness self._separator = ttk.Separator(self, orient =\"horizontal\") self._separator.grid(row = 0, column = 1, sticky =\"we\") self.frame = ttk.Frame(self) # This will call activate function of class self._activate() def _activate(self): if not self._variable.get(): # As soon as button is pressed it removes this widget # but is not destroyed means can be displayed again self.frame.grid_forget() # This will change the text of the checkbutton self._button.configure(text = self._collapsed_text) elif self._variable.get(): # increasing the frame area so new widgets # could reside in this container self.frame.grid(row = 1, column = 0, columnspan = 2) self._button.configure(text = self._expanded_text) def toggle(self): \"\"\"Switches the label frame to the opposite state.\"\"\" self._variable.set(not self._variable.get()) self._activate()",
"e": 3652,
"s": 1063,
"text": null
},
{
"code": null,
"e": 3704,
"s": 3652,
"text": " Program to demonstrate use of CollapsiblePane – "
},
{
"code": null,
"e": 3712,
"s": 3704,
"text": "Python3"
},
{
"code": "# Importing tkinter and ttk modulesfrom tkinter import * from tkinter.ttk import * # Importing Collapsible Pane class that we have# created in separate filefrom collapsiblepane import CollapsiblePane as cp # Making root window or parent windowroot = Tk()root.geometry('200x200') # Creating Object of Collapsible Pane Container# If we do not pass these strings in# parameter the default strings will appear# on button that were, expand >>, collapse <<cpane = cp(root, 'Expanded', 'Collapsed')cpane.grid(row = 0, column = 0) # Button and checkbutton, these will# appear in collapsible pane containerb1 = Button(cpane.frame, text =\"GFG\").grid( row = 1, column = 2, pady = 10) cb1 = Checkbutton(cpane.frame, text =\"GFG\").grid( row = 2, column = 3, pady = 10) mainloop()",
"e": 4506,
"s": 3712,
"text": null
},
{
"code": null,
"e": 4516,
"s": 4506,
"text": "Output: "
},
{
"code": null,
"e": 4531,
"s": 4520,
"text": "nidhi_biet"
},
{
"code": null,
"e": 4540,
"s": 4531,
"text": "sweetyty"
},
{
"code": null,
"e": 4559,
"s": 4540,
"text": "surindertarika1234"
},
{
"code": null,
"e": 4576,
"s": 4559,
"text": "surinderdawra388"
},
{
"code": null,
"e": 4587,
"s": 4576,
"text": "Python-gui"
},
{
"code": null,
"e": 4602,
"s": 4587,
"text": "Python-tkinter"
},
{
"code": null,
"e": 4609,
"s": 4602,
"text": "Python"
}
] |
Overlay Multiple Images in a Single ImageView in Android | 11 Aug, 2021
In Android, an image can be displayed inside an ImageView in the layout. ImageView accepts only a single image at a time as input. However, there can be a need to display two or more images in the same ImageView. Let us say, our application shows the status of airplane mode. When airplane mode is enabled, it must display the image of an airplane and when it is disabled, it must overlay the same image with something like a cross or block symbol. As ImageView accepts only a single input source, it is impossible to set two images as the source. So, in such a case, we will have to create a resource that consists of a list of images and set this resource as the source attribute of the ImageView. So, through this article, we will show you how you could create a resource containing multiple images and set it in the ImageView.
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project.
Step 2: Import images of your choice in the drawable folder
We imported two vector assets from the local clip art. Store them in the drawable folder.
drawable/ic_airplane
drawable/ic_block
Refer to this article: How to Add Image to Drawable Folder in Android Studio?
Step 3: Create a Drawable Resource File with root element as layer-list (layer.xml)
Create a drawable resource file inside the drawable folder with the root element as a layer list. Give it a name like a layer. The generated file has an extension XML.
Step 4: Add items (imported images) to the layer.xml
Add items in such a way that the next item overlaps the previous one.
XML
<?xml version="1.0" encoding="utf-8"?><layer-list xmlns:android="http://schemas.android.com/apk/res/android"> <!-- Any number of images of our choice --> <item android:drawable="@drawable/ic_airplane"/> <item android:drawable="@drawable/ic_block"/> </layer-list>
Step 5: Working with the activity_main.xml file
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add ImageView and a button in the layout file. ImageView will display the layer-list upon button click.
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <!-- ImageView to display multiple images --> <ImageView android:id="@+id/imageView" android:layout_width="300sp" android:layout_height="300sp" android:layout_centerInParent="true" android:background="#0f9d58"/> <!-- A button to load the images in the ImageView --> <Button android:id="@+id/button" android:layout_below="@id/imageView" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Overlay" android:layout_centerHorizontal="true"/> </RelativeLayout>
Step 6: Working with the MainActivity.kt file
Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail.
Kotlin
import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and Initializing // ImageView and Button from the layout val mImageView = findViewById<ImageView>(R.id.imageView) val mButton = findViewById<Button>(R.id.button) // When button is clicked mButton.setOnClickListener { // Set the drawable resource file // (layer-list of images) in the ImageView mImageView.setImageResource(R.drawable.layer) } }}
Output:
We can see that as we click on the overlay button, the ImageView is set with the two images, one overlapping the other.
Android
Kotlin
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here. | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n11 Aug, 2021"
},
{
"code": null,
"e": 859,
"s": 28,
"text": "In Android, an image can be displayed inside an ImageView in the layout. ImageView accepts only a single image at a time as input. However, there can be a need to display two or more images in the same ImageView. Let us say, our application shows the status of airplane mode. When airplane mode is enabled, it must display the image of an airplane and when it is disabled, it must overlay the same image with something like a cross or block symbol. As ImageView accepts only a single input source, it is impossible to set two images as the source. So, in such a case, we will have to create a resource that consists of a list of images and set this resource as the source attribute of the ImageView. So, through this article, we will show you how you could create a resource containing multiple images and set it in the ImageView."
},
{
"code": null,
"e": 906,
"s": 859,
"text": "Step 1: Create a New Project in Android Studio"
},
{
"code": null,
"e": 1145,
"s": 906,
"text": "To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. We demonstrated the application in Kotlin, so make sure you select Kotlin as the primary language while creating a New Project."
},
{
"code": null,
"e": 1205,
"s": 1145,
"text": "Step 2: Import images of your choice in the drawable folder"
},
{
"code": null,
"e": 1295,
"s": 1205,
"text": "We imported two vector assets from the local clip art. Store them in the drawable folder."
},
{
"code": null,
"e": 1316,
"s": 1295,
"text": "drawable/ic_airplane"
},
{
"code": null,
"e": 1334,
"s": 1316,
"text": "drawable/ic_block"
},
{
"code": null,
"e": 1412,
"s": 1334,
"text": "Refer to this article: How to Add Image to Drawable Folder in Android Studio?"
},
{
"code": null,
"e": 1496,
"s": 1412,
"text": "Step 3: Create a Drawable Resource File with root element as layer-list (layer.xml)"
},
{
"code": null,
"e": 1664,
"s": 1496,
"text": "Create a drawable resource file inside the drawable folder with the root element as a layer list. Give it a name like a layer. The generated file has an extension XML."
},
{
"code": null,
"e": 1717,
"s": 1664,
"text": "Step 4: Add items (imported images) to the layer.xml"
},
{
"code": null,
"e": 1787,
"s": 1717,
"text": "Add items in such a way that the next item overlaps the previous one."
},
{
"code": null,
"e": 1791,
"s": 1787,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><layer-list xmlns:android=\"http://schemas.android.com/apk/res/android\"> <!-- Any number of images of our choice --> <item android:drawable=\"@drawable/ic_airplane\"/> <item android:drawable=\"@drawable/ic_block\"/> </layer-list>",
"e": 2066,
"s": 1791,
"text": null
},
{
"code": null,
"e": 2114,
"s": 2066,
"text": "Step 5: Working with the activity_main.xml file"
},
{
"code": null,
"e": 2360,
"s": 2114,
"text": "Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Add ImageView and a button in the layout file. ImageView will display the layer-list upon button click."
},
{
"code": null,
"e": 2364,
"s": 2360,
"text": "XML"
},
{
"code": "<?xml version=\"1.0\" encoding=\"utf-8\"?><RelativeLayout xmlns:android=\"http://schemas.android.com/apk/res/android\" xmlns:app=\"http://schemas.android.com/apk/res-auto\" xmlns:tools=\"http://schemas.android.com/tools\" android:layout_width=\"match_parent\" android:layout_height=\"match_parent\" tools:context=\".MainActivity\"> <!-- ImageView to display multiple images --> <ImageView android:id=\"@+id/imageView\" android:layout_width=\"300sp\" android:layout_height=\"300sp\" android:layout_centerInParent=\"true\" android:background=\"#0f9d58\"/> <!-- A button to load the images in the ImageView --> <Button android:id=\"@+id/button\" android:layout_below=\"@id/imageView\" android:layout_width=\"wrap_content\" android:layout_height=\"wrap_content\" android:text=\"Overlay\" android:layout_centerHorizontal=\"true\"/> </RelativeLayout>",
"e": 3283,
"s": 2364,
"text": null
},
{
"code": null,
"e": 3329,
"s": 3283,
"text": "Step 6: Working with the MainActivity.kt file"
},
{
"code": null,
"e": 3515,
"s": 3329,
"text": "Go to the MainActivity.kt file and refer to the following code. Below is the code for the MainActivity.kt file. Comments are added inside the code to understand the code in more detail."
},
{
"code": null,
"e": 3522,
"s": 3515,
"text": "Kotlin"
},
{
"code": "import androidx.appcompat.app.AppCompatActivityimport android.os.Bundleimport android.widget.Buttonimport android.widget.ImageView class MainActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) // Declaring and Initializing // ImageView and Button from the layout val mImageView = findViewById<ImageView>(R.id.imageView) val mButton = findViewById<Button>(R.id.button) // When button is clicked mButton.setOnClickListener { // Set the drawable resource file // (layer-list of images) in the ImageView mImageView.setImageResource(R.drawable.layer) } }}",
"e": 4290,
"s": 3522,
"text": null
},
{
"code": null,
"e": 4298,
"s": 4290,
"text": "Output:"
},
{
"code": null,
"e": 4418,
"s": 4298,
"text": "We can see that as we click on the overlay button, the ImageView is set with the two images, one overlapping the other."
},
{
"code": null,
"e": 4426,
"s": 4418,
"text": "Android"
},
{
"code": null,
"e": 4433,
"s": 4426,
"text": "Kotlin"
},
{
"code": null,
"e": 4441,
"s": 4433,
"text": "Android"
}
] |
Why card images use data-src (not src) for image in Bootstrap 4 ? | 09 Jul, 2020
Bootstrap 4 card images use src in image tags to providing the location to be loaded in the given image tag and data-src to provide additional information that can be used by JavaScript for improving the users’ experience. For data-src and src tag we can conclude as follows:src:
If you want to load and display a particular image, then use .src to load that image URL.
data-src:
If you want a piece of metadata (on any tag) that can contain a URL, then use data-src or any data-xxx that you want to select.
The data-* attributes are used to store custom data private to the page or application.
The data-* attributes gives us the ability to embed custom data attributes on all HTML elements.
The data can then be used by JavaScript to create a more engaging user experience.
Syntax:
Using src attribute:<img id="img1" src="abc.jpg">
<script>
var url = document.getElementById("img1").src;
</script>
<img id="img1" src="abc.jpg">
<script>
var url = document.getElementById("img1").src;
</script>
Using data-src attribute:<img id="img1" src="xyz.jpg" data-src="abc.jpg
<script>
var ele = document.getElementById("img1");
// Switch the image to the URL specified in data-src
ele.src = ele.dataset.src;
</script>
<img id="img1" src="xyz.jpg" data-src="abc.jpg
<script>
var ele = document.getElementById("img1");
// Switch the image to the URL specified in data-src
ele.src = ele.dataset.src;
</script>
Below example illustrates the above concept:
Example: The below code can be seen how src attribute is used to provide a link to image and data-src can be used to provide additional information to JavaScript like here it was used to change the original src link for the image with one in the data-src attribute.
<!DOCTYPE html><html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="X-UA-Compatible" content="ie=edge" /> <title> Why card images use data-src (not src) for image in Bootstrap 4 ? </title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous" /> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"> </script> <style> h1 { color: green; } .second { float: right; margin: 20px; } .first { float: left; margin: 20px; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> </center> <div class="container"> <div class="card first" style="width: 18rem;"> <img class="card-img-top" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png" alt="Card image cap" /> <div class="card-body"> <h5 class="card-title">Courses</h5> <p class="card-text"> Attend the courses Increase the probability </p> <a href="#" class="btn btn-primary">Attend</a> </div> </div> <!-- It loaded with JavaScript to allow lazy loading of images --> <div class="card second" style="width: 18rem;"> <img id="img1" class="card-img-top" data-src="https://media.geeksforgeeks.org/wp-content/uploads/20200121112744/logo11.png" style="height:295px;" src="https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png" alt="Card image cap" /> <div class="card-body"> <h5 class="card-title">Interview</h5> <p class="card-text"> Prepare your self for the Interview </p> <a href="#" class="btn btn-primary">Attend</a> </div> </div> </div> <script> var ele = document.getElementById("img1"); // Switch the image to the URL // specified in data-src ele.src = ele.dataset.src; </script></body> </html>
Output:
Akanksha_Rai
Bootstrap-4
Bootstrap-Misc
Picked
Bootstrap
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to pass data into a bootstrap modal?
How to set Bootstrap Timepicker using datetimepicker library ?
How to Show Images on Click using HTML ?
How to Use Bootstrap with React?
Difference between Bootstrap 4 and Bootstrap 5
Installation of Node.js on Linux
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Difference between var, let and const keywords in JavaScript
How to insert spaces/tabs in text using HTML/CSS?
How to fetch data from an API in ReactJS ? | [
{
"code": null,
"e": 28,
"s": 0,
"text": "\n09 Jul, 2020"
},
{
"code": null,
"e": 308,
"s": 28,
"text": "Bootstrap 4 card images use src in image tags to providing the location to be loaded in the given image tag and data-src to provide additional information that can be used by JavaScript for improving the users’ experience. For data-src and src tag we can conclude as follows:src:"
},
{
"code": null,
"e": 398,
"s": 308,
"text": "If you want to load and display a particular image, then use .src to load that image URL."
},
{
"code": null,
"e": 408,
"s": 398,
"text": "data-src:"
},
{
"code": null,
"e": 536,
"s": 408,
"text": "If you want a piece of metadata (on any tag) that can contain a URL, then use data-src or any data-xxx that you want to select."
},
{
"code": null,
"e": 624,
"s": 536,
"text": "The data-* attributes are used to store custom data private to the page or application."
},
{
"code": null,
"e": 721,
"s": 624,
"text": "The data-* attributes gives us the ability to embed custom data attributes on all HTML elements."
},
{
"code": null,
"e": 804,
"s": 721,
"text": "The data can then be used by JavaScript to create a more engaging user experience."
},
{
"code": null,
"e": 812,
"s": 804,
"text": "Syntax:"
},
{
"code": null,
"e": 933,
"s": 812,
"text": "Using src attribute:<img id=\"img1\" src=\"abc.jpg\">\n\n<script>\n var url = document.getElementById(\"img1\").src;\n</script>"
},
{
"code": null,
"e": 1034,
"s": 933,
"text": "<img id=\"img1\" src=\"abc.jpg\">\n\n<script>\n var url = document.getElementById(\"img1\").src;\n</script>"
},
{
"code": null,
"e": 1262,
"s": 1034,
"text": "Using data-src attribute:<img id=\"img1\" src=\"xyz.jpg\" data-src=\"abc.jpg\n<script>\n var ele = document.getElementById(\"img1\");\n\n // Switch the image to the URL specified in data-src\n ele.src = ele.dataset.src;\n</script>\n"
},
{
"code": null,
"e": 1465,
"s": 1262,
"text": "<img id=\"img1\" src=\"xyz.jpg\" data-src=\"abc.jpg\n<script>\n var ele = document.getElementById(\"img1\");\n\n // Switch the image to the URL specified in data-src\n ele.src = ele.dataset.src;\n</script>\n"
},
{
"code": null,
"e": 1510,
"s": 1465,
"text": "Below example illustrates the above concept:"
},
{
"code": null,
"e": 1776,
"s": 1510,
"text": "Example: The below code can be seen how src attribute is used to provide a link to image and data-src can be used to provide additional information to JavaScript like here it was used to change the original src link for the image with one in the data-src attribute."
},
{
"code": "<!DOCTYPE html><html lang=\"en\"> <head> <meta charset=\"UTF-8\" /> <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\" /> <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\" /> <title> Why card images use data-src (not src) for image in Bootstrap 4 ? </title> <link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css\" integrity=\"sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO\" crossorigin=\"anonymous\" /> <script src=\"https://code.jquery.com/jquery-3.3.1.slim.min.js\" integrity=\"sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo\" crossorigin=\"anonymous\"></script> <script src=\"https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js\" integrity=\"sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49\" crossorigin=\"anonymous\"></script> <script src=\"https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js\" integrity=\"sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy\" crossorigin=\"anonymous\"> </script> <style> h1 { color: green; } .second { float: right; margin: 20px; } .first { float: left; margin: 20px; } </style></head> <body> <center> <h1>GeeksforGeeks</h1> <b>A Computer Science Portal for Geeks</b> </center> <div class=\"container\"> <div class=\"card first\" style=\"width: 18rem;\"> <img class=\"card-img-top\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\" alt=\"Card image cap\" /> <div class=\"card-body\"> <h5 class=\"card-title\">Courses</h5> <p class=\"card-text\"> Attend the courses Increase the probability </p> <a href=\"#\" class=\"btn btn-primary\">Attend</a> </div> </div> <!-- It loaded with JavaScript to allow lazy loading of images --> <div class=\"card second\" style=\"width: 18rem;\"> <img id=\"img1\" class=\"card-img-top\" data-src=\"https://media.geeksforgeeks.org/wp-content/uploads/20200121112744/logo11.png\" style=\"height:295px;\" src=\"https://media.geeksforgeeks.org/wp-content/uploads/20190506125816/avt.png\" alt=\"Card image cap\" /> <div class=\"card-body\"> <h5 class=\"card-title\">Interview</h5> <p class=\"card-text\"> Prepare your self for the Interview </p> <a href=\"#\" class=\"btn btn-primary\">Attend</a> </div> </div> </div> <script> var ele = document.getElementById(\"img1\"); // Switch the image to the URL // specified in data-src ele.src = ele.dataset.src; </script></body> </html>",
"e": 4952,
"s": 1776,
"text": null
},
{
"code": null,
"e": 4960,
"s": 4952,
"text": "Output:"
},
{
"code": null,
"e": 4973,
"s": 4960,
"text": "Akanksha_Rai"
},
{
"code": null,
"e": 4985,
"s": 4973,
"text": "Bootstrap-4"
},
{
"code": null,
"e": 5000,
"s": 4985,
"text": "Bootstrap-Misc"
},
{
"code": null,
"e": 5007,
"s": 5000,
"text": "Picked"
},
{
"code": null,
"e": 5017,
"s": 5007,
"text": "Bootstrap"
},
{
"code": null,
"e": 5034,
"s": 5017,
"text": "Web Technologies"
},
{
"code": null,
"e": 5061,
"s": 5034,
"text": "Web technologies Questions"
},
{
"code": null,
"e": 5159,
"s": 5061,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 5200,
"s": 5159,
"text": "How to pass data into a bootstrap modal?"
},
{
"code": null,
"e": 5263,
"s": 5200,
"text": "How to set Bootstrap Timepicker using datetimepicker library ?"
},
{
"code": null,
"e": 5304,
"s": 5263,
"text": "How to Show Images on Click using HTML ?"
},
{
"code": null,
"e": 5337,
"s": 5304,
"text": "How to Use Bootstrap with React?"
},
{
"code": null,
"e": 5384,
"s": 5337,
"text": "Difference between Bootstrap 4 and Bootstrap 5"
},
{
"code": null,
"e": 5417,
"s": 5384,
"text": "Installation of Node.js on Linux"
},
{
"code": null,
"e": 5479,
"s": 5417,
"text": "Top 10 Projects For Beginners To Practice HTML and CSS Skills"
},
{
"code": null,
"e": 5540,
"s": 5479,
"text": "Difference between var, let and const keywords in JavaScript"
},
{
"code": null,
"e": 5590,
"s": 5540,
"text": "How to insert spaces/tabs in text using HTML/CSS?"
}
] |
jQuery - jQuery.post() Method | The jQuery.post( url, [data], [callback], [type] ) method loads a page from the server using a POST HTTP request.
The method returns XMLHttpRequest object.
Here is the simple syntax to use this method −
$.post( url, [data], [callback], [type] )
Here is the description of all the parameters used by this method −
url − A string containing the URL to which the request is sent
url − A string containing the URL to which the request is sent
data − This optional parameter represents key/value pairs or the return value of the .serialize() function that will be sent to the server.
data − This optional parameter represents key/value pairs or the return value of the .serialize() function that will be sent to the server.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
callback − This optional parameter represents a function to be executed whenever the data is loaded successfully.
type − This optional parameter represents a type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".
type − This optional parameter represents a type of data to be returned to callback function: "xml", "html", "script", "json", "jsonp", or "text".
Assuming we have following PHP content in result.php file −
<?php
if( $_REQUEST["name"] ) {
$name = $_REQUEST['name'];
echo "Welcome ". $name;
}
?>
Following is a simple example a simple showing the usage of this method −
<html>
<head>
<title>The jQuery Example</title>
<script type = "text/javascript"
src = "https://www.tutorialspoint.com/jquery/jquery-3.6.0.js">
</script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#driver").click(function(event){
$.post(
"result.php",
{ name: "Zara" },
function(data) {
$('#stage').html(data);
}
);
});
});
</script>
</head>
<body>
<p>Click on the button to load result.html file −</p>
<div id = "stage" style = "background-color:cc0;">
STAGE
</div>
<input type = "button" id = "driver" value = "Load Data" />
</body>
</html>
This should produce following result −
Click on the button to load result.html file − | [
{
"code": null,
"e": 2903,
"s": 2789,
"text": "The jQuery.post( url, [data], [callback], [type] ) method loads a page from the server using a POST HTTP request."
},
{
"code": null,
"e": 2945,
"s": 2903,
"text": "The method returns XMLHttpRequest object."
},
{
"code": null,
"e": 2992,
"s": 2945,
"text": "Here is the simple syntax to use this method −"
},
{
"code": null,
"e": 3035,
"s": 2992,
"text": "$.post( url, [data], [callback], [type] )\n"
},
{
"code": null,
"e": 3103,
"s": 3035,
"text": "Here is the description of all the parameters used by this method −"
},
{
"code": null,
"e": 3166,
"s": 3103,
"text": "url − A string containing the URL to which the request is sent"
},
{
"code": null,
"e": 3229,
"s": 3166,
"text": "url − A string containing the URL to which the request is sent"
},
{
"code": null,
"e": 3369,
"s": 3229,
"text": "data − This optional parameter represents key/value pairs or the return value of the .serialize() function that will be sent to the server."
},
{
"code": null,
"e": 3509,
"s": 3369,
"text": "data − This optional parameter represents key/value pairs or the return value of the .serialize() function that will be sent to the server."
},
{
"code": null,
"e": 3623,
"s": 3509,
"text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully."
},
{
"code": null,
"e": 3737,
"s": 3623,
"text": "callback − This optional parameter represents a function to be executed whenever the data is loaded successfully."
},
{
"code": null,
"e": 3884,
"s": 3737,
"text": "type − This optional parameter represents a type of data to be returned to callback function: \"xml\", \"html\", \"script\", \"json\", \"jsonp\", or \"text\"."
},
{
"code": null,
"e": 4031,
"s": 3884,
"text": "type − This optional parameter represents a type of data to be returned to callback function: \"xml\", \"html\", \"script\", \"json\", \"jsonp\", or \"text\"."
},
{
"code": null,
"e": 4091,
"s": 4031,
"text": "Assuming we have following PHP content in result.php file −"
},
{
"code": null,
"e": 4187,
"s": 4091,
"text": "<?php\nif( $_REQUEST[\"name\"] ) {\n\n $name = $_REQUEST['name'];\n echo \"Welcome \". $name;\n}\n\n?>"
},
{
"code": null,
"e": 4261,
"s": 4187,
"text": "Following is a simple example a simple showing the usage of this method −"
},
{
"code": null,
"e": 5135,
"s": 4261,
"text": "<html>\n <head>\n <title>The jQuery Example</title>\n <script type = \"text/javascript\" \n src = \"https://www.tutorialspoint.com/jquery/jquery-3.6.0.js\">\n </script>\n\t\t\n <script type = \"text/javascript\" language = \"javascript\">\n $(document).ready(function() {\n\t\t\t\n $(\"#driver\").click(function(event){\n\t\t\t\t\n $.post( \n \"result.php\",\n { name: \"Zara\" },\n function(data) {\n $('#stage').html(data);\n }\n );\n\t\t\t\t\t\n });\n\t\t\t\t\n });\n </script>\n </head>\n\t\n <body>\n <p>Click on the button to load result.html file −</p>\n\t\t\n <div id = \"stage\" style = \"background-color:cc0;\">\n STAGE\n </div>\n\t\t\n <input type = \"button\" id = \"driver\" value = \"Load Data\" />\n </body>\n</html>"
},
{
"code": null,
"e": 5174,
"s": 5135,
"text": "This should produce following result −"
}
] |
PyQt5 - isChecked() method for Check Box - GeeksforGeeks | 22 Apr, 2020
isChecked method is used to know if the check box is checked or not. This method will return true if the check box is checked else it will return false. If we use this method after creating the check box it will always return False as by default check box is not checked.
Syntax : checkbox.isChecked()
Argument : It takes no argument.
Return : It return bool, true is it checked else false
Below is the implementation.
# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle("Python ") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box self.checkbox = QCheckBox('Check box', self) # setting geometry of check box self.checkbox.setGeometry(200, 150, 100, 30) # connecting it to function self.checkbox.stateChanged.connect(self.method) # checking if it checked check = self.checkbox.isChecked() # printing the check print(check) def method(self): # printing the checked status print(self.checkbox.isChecked()) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())
Output :
False
True
When we run the code False will be printed and after making check box checked it will print True.
Python-gui
Python-PyQt
Python
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
How to Install PIP on Windows ?
Check if element exists in list in Python
How To Convert Python Dictionary To JSON?
How to drop one or multiple columns in Pandas Dataframe
Python Classes and Objects
Python | os.path.join() method
Python | Get unique values from a list
Create a directory in Python
Defaultdict in Python
Python | Pandas dataframe.groupby() | [
{
"code": null,
"e": 25537,
"s": 25509,
"text": "\n22 Apr, 2020"
},
{
"code": null,
"e": 25809,
"s": 25537,
"text": "isChecked method is used to know if the check box is checked or not. This method will return true if the check box is checked else it will return false. If we use this method after creating the check box it will always return False as by default check box is not checked."
},
{
"code": null,
"e": 25839,
"s": 25809,
"text": "Syntax : checkbox.isChecked()"
},
{
"code": null,
"e": 25872,
"s": 25839,
"text": "Argument : It takes no argument."
},
{
"code": null,
"e": 25927,
"s": 25872,
"text": "Return : It return bool, true is it checked else false"
},
{
"code": null,
"e": 25956,
"s": 25927,
"text": "Below is the implementation."
},
{
"code": "# importing librariesfrom PyQt5.QtWidgets import * from PyQt5 import QtCore, QtGuifrom PyQt5.QtGui import * from PyQt5.QtCore import * import sys class Window(QMainWindow): def __init__(self): super().__init__() # setting title self.setWindowTitle(\"Python \") # setting geometry self.setGeometry(100, 100, 600, 400) # calling method self.UiComponents() # showing all the widgets self.show() # method for widgets def UiComponents(self): # creating the check-box self.checkbox = QCheckBox('Check box', self) # setting geometry of check box self.checkbox.setGeometry(200, 150, 100, 30) # connecting it to function self.checkbox.stateChanged.connect(self.method) # checking if it checked check = self.checkbox.isChecked() # printing the check print(check) def method(self): # printing the checked status print(self.checkbox.isChecked()) # create pyqt5 appApp = QApplication(sys.argv) # create the instance of our Windowwindow = Window() # start the appsys.exit(App.exec())",
"e": 27121,
"s": 25956,
"text": null
},
{
"code": null,
"e": 27130,
"s": 27121,
"text": "Output :"
},
{
"code": null,
"e": 27142,
"s": 27130,
"text": "False\nTrue\n"
},
{
"code": null,
"e": 27240,
"s": 27142,
"text": "When we run the code False will be printed and after making check box checked it will print True."
},
{
"code": null,
"e": 27251,
"s": 27240,
"text": "Python-gui"
},
{
"code": null,
"e": 27263,
"s": 27251,
"text": "Python-PyQt"
},
{
"code": null,
"e": 27270,
"s": 27263,
"text": "Python"
},
{
"code": null,
"e": 27368,
"s": 27270,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27400,
"s": 27368,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27442,
"s": 27400,
"text": "Check if element exists in list in Python"
},
{
"code": null,
"e": 27484,
"s": 27442,
"text": "How To Convert Python Dictionary To JSON?"
},
{
"code": null,
"e": 27540,
"s": 27484,
"text": "How to drop one or multiple columns in Pandas Dataframe"
},
{
"code": null,
"e": 27567,
"s": 27540,
"text": "Python Classes and Objects"
},
{
"code": null,
"e": 27598,
"s": 27567,
"text": "Python | os.path.join() method"
},
{
"code": null,
"e": 27637,
"s": 27598,
"text": "Python | Get unique values from a list"
},
{
"code": null,
"e": 27666,
"s": 27637,
"text": "Create a directory in Python"
},
{
"code": null,
"e": 27688,
"s": 27666,
"text": "Defaultdict in Python"
}
] |
ByteBuffer allocateDirect() method in Java with Examples - GeeksforGeeks | 19 Sep, 2018
The allocateDirect() method of java.nio.ByteBuffer class is used Allocates a new direct byte buffer.
The new buffer’s position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero. Whether or not it has a backing array is unspecified.
This method is 25%-75% faster than allocate() method.
Syntax:
public static ByteBuffer allocateDirect(int capacity)
Parameters: This method takes capacity, in bytes, as parameter.
Return Value: This method returns the new byte buffer.
Exception: This method throws IllegalArgumentException, If the capacity is a negative integer.
Below are the examples to illustrate the allocateDirect() method:
Examples 1:
// Java program to demonstrate// allocateDirect() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocateDirect(capacity); // creating byte array of size capacity byte[] value = { 20, 30, 40, 50 }; // wrap the byte array into ByteBuffer bb = ByteBuffer.wrap(value); // print the ByteBuffer System.out.println("Direct ByteBuffer: " + Arrays.toString(bb.array())); // print the state of the buffer System.out.print("\nState of the ByteBuffer : "); System.out.println(bb.toString()); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception thrown : " + e); } }}
Direct ByteBuffer: [20, 30, 40, 50]
State of the ByteBuffer : java.nio.HeapByteBuffer[pos=0 lim=4 cap=4]
Examples 2: To show IllegalArgumentException
// Java program to demonstrate// allocateDirect() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity // with negative value int capacity = -4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity System.out.println("Trying to allocate" + " negative value in ByteBuffer"); ByteBuffer bb = ByteBuffer.allocateDirect(capacity); // creating byte array of size capacity byte[] value = { 20, 30, 40, 50 }; // wrap the byte array into ByteBuffer bb = ByteBuffer.wrap(value); // print the ByteBuffer System.out.println("Direct ByteBuffer: " + Arrays.toString(bb.array())); // print the state of the buffer System.out.print("\nState of the ByteBuffer : "); System.out.println(bb.toString()); } catch (IllegalArgumentException e) { System.out.println("Exception thrown : " + e); } catch (ReadOnlyBufferException e) { System.out.println("Exception thrown : " + e); } }}
Trying to allocate negative value in ByteBuffer
Exception thrown : java.lang.IllegalArgumentException: Negative capacity: -4
Java-ByteBuffer
Java-Functions
Java-NIO package
Java
Java
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Object Oriented Programming (OOPs) Concept in Java
HashMap in Java with Examples
Stream In Java
Interfaces in Java
How to iterate any Map in Java
ArrayList in Java
Initialize an ArrayList in Java
Stack Class in Java
Multidimensional Arrays in Java
Singleton Class in Java | [
{
"code": null,
"e": 25857,
"s": 25829,
"text": "\n19 Sep, 2018"
},
{
"code": null,
"e": 25958,
"s": 25857,
"text": "The allocateDirect() method of java.nio.ByteBuffer class is used Allocates a new direct byte buffer."
},
{
"code": null,
"e": 26166,
"s": 25958,
"text": "The new buffer’s position will be zero, its limit will be its capacity, its mark will be undefined, and each of its elements will be initialized to zero. Whether or not it has a backing array is unspecified."
},
{
"code": null,
"e": 26220,
"s": 26166,
"text": "This method is 25%-75% faster than allocate() method."
},
{
"code": null,
"e": 26228,
"s": 26220,
"text": "Syntax:"
},
{
"code": null,
"e": 26282,
"s": 26228,
"text": "public static ByteBuffer allocateDirect(int capacity)"
},
{
"code": null,
"e": 26346,
"s": 26282,
"text": "Parameters: This method takes capacity, in bytes, as parameter."
},
{
"code": null,
"e": 26401,
"s": 26346,
"text": "Return Value: This method returns the new byte buffer."
},
{
"code": null,
"e": 26496,
"s": 26401,
"text": "Exception: This method throws IllegalArgumentException, If the capacity is a negative integer."
},
{
"code": null,
"e": 26562,
"s": 26496,
"text": "Below are the examples to illustrate the allocateDirect() method:"
},
{
"code": null,
"e": 26574,
"s": 26562,
"text": "Examples 1:"
},
{
"code": "// Java program to demonstrate// allocateDirect() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity of the ByteBuffer int capacity = 4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity ByteBuffer bb = ByteBuffer.allocateDirect(capacity); // creating byte array of size capacity byte[] value = { 20, 30, 40, 50 }; // wrap the byte array into ByteBuffer bb = ByteBuffer.wrap(value); // print the ByteBuffer System.out.println(\"Direct ByteBuffer: \" + Arrays.toString(bb.array())); // print the state of the buffer System.out.print(\"\\nState of the ByteBuffer : \"); System.out.println(bb.toString()); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 27753,
"s": 26574,
"text": null
},
{
"code": null,
"e": 27861,
"s": 27753,
"text": "Direct ByteBuffer: [20, 30, 40, 50]\n\nState of the ByteBuffer : java.nio.HeapByteBuffer[pos=0 lim=4 cap=4]\n"
},
{
"code": null,
"e": 27906,
"s": 27861,
"text": "Examples 2: To show IllegalArgumentException"
},
{
"code": "// Java program to demonstrate// allocateDirect() method import java.nio.*;import java.util.*; public class GFG { public static void main(String[] args) { // Declaring the capacity // with negative value int capacity = -4; // Creating the ByteBuffer try { // creating object of ByteBuffer // and allocating size capacity System.out.println(\"Trying to allocate\" + \" negative value in ByteBuffer\"); ByteBuffer bb = ByteBuffer.allocateDirect(capacity); // creating byte array of size capacity byte[] value = { 20, 30, 40, 50 }; // wrap the byte array into ByteBuffer bb = ByteBuffer.wrap(value); // print the ByteBuffer System.out.println(\"Direct ByteBuffer: \" + Arrays.toString(bb.array())); // print the state of the buffer System.out.print(\"\\nState of the ByteBuffer : \"); System.out.println(bb.toString()); } catch (IllegalArgumentException e) { System.out.println(\"Exception thrown : \" + e); } catch (ReadOnlyBufferException e) { System.out.println(\"Exception thrown : \" + e); } }}",
"e": 29217,
"s": 27906,
"text": null
},
{
"code": null,
"e": 29343,
"s": 29217,
"text": "Trying to allocate negative value in ByteBuffer\nException thrown : java.lang.IllegalArgumentException: Negative capacity: -4\n"
},
{
"code": null,
"e": 29359,
"s": 29343,
"text": "Java-ByteBuffer"
},
{
"code": null,
"e": 29374,
"s": 29359,
"text": "Java-Functions"
},
{
"code": null,
"e": 29391,
"s": 29374,
"text": "Java-NIO package"
},
{
"code": null,
"e": 29396,
"s": 29391,
"text": "Java"
},
{
"code": null,
"e": 29401,
"s": 29396,
"text": "Java"
},
{
"code": null,
"e": 29499,
"s": 29401,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 29550,
"s": 29499,
"text": "Object Oriented Programming (OOPs) Concept in Java"
},
{
"code": null,
"e": 29580,
"s": 29550,
"text": "HashMap in Java with Examples"
},
{
"code": null,
"e": 29595,
"s": 29580,
"text": "Stream In Java"
},
{
"code": null,
"e": 29614,
"s": 29595,
"text": "Interfaces in Java"
},
{
"code": null,
"e": 29645,
"s": 29614,
"text": "How to iterate any Map in Java"
},
{
"code": null,
"e": 29663,
"s": 29645,
"text": "ArrayList in Java"
},
{
"code": null,
"e": 29695,
"s": 29663,
"text": "Initialize an ArrayList in Java"
},
{
"code": null,
"e": 29715,
"s": 29695,
"text": "Stack Class in Java"
},
{
"code": null,
"e": 29747,
"s": 29715,
"text": "Multidimensional Arrays in Java"
}
] |
Python - Multiply Consecutive elements in list - GeeksforGeeks | 29 Dec, 2019
While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive product in the list.
Method #1 : Using list comprehensionNaive method can be used to perform, but as this article discusses the one liner solutions to this particular problem, we start with the list comprehension as a method to perform this task.
# Python3 code to demonstrate # Consecutive Product list# using list comprehension # initializing list test_list = [1, 4, 5, 3, 6] # printing original list print ("The original list is : " + str(test_list)) # using list comprehension# Consecutive Product listres = [test_list[i] * test_list[i + 1] for i in range(len(test_list)-1)] # printing resultprint ("The computed successive product list is : " + str(res))
The original list is : [1, 4, 5, 3, 6]
The computed successive product list is : [4, 20, 15, 18]
Method #2 : Using zip()zip() can also be used to perform the similar task and uses the power of negative indices to zip() the index element with its next element and hence compute the product.
# Python3 code to demonstrate # Consecutive Product list# using zip() # initializing list test_list = [1, 4, 5, 3, 6] # printing original list print ("The original list is : " + str(test_list)) # using zip()# Consecutive Product listres = [i * j for i, j in zip(test_list[: -1], test_list[1 :])] # printing resultprint ("The computed successive product list is : " + str(res))
The original list is : [1, 4, 5, 3, 6]
The computed successive product list is : [4, 20, 15, 18]
Python list-programs
Python
Python Programs
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Python Dictionary
How to Install PIP on Windows ?
Enumerate() in Python
Different ways to create Pandas Dataframe
Iterate over a list in Python
Python 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": 25739,
"s": 25711,
"text": "\n29 Dec, 2019"
},
{
"code": null,
"e": 26049,
"s": 25739,
"text": "While working with python, we usually come by many problems that we need to solve in day-day and in development. Specially in development, small tasks of python are desired to be performed in just one line. We discuss some ways to compute a list consisting of elements that are successive product in the list."
},
{
"code": null,
"e": 26275,
"s": 26049,
"text": "Method #1 : Using list comprehensionNaive method can be used to perform, but as this article discusses the one liner solutions to this particular problem, we start with the list comprehension as a method to perform this task."
},
{
"code": "# Python3 code to demonstrate # Consecutive Product list# using list comprehension # initializing list test_list = [1, 4, 5, 3, 6] # printing original list print (\"The original list is : \" + str(test_list)) # using list comprehension# Consecutive Product listres = [test_list[i] * test_list[i + 1] for i in range(len(test_list)-1)] # printing resultprint (\"The computed successive product list is : \" + str(res))",
"e": 26694,
"s": 26275,
"text": null
},
{
"code": null,
"e": 26792,
"s": 26694,
"text": "The original list is : [1, 4, 5, 3, 6]\nThe computed successive product list is : [4, 20, 15, 18]\n"
},
{
"code": null,
"e": 26987,
"s": 26794,
"text": "Method #2 : Using zip()zip() can also be used to perform the similar task and uses the power of negative indices to zip() the index element with its next element and hence compute the product."
},
{
"code": "# Python3 code to demonstrate # Consecutive Product list# using zip() # initializing list test_list = [1, 4, 5, 3, 6] # printing original list print (\"The original list is : \" + str(test_list)) # using zip()# Consecutive Product listres = [i * j for i, j in zip(test_list[: -1], test_list[1 :])] # printing resultprint (\"The computed successive product list is : \" + str(res))",
"e": 27368,
"s": 26987,
"text": null
},
{
"code": null,
"e": 27466,
"s": 27368,
"text": "The original list is : [1, 4, 5, 3, 6]\nThe computed successive product list is : [4, 20, 15, 18]\n"
},
{
"code": null,
"e": 27487,
"s": 27466,
"text": "Python list-programs"
},
{
"code": null,
"e": 27494,
"s": 27487,
"text": "Python"
},
{
"code": null,
"e": 27510,
"s": 27494,
"text": "Python Programs"
},
{
"code": null,
"e": 27608,
"s": 27510,
"text": "Writing code in comment?\nPlease use ide.geeksforgeeks.org,\ngenerate link and share the link here."
},
{
"code": null,
"e": 27626,
"s": 27608,
"text": "Python Dictionary"
},
{
"code": null,
"e": 27658,
"s": 27626,
"text": "How to Install PIP on Windows ?"
},
{
"code": null,
"e": 27680,
"s": 27658,
"text": "Enumerate() in Python"
},
{
"code": null,
"e": 27722,
"s": 27680,
"text": "Different ways to create Pandas Dataframe"
},
{
"code": null,
"e": 27752,
"s": 27722,
"text": "Iterate over a list in Python"
},
{
"code": null,
"e": 27795,
"s": 27752,
"text": "Python program to convert a list to string"
},
{
"code": null,
"e": 27817,
"s": 27795,
"text": "Defaultdict in Python"
},
{
"code": null,
"e": 27856,
"s": 27817,
"text": "Python | Get dictionary keys as a list"
},
{
"code": null,
"e": 27902,
"s": 27856,
"text": "Python | Split string into list of characters"
}
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.